]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
tools: config-create: Do not enter infinite over disabled PCI devices
[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         (vendor_device,) = struct.unpack('<I', f.read(4))
344         if vendor_device == 0xffffffff:
345             print('WARNING: Ignoring apparently disabled PCI device %s' % dir)
346             return None
347         f.seek(0x0A)
348         (classcode,) = struct.unpack('<H', f.read(2))
349         f.close()
350         if classcode == 0x0604:
351             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
352         else:
353             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
354         a = dir.split(':')
355         domain = int(a[0], 16)
356         bus = int(a[1], 16)
357         df = a[2].split('.')
358         bars = PCIBARs(dpath)
359         caps = PCICapability.parse_pcicaps(dpath)
360         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
361                          bars, caps, dpath)
362
363
364 class PCIPCIBridge(PCIDevice):
365     @staticmethod
366     def get_2nd_busses(dev):
367         assert dev.type == 'JAILHOUSE_PCI_TYPE_BRIDGE'
368         f = input_open(os.path.join(dev.path, 'config'), 'rb')
369         f.seek(0x19)
370         (secondbus, subordinate) = struct.unpack('<BB', f.read(2))
371         f.close()
372         return (secondbus, subordinate)
373
374
375 class MemRegion:
376     def __init__(self, start, stop, typestr, comments=None):
377         self.start = start
378         self.stop = stop
379         self.typestr = typestr
380         self.comments = comments or []
381
382     def __str__(self):
383         return 'MemRegion: %08x-%08x : %s' % \
384             (self.start, self.stop, self.typestr)
385
386     def size(self):
387         # round up to full PAGE_SIZE
388         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
389
390     def flagstr(self, p=''):
391         if (
392             self.typestr == 'System RAM' or
393             self.typestr == 'Kernel' or
394             self.typestr == 'RAM buffer' or
395             self.typestr == 'ACPI DMAR RMRR' or
396             self.typestr == 'ACPI IVRS'
397         ):
398             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
399             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
400             return s
401         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
402
403
404 class IOAPIC:
405     def __init__(self, id, address, gsi_base, iommu=0, bdf=0):
406         self.id = id
407         self.address = address
408         self.gsi_base = gsi_base
409         self.iommu = iommu
410         self.bdf = bdf
411
412     def __str__(self):
413         return 'IOAPIC %d, GSI base %d' % (self.id, self.gsi_base)
414
415     def irqchip_id(self):
416         # encode the IOMMU number into the irqchip ID
417         return (self.iommu << 16) | self.bdf
418
419
420 class IOMemRegionTree:
421     def __init__(self, region, level):
422         self.region = region
423         self.level = level
424         self.parent = None
425         self.children = []
426
427     def __str__(self):
428         s = ''
429         if (self.region):
430             s = (' ' * (self.level - 1)) + str(self.region)
431             if self.parent and self.parent.region:
432                 s += ' --> ' + self.parent.region.typestr
433             s += '\n'
434         for c in self.children:
435             s += str(c)
436         return s
437
438     def regions_split_by_kernel(self):
439         kernel = [x for x in self.children if
440                   x.region.typestr.startswith('Kernel ')]
441
442         if (len(kernel) == 0):
443             return [self.region]
444
445         r = self.region
446         s = r.typestr
447
448         kernel_start = kernel[0].region.start
449         kernel_stop = kernel[len(kernel) - 1].region.stop
450
451         # align this for 16M, but only if we have enough space
452         kernel_stop = (kernel_stop & ~0xFFFFFF) + 0xFFFFFF
453         if (kernel_stop > r.stop):
454             kernel_stop = r.stop
455
456         before_kernel = None
457         after_kernel = None
458
459         # before Kernel if any
460         if (r.start < kernel_start):
461             before_kernel = MemRegion(r.start, kernel_start - 1, s)
462
463         kernel_region = MemRegion(kernel_start, kernel_stop, "Kernel")
464
465         # after Kernel if any
466         if (r.stop > kernel_stop):
467             after_kernel = MemRegion(kernel_stop + 1, r.stop, s)
468
469         return [before_kernel, kernel_region, after_kernel]
470
471     @staticmethod
472     def parse_iomem_line(line):
473         a = line.split(':', 1)
474         level = int(a[0].count(' ') / 2) + 1
475         region = a[0].split('-', 1)
476         a[1] = a[1].strip()
477         return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
478
479     @staticmethod
480     def parse_iomem_file():
481         root = IOMemRegionTree(None, 0)
482         f = input_open('/proc/iomem')
483         lastlevel = 0
484         lastnode = root
485         for line in f:
486             (level, r) = IOMemRegionTree.parse_iomem_line(line)
487             t = IOMemRegionTree(r, level)
488             if (t.level > lastlevel):
489                 t.parent = lastnode
490             if (t.level == lastlevel):
491                 t.parent = lastnode.parent
492             if (t.level < lastlevel):
493                 p = lastnode.parent
494                 while(t.level < p.level):
495                     p = p.parent
496                 t.parent = p.parent
497
498             t.parent.children.append(t)
499             lastnode = t
500             lastlevel = t.level
501         f.close()
502
503         return root
504
505     # find HPET regions in tree
506     @staticmethod
507     def find_hpet_regions(tree):
508         regions = []
509
510         for tree in tree.children:
511             r = tree.region
512             s = r.typestr
513
514             if (s.find('HPET') >= 0):
515                 regions.append(r)
516
517             # if the tree continues recurse further down ...
518             if (len(tree.children) > 0):
519                 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
520
521         return regions
522
523     # recurse down the tree
524     @staticmethod
525     def parse_iomem_tree(tree):
526         regions = []
527
528         for tree in tree.children:
529             r = tree.region
530             s = r.typestr
531
532             # System RAM on the first level will be added completely,
533             # if they don't contain the kernel itself, if they do,
534             # we split them
535             if (tree.level == 1 and s == 'System RAM'):
536                 regions.extend(tree.regions_split_by_kernel())
537                 continue
538
539             # blacklisted on all levels
540             if (
541                 (s.find('PCI MMCONFIG') >= 0) or
542                 (s.find('APIC') >= 0)  # covers both APIC and IOAPIC
543             ):
544                 continue
545
546             # generally blacklisted, unless we find an HPET behind it
547             if (s == 'reserved'):
548                 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
549                 continue
550
551             # if the tree continues recurse further down ...
552             if (len(tree.children) > 0):
553                 regions.extend(IOMemRegionTree.parse_iomem_tree(tree))
554                 continue
555
556             # add all remaining leaves
557             regions.append(r)
558
559         return regions
560
561
562 class IOMMUConfig(object):
563     def __init__(self, props):
564         self.base_addr = props['base_addr']
565         self.mmio_size = props['mmio_size']
566         if 'amd_bdf' in props:
567             self.amd_bdf = props['amd_bdf']
568             self.amd_base_cap = props['amd_base_cap']
569             self.amd_msi_cap = props['amd_msi_cap']
570             self.amd_features = props['amd_features']
571
572     @property
573     def is_amd_iommu(self):
574         return hasattr(self, 'amd_bdf')
575
576
577 def parse_iomem(pcidevices):
578     regions = IOMemRegionTree.parse_iomem_tree(
579         IOMemRegionTree.parse_iomem_file())
580
581     rom_region = MemRegion(0xc0000, 0xdffff, 'ROMs')
582     add_rom_region = False
583
584     ret = []
585     dmar_regions = []
586     for r in regions:
587         append_r = True
588         # filter the list for MSI-X pages
589         for d in pcidevices:
590             if d.msix_address >= r.start and d.msix_address <= r.stop:
591                 if d.msix_address > r.start:
592                     head_r = MemRegion(r.start, d.msix_address - 1,
593                                        r.typestr, r.comments)
594                     ret.append(head_r)
595                 if d.msix_address + d.msix_region_size < r.stop:
596                     tail_r = MemRegion(d.msix_address + d.msix_region_size,
597                                        r.stop, r.typestr, r.comments)
598                     ret.append(tail_r)
599                 append_r = False
600                 break
601         # filter out the ROMs
602         if (r.start >= rom_region.start and r.stop <= rom_region.stop):
603             add_rom_region = True
604             append_r = False
605         # filter out and save DMAR regions
606         if r.typestr.find('dmar') >= 0:
607             dmar_regions.append(r)
608             append_r = False
609         if append_r:
610             ret.append(r)
611
612     # add a region that covers all potential ROMs
613     if add_rom_region:
614         ret.append(rom_region)
615
616     # newer Linux kernels will report the first page as reserved
617     # it is needed for CPU init so include it anyways
618     if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
619         ret[0].start = 0
620
621     return ret, dmar_regions
622
623
624 def parse_pcidevices():
625     devices = []
626     caps = []
627     basedir = '/sys/bus/pci/devices'
628     list = input_listdir(basedir, ['*/config'])
629     for dir in list:
630         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
631         if d is not None:
632             if len(d.caps) > 0:
633                 duplicate = False
634                 # look for duplicate capability patterns
635                 for d2 in devices:
636                     if d2.caps == d.caps:
637                         # reused existing capability list, but record all users
638                         d2.caps[0].comments.append(str(d))
639                         d.caps_start = d2.caps_start
640                         duplicate = True
641                         break
642                 if not duplicate:
643                     d.caps[0].comments.append(str(d))
644                     d.caps_start = len(caps)
645                     caps.extend(d.caps)
646             devices.append(d)
647     return (devices, caps)
648
649
650 def parse_kernel_cmdline():
651     line = input_readline('/proc/cmdline')
652     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
653                  '([0-9a-fA-FxX]+)([KMG]?).*',
654                  line)
655     if m is not None:
656         size = kmg_multiply(int(m.group(1), 0), m.group(2))
657         start = kmg_multiply(int(m.group(3), 0), m.group(4))
658         return [start, size]
659     return None
660
661
662 def alloc_mem(regions, size):
663     mem = [0x3b000000, size]
664     for r in regions:
665         if (
666             r.typestr == 'System RAM' and
667             r.start <= mem[0] and
668             r.stop + 1 >= mem[0] + mem[1]
669         ):
670             if r.start < mem[0]:
671                 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
672                 regions.insert(regions.index(r), head_r)
673             if r.stop + 1 > mem[0] + mem[1]:
674                 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
675                                    r.comments)
676                 regions.insert(regions.index(r), tail_r)
677             regions.remove(r)
678             return mem
679     for r in reversed(regions):
680         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
681             mem[0] = r.start
682             r.start += mem[1]
683             return mem
684     raise RuntimeError('failed to allocate memory')
685
686
687 def count_cpus():
688     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
689     count = 0
690     for f in list:
691         if re.match(r'cpu[0-9]+', f):
692             count += 1
693     return count
694
695
696 def parse_madt():
697     f = input_open('/sys/firmware/acpi/tables/APIC', 'rb')
698     signature = f.read(4)
699     if signature != b'APIC':
700         raise RuntimeError('MADT: incorrect input file format %s' % signature)
701     (length,) = struct.unpack('<I', f.read(4))
702     f.seek(44)
703     length -= 44
704     ioapics = []
705
706     while length > 0:
707         offset = 0
708         (struct_type, struct_len) = struct.unpack('<BB', f.read(2))
709         offset += 2
710         length -= struct_len
711
712         if struct_type == 1:
713             (id, address, gsi_base) = struct.unpack('<BxII', f.read(10))
714             offset += 10
715             ioapics.append(IOAPIC(id, address, gsi_base))
716
717         f.seek(struct_len - offset, os.SEEK_CUR)
718
719     f.close()
720     return ioapics
721
722
723 def parse_dmar_devscope(f):
724     (scope_type, scope_len, id, bus, dev, fn) = \
725         struct.unpack('<BBxxBBBB', f.read(8))
726     if scope_len != 8:
727         raise RuntimeError('Unsupported DMAR Device Scope Structure')
728     return (scope_type, scope_len, id, bus, dev, fn)
729
730
731 # parsing of DMAR ACPI Table
732 # see Intel VT-d Spec chapter 8
733 def parse_dmar(pcidevices, ioapics, dmar_regions):
734     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
735     signature = f.read(4)
736     if signature != b'DMAR':
737         raise RuntimeError('DMAR: incorrect input file format %s' % signature)
738     (length,) = struct.unpack('<I', f.read(4))
739     f.seek(48)
740     length -= 48
741     units = []
742     regions = []
743
744     while length > 0:
745         offset = 0
746         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
747         offset += 4
748         length -= struct_len
749
750         # DMA Remapping Hardware Unit Definition
751         if struct_type == 0:
752             (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
753             if segment != 0:
754                 raise RuntimeError('We do not support multiple PCI segments')
755             if len(units) >= 8:
756                 raise RuntimeError('Too many DMAR units. '
757                                    'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
758             size = 0
759             for r in dmar_regions:
760                 if base == r.start:
761                     size = r.size()
762             if size == 0:
763                 raise RuntimeError('DMAR region size cannot be identified.\n'
764                                    'Target Linux must run with Intel IOMMU '
765                                    'enabled.')
766             if size > 0x3000:
767                 raise RuntimeError('Unexpectedly large DMAR region.')
768             units.append(IOMMUConfig({
769                 'base_addr': base,
770                 'mmio_size': size
771             }))
772             if flags & 1:
773                 for d in pcidevices:
774                     if d.iommu is None:
775                         d.iommu = len(units) - 1
776             offset += 16 - offset
777             while offset < struct_len:
778                 (scope_type, scope_len, id, bus, dev, fn) =\
779                     parse_dmar_devscope(f)
780                 # PCI Endpoint Device
781                 if scope_type == 1:
782                     assert not (flags & 1)
783                     for d in pcidevices:
784                         if d.bus == bus and d.dev == dev and d.fn == fn:
785                             d.iommu = len(units) - 1
786                             break
787                 # PCI Sub-hierarchy
788                 elif scope_type == 2:
789                     assert not (flags & 1)
790                     for d in pcidevices:
791                         if d.bus == bus and d.dev == dev and d.fn == fn:
792                             (secondbus, subordinate) = \
793                                 PCIPCIBridge.get_2nd_busses(d)
794                             for d2 in pcidevices:
795                                 if (
796                                     d2.bus >= secondbus and
797                                     d2.bus <= subordinate
798                                 ):
799                                     d2.iommu = len(units) - 1
800                             break
801                 # IOAPIC
802                 elif scope_type == 3:
803                     ioapic = next(chip for chip in ioapics if chip.id == id)
804                     bdf = (bus << 8) | (dev << 3) | fn
805                     for chip in ioapics:
806                         if chip.bdf == bdf:
807                             raise RuntimeError('IOAPICs with identical BDF')
808                     ioapic.bdf = bdf
809                     ioapic.iommu = len(units) - 1
810                 offset += scope_len
811
812         # Reserved Memory Region Reporting Structure
813         if struct_type == 1:
814             f.seek(8 - offset, os.SEEK_CUR)
815             offset += 8 - offset
816             (base, limit) = struct.unpack('<QQ', f.read(16))
817             offset += 16
818
819             comments = []
820             while offset < struct_len:
821                 (scope_type, scope_len, id, bus, dev, fn) =\
822                     parse_dmar_devscope(f)
823                 if scope_type == 1:
824                     comments.append('PCI device: %02x:%02x.%x' %
825                                     (bus, dev, fn))
826                 else:
827                     comments.append('DMAR parser could not decode device path')
828                 offset += scope_len
829
830             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
831             regions.append(reg)
832
833         f.seek(struct_len - offset, os.SEEK_CUR)
834
835     f.close()
836
837     for d in pcidevices:
838         if d.iommu is None:
839             raise RuntimeError(
840                 'PCI device %02x:%02x.%x outside the scope of an '
841                 'IOMMU' % (d.bus, d.dev, d.fn))
842
843     return units, regions
844
845
846 def parse_ivrs(pcidevices, ioapics):
847     def format_bdf(bdf):
848         bus, dev, fun = (bdf >> 8) & 0xff, (bdf >> 3) & 0x1f, bdf & 0x7
849         return '%02x:%02x.%x' % (bus, dev, fun)
850
851     f = input_open('/sys/firmware/acpi/tables/IVRS', 'rb')
852     signature = f.read(4)
853     if signature != b'IVRS':
854         raise RuntimeError('IVRS: incorrect input file format %s' % signature)
855
856     (length, revision) = struct.unpack('<IB', f.read(5))
857     if revision > 2:
858         raise RuntimeError('IVRS: unsupported Revision %02x' % revision)
859
860     f.seek(48, os.SEEK_SET)
861     length -= 48
862
863     units = []
864     regions = []
865     # BDF of devices that are permitted outside IOMMU: root complex
866     iommu_skiplist = set([0x0])
867     ivhd_blocks = 0
868     while length > 0:
869         (block_type, block_length) = struct.unpack('<BxH', f.read(4))
870         if block_type in [0x10, 0x11]:
871             ivhd_blocks += 1
872             if ivhd_blocks > 1:
873                 raise RuntimeError('Jailhouse doesn\'t support more than one '
874                                    'AMD IOMMU per PCI function.')
875             # IVHD block
876             ivhd_fields = struct.unpack('<HHQHxxL', f.read(20))
877             (iommu_bdf, base_cap_ofs,
878              base_addr, pci_seg, iommu_feat) = ivhd_fields
879
880             length -= block_length
881             block_length -= 24
882
883             if pci_seg != 0:
884                 raise RuntimeError('We do not support multiple PCI segments')
885
886             if len(units) > 8:
887                 raise RuntimeError('Too many IOMMU units. '
888                                    'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
889
890             msi_cap_ofs = None
891
892             for i, d in enumerate(pcidevices):
893                 if d.bdf() == iommu_bdf:
894                     # Extract MSI capability offset
895                     for c in d.caps:
896                         if c.id == 0x05:
897                             msi_cap_ofs = c.start
898                     # We must not map IOMMU to the cells
899                     del pcidevices[i]
900
901             if msi_cap_ofs is None:
902                 raise RuntimeError('AMD IOMMU lacks MSI support, and '
903                                    'Jailhouse doesn\'t support MSI-X yet.')
904
905             if (iommu_feat & (0xF << 13)) and (iommu_feat & (0x3F << 17)):
906                 # Performance Counters are supported, allocate 512K
907                 mmio_size = 524288
908             else:
909                 # Allocate 16K
910                 mmio_size = 16384
911
912             units.append(IOMMUConfig({
913                 'base_addr': base_addr,
914                 'mmio_size': mmio_size,
915                 'amd_bdf': iommu_bdf,
916                 'amd_base_cap': base_cap_ofs,
917                 'amd_msi_cap': msi_cap_ofs,
918                 # IVHD block type 0x11 has exact EFR copy but type 0x10 may
919                 # overwrite what hardware reports. Set reserved bit 0 in that
920                 # case to indicate that the value is in use.
921                 'amd_features': (iommu_feat | 0x1) if block_type == 0x10 else 0
922             }))
923
924             bdf_start_range = None
925             while block_length > 0:
926                 (entry_type, device_id) = struct.unpack('<BHx', f.read(4))
927                 block_length -= 4
928
929                 if entry_type == 0x01:
930                     # All
931                     for d in pcidevices:
932                         d.iommu = len(units) - 1
933                 elif entry_type == 0x02:
934                     # Select
935                     for d in pcidevices:
936                         if d.bdf() == device_id:
937                             d.iommu = len(units) - 1
938                 elif entry_type == 0x03:
939                     # Start of range
940                     bdf_start_range = device_id
941                 elif entry_type == 0x04:
942                     # End of range
943                     if bdf_start_range is None:
944                         continue
945                     for d in pcidevices:
946                         if d.bdf() >= bdf_start_range and d.bdf() <= device_id:
947                             d.iommu = len(units) - 1
948                     bdf_start_range = None
949                 elif entry_type == 0x42:
950                     # Alias select
951                     (device_id_b,) = struct.unpack('<xHx', f.read(4))
952                     block_length -= 4
953                     for d in pcidevices:
954                         if d.bdf() == device_id_b:
955                             d.iommu = len(units) - 1
956                 elif entry_type == 0x43:
957                     # Alias start of range
958                     (device_id_b,) = struct.unpack('<xHx', f.read(4))
959                     block_length -= 4
960                     bdf_start_range = device_id_b
961                 elif entry_type == 0x48:
962                     # Special device
963                     (handle, device_id_b, variety) = struct.unpack(
964                         '<BHB', f.read(4))
965                     block_length -= 4
966                     if variety == 0x01:  # IOAPIC
967                         for chip in ioapics:
968                             if chip.id == handle:
969                                 chip.bdf = device_id
970                                 chip.iommu = len(units) - 1
971                 else:
972                     # Reserved or ignored entries
973                     if entry_type >= 0x40:
974                         f.seek(4, os.SEEK_CUR)
975                         block_length -= 4
976
977         elif type in [0x20, 0x21, 0x22]:
978             # IVMD block
979             ivmd_fields = struct.unpack('<BBHHHxxxxxxxxQQ', f.read(32))
980             (block_type, block_flags, block_length,
981              device_id, aux_data, mem_addr, mem_len) = ivmd_fields
982             length -= block_length
983
984             if int(block_flags):
985                 bdf_str = format_bdf(device_id)
986                 print(
987                     'WARNING: Jailhouse doesn\'t support configurable '
988                     '(eg. read-only) device memory. Device %s may not '
989                     'work properly, especially in non-root cell.' % bdf_str)
990
991             if block_type == 0x20:
992                 # All devices
993                 comment = None
994             elif block_type == 0x21:
995                 # Selected device
996                 comment = 'PCI Device: %s' % format_bdf(device_id)
997             elif block_type == 0x22:
998                 # Device range
999                 comment = 'PCI Device: %s - %s' % (
1000                     format_bdf(device_id), format_bdf(aux_data))
1001
1002             if comment:
1003                 print('WARNING: Jailhouse doesn\'t support per-device memory '
1004                       'regions. The memory at 0x%x will be mapped accessible '
1005                       'to all devices.' % mem_addr)
1006
1007             regions.append(MemRegion(mem_addr, mem_len, 'ACPI IVRS', comment))
1008         elif type == 0x40:
1009             raise RuntimeError(
1010                 'You board uses IVRS Rev. 2 feature Jailhouse doesn\'t '
1011                 'support yet. Please report this to '
1012                 'jailhouse-dev@googlegroups.com.')
1013         else:
1014             print(
1015                 'WARNING: Skipping unknown IVRS '
1016                 'block type 0x%02x' % block_type)
1017
1018         for d in pcidevices:
1019             if d.bdf() not in iommu_skiplist and d.iommu is None:
1020                 raise RuntimeError(
1021                     'PCI device %02x:%02x.%x outside the scope of an '
1022                     'IOMMU' % (d.bus, d.dev, d.fn))
1023
1024         f.close()
1025         return units, regions
1026
1027
1028 def parse_ioports():
1029     pm_timer_base = None
1030     f = input_open('/proc/ioports')
1031     for line in f:
1032         if line.endswith('ACPI PM_TMR\n'):
1033             pm_timer_base = int(line.split('-')[0], 16)
1034             break
1035     f.close()
1036     return pm_timer_base
1037
1038
1039 class MMConfig:
1040     def __init__(self, base, end_bus):
1041         self.base = base
1042         self.end_bus = end_bus
1043
1044     @staticmethod
1045     def parse():
1046         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
1047         signature = f.read(4)
1048         if signature != b'MCFG':
1049             raise RuntimeError('MCFG: incorrect input file format %s' %
1050                                signature)
1051         (length,) = struct.unpack('<I', f.read(4))
1052         if length > 60:
1053             raise RuntimeError('Multiple MMCONFIG regions found! '
1054                                'This is not supported')
1055         f.seek(44)
1056         (base, segment, start_bus, end_bus) = \
1057             struct.unpack('<QHBB', f.read(12))
1058         if segment != 0 or start_bus != 0:
1059             raise RuntimeError('Invalid MCFG structure found')
1060         return MMConfig(base, end_bus)
1061
1062
1063 def get_cpu_vendor():
1064     global cpuvendor
1065     if cpuvendor is not None:
1066         return cpuvendor
1067     with input_open('/proc/cpuinfo', 'r') as f:
1068         for line in f:
1069             if not line.strip():
1070                 continue
1071             key, value = line.split(':')
1072             if key.strip() == 'vendor_id':
1073                 cpuvendor = value.strip()
1074                 return cpuvendor
1075
1076
1077 if options.generate_collector:
1078     f = open(options.file, 'w')
1079     filelist = ' '.join(inputs['files'])
1080     filelist_opt = ' '.join(inputs['files_opt'])
1081     filelist_intel = ' '.join(inputs['files_intel'])
1082     filelist_amd = ' '.join(inputs['files_amd'])
1083
1084     tmpl = Template(filename=os.path.join(options.template_dir,
1085                                           'jailhouse-config-collect.tmpl'))
1086     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
1087             filelist_intel=filelist_intel, filelist_amd=filelist_amd))
1088     f.close()
1089     sys.exit(0)
1090
1091 if ((options.root is '/') and (os.geteuid() is not 0)):
1092     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
1093     sys.exit(1)
1094
1095 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
1096 if jh_enabled == '1':
1097     print('ERROR: Jailhouse was enabled when collecting input files! '
1098           'Disable jailhouse and try again.',
1099           file=sys.stderr)
1100     sys.exit(1)
1101
1102 (pcidevices, pcicaps) = parse_pcidevices()
1103
1104 product = [input_readline('/sys/class/dmi/id/sys_vendor',
1105                           True).rstrip(),
1106            input_readline('/sys/class/dmi/id/product_name',
1107                           True).rstrip()
1108            ]
1109
1110 inmatemem = kmg_multiply_str(options.mem_inmates)
1111 hvmem = [0, kmg_multiply_str(options.mem_hv)]
1112
1113 (regions, dmar_regions) = parse_iomem(pcidevices)
1114 ourmem = parse_kernel_cmdline()
1115 total = hvmem[1] + inmatemem
1116
1117 mmconfig = MMConfig.parse()
1118
1119 ioapics = parse_madt()
1120
1121 vendor = get_cpu_vendor()
1122 if vendor == 'GenuineIntel':
1123     (iommu_units, extra_memregs) = parse_dmar(pcidevices, ioapics,
1124                                               dmar_regions)
1125 else:
1126     (iommu_units, extra_memregs) = parse_ivrs(pcidevices, ioapics)
1127 regions += extra_memregs
1128
1129 # kernel does not have memmap region, pick one
1130 if ourmem is None:
1131     ourmem = alloc_mem(regions, total)
1132 elif (total > ourmem[1]):
1133     raise RuntimeError('Your memmap reservation is too small you need >="' +
1134                        hex(total) + '". Hint: your kernel cmd line needs '
1135                        '"memmap=' + hex(total) + '$' + hex(ourmem[0]) + '"')
1136
1137 hvmem[0] = ourmem[0]
1138
1139 inmatereg = MemRegion(ourmem[0] + hvmem[1],
1140                       ourmem[0] + hvmem[1] + inmatemem - 1,
1141                       'JAILHOUSE Inmate Memory')
1142 regions.append(inmatereg)
1143
1144 cpucount = count_cpus()
1145
1146 pm_timer_base = parse_ioports()
1147
1148
1149 f = open(options.file, 'w')
1150 tmpl = Template(filename=os.path.join(options.template_dir,
1151                                       'root-cell-config.c.tmpl'))
1152 kwargs = {
1153     'regions': regions,
1154     'ourmem': ourmem,
1155     'argstr': ' '.join(sys.argv),
1156     'hvmem': hvmem,
1157     'product': product,
1158     'pcidevices': pcidevices,
1159     'pcicaps': pcicaps,
1160     'cpucount': cpucount,
1161     'irqchips': ioapics,
1162     'pm_timer_base': pm_timer_base,
1163     'mmconfig': mmconfig,
1164     'iommu_units': iommu_units
1165 }
1166
1167 f.write(tmpl.render(**kwargs))
1168
1169 f.close()