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()
80 inputs['files'].add('/proc/iomem')
81 inputs['files'].add('/proc/cpuinfo')
82 inputs['files'].add('/proc/cmdline')
83 inputs['files'].add('/proc/ioports')
84 inputs['files'].add('/sys/bus/pci/devices/*/config')
85 inputs['files'].add('/sys/bus/pci/devices/*/resource')
86 inputs['files'].add('/sys/devices/system/cpu/cpu*/uevent')
87 inputs['files'].add('/sys/firmware/acpi/tables/APIC')
88 inputs['files'].add('/sys/firmware/acpi/tables/MCFG')
90 inputs['files_opt'].add('/sys/class/dmi/id/product_name')
91 inputs['files_opt'].add('/sys/class/dmi/id/sys_vendor')
92 inputs['files_opt'].add('/sys/devices/jailhouse/enabled')
93 # platform specific files
94 inputs['files_intel'].add('/sys/firmware/acpi/tables/DMAR')
95 inputs['files_amd'].add('/sys/firmware/acpi/tables/IVRS')
98 def kmg_multiply(value, kmg):
99 if (kmg == 'K' or kmg == 'k'):
101 if (kmg == 'M' or kmg == 'm'):
102 return 1024**2 * value
103 if (kmg == 'G' or kmg == 'g'):
104 return 1024**3 * value
108 def kmg_multiply_str(str):
109 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
111 return kmg_multiply(int(m.group(1)), m.group(2))
112 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
115 def check_input_listed(name, optional=False):
116 set = inputs['files_opt']
117 if optional is False:
118 set = inputs['files']
120 if cpuvendor == 'GenuineIntel':
121 set = set.union(inputs['files_intel'])
122 elif cpuvendor == 'AuthenticAMD':
123 set = set.union(inputs['files_amd'])
126 if fnmatch.fnmatch(name, file):
128 raise RuntimeError('"' + name + '" is not a listed input file')
131 def input_open(name, mode='r', optional=False):
132 check_input_listed(name, optional)
134 f = open(options.root + name, mode)
135 except Exception as e:
137 return open("/dev/null", mode)
142 def input_readline(name, optional=False):
143 f = input_open(name, optional=optional)
149 def input_listdir(dir, wildcards):
151 check_input_listed(os.path.join(dir, w))
152 dirs = os.listdir(options.root + dir)
158 IORESOURCE_IO = 0x00000100
159 IORESOURCE_MEM = 0x00000200
160 IORESOURCE_MEM_64 = 0x00100000
162 def __init__(self, dir):
164 f = input_open(os.path.join(dir, 'resource'), 'r')
166 (start, end, flags) = f.readline().split()
167 flags = int(flags, 16)
168 if flags & PCIBARs.IORESOURCE_IO:
169 mask = ~(int(end, 16) - int(start, 16))
170 elif flags & PCIBARs.IORESOURCE_MEM:
171 mask = ~(int(end, 16) - int(start, 16))
172 if flags & PCIBARs.IORESOURCE_MEM_64:
173 self.mask.append(mask & 0xffffffff)
178 self.mask.append(mask & 0xffffffff)
183 def __init__(self, id, start, len, flags, content, msix_address):
188 self.content = content
189 self.msix_address = msix_address
192 def __eq__(self, other):
193 return self.id == other.id and self.start == other.start and \
194 self.len == other.len and self.flags == other.flags
197 RW = 'JAILHOUSE_PCICAPS_WRITE'
199 JAILHOUSE_PCI_EXT_CAP = 0x8000
202 def parse_pcicaps(dir):
204 has_extended_caps = False
205 f = input_open(os.path.join(dir, 'config'), 'rb')
207 (status,) = struct.unpack('<H', f.read(2))
208 # capability list supported?
209 if (status & (1 << 4)) == 0:
212 # walk capability list
214 (next,) = struct.unpack('B', f.read(1))
219 (id, next) = struct.unpack('<BB', f.read(2))
220 if id == 0x01: # Power Management
221 # this cap can be handed out completely
223 flags = PCICapability.RW
224 elif id == 0x05: # MSI
225 # access will be moderated by hypervisor
227 (msgctl,) = struct.unpack('<H', f.read(2))
228 if (msgctl & (1 << 7)) != 0: # 64-bit support
230 if (msgctl & (1 << 8)) != 0: # per-vector masking support
232 flags = PCICapability.RW
233 elif id == 0x10: # Express
235 (cap_reg,) = struct.unpack('<H', f.read(2))
236 if (cap_reg & 0xf) >= 2: # v2 capability
238 # access side effects still need to be analyzed
239 flags = PCICapability.RD
240 has_extended_caps = True
241 elif id == 0x11: # MSI-X
242 # access will be moderated by hypervisor
244 (table,) = struct.unpack('<xxI', f.read(6))
245 f.seek(0x10 + (table & 7) * 4)
246 (bar,) = struct.unpack('<I', f.read(4))
248 raise RuntimeError('Invalid MSI-X BAR found')
250 bar |= struct.unpack('<I', f.read(4))[0] << 32
251 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
252 flags = PCICapability.RW
254 # unknown/unhandled cap, mark its existence
256 flags = PCICapability.RD
258 content = f.read(len - 2)
259 caps.append(PCICapability(id, cap, len, flags, content,
262 if has_extended_caps:
263 # walk extended capability list
268 (id, version_next) = struct.unpack('<HH', f.read(4))
269 next = version_next >> 4
272 elif id == 0x0010: # SR-IOV
274 # access side effects still need to be analyzed
275 flags = PCICapability.RD
277 if (id & PCICapability.JAILHOUSE_PCI_EXT_CAP) != 0:
278 print('WARNING: Ignoring unsupported PCI Express '
279 'Extended Capability ID %x' % id)
281 # unknown/unhandled cap, mark its existence
283 flags = PCICapability.RD
285 content = f.read(len - 4)
286 id |= PCICapability.JAILHOUSE_PCI_EXT_CAP
287 caps.append(PCICapability(id, cap, len, flags, content, 0))
294 def __init__(self, type, domain, bus, dev, fn, bars, caps, path):
305 self.num_caps = len(caps)
306 self.num_msi_vectors = 0
308 self.num_msix_vectors = 0
309 self.msix_region_size = 0
310 self.msix_address = 0
312 if c.id in (0x05, 0x11):
313 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
314 if c.id == 0x05: # MSI
315 self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
316 self.msi_64bits = (msg_ctrl >> 7) & 1
318 if c.msix_address != 0:
319 vectors = (msg_ctrl & 0x7ff) + 1
320 self.num_msix_vectors = vectors
321 self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
322 self.msix_address = c.msix_address
324 print('WARNING: Ignoring invalid MSI-X configuration'
325 ' of device %02x:%02x.%x' % (bus, dev, fn))
328 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
331 return self.bus << 8 | self.dev << 3 | self.fn
334 def parse_pcidevice_sysfsdir(basedir, dir):
335 dpath = os.path.join(basedir, dir)
336 f = input_open(os.path.join(dpath, 'config'), 'rb')
338 (classcode,) = struct.unpack('<H', f.read(2))
340 if classcode == 0x0604:
341 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
343 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
345 domain = int(a[0], 16)
348 bars = PCIBARs(dpath)
349 caps = PCICapability.parse_pcicaps(dpath)
350 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
354 class PCIPCIBridge(PCIDevice):
356 def get_2nd_busses(dev):
357 assert dev.type == 'JAILHOUSE_PCI_TYPE_BRIDGE'
358 f = input_open(os.path.join(dev.path, 'config'), 'rb')
360 (secondbus, subordinate) = struct.unpack('<BB', f.read(2))
362 return (secondbus, subordinate)
366 def __init__(self, start, stop, typestr, comments=None):
369 self.typestr = typestr
373 self.comments = comments
376 return 'MemRegion: %08x-%08x : %s' % \
377 (self.start, self.stop, self.typestr)
380 # round up to full PAGE_SIZE
381 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
383 def flagstr(self, p=''):
385 self.typestr == 'System RAM' or
386 self.typestr == 'Kernel' or
387 self.typestr == 'RAM buffer' or
388 self.typestr == 'ACPI DMAR RMRR' or
389 self.typestr == 'ACPI IVRS'
391 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
392 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
394 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
398 def __init__(self, id, address, gsi_base, iommu=0, bdf=0):
400 self.address = address
401 self.gsi_base = gsi_base
406 return 'IOAPIC %d, GSI base %d' % (self.id, self.gsi_base)
408 def irqchip_id(self):
409 # encode the IOMMU number into the irqchip ID
410 return (self.iommu << 16) | self.bdf
413 class IOMemRegionTree:
414 def __init__(self, region, level):
423 s = (' ' * (self.level - 1)) + str(self.region)
424 if self.parent and self.parent.region:
425 s += ' --> ' + self.parent.region.typestr
427 for c in self.children:
431 def regions_split_by_kernel(self):
432 kernel = [x for x in self.children if
433 x.region.typestr.startswith('Kernel ')]
435 if (len(kernel) == 0):
441 kernel_start = kernel[0].region.start
442 kernel_stop = kernel[len(kernel) - 1].region.stop
444 # align this for 16M, but only if we have enough space
445 kernel_stop = (kernel_stop & ~0xFFFFFF) + 0xFFFFFF
446 if (kernel_stop > r.stop):
452 # before Kernel if any
453 if (r.start < kernel_start):
454 before_kernel = MemRegion(r.start, kernel_start - 1, s)
456 kernel_region = MemRegion(kernel_start, kernel_stop, "Kernel")
458 # after Kernel if any
459 if (r.stop > kernel_stop):
460 after_kernel = MemRegion(kernel_stop + 1, r.stop, s)
462 return [before_kernel, kernel_region, after_kernel]
465 def parse_iomem_line(line):
466 a = line.split(':', 1)
467 level = int(a[0].count(' ') / 2) + 1
468 region = a[0].split('-', 1)
470 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
473 def parse_iomem_file():
474 root = IOMemRegionTree(None, 0)
475 f = input_open('/proc/iomem')
479 (level, r) = IOMemRegionTree.parse_iomem_line(line)
480 t = IOMemRegionTree(r, level)
481 if (t.level > lastlevel):
483 if (t.level == lastlevel):
484 t.parent = lastnode.parent
485 if (t.level < lastlevel):
487 while(t.level < p.level):
491 t.parent.children.append(t)
498 # find HPET regions in tree
500 def find_hpet_regions(tree):
503 for tree in tree.children:
507 if (s.find('HPET') >= 0):
510 # if the tree continues recurse further down ...
511 if (len(tree.children) > 0):
512 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
516 # recurse down the tree
518 def parse_iomem_tree(tree):
521 for tree in tree.children:
525 # System RAM on the first level will be added completely,
526 # if they don't contain the kernel itself, if they do,
528 if (tree.level == 1 and s == 'System RAM'):
529 regions.extend(tree.regions_split_by_kernel())
532 # blacklisted on all levels
534 (s.find('PCI MMCONFIG') >= 0) or
535 (s.find('APIC') >= 0) or # covers both APIC and IOAPIC
536 (s.find('dmar') >= 0)
540 # generally blacklisted, unless we find an HPET behind it
541 if (s == 'reserved'):
542 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
545 # if the tree continues recurse further down ...
546 if (len(tree.children) > 0):
547 regions.extend(IOMemRegionTree.parse_iomem_tree(tree))
550 # add all remaining leaves
556 def parse_iomem(pcidevices):
557 regions = IOMemRegionTree.parse_iomem_tree(
558 IOMemRegionTree.parse_iomem_file())
560 rom_region = MemRegion(0xc0000, 0xdffff, 'ROMs')
561 add_rom_region = False
566 # filter the list for MSI-X pages
568 if d.msix_address >= r.start and d.msix_address <= r.stop:
569 if d.msix_address > r.start:
570 head_r = MemRegion(r.start, d.msix_address - 1,
571 r.typestr, r.comments)
573 if d.msix_address + d.msix_region_size < r.stop:
574 tail_r = MemRegion(d.msix_address + d.msix_region_size,
575 r.stop, r.typestr, r.comments)
579 # filter out the ROMs
580 if (r.start >= rom_region.start and r.stop <= rom_region.stop):
581 add_rom_region = True
586 # add a region that covers all potential ROMs
588 ret.append(rom_region)
590 # newer Linux kernels will report the first page as reserved
591 # it is needed for CPU init so include it anyways
592 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
598 def parse_pcidevices():
601 basedir = '/sys/bus/pci/devices'
602 list = input_listdir(basedir, ['*/config'])
604 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
608 # look for duplicate capability patterns
610 if d2.caps == d.caps:
611 # reused existing capability list, but record all users
612 d2.caps[0].comments.append(str(d))
613 d.caps_start = d2.caps_start
617 d.caps[0].comments.append(str(d))
618 d.caps_start = len(caps)
621 return (devices, caps)
624 def parse_kernel_cmdline():
625 line = input_readline('/proc/cmdline')
626 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
627 '([0-9a-fA-FxX]+)([KMG]?).*',
630 size = kmg_multiply(int(m.group(1), 0), m.group(2))
631 start = kmg_multiply(int(m.group(3), 0), m.group(4))
636 def alloc_mem(regions, size):
637 mem = [0x3b000000, size]
640 r.typestr == 'System RAM' and
641 r.start <= mem[0] and
642 r.stop + 1 >= mem[0] + mem[1]
645 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
646 regions.insert(regions.index(r), head_r)
647 if r.stop + 1 > mem[0] + mem[1]:
648 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
650 regions.insert(regions.index(r), tail_r)
653 for r in reversed(regions):
654 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
658 raise RuntimeError('failed to allocate memory')
662 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
665 if re.match(r'cpu[0-9]+', f):
671 f = input_open('/sys/firmware/acpi/tables/APIC', 'rb')
672 signature = f.read(4)
673 if signature != b'APIC':
674 raise RuntimeError('MADT: incorrect input file format %s' % signature)
675 (length,) = struct.unpack('<I', f.read(4))
682 (struct_type, struct_len) = struct.unpack('<BB', f.read(2))
687 (id, address, gsi_base) = struct.unpack('<BxII', f.read(10))
689 ioapics.append(IOAPIC(id, address, gsi_base))
691 f.seek(struct_len - offset, os.SEEK_CUR)
697 def parse_dmar_devscope(f):
698 (scope_type, scope_len, id, bus, dev, fn) = \
699 struct.unpack('<BBxxBBBB', f.read(8))
701 raise RuntimeError('Unsupported DMAR Device Scope Structure')
702 return (scope_type, scope_len, id, bus, dev, fn)
705 # parsing of DMAR ACPI Table
706 # see Intel VT-d Spec chapter 8
707 def parse_dmar(pcidevices, ioapics):
708 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
709 signature = f.read(4)
710 if signature != b'DMAR':
711 raise RuntimeError('DMAR: incorrect input file format %s' % signature)
712 (length,) = struct.unpack('<I', f.read(4))
720 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
724 # DMA Remapping Hardware Unit Definition
726 (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
728 raise RuntimeError('We do not support multiple PCI segments')
730 raise RuntimeError('Too many DMAR units. '
731 'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
736 d.iommu = len(units) - 1
737 offset += 16 - offset
738 while offset < struct_len:
739 (scope_type, scope_len, id, bus, dev, fn) =\
740 parse_dmar_devscope(f)
741 # PCI Endpoint Device
743 assert not (flags & 1)
745 if d.bus == bus and d.dev == dev and d.fn == fn:
746 d.iommu = len(units) - 1
749 elif scope_type == 2:
750 assert not (flags & 1)
752 if d.bus == bus and d.dev == dev and d.fn == fn:
753 (secondbus, subordinate) = \
754 PCIPCIBridge.get_2nd_busses(d)
755 for d2 in pcidevices:
757 d2.bus >= secondbus and
758 d2.bus <= subordinate
760 d2.iommu = len(units) - 1
763 elif scope_type == 3:
764 ioapic = next(chip for chip in ioapics if chip.id == id)
765 bdf = (bus << 8) | (dev << 3) | fn
768 raise RuntimeError('IOAPICs with identical BDF')
770 ioapic.iommu = len(units) - 1
773 # Reserved Memory Region Reporting Structure
775 f.seek(8 - offset, os.SEEK_CUR)
777 (base, limit) = struct.unpack('<QQ', f.read(16))
781 while offset < struct_len:
782 (scope_type, scope_len, id, bus, dev, fn) =\
783 parse_dmar_devscope(f)
785 comments.append('PCI device: %02x:%02x.%x' %
788 comments.append('DMAR parser could not decode device path')
791 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
794 f.seek(struct_len - offset, os.SEEK_CUR)
801 'PCI device %02x:%02x.%x outside the scope of an '
802 'IOMMU' % (d.bus, d.dev, d.fn))
804 return units, regions
807 def parse_ivrs(pcidevices, ioapics):
809 bus, dev, fun = (bdf >> 8) & 0xff, (bdf >> 3) & 0x1f, bdf & 0x7
810 return '%02x:%02x.%x' % (bus, dev, fun)
812 f = input_open('/sys/firmware/acpi/tables/IVRS', 'rb')
813 signature = f.read(4)
814 if signature != b'IVRS':
815 raise RuntimeError('IVRS: incorrect input file format %s' % signature)
817 (length, revision) = struct.unpack('<IB', f.read(5))
819 raise RuntimeError('IVRS: unsupported Revision %02x' % revision)
821 f.seek(48, os.SEEK_SET)
826 # BDF of devices that are permitted outside IOMMU: root complex
827 iommu_skiplist = set([0x0])
829 (block_type, block_length) = struct.unpack('<BxH', f.read(4))
830 if block_type in [0x10, 0x11]:
832 (iommu_id, base_addr, pci_seg) = \
833 struct.unpack('<HxxQH', f.read(14))
834 length -= block_length
837 # IOMMU EFR image and reserved area
838 skip_bytes = 6 if block_type == 0x10 else 22
839 f.seek(skip_bytes, os.SEEK_CUR)
840 block_length -= skip_bytes
843 raise RuntimeError('We do not support multiple PCI segments')
846 raise RuntimeError('Too many IOMMU units. '
847 'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
849 # We shouldn't map IOMMU to the cells
850 for i, d in enumerate(pcidevices):
851 if d.bdf() == iommu_id:
854 units.append(base_addr)
856 bdf_start_range = None
857 while block_length > 0:
858 (entry_type, device_id) = struct.unpack('<BHx', f.read(4))
861 if entry_type == 0x01:
864 d.iommu = len(units) - 1
865 elif entry_type == 0x02:
868 if d.bdf() == device_id:
869 d.iommu = len(units) - 1
870 elif entry_type == 0x03:
872 bdf_start_range = device_id
873 elif entry_type == 0x04:
875 if bdf_start_range is None:
878 if d.bdf() >= bdf_start_range and d.bdf() <= device_id:
879 d.iommu = len(units) - 1
880 bdf_start_range = None
881 elif entry_type == 0x42:
883 (device_id_b,) = struct.unpack('<xHx', f.read(4))
886 if d.bdf() == device_id_b:
887 d.iommu = len(units) - 1
888 elif entry_type == 0x43:
889 # Alias start of range
890 (device_id_b,) = struct.unpack('<xHx', f.read(4))
892 bdf_start_range = device_id_b
893 elif entry_type == 0x48:
895 (handle, device_id_b, variety) = struct.unpack(
898 if variety == 0x01: # IOAPIC
900 if chip.id == handle:
902 chip.iommu = len(units) - 1
904 # Reserved or ignored entries
905 if entry_type >= 0x40:
906 f.seek(4, os.SEEK_CUR)
909 elif type in [0x20, 0x21, 0x22]:
911 (block_type, block_flags, block_length,
912 device_id, aux_data, mem_addr, mem_len) = struct.unpack(
914 length -= block_length
917 bdf_str = format_bdf(device_id)
919 'WARNING: Jailhouse doesn\'t support configurable '
920 '(eg. read-only) device memory. Device %s may not '
921 'work properly, especially in non-root cell.' % bdf_str)
923 if block_type == 0x20:
926 elif block_type == 0x21:
928 comment = 'PCI Device: %s' % format_bdf(device_id)
929 elif block_type == 0x22:
931 comment = 'PCI Device: %s - %s' % (
932 format_bdf(device_id), format_bdf(aux_data))
935 print('WARNING: Jailhouse doesn\'t support per-device memory '
936 'regions. The memory at 0x%x will be mapped accessible '
937 'to all devices.' % mem_addr)
939 regions.append(MemRegion(mem_addr, mem_len, 'ACPI IVRS', comment))
942 'You board uses IVRS Rev. 2 feature Jailhouse doesn\'t '
943 'support yet. Please report this to '
944 'jailhouse-dev@googlegroups.com.')
947 'WARNING: Skipping unknown IVRS '
948 'block type 0x%02x' % block_type)
951 if d.bdf() not in iommu_skiplist and d.iommu is None:
953 'PCI device %02x:%02x.%x outside the scope of an '
954 'IOMMU' % (d.bus, d.dev, d.fn))
957 return units, regions
962 f = input_open('/proc/ioports')
964 if line.endswith('ACPI PM_TMR\n'):
965 pm_timer_base = int(line.split('-')[0], 16)
972 def __init__(self, base, end_bus):
974 self.end_bus = end_bus
978 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
979 signature = f.read(4)
980 if signature != b'MCFG':
981 raise RuntimeError('MCFG: incorrect input file format %s' %
983 (length,) = struct.unpack('<I', f.read(4))
985 raise RuntimeError('Multiple MMCONFIG regions found! '
986 'This is not supported')
988 (base, segment, start_bus, end_bus) = \
989 struct.unpack('<QHBB', f.read(12))
990 if segment != 0 or start_bus != 0:
991 raise RuntimeError('Invalid MCFG structure found')
992 return MMConfig(base, end_bus)
995 def get_cpu_vendor():
997 if cpuvendor is not None:
999 with input_open('/proc/cpuinfo', 'r') as f:
1001 if not line.strip():
1003 key, value = line.split(':')
1004 if key.strip() == 'vendor_id':
1005 cpuvendor = value.strip()
1009 if options.generate_collector:
1010 f = open(options.file, 'w')
1011 filelist = ' '.join(inputs['files'])
1012 filelist_opt = ' '.join(inputs['files_opt'])
1013 filelist_intel = ' '.join(inputs['files_intel'])
1014 filelist_amd = ' '.join(inputs['files_amd'])
1016 tmpl = Template(filename=os.path.join(options.template_dir,
1017 'jailhouse-config-collect.tmpl'))
1018 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
1019 filelist_intel=filelist_intel, filelist_amd=filelist_amd))
1023 if ((options.root is '/') and (os.geteuid() is not 0)):
1024 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
1027 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
1028 if jh_enabled == '1':
1029 print('ERROR: Jailhouse was enabled when collecting input files! '
1030 'Disable jailhouse and try again.',
1034 (pcidevices, pcicaps) = parse_pcidevices()
1036 product = [input_readline('/sys/class/dmi/id/sys_vendor',
1038 input_readline('/sys/class/dmi/id/product_name',
1042 inmatemem = kmg_multiply_str(options.mem_inmates)
1043 hvmem = [0, kmg_multiply_str(options.mem_hv)]
1045 regions = parse_iomem(pcidevices)
1046 ourmem = parse_kernel_cmdline()
1047 total = hvmem[1] + inmatemem
1049 mmconfig = MMConfig.parse()
1051 ioapics = parse_madt()
1053 vendor = get_cpu_vendor()
1054 if vendor == 'GenuineIntel':
1055 (iommu_units, extra_memregs) = parse_dmar(pcidevices, ioapics)
1057 (iommu_units, extra_memregs) = parse_ivrs(pcidevices, ioapics)
1058 regions += extra_memregs
1060 # kernel does not have memmap region, pick one
1062 ourmem = alloc_mem(regions, total)
1063 elif (total > ourmem[1]):
1064 raise RuntimeError('Your memmap reservation is too small you need >="' +
1065 hex(total) + '". Hint: your kernel cmd line needs '
1066 '"memmap=' + hex(total) + '$' + hex(ourmem[0]) + '"')
1068 hvmem[0] = ourmem[0]
1070 inmatereg = MemRegion(ourmem[0] + hvmem[1],
1071 ourmem[0] + hvmem[1] + inmatemem - 1,
1072 'JAILHOUSE Inmate Memory')
1073 regions.append(inmatereg)
1075 cpucount = count_cpus()
1077 pm_timer_base = parse_ioports()
1080 f = open(options.file, 'w')
1081 tmpl = Template(filename=os.path.join(options.template_dir,
1082 'root-cell-config.c.tmpl'))
1086 'argstr': ' '.join(sys.argv),
1089 'pcidevices': pcidevices,
1091 'cpucount': cpucount,
1092 'irqchips': ioapics,
1093 'pm_timer_base': pm_timer_base,
1094 'mmconfig': mmconfig,
1095 'iommu_units': iommu_units
1098 f.write(tmpl.render(**kwargs))