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