3 # Jailhouse, a Linux-based partitioning hypervisor
5 # Copyright (c) Siemens AG, 2014
7 # This work is licensed under the terms of the GNU GPL, version 2. See
8 # the COPYING file in the top-level directory.
10 # This script should help to create a basic jailhouse configuration file.
11 # It needs to be executed on the target machine, where it will gather
12 # information about the system. For more advanced scenarios you will have
13 # to change the generated C-code.
15 from __future__ import print_function
21 from mako.template import Template
23 abspath = os.path.abspath(os.path.dirname(sys.argv[0]))
25 # pretend to be part of the jailhouse tool
26 sys.argv[0] = sys.argv[0].replace('-', ' ')
28 parser = argparse.ArgumentParser()
29 parser.add_argument('-g', '--generate-collector',
30 help='generate a script to collect input files on '
33 parser.add_argument('-r', '--root',
34 help='gather information in ROOT/, the default is "/" '
35 'which means creating a config for localhost',
39 parser.add_argument('-t', '--template-dir',
40 help='the directory where the templates are located,'
41 'the default is "' + abspath + '"',
46 memargs = [['--mem-inmates', '2M', 'inmate'],
47 ['--mem-hv', '64M', 'hypervisor']]
50 parser.add_argument(entry[0],
51 help='the amount of ' + entry[2] +
52 ' memory, default is "' + entry[1] +
53 '", format "xxx[K|M|G]"',
58 parser.add_argument('file', metavar='FILE',
59 help='name of file to write out',
62 options = parser.parse_args()
64 inputs = {'files': set(), 'files_opt': set(), 'dirs': set()}
67 def kmg_multiply(value, kmg):
68 if (kmg == 'K' or kmg == 'k'):
70 if (kmg == 'M' or kmg == 'm'):
71 return 1024**2 * value
72 if (kmg == 'G' or kmg == 'g'):
73 return 1024**3 * value
77 def kmg_multiply_str(str):
78 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
80 return kmg_multiply(int(m.group(1)), m.group(2))
81 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
85 def input_open(name, mode='r', optional=False):
86 inputs['files_opt' if optional else 'files'].add(name)
88 f = open(options.root + name, mode)
89 except Exception as e:
90 if optional or options.generate_collector:
91 return open("/dev/null", mode)
96 def input_readline(name, optional=False):
97 f = input_open(name, optional=optional)
103 def input_listdir(dir, wildcards):
105 inputs['dirs'].add(os.path.join(dir, w))
106 if options.generate_collector:
108 dirs = os.listdir(options.root + dir)
114 def __init__(self, id, start, len, flags, content, msix_address):
119 self.content = content
120 self.msix_address = msix_address
123 def __eq__(self, other):
124 return self.id == other.id and self.start == other.start and \
125 self.len == other.len and self.flags == other.flags
128 RW = 'JAILHOUSE_PCICAPS_WRITE'
131 def parse_pcicaps(dir):
133 f = input_open(os.path.join(dir, 'config'), 'rb')
135 (status,) = struct.unpack('<H', f.read(2))
136 # capability list supported?
137 if (status & (1 << 4)) == 0:
140 # walk capability list
142 (next,) = struct.unpack('B', f.read(1))
147 (id, next) = struct.unpack('<BB', f.read(2))
148 if id == 0x01: # Power Management
149 # this cap can be handed out completely
151 flags = PCICapability.RW
152 elif id == 0x05: # MSI
153 # access will be moderated by hypervisor
155 (msgctl,) = struct.unpack('<H', f.read(2))
156 if (msgctl & (1 << 7)) != 0: # 64-bit support
158 if (msgctl & (1 << 8)) != 0: # per-vector masking support
160 flags = PCICapability.RW
161 elif id == 0x11: # MSI-X
162 # access will be moderated by hypervisor
164 (table,) = struct.unpack('<xxI', f.read(6))
165 f.seek(0x10 + (table & 7) * 4)
166 (bar,) = struct.unpack('<I', f.read(4))
168 raise RuntimeError('Invalid MSI-X BAR found')
170 bar |= struct.unpack('<I', f.read(4))[0] << 32
171 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
172 flags = PCICapability.RW
174 # unknown/unhandled cap, mark its existence
176 flags = PCICapability.RD
178 content = f.read(len - 2)
179 caps.append(PCICapability(id, cap, len, flags, content,
185 def __init__(self, type, domain, bus, dev, fn, caps):
194 self.num_caps = len(caps)
195 self.num_msi_vectors = 0
197 self.num_msix_vectors = 0
198 self.msix_region_size = 0
199 self.msix_address = 0
201 if c.id in (0x05, 0x11):
202 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
203 if c.id == 0x05: # MSI
204 self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
205 self.msi_64bits = (msg_ctrl >> 7) & 1
207 vectors = (msg_ctrl & 0x7ff) + 1
208 self.num_msix_vectors = vectors
209 self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
210 self.msix_address = c.msix_address
213 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
216 return self.bus << 8 | self.dev << 3 | self.fn
219 def parse_pcidevice_sysfsdir(basedir, dir):
220 dpath = os.path.join(basedir, dir)
221 dclass = input_readline(os.path.join(dpath, 'class'))
222 if re.match(r'0x0604..', dclass):
223 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
225 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
227 domain = int(a[0], 16)
230 caps = PCICapability.parse_pcicaps(dpath)
231 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
236 def __init__(self, start, stop, typestr, comments=None):
239 self.typestr = typestr
243 self.comments = comments
246 return 'MemRegion: %08x-%08x : %s' % \
247 (self.start, self.stop, self.typestr)
250 # round up to full PAGE_SIZE
251 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
253 def flagstr(self, p=''):
255 self.typestr == 'System RAM' or
256 self.typestr == 'RAM buffer' or
257 self.typestr == 'ACPI DMAR RMRR'
259 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
260 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
262 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
265 class IOMemRegionTree:
266 def __init__(self, region, level, linenum):
268 self.linenum = linenum
271 self.children = set()
276 s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
278 if self.parent and self.parent.region:
279 s += '--> ' + self.parent.region.typestr + ' line %d' \
280 % (self.parent.linenum)
282 for c in self.children:
287 def parse_iomem_line(line):
288 a = line.split(':', 1)
289 level = int(a[0].count(' ') / 2) + 1
290 region = a[0].split('-', 1)
292 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
295 def parse_iomem_file():
296 root = IOMemRegionTree(None, 0, -1)
297 f = input_open('/proc/iomem')
302 (level, r) = IOMemRegionTree.parse_iomem_line(line)
303 t = IOMemRegionTree(r, level, linenum)
304 if (t.level > lastlevel):
306 if (t.level == lastlevel):
307 t.parent = lastnode.parent
308 if (t.level < lastlevel):
310 while(t.level < p.level):
314 t.parent.children.add(t)
322 # recurse down the tree
324 def parse_iomem_tree(tree):
328 for tree in tree.children:
332 # System RAM on first level will be added without digging deeper
333 if (tree.level == 1 and s == 'System RAM'):
335 linenumbers.append(tree.linenum)
338 # blacklisted on all levels
340 (s.find('PCI MMCONFIG') >= 0) or
341 (s.find('APIC') >= 0) or # covers both APIC and IOAPIC
342 (s.find('dmar') >= 0)
346 # generally blacklisted, unless we find an HPET right behind it
348 if (s == 'reserved'):
349 for subtree in tree.children:
351 if (r2.typestr.find('HPET') >= 0):
353 linenumbers.append(subtree.linenum)
356 # if the tree continues recurse further down ...
357 if (len(tree.children) > 0):
358 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
359 linenumbers.extend(ln2)
363 # add all remaining leaves
365 linenumbers.append(tree.linenum)
367 return linenumbers, regions
370 def parse_iomem(pcidevices):
371 (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
373 # create a spare array so we can easiely keep the order from the file
374 regions = [None for x in range(maxsz)]
376 lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
382 # now prepare a non-sparse array for a return value,
383 # also filtering out MSI-X pages
388 if d.msix_address >= r.start and d.msix_address <= r.stop:
389 if d.msix_address > r.start:
390 head_r = MemRegion(r.start, d.msix_address - 1,
391 r.typestr, r.comments)
393 if d.msix_address + d.msix_region_size < r.stop:
394 tail_r = MemRegion(d.msix_address + d.msix_region_size,
395 r.stop, r.typestr, r.comments)
402 # newer Linux kernels will report the first page as reserved
403 # it is needed for CPU init so include it anyways
404 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
410 def parse_pcidevices():
413 basedir = '/sys/bus/pci/devices'
414 list = input_listdir(basedir, ['*/class', '*/config'])
416 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
420 # look for duplicate capability patterns
422 if d2.caps == d.caps:
423 # reused existing capability list, but record all users
424 d2.caps[0].comments.append(str(d))
425 d.caps_start = d2.caps_start
429 d.caps[0].comments.append(str(d))
430 d.caps_start = len(caps)
433 return (devices, caps)
437 line = input_readline('/proc/cmdline')
438 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
439 '([0-9a-fA-FxX]+)([KMG]?).*',
442 size = kmg_multiply(int(m.group(1), 0), m.group(2))
443 start = kmg_multiply(int(m.group(3), 0), m.group(4))
448 def alloc_mem(regions, size):
449 mem = [0x3b000000, size]
452 r.typestr == 'System RAM' and
453 r.start <= mem[0] and
454 r.stop + 1 >= mem[0] + mem[1]
457 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
458 regions.insert(regions.index(r), head_r)
459 if r.stop + 1 > mem[0] + mem[1]:
460 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
462 regions.insert(regions.index(r), tail_r)
465 for r in reversed(regions):
466 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
470 raise RuntimeError('failed to allocate memory')
474 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
477 if re.match(r'cpu[0-9]+', f):
482 def parse_dmar_devscope(f):
483 (scope_type, scope_len, bus, dev, fn) = \
484 struct.unpack('<BBxxxBBB', f.read(8))
486 raise RuntimeError('Unsupported DMAR Device Scope Structure')
487 return (scope_type, scope_len, bus, dev, fn)
490 # parsing of DMAR ACPI Table
491 # see Intel VT-d Spec chapter 8
492 def parse_dmar(pcidevices):
493 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb', True)
494 if get_cpu_vendor() == 'AuthenticAMD':
495 print('WARNING: AMD IOMMU support is not implemented yet')
497 signature = f.read(4)
498 if signature != b'DMAR':
499 if options.generate_collector:
501 raise RuntimeError('DMAR: incorrect input file format %s' % signature)
502 (length,) = struct.unpack('<I', f.read(4))
511 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
515 # DMA Remapping Hardware Unit Definition
517 (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
519 raise RuntimeError('We do not support multiple PCI segments')
521 raise RuntimeError('Too many DMAR units. '
522 'Raise JAILHOUSE_MAX_DMAR_UNITS.')
527 d.iommu = len(units) - 1
528 offset += 16 - offset
529 while offset < struct_len:
530 (scope_type, scope_len, bus, dev, fn) =\
531 parse_dmar_devscope(f)
534 if d.bus == bus and d.dev == dev and d.fn == fn:
535 d.iommu = len(units) - 1
536 elif scope_type == 2:
537 raise RuntimeError('Unsupported DMAR Device Scope type')
538 elif scope_type == 3:
540 raise RuntimeError('We do not support more '
542 # encode the DMAR unit number into the device ID
543 ioapic_id = ((len(units) - 1) << 16) | \
544 (bus << 8) | (dev << 3) | fn
547 # Reserved Memory Region Reporting Structure
549 f.seek(8 - offset, os.SEEK_CUR)
551 (base, limit) = struct.unpack('<QQ', f.read(16))
555 while offset < struct_len:
556 (scope_type, scope_len, bus, dev, fn) =\
557 parse_dmar_devscope(f)
559 comments.append('PCI device: %02x:%02x.%x' %
562 comments.append('DMAR parser could not decode device path')
565 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
568 f.seek(struct_len - offset, os.SEEK_CUR)
570 return units, ioapic_id, regions
575 f = input_open('/proc/ioports')
577 if line.endswith('ACPI PM_TMR\n'):
578 pm_timer_base = int(line.split('-')[0], 16)
585 def __init__(self, base, end_bus):
587 self.end_bus = end_bus
591 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
592 signature = f.read(4)
593 if signature != b'MCFG':
594 if options.generate_collector:
595 return MMConfig(0, 0)
596 raise RuntimeError('MCFG: incorrect input file format %s' %
598 (length,) = struct.unpack('<I', f.read(4))
600 raise RuntimeError('Multiple MMCONFIG regions found! '
601 'This is not supported')
603 (base, segment, start_bus, end_bus) = \
604 struct.unpack('<QHBB', f.read(12))
605 if segment != 0 or start_bus != 0:
606 raise RuntimeError('Invalid MCFG structure found')
607 return MMConfig(base, end_bus)
610 def get_cpu_vendor():
611 with input_open('/proc/cpuinfo', 'r') as f:
615 key, value = line.split(':')
616 if key.strip() == 'vendor_id':
621 (options.generate_collector is False) and (options.root is '/')
622 and (os.geteuid() is not 0)
624 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
627 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
629 if options.generate_collector is False and jh_enabled == '1':
630 print('ERROR: Jailhouse was enabled when collecting input files! '
631 'Disable jailhouse and try again.',
635 (pcidevices, pcicaps) = parse_pcidevices()
637 product = [input_readline('/sys/class/dmi/id/sys_vendor',
639 input_readline('/sys/class/dmi/id/product_name',
643 inmatemem = kmg_multiply_str(options.mem_inmates)
644 hvmem = [0, kmg_multiply_str(options.mem_hv)]
646 regions = parse_iomem(pcidevices)
647 ourmem = parse_cmdline()
648 total = hvmem[1] + inmatemem
650 mmconfig = MMConfig.parse()
652 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar(pcidevices)
656 if get_cpu_vendor() == 'AuthenticAMD':
657 d.iommu = 0 # temporary workaround
659 raise RuntimeError('PCI device %02x:%02x.%x outside the scope of an '
660 'IOMMU' % (d.bus, d.dev, d.fn))
662 # kernel does not have memmap region, pick one
664 ourmem = alloc_mem(regions, total)
665 elif (total > ourmem[1]):
666 raise RuntimeError('Your memmap reservation is too small you need >="' +
671 inmatereg = MemRegion(ourmem[0] + hvmem[1],
672 ourmem[0] + hvmem[1] + inmatemem - 1,
673 'JAILHOUSE Inmate Memory')
674 regions.append(inmatereg)
676 cpucount = count_cpus()
678 pm_timer_base = parse_ioports()
680 f = open(options.file, 'w')
682 if options.generate_collector:
683 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
684 filelist_opt = ' '.join(inputs['files_opt'])
686 tmpl = Template(filename=os.path.join(options.template_dir,
687 'jailhouse-config-collect.tmpl'))
688 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
690 tmpl = Template(filename=os.path.join(options.template_dir,
691 'root-cell-config.c.tmpl'))
692 f.write(tmpl.render(regions=regions,
694 argstr=' '.join(sys.argv),
697 pcidevices=pcidevices,
701 pm_timer_base=pm_timer_base,
703 dmar_units=dmar_units))