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