]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
tools: Rewrap jailhouse help output
[jailhouse.git] / tools / jailhouse-config-create
1 #!/usr/bin/env python
2 #
3 # Jailhouse, a Linux-based partitioning hypervisor
4 #
5 # Copyright (c) Siemens AG, 2014
6 #
7 # This work is licensed under the terms of the GNU GPL, version 2.  See
8 # the COPYING file in the top-level directory.
9 #
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.
14
15 from __future__ import print_function
16 import sys
17 import os
18 import re
19 import argparse
20 import struct
21 import fnmatch
22 from mako.template import Template
23
24 datadir = None
25
26 if datadir:
27     template_default_dir = datadir + "/jailhouse"
28 else:
29     template_default_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
30
31 cpuvendor = None
32
33 # pretend to be part of the jailhouse tool
34 sys.argv[0] = sys.argv[0].replace('-', ' ')
35
36 parser = argparse.ArgumentParser()
37 parser.add_argument('-g', '--generate-collector',
38                     help='generate a script to collect input files on '
39                          'a remote machine',
40                     action='store_true')
41 parser.add_argument('-r', '--root',
42                     help='gather information in ROOT/, the default is "/" '
43                          'which means creating a config for localhost',
44                     default='/',
45                     action='store',
46                     type=str)
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,
51                     action='store',
52                     type=str)
53
54 memargs = [['--mem-inmates', '2M', 'inmate'],
55            ['--mem-hv', '64M', 'hypervisor']]
56
57 for entry in memargs:
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]"',
62                         default=entry[1],
63                         action='store',
64                         type=str)
65
66 parser.add_argument('file', metavar='FILE',
67                     help='name of file to write out',
68                     type=str)
69
70 options = parser.parse_args()
71
72 inputs = {
73     'files': set(),
74     'files_opt': set(),
75     'files_intel': set(),
76     'files_amd': set()
77 }
78
79 # required files
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')
89 # optional files
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')
96
97
98 def kmg_multiply(value, kmg):
99     if (kmg == 'K' or kmg == 'k'):
100         return 1024 * value
101     if (kmg == 'M' or kmg == 'm'):
102         return 1024**2 * value
103     if (kmg == 'G' or kmg == 'g'):
104         return 1024**3 * value
105     return value
106
107
108 def kmg_multiply_str(str):
109     m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
110     if m is not None:
111         return kmg_multiply(int(m.group(1)), m.group(2))
112     raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
113
114
115 def check_input_listed(name, optional=False):
116     set = inputs['files_opt']
117     if optional is False:
118         set = inputs['files']
119         global cpuvendor
120         if cpuvendor == 'GenuineIntel':
121             set = set.union(inputs['files_intel'])
122         elif cpuvendor == 'AuthenticAMD':
123             set = set.union(inputs['files_amd'])
124
125     for file in set:
126         if fnmatch.fnmatch(name, file):
127             return True
128     raise RuntimeError('"' + name + '" is not a listed input file')
129
130
131 def input_open(name, mode='r', optional=False):
132     check_input_listed(name, optional)
133     try:
134         f = open(options.root + name, mode)
135     except Exception as e:
136         if optional:
137             return open("/dev/null", mode)
138         raise e
139     return f
140
141
142 def input_readline(name, optional=False):
143     f = input_open(name, optional=optional)
144     line = f.readline()
145     f.close()
146     return line
147
148
149 def input_listdir(dir, wildcards):
150     for w in wildcards:
151         check_input_listed(os.path.join(dir, w))
152     dirs = os.listdir(options.root + dir)
153     dirs.sort()
154     return dirs
155
156
157 class PCIBARs:
158     IORESOURCE_IO = 0x00000100
159     IORESOURCE_MEM = 0x00000200
160     IORESOURCE_MEM_64 = 0x00100000
161
162     def __init__(self, dir):
163         self.mask = []
164         f = input_open(os.path.join(dir, 'resource'), 'r')
165         for n in range(6):
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)
174                     mask >>= 32
175                     n += 1
176             else:
177                 mask = 0
178             self.mask.append(mask & 0xffffffff)
179         f.close()
180
181
182 class PCICapability:
183     def __init__(self, id, start, len, flags, content, msix_address):
184         self.id = id
185         self.start = start
186         self.len = len
187         self.flags = flags
188         self.content = content
189         self.msix_address = msix_address
190         self.comments = []
191
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
195
196     RD = '0'
197     RW = 'JAILHOUSE_PCICAPS_WRITE'
198
199     JAILHOUSE_PCI_EXT_CAP = 0x8000
200
201     @staticmethod
202     def parse_pcicaps(dir):
203         caps = []
204         has_extended_caps = False
205         f = input_open(os.path.join(dir, 'config'), 'rb')
206         f.seek(0x06)
207         (status,) = struct.unpack('<H', f.read(2))
208         # capability list supported?
209         if (status & (1 << 4)) == 0:
210             f.close()
211             return caps
212         # walk capability list
213         f.seek(0x34)
214         (next,) = struct.unpack('B', f.read(1))
215         while next != 0:
216             cap = next
217             msix_address = 0
218             f.seek(cap)
219             (id, next) = struct.unpack('<BB', f.read(2))
220             if id == 0x01:  # Power Management
221                 # this cap can be handed out completely
222                 len = 8
223                 flags = PCICapability.RW
224             elif id == 0x05:  # MSI
225                 # access will be moderated by hypervisor
226                 len = 10
227                 (msgctl,) = struct.unpack('<H', f.read(2))
228                 if (msgctl & (1 << 7)) != 0:  # 64-bit support
229                     len += 4
230                 if (msgctl & (1 << 8)) != 0:  # per-vector masking support
231                     len += 10
232                 flags = PCICapability.RW
233             elif id == 0x10:  # Express
234                 len = 20
235                 (cap_reg,) = struct.unpack('<H', f.read(2))
236                 if (cap_reg & 0xf) >= 2:  # v2 capability
237                     len = 44
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
243                 len = 12
244                 (table,) = struct.unpack('<xxI', f.read(6))
245                 f.seek(0x10 + (table & 7) * 4)
246                 (bar,) = struct.unpack('<I', f.read(4))
247                 if (bar & 0x3) != 0:
248                     raise RuntimeError('Invalid MSI-X BAR found')
249                 if (bar & 0x4) != 0:
250                     bar |= struct.unpack('<I', f.read(4))[0] << 32
251                 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
252                 flags = PCICapability.RW
253             else:
254                 # unknown/unhandled cap, mark its existence
255                 len = 2
256                 flags = PCICapability.RD
257             f.seek(cap + 2)
258             content = f.read(len - 2)
259             caps.append(PCICapability(id, cap, len, flags, content,
260                                       msix_address))
261
262         if has_extended_caps:
263             # walk extended capability list
264             next = 0x100
265             while next != 0:
266                 cap = next
267                 f.seek(cap)
268                 (id, version_next) = struct.unpack('<HH', f.read(4))
269                 next = version_next >> 4
270                 if id == 0xffff:
271                     break
272                 elif id == 0x0010:  # SR-IOV
273                     len = 64
274                     # access side effects still need to be analyzed
275                     flags = PCICapability.RD
276                 else:
277                     if (id & PCICapability.JAILHOUSE_PCI_EXT_CAP) != 0:
278                         print('WARNING: Ignoring unsupported PCI Express '
279                               'Extended Capability ID %x' % id)
280                         continue
281                     # unknown/unhandled cap, mark its existence
282                     len = 4
283                     flags = PCICapability.RD
284                 f.seek(cap + 4)
285                 content = f.read(len - 4)
286                 id |= PCICapability.JAILHOUSE_PCI_EXT_CAP
287                 caps.append(PCICapability(id, cap, len, flags, content, 0))
288
289         f.close()
290         return caps
291
292
293 class PCIDevice:
294     def __init__(self, type, domain, bus, dev, fn, bars, caps, path):
295         self.type = type
296         self.iommu = None
297         self.domain = domain
298         self.bus = bus
299         self.dev = dev
300         self.fn = fn
301         self.bars = bars
302         self.caps = caps
303         self.path = path
304         self.caps_start = 0
305         self.num_caps = len(caps)
306         self.num_msi_vectors = 0
307         self.msi_64bits = 0
308         self.num_msix_vectors = 0
309         self.msix_region_size = 0
310         self.msix_address = 0
311         for c in caps:
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
317                 else:  # MSI-X
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
323                     else:
324                         print('WARNING: Ignoring invalid MSI-X configuration'
325                               ' of device %02x:%02x.%x' % (bus, dev, fn))
326
327     def __str__(self):
328         return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
329
330     def bdf(self):
331         return self.bus << 8 | self.dev << 3 | self.fn
332
333     @staticmethod
334     def parse_pcidevice_sysfsdir(basedir, dir):
335         dpath = os.path.join(basedir, dir)
336         f = input_open(os.path.join(dpath, 'config'), 'rb')
337         f.seek(0x0A)
338         (classcode,) = struct.unpack('<H', f.read(2))
339         f.close()
340         if classcode == 0x0604:
341             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
342         else:
343             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
344         a = dir.split(':')
345         domain = int(a[0], 16)
346         bus = int(a[1], 16)
347         df = a[2].split('.')
348         bars = PCIBARs(dpath)
349         caps = PCICapability.parse_pcicaps(dpath)
350         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
351                          bars, caps, dpath)
352
353
354 class PCIPCIBridge(PCIDevice):
355     @staticmethod
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')
359         f.seek(0x19)
360         (secondbus, subordinate) = struct.unpack('<BB', f.read(2))
361         f.close()
362         return (secondbus, subordinate)
363
364
365 class MemRegion:
366     def __init__(self, start, stop, typestr, comments=None):
367         self.start = start
368         self.stop = stop
369         self.typestr = typestr
370         if comments is None:
371             self.comments = []
372         else:
373             self.comments = comments
374
375     def __str__(self):
376         return 'MemRegion: %08x-%08x : %s' % \
377             (self.start, self.stop, self.typestr)
378
379     def size(self):
380         # round up to full PAGE_SIZE
381         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
382
383     def flagstr(self, p=''):
384         if (
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'
390         ):
391             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
392             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
393             return s
394         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
395
396
397 class IOAPIC:
398     def __init__(self, id, address, gsi_base, iommu=0, bdf=0):
399         self.id = id
400         self.address = address
401         self.gsi_base = gsi_base
402         self.iommu = iommu
403         self.bdf = bdf
404
405     def __str__(self):
406         return 'IOAPIC %d, GSI base %d' % (self.id, self.gsi_base)
407
408     def irqchip_id(self):
409         # encode the IOMMU number into the irqchip ID
410         return (self.iommu << 16) | self.bdf
411
412
413 class IOMemRegionTree:
414     def __init__(self, region, level):
415         self.region = region
416         self.level = level
417         self.parent = None
418         self.children = []
419
420     def __str__(self):
421         s = ''
422         if (self.region):
423             s = (' ' * (self.level - 1)) + str(self.region)
424             if self.parent and self.parent.region:
425                 s += ' --> ' + self.parent.region.typestr
426             s += '\n'
427         for c in self.children:
428             s += str(c)
429         return s
430
431     def regions_split_by_kernel(self):
432         kernel = [x for x in self.children if
433                   x.region.typestr.startswith('Kernel ')]
434
435         if (len(kernel) == 0):
436             return [self.region]
437
438         r = self.region
439         s = r.typestr
440
441         kernel_start = kernel[0].region.start
442         kernel_stop = kernel[len(kernel) - 1].region.stop
443
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):
447             kernel_stop = r.stop
448
449         before_kernel = None
450         after_kernel = None
451
452         # before Kernel if any
453         if (r.start < kernel_start):
454             before_kernel = MemRegion(r.start, kernel_start - 1, s)
455
456         kernel_region = MemRegion(kernel_start, kernel_stop, "Kernel")
457
458         # after Kernel if any
459         if (r.stop > kernel_stop):
460             after_kernel = MemRegion(kernel_stop + 1, r.stop, s)
461
462         return [before_kernel, kernel_region, after_kernel]
463
464     @staticmethod
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)
469         a[1] = a[1].strip()
470         return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
471
472     @staticmethod
473     def parse_iomem_file():
474         root = IOMemRegionTree(None, 0)
475         f = input_open('/proc/iomem')
476         lastlevel = 0
477         lastnode = root
478         for line in f:
479             (level, r) = IOMemRegionTree.parse_iomem_line(line)
480             t = IOMemRegionTree(r, level)
481             if (t.level > lastlevel):
482                 t.parent = lastnode
483             if (t.level == lastlevel):
484                 t.parent = lastnode.parent
485             if (t.level < lastlevel):
486                 p = lastnode.parent
487                 while(t.level < p.level):
488                     p = p.parent
489                 t.parent = p.parent
490
491             t.parent.children.append(t)
492             lastnode = t
493             lastlevel = t.level
494         f.close()
495
496         return root
497
498     # find HPET regions in tree
499     @staticmethod
500     def find_hpet_regions(tree):
501         regions = []
502
503         for tree in tree.children:
504             r = tree.region
505             s = r.typestr
506
507             if (s.find('HPET') >= 0):
508                 regions.append(r)
509
510             # if the tree continues recurse further down ...
511             if (len(tree.children) > 0):
512                 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
513
514         return regions
515
516     # recurse down the tree
517     @staticmethod
518     def parse_iomem_tree(tree):
519         regions = []
520
521         for tree in tree.children:
522             r = tree.region
523             s = r.typestr
524
525             # System RAM on the first level will be added completely,
526             # if they don't contain the kernel itself, if they do,
527             # we split them
528             if (tree.level == 1 and s == 'System RAM'):
529                 regions.extend(tree.regions_split_by_kernel())
530                 continue
531
532             # blacklisted on all levels
533             if (
534                 (s.find('PCI MMCONFIG') >= 0) or
535                 (s.find('APIC') >= 0) or  # covers both APIC and IOAPIC
536                 (s.find('dmar') >= 0)
537             ):
538                 continue
539
540             # generally blacklisted, unless we find an HPET behind it
541             if (s == 'reserved'):
542                 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
543                 continue
544
545             # if the tree continues recurse further down ...
546             if (len(tree.children) > 0):
547                 regions.extend(IOMemRegionTree.parse_iomem_tree(tree))
548                 continue
549
550             # add all remaining leaves
551             regions.append(r)
552
553         return regions
554
555
556 def parse_iomem(pcidevices):
557     regions = IOMemRegionTree.parse_iomem_tree(
558         IOMemRegionTree.parse_iomem_file())
559
560     rom_region = MemRegion(0xc0000, 0xdffff, 'ROMs')
561     add_rom_region = False
562
563     ret = []
564     for r in regions:
565         append_r = True
566         # filter the list for MSI-X pages
567         for d in pcidevices:
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)
572                     ret.append(head_r)
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)
576                     ret.append(tail_r)
577                 append_r = False
578                 break
579         # filter out the ROMs
580         if (r.start >= rom_region.start and r.stop <= rom_region.stop):
581             add_rom_region = True
582             append_r = False
583         if append_r:
584             ret.append(r)
585
586     # add a region that covers all potential ROMs
587     if add_rom_region:
588         ret.append(rom_region)
589
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):
593         ret[0].start = 0
594
595     return ret
596
597
598 def parse_pcidevices():
599     devices = []
600     caps = []
601     basedir = '/sys/bus/pci/devices'
602     list = input_listdir(basedir, ['*/config'])
603     for dir in list:
604         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
605         if d is not None:
606             if len(d.caps) > 0:
607                 duplicate = False
608                 # look for duplicate capability patterns
609                 for d2 in devices:
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
614                         duplicate = True
615                         break
616                 if not duplicate:
617                     d.caps[0].comments.append(str(d))
618                     d.caps_start = len(caps)
619                     caps.extend(d.caps)
620             devices.append(d)
621     return (devices, caps)
622
623
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]?).*',
628                  line)
629     if m is not None:
630         size = kmg_multiply(int(m.group(1), 0), m.group(2))
631         start = kmg_multiply(int(m.group(3), 0), m.group(4))
632         return [start, size]
633     return None
634
635
636 def alloc_mem(regions, size):
637     mem = [0x3b000000, size]
638     for r in regions:
639         if (
640             r.typestr == 'System RAM' and
641             r.start <= mem[0] and
642             r.stop + 1 >= mem[0] + mem[1]
643         ):
644             if r.start < mem[0]:
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,
649                                    r.comments)
650                 regions.insert(regions.index(r), tail_r)
651             regions.remove(r)
652             return mem
653     for r in reversed(regions):
654         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
655             mem[0] = r.start
656             r.start += mem[1]
657             return mem
658     raise RuntimeError('failed to allocate memory')
659
660
661 def count_cpus():
662     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
663     count = 0
664     for f in list:
665         if re.match(r'cpu[0-9]+', f):
666             count += 1
667     return count
668
669
670 def parse_madt():
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))
676     f.seek(44)
677     length -= 44
678     ioapics = []
679
680     while length > 0:
681         offset = 0
682         (struct_type, struct_len) = struct.unpack('<BB', f.read(2))
683         offset += 2
684         length -= struct_len
685
686         if struct_type == 1:
687             (id, address, gsi_base) = struct.unpack('<BxII', f.read(10))
688             offset += 10
689             ioapics.append(IOAPIC(id, address, gsi_base))
690
691         f.seek(struct_len - offset, os.SEEK_CUR)
692
693     f.close()
694     return ioapics
695
696
697 def parse_dmar_devscope(f):
698     (scope_type, scope_len, id, bus, dev, fn) = \
699         struct.unpack('<BBxxBBBB', f.read(8))
700     if scope_len != 8:
701         raise RuntimeError('Unsupported DMAR Device Scope Structure')
702     return (scope_type, scope_len, id, bus, dev, fn)
703
704
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))
713     f.seek(48)
714     length -= 48
715     units = []
716     regions = []
717
718     while length > 0:
719         offset = 0
720         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
721         offset += 4
722         length -= struct_len
723
724         # DMA Remapping Hardware Unit Definition
725         if struct_type == 0:
726             (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
727             if segment != 0:
728                 raise RuntimeError('We do not support multiple PCI segments')
729             if len(units) >= 8:
730                 raise RuntimeError('Too many DMAR units. '
731                                    'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
732             units.append(base)
733             if flags & 1:
734                 for d in pcidevices:
735                     if d.iommu is None:
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
742                 if scope_type == 1:
743                     assert not (flags & 1)
744                     for d in pcidevices:
745                         if d.bus == bus and d.dev == dev and d.fn == fn:
746                             d.iommu = len(units) - 1
747                             break
748                 # PCI Sub-hierarchy
749                 elif scope_type == 2:
750                     assert not (flags & 1)
751                     for d in pcidevices:
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:
756                                 if (
757                                     d2.bus >= secondbus and
758                                     d2.bus <= subordinate
759                                 ):
760                                     d2.iommu = len(units) - 1
761                             break
762                 # IOAPIC
763                 elif scope_type == 3:
764                     ioapic = next(chip for chip in ioapics if chip.id == id)
765                     bdf = (bus << 8) | (dev << 3) | fn
766                     for chip in ioapics:
767                         if chip.bdf == bdf:
768                             raise RuntimeError('IOAPICs with identical BDF')
769                     ioapic.bdf = bdf
770                     ioapic.iommu = len(units) - 1
771                 offset += scope_len
772
773         # Reserved Memory Region Reporting Structure
774         if struct_type == 1:
775             f.seek(8 - offset, os.SEEK_CUR)
776             offset += 8 - offset
777             (base, limit) = struct.unpack('<QQ', f.read(16))
778             offset += 16
779
780             comments = []
781             while offset < struct_len:
782                 (scope_type, scope_len, id, bus, dev, fn) =\
783                     parse_dmar_devscope(f)
784                 if scope_type == 1:
785                     comments.append('PCI device: %02x:%02x.%x' %
786                                     (bus, dev, fn))
787                 else:
788                     comments.append('DMAR parser could not decode device path')
789                 offset += scope_len
790
791             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
792             regions.append(reg)
793
794         f.seek(struct_len - offset, os.SEEK_CUR)
795
796     f.close()
797
798     for d in pcidevices:
799         if d.iommu is None:
800             raise RuntimeError(
801                 'PCI device %02x:%02x.%x outside the scope of an '
802                 'IOMMU' % (d.bus, d.dev, d.fn))
803
804     return units, regions
805
806
807 def parse_ivrs(pcidevices, ioapics):
808     def format_bdf(bdf):
809         bus, dev, fun = (bdf >> 8) & 0xff, (bdf >> 3) & 0x1f, bdf & 0x7
810         return '%02x:%02x.%x' % (bus, dev, fun)
811
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)
816
817     (length, revision) = struct.unpack('<IB', f.read(5))
818     if revision > 2:
819         raise RuntimeError('IVRS: unsupported Revision %02x' % revision)
820
821     f.seek(48, os.SEEK_SET)
822     length -= 48
823
824     units = []
825     regions = []
826     # BDF of devices that are permitted outside IOMMU: root complex
827     iommu_skiplist = set([0x0])
828     while length > 0:
829         (block_type, block_length) = struct.unpack('<BxH', f.read(4))
830         if block_type in [0x10, 0x11]:
831             # IVHD block
832             (iommu_id, base_addr, pci_seg) = \
833                 struct.unpack('<HxxQH', f.read(14))
834             length -= block_length
835             block_length -= 18
836
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
841
842             if pci_seg != 0:
843                 raise RuntimeError('We do not support multiple PCI segments')
844
845             if len(units) > 8:
846                 raise RuntimeError('Too many IOMMU units. '
847                                    'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
848
849             # We shouldn't map IOMMU to the cells
850             for i, d in enumerate(pcidevices):
851                 if d.bdf() == iommu_id:
852                     del pcidevices[i]
853
854             units.append(base_addr)
855
856             bdf_start_range = None
857             while block_length > 0:
858                 (entry_type, device_id) = struct.unpack('<BHx', f.read(4))
859                 block_length -= 4
860
861                 if entry_type == 0x01:
862                     # All
863                     for d in pcidevices:
864                         d.iommu = len(units) - 1
865                 elif entry_type == 0x02:
866                     # Select
867                     for d in pcidevices:
868                         if d.bdf() == device_id:
869                             d.iommu = len(units) - 1
870                 elif entry_type == 0x03:
871                     # Start of range
872                     bdf_start_range = device_id
873                 elif entry_type == 0x04:
874                     # End of range
875                     if bdf_start_range is None:
876                         continue
877                     for d in pcidevices:
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:
882                     # Alias select
883                     (device_id_b,) = struct.unpack('<xHx', f.read(4))
884                     block_length -= 4
885                     for d in pcidevices:
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))
891                     block_length -= 4
892                     bdf_start_range = device_id_b
893                 elif entry_type == 0x48:
894                     # Special device
895                     (handle, device_id_b, variety) = struct.unpack(
896                         '<BHB', f.read(4))
897                     block_length -= 4
898                     if variety == 0x01:  # IOAPIC
899                         for chip in ioapics:
900                             if chip.id == handle:
901                                 chip.bdf = device_id
902                                 chip.iommu = len(units) - 1
903                 else:
904                     # Reserved or ignored entries
905                     if entry_type >= 0x40:
906                         f.seek(4, os.SEEK_CUR)
907                         block_length -= 4
908
909         elif type in [0x20, 0x21, 0x22]:
910             # IVMD block
911             (block_type, block_flags, block_length,
912              device_id, aux_data, mem_addr, mem_len) = struct.unpack(
913                  '<BBHHHxxxxxxxxQQ')
914             length -= block_length
915
916             if int(block_flags):
917                 bdf_str = format_bdf(device_id)
918                 print(
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)
922
923             if block_type == 0x20:
924                 # All devices
925                 comment = None
926             elif block_type == 0x21:
927                 # Selected device
928                 comment = 'PCI Device: %s' % format_bdf(device_id)
929             elif block_type == 0x22:
930                 # Device range
931                 comment = 'PCI Device: %s - %s' % (
932                     format_bdf(device_id), format_bdf(aux_data))
933
934             if comment:
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)
938
939             regions.append(MemRegion(mem_addr, mem_len, 'ACPI IVRS', comment))
940         elif type == 0x40:
941             raise RuntimeError(
942                 'You board uses IVRS Rev. 2 feature Jailhouse doesn\'t '
943                 'support yet. Please report this to '
944                 'jailhouse-dev@googlegroups.com.')
945         else:
946             print(
947                 'WARNING: Skipping unknown IVRS '
948                 'block type 0x%02x' % block_type)
949
950         for d in pcidevices:
951             if d.bdf() not in iommu_skiplist and d.iommu is None:
952                 raise RuntimeError(
953                     'PCI device %02x:%02x.%x outside the scope of an '
954                     'IOMMU' % (d.bus, d.dev, d.fn))
955
956         f.close()
957         return units, regions
958
959
960 def parse_ioports():
961     pm_timer_base = None
962     f = input_open('/proc/ioports')
963     for line in f:
964         if line.endswith('ACPI PM_TMR\n'):
965             pm_timer_base = int(line.split('-')[0], 16)
966             break
967     f.close()
968     return pm_timer_base
969
970
971 class MMConfig:
972     def __init__(self, base, end_bus):
973         self.base = base
974         self.end_bus = end_bus
975
976     @staticmethod
977     def parse():
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' %
982                                signature)
983         (length,) = struct.unpack('<I', f.read(4))
984         if length > 60:
985             raise RuntimeError('Multiple MMCONFIG regions found! '
986                                'This is not supported')
987         f.seek(44)
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)
993
994
995 def get_cpu_vendor():
996     global cpuvendor
997     if cpuvendor is not None:
998         return cpuvendor
999     with input_open('/proc/cpuinfo', 'r') as f:
1000         for line in f:
1001             if not line.strip():
1002                 continue
1003             key, value = line.split(':')
1004             if key.strip() == 'vendor_id':
1005                 cpuvendor = value.strip()
1006                 return cpuvendor
1007
1008
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'])
1015
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))
1020     f.close()
1021     sys.exit(0)
1022
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)
1025     sys.exit(1)
1026
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.',
1031           file=sys.stderr)
1032     sys.exit(1)
1033
1034 (pcidevices, pcicaps) = parse_pcidevices()
1035
1036 product = [input_readline('/sys/class/dmi/id/sys_vendor',
1037                           True).rstrip(),
1038            input_readline('/sys/class/dmi/id/product_name',
1039                           True).rstrip()
1040            ]
1041
1042 inmatemem = kmg_multiply_str(options.mem_inmates)
1043 hvmem = [0, kmg_multiply_str(options.mem_hv)]
1044
1045 regions = parse_iomem(pcidevices)
1046 ourmem = parse_kernel_cmdline()
1047 total = hvmem[1] + inmatemem
1048
1049 mmconfig = MMConfig.parse()
1050
1051 ioapics = parse_madt()
1052
1053 vendor = get_cpu_vendor()
1054 if vendor == 'GenuineIntel':
1055     (iommu_units, extra_memregs) = parse_dmar(pcidevices, ioapics)
1056 else:
1057     (iommu_units, extra_memregs) = parse_ivrs(pcidevices, ioapics)
1058 regions += extra_memregs
1059
1060 # kernel does not have memmap region, pick one
1061 if ourmem is None:
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]) + '"')
1067
1068 hvmem[0] = ourmem[0]
1069
1070 inmatereg = MemRegion(ourmem[0] + hvmem[1],
1071                       ourmem[0] + hvmem[1] + inmatemem - 1,
1072                       'JAILHOUSE Inmate Memory')
1073 regions.append(inmatereg)
1074
1075 cpucount = count_cpus()
1076
1077 pm_timer_base = parse_ioports()
1078
1079
1080 f = open(options.file, 'w')
1081 tmpl = Template(filename=os.path.join(options.template_dir,
1082                                       'root-cell-config.c.tmpl'))
1083 kwargs = {
1084     'regions': regions,
1085     'ourmem': ourmem,
1086     'argstr': ' '.join(sys.argv),
1087     'hvmem': hvmem,
1088     'product': product,
1089     'pcidevices': pcidevices,
1090     'pcicaps': pcicaps,
1091     'cpucount': cpucount,
1092     'irqchips': ioapics,
1093     'pm_timer_base': pm_timer_base,
1094     'mmconfig': mmconfig,
1095     'iommu_units': iommu_units
1096 }
1097
1098 f.write(tmpl.render(**kwargs))
1099
1100 f.close()