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):
119 self.content = content
122 def __eq__(self, other):
123 return self.id == other.id and self.start == other.start and \
124 self.len == other.len and self.flags == other.flags
127 RW = 'JAILHOUSE_PCICAPS_WRITE'
130 def parse_pcicaps(dir):
132 f = input_open(os.path.join(dir, 'config'), 'rb')
134 (status,) = struct.unpack('<H', f.read(2))
135 # capability list supported?
136 if (status & (1 << 4)) == 0:
139 # walk capability list
141 (next,) = struct.unpack('B', f.read(1))
145 (id, next) = struct.unpack('<BB', f.read(2))
146 if id == 0x01: # Power Management
147 # this cap can be handed out completely
149 flags = PCICapability.RW
150 elif id == 0x05: # MSI
151 # access will be moderated by hypervisor
153 (msgctl,) = struct.unpack('<H', f.read(2))
154 if (msgctl & (1 << 7)) != 0: # 64-bit support
156 if (msgctl & (1 << 8)) != 0: # per-vector masking support
158 flags = PCICapability.RW
159 elif id == 0x11: # MSI-X
160 # access will be moderated by hypervisor
162 flags = PCICapability.RW
164 # unknown/unhandled cap, mark its existence
166 flags = PCICapability.RD
168 content = f.read(len - 2)
169 caps.append(PCICapability(id, cap, len, flags, content))
174 def __init__(self, type, domain, bus, dev, fn, caps):
182 self.num_caps = len(caps)
183 self.num_msi_vectors = 0
186 if c.id in (0x05, 0x11):
187 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
188 if c.id == 0x05: # MSI
189 self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
190 self.msi_64bits = (msg_ctrl >> 7) & 1
193 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
196 return self.bus << 8 | self.dev << 3 | self.fn
199 def parse_pcidevice_sysfsdir(basedir, dir):
200 dpath = os.path.join(basedir, dir)
201 dclass = input_readline(os.path.join(dpath, 'class'))
202 if re.match(r'0x0604..', dclass):
203 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
205 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
207 domain = int(a[0], 16)
210 caps = PCICapability.parse_pcicaps(dpath)
211 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
216 def __init__(self, start, stop, typestr, comments=None):
219 self.typestr = typestr
223 self.comments = comments
226 return 'MemRegion: %08x-%08x : %s' % \
227 (self.start, self.stop, self.typestr)
230 # round up to full PAGE_SIZE
231 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
233 def flagstr(self, p=''):
235 self.typestr == 'System RAM' or
236 self.typestr == 'RAM buffer' or
237 self.typestr == 'ACPI DMAR RMRR'
239 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
240 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
242 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
245 class IOMemRegionTree:
246 def __init__(self, region, level, linenum):
248 self.linenum = linenum
251 self.children = set()
256 s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
258 if self.parent and self.parent.region:
259 s += '--> ' + self.parent.region.typestr + ' line %d' \
260 % (self.parent.linenum)
262 for c in self.children:
267 def parse_iomem_line(line):
268 a = line.split(':', 1)
269 level = int(a[0].count(' ') / 2) + 1
270 region = a[0].split('-', 1)
272 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
275 def parse_iomem_file():
276 root = IOMemRegionTree(None, 0, -1)
277 f = input_open('/proc/iomem')
282 (level, r) = IOMemRegionTree.parse_iomem_line(line)
283 t = IOMemRegionTree(r, level, linenum)
284 if (t.level > lastlevel):
286 if (t.level == lastlevel):
287 t.parent = lastnode.parent
288 if (t.level < lastlevel):
290 while(t.level < p.level):
294 t.parent.children.add(t)
302 # recurse down the tree
304 def parse_iomem_tree(tree):
308 for tree in tree.children:
312 # System RAM on first level will be added without digging deeper
313 if (tree.level == 1 and s == 'System RAM'):
315 linenumbers.append(tree.linenum)
318 # blacklisted on all levels
320 (s.find('PCI MMCONFIG') >= 0) or
321 (s.find('APIC') >= 0) or # covers both APIC and IOAPIC
322 (s.find('dmar') >= 0)
326 # generally blacklisted, unless we find an HPET right behind it
328 if (s == 'reserved'):
329 for subtree in tree.children:
331 if (r2.typestr.find('HPET') >= 0):
333 linenumbers.append(subtree.linenum)
336 # if the tree continues recurse further down ...
337 if (len(tree.children) > 0):
338 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
339 linenumbers.extend(ln2)
343 # add all remaining leaves
345 linenumbers.append(tree.linenum)
347 return linenumbers, regions
351 (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
353 # create a spare array so we can easiely keep the order from the file
354 regions = [None for x in range(maxsz)]
356 lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
362 # now prepare a non-sparse array for a return value
368 # newer Linux kernels will report the first page as reserved
369 # it is needed for CPU init so include it anyways
370 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
376 def parse_pcidevices():
379 basedir = '/sys/bus/pci/devices'
380 list = input_listdir(basedir, ['*/class', '*/config'])
382 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
386 # look for duplicate capability patterns
388 if d2.caps == d.caps:
389 # reused existing capability list, but record all users
390 d2.caps[0].comments.append(str(d))
391 d.caps_start = d2.caps_start
395 d.caps[0].comments.append(str(d))
396 d.caps_start = len(caps)
399 return (devices, caps)
403 line = input_readline('/proc/cmdline')
404 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
405 '([0-9a-fA-FxX]+)([KMG]?).*',
408 size = kmg_multiply(int(m.group(1), 0), m.group(2))
409 start = kmg_multiply(int(m.group(3), 0), m.group(4))
414 def alloc_mem(regions, size):
416 for r in reversed(regions):
417 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
421 raise RuntimeError('failed to allocate memory')
425 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
428 if re.match(r'cpu[0-9]+', f):
433 def parse_dmar_devscope(f):
434 (scope_type, scope_len, bus, dev, fn) = \
435 struct.unpack('<BBxxxBBB', f.read(8))
437 raise RuntimeError('Unsupported DMAR Device Scope Structure')
438 return (scope_type, scope_len, bus, dev, fn)
441 # parsing of DMAR ACPI Table
442 # see Intel VT-d Spec chapter 8
444 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb', True)
445 if get_cpu_vendor() == 'AuthenticAMD':
446 print('WARNING: AMD IOMMU support is not implemented yet')
448 signature = f.read(4)
449 if signature != b'DMAR':
450 if options.generate_collector:
452 raise RuntimeError('DMAR: incorrect input file format %s' % signature)
453 (length,) = struct.unpack('<I', f.read(4))
462 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
466 # DMA Remapping Hardware Unit Definition
468 (segment, base) = struct.unpack('<xxHQ', f.read(12))
470 raise RuntimeError('We do not support multiple PCI segments')
472 raise RuntimeError('Too many DMAR units. '
473 'Raise JAILHOUSE_MAX_DMAR_UNITS.')
475 offset += 16 - offset
476 while offset < struct_len:
477 (scope_type, scope_len, bus, dev, fn) =\
478 parse_dmar_devscope(f)
481 raise RuntimeError('We do not support more '
483 ioapic_id = (bus << 8) | (dev << 3) | fn
486 # Reserved Memory Region Reporting Structure
488 f.seek(8 - offset, os.SEEK_CUR)
490 (base, limit) = struct.unpack('<QQ', f.read(16))
494 while offset < struct_len:
495 (scope_type, scope_len, bus, dev, fn) =\
496 parse_dmar_devscope(f)
498 comments.append('PCI device: %02x:%02x.%x' %
501 comments.append('DMAR parser could not decode device path')
504 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
507 f.seek(struct_len - offset, os.SEEK_CUR)
509 return units, ioapic_id, regions
514 f = input_open('/proc/ioports')
516 if line.endswith('ACPI PM_TMR\n'):
517 pm_timer_base = int(line.split('-')[0], 16)
524 def __init__(self, base, end_bus):
526 self.end_bus = end_bus
530 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
531 signature = f.read(4)
532 if signature != b'MCFG':
533 if options.generate_collector:
534 return MMConfig(0, 0)
535 raise RuntimeError('MCFG: incorrect input file format %s' %
537 (length,) = struct.unpack('<I', f.read(4))
539 raise RuntimeError('Multiple MMCONFIG regions found! '
540 'This is not supported')
542 (base, segment, start_bus, end_bus) = \
543 struct.unpack('<QHBB', f.read(12))
544 if segment != 0 or start_bus != 0:
545 raise RuntimeError('Invalid MCFG structure found')
546 return MMConfig(base, end_bus)
550 (options.generate_collector is False) and (options.root is '/')
551 and (os.geteuid() is not 0)
553 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
556 def get_cpu_vendor():
557 with input_open('/proc/cpuinfo', 'r') as f:
561 key, value = line.split(':')
562 if key.strip() == 'vendor_id':
566 (pcidevices, pcicaps) = parse_pcidevices()
568 product = [input_readline('/sys/class/dmi/id/sys_vendor',
570 input_readline('/sys/class/dmi/id/product_name',
574 inmatemem = kmg_multiply_str(options.mem_inmates)
575 hvmem = [0, kmg_multiply_str(options.mem_hv)]
577 regions = parse_iomem()
578 ourmem = parse_cmdline()
579 total = hvmem[1] + inmatemem
581 mmconfig = MMConfig.parse()
583 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar()
586 # kernel does not have memmap region, pick one
588 ourmem = alloc_mem(regions, total)
589 elif (total > ourmem[1]):
590 raise RuntimeError('Your memmap reservation is too small you need >="' +
595 inmatereg = MemRegion(ourmem[0] + hvmem[1],
596 ourmem[0] + hvmem[1] + inmatemem - 1,
597 'JAILHOUSE Inmate Memory')
598 regions.append(inmatereg)
600 cpucount = count_cpus()
602 pm_timer_base = parse_ioports()
604 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
606 if options.generate_collector is False and jh_enabled == '1':
607 print('ERROR: Jailhouse was enabled when collecting input files! '
608 'Disable jailhouse and try again.',
612 f = open(options.file, 'w')
614 if options.generate_collector:
615 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
616 filelist_opt = ' '.join(inputs['files_opt'])
618 tmpl = Template(filename=os.path.join(options.template_dir,
619 'jailhouse-config-collect.tmpl'))
620 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
622 tmpl = Template(filename=os.path.join(options.template_dir,
623 'root-cell-config.c.tmpl'))
624 f.write(tmpl.render(regions=regions,
626 argstr=' '.join(sys.argv),
629 pcidevices=pcidevices,
633 pm_timer_base=pm_timer_base,
635 dmar_units=dmar_units))