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
22 from mako.template import Template
27 template_default_dir = datadir + "/jailhouse"
29 template_default_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
33 # pretend to be part of the jailhouse tool
34 sys.argv[0] = sys.argv[0].replace('-', ' ')
36 parser = argparse.ArgumentParser()
37 parser.add_argument('-g', '--generate-collector',
38 help='generate a script to collect input files on '
41 parser.add_argument('-r', '--root',
42 help='gather information in ROOT/, the default is "/" '
43 'which means creating a config for localhost',
47 parser.add_argument('-t', '--template-dir',
48 help='the directory where the templates are located,'
49 'the default is "' + template_default_dir + '"',
50 default=template_default_dir,
54 memargs = [['--mem-inmates', '2M', 'inmate'],
55 ['--mem-hv', '64M', 'hypervisor']]
58 parser.add_argument(entry[0],
59 help='the amount of ' + entry[2] +
60 ' memory, default is "' + entry[1] +
61 '", format "xxx[K|M|G]"',
66 parser.add_argument('file', metavar='FILE',
67 help='name of file to write out',
70 options = parser.parse_args()
72 inputs = {'files': set(), 'files_opt': set(), 'files_intel': set()}
75 inputs['files'].add('/proc/iomem')
76 inputs['files'].add('/proc/cpuinfo')
77 inputs['files'].add('/proc/cmdline')
78 inputs['files'].add('/proc/ioports')
79 inputs['files'].add('/sys/bus/pci/devices/*/config')
80 inputs['files'].add('/sys/bus/pci/devices/*/class')
81 inputs['files'].add('/sys/devices/system/cpu/cpu*/uevent')
82 inputs['files'].add('/sys/firmware/acpi/tables/APIC')
83 inputs['files'].add('/sys/firmware/acpi/tables/MCFG')
85 inputs['files_opt'].add('/sys/class/dmi/id/product_name')
86 inputs['files_opt'].add('/sys/class/dmi/id/sys_vendor')
87 inputs['files_opt'].add('/sys/devices/jailhouse/enabled')
88 ## platform specific files
89 inputs['files_intel'].add('/sys/firmware/acpi/tables/DMAR')
92 def kmg_multiply(value, kmg):
93 if (kmg == 'K' or kmg == 'k'):
95 if (kmg == 'M' or kmg == 'm'):
96 return 1024**2 * value
97 if (kmg == 'G' or kmg == 'g'):
98 return 1024**3 * value
102 def kmg_multiply_str(str):
103 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
105 return kmg_multiply(int(m.group(1)), m.group(2))
106 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
109 def check_input_listed(name, optional=False):
110 set = inputs['files_opt']
111 if optional is False:
112 set = inputs['files']
114 if cpuvendor == 'GenuineIntel':
115 set = set.union(inputs['files_intel'])
118 if fnmatch.fnmatch(name, file):
120 raise RuntimeError('"' + name + '" is not a listed input file')
123 def input_open(name, mode='r', optional=False):
124 check_input_listed(name, optional)
126 f = open(options.root + name, mode)
127 except Exception as e:
129 return open("/dev/null", mode)
134 def input_readline(name, optional=False):
135 f = input_open(name, optional=optional)
141 def input_listdir(dir, wildcards):
143 check_input_listed(os.path.join(dir, w))
144 dirs = os.listdir(options.root + dir)
150 def __init__(self, id, start, len, flags, content, msix_address):
155 self.content = content
156 self.msix_address = msix_address
159 def __eq__(self, other):
160 return self.id == other.id and self.start == other.start and \
161 self.len == other.len and self.flags == other.flags
164 RW = 'JAILHOUSE_PCICAPS_WRITE'
167 def parse_pcicaps(dir):
169 f = input_open(os.path.join(dir, 'config'), 'rb')
171 (status,) = struct.unpack('<H', f.read(2))
172 # capability list supported?
173 if (status & (1 << 4)) == 0:
176 # walk capability list
178 (next,) = struct.unpack('B', f.read(1))
183 (id, next) = struct.unpack('<BB', f.read(2))
184 if id == 0x01: # Power Management
185 # this cap can be handed out completely
187 flags = PCICapability.RW
188 elif id == 0x05: # MSI
189 # access will be moderated by hypervisor
191 (msgctl,) = struct.unpack('<H', f.read(2))
192 if (msgctl & (1 << 7)) != 0: # 64-bit support
194 if (msgctl & (1 << 8)) != 0: # per-vector masking support
196 flags = PCICapability.RW
197 elif id == 0x11: # MSI-X
198 # access will be moderated by hypervisor
200 (table,) = struct.unpack('<xxI', f.read(6))
201 f.seek(0x10 + (table & 7) * 4)
202 (bar,) = struct.unpack('<I', f.read(4))
204 raise RuntimeError('Invalid MSI-X BAR found')
206 bar |= struct.unpack('<I', f.read(4))[0] << 32
207 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
208 flags = PCICapability.RW
210 # unknown/unhandled cap, mark its existence
212 flags = PCICapability.RD
214 content = f.read(len - 2)
215 caps.append(PCICapability(id, cap, len, flags, content,
221 def __init__(self, type, domain, bus, dev, fn, caps):
230 self.num_caps = len(caps)
231 self.num_msi_vectors = 0
233 self.num_msix_vectors = 0
234 self.msix_region_size = 0
235 self.msix_address = 0
237 if c.id in (0x05, 0x11):
238 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
239 if c.id == 0x05: # MSI
240 self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
241 self.msi_64bits = (msg_ctrl >> 7) & 1
243 vectors = (msg_ctrl & 0x7ff) + 1
244 self.num_msix_vectors = vectors
245 self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
246 self.msix_address = c.msix_address
249 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
252 return self.bus << 8 | self.dev << 3 | self.fn
255 def parse_pcidevice_sysfsdir(basedir, dir):
256 dpath = os.path.join(basedir, dir)
257 dclass = input_readline(os.path.join(dpath, 'class'))
258 if re.match(r'0x0604..', dclass):
259 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
261 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
263 domain = int(a[0], 16)
266 caps = PCICapability.parse_pcicaps(dpath)
267 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
272 def __init__(self, start, stop, typestr, comments=None):
275 self.typestr = typestr
279 self.comments = comments
282 return 'MemRegion: %08x-%08x : %s' % \
283 (self.start, self.stop, self.typestr)
286 # round up to full PAGE_SIZE
287 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
289 def flagstr(self, p=''):
291 self.typestr == 'System RAM' or
292 self.typestr == 'Kernel' or
293 self.typestr == 'RAM buffer' or
294 self.typestr == 'ACPI DMAR RMRR'
296 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
297 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
299 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
303 def __init__(self, id, address, gsi_base, iommu=0, bdf=0):
305 self.address = address
306 self.gsi_base = gsi_base
311 return 'IOAPIC %d, GSI base %d' % (self.id, self.gsi_base)
313 def irqchip_id(self):
314 # encode the IOMMU number into the irqchip ID
315 return (self.iommu << 16) | self.bdf
318 class IOMemRegionTree:
319 def __init__(self, region, level):
328 s = (' ' * (self.level - 1)) + str(self.region)
329 if self.parent and self.parent.region:
330 s += ' --> ' + self.parent.region.typestr
332 for c in self.children:
336 def regions_split_by_kernel(self):
337 kernel = [x for x in self.children if
338 x.region.typestr.startswith('Kernel ')]
340 if (len(kernel) == 0):
346 kernel_start = kernel[0].region.start
347 kernel_stop = kernel[len(kernel) - 1].region.stop
349 # align this for 16M, but only if we have enough space
350 kernel_stop = (kernel_stop & ~0xFFFFFF) + 0xFFFFFF
351 if (kernel_stop > r.stop):
357 # before Kernel if any
358 if (r.start < kernel_start):
359 before_kernel = MemRegion(r.start, kernel_start - 1, s)
361 kernel_region = MemRegion(kernel_start, kernel_stop, "Kernel")
363 # after Kernel if any
364 if (r.stop > kernel_stop):
365 after_kernel = MemRegion(kernel_stop + 1, r.stop, s)
367 return [before_kernel, kernel_region, after_kernel]
370 def parse_iomem_line(line):
371 a = line.split(':', 1)
372 level = int(a[0].count(' ') / 2) + 1
373 region = a[0].split('-', 1)
375 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
378 def parse_iomem_file():
379 root = IOMemRegionTree(None, 0)
380 f = input_open('/proc/iomem')
384 (level, r) = IOMemRegionTree.parse_iomem_line(line)
385 t = IOMemRegionTree(r, level)
386 if (t.level > lastlevel):
388 if (t.level == lastlevel):
389 t.parent = lastnode.parent
390 if (t.level < lastlevel):
392 while(t.level < p.level):
396 t.parent.children.append(t)
403 # find HPET regions in tree
405 def find_hpet_regions(tree):
408 for tree in tree.children:
412 if (s.find('HPET') >= 0):
415 # if the tree continues recurse further down ...
416 if (len(tree.children) > 0):
417 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
421 # recurse down the tree
423 def parse_iomem_tree(tree):
426 for tree in tree.children:
430 # System RAM on the first level will be added completely,
431 # if they don't contain the kernel itself, if they do,
433 if (tree.level == 1 and s == 'System RAM'):
434 regions.extend(tree.regions_split_by_kernel())
437 # blacklisted on all levels
439 (s.find('PCI MMCONFIG') >= 0) or
440 (s.find('APIC') >= 0) or # covers both APIC and IOAPIC
441 (s.find('dmar') >= 0)
445 # generally blacklisted, unless we find an HPET behind it
446 if (s == 'reserved'):
447 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
450 # if the tree continues recurse further down ...
451 if (len(tree.children) > 0):
452 regions.extend(IOMemRegionTree.parse_iomem_tree(tree))
455 # add all remaining leaves
461 def parse_iomem(pcidevices):
462 regions = IOMemRegionTree.parse_iomem_tree(
463 IOMemRegionTree.parse_iomem_file())
465 # filter the list for MSI-X pages
469 if d.msix_address >= r.start and d.msix_address <= r.stop:
470 if d.msix_address > r.start:
471 head_r = MemRegion(r.start, d.msix_address - 1,
472 r.typestr, r.comments)
474 if d.msix_address + d.msix_region_size < r.stop:
475 tail_r = MemRegion(d.msix_address + d.msix_region_size,
476 r.stop, r.typestr, r.comments)
483 # newer Linux kernels will report the first page as reserved
484 # it is needed for CPU init so include it anyways
485 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
491 def parse_pcidevices():
494 basedir = '/sys/bus/pci/devices'
495 list = input_listdir(basedir, ['*/class', '*/config'])
497 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
501 # look for duplicate capability patterns
503 if d2.caps == d.caps:
504 # reused existing capability list, but record all users
505 d2.caps[0].comments.append(str(d))
506 d.caps_start = d2.caps_start
510 d.caps[0].comments.append(str(d))
511 d.caps_start = len(caps)
514 return (devices, caps)
517 def parse_kernel_cmdline():
518 line = input_readline('/proc/cmdline')
519 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
520 '([0-9a-fA-FxX]+)([KMG]?).*',
523 size = kmg_multiply(int(m.group(1), 0), m.group(2))
524 start = kmg_multiply(int(m.group(3), 0), m.group(4))
529 def alloc_mem(regions, size):
530 mem = [0x3b000000, size]
533 r.typestr == 'System RAM' and
534 r.start <= mem[0] and
535 r.stop + 1 >= mem[0] + mem[1]
538 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
539 regions.insert(regions.index(r), head_r)
540 if r.stop + 1 > mem[0] + mem[1]:
541 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
543 regions.insert(regions.index(r), tail_r)
546 for r in reversed(regions):
547 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
551 raise RuntimeError('failed to allocate memory')
555 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
558 if re.match(r'cpu[0-9]+', f):
564 f = input_open('/sys/firmware/acpi/tables/APIC', 'rb')
565 signature = f.read(4)
566 if signature != b'APIC':
567 raise RuntimeError('MADT: incorrect input file format %s' % signature)
568 (length,) = struct.unpack('<I', f.read(4))
575 (struct_type, struct_len) = struct.unpack('<BB', f.read(2))
580 (id, address, gsi_base) = struct.unpack('<BxII', f.read(10))
582 ioapics.append(IOAPIC(id, address, gsi_base))
584 f.seek(struct_len - offset, os.SEEK_CUR)
589 def parse_dmar_devscope(f):
590 (scope_type, scope_len, id, bus, dev, fn) = \
591 struct.unpack('<BBxxBBBB', f.read(8))
593 raise RuntimeError('Unsupported DMAR Device Scope Structure')
594 return (scope_type, scope_len, id, bus, dev, fn)
597 # parsing of DMAR ACPI Table
598 # see Intel VT-d Spec chapter 8
599 def parse_dmar(pcidevices, ioapics):
600 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
601 signature = f.read(4)
602 if signature != b'DMAR':
603 raise RuntimeError('DMAR: incorrect input file format %s' % signature)
604 (length,) = struct.unpack('<I', f.read(4))
612 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
616 # DMA Remapping Hardware Unit Definition
618 (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
620 raise RuntimeError('We do not support multiple PCI segments')
622 raise RuntimeError('Too many DMAR units. '
623 'Raise JAILHOUSE_MAX_DMAR_UNITS.')
628 d.iommu = len(units) - 1
629 offset += 16 - offset
630 while offset < struct_len:
631 (scope_type, scope_len, id, bus, dev, fn) =\
632 parse_dmar_devscope(f)
635 if d.bus == bus and d.dev == dev and d.fn == fn:
636 d.iommu = len(units) - 1
637 elif scope_type == 2:
638 raise RuntimeError('Unsupported DMAR Device Scope type')
639 elif scope_type == 3:
640 ioapic = next(chip for chip in ioapics if chip.id == id)
641 bdf = (bus << 8) | (dev << 3) | fn
644 raise RuntimeError('IOAPICs with identical BDF')
646 ioapic.dmar_unit = len(units) - 1
649 # Reserved Memory Region Reporting Structure
651 f.seek(8 - offset, os.SEEK_CUR)
653 (base, limit) = struct.unpack('<QQ', f.read(16))
657 while offset < struct_len:
658 (scope_type, scope_len, id, bus, dev, fn) =\
659 parse_dmar_devscope(f)
661 comments.append('PCI device: %02x:%02x.%x' %
664 comments.append('DMAR parser could not decode device path')
667 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
670 f.seek(struct_len - offset, os.SEEK_CUR)
672 return units, regions
677 f = input_open('/proc/ioports')
679 if line.endswith('ACPI PM_TMR\n'):
680 pm_timer_base = int(line.split('-')[0], 16)
687 def __init__(self, base, end_bus):
689 self.end_bus = end_bus
693 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
694 signature = f.read(4)
695 if signature != b'MCFG':
696 raise RuntimeError('MCFG: incorrect input file format %s' %
698 (length,) = struct.unpack('<I', f.read(4))
700 raise RuntimeError('Multiple MMCONFIG regions found! '
701 'This is not supported')
703 (base, segment, start_bus, end_bus) = \
704 struct.unpack('<QHBB', f.read(12))
705 if segment != 0 or start_bus != 0:
706 raise RuntimeError('Invalid MCFG structure found')
707 return MMConfig(base, end_bus)
710 def get_cpu_vendor():
712 if cpuvendor is not None:
714 with input_open('/proc/cpuinfo', 'r') as f:
718 key, value = line.split(':')
719 if key.strip() == 'vendor_id':
720 cpuvendor = value.strip()
724 if options.generate_collector:
725 f = open(options.file, 'w')
726 filelist = ' '.join(inputs['files'])
727 filelist_opt = ' '.join(inputs['files_opt'])
728 filelist_intel = ' '.join(inputs['files_intel'])
730 tmpl = Template(filename=os.path.join(options.template_dir,
731 'jailhouse-config-collect.tmpl'))
732 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
733 filelist_intel=filelist_intel))
737 if ((options.root is '/') and (os.geteuid() is not 0)):
738 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
741 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
742 if jh_enabled == '1':
743 print('ERROR: Jailhouse was enabled when collecting input files! '
744 'Disable jailhouse and try again.',
748 (pcidevices, pcicaps) = parse_pcidevices()
750 product = [input_readline('/sys/class/dmi/id/sys_vendor',
752 input_readline('/sys/class/dmi/id/product_name',
756 inmatemem = kmg_multiply_str(options.mem_inmates)
757 hvmem = [0, kmg_multiply_str(options.mem_hv)]
759 regions = parse_iomem(pcidevices)
760 ourmem = parse_kernel_cmdline()
761 total = hvmem[1] + inmatemem
763 mmconfig = MMConfig.parse()
765 ioapics = parse_madt()
767 if get_cpu_vendor() == 'GenuineIntel':
768 (dmar_units, rmrr_regs) = parse_dmar(pcidevices, ioapics)
770 (dmar_units, rmrr_regs) = [], []
774 if get_cpu_vendor() == 'AuthenticAMD':
775 d.iommu = 0 # temporary workaround
777 raise RuntimeError('PCI device %02x:%02x.%x outside the scope of an '
778 'IOMMU' % (d.bus, d.dev, d.fn))
780 # kernel does not have memmap region, pick one
782 ourmem = alloc_mem(regions, total)
783 elif (total > ourmem[1]):
784 raise RuntimeError('Your memmap reservation is too small you need >="' +
789 inmatereg = MemRegion(ourmem[0] + hvmem[1],
790 ourmem[0] + hvmem[1] + inmatemem - 1,
791 'JAILHOUSE Inmate Memory')
792 regions.append(inmatereg)
794 cpucount = count_cpus()
796 pm_timer_base = parse_ioports()
799 f = open(options.file, 'w')
800 tmpl = Template(filename=os.path.join(options.template_dir,
801 'root-cell-config.c.tmpl'))
802 f.write(tmpl.render(regions=regions,
804 argstr=' '.join(sys.argv),
807 pcidevices=pcidevices,
811 pm_timer_base=pm_timer_base,
813 dmar_units=dmar_units))