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
379 self.comments = comments
382 return 'MemRegion: %08x-%08x : %s' % \
383 (self.start, self.stop, self.typestr)
386 # round up to full PAGE_SIZE
387 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
389 def flagstr(self, p=''):
391 self.typestr == 'System RAM' or
392 self.typestr == 'Kernel' or
393 self.typestr == 'RAM buffer' or
394 self.typestr == 'ACPI DMAR RMRR' or
395 self.typestr == 'ACPI IVRS'
397 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
398 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
400 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
404 def __init__(self, id, address, gsi_base, iommu=0, bdf=0):
406 self.address = address
407 self.gsi_base = gsi_base
412 return 'IOAPIC %d, GSI base %d' % (self.id, self.gsi_base)
414 def irqchip_id(self):
415 # encode the IOMMU number into the irqchip ID
416 return (self.iommu << 16) | self.bdf
419 class IOMemRegionTree:
420 def __init__(self, region, level):
429 s = (' ' * (self.level - 1)) + str(self.region)
430 if self.parent and self.parent.region:
431 s += ' --> ' + self.parent.region.typestr
433 for c in self.children:
437 def regions_split_by_kernel(self):
438 kernel = [x for x in self.children if
439 x.region.typestr.startswith('Kernel ')]
441 if (len(kernel) == 0):
447 kernel_start = kernel[0].region.start
448 kernel_stop = kernel[len(kernel) - 1].region.stop
450 # align this for 16M, but only if we have enough space
451 kernel_stop = (kernel_stop & ~0xFFFFFF) + 0xFFFFFF
452 if (kernel_stop > r.stop):
458 # before Kernel if any
459 if (r.start < kernel_start):
460 before_kernel = MemRegion(r.start, kernel_start - 1, s)
462 kernel_region = MemRegion(kernel_start, kernel_stop, "Kernel")
464 # after Kernel if any
465 if (r.stop > kernel_stop):
466 after_kernel = MemRegion(kernel_stop + 1, r.stop, s)
468 return [before_kernel, kernel_region, after_kernel]
471 def parse_iomem_line(line):
472 a = line.split(':', 1)
473 level = int(a[0].count(' ') / 2) + 1
474 region = a[0].split('-', 1)
476 return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
479 def parse_iomem_file():
480 root = IOMemRegionTree(None, 0)
481 f = input_open('/proc/iomem')
485 (level, r) = IOMemRegionTree.parse_iomem_line(line)
486 t = IOMemRegionTree(r, level)
487 if (t.level > lastlevel):
489 if (t.level == lastlevel):
490 t.parent = lastnode.parent
491 if (t.level < lastlevel):
493 while(t.level < p.level):
497 t.parent.children.append(t)
504 # find HPET regions in tree
506 def find_hpet_regions(tree):
509 for tree in tree.children:
513 if (s.find('HPET') >= 0):
516 # if the tree continues recurse further down ...
517 if (len(tree.children) > 0):
518 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
522 # recurse down the tree
524 def parse_iomem_tree(tree):
527 for tree in tree.children:
531 # System RAM on the first level will be added completely,
532 # if they don't contain the kernel itself, if they do,
534 if (tree.level == 1 and s == 'System RAM'):
535 regions.extend(tree.regions_split_by_kernel())
538 # blacklisted on all levels
540 (s.find('PCI MMCONFIG') >= 0) or
541 (s.find('APIC') >= 0) # covers both APIC and IOAPIC
545 # generally blacklisted, unless we find an HPET behind it
546 if (s == 'reserved'):
547 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
550 # if the tree continues recurse further down ...
551 if (len(tree.children) > 0):
552 regions.extend(IOMemRegionTree.parse_iomem_tree(tree))
555 # add all remaining leaves
561 class IOMMUConfig(object):
562 def __init__(self, props):
563 self.base_addr = props['base_addr']
564 self.mmio_size = props['mmio_size']
565 if 'amd_bdf' in props:
566 self.amd_bdf = props['amd_bdf']
567 self.amd_base_cap = props['amd_base_cap']
568 self.amd_msi_cap = props['amd_msi_cap']
569 self.amd_features = props['amd_features']
572 def is_amd_iommu(self):
573 return hasattr(self, 'amd_bdf')
576 def parse_iomem(pcidevices):
577 regions = IOMemRegionTree.parse_iomem_tree(
578 IOMemRegionTree.parse_iomem_file())
580 rom_region = MemRegion(0xc0000, 0xdffff, 'ROMs')
581 add_rom_region = False
587 # filter the list for MSI-X pages
589 if d.msix_address >= r.start and d.msix_address <= r.stop:
590 if d.msix_address > r.start:
591 head_r = MemRegion(r.start, d.msix_address - 1,
592 r.typestr, r.comments)
594 if d.msix_address + d.msix_region_size < r.stop:
595 tail_r = MemRegion(d.msix_address + d.msix_region_size,
596 r.stop, r.typestr, r.comments)
600 # filter out the ROMs
601 if (r.start >= rom_region.start and r.stop <= rom_region.stop):
602 add_rom_region = True
604 # filter out and save DMAR regions
605 if r.typestr.find('dmar') >= 0:
606 dmar_regions.append(r)
611 # add a region that covers all potential ROMs
613 ret.append(rom_region)
615 # newer Linux kernels will report the first page as reserved
616 # it is needed for CPU init so include it anyways
617 if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
620 return ret, dmar_regions
623 def parse_pcidevices():
626 basedir = '/sys/bus/pci/devices'
627 list = input_listdir(basedir, ['*/config'])
629 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
633 # look for duplicate capability patterns
635 if d2.caps == d.caps:
636 # reused existing capability list, but record all users
637 d2.caps[0].comments.append(str(d))
638 d.caps_start = d2.caps_start
642 d.caps[0].comments.append(str(d))
643 d.caps_start = len(caps)
646 return (devices, caps)
649 def parse_kernel_cmdline():
650 line = input_readline('/proc/cmdline')
651 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
652 '([0-9a-fA-FxX]+)([KMG]?).*',
655 size = kmg_multiply(int(m.group(1), 0), m.group(2))
656 start = kmg_multiply(int(m.group(3), 0), m.group(4))
661 def alloc_mem(regions, size):
662 mem = [0x3b000000, size]
665 r.typestr == 'System RAM' and
666 r.start <= mem[0] and
667 r.stop + 1 >= mem[0] + mem[1]
670 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
671 regions.insert(regions.index(r), head_r)
672 if r.stop + 1 > mem[0] + mem[1]:
673 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
675 regions.insert(regions.index(r), tail_r)
678 for r in reversed(regions):
679 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
683 raise RuntimeError('failed to allocate memory')
687 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
690 if re.match(r'cpu[0-9]+', f):
696 f = input_open('/sys/firmware/acpi/tables/APIC', 'rb')
697 signature = f.read(4)
698 if signature != b'APIC':
699 raise RuntimeError('MADT: incorrect input file format %s' % signature)
700 (length,) = struct.unpack('<I', f.read(4))
707 (struct_type, struct_len) = struct.unpack('<BB', f.read(2))
712 (id, address, gsi_base) = struct.unpack('<BxII', f.read(10))
714 ioapics.append(IOAPIC(id, address, gsi_base))
716 f.seek(struct_len - offset, os.SEEK_CUR)
722 def parse_dmar_devscope(f):
723 (scope_type, scope_len, id, bus, dev, fn) = \
724 struct.unpack('<BBxxBBBB', f.read(8))
726 raise RuntimeError('Unsupported DMAR Device Scope Structure')
727 return (scope_type, scope_len, id, bus, dev, fn)
730 # parsing of DMAR ACPI Table
731 # see Intel VT-d Spec chapter 8
732 def parse_dmar(pcidevices, ioapics, dmar_regions):
733 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
734 signature = f.read(4)
735 if signature != b'DMAR':
736 raise RuntimeError('DMAR: incorrect input file format %s' % signature)
737 (length,) = struct.unpack('<I', f.read(4))
745 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
749 # DMA Remapping Hardware Unit Definition
751 (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
753 raise RuntimeError('We do not support multiple PCI segments')
755 raise RuntimeError('Too many DMAR units. '
756 'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
758 for r in dmar_regions:
762 raise RuntimeError('DMAR region size cannot be identified.\n'
763 'Target Linux must run with Intel IOMMU '
766 raise RuntimeError('Unexpectedly large DMAR region.')
767 units.append(IOMMUConfig({
774 d.iommu = len(units) - 1
775 offset += 16 - offset
776 while offset < struct_len:
777 (scope_type, scope_len, id, bus, dev, fn) =\
778 parse_dmar_devscope(f)
779 # PCI Endpoint Device
781 assert not (flags & 1)
783 if d.bus == bus and d.dev == dev and d.fn == fn:
784 d.iommu = len(units) - 1
787 elif scope_type == 2:
788 assert not (flags & 1)
790 if d.bus == bus and d.dev == dev and d.fn == fn:
791 (secondbus, subordinate) = \
792 PCIPCIBridge.get_2nd_busses(d)
793 for d2 in pcidevices:
795 d2.bus >= secondbus and
796 d2.bus <= subordinate
798 d2.iommu = len(units) - 1
801 elif scope_type == 3:
802 ioapic = next(chip for chip in ioapics if chip.id == id)
803 bdf = (bus << 8) | (dev << 3) | fn
806 raise RuntimeError('IOAPICs with identical BDF')
808 ioapic.iommu = len(units) - 1
811 # Reserved Memory Region Reporting Structure
813 f.seek(8 - offset, os.SEEK_CUR)
815 (base, limit) = struct.unpack('<QQ', f.read(16))
819 while offset < struct_len:
820 (scope_type, scope_len, id, bus, dev, fn) =\
821 parse_dmar_devscope(f)
823 comments.append('PCI device: %02x:%02x.%x' %
826 comments.append('DMAR parser could not decode device path')
829 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
832 f.seek(struct_len - offset, os.SEEK_CUR)
839 'PCI device %02x:%02x.%x outside the scope of an '
840 'IOMMU' % (d.bus, d.dev, d.fn))
842 return units, regions
845 def parse_ivrs(pcidevices, ioapics):
847 bus, dev, fun = (bdf >> 8) & 0xff, (bdf >> 3) & 0x1f, bdf & 0x7
848 return '%02x:%02x.%x' % (bus, dev, fun)
850 f = input_open('/sys/firmware/acpi/tables/IVRS', 'rb')
851 signature = f.read(4)
852 if signature != b'IVRS':
853 raise RuntimeError('IVRS: incorrect input file format %s' % signature)
855 (length, revision) = struct.unpack('<IB', f.read(5))
857 raise RuntimeError('IVRS: unsupported Revision %02x' % revision)
859 f.seek(48, os.SEEK_SET)
864 # BDF of devices that are permitted outside IOMMU: root complex
865 iommu_skiplist = set([0x0])
868 (block_type, block_length) = struct.unpack('<BxH', f.read(4))
869 if block_type in [0x10, 0x11]:
872 raise RuntimeError('Jailhouse doesn\'t support more than one '
873 'AMD IOMMU per PCI function.')
875 ivhd_fields = struct.unpack('<HHQHxxL', f.read(20))
876 (iommu_bdf, base_cap_ofs,
877 base_addr, pci_seg, iommu_feat) = ivhd_fields
879 length -= block_length
883 raise RuntimeError('We do not support multiple PCI segments')
886 raise RuntimeError('Too many IOMMU units. '
887 'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
891 for i, d in enumerate(pcidevices):
892 if d.bdf() == iommu_bdf:
893 # Extract MSI capability offset
896 msi_cap_ofs = c.start
897 # We must not map IOMMU to the cells
900 if msi_cap_ofs is None:
901 raise RuntimeError('AMD IOMMU lacks MSI support, and '
902 'Jailhouse doesn\'t support MSI-X yet.')
904 if (iommu_feat & (0xF << 13)) and (iommu_feat & (0x3F << 17)):
905 # Performance Counters are supported, allocate 512K
911 units.append(IOMMUConfig({
912 'base_addr': base_addr,
913 'mmio_size': mmio_size,
914 'amd_bdf': iommu_bdf,
915 'amd_base_cap': base_cap_ofs,
916 'amd_msi_cap': msi_cap_ofs,
917 # IVHD block type 0x11 has exact EFR copy but type 0x10 may
918 # overwrite what hardware reports. Set reserved bit 0 in that
919 # case to indicate that the value is in use.
920 'amd_features': (iommu_feat | 0x1) if block_type == 0x10 else 0
923 bdf_start_range = None
924 while block_length > 0:
925 (entry_type, device_id) = struct.unpack('<BHx', f.read(4))
928 if entry_type == 0x01:
931 d.iommu = len(units) - 1
932 elif entry_type == 0x02:
935 if d.bdf() == device_id:
936 d.iommu = len(units) - 1
937 elif entry_type == 0x03:
939 bdf_start_range = device_id
940 elif entry_type == 0x04:
942 if bdf_start_range is None:
945 if d.bdf() >= bdf_start_range and d.bdf() <= device_id:
946 d.iommu = len(units) - 1
947 bdf_start_range = None
948 elif entry_type == 0x42:
950 (device_id_b,) = struct.unpack('<xHx', f.read(4))
953 if d.bdf() == device_id_b:
954 d.iommu = len(units) - 1
955 elif entry_type == 0x43:
956 # Alias start of range
957 (device_id_b,) = struct.unpack('<xHx', f.read(4))
959 bdf_start_range = device_id_b
960 elif entry_type == 0x48:
962 (handle, device_id_b, variety) = struct.unpack(
965 if variety == 0x01: # IOAPIC
967 if chip.id == handle:
969 chip.iommu = len(units) - 1
971 # Reserved or ignored entries
972 if entry_type >= 0x40:
973 f.seek(4, os.SEEK_CUR)
976 elif type in [0x20, 0x21, 0x22]:
978 ivmd_fields = struct.unpack('<BBHHHxxxxxxxxQQ', f.read(32))
979 (block_type, block_flags, block_length,
980 device_id, aux_data, mem_addr, mem_len) = ivmd_fields
981 length -= block_length
984 bdf_str = format_bdf(device_id)
986 'WARNING: Jailhouse doesn\'t support configurable '
987 '(eg. read-only) device memory. Device %s may not '
988 'work properly, especially in non-root cell.' % bdf_str)
990 if block_type == 0x20:
993 elif block_type == 0x21:
995 comment = 'PCI Device: %s' % format_bdf(device_id)
996 elif block_type == 0x22:
998 comment = 'PCI Device: %s - %s' % (
999 format_bdf(device_id), format_bdf(aux_data))
1002 print('WARNING: Jailhouse doesn\'t support per-device memory '
1003 'regions. The memory at 0x%x will be mapped accessible '
1004 'to all devices.' % mem_addr)
1006 regions.append(MemRegion(mem_addr, mem_len, 'ACPI IVRS', comment))
1009 'You board uses IVRS Rev. 2 feature Jailhouse doesn\'t '
1010 'support yet. Please report this to '
1011 'jailhouse-dev@googlegroups.com.')
1014 'WARNING: Skipping unknown IVRS '
1015 'block type 0x%02x' % block_type)
1017 for d in pcidevices:
1018 if d.bdf() not in iommu_skiplist and d.iommu is None:
1020 'PCI device %02x:%02x.%x outside the scope of an '
1021 'IOMMU' % (d.bus, d.dev, d.fn))
1024 return units, regions
1027 def parse_ioports():
1028 pm_timer_base = None
1029 f = input_open('/proc/ioports')
1031 if line.endswith('ACPI PM_TMR\n'):
1032 pm_timer_base = int(line.split('-')[0], 16)
1035 return pm_timer_base
1039 def __init__(self, base, end_bus):
1041 self.end_bus = end_bus
1045 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
1046 signature = f.read(4)
1047 if signature != b'MCFG':
1048 raise RuntimeError('MCFG: incorrect input file format %s' %
1050 (length,) = struct.unpack('<I', f.read(4))
1052 raise RuntimeError('Multiple MMCONFIG regions found! '
1053 'This is not supported')
1055 (base, segment, start_bus, end_bus) = \
1056 struct.unpack('<QHBB', f.read(12))
1057 if segment != 0 or start_bus != 0:
1058 raise RuntimeError('Invalid MCFG structure found')
1059 return MMConfig(base, end_bus)
1062 def get_cpu_vendor():
1064 if cpuvendor is not None:
1066 with input_open('/proc/cpuinfo', 'r') as f:
1068 if not line.strip():
1070 key, value = line.split(':')
1071 if key.strip() == 'vendor_id':
1072 cpuvendor = value.strip()
1076 if options.generate_collector:
1077 f = open(options.file, 'w')
1078 filelist = ' '.join(inputs['files'])
1079 filelist_opt = ' '.join(inputs['files_opt'])
1080 filelist_intel = ' '.join(inputs['files_intel'])
1081 filelist_amd = ' '.join(inputs['files_amd'])
1083 tmpl = Template(filename=os.path.join(options.template_dir,
1084 'jailhouse-config-collect.tmpl'))
1085 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
1086 filelist_intel=filelist_intel, filelist_amd=filelist_amd))
1090 if ((options.root is '/') and (os.geteuid() is not 0)):
1091 print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
1094 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
1095 if jh_enabled == '1':
1096 print('ERROR: Jailhouse was enabled when collecting input files! '
1097 'Disable jailhouse and try again.',
1101 (pcidevices, pcicaps) = parse_pcidevices()
1103 product = [input_readline('/sys/class/dmi/id/sys_vendor',
1105 input_readline('/sys/class/dmi/id/product_name',
1109 inmatemem = kmg_multiply_str(options.mem_inmates)
1110 hvmem = [0, kmg_multiply_str(options.mem_hv)]
1112 (regions, dmar_regions) = parse_iomem(pcidevices)
1113 ourmem = parse_kernel_cmdline()
1114 total = hvmem[1] + inmatemem
1116 mmconfig = MMConfig.parse()
1118 ioapics = parse_madt()
1120 vendor = get_cpu_vendor()
1121 if vendor == 'GenuineIntel':
1122 (iommu_units, extra_memregs) = parse_dmar(pcidevices, ioapics,
1125 (iommu_units, extra_memregs) = parse_ivrs(pcidevices, ioapics)
1126 regions += extra_memregs
1128 # kernel does not have memmap region, pick one
1130 ourmem = alloc_mem(regions, total)
1131 elif (total > ourmem[1]):
1132 raise RuntimeError('Your memmap reservation is too small you need >="' +
1133 hex(total) + '". Hint: your kernel cmd line needs '
1134 '"memmap=' + hex(total) + '$' + hex(ourmem[0]) + '"')
1136 hvmem[0] = ourmem[0]
1138 inmatereg = MemRegion(ourmem[0] + hvmem[1],
1139 ourmem[0] + hvmem[1] + inmatemem - 1,
1140 'JAILHOUSE Inmate Memory')
1141 regions.append(inmatereg)
1143 cpucount = count_cpus()
1145 pm_timer_base = parse_ioports()
1148 f = open(options.file, 'w')
1149 tmpl = Template(filename=os.path.join(options.template_dir,
1150 'root-cell-config.c.tmpl'))
1154 'argstr': ' '.join(sys.argv),
1157 'pcidevices': pcidevices,
1159 'cpucount': cpucount,
1160 'irqchips': ioapics,
1161 'pm_timer_base': pm_timer_base,
1162 'mmconfig': mmconfig,
1163 'iommu_units': iommu_units
1166 f.write(tmpl.render(**kwargs))