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
26 template_default_dir = datadir + "/jailhouse"
28 template_default_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
30 # pretend to be part of the jailhouse tool
31 sys.argv[0] = sys.argv[0].replace('-', ' ')
33 parser = argparse.ArgumentParser()
34 parser.add_argument('-g', '--generate-collector',
35 help='generate a script to collect input files on '
38 parser.add_argument('-r', '--root',
39 help='gather information in ROOT/, the default is "/" '
40 'which means creating a config for localhost',
44 parser.add_argument('-t', '--template-dir',
45 help='the directory where the templates are located,'
46 'the default is "' + template_default_dir + '"',
47 default=template_default_dir,
51 memargs = [['--mem-inmates', '2M', 'inmate'],
52 ['--mem-hv', '64M', 'hypervisor']]
55 parser.add_argument(entry[0],
56 help='the amount of ' + entry[2] +
57 ' memory, default is "' + entry[1] +
58 '", format "xxx[K|M|G]"',
63 parser.add_argument('file', metavar='FILE',
64 help='name of file to write out',
67 options = parser.parse_args()
69 inputs = {'files': set(), 'files_opt': set(), 'dirs': set()}
72 def kmg_multiply(value, kmg):
73 if (kmg == 'K' or kmg == 'k'):
75 if (kmg == 'M' or kmg == 'm'):
76 return 1024**2 * value
77 if (kmg == 'G' or kmg == 'g'):
78 return 1024**3 * value
82 def kmg_multiply_str(str):
83 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
85 return kmg_multiply(int(m.group(1)), m.group(2))
86 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
89 def input_open(name, mode='r', optional=False):
90 inputs['files_opt' if optional else 'files'].add(name)
92 f = open(options.root + name, mode)
93 except Exception as e:
94 if optional or options.generate_collector:
95 return open("/dev/null", mode)
100 def input_readline(name, optional=False):
101 f = input_open(name, optional=optional)
107 def input_listdir(dir, wildcards):
109 inputs['dirs'].add(os.path.join(dir, w))
110 if options.generate_collector:
112 dirs = os.listdir(options.root + dir)
118 def __init__(self, id, start, len, flags, content, msix_address):
123 self.content = content
124 self.msix_address = msix_address
127 def __eq__(self, other):
128 return self.id == other.id and self.start == other.start and \
129 self.len == other.len and self.flags == other.flags
132 RW = 'JAILHOUSE_PCICAPS_WRITE'
135 def parse_pcicaps(dir):
137 f = input_open(os.path.join(dir, 'config'), 'rb')
139 (status,) = struct.unpack('<H', f.read(2))
140 # capability list supported?
141 if (status & (1 << 4)) == 0:
144 # walk capability list
146 (next,) = struct.unpack('B', f.read(1))
151 (id, next) = struct.unpack('<BB', f.read(2))
152 if id == 0x01: # Power Management
153 # this cap can be handed out completely
155 flags = PCICapability.RW
156 elif id == 0x05: # MSI
157 # access will be moderated by hypervisor
159 (msgctl,) = struct.unpack('<H', f.read(2))
160 if (msgctl & (1 << 7)) != 0: # 64-bit support
162 if (msgctl & (1 << 8)) != 0: # per-vector masking support
164 flags = PCICapability.RW
165 elif id == 0x11: # MSI-X
166 # access will be moderated by hypervisor
168 (table,) = struct.unpack('<xxI', f.read(6))
169 f.seek(0x10 + (table & 7) * 4)
170 (bar,) = struct.unpack('<I', f.read(4))
172 raise RuntimeError('Invalid MSI-X BAR found')
174 bar |= struct.unpack('<I', f.read(4))[0] << 32
175 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
176 flags = PCICapability.RW
178 # unknown/unhandled cap, mark its existence
180 flags = PCICapability.RD
182 content = f.read(len - 2)
183 caps.append(PCICapability(id, cap, len, flags, content,
189 def __init__(self, type, domain, bus, dev, fn, caps):
198 self.num_caps = len(caps)
199 self.num_msi_vectors = 0
201 self.num_msix_vectors = 0
202 self.msix_region_size = 0
203 self.msix_address = 0
205 if c.id in (0x05, 0x11):
206 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
207 if c.id == 0x05: # MSI
208 self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
209 self.msi_64bits = (msg_ctrl >> 7) & 1
211 vectors = (msg_ctrl & 0x7ff) + 1
212 self.num_msix_vectors = vectors
213 self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
214 self.msix_address = c.msix_address
217 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
220 return self.bus << 8 | self.dev << 3 | self.fn
223 def parse_pcidevice_sysfsdir(basedir, dir):
224 dpath = os.path.join(basedir, dir)
225 dclass = input_readline(os.path.join(dpath, 'class'))
226 if re.match(r'0x0604..', dclass):
227 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
229 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
231 domain = int(a[0], 16)
234 caps = PCICapability.parse_pcicaps(dpath)
235 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
240 def __init__(self, start, stop, typestr, comments=None):
243 self.typestr = typestr
247 self.comments = comments
250 return 'MemRegion: %08x-%08x : %s' % \
251 (self.start, self.stop, self.typestr)
254 # round up to full PAGE_SIZE
255 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
257 def flagstr(self, p=''):
259 self.typestr == 'System RAM' or
260 self.typestr == 'RAM buffer' or
261 self.typestr == 'ACPI DMAR RMRR'
263 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
264 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
266 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
269 class IOMemRegionTree:
270 def __init__(self, region, level, linenum):
272 self.linenum = linenum
275 self.children = set()
280 s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
282 if self.parent and self.parent.region:
283 s += '--> ' + self.parent.region.typestr + ' line %d' \
284 % (self.parent.linenum)
286 for c in self.children:
291 def parse_iomem_line(line):
292 a = line.split(':', 1)
293 level = int(a[0].count(' ') / 2) + 1
294 region = a[0].split('-', 1)
296 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
299 def parse_iomem_file():
300 root = IOMemRegionTree(None, 0, -1)
301 f = input_open('/proc/iomem')
306 (level, r) = IOMemRegionTree.parse_iomem_line(line)
307 t = IOMemRegionTree(r, level, linenum)
308 if (t.level > lastlevel):
310 if (t.level == lastlevel):
311 t.parent = lastnode.parent
312 if (t.level < lastlevel):
314 while(t.level < p.level):
318 t.parent.children.add(t)
326 # recurse down the tree
328 def parse_iomem_tree(tree):
332 for tree in tree.children:
336 # System RAM on first level will be added without digging deeper
337 if (tree.level == 1 and s == 'System RAM'):
339 linenumbers.append(tree.linenum)
342 # blacklisted on all levels
344 (s.find('PCI MMCONFIG') >= 0) or
345 (s.find('APIC') >= 0) or # covers both APIC and IOAPIC
346 (s.find('dmar') >= 0)
350 # generally blacklisted, unless we find an HPET right behind it
352 if (s == 'reserved'):
353 for subtree in tree.children:
355 if (r2.typestr.find('HPET') >= 0):
357 linenumbers.append(subtree.linenum)
360 # if the tree continues recurse further down ...
361 if (len(tree.children) > 0):
362 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
363 linenumbers.extend(ln2)
367 # add all remaining leaves
369 linenumbers.append(tree.linenum)
371 return linenumbers, regions
374 def parse_iomem(pcidevices):
375 (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
377 # create a spare array so we can easiely keep the order from the file
378 regions = [None for x in range(maxsz)]
380 lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
386 # now prepare a non-sparse array for a return value,
387 # also filtering out MSI-X pages
392 if d.msix_address >= r.start and d.msix_address <= r.stop:
393 if d.msix_address > r.start:
394 head_r = MemRegion(r.start, d.msix_address - 1,
395 r.typestr, r.comments)
397 if d.msix_address + d.msix_region_size < r.stop:
398 tail_r = MemRegion(d.msix_address + d.msix_region_size,
399 r.stop, r.typestr, r.comments)
406 # newer Linux kernels will report the first page as reserved
407 # it is needed for CPU init so include it anyways
408 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
414 def parse_pcidevices():
417 basedir = '/sys/bus/pci/devices'
418 list = input_listdir(basedir, ['*/class', '*/config'])
420 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
424 # look for duplicate capability patterns
426 if d2.caps == d.caps:
427 # reused existing capability list, but record all users
428 d2.caps[0].comments.append(str(d))
429 d.caps_start = d2.caps_start
433 d.caps[0].comments.append(str(d))
434 d.caps_start = len(caps)
437 return (devices, caps)
441 line = input_readline('/proc/cmdline')
442 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
443 '([0-9a-fA-FxX]+)([KMG]?).*',
446 size = kmg_multiply(int(m.group(1), 0), m.group(2))
447 start = kmg_multiply(int(m.group(3), 0), m.group(4))
452 def alloc_mem(regions, size):
453 mem = [0x3b000000, size]
456 r.typestr == 'System RAM' and
457 r.start <= mem[0] and
458 r.stop + 1 >= mem[0] + mem[1]
461 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
462 regions.insert(regions.index(r), head_r)
463 if r.stop + 1 > mem[0] + mem[1]:
464 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
466 regions.insert(regions.index(r), tail_r)
469 for r in reversed(regions):
470 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
474 raise RuntimeError('failed to allocate memory')
478 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
481 if re.match(r'cpu[0-9]+', f):
486 def parse_dmar_devscope(f):
487 (scope_type, scope_len, bus, dev, fn) = \
488 struct.unpack('<BBxxxBBB', f.read(8))
490 raise RuntimeError('Unsupported DMAR Device Scope Structure')
491 return (scope_type, scope_len, bus, dev, fn)
494 # parsing of DMAR ACPI Table
495 # see Intel VT-d Spec chapter 8
496 def parse_dmar(pcidevices):
497 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb', True)
498 if get_cpu_vendor() == 'AuthenticAMD':
499 print('WARNING: AMD IOMMU support is not implemented yet')
501 signature = f.read(4)
502 if signature != b'DMAR':
503 if options.generate_collector:
505 raise RuntimeError('DMAR: incorrect input file format %s' % signature)
506 (length,) = struct.unpack('<I', f.read(4))
515 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
519 # DMA Remapping Hardware Unit Definition
521 (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
523 raise RuntimeError('We do not support multiple PCI segments')
525 raise RuntimeError('Too many DMAR units. '
526 'Raise JAILHOUSE_MAX_DMAR_UNITS.')
531 d.iommu = len(units) - 1
532 offset += 16 - offset
533 while offset < struct_len:
534 (scope_type, scope_len, bus, dev, fn) =\
535 parse_dmar_devscope(f)
538 if d.bus == bus and d.dev == dev and d.fn == fn:
539 d.iommu = len(units) - 1
540 elif scope_type == 2:
541 raise RuntimeError('Unsupported DMAR Device Scope type')
542 elif scope_type == 3:
544 raise RuntimeError('We do not support more '
546 # encode the DMAR unit number into the device ID
547 ioapic_id = ((len(units) - 1) << 16) | \
548 (bus << 8) | (dev << 3) | fn
551 # Reserved Memory Region Reporting Structure
553 f.seek(8 - offset, os.SEEK_CUR)
555 (base, limit) = struct.unpack('<QQ', f.read(16))
559 while offset < struct_len:
560 (scope_type, scope_len, bus, dev, fn) =\
561 parse_dmar_devscope(f)
563 comments.append('PCI device: %02x:%02x.%x' %
566 comments.append('DMAR parser could not decode device path')
569 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
572 f.seek(struct_len - offset, os.SEEK_CUR)
574 return units, ioapic_id, regions
579 f = input_open('/proc/ioports')
581 if line.endswith('ACPI PM_TMR\n'):
582 pm_timer_base = int(line.split('-')[0], 16)
589 def __init__(self, base, end_bus):
591 self.end_bus = end_bus
595 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
596 signature = f.read(4)
597 if signature != b'MCFG':
598 if options.generate_collector:
599 return MMConfig(0, 0)
600 raise RuntimeError('MCFG: incorrect input file format %s' %
602 (length,) = struct.unpack('<I', f.read(4))
604 raise RuntimeError('Multiple MMCONFIG regions found! '
605 'This is not supported')
607 (base, segment, start_bus, end_bus) = \
608 struct.unpack('<QHBB', f.read(12))
609 if segment != 0 or start_bus != 0:
610 raise RuntimeError('Invalid MCFG structure found')
611 return MMConfig(base, end_bus)
614 def get_cpu_vendor():
615 with input_open('/proc/cpuinfo', 'r') as f:
619 key, value = line.split(':')
620 if key.strip() == 'vendor_id':
625 (options.generate_collector is False) and (options.root is '/')
626 and (os.geteuid() is not 0)
628 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
631 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
633 if options.generate_collector is False and jh_enabled == '1':
634 print('ERROR: Jailhouse was enabled when collecting input files! '
635 'Disable jailhouse and try again.',
639 (pcidevices, pcicaps) = parse_pcidevices()
641 product = [input_readline('/sys/class/dmi/id/sys_vendor',
643 input_readline('/sys/class/dmi/id/product_name',
647 inmatemem = kmg_multiply_str(options.mem_inmates)
648 hvmem = [0, kmg_multiply_str(options.mem_hv)]
650 regions = parse_iomem(pcidevices)
651 ourmem = parse_cmdline()
652 total = hvmem[1] + inmatemem
654 mmconfig = MMConfig.parse()
656 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar(pcidevices)
660 if get_cpu_vendor() == 'AuthenticAMD':
661 d.iommu = 0 # temporary workaround
663 raise RuntimeError('PCI device %02x:%02x.%x outside the scope of an '
664 'IOMMU' % (d.bus, d.dev, d.fn))
666 # kernel does not have memmap region, pick one
668 ourmem = alloc_mem(regions, total)
669 elif (total > ourmem[1]):
670 raise RuntimeError('Your memmap reservation is too small you need >="' +
675 inmatereg = MemRegion(ourmem[0] + hvmem[1],
676 ourmem[0] + hvmem[1] + inmatemem - 1,
677 'JAILHOUSE Inmate Memory')
678 regions.append(inmatereg)
680 cpucount = count_cpus()
682 pm_timer_base = parse_ioports()
684 f = open(options.file, 'w')
686 if options.generate_collector:
687 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
688 filelist_opt = ' '.join(inputs['files_opt'])
690 tmpl = Template(filename=os.path.join(options.template_dir,
691 'jailhouse-config-collect.tmpl'))
692 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
694 tmpl = Template(filename=os.path.join(options.template_dir,
695 'root-cell-config.c.tmpl'))
696 f.write(tmpl.render(regions=regions,
698 argstr=' '.join(sys.argv),
701 pcidevices=pcidevices,
705 pm_timer_base=pm_timer_base,
707 dmar_units=dmar_units))