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