3 # Jailhouse, a Linux-based partitioning hypervisor
5 # Copyright (c) Siemens AG, 2014-2016
6 # Copyright (c) Valentine Sinitsyn, 2014-2015
9 # Henning Schild <henning.schild@siemens.com>
10 # Jan Kiszka <jan.kiszka@siemens.com>
11 # Valentine Sinitsyn <valentine.sinitsyn@gmail.com>
13 # This work is licensed under the terms of the GNU GPL, version 2. See
14 # the COPYING file in the top-level directory.
16 # This script should help to create a basic jailhouse configuration file.
17 # It needs to be executed on the target machine, where it will gather
18 # information about the system. For more advanced scenarios you will have
19 # to change the generated C-code.
21 from __future__ import print_function
28 from mako.template import Template
33 template_default_dir = datadir + "/jailhouse"
35 template_default_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
39 # pretend to be part of the jailhouse tool
40 sys.argv[0] = sys.argv[0].replace('-', ' ')
42 parser = argparse.ArgumentParser()
43 parser.add_argument('-g', '--generate-collector',
44 help='generate a script to collect input files on '
47 parser.add_argument('-r', '--root',
48 help='gather information in ROOT/, the default is "/" '
49 'which means creating a config for localhost',
53 parser.add_argument('-t', '--template-dir',
54 help='the directory where the templates are located,'
55 'the default is "' + template_default_dir + '"',
56 default=template_default_dir,
60 memargs = [['--mem-inmates', '2M', 'inmate'],
61 ['--mem-hv', '64M', 'hypervisor']]
64 parser.add_argument(entry[0],
65 help='the amount of ' + entry[2] +
66 ' memory, default is "' + entry[1] +
67 '", format "xxx[K|M|G]"',
72 parser.add_argument('file', metavar='FILE',
73 help='name of file to write out',
76 options = parser.parse_args()
86 inputs['files'].add('/proc/iomem')
87 inputs['files'].add('/proc/cpuinfo')
88 inputs['files'].add('/proc/cmdline')
89 inputs['files'].add('/proc/ioports')
90 inputs['files'].add('/sys/bus/pci/devices/*/config')
91 inputs['files'].add('/sys/bus/pci/devices/*/resource')
92 inputs['files'].add('/sys/devices/system/cpu/cpu*/uevent')
93 inputs['files'].add('/sys/firmware/acpi/tables/APIC')
94 inputs['files'].add('/sys/firmware/acpi/tables/MCFG')
96 inputs['files_opt'].add('/sys/class/dmi/id/product_name')
97 inputs['files_opt'].add('/sys/class/dmi/id/sys_vendor')
98 inputs['files_opt'].add('/sys/devices/jailhouse/enabled')
99 # platform specific files
100 inputs['files_intel'].add('/sys/firmware/acpi/tables/DMAR')
101 inputs['files_amd'].add('/sys/firmware/acpi/tables/IVRS')
104 def kmg_multiply(value, kmg):
105 if (kmg == 'K' or kmg == 'k'):
107 if (kmg == 'M' or kmg == 'm'):
108 return 1024**2 * value
109 if (kmg == 'G' or kmg == 'g'):
110 return 1024**3 * value
114 def kmg_multiply_str(str):
115 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
117 return kmg_multiply(int(m.group(1)), m.group(2))
118 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
121 def check_input_listed(name, optional=False):
122 set = inputs['files_opt']
123 if optional is False:
124 set = inputs['files']
126 if cpuvendor == 'GenuineIntel':
127 set = set.union(inputs['files_intel'])
128 elif cpuvendor == 'AuthenticAMD':
129 set = set.union(inputs['files_amd'])
132 if fnmatch.fnmatch(name, file):
134 raise RuntimeError('"' + name + '" is not a listed input file')
137 def input_open(name, mode='r', optional=False):
138 check_input_listed(name, optional)
140 f = open(options.root + name, mode)
141 except Exception as e:
143 return open("/dev/null", mode)
148 def input_readline(name, optional=False):
149 f = input_open(name, optional=optional)
155 def input_listdir(dir, wildcards):
157 check_input_listed(os.path.join(dir, w))
158 dirs = os.listdir(options.root + dir)
164 IORESOURCE_IO = 0x00000100
165 IORESOURCE_MEM = 0x00000200
166 IORESOURCE_MEM_64 = 0x00100000
168 def __init__(self, dir):
170 f = input_open(os.path.join(dir, 'resource'), 'r')
172 (start, end, flags) = f.readline().split()
173 flags = int(flags, 16)
174 if flags & PCIBARs.IORESOURCE_IO:
175 mask = ~(int(end, 16) - int(start, 16))
176 elif flags & PCIBARs.IORESOURCE_MEM:
177 mask = ~(int(end, 16) - int(start, 16))
178 if flags & PCIBARs.IORESOURCE_MEM_64:
179 self.mask.append(mask & 0xffffffff)
184 self.mask.append(mask & 0xffffffff)
189 def __init__(self, id, start, len, flags, content, msix_address):
194 self.content = content
195 self.msix_address = msix_address
198 def __eq__(self, other):
199 return self.id == other.id and self.start == other.start and \
200 self.len == other.len and self.flags == other.flags
203 RW = 'JAILHOUSE_PCICAPS_WRITE'
205 JAILHOUSE_PCI_EXT_CAP = 0x8000
208 def parse_pcicaps(dir):
210 has_extended_caps = False
211 f = input_open(os.path.join(dir, 'config'), 'rb')
213 (status,) = struct.unpack('<H', f.read(2))
214 # capability list supported?
215 if (status & (1 << 4)) == 0:
218 # walk capability list
220 (next,) = struct.unpack('B', f.read(1))
225 (id, next) = struct.unpack('<BB', f.read(2))
226 if id == 0x01: # Power Management
227 # this cap can be handed out completely
229 flags = PCICapability.RW
230 elif id == 0x05: # MSI
231 # access will be moderated by hypervisor
233 (msgctl,) = struct.unpack('<H', f.read(2))
234 if (msgctl & (1 << 7)) != 0: # 64-bit support
236 if (msgctl & (1 << 8)) != 0: # per-vector masking support
238 flags = PCICapability.RW
239 elif id == 0x10: # Express
241 (cap_reg,) = struct.unpack('<H', f.read(2))
242 if (cap_reg & 0xf) >= 2: # v2 capability
244 # access side effects still need to be analyzed
245 flags = PCICapability.RD
246 has_extended_caps = True
247 elif id == 0x11: # MSI-X
248 # access will be moderated by hypervisor
250 (table,) = struct.unpack('<xxI', f.read(6))
251 f.seek(0x10 + (table & 7) * 4)
252 (bar,) = struct.unpack('<I', f.read(4))
254 raise RuntimeError('Invalid MSI-X BAR found')
256 bar |= struct.unpack('<I', f.read(4))[0] << 32
257 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
258 flags = PCICapability.RW
260 # unknown/unhandled cap, mark its existence
262 flags = PCICapability.RD
264 content = f.read(len - 2)
265 caps.append(PCICapability(id, cap, len, flags, content,
268 if has_extended_caps:
269 # walk extended capability list
274 (id, version_next) = struct.unpack('<HH', f.read(4))
275 next = version_next >> 4
278 elif id == 0x0010: # SR-IOV
280 # access side effects still need to be analyzed
281 flags = PCICapability.RD
283 if (id & PCICapability.JAILHOUSE_PCI_EXT_CAP) != 0:
284 print('WARNING: Ignoring unsupported PCI Express '
285 'Extended Capability ID %x' % id)
287 # unknown/unhandled cap, mark its existence
289 flags = PCICapability.RD
291 content = f.read(len - 4)
292 id |= PCICapability.JAILHOUSE_PCI_EXT_CAP
293 caps.append(PCICapability(id, cap, len, flags, content, 0))
300 def __init__(self, type, domain, bus, dev, fn, bars, caps, path):
311 self.num_caps = len(caps)
312 self.num_msi_vectors = 0
314 self.num_msix_vectors = 0
315 self.msix_region_size = 0
316 self.msix_address = 0
318 if c.id in (0x05, 0x11):
319 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
320 if c.id == 0x05: # MSI
321 self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
322 self.msi_64bits = (msg_ctrl >> 7) & 1
324 if c.msix_address != 0:
325 vectors = (msg_ctrl & 0x7ff) + 1
326 self.num_msix_vectors = vectors
327 self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
328 self.msix_address = c.msix_address
330 print('WARNING: Ignoring invalid MSI-X configuration'
331 ' of device %02x:%02x.%x' % (bus, dev, fn))
334 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
337 return self.bus << 8 | self.dev << 3 | self.fn
340 def parse_pcidevice_sysfsdir(basedir, dir):
341 dpath = os.path.join(basedir, dir)
342 f = input_open(os.path.join(dpath, 'config'), 'rb')
344 (classcode,) = struct.unpack('<H', f.read(2))
346 if classcode == 0x0604:
347 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
349 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
351 domain = int(a[0], 16)
354 bars = PCIBARs(dpath)
355 caps = PCICapability.parse_pcicaps(dpath)
356 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
360 class PCIPCIBridge(PCIDevice):
362 def get_2nd_busses(dev):
363 assert dev.type == 'JAILHOUSE_PCI_TYPE_BRIDGE'
364 f = input_open(os.path.join(dev.path, 'config'), 'rb')
366 (secondbus, subordinate) = struct.unpack('<BB', f.read(2))
368 return (secondbus, subordinate)
372 def __init__(self, start, stop, typestr, comments=None):
375 self.typestr = typestr
376 self.comments = comments or []
379 return 'MemRegion: %08x-%08x : %s' % \
380 (self.start, self.stop, self.typestr)
383 # round up to full PAGE_SIZE
384 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
386 def flagstr(self, p=''):
388 self.typestr == 'System RAM' or
389 self.typestr == 'Kernel' or
390 self.typestr == 'RAM buffer' or
391 self.typestr == 'ACPI DMAR RMRR' or
392 self.typestr == 'ACPI IVRS'
394 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
395 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
397 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
401 def __init__(self, id, address, gsi_base, iommu=0, bdf=0):
403 self.address = address
404 self.gsi_base = gsi_base
409 return 'IOAPIC %d, GSI base %d' % (self.id, self.gsi_base)
411 def irqchip_id(self):
412 # encode the IOMMU number into the irqchip ID
413 return (self.iommu << 16) | self.bdf
416 class IOMemRegionTree:
417 def __init__(self, region, level):
426 s = (' ' * (self.level - 1)) + str(self.region)
427 if self.parent and self.parent.region:
428 s += ' --> ' + self.parent.region.typestr
430 for c in self.children:
434 def regions_split_by_kernel(self):
435 kernel = [x for x in self.children if
436 x.region.typestr.startswith('Kernel ')]
438 if (len(kernel) == 0):
444 kernel_start = kernel[0].region.start
445 kernel_stop = kernel[len(kernel) - 1].region.stop
447 # align this for 16M, but only if we have enough space
448 kernel_stop = (kernel_stop & ~0xFFFFFF) + 0xFFFFFF
449 if (kernel_stop > r.stop):
455 # before Kernel if any
456 if (r.start < kernel_start):
457 before_kernel = MemRegion(r.start, kernel_start - 1, s)
459 kernel_region = MemRegion(kernel_start, kernel_stop, "Kernel")
461 # after Kernel if any
462 if (r.stop > kernel_stop):
463 after_kernel = MemRegion(kernel_stop + 1, r.stop, s)
465 return [before_kernel, kernel_region, after_kernel]
468 def parse_iomem_line(line):
469 a = line.split(':', 1)
470 level = int(a[0].count(' ') / 2) + 1
471 region = a[0].split('-', 1)
473 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
476 def parse_iomem_file():
477 root = IOMemRegionTree(None, 0)
478 f = input_open('/proc/iomem')
482 (level, r) = IOMemRegionTree.parse_iomem_line(line)
483 t = IOMemRegionTree(r, level)
484 if (t.level > lastlevel):
486 if (t.level == lastlevel):
487 t.parent = lastnode.parent
488 if (t.level < lastlevel):
490 while(t.level < p.level):
494 t.parent.children.append(t)
501 # find HPET regions in tree
503 def find_hpet_regions(tree):
506 for tree in tree.children:
510 if (s.find('HPET') >= 0):
513 # if the tree continues recurse further down ...
514 if (len(tree.children) > 0):
515 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
519 # recurse down the tree
521 def parse_iomem_tree(tree):
524 for tree in tree.children:
528 # System RAM on the first level will be added completely,
529 # if they don't contain the kernel itself, if they do,
531 if (tree.level == 1 and s == 'System RAM'):
532 regions.extend(tree.regions_split_by_kernel())
535 # blacklisted on all levels
537 (s.find('PCI MMCONFIG') >= 0) or
538 (s.find('APIC') >= 0) # covers both APIC and IOAPIC
542 # generally blacklisted, unless we find an HPET behind it
543 if (s == 'reserved'):
544 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
547 # if the tree continues recurse further down ...
548 if (len(tree.children) > 0):
549 regions.extend(IOMemRegionTree.parse_iomem_tree(tree))
552 # add all remaining leaves
558 class IOMMUConfig(object):
559 def __init__(self, props):
560 self.base_addr = props['base_addr']
561 self.mmio_size = props['mmio_size']
562 if 'amd_bdf' in props:
563 self.amd_bdf = props['amd_bdf']
564 self.amd_base_cap = props['amd_base_cap']
565 self.amd_msi_cap = props['amd_msi_cap']
566 self.amd_features = props['amd_features']
569 def is_amd_iommu(self):
570 return hasattr(self, 'amd_bdf')
573 def parse_iomem(pcidevices):
574 regions = IOMemRegionTree.parse_iomem_tree(
575 IOMemRegionTree.parse_iomem_file())
577 rom_region = MemRegion(0xc0000, 0xdffff, 'ROMs')
578 add_rom_region = False
584 # filter the list for MSI-X pages
586 if d.msix_address >= r.start and d.msix_address <= r.stop:
587 if d.msix_address > r.start:
588 head_r = MemRegion(r.start, d.msix_address - 1,
589 r.typestr, r.comments)
591 if d.msix_address + d.msix_region_size < r.stop:
592 tail_r = MemRegion(d.msix_address + d.msix_region_size,
593 r.stop, r.typestr, r.comments)
597 # filter out the ROMs
598 if (r.start >= rom_region.start and r.stop <= rom_region.stop):
599 add_rom_region = True
601 # filter out and save DMAR regions
602 if r.typestr.find('dmar') >= 0:
603 dmar_regions.append(r)
608 # add a region that covers all potential ROMs
610 ret.append(rom_region)
612 # newer Linux kernels will report the first page as reserved
613 # it is needed for CPU init so include it anyways
614 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
617 return ret, dmar_regions
620 def parse_pcidevices():
623 basedir = '/sys/bus/pci/devices'
624 list = input_listdir(basedir, ['*/config'])
626 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
630 # look for duplicate capability patterns
632 if d2.caps == d.caps:
633 # reused existing capability list, but record all users
634 d2.caps[0].comments.append(str(d))
635 d.caps_start = d2.caps_start
639 d.caps[0].comments.append(str(d))
640 d.caps_start = len(caps)
643 return (devices, caps)
646 def parse_kernel_cmdline():
647 line = input_readline('/proc/cmdline')
648 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
649 '([0-9a-fA-FxX]+)([KMG]?).*',
652 size = kmg_multiply(int(m.group(1), 0), m.group(2))
653 start = kmg_multiply(int(m.group(3), 0), m.group(4))
658 def alloc_mem(regions, size):
659 mem = [0x3b000000, size]
662 r.typestr == 'System RAM' and
663 r.start <= mem[0] and
664 r.stop + 1 >= mem[0] + mem[1]
667 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
668 regions.insert(regions.index(r), head_r)
669 if r.stop + 1 > mem[0] + mem[1]:
670 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
672 regions.insert(regions.index(r), tail_r)
675 for r in reversed(regions):
676 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
680 raise RuntimeError('failed to allocate memory')
684 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
687 if re.match(r'cpu[0-9]+', f):
693 f = input_open('/sys/firmware/acpi/tables/APIC', 'rb')
694 signature = f.read(4)
695 if signature != b'APIC':
696 raise RuntimeError('MADT: incorrect input file format %s' % signature)
697 (length,) = struct.unpack('<I', f.read(4))
704 (struct_type, struct_len) = struct.unpack('<BB', f.read(2))
709 (id, address, gsi_base) = struct.unpack('<BxII', f.read(10))
711 ioapics.append(IOAPIC(id, address, gsi_base))
713 f.seek(struct_len - offset, os.SEEK_CUR)
719 def parse_dmar_devscope(f):
720 (scope_type, scope_len, id, bus, dev, fn) = \
721 struct.unpack('<BBxxBBBB', f.read(8))
723 raise RuntimeError('Unsupported DMAR Device Scope Structure')
724 return (scope_type, scope_len, id, bus, dev, fn)
727 # parsing of DMAR ACPI Table
728 # see Intel VT-d Spec chapter 8
729 def parse_dmar(pcidevices, ioapics, dmar_regions):
730 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
731 signature = f.read(4)
732 if signature != b'DMAR':
733 raise RuntimeError('DMAR: incorrect input file format %s' % signature)
734 (length,) = struct.unpack('<I', f.read(4))
742 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
746 # DMA Remapping Hardware Unit Definition
748 (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
750 raise RuntimeError('We do not support multiple PCI segments')
752 raise RuntimeError('Too many DMAR units. '
753 'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
755 for r in dmar_regions:
759 raise RuntimeError('DMAR region size cannot be identified.\n'
760 'Target Linux must run with Intel IOMMU '
763 raise RuntimeError('Unexpectedly large DMAR region.')
764 units.append(IOMMUConfig({
771 d.iommu = len(units) - 1
772 offset += 16 - offset
773 while offset < struct_len:
774 (scope_type, scope_len, id, bus, dev, fn) =\
775 parse_dmar_devscope(f)
776 # PCI Endpoint Device
778 assert not (flags & 1)
780 if d.bus == bus and d.dev == dev and d.fn == fn:
781 d.iommu = len(units) - 1
784 elif scope_type == 2:
785 assert not (flags & 1)
787 if d.bus == bus and d.dev == dev and d.fn == fn:
788 (secondbus, subordinate) = \
789 PCIPCIBridge.get_2nd_busses(d)
790 for d2 in pcidevices:
792 d2.bus >= secondbus and
793 d2.bus <= subordinate
795 d2.iommu = len(units) - 1
798 elif scope_type == 3:
799 ioapic = next(chip for chip in ioapics if chip.id == id)
800 bdf = (bus << 8) | (dev << 3) | fn
803 raise RuntimeError('IOAPICs with identical BDF')
805 ioapic.iommu = len(units) - 1
808 # Reserved Memory Region Reporting Structure
810 f.seek(8 - offset, os.SEEK_CUR)
812 (base, limit) = struct.unpack('<QQ', f.read(16))
816 while offset < struct_len:
817 (scope_type, scope_len, id, bus, dev, fn) =\
818 parse_dmar_devscope(f)
820 comments.append('PCI device: %02x:%02x.%x' %
823 comments.append('DMAR parser could not decode device path')
826 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
829 f.seek(struct_len - offset, os.SEEK_CUR)
836 'PCI device %02x:%02x.%x outside the scope of an '
837 'IOMMU' % (d.bus, d.dev, d.fn))
839 return units, regions
842 def parse_ivrs(pcidevices, ioapics):
844 bus, dev, fun = (bdf >> 8) & 0xff, (bdf >> 3) & 0x1f, bdf & 0x7
845 return '%02x:%02x.%x' % (bus, dev, fun)
847 f = input_open('/sys/firmware/acpi/tables/IVRS', 'rb')
848 signature = f.read(4)
849 if signature != b'IVRS':
850 raise RuntimeError('IVRS: incorrect input file format %s' % signature)
852 (length, revision) = struct.unpack('<IB', f.read(5))
854 raise RuntimeError('IVRS: unsupported Revision %02x' % revision)
856 f.seek(48, os.SEEK_SET)
861 # BDF of devices that are permitted outside IOMMU: root complex
862 iommu_skiplist = set([0x0])
865 (block_type, block_length) = struct.unpack('<BxH', f.read(4))
866 if block_type in [0x10, 0x11]:
869 raise RuntimeError('Jailhouse doesn\'t support more than one '
870 'AMD IOMMU per PCI function.')
872 ivhd_fields = struct.unpack('<HHQHxxL', f.read(20))
873 (iommu_bdf, base_cap_ofs,
874 base_addr, pci_seg, iommu_feat) = ivhd_fields
876 length -= block_length
880 raise RuntimeError('We do not support multiple PCI segments')
883 raise RuntimeError('Too many IOMMU units. '
884 'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
888 for i, d in enumerate(pcidevices):
889 if d.bdf() == iommu_bdf:
890 # Extract MSI capability offset
893 msi_cap_ofs = c.start
894 # We must not map IOMMU to the cells
897 if msi_cap_ofs is None:
898 raise RuntimeError('AMD IOMMU lacks MSI support, and '
899 'Jailhouse doesn\'t support MSI-X yet.')
901 if (iommu_feat & (0xF << 13)) and (iommu_feat & (0x3F << 17)):
902 # Performance Counters are supported, allocate 512K
908 units.append(IOMMUConfig({
909 'base_addr': base_addr,
910 'mmio_size': mmio_size,
911 'amd_bdf': iommu_bdf,
912 'amd_base_cap': base_cap_ofs,
913 'amd_msi_cap': msi_cap_ofs,
914 # IVHD block type 0x11 has exact EFR copy but type 0x10 may
915 # overwrite what hardware reports. Set reserved bit 0 in that
916 # case to indicate that the value is in use.
917 'amd_features': (iommu_feat | 0x1) if block_type == 0x10 else 0
920 bdf_start_range = None
921 while block_length > 0:
922 (entry_type, device_id) = struct.unpack('<BHx', f.read(4))
925 if entry_type == 0x01:
928 d.iommu = len(units) - 1
929 elif entry_type == 0x02:
932 if d.bdf() == device_id:
933 d.iommu = len(units) - 1
934 elif entry_type == 0x03:
936 bdf_start_range = device_id
937 elif entry_type == 0x04:
939 if bdf_start_range is None:
942 if d.bdf() >= bdf_start_range and d.bdf() <= device_id:
943 d.iommu = len(units) - 1
944 bdf_start_range = None
945 elif entry_type == 0x42:
947 (device_id_b,) = struct.unpack('<xHx', f.read(4))
950 if d.bdf() == device_id_b:
951 d.iommu = len(units) - 1
952 elif entry_type == 0x43:
953 # Alias start of range
954 (device_id_b,) = struct.unpack('<xHx', f.read(4))
956 bdf_start_range = device_id_b
957 elif entry_type == 0x48:
959 (handle, device_id_b, variety) = struct.unpack(
962 if variety == 0x01: # IOAPIC
964 if chip.id == handle:
966 chip.iommu = len(units) - 1
968 # Reserved or ignored entries
969 if entry_type >= 0x40:
970 f.seek(4, os.SEEK_CUR)
973 elif type in [0x20, 0x21, 0x22]:
975 ivmd_fields = struct.unpack('<BBHHHxxxxxxxxQQ', f.read(32))
976 (block_type, block_flags, block_length,
977 device_id, aux_data, mem_addr, mem_len) = ivmd_fields
978 length -= block_length
981 bdf_str = format_bdf(device_id)
983 'WARNING: Jailhouse doesn\'t support configurable '
984 '(eg. read-only) device memory. Device %s may not '
985 'work properly, especially in non-root cell.' % bdf_str)
987 if block_type == 0x20:
990 elif block_type == 0x21:
992 comment = 'PCI Device: %s' % format_bdf(device_id)
993 elif block_type == 0x22:
995 comment = 'PCI Device: %s - %s' % (
996 format_bdf(device_id), format_bdf(aux_data))
999 print('WARNING: Jailhouse doesn\'t support per-device memory '
1000 'regions. The memory at 0x%x will be mapped accessible '
1001 'to all devices.' % mem_addr)
1003 regions.append(MemRegion(mem_addr, mem_len, 'ACPI IVRS', comment))
1006 'You board uses IVRS Rev. 2 feature Jailhouse doesn\'t '
1007 'support yet. Please report this to '
1008 'jailhouse-dev@googlegroups.com.')
1011 'WARNING: Skipping unknown IVRS '
1012 'block type 0x%02x' % block_type)
1014 for d in pcidevices:
1015 if d.bdf() not in iommu_skiplist and d.iommu is None:
1017 'PCI device %02x:%02x.%x outside the scope of an '
1018 'IOMMU' % (d.bus, d.dev, d.fn))
1021 return units, regions
1024 def parse_ioports():
1025 pm_timer_base = None
1026 f = input_open('/proc/ioports')
1028 if line.endswith('ACPI PM_TMR\n'):
1029 pm_timer_base = int(line.split('-')[0], 16)
1032 return pm_timer_base
1036 def __init__(self, base, end_bus):
1038 self.end_bus = end_bus
1042 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
1043 signature = f.read(4)
1044 if signature != b'MCFG':
1045 raise RuntimeError('MCFG: incorrect input file format %s' %
1047 (length,) = struct.unpack('<I', f.read(4))
1049 raise RuntimeError('Multiple MMCONFIG regions found! '
1050 'This is not supported')
1052 (base, segment, start_bus, end_bus) = \
1053 struct.unpack('<QHBB', f.read(12))
1054 if segment != 0 or start_bus != 0:
1055 raise RuntimeError('Invalid MCFG structure found')
1056 return MMConfig(base, end_bus)
1059 def get_cpu_vendor():
1061 if cpuvendor is not None:
1063 with input_open('/proc/cpuinfo', 'r') as f:
1065 if not line.strip():
1067 key, value = line.split(':')
1068 if key.strip() == 'vendor_id':
1069 cpuvendor = value.strip()
1073 if options.generate_collector:
1074 f = open(options.file, 'w')
1075 filelist = ' '.join(inputs['files'])
1076 filelist_opt = ' '.join(inputs['files_opt'])
1077 filelist_intel = ' '.join(inputs['files_intel'])
1078 filelist_amd = ' '.join(inputs['files_amd'])
1080 tmpl = Template(filename=os.path.join(options.template_dir,
1081 'jailhouse-config-collect.tmpl'))
1082 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
1083 filelist_intel=filelist_intel, filelist_amd=filelist_amd))
1087 if ((options.root is '/') and (os.geteuid() is not 0)):
1088 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
1091 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
1092 if jh_enabled == '1':
1093 print('ERROR: Jailhouse was enabled when collecting input files! '
1094 'Disable jailhouse and try again.',
1098 (pcidevices, pcicaps) = parse_pcidevices()
1100 product = [input_readline('/sys/class/dmi/id/sys_vendor',
1102 input_readline('/sys/class/dmi/id/product_name',
1106 inmatemem = kmg_multiply_str(options.mem_inmates)
1107 hvmem = [0, kmg_multiply_str(options.mem_hv)]
1109 (regions, dmar_regions) = parse_iomem(pcidevices)
1110 ourmem = parse_kernel_cmdline()
1111 total = hvmem[1] + inmatemem
1113 mmconfig = MMConfig.parse()
1115 ioapics = parse_madt()
1117 vendor = get_cpu_vendor()
1118 if vendor == 'GenuineIntel':
1119 (iommu_units, extra_memregs) = parse_dmar(pcidevices, ioapics,
1122 (iommu_units, extra_memregs) = parse_ivrs(pcidevices, ioapics)
1123 regions += extra_memregs
1125 # kernel does not have memmap region, pick one
1127 ourmem = alloc_mem(regions, total)
1128 elif (total > ourmem[1]):
1129 raise RuntimeError('Your memmap reservation is too small you need >="' +
1130 hex(total) + '". Hint: your kernel cmd line needs '
1131 '"memmap=' + hex(total) + '$' + hex(ourmem[0]) + '"')
1133 hvmem[0] = ourmem[0]
1135 inmatereg = MemRegion(ourmem[0] + hvmem[1],
1136 ourmem[0] + hvmem[1] + inmatemem - 1,
1137 'JAILHOUSE Inmate Memory')
1138 regions.append(inmatereg)
1140 cpucount = count_cpus()
1142 pm_timer_base = parse_ioports()
1145 f = open(options.file, 'w')
1146 tmpl = Template(filename=os.path.join(options.template_dir,
1147 'root-cell-config.c.tmpl'))
1151 'argstr': ' '.join(sys.argv),
1154 'pcidevices': pcidevices,
1156 'cpucount': cpucount,
1157 'irqchips': ioapics,
1158 'pm_timer_base': pm_timer_base,
1159 'mmconfig': mmconfig,
1160 'iommu_units': iommu_units
1163 f.write(tmpl.render(**kwargs))