]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
b7207fb4145cb0ee181aaab0c6ebdf150fbdc701
[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
566
567 def parse_iomem(pcidevices):
568     regions = IOMemRegionTree.parse_iomem_tree(
569         IOMemRegionTree.parse_iomem_file())
570
571     rom_region = MemRegion(0xc0000, 0xdffff, 'ROMs')
572     add_rom_region = False
573
574     ret = []
575     dmar_regions = []
576     for r in regions:
577         append_r = True
578         # filter the list for MSI-X pages
579         for d in pcidevices:
580             if d.msix_address >= r.start and d.msix_address <= r.stop:
581                 if d.msix_address > r.start:
582                     head_r = MemRegion(r.start, d.msix_address - 1,
583                                        r.typestr, r.comments)
584                     ret.append(head_r)
585                 if d.msix_address + d.msix_region_size < r.stop:
586                     tail_r = MemRegion(d.msix_address + d.msix_region_size,
587                                        r.stop, r.typestr, r.comments)
588                     ret.append(tail_r)
589                 append_r = False
590                 break
591         # filter out the ROMs
592         if (r.start >= rom_region.start and r.stop <= rom_region.stop):
593             add_rom_region = True
594             append_r = False
595         # filter out and save DMAR regions
596         if r.typestr.find('dmar') >= 0:
597             dmar_regions.append(r)
598             append_r = False
599         if append_r:
600             ret.append(r)
601
602     # add a region that covers all potential ROMs
603     if add_rom_region:
604         ret.append(rom_region)
605
606     # newer Linux kernels will report the first page as reserved
607     # it is needed for CPU init so include it anyways
608     if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
609         ret[0].start = 0
610
611     return ret, dmar_regions
612
613
614 def parse_pcidevices():
615     devices = []
616     caps = []
617     basedir = '/sys/bus/pci/devices'
618     list = input_listdir(basedir, ['*/config'])
619     for dir in list:
620         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
621         if d is not None:
622             if len(d.caps) > 0:
623                 duplicate = False
624                 # look for duplicate capability patterns
625                 for d2 in devices:
626                     if d2.caps == d.caps:
627                         # reused existing capability list, but record all users
628                         d2.caps[0].comments.append(str(d))
629                         d.caps_start = d2.caps_start
630                         duplicate = True
631                         break
632                 if not duplicate:
633                     d.caps[0].comments.append(str(d))
634                     d.caps_start = len(caps)
635                     caps.extend(d.caps)
636             devices.append(d)
637     return (devices, caps)
638
639
640 def parse_kernel_cmdline():
641     line = input_readline('/proc/cmdline')
642     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
643                  '([0-9a-fA-FxX]+)([KMG]?).*',
644                  line)
645     if m is not None:
646         size = kmg_multiply(int(m.group(1), 0), m.group(2))
647         start = kmg_multiply(int(m.group(3), 0), m.group(4))
648         return [start, size]
649     return None
650
651
652 def alloc_mem(regions, size):
653     mem = [0x3b000000, size]
654     for r in regions:
655         if (
656             r.typestr == 'System RAM' and
657             r.start <= mem[0] and
658             r.stop + 1 >= mem[0] + mem[1]
659         ):
660             if r.start < mem[0]:
661                 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
662                 regions.insert(regions.index(r), head_r)
663             if r.stop + 1 > mem[0] + mem[1]:
664                 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
665                                    r.comments)
666                 regions.insert(regions.index(r), tail_r)
667             regions.remove(r)
668             return mem
669     for r in reversed(regions):
670         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
671             mem[0] = r.start
672             r.start += mem[1]
673             return mem
674     raise RuntimeError('failed to allocate memory')
675
676
677 def count_cpus():
678     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
679     count = 0
680     for f in list:
681         if re.match(r'cpu[0-9]+', f):
682             count += 1
683     return count
684
685
686 def parse_madt():
687     f = input_open('/sys/firmware/acpi/tables/APIC', 'rb')
688     signature = f.read(4)
689     if signature != b'APIC':
690         raise RuntimeError('MADT: incorrect input file format %s' % signature)
691     (length,) = struct.unpack('<I', f.read(4))
692     f.seek(44)
693     length -= 44
694     ioapics = []
695
696     while length > 0:
697         offset = 0
698         (struct_type, struct_len) = struct.unpack('<BB', f.read(2))
699         offset += 2
700         length -= struct_len
701
702         if struct_type == 1:
703             (id, address, gsi_base) = struct.unpack('<BxII', f.read(10))
704             offset += 10
705             ioapics.append(IOAPIC(id, address, gsi_base))
706
707         f.seek(struct_len - offset, os.SEEK_CUR)
708
709     f.close()
710     return ioapics
711
712
713 def parse_dmar_devscope(f):
714     (scope_type, scope_len, id, bus, dev, fn) = \
715         struct.unpack('<BBxxBBBB', f.read(8))
716     if scope_len != 8:
717         raise RuntimeError('Unsupported DMAR Device Scope Structure')
718     return (scope_type, scope_len, id, bus, dev, fn)
719
720
721 # parsing of DMAR ACPI Table
722 # see Intel VT-d Spec chapter 8
723 def parse_dmar(pcidevices, ioapics, dmar_regions):
724     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
725     signature = f.read(4)
726     if signature != b'DMAR':
727         raise RuntimeError('DMAR: incorrect input file format %s' % signature)
728     (length,) = struct.unpack('<I', f.read(4))
729     f.seek(48)
730     length -= 48
731     units = []
732     regions = []
733
734     while length > 0:
735         offset = 0
736         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
737         offset += 4
738         length -= struct_len
739
740         # DMA Remapping Hardware Unit Definition
741         if struct_type == 0:
742             (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
743             if segment != 0:
744                 raise RuntimeError('We do not support multiple PCI segments')
745             if len(units) >= 8:
746                 raise RuntimeError('Too many DMAR units. '
747                                    'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
748             size = 0
749             for r in dmar_regions:
750                 if base == r.start:
751                     size = r.size()
752             if size == 0:
753                 raise RuntimeError('DMAR region size cannot be identified.\n'
754                                    'Target Linux must run with Intel IOMMU '
755                                    'enabled.')
756             if size > 0x3000:
757                 raise RuntimeError('Unexpectedly large DMAR region.')
758             units.append(IOMMUConfig({
759                 'base_addr': base,
760                 'mmio_size': size
761             }))
762             if flags & 1:
763                 for d in pcidevices:
764                     if d.iommu is None:
765                         d.iommu = len(units) - 1
766             offset += 16 - offset
767             while offset < struct_len:
768                 (scope_type, scope_len, id, bus, dev, fn) =\
769                     parse_dmar_devscope(f)
770                 # PCI Endpoint Device
771                 if scope_type == 1:
772                     assert not (flags & 1)
773                     for d in pcidevices:
774                         if d.bus == bus and d.dev == dev and d.fn == fn:
775                             d.iommu = len(units) - 1
776                             break
777                 # PCI Sub-hierarchy
778                 elif scope_type == 2:
779                     assert not (flags & 1)
780                     for d in pcidevices:
781                         if d.bus == bus and d.dev == dev and d.fn == fn:
782                             (secondbus, subordinate) = \
783                                 PCIPCIBridge.get_2nd_busses(d)
784                             for d2 in pcidevices:
785                                 if (
786                                     d2.bus >= secondbus and
787                                     d2.bus <= subordinate
788                                 ):
789                                     d2.iommu = len(units) - 1
790                             break
791                 # IOAPIC
792                 elif scope_type == 3:
793                     ioapic = next(chip for chip in ioapics if chip.id == id)
794                     bdf = (bus << 8) | (dev << 3) | fn
795                     for chip in ioapics:
796                         if chip.bdf == bdf:
797                             raise RuntimeError('IOAPICs with identical BDF')
798                     ioapic.bdf = bdf
799                     ioapic.iommu = len(units) - 1
800                 offset += scope_len
801
802         # Reserved Memory Region Reporting Structure
803         if struct_type == 1:
804             f.seek(8 - offset, os.SEEK_CUR)
805             offset += 8 - offset
806             (base, limit) = struct.unpack('<QQ', f.read(16))
807             offset += 16
808
809             comments = []
810             while offset < struct_len:
811                 (scope_type, scope_len, id, bus, dev, fn) =\
812                     parse_dmar_devscope(f)
813                 if scope_type == 1:
814                     comments.append('PCI device: %02x:%02x.%x' %
815                                     (bus, dev, fn))
816                 else:
817                     comments.append('DMAR parser could not decode device path')
818                 offset += scope_len
819
820             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
821             regions.append(reg)
822
823         f.seek(struct_len - offset, os.SEEK_CUR)
824
825     f.close()
826
827     for d in pcidevices:
828         if d.iommu is None:
829             raise RuntimeError(
830                 'PCI device %02x:%02x.%x outside the scope of an '
831                 'IOMMU' % (d.bus, d.dev, d.fn))
832
833     return units, regions
834
835
836 def parse_ivrs(pcidevices, ioapics):
837     def format_bdf(bdf):
838         bus, dev, fun = (bdf >> 8) & 0xff, (bdf >> 3) & 0x1f, bdf & 0x7
839         return '%02x:%02x.%x' % (bus, dev, fun)
840
841     f = input_open('/sys/firmware/acpi/tables/IVRS', 'rb')
842     signature = f.read(4)
843     if signature != b'IVRS':
844         raise RuntimeError('IVRS: incorrect input file format %s' % signature)
845
846     (length, revision) = struct.unpack('<IB', f.read(5))
847     if revision > 2:
848         raise RuntimeError('IVRS: unsupported Revision %02x' % revision)
849
850     f.seek(48, os.SEEK_SET)
851     length -= 48
852
853     units = []
854     regions = []
855     # BDF of devices that are permitted outside IOMMU: root complex
856     iommu_skiplist = set([0x0])
857     ivhd_blocks = 0
858     while length > 0:
859         (block_type, block_length) = struct.unpack('<BxH', f.read(4))
860         if block_type in [0x10, 0x11]:
861             ivhd_blocks += 1
862             if ivhd_blocks > 1:
863                 raise RuntimeError('Jailhouse doesn\'t support more than one '
864                                    'AMD IOMMU per PCI function.')
865             # IVHD block
866             ivhd_fields = struct.unpack('<HHQHxxL', f.read(20))
867             (iommu_bdf, base_cap_ofs,
868              base_addr, pci_seg, iommu_feat) = ivhd_fields
869
870             length -= block_length
871             block_length -= 24
872
873             if pci_seg != 0:
874                 raise RuntimeError('We do not support multiple PCI segments')
875
876             if len(units) > 8:
877                 raise RuntimeError('Too many IOMMU units. '
878                                    'Raise JAILHOUSE_MAX_IOMMU_UNITS.')
879
880             for i, d in enumerate(pcidevices):
881                 if d.bdf() == iommu_bdf:
882                     # We must not map IOMMU to the cells
883                     del pcidevices[i]
884
885             if (iommu_feat & (0xF << 13)) and (iommu_feat & (0x3F << 17)):
886                 # Performance Counters are supported, allocate 512K
887                 mmio_size = 524288
888             else:
889                 # Allocate 16K
890                 mmio_size = 16384
891
892             units.append(IOMMUConfig({
893                 'base_addr': base_addr,
894                 'mmio_size': mmio_size,
895             }))
896
897             bdf_start_range = None
898             while block_length > 0:
899                 (entry_type, device_id) = struct.unpack('<BHx', f.read(4))
900                 block_length -= 4
901
902                 if entry_type == 0x01:
903                     # All
904                     for d in pcidevices:
905                         d.iommu = len(units) - 1
906                 elif entry_type == 0x02:
907                     # Select
908                     for d in pcidevices:
909                         if d.bdf() == device_id:
910                             d.iommu = len(units) - 1
911                 elif entry_type == 0x03:
912                     # Start of range
913                     bdf_start_range = device_id
914                 elif entry_type == 0x04:
915                     # End of range
916                     if bdf_start_range is None:
917                         continue
918                     for d in pcidevices:
919                         if d.bdf() >= bdf_start_range and d.bdf() <= device_id:
920                             d.iommu = len(units) - 1
921                     bdf_start_range = None
922                 elif entry_type == 0x42:
923                     # Alias select
924                     (device_id_b,) = struct.unpack('<xHx', f.read(4))
925                     block_length -= 4
926                     for d in pcidevices:
927                         if d.bdf() == device_id_b:
928                             d.iommu = len(units) - 1
929                 elif entry_type == 0x43:
930                     # Alias start of range
931                     (device_id_b,) = struct.unpack('<xHx', f.read(4))
932                     block_length -= 4
933                     bdf_start_range = device_id_b
934                 elif entry_type == 0x48:
935                     # Special device
936                     (handle, device_id_b, variety) = struct.unpack(
937                         '<BHB', f.read(4))
938                     block_length -= 4
939                     if variety == 0x01:  # IOAPIC
940                         for chip in ioapics:
941                             if chip.id == handle:
942                                 chip.bdf = device_id
943                                 chip.iommu = len(units) - 1
944                 else:
945                     # Reserved or ignored entries
946                     if entry_type >= 0x40:
947                         f.seek(4, os.SEEK_CUR)
948                         block_length -= 4
949
950         elif type in [0x20, 0x21, 0x22]:
951             # IVMD block
952             ivmd_fields = struct.unpack('<BBHHHxxxxxxxxQQ', f.read(32))
953             (block_type, block_flags, block_length,
954              device_id, aux_data, mem_addr, mem_len) = ivmd_fields
955             length -= block_length
956
957             if int(block_flags):
958                 bdf_str = format_bdf(device_id)
959                 print(
960                     'WARNING: Jailhouse doesn\'t support configurable '
961                     '(eg. read-only) device memory. Device %s may not '
962                     'work properly, especially in non-root cell.' % bdf_str)
963
964             if block_type == 0x20:
965                 # All devices
966                 comment = None
967             elif block_type == 0x21:
968                 # Selected device
969                 comment = 'PCI Device: %s' % format_bdf(device_id)
970             elif block_type == 0x22:
971                 # Device range
972                 comment = 'PCI Device: %s - %s' % (
973                     format_bdf(device_id), format_bdf(aux_data))
974
975             if comment:
976                 print('WARNING: Jailhouse doesn\'t support per-device memory '
977                       'regions. The memory at 0x%x will be mapped accessible '
978                       'to all devices.' % mem_addr)
979
980             regions.append(MemRegion(mem_addr, mem_len, 'ACPI IVRS', comment))
981         elif type == 0x40:
982             raise RuntimeError(
983                 'You board uses IVRS Rev. 2 feature Jailhouse doesn\'t '
984                 'support yet. Please report this to '
985                 'jailhouse-dev@googlegroups.com.')
986         else:
987             print(
988                 'WARNING: Skipping unknown IVRS '
989                 'block type 0x%02x' % block_type)
990
991         for d in pcidevices:
992             if d.bdf() not in iommu_skiplist and d.iommu is None:
993                 raise RuntimeError(
994                     'PCI device %02x:%02x.%x outside the scope of an '
995                     'IOMMU' % (d.bus, d.dev, d.fn))
996
997         f.close()
998         return units, regions
999
1000
1001 def parse_ioports():
1002     pm_timer_base = None
1003     f = input_open('/proc/ioports')
1004     for line in f:
1005         if line.endswith('ACPI PM_TMR\n'):
1006             pm_timer_base = int(line.split('-')[0], 16)
1007             break
1008     f.close()
1009     return pm_timer_base
1010
1011
1012 class MMConfig:
1013     def __init__(self, base, end_bus):
1014         self.base = base
1015         self.end_bus = end_bus
1016
1017     @staticmethod
1018     def parse():
1019         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
1020         signature = f.read(4)
1021         if signature != b'MCFG':
1022             raise RuntimeError('MCFG: incorrect input file format %s' %
1023                                signature)
1024         (length,) = struct.unpack('<I', f.read(4))
1025         if length > 60:
1026             raise RuntimeError('Multiple MMCONFIG regions found! '
1027                                'This is not supported')
1028         f.seek(44)
1029         (base, segment, start_bus, end_bus) = \
1030             struct.unpack('<QHBB', f.read(12))
1031         if segment != 0 or start_bus != 0:
1032             raise RuntimeError('Invalid MCFG structure found')
1033         return MMConfig(base, end_bus)
1034
1035
1036 def get_cpu_vendor():
1037     global cpuvendor
1038     if cpuvendor is not None:
1039         return cpuvendor
1040     with input_open('/proc/cpuinfo', 'r') as f:
1041         for line in f:
1042             if not line.strip():
1043                 continue
1044             key, value = line.split(':')
1045             if key.strip() == 'vendor_id':
1046                 cpuvendor = value.strip()
1047                 return cpuvendor
1048
1049
1050 if options.generate_collector:
1051     f = open(options.file, 'w')
1052     filelist = ' '.join(inputs['files'])
1053     filelist_opt = ' '.join(inputs['files_opt'])
1054     filelist_intel = ' '.join(inputs['files_intel'])
1055     filelist_amd = ' '.join(inputs['files_amd'])
1056
1057     tmpl = Template(filename=os.path.join(options.template_dir,
1058                                           'jailhouse-config-collect.tmpl'))
1059     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
1060             filelist_intel=filelist_intel, filelist_amd=filelist_amd))
1061     f.close()
1062     sys.exit(0)
1063
1064 if ((options.root is '/') and (os.geteuid() is not 0)):
1065     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
1066     sys.exit(1)
1067
1068 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
1069 if jh_enabled == '1':
1070     print('ERROR: Jailhouse was enabled when collecting input files! '
1071           'Disable jailhouse and try again.',
1072           file=sys.stderr)
1073     sys.exit(1)
1074
1075 (pcidevices, pcicaps) = parse_pcidevices()
1076
1077 product = [input_readline('/sys/class/dmi/id/sys_vendor',
1078                           True).rstrip(),
1079            input_readline('/sys/class/dmi/id/product_name',
1080                           True).rstrip()
1081            ]
1082
1083 inmatemem = kmg_multiply_str(options.mem_inmates)
1084 hvmem = [0, kmg_multiply_str(options.mem_hv)]
1085
1086 (regions, dmar_regions) = parse_iomem(pcidevices)
1087 ourmem = parse_kernel_cmdline()
1088 total = hvmem[1] + inmatemem
1089
1090 mmconfig = MMConfig.parse()
1091
1092 ioapics = parse_madt()
1093
1094 vendor = get_cpu_vendor()
1095 if vendor == 'GenuineIntel':
1096     (iommu_units, extra_memregs) = parse_dmar(pcidevices, ioapics,
1097                                               dmar_regions)
1098 else:
1099     (iommu_units, extra_memregs) = parse_ivrs(pcidevices, ioapics)
1100 regions += extra_memregs
1101
1102 # kernel does not have memmap region, pick one
1103 if ourmem is None:
1104     ourmem = alloc_mem(regions, total)
1105 elif (total > ourmem[1]):
1106     raise RuntimeError('Your memmap reservation is too small you need >="' +
1107                        hex(total) + '". Hint: your kernel cmd line needs '
1108                        '"memmap=' + hex(total) + '$' + hex(ourmem[0]) + '"')
1109
1110 hvmem[0] = ourmem[0]
1111
1112 inmatereg = MemRegion(ourmem[0] + hvmem[1],
1113                       ourmem[0] + hvmem[1] + inmatemem - 1,
1114                       'JAILHOUSE Inmate Memory')
1115 regions.append(inmatereg)
1116
1117 cpucount = count_cpus()
1118
1119 pm_timer_base = parse_ioports()
1120
1121
1122 f = open(options.file, 'w')
1123 tmpl = Template(filename=os.path.join(options.template_dir,
1124                                       'root-cell-config.c.tmpl'))
1125 kwargs = {
1126     'regions': regions,
1127     'ourmem': ourmem,
1128     'argstr': ' '.join(sys.argv),
1129     'hvmem': hvmem,
1130     'product': product,
1131     'pcidevices': pcidevices,
1132     'pcicaps': pcicaps,
1133     'cpucount': cpucount,
1134     'irqchips': ioapics,
1135     'pm_timer_base': pm_timer_base,
1136     'mmconfig': mmconfig,
1137     'iommu_units': iommu_units
1138 }
1139
1140 f.write(tmpl.render(**kwargs))
1141
1142 f.close()