]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
0b41cf9015be082a1cbf9871262d1352f27cebd7
[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 class PCICapability:
182     def __init__(self, id, start, len, flags, content, msix_address):
183         self.id = id
184         self.start = start
185         self.len = len
186         self.flags = flags
187         self.content = content
188         self.msix_address = msix_address
189         self.comments = []
190
191     def __eq__(self, other):
192         return self.id == other.id and self.start == other.start and \
193             self.len == other.len and self.flags == other.flags
194
195     RD = '0'
196     RW = 'JAILHOUSE_PCICAPS_WRITE'
197
198     @staticmethod
199     def parse_pcicaps(dir):
200         caps = []
201         f = input_open(os.path.join(dir, 'config'), 'rb')
202         f.seek(0x06)
203         (status,) = struct.unpack('<H', f.read(2))
204         # capability list supported?
205         if (status & (1 << 4)) == 0:
206             f.close()
207             return caps
208         # walk capability list
209         f.seek(0x34)
210         (next,) = struct.unpack('B', f.read(1))
211         while next != 0:
212             cap = next
213             msix_address = 0
214             f.seek(cap)
215             (id, next) = struct.unpack('<BB', f.read(2))
216             if id == 0x01:  # Power Management
217                 # this cap can be handed out completely
218                 len = 8
219                 flags = PCICapability.RW
220             elif id == 0x05:  # MSI
221                 # access will be moderated by hypervisor
222                 len = 10
223                 (msgctl,) = struct.unpack('<H', f.read(2))
224                 if (msgctl & (1 << 7)) != 0:  # 64-bit support
225                     len += 4
226                 if (msgctl & (1 << 8)) != 0:  # per-vector masking support
227                     len += 10
228                 flags = PCICapability.RW
229             elif id == 0x11:  # MSI-X
230                 # access will be moderated by hypervisor
231                 len = 12
232                 (table,) = struct.unpack('<xxI', f.read(6))
233                 f.seek(0x10 + (table & 7) * 4)
234                 (bar,) = struct.unpack('<I', f.read(4))
235                 if (bar & 0x3) != 0:
236                     raise RuntimeError('Invalid MSI-X BAR found')
237                 if (bar & 0x4) != 0:
238                     bar |= struct.unpack('<I', f.read(4))[0] << 32
239                 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
240                 flags = PCICapability.RW
241             else:
242                 # unknown/unhandled cap, mark its existence
243                 len = 2
244                 flags = PCICapability.RD
245             f.seek(cap + 2)
246             content = f.read(len - 2)
247             caps.append(PCICapability(id, cap, len, flags, content,
248                                       msix_address))
249         f.close()
250         return caps
251
252
253 class PCIDevice:
254     def __init__(self, type, domain, bus, dev, fn, bars, caps, path):
255         self.type = type
256         self.iommu = None
257         self.domain = domain
258         self.bus = bus
259         self.dev = dev
260         self.fn = fn
261         self.bars = bars
262         self.caps = caps
263         self.path = path
264         self.caps_start = 0
265         self.num_caps = len(caps)
266         self.num_msi_vectors = 0
267         self.msi_64bits = 0
268         self.num_msix_vectors = 0
269         self.msix_region_size = 0
270         self.msix_address = 0
271         for c in caps:
272             if c.id in (0x05, 0x11):
273                 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
274                 if c.id == 0x05:  # MSI
275                     self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
276                     self.msi_64bits = (msg_ctrl >> 7) & 1
277                 else:  # MSI-X
278                     if c.msix_address != 0:
279                         vectors = (msg_ctrl & 0x7ff) + 1
280                         self.num_msix_vectors = vectors
281                         self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
282                         self.msix_address = c.msix_address
283                     else:
284                         print('WARNING: Ignoring invalid MSI-X configuration'
285                               ' of device %02x:%02x.%x' % (bus, dev, fn))
286
287     def __str__(self):
288         return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
289
290     def bdf(self):
291         return self.bus << 8 | self.dev << 3 | self.fn
292
293     @staticmethod
294     def parse_pcidevice_sysfsdir(basedir, dir):
295         dpath = os.path.join(basedir, dir)
296         f = input_open(os.path.join(dpath, 'config'), 'rb')
297         f.seek(0x0A)
298         (classcode,) = struct.unpack('<H', f.read(2))
299         f.close()
300         if classcode == 0x0604:
301             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
302         else:
303             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
304         a = dir.split(':')
305         domain = int(a[0], 16)
306         bus = int(a[1], 16)
307         df = a[2].split('.')
308         bars = PCIBARs(dpath)
309         caps = PCICapability.parse_pcicaps(dpath)
310         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
311                          bars, caps, dpath)
312
313
314 class PCIPCIBridge(PCIDevice):
315     @staticmethod
316     def get_2nd_busses(dev):
317         assert dev.type == 'JAILHOUSE_PCI_TYPE_BRIDGE'
318         f = input_open(os.path.join(dev.path, 'config'), 'rb')
319         f.seek(0x19)
320         (secondbus, subordinate) = struct.unpack('<BB', f.read(2))
321         f.close()
322         return (secondbus, subordinate)
323
324
325 class MemRegion:
326     def __init__(self, start, stop, typestr, comments=None):
327         self.start = start
328         self.stop = stop
329         self.typestr = typestr
330         if comments is None:
331             self.comments = []
332         else:
333             self.comments = comments
334
335     def __str__(self):
336         return 'MemRegion: %08x-%08x : %s' % \
337             (self.start, self.stop, self.typestr)
338
339     def size(self):
340         # round up to full PAGE_SIZE
341         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
342
343     def flagstr(self, p=''):
344         if (
345             self.typestr == 'System RAM' or
346             self.typestr == 'Kernel' or
347             self.typestr == 'RAM buffer' or
348             self.typestr == 'ACPI DMAR RMRR' or
349             self.typestr == 'ACPI IVRS'
350         ):
351             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
352             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
353             return s
354         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
355
356
357 class IOAPIC:
358     def __init__(self, id, address, gsi_base, iommu=0, bdf=0):
359         self.id = id
360         self.address = address
361         self.gsi_base = gsi_base
362         self.iommu = iommu
363         self.bdf = bdf
364
365     def __str__(self):
366         return 'IOAPIC %d, GSI base %d' % (self.id, self.gsi_base)
367
368     def irqchip_id(self):
369         # encode the IOMMU number into the irqchip ID
370         return (self.iommu << 16) | self.bdf
371
372
373 class IOMemRegionTree:
374     def __init__(self, region, level):
375         self.region = region
376         self.level = level
377         self.parent = None
378         self.children = []
379
380     def __str__(self):
381         s = ''
382         if (self.region):
383             s = (' ' * (self.level - 1)) + str(self.region)
384             if self.parent and self.parent.region:
385                 s += ' --> ' + self.parent.region.typestr
386             s += '\n'
387         for c in self.children:
388             s += str(c)
389         return s
390
391     def regions_split_by_kernel(self):
392         kernel = [x for x in self.children if
393                   x.region.typestr.startswith('Kernel ')]
394
395         if (len(kernel) == 0):
396             return [self.region]
397
398         r = self.region
399         s = r.typestr
400
401         kernel_start = kernel[0].region.start
402         kernel_stop = kernel[len(kernel) - 1].region.stop
403
404         # align this for 16M, but only if we have enough space
405         kernel_stop = (kernel_stop & ~0xFFFFFF) + 0xFFFFFF
406         if (kernel_stop > r.stop):
407             kernel_stop = r.stop
408
409         before_kernel = None
410         after_kernel = None
411
412         # before Kernel if any
413         if (r.start < kernel_start):
414             before_kernel = MemRegion(r.start, kernel_start - 1, s)
415
416         kernel_region = MemRegion(kernel_start, kernel_stop, "Kernel")
417
418         # after Kernel if any
419         if (r.stop > kernel_stop):
420             after_kernel = MemRegion(kernel_stop + 1, r.stop, s)
421
422         return [before_kernel, kernel_region, after_kernel]
423
424     @staticmethod
425     def parse_iomem_line(line):
426         a = line.split(':', 1)
427         level = int(a[0].count(' ') / 2) + 1
428         region = a[0].split('-', 1)
429         a[1] = a[1].strip()
430         return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
431
432     @staticmethod
433     def parse_iomem_file():
434         root = IOMemRegionTree(None, 0)
435         f = input_open('/proc/iomem')
436         lastlevel = 0
437         lastnode = root
438         for line in f:
439             (level, r) = IOMemRegionTree.parse_iomem_line(line)
440             t = IOMemRegionTree(r, level)
441             if (t.level > lastlevel):
442                 t.parent = lastnode
443             if (t.level == lastlevel):
444                 t.parent = lastnode.parent
445             if (t.level < lastlevel):
446                 p = lastnode.parent
447                 while(t.level < p.level):
448                     p = p.parent
449                 t.parent = p.parent
450
451             t.parent.children.append(t)
452             lastnode = t
453             lastlevel = t.level
454         f.close()
455
456         return root
457
458     # find HPET regions in tree
459     @staticmethod
460     def find_hpet_regions(tree):
461         regions = []
462
463         for tree in tree.children:
464             r = tree.region
465             s = r.typestr
466
467             if (s.find('HPET') >= 0):
468                 regions.append(r)
469
470             # if the tree continues recurse further down ...
471             if (len(tree.children) > 0):
472                 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
473
474         return regions
475
476     # recurse down the tree
477     @staticmethod
478     def parse_iomem_tree(tree):
479         regions = []
480
481         for tree in tree.children:
482             r = tree.region
483             s = r.typestr
484
485             # System RAM on the first level will be added completely,
486             # if they don't contain the kernel itself, if they do,
487             # we split them
488             if (tree.level == 1 and s == 'System RAM'):
489                 regions.extend(tree.regions_split_by_kernel())
490                 continue
491
492             # blacklisted on all levels
493             if (
494                 (s.find('PCI MMCONFIG') >= 0) or
495                 (s.find('APIC') >= 0) or  # covers both APIC and IOAPIC
496                 (s.find('dmar') >= 0)
497             ):
498                 continue
499
500             # generally blacklisted, unless we find an HPET behind it
501             if (s == 'reserved'):
502                 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
503                 continue
504
505             # if the tree continues recurse further down ...
506             if (len(tree.children) > 0):
507                 regions.extend(IOMemRegionTree.parse_iomem_tree(tree))
508                 continue
509
510             # add all remaining leaves
511             regions.append(r)
512
513         return regions
514
515
516 def parse_iomem(pcidevices):
517     regions = IOMemRegionTree.parse_iomem_tree(
518         IOMemRegionTree.parse_iomem_file())
519
520     rom_region = MemRegion(0xc0000, 0xdffff, 'ROMs')
521     add_rom_region = False
522
523     ret = []
524     for r in regions:
525         append_r = True
526         # filter the list for MSI-X pages
527         for d in pcidevices:
528             if d.msix_address >= r.start and d.msix_address <= r.stop:
529                 if d.msix_address > r.start:
530                     head_r = MemRegion(r.start, d.msix_address - 1,
531                                        r.typestr, r.comments)
532                     ret.append(head_r)
533                 if d.msix_address + d.msix_region_size < r.stop:
534                     tail_r = MemRegion(d.msix_address + d.msix_region_size,
535                                        r.stop, r.typestr, r.comments)
536                     ret.append(tail_r)
537                 append_r = False
538                 break
539         # filter out the ROMs
540         if (r.start >= rom_region.start and r.stop <= rom_region.stop):
541             add_rom_region = True
542             append_r = False
543         if append_r:
544             ret.append(r)
545
546     # add a region that covers all potential ROMs
547     if add_rom_region:
548         ret.append(rom_region)
549
550     # newer Linux kernels will report the first page as reserved
551     # it is needed for CPU init so include it anyways
552     if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
553         ret[0].start = 0
554
555     return ret
556
557
558 def parse_pcidevices():
559     devices = []
560     caps = []
561     basedir = '/sys/bus/pci/devices'
562     list = input_listdir(basedir, ['*/config'])
563     for dir in list:
564         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
565         if d is not None:
566             if len(d.caps) > 0:
567                 duplicate = False
568                 # look for duplicate capability patterns
569                 for d2 in devices:
570                     if d2.caps == d.caps:
571                         # reused existing capability list, but record all users
572                         d2.caps[0].comments.append(str(d))
573                         d.caps_start = d2.caps_start
574                         duplicate = True
575                         break
576                 if not duplicate:
577                     d.caps[0].comments.append(str(d))
578                     d.caps_start = len(caps)
579                     caps.extend(d.caps)
580             devices.append(d)
581     return (devices, caps)
582
583
584 def parse_kernel_cmdline():
585     line = input_readline('/proc/cmdline')
586     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
587                  '([0-9a-fA-FxX]+)([KMG]?).*',
588                  line)
589     if m is not None:
590         size = kmg_multiply(int(m.group(1), 0), m.group(2))
591         start = kmg_multiply(int(m.group(3), 0), m.group(4))
592         return [start, size]
593     return None
594
595
596 def alloc_mem(regions, size):
597     mem = [0x3b000000, size]
598     for r in regions:
599         if (
600             r.typestr == 'System RAM' and
601             r.start <= mem[0] and
602             r.stop + 1 >= mem[0] + mem[1]
603         ):
604             if r.start < mem[0]:
605                 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
606                 regions.insert(regions.index(r), head_r)
607             if r.stop + 1 > mem[0] + mem[1]:
608                 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
609                                    r.comments)
610                 regions.insert(regions.index(r), tail_r)
611             regions.remove(r)
612             return mem
613     for r in reversed(regions):
614         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
615             mem[0] = r.start
616             r.start += mem[1]
617             return mem
618     raise RuntimeError('failed to allocate memory')
619
620
621 def count_cpus():
622     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
623     count = 0
624     for f in list:
625         if re.match(r'cpu[0-9]+', f):
626             count += 1
627     return count
628
629
630 def parse_madt():
631     f = input_open('/sys/firmware/acpi/tables/APIC', 'rb')
632     signature = f.read(4)
633     if signature != b'APIC':
634         raise RuntimeError('MADT: incorrect input file format %s' % signature)
635     (length,) = struct.unpack('<I', f.read(4))
636     f.seek(44)
637     length -= 44
638     ioapics = []
639
640     while length > 0:
641         offset = 0
642         (struct_type, struct_len) = struct.unpack('<BB', f.read(2))
643         offset += 2
644         length -= struct_len
645
646         if struct_type == 1:
647             (id, address, gsi_base) = struct.unpack('<BxII', f.read(10))
648             offset += 10
649             ioapics.append(IOAPIC(id, address, gsi_base))
650
651         f.seek(struct_len - offset, os.SEEK_CUR)
652
653     f.close()
654     return ioapics
655
656
657 def parse_dmar_devscope(f):
658     (scope_type, scope_len, id, bus, dev, fn) = \
659         struct.unpack('<BBxxBBBB', f.read(8))
660     if scope_len != 8:
661         raise RuntimeError('Unsupported DMAR Device Scope Structure')
662     return (scope_type, scope_len, id, bus, dev, fn)
663
664
665 # parsing of DMAR ACPI Table
666 # see Intel VT-d Spec chapter 8
667 def parse_dmar(pcidevices, ioapics):
668     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
669     signature = f.read(4)
670     if signature != b'DMAR':
671         raise RuntimeError('DMAR: incorrect input file format %s' % signature)
672     (length,) = struct.unpack('<I', f.read(4))
673     f.seek(48)
674     length -= 48
675     units = []
676     regions = []
677
678     while length > 0:
679         offset = 0
680         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
681         offset += 4
682         length -= struct_len
683
684         # DMA Remapping Hardware Unit Definition
685         if struct_type == 0:
686             (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
687             if segment != 0:
688                 raise RuntimeError('We do not support multiple PCI segments')
689             if len(units) >= 8:
690                 raise RuntimeError('Too many DMAR units. '
691                                    'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
692             units.append(base)
693             if flags & 1:
694                 for d in pcidevices:
695                     if d.iommu is None:
696                         d.iommu = len(units) - 1
697             offset += 16 - offset
698             while offset < struct_len:
699                 (scope_type, scope_len, id, bus, dev, fn) =\
700                     parse_dmar_devscope(f)
701                 # PCI Endpoint Device
702                 if scope_type == 1:
703                     assert not (flags & 1)
704                     for d in pcidevices:
705                         if d.bus == bus and d.dev == dev and d.fn == fn:
706                             d.iommu = len(units) - 1
707                             break
708                 # PCI Sub-hierarchy
709                 elif scope_type == 2:
710                     assert not (flags & 1)
711                     for d in pcidevices:
712                         if d.bus == bus and d.dev == dev and d.fn == fn:
713                             (secondbus, subordinate) = \
714                                 PCIPCIBridge.get_2nd_busses(d)
715                             for d2 in pcidevices:
716                                 if (
717                                     d2.bus >= secondbus and
718                                     d2.bus <= subordinate
719                                 ):
720                                     d2.iommu = len(units) - 1
721                             break
722                 # IOAPIC
723                 elif scope_type == 3:
724                     ioapic = next(chip for chip in ioapics if chip.id == id)
725                     bdf = (bus << 8) | (dev << 3) | fn
726                     for chip in ioapics:
727                         if chip.bdf == bdf:
728                             raise RuntimeError('IOAPICs with identical BDF')
729                     ioapic.bdf = bdf
730                     ioapic.iommu = len(units) - 1
731                 offset += scope_len
732
733         # Reserved Memory Region Reporting Structure
734         if struct_type == 1:
735             f.seek(8 - offset, os.SEEK_CUR)
736             offset += 8 - offset
737             (base, limit) = struct.unpack('<QQ', f.read(16))
738             offset += 16
739
740             comments = []
741             while offset < struct_len:
742                 (scope_type, scope_len, id, bus, dev, fn) =\
743                     parse_dmar_devscope(f)
744                 if scope_type == 1:
745                     comments.append('PCI device: %02x:%02x.%x' %
746                                     (bus, dev, fn))
747                 else:
748                     comments.append('DMAR parser could not decode device path')
749                 offset += scope_len
750
751             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
752             regions.append(reg)
753
754         f.seek(struct_len - offset, os.SEEK_CUR)
755
756     f.close()
757
758     for d in pcidevices:
759         if d.iommu is None:
760             raise RuntimeError(
761                 'PCI device %02x:%02x.%x outside the scope of an '
762                 'IOMMU' % (d.bus, d.dev, d.fn))
763
764     return units, regions
765
766
767 def parse_ivrs(pcidevices, ioapics):
768     def format_bdf(bdf):
769         bus, dev, fun = (bdf >> 8) & 0xff, (bdf >> 3) & 0x1f, bdf & 0x7
770         return '%02x:%02x.%x' % (bus, dev, fun)
771
772     f = input_open('/sys/firmware/acpi/tables/IVRS', 'rb')
773     signature = f.read(4)
774     if signature != b'IVRS':
775         raise RuntimeError('IVRS: incorrect input file format %s' % signature)
776
777     (length, revision) = struct.unpack('<IB', f.read(5))
778     if revision > 2:
779         raise RuntimeError('IVRS: unsupported Revision %02x' % revision)
780
781     f.seek(48, os.SEEK_SET)
782     length -= 48
783
784     units = []
785     regions = []
786     # BDF of devices that are permitted outside IOMMU: root complex
787     iommu_skiplist = set([0x0])
788     while length > 0:
789         (block_type, block_length) = struct.unpack('<BxH', f.read(4))
790         if block_type in [0x10, 0x11]:
791             # IVHD block
792             (iommu_id, base_addr, pci_seg) = \
793                 struct.unpack('<HxxQH', f.read(14))
794             length -= block_length
795             block_length -= 18
796
797             # IOMMU EFR image and reserved area
798             skip_bytes = 6 if block_type == 0x10 else 22
799             f.seek(skip_bytes, os.SEEK_CUR)
800             block_length -= skip_bytes
801
802             if pci_seg != 0:
803                 raise RuntimeError('We do not support multiple PCI segments')
804
805             if len(units) > 8:
806                 raise RuntimeError('Too many IOMMU units. '
807                                    'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
808
809             # We shouldn't map IOMMU to the cells
810             for i, d in enumerate(pcidevices):
811                 if d.bdf() == iommu_id:
812                     del pcidevices[i]
813
814             units.append(base_addr)
815
816             bdf_start_range = None
817             while block_length > 0:
818                 (entry_type, device_id) = struct.unpack('<BHx', f.read(4))
819                 block_length -= 4
820
821                 if entry_type == 0x01:
822                     # All
823                     for d in pcidevices:
824                         d.iommu = len(units) - 1
825                 elif entry_type == 0x02:
826                     # Select
827                     for d in pcidevices:
828                         if d.bdf() == device_id:
829                             d.iommu = len(units) - 1
830                 elif entry_type == 0x03:
831                     # Start of range
832                     bdf_start_range = device_id
833                 elif entry_type == 0x04:
834                     # End of range
835                     if bdf_start_range is None:
836                         continue
837                     for d in pcidevices:
838                         if d.bdf() >= bdf_start_range and d.bdf() <= device_id:
839                             d.iommu = len(units) - 1
840                     bdf_start_range = None
841                 elif entry_type == 0x42:
842                     # Alias select
843                     (device_id_b,) = struct.unpack('<xHx', f.read(4))
844                     block_length -= 4
845                     for d in pcidevices:
846                         if d.bdf() == device_id_b:
847                             d.iommu = len(units) - 1
848                 elif entry_type == 0x43:
849                     # Alias start of range
850                     (device_id_b,) = struct.unpack('<xHx', f.read(4))
851                     block_length -= 4
852                     bdf_start_range = device_id_b
853                 elif entry_type == 0x48:
854                     # Special device
855                     (handle, device_id_b, variety) = struct.unpack(
856                         '<BHB', f.read(4))
857                     block_length -= 4
858                     if variety == 0x01:  # IOAPIC
859                         for chip in ioapics:
860                             if chip.id == handle:
861                                 chip.bdf = device_id
862                                 chip.iommu = len(units) - 1
863                 else:
864                     # Reserved or ignored entries
865                     if entry_type >= 0x40:
866                         f.seek(4, os.SEEK_CUR)
867                         block_length -= 4
868
869         elif type in [0x20, 0x21, 0x22]:
870             # IVMD block
871             (block_type, block_flags, block_length,
872              device_id, aux_data, mem_addr, mem_len) = struct.unpack(
873                  '<BBHHHxxxxxxxxQQ')
874             length -= block_length
875
876             if int(block_flags):
877                 bdf_str = format_bdf(device_id)
878                 print(
879                     'WARNING: Jailhouse doesn\'t support configurable '
880                     '(eg. read-only) device memory. Device %s may not '
881                     'work properly, especially in non-root cell.' % bdf_str)
882
883             if block_type == 0x20:
884                 # All devices
885                 comment = None
886             elif block_type == 0x21:
887                 # Selected device
888                 comment = 'PCI Device: %s' % format_bdf(device_id)
889             elif block_type == 0x22:
890                 # Device range
891                 comment = 'PCI Device: %s - %s' % (
892                     format_bdf(device_id), format_bdf(aux_data))
893
894             if comment:
895                 print('WARNING: Jailhouse doesn\'t support per-device memory '
896                       'regions. The memory at 0x%x will be mapped accessible '
897                       'to all devices.' % mem_addr)
898
899             regions.append(MemRegion(mem_addr, mem_len, 'ACPI IVRS', comment))
900         elif type == 0x40:
901             raise RuntimeError(
902                 'You board uses IVRS Rev. 2 feature Jailhouse doesn\'t '
903                 'support yet. Please report this to '
904                 'jailhouse-dev@googlegroups.com.')
905         else:
906             print(
907                 'WARNING: Skipping unknown IVRS '
908                 'block type 0x%02x' % block_type)
909
910         for d in pcidevices:
911             if d.bdf() not in iommu_skiplist and d.iommu is None:
912                 raise RuntimeError(
913                     'PCI device %02x:%02x.%x outside the scope of an '
914                     'IOMMU' % (d.bus, d.dev, d.fn))
915
916         f.close()
917         return units, regions
918
919
920 def parse_ioports():
921     pm_timer_base = None
922     f = input_open('/proc/ioports')
923     for line in f:
924         if line.endswith('ACPI PM_TMR\n'):
925             pm_timer_base = int(line.split('-')[0], 16)
926             break
927     f.close()
928     return pm_timer_base
929
930
931 class MMConfig:
932     def __init__(self, base, end_bus):
933         self.base = base
934         self.end_bus = end_bus
935
936     @staticmethod
937     def parse():
938         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
939         signature = f.read(4)
940         if signature != b'MCFG':
941             raise RuntimeError('MCFG: incorrect input file format %s' %
942                                signature)
943         (length,) = struct.unpack('<I', f.read(4))
944         if length > 60:
945             raise RuntimeError('Multiple MMCONFIG regions found! '
946                                'This is not supported')
947         f.seek(44)
948         (base, segment, start_bus, end_bus) = \
949             struct.unpack('<QHBB', f.read(12))
950         if segment != 0 or start_bus != 0:
951             raise RuntimeError('Invalid MCFG structure found')
952         return MMConfig(base, end_bus)
953
954
955 def get_cpu_vendor():
956     global cpuvendor
957     if cpuvendor is not None:
958         return cpuvendor
959     with input_open('/proc/cpuinfo', 'r') as f:
960         for line in f:
961             if not line.strip():
962                 continue
963             key, value = line.split(':')
964             if key.strip() == 'vendor_id':
965                 cpuvendor = value.strip()
966                 return cpuvendor
967
968
969 if options.generate_collector:
970     f = open(options.file, 'w')
971     filelist = ' '.join(inputs['files'])
972     filelist_opt = ' '.join(inputs['files_opt'])
973     filelist_intel = ' '.join(inputs['files_intel'])
974     filelist_amd = ' '.join(inputs['files_amd'])
975
976     tmpl = Template(filename=os.path.join(options.template_dir,
977                                           'jailhouse-config-collect.tmpl'))
978     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
979             filelist_intel=filelist_intel, filelist_amd=filelist_amd))
980     f.close()
981     sys.exit(0)
982
983 if ((options.root is '/') and (os.geteuid() is not 0)):
984     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
985     sys.exit(1)
986
987 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
988 if jh_enabled == '1':
989     print('ERROR: Jailhouse was enabled when collecting input files! '
990           'Disable jailhouse and try again.',
991           file=sys.stderr)
992     sys.exit(1)
993
994 (pcidevices, pcicaps) = parse_pcidevices()
995
996 product = [input_readline('/sys/class/dmi/id/sys_vendor',
997                           True).rstrip(),
998            input_readline('/sys/class/dmi/id/product_name',
999                           True).rstrip()
1000            ]
1001
1002 inmatemem = kmg_multiply_str(options.mem_inmates)
1003 hvmem = [0, kmg_multiply_str(options.mem_hv)]
1004
1005 regions = parse_iomem(pcidevices)
1006 ourmem = parse_kernel_cmdline()
1007 total = hvmem[1] + inmatemem
1008
1009 mmconfig = MMConfig.parse()
1010
1011 ioapics = parse_madt()
1012
1013 vendor = get_cpu_vendor()
1014 if vendor == 'GenuineIntel':
1015     (iommu_units, extra_memregs) = parse_dmar(pcidevices, ioapics)
1016 else:
1017     (iommu_units, extra_memregs) = parse_ivrs(pcidevices, ioapics)
1018 regions += extra_memregs
1019
1020 # kernel does not have memmap region, pick one
1021 if ourmem is None:
1022     ourmem = alloc_mem(regions, total)
1023 elif (total > ourmem[1]):
1024     raise RuntimeError('Your memmap reservation is too small you need >="' +
1025                        hex(total) + '"')
1026
1027 hvmem[0] = ourmem[0]
1028
1029 inmatereg = MemRegion(ourmem[0] + hvmem[1],
1030                       ourmem[0] + hvmem[1] + inmatemem - 1,
1031                       'JAILHOUSE Inmate Memory')
1032 regions.append(inmatereg)
1033
1034 cpucount = count_cpus()
1035
1036 pm_timer_base = parse_ioports()
1037
1038
1039 f = open(options.file, 'w')
1040 tmpl = Template(filename=os.path.join(options.template_dir,
1041                                       'root-cell-config.c.tmpl'))
1042 kwargs = {
1043     'regions': regions,
1044     'ourmem': ourmem,
1045     'argstr': ' '.join(sys.argv),
1046     'hvmem': hvmem,
1047     'product': product,
1048     'pcidevices': pcidevices,
1049     'pcicaps': pcicaps,
1050     'cpucount': cpucount,
1051     'irqchips': ioapics,
1052     'pm_timer_base': pm_timer_base,
1053     'mmconfig': mmconfig,
1054     'iommu_units': iommu_units
1055 }
1056
1057 f.write(tmpl.render(**kwargs))
1058
1059 f.close()