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()}
68 def __init__(self, id, start, len, flags):
75 def __eq__(self, other):
76 return self.id == other.id and self.start == other.start and \
77 self.len == other.len and self.flags == other.flags
80 RW = 'JAILHOUSE_PCICAPS_WRITE'
83 def parse_pcicaps(dir):
85 f = input_open(os.path.join(dir, 'config'), 'rb')
87 (status,) = struct.unpack('<H', f.read(2))
88 # capability list supported?
89 if (status & (1 << 4)) == 0:
92 # walk capability list
94 (next,) = struct.unpack('B', f.read(1))
98 (id, next) = struct.unpack('<BB', f.read(2))
99 if id == 0x01: # Power Management
100 # this cap can be handed out completely
102 flags = PCICapability.RW
103 elif id == 0x05: # MSI
104 # access will be moderated by hypervisor
106 (msgctl,) = struct.unpack('<H', f.read(2))
107 if (msgctl & (1 << 7)) != 0: # 64-bit support
109 if (msgctl & (1 << 8)) != 0: # per-vector masking support
111 flags = PCICapability.RW
112 elif id == 0x11: # MSI-X
113 # access will be moderated by hypervisor
115 flags = PCICapability.RW
117 # unknown/unhandled cap, mark its existence
119 flags = PCICapability.RD
120 caps.append(PCICapability(id, cap, len, flags))
125 def __init__(self, type, domain, bus, dev, fn, caps):
133 self.num_caps = len(caps)
136 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
139 return self.bus << 8 | self.dev << 3 | self.fn
142 def parse_pcidevice_sysfsdir(basedir, dir):
143 dpath = os.path.join(basedir, dir)
144 dclass = input_readline(os.path.join(dpath, 'class'))
145 if re.match(r'0x0604..', dclass):
146 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
148 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
150 domain = int(a[0], 16)
153 caps = PCICapability.parse_pcicaps(dpath)
154 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
159 def __init__(self, start, stop, typestr, comments=None):
162 self.typestr = typestr
166 self.comments = comments
169 return 'MemRegion: %08x-%08x : %s' % \
170 (self.start, self.stop, self.typestr)
173 # round up to full PAGE_SIZE
174 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
176 def flagstr(self, p=''):
178 self.typestr == 'ACPI Tables' or
179 self.typestr == 'ACPI Non-volatile Storage'
181 return 'JAILHOUSE_MEM_READ'
183 self.typestr == 'System RAM' or
184 self.typestr == 'RAM buffer' or
185 self.typestr == 'ACPI DMAR RMRR'
187 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
188 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
190 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
193 class IOMemRegionTree:
194 def __init__(self, region, level, linenum):
196 self.linenum = linenum
199 self.children = set()
204 s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
206 if self.parent and self.parent.region:
207 s += '--> ' + self.parent.region.typestr + ' line %d' \
208 % (self.parent.linenum)
210 for c in self.children:
215 def parse_iomem_line(line):
216 a = line.split(':', 1)
217 level = int(a[0].count(' ') / 2) + 1
218 region = a[0].split('-', 1)
220 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
223 def parse_iomem_file():
224 root = IOMemRegionTree(None, 0, -1)
225 f = input_open('/proc/iomem')
230 (level, r) = IOMemRegionTree.parse_iomem_line(line)
231 t = IOMemRegionTree(r, level, linenum)
232 if (t.level > lastlevel):
234 if (t.level == lastlevel):
235 t.parent = lastnode.parent
236 if (t.level < lastlevel):
238 while(t.level < p.level):
242 t.parent.children.add(t)
250 # recurse down the tree
252 def parse_iomem_tree(tree):
256 for tree in tree.children:
260 # System RAM on first level will be added without digging deeper
261 if (tree.level == 1 and s == 'System RAM'):
263 linenumbers.append(tree.linenum)
266 # blacklisted on all levels
268 (s.find('PCI MMCONFIG') >= 0) or
269 (s.find('APIC') >= 0)
273 # generally blacklisted, unless we find an HPET right behind it
275 if (s == 'reserved'):
276 for subtree in tree.children:
278 if (r2.typestr.find('HPET') >= 0):
280 linenumbers.append(subtree.linenum)
283 # if the tree continues recurse further down ...
284 if (len(tree.children) > 0):
285 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
286 linenumbers.extend(ln2)
290 # add all remaining leaves
292 linenumbers.append(tree.linenum)
294 return linenumbers, regions
298 (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
300 # create a spare array so we can easiely keep the order from the file
301 regions = [None for x in range(maxsz)]
303 lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
309 # now prepare a non-sparse array for a return value
315 # newer Linux kernels will report the first page as reserved
316 # it is needed for CPU init so include it anyways
317 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
323 def parse_pcidevices():
326 basedir = '/sys/bus/pci/devices'
327 list = input_listdir(basedir, ['*/class', '*/config'])
329 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
333 # look for duplicate capability patterns
335 if d2.caps == d.caps:
336 # reused existing capability list, but record all users
337 d2.caps[0].comments.append(str(d))
338 d.caps_start = d2.caps_start
342 d.caps[0].comments.append(str(d))
343 d.caps_start = len(caps)
346 return (devices, caps)
349 def kmg_multiply(value, kmg):
350 if (kmg == 'K' or kmg == 'k'):
352 if (kmg == 'M' or kmg == 'm'):
353 return 1024**2 * value
354 if (kmg == 'G' or kmg == 'g'):
355 return 1024**3 * value
359 def kmg_multiply_str(str):
360 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
362 return kmg_multiply(int(m.group(1)), m.group(2))
363 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
367 def input_open(name, mode='r', optional=False):
368 inputs['files_opt' if optional else 'files'].add(name)
370 f = open(options.root + name, mode)
371 except Exception as e:
372 if optional or options.generate_collector:
373 return open("/dev/null", mode)
378 def input_readline(name, optional=False):
379 f = input_open(name, optional=optional)
385 def input_listdir(dir, wildcards):
387 inputs['dirs'].add(os.path.join(dir, w))
388 if options.generate_collector:
390 dirs = os.listdir(options.root + dir)
396 line = input_readline('/proc/cmdline')
397 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
398 '([0-9a-fA-FxX]+)([KMG]?).*',
401 size = kmg_multiply(int(m.group(1), 0), m.group(2))
402 start = kmg_multiply(int(m.group(3), 0), m.group(4))
407 def alloc_mem(regions, size):
409 for r in reversed(regions):
410 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
414 raise RuntimeError('failed to allocate memory')
418 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
421 if re.match(r'cpu[0-9]+', f):
426 def parse_dmar_devscope(f):
428 (scope_type, scope_len, bus, dev, fn) = \
429 struct.unpack('<BBxxxBBB', f.read(8))
431 return (offset, scope_type, scope_len, bus, dev, fn)
434 # parsing of DMAR ACPI Table
435 # see Intel VT-d Spec chapter 8
437 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
438 signature = f.read(4)
439 if signature != b'DMAR':
440 if options.generate_collector:
442 raise RuntimeError('incorrect input file format %s' % signature)
443 (length,) = struct.unpack('<I', f.read(4))
452 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
456 # DMA Remapping Hardware Unit Definition
458 (segment, base) = struct.unpack('<xxHQ', f.read(12))
460 raise RuntimeError('We do not support multiple PCI segments')
462 raise RuntimeError('Too many DMAR units. '
463 'Raise JAILHOUSE_MAX_DMAR_UNITS.')
465 offset += 16 - offset
466 while offset < struct_len:
467 (off, scope_type, scope_len, bus, dev, fn) =\
468 parse_dmar_devscope(f)
472 raise RuntimeError('We do not support more '
474 ioapic_id = (bus << 8) | (dev << 3) | fn
475 f.seek(scope_len - 8, os.SEEK_CUR)
476 offset += scope_len - 8
478 # Reserved Memory Region Reporting Structure
480 f.seek(8 - offset, os.SEEK_CUR)
482 (base, limit) = struct.unpack('<QQ', f.read(16))
486 while offset < struct_len:
487 (off, scope_type, scope_len, bus, dev, fn) =\
488 parse_dmar_devscope(f)
490 npath = (scope_len - 6)/2
491 if scope_type == 1 and npath == 1:
492 comments.append('PCI device: %02x:%02x.%x' %
495 comments.append('DMAR parser could not decode device path')
496 f.seek(scope_len - off, os.SEEK_CUR)
497 offset += scope_len - off
499 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
502 f.seek(struct_len - offset, os.SEEK_CUR)
504 return units, ioapic_id, regions
509 f = input_open('/proc/ioports')
511 if line.endswith('ACPI PM_TMR\n'):
512 pm_timer_base = int(line.split('-')[0], 16)
519 def __init__(self, base, end_bus):
521 self.end_bus = end_bus
525 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
526 signature = f.read(4)
527 if signature != b'MCFG':
528 if options.generate_collector:
529 return MMConfig(0, 0)
530 raise RuntimeError('incorrect input file format %s' % signature)
531 (length,) = struct.unpack('<I', f.read(4))
533 raise RuntimeError('Multiple MMCONFIG regions found! '
534 'This is not supported')
536 (base, segment, start_bus, end_bus) = \
537 struct.unpack('<QHBB', f.read(12))
538 if segment != 0 or start_bus != 0:
539 raise RuntimeError('Invalid MCFG structure found')
540 return MMConfig(base, end_bus)
544 (options.generate_collector is False) and (options.root is '/')
545 and (os.geteuid() is not 0)
547 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
550 (pcidevices, pcicaps) = parse_pcidevices()
552 product = [input_readline('/sys/class/dmi/id/sys_vendor',
554 input_readline('/sys/class/dmi/id/product_name',
558 inmatemem = kmg_multiply_str(options.mem_inmates)
559 hvmem = [0, kmg_multiply_str(options.mem_hv)]
561 regions = parse_iomem()
562 ourmem = parse_cmdline()
563 total = hvmem[1] + inmatemem
565 mmconfig = MMConfig.parse()
567 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar()
570 # kernel does not have memmap region, pick one
572 ourmem = alloc_mem(regions, total)
573 elif (total > ourmem[1]):
574 raise RuntimeError('Your memmap reservation is too small you need >="' +
579 inmatereg = MemRegion(ourmem[0] + hvmem[1],
580 ourmem[0] + hvmem[1] + inmatemem - 1,
581 'JAILHOUSE Inmate Memory')
582 regions.append(inmatereg)
584 cpucount = count_cpus()
586 pm_timer_base = parse_ioports()
588 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
590 if options.generate_collector is False and jh_enabled == '1':
591 print('ERROR: Jailhouse was enabled when collecting input files! '
592 'Disable jailhouse and try again.',
596 f = open(options.file, 'w')
598 if options.generate_collector:
599 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
600 filelist_opt = ' '.join(inputs['files_opt'])
602 tmpl = Template(filename=os.path.join(options.template_dir,
603 'jailhouse-config-collect.tmpl'))
604 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
606 tmpl = Template(filename=os.path.join(options.template_dir,
607 'root-cell-config.c.tmpl'))
608 f.write(tmpl.render(regions=regions,
610 argstr=' '.join(sys.argv),
613 pcidevices=pcidevices,
617 pm_timer_base=pm_timer_base,
619 dmar_units=dmar_units))