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