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):
121 def __eq__(self, other):
122 return self.id == other.id and self.start == other.start and \
123 self.len == other.len and self.flags == other.flags
126 RW = 'JAILHOUSE_PCICAPS_WRITE'
129 def parse_pcicaps(dir):
131 f = input_open(os.path.join(dir, 'config'), 'rb')
133 (status,) = struct.unpack('<H', f.read(2))
134 # capability list supported?
135 if (status & (1 << 4)) == 0:
138 # walk capability list
140 (next,) = struct.unpack('B', f.read(1))
144 (id, next) = struct.unpack('<BB', f.read(2))
145 if id == 0x01: # Power Management
146 # this cap can be handed out completely
148 flags = PCICapability.RW
149 elif id == 0x05: # MSI
150 # access will be moderated by hypervisor
152 (msgctl,) = struct.unpack('<H', f.read(2))
153 if (msgctl & (1 << 7)) != 0: # 64-bit support
155 if (msgctl & (1 << 8)) != 0: # per-vector masking support
157 flags = PCICapability.RW
158 elif id == 0x11: # MSI-X
159 # access will be moderated by hypervisor
161 flags = PCICapability.RW
163 # unknown/unhandled cap, mark its existence
165 flags = PCICapability.RD
166 caps.append(PCICapability(id, cap, len, flags))
171 def __init__(self, type, domain, bus, dev, fn, caps):
179 self.num_caps = len(caps)
182 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
185 return self.bus << 8 | self.dev << 3 | self.fn
188 def parse_pcidevice_sysfsdir(basedir, dir):
189 dpath = os.path.join(basedir, dir)
190 dclass = input_readline(os.path.join(dpath, 'class'))
191 if re.match(r'0x0604..', dclass):
192 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
194 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
196 domain = int(a[0], 16)
199 caps = PCICapability.parse_pcicaps(dpath)
200 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
205 def __init__(self, start, stop, typestr, comments=None):
208 self.typestr = typestr
212 self.comments = comments
215 return 'MemRegion: %08x-%08x : %s' % \
216 (self.start, self.stop, self.typestr)
219 # round up to full PAGE_SIZE
220 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
222 def flagstr(self, p=''):
224 self.typestr == 'System RAM' or
225 self.typestr == 'RAM buffer' or
226 self.typestr == 'ACPI DMAR RMRR'
228 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
229 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
231 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
234 class IOMemRegionTree:
235 def __init__(self, region, level, linenum):
237 self.linenum = linenum
240 self.children = set()
245 s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
247 if self.parent and self.parent.region:
248 s += '--> ' + self.parent.region.typestr + ' line %d' \
249 % (self.parent.linenum)
251 for c in self.children:
256 def parse_iomem_line(line):
257 a = line.split(':', 1)
258 level = int(a[0].count(' ') / 2) + 1
259 region = a[0].split('-', 1)
261 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
264 def parse_iomem_file():
265 root = IOMemRegionTree(None, 0, -1)
266 f = input_open('/proc/iomem')
271 (level, r) = IOMemRegionTree.parse_iomem_line(line)
272 t = IOMemRegionTree(r, level, linenum)
273 if (t.level > lastlevel):
275 if (t.level == lastlevel):
276 t.parent = lastnode.parent
277 if (t.level < lastlevel):
279 while(t.level < p.level):
283 t.parent.children.add(t)
291 # recurse down the tree
293 def parse_iomem_tree(tree):
297 for tree in tree.children:
301 # System RAM on first level will be added without digging deeper
302 if (tree.level == 1 and s == 'System RAM'):
304 linenumbers.append(tree.linenum)
307 # blacklisted on all levels
309 (s.find('PCI MMCONFIG') >= 0) or
310 (s.find('APIC') >= 0) or # covers both APIC and IOAPIC
311 (s.find('dmar') >= 0)
315 # generally blacklisted, unless we find an HPET right behind it
317 if (s == 'reserved'):
318 for subtree in tree.children:
320 if (r2.typestr.find('HPET') >= 0):
322 linenumbers.append(subtree.linenum)
325 # if the tree continues recurse further down ...
326 if (len(tree.children) > 0):
327 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
328 linenumbers.extend(ln2)
332 # add all remaining leaves
334 linenumbers.append(tree.linenum)
336 return linenumbers, regions
340 (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
342 # create a spare array so we can easiely keep the order from the file
343 regions = [None for x in range(maxsz)]
345 lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
351 # now prepare a non-sparse array for a return value
357 # newer Linux kernels will report the first page as reserved
358 # it is needed for CPU init so include it anyways
359 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
365 def parse_pcidevices():
368 basedir = '/sys/bus/pci/devices'
369 list = input_listdir(basedir, ['*/class', '*/config'])
371 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
375 # look for duplicate capability patterns
377 if d2.caps == d.caps:
378 # reused existing capability list, but record all users
379 d2.caps[0].comments.append(str(d))
380 d.caps_start = d2.caps_start
384 d.caps[0].comments.append(str(d))
385 d.caps_start = len(caps)
388 return (devices, caps)
392 line = input_readline('/proc/cmdline')
393 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
394 '([0-9a-fA-FxX]+)([KMG]?).*',
397 size = kmg_multiply(int(m.group(1), 0), m.group(2))
398 start = kmg_multiply(int(m.group(3), 0), m.group(4))
403 def alloc_mem(regions, size):
405 for r in reversed(regions):
406 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
410 raise RuntimeError('failed to allocate memory')
414 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
417 if re.match(r'cpu[0-9]+', f):
422 def parse_dmar_devscope(f):
423 (scope_type, scope_len, bus, dev, fn) = \
424 struct.unpack('<BBxxxBBB', f.read(8))
426 raise RuntimeError('Unsupported DMAR Device Scope Structure')
427 return (scope_type, scope_len, bus, dev, fn)
430 # parsing of DMAR ACPI Table
431 # see Intel VT-d Spec chapter 8
433 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb', True)
434 if get_cpu_vendor() == 'AuthenticAMD':
435 print('WARNING: AMD IOMMU support is not implemented yet')
437 signature = f.read(4)
438 if signature != b'DMAR':
439 if options.generate_collector:
441 raise RuntimeError('DMAR: incorrect input file format %s' % signature)
442 (length,) = struct.unpack('<I', f.read(4))
451 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
455 # DMA Remapping Hardware Unit Definition
457 (segment, base) = struct.unpack('<xxHQ', f.read(12))
459 raise RuntimeError('We do not support multiple PCI segments')
461 raise RuntimeError('Too many DMAR units. '
462 'Raise JAILHOUSE_MAX_DMAR_UNITS.')
464 offset += 16 - offset
465 while offset < struct_len:
466 (scope_type, scope_len, bus, dev, fn) =\
467 parse_dmar_devscope(f)
470 raise RuntimeError('We do not support more '
472 ioapic_id = (bus << 8) | (dev << 3) | fn
475 # Reserved Memory Region Reporting Structure
477 f.seek(8 - offset, os.SEEK_CUR)
479 (base, limit) = struct.unpack('<QQ', f.read(16))
483 while offset < struct_len:
484 (scope_type, scope_len, bus, dev, fn) =\
485 parse_dmar_devscope(f)
487 comments.append('PCI device: %02x:%02x.%x' %
490 comments.append('DMAR parser could not decode device path')
493 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
496 f.seek(struct_len - offset, os.SEEK_CUR)
498 return units, ioapic_id, regions
503 f = input_open('/proc/ioports')
505 if line.endswith('ACPI PM_TMR\n'):
506 pm_timer_base = int(line.split('-')[0], 16)
513 def __init__(self, base, end_bus):
515 self.end_bus = end_bus
519 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
520 signature = f.read(4)
521 if signature != b'MCFG':
522 if options.generate_collector:
523 return MMConfig(0, 0)
524 raise RuntimeError('MCFG: incorrect input file format %s' %
526 (length,) = struct.unpack('<I', f.read(4))
528 raise RuntimeError('Multiple MMCONFIG regions found! '
529 'This is not supported')
531 (base, segment, start_bus, end_bus) = \
532 struct.unpack('<QHBB', f.read(12))
533 if segment != 0 or start_bus != 0:
534 raise RuntimeError('Invalid MCFG structure found')
535 return MMConfig(base, end_bus)
539 (options.generate_collector is False) and (options.root is '/')
540 and (os.geteuid() is not 0)
542 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
545 def get_cpu_vendor():
546 with input_open('/proc/cpuinfo', 'r') as f:
550 key, value = line.split(':')
551 if key.strip() == 'vendor_id':
555 (pcidevices, pcicaps) = parse_pcidevices()
557 product = [input_readline('/sys/class/dmi/id/sys_vendor',
559 input_readline('/sys/class/dmi/id/product_name',
563 inmatemem = kmg_multiply_str(options.mem_inmates)
564 hvmem = [0, kmg_multiply_str(options.mem_hv)]
566 regions = parse_iomem()
567 ourmem = parse_cmdline()
568 total = hvmem[1] + inmatemem
570 mmconfig = MMConfig.parse()
572 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar()
575 # kernel does not have memmap region, pick one
577 ourmem = alloc_mem(regions, total)
578 elif (total > ourmem[1]):
579 raise RuntimeError('Your memmap reservation is too small you need >="' +
584 inmatereg = MemRegion(ourmem[0] + hvmem[1],
585 ourmem[0] + hvmem[1] + inmatemem - 1,
586 'JAILHOUSE Inmate Memory')
587 regions.append(inmatereg)
589 cpucount = count_cpus()
591 pm_timer_base = parse_ioports()
593 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
595 if options.generate_collector is False and jh_enabled == '1':
596 print('ERROR: Jailhouse was enabled when collecting input files! '
597 'Disable jailhouse and try again.',
601 f = open(options.file, 'w')
603 if options.generate_collector:
604 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
605 filelist_opt = ' '.join(inputs['files_opt'])
607 tmpl = Template(filename=os.path.join(options.template_dir,
608 'jailhouse-config-collect.tmpl'))
609 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
611 tmpl = Template(filename=os.path.join(options.template_dir,
612 'root-cell-config.c.tmpl'))
613 f.write(tmpl.render(regions=regions,
615 argstr=' '.join(sys.argv),
618 pcidevices=pcidevices,
622 pm_timer_base=pm_timer_base,
624 dmar_units=dmar_units))