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