]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
core/configs/tools: Report IOMMU association of devices via config file
[jailhouse.git] / tools / jailhouse-config-create
1 #!/usr/bin/env python
2 #
3 # Jailhouse, a Linux-based partitioning hypervisor
4 #
5 # Copyright (c) Siemens AG, 2014
6 #
7 # This work is licensed under the terms of the GNU GPL, version 2.  See
8 # the COPYING file in the top-level directory.
9 #
10 # This script should help to create a basic jailhouse configuration file.
11 # It needs to be executed on the target machine, where it will gather
12 # information about the system. For more advanced scenarios you will have
13 # to change the generated C-code.
14
15 from __future__ import print_function
16 import sys
17 import os
18 import re
19 import argparse
20 import struct
21 from mako.template import Template
22
23 abspath = os.path.abspath(os.path.dirname(sys.argv[0]))
24
25 # pretend to be part of the jailhouse tool
26 sys.argv[0] = sys.argv[0].replace('-', ' ')
27
28 parser = argparse.ArgumentParser()
29 parser.add_argument('-g', '--generate-collector',
30                     help='generate a script to collect input files on '
31                          'a remote machine',
32                     action='store_true')
33 parser.add_argument('-r', '--root',
34                     help='gather information in ROOT/, the default is "/" '
35                          'which means creating a config for localhost',
36                     default='/',
37                     action='store',
38                     type=str)
39 parser.add_argument('-t', '--template-dir',
40                     help='the directory where the templates are located,'
41                          'the default is "' + abspath + '"',
42                     default=abspath,
43                     action='store',
44                     type=str)
45
46 memargs = [['--mem-inmates', '2M', 'inmate'],
47            ['--mem-hv', '64M', 'hypervisor']]
48
49 for entry in memargs:
50     parser.add_argument(entry[0],
51                         help='the amount of ' + entry[2] +
52                              ' memory, default is "' + entry[1] +
53                              '", format "xxx[K|M|G]"',
54                         default=entry[1],
55                         action='store',
56                         type=str)
57
58 parser.add_argument('file', metavar='FILE',
59                     help='name of file to write out',
60                     type=str)
61
62 options = parser.parse_args()
63
64 inputs = {'files': set(), 'files_opt': set(), 'dirs': set()}
65
66
67 def kmg_multiply(value, kmg):
68     if (kmg == 'K' or kmg == 'k'):
69         return 1024 * value
70     if (kmg == 'M' or kmg == 'm'):
71         return 1024**2 * value
72     if (kmg == 'G' or kmg == 'g'):
73         return 1024**3 * value
74     return value
75
76
77 def kmg_multiply_str(str):
78     m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
79     if m is not None:
80         return kmg_multiply(int(m.group(1)), m.group(2))
81     raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
82     return 0
83
84
85 def input_open(name, mode='r', optional=False):
86     inputs['files_opt' if optional else 'files'].add(name)
87     try:
88         f = open(options.root + name, mode)
89     except Exception as e:
90         if optional or options.generate_collector:
91             return open("/dev/null", mode)
92         raise e
93     return f
94
95
96 def input_readline(name, optional=False):
97     f = input_open(name, optional=optional)
98     line = f.readline()
99     f.close()
100     return line
101
102
103 def input_listdir(dir, wildcards):
104     for w in wildcards:
105         inputs['dirs'].add(os.path.join(dir, w))
106     if options.generate_collector:
107         return []
108     dirs = os.listdir(options.root + dir)
109     dirs.sort()
110     return dirs
111
112
113 class PCICapability:
114     def __init__(self, id, start, len, flags, content, msix_address):
115         self.id = id
116         self.start = start
117         self.len = len
118         self.flags = flags
119         self.content = content
120         self.msix_address = msix_address
121         self.comments = []
122
123     def __eq__(self, other):
124         return self.id == other.id and self.start == other.start and \
125             self.len == other.len and self.flags == other.flags
126
127     RD = '0'
128     RW = 'JAILHOUSE_PCICAPS_WRITE'
129
130     @staticmethod
131     def parse_pcicaps(dir):
132         caps = []
133         f = input_open(os.path.join(dir, 'config'), 'rb')
134         f.seek(0x06)
135         (status,) = struct.unpack('<H', f.read(2))
136         # capability list supported?
137         if (status & (1 << 4)) == 0:
138             f.close()
139             return caps
140         # walk capability list
141         f.seek(0x34)
142         (next,) = struct.unpack('B', f.read(1))
143         while next != 0:
144             cap = next
145             msix_address = 0
146             f.seek(cap)
147             (id, next) = struct.unpack('<BB', f.read(2))
148             if id == 0x01:  # Power Management
149                 # this cap can be handed out completely
150                 len = 8
151                 flags = PCICapability.RW
152             elif id == 0x05:  # MSI
153                 # access will be moderated by hypervisor
154                 len = 10
155                 (msgctl,) = struct.unpack('<H', f.read(2))
156                 if (msgctl & (1 << 7)) != 0:  # 64-bit support
157                     len += 4
158                 if (msgctl & (1 << 8)) != 0:  # per-vector masking support
159                     len += 10
160                 flags = PCICapability.RW
161             elif id == 0x11:  # MSI-X
162                 # access will be moderated by hypervisor
163                 len = 12
164                 (table,) = struct.unpack('<xxI', f.read(6))
165                 f.seek(0x10 + (table & 7) * 4)
166                 (bar,) = struct.unpack('<I', f.read(4))
167                 if (bar & 0x3) != 0:
168                     raise RuntimeError('Invalid MSI-X BAR found')
169                 if (bar & 0x4) != 0:
170                     bar |= struct.unpack('<I', f.read(4))[0] << 32
171                 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
172                 flags = PCICapability.RW
173             else:
174                 # unknown/unhandled cap, mark its existence
175                 len = 2
176                 flags = PCICapability.RD
177             f.seek(cap + 2)
178             content = f.read(len - 2)
179             caps.append(PCICapability(id, cap, len, flags, content,
180                                       msix_address))
181         return caps
182
183
184 class PCIDevice:
185     def __init__(self, type, domain, bus, dev, fn, caps):
186         self.type = type
187         self.iommu = None
188         self.domain = domain
189         self.bus = bus
190         self.dev = dev
191         self.fn = fn
192         self.caps = caps
193         self.caps_start = 0
194         self.num_caps = len(caps)
195         self.num_msi_vectors = 0
196         self.msi_64bits = 0
197         self.num_msix_vectors = 0
198         self.msix_region_size = 0
199         self.msix_address = 0
200         for c in caps:
201             if c.id in (0x05, 0x11):
202                 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
203                 if c.id == 0x05:  # MSI
204                     self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
205                     self.msi_64bits = (msg_ctrl >> 7) & 1
206                 else:  # MSI-X
207                     vectors = (msg_ctrl & 0x7ff) + 1
208                     self.num_msix_vectors = vectors
209                     self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
210                     self.msix_address = c.msix_address
211
212     def __str__(self):
213         return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
214
215     def bdf(self):
216         return self.bus << 8 | self.dev << 3 | self.fn
217
218     @staticmethod
219     def parse_pcidevice_sysfsdir(basedir, dir):
220         dpath = os.path.join(basedir, dir)
221         dclass = input_readline(os.path.join(dpath, 'class'))
222         if re.match(r'0x0604..', dclass):
223             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
224         else:
225             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
226         a = dir.split(':')
227         domain = int(a[0], 16)
228         bus = int(a[1], 16)
229         df = a[2].split('.')
230         caps = PCICapability.parse_pcicaps(dpath)
231         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
232                          caps)
233
234
235 class MemRegion:
236     def __init__(self, start, stop, typestr, comments=None):
237         self.start = start
238         self.stop = stop
239         self.typestr = typestr
240         if comments is None:
241             self.comments = []
242         else:
243             self.comments = comments
244
245     def __str__(self):
246         return 'MemRegion: %08x-%08x : %s' % \
247             (self.start, self.stop, self.typestr)
248
249     def size(self):
250         # round up to full PAGE_SIZE
251         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
252
253     def flagstr(self, p=''):
254         if (
255             self.typestr == 'System RAM' or
256             self.typestr == 'RAM buffer' or
257             self.typestr == 'ACPI DMAR RMRR'
258         ):
259             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
260             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
261             return s
262         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
263
264
265 class IOMemRegionTree:
266     def __init__(self, region, level, linenum):
267         self.region = region
268         self.linenum = linenum
269         self.level = level
270         self.parent = None
271         self.children = set()
272
273     def __str__(self):
274         s = ''
275         if (self.region):
276             s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
277                 % (self.linenum)
278             if self.parent and self.parent.region:
279                 s += '--> ' + self.parent.region.typestr + ' line %d' \
280                     % (self.parent.linenum)
281             s += '\n'
282         for c in self.children:
283             s += str(c)
284         return s
285
286     @staticmethod
287     def parse_iomem_line(line):
288         a = line.split(':', 1)
289         level = int(a[0].count(' ') / 2) + 1
290         region = a[0].split('-', 1)
291         a[1] = a[1].strip()
292         return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
293
294     @staticmethod
295     def parse_iomem_file():
296         root = IOMemRegionTree(None, 0, -1)
297         f = input_open('/proc/iomem')
298         lastlevel = 0
299         lastnode = root
300         linenum = 0
301         for line in f:
302             (level, r) = IOMemRegionTree.parse_iomem_line(line)
303             t = IOMemRegionTree(r, level, linenum)
304             if (t.level > lastlevel):
305                 t.parent = lastnode
306             if (t.level == lastlevel):
307                 t.parent = lastnode.parent
308             if (t.level < lastlevel):
309                 p = lastnode.parent
310                 while(t.level < p.level):
311                     p = p.parent
312                 t.parent = p.parent
313
314             t.parent.children.add(t)
315             lastnode = t
316             lastlevel = t.level
317             linenum += 1
318         f.close()
319
320         return linenum, root
321
322     # recurse down the tree
323     @staticmethod
324     def parse_iomem_tree(tree):
325         regions = []
326         linenumbers = []
327
328         for tree in tree.children:
329             r = tree.region
330             s = r.typestr
331
332             # System RAM on first level will be added without digging deeper
333             if (tree.level == 1 and s == 'System RAM'):
334                 regions.append(r)
335                 linenumbers.append(tree.linenum)
336                 continue
337
338             # blacklisted on all levels
339             if (
340                 (s.find('PCI MMCONFIG') >= 0) or
341                 (s.find('APIC') >= 0) or  # covers both APIC and IOAPIC
342                 (s.find('dmar') >= 0)
343             ):
344                 continue
345
346             # generally blacklisted, unless we find an HPET right behind it
347             # on the next level
348             if (s == 'reserved'):
349                 for subtree in tree.children:
350                     r2 = subtree.region
351                     if (r2.typestr.find('HPET') >= 0):
352                         regions.append(r2)
353                         linenumbers.append(subtree.linenum)
354                 continue
355
356             # if the tree continues recurse further down ...
357             if (len(tree.children) > 0):
358                 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
359                 linenumbers.extend(ln2)
360                 regions.extend(r2)
361                 continue
362
363             # add all remaining leaves
364             regions.append(r)
365             linenumbers.append(tree.linenum)
366
367         return linenumbers, regions
368
369
370 def parse_iomem(pcidevices):
371     (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
372
373     # create a spare array so we can easiely keep the order from the file
374     regions = [None for x in range(maxsz)]
375
376     lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
377     i = 0
378     for l in lines:
379         regions[l] = regs[i]
380         i += 1
381
382     # now prepare a non-sparse array for a return value,
383     # also filtering out MSI-X pages
384     ret = []
385     for r in regions:
386         if r:
387             for d in pcidevices:
388                 if d.msix_address >= r.start and d.msix_address <= r.stop:
389                     if d.msix_address > r.start:
390                         head_r = MemRegion(r.start, d.msix_address - 1,
391                                            r.typestr, r.comments)
392                         ret.append(head_r)
393                     if d.msix_address + d.msix_region_size < r.stop:
394                         tail_r = MemRegion(d.msix_address + d.msix_region_size,
395                                            r.stop, r.typestr, r.comments)
396                         ret.append(tail_r)
397                     r = None
398                     break
399             if r:
400                 ret.append(r)
401
402     # newer Linux kernels will report the first page as reserved
403     # it is needed for CPU init so include it anyways
404     if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
405         ret[0].start = 0
406
407     return ret
408
409
410 def parse_pcidevices():
411     devices = []
412     caps = []
413     basedir = '/sys/bus/pci/devices'
414     list = input_listdir(basedir, ['*/class', '*/config'])
415     for dir in list:
416         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
417         if d is not None:
418             if len(d.caps) > 0:
419                 duplicate = False
420                 # look for duplicate capability patterns
421                 for d2 in devices:
422                     if d2.caps == d.caps:
423                         # reused existing capability list, but record all users
424                         d2.caps[0].comments.append(str(d))
425                         d.caps_start = d2.caps_start
426                         duplicate = True
427                         break
428                 if not duplicate:
429                     d.caps[0].comments.append(str(d))
430                     d.caps_start = len(caps)
431                     caps.extend(d.caps)
432             devices.append(d)
433     return (devices, caps)
434
435
436 def parse_cmdline():
437     line = input_readline('/proc/cmdline')
438     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
439                  '([0-9a-fA-FxX]+)([KMG]?).*',
440                  line)
441     if m is not None:
442         size = kmg_multiply(int(m.group(1), 0), m.group(2))
443         start = kmg_multiply(int(m.group(3), 0), m.group(4))
444         return [start, size]
445     return None
446
447
448 def alloc_mem(regions, size):
449     mem = [0, size]
450     for r in reversed(regions):
451         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
452             mem[0] = r.start
453             r.start += mem[1]
454             return mem
455     raise RuntimeError('failed to allocate memory')
456
457
458 def count_cpus():
459     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
460     count = 0
461     for f in list:
462         if re.match(r'cpu[0-9]+', f):
463             count += 1
464     return count
465
466
467 def parse_dmar_devscope(f):
468     (scope_type, scope_len, bus, dev, fn) = \
469         struct.unpack('<BBxxxBBB', f.read(8))
470     if scope_len != 8:
471         raise RuntimeError('Unsupported DMAR Device Scope Structure')
472     return (scope_type, scope_len, bus, dev, fn)
473
474
475 # parsing of DMAR ACPI Table
476 # see Intel VT-d Spec chapter 8
477 def parse_dmar(pcidevices):
478     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb', True)
479     if get_cpu_vendor() == 'AuthenticAMD':
480         print('WARNING: AMD IOMMU support is not implemented yet')
481         return [], 0, []
482     signature = f.read(4)
483     if signature != b'DMAR':
484         if options.generate_collector:
485             return [], 0, []
486         raise RuntimeError('DMAR: incorrect input file format %s' % signature)
487     (length,) = struct.unpack('<I', f.read(4))
488     f.seek(48)
489     length -= 48
490     units = []
491     regions = []
492     ioapic_id = 0
493
494     while length > 0:
495         offset = 0
496         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
497         offset += 4
498         length -= struct_len
499
500         # DMA Remapping Hardware Unit Definition
501         if struct_type == 0:
502             (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
503             if segment != 0:
504                 raise RuntimeError('We do not support multiple PCI segments')
505             if len(units) >= 8:
506                 raise RuntimeError('Too many DMAR units. '
507                                    'Raise JAILHOUSE_MAX_DMAR_UNITS.')
508             units.append(base)
509             if flags & 1:
510                 for d in pcidevices:
511                     if d.iommu == None:
512                         d.iommu = len(units) - 1
513             offset += 16 - offset
514             while offset < struct_len:
515                 (scope_type, scope_len, bus, dev, fn) =\
516                     parse_dmar_devscope(f)
517                 if scope_type == 1:
518                     for d in pcidevices:
519                         if d.bus == bus and d.dev == dev and d.fn == fn:
520                             d.iommu = len(units) - 1
521                 elif scope_type == 2:
522                     raise RuntimeError('Unsupported DMAR Device Scope type')
523                 elif scope_type == 3:
524                     if ioapic_id != 0:
525                         raise RuntimeError('We do not support more '
526                                            'than 1 IOAPIC')
527                     # encode the DMAR unit number into the device ID
528                     ioapic_id = ((len(units) - 1) << 16) | \
529                         (bus << 8) | (dev << 3) | fn
530                 offset += scope_len
531
532         # Reserved Memory Region Reporting Structure
533         if struct_type == 1:
534             f.seek(8 - offset, os.SEEK_CUR)
535             offset += 8 - offset
536             (base, limit) = struct.unpack('<QQ', f.read(16))
537             offset += 16
538
539             comments = []
540             while offset < struct_len:
541                 (scope_type, scope_len, bus, dev, fn) =\
542                     parse_dmar_devscope(f)
543                 if scope_type == 1:
544                     comments.append('PCI device: %02x:%02x.%x' %
545                                     (bus, dev, fn))
546                 else:
547                     comments.append('DMAR parser could not decode device path')
548                 offset += scope_len
549
550             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
551             regions.append(reg)
552
553         f.seek(struct_len - offset, os.SEEK_CUR)
554
555     return units, ioapic_id, regions
556
557
558 def parse_ioports():
559     pm_timer_base = None
560     f = input_open('/proc/ioports')
561     for line in f:
562         if line.endswith('ACPI PM_TMR\n'):
563             pm_timer_base = int(line.split('-')[0], 16)
564             break
565     f.close()
566     return pm_timer_base
567
568
569 class MMConfig:
570     def __init__(self, base, end_bus):
571         self.base = base
572         self.end_bus = end_bus
573
574     @staticmethod
575     def parse():
576         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
577         signature = f.read(4)
578         if signature != b'MCFG':
579             if options.generate_collector:
580                 return MMConfig(0, 0)
581             raise RuntimeError('MCFG: incorrect input file format %s' %
582                                signature)
583         (length,) = struct.unpack('<I', f.read(4))
584         if length > 60:
585             raise RuntimeError('Multiple MMCONFIG regions found! '
586                                'This is not supported')
587         f.seek(44)
588         (base, segment, start_bus, end_bus) = \
589             struct.unpack('<QHBB', f.read(12))
590         if segment != 0 or start_bus != 0:
591             raise RuntimeError('Invalid MCFG structure found')
592         return MMConfig(base, end_bus)
593
594
595 if (
596     (options.generate_collector is False) and (options.root is '/')
597     and (os.geteuid() is not 0)
598 ):
599     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
600     sys.exit(1)
601
602 def get_cpu_vendor():
603     with input_open('/proc/cpuinfo', 'r') as f:
604         for line in f:
605             if not line.strip():
606                 continue
607             key, value = line.split(':')
608             if key.strip() == 'vendor_id':
609                 return value.strip()
610
611
612 (pcidevices, pcicaps) = parse_pcidevices()
613
614 product = [input_readline('/sys/class/dmi/id/sys_vendor',
615                           True).rstrip(),
616            input_readline('/sys/class/dmi/id/product_name',
617                           True).rstrip()
618            ]
619
620 inmatemem = kmg_multiply_str(options.mem_inmates)
621 hvmem = [0, kmg_multiply_str(options.mem_hv)]
622
623 regions = parse_iomem(pcidevices)
624 ourmem = parse_cmdline()
625 total = hvmem[1] + inmatemem
626
627 mmconfig = MMConfig.parse()
628
629 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar(pcidevices)
630 regions += rmrr_regs
631
632 for d in pcidevices:
633     if get_cpu_vendor() == 'AuthenticAMD':
634         d.iommu = 0  # temporary workaround
635     if d.iommu == None:
636         raise RuntimeError('PCI device %02x:%02x.%x outside the scope of an '
637                            'IOMMU' % (d.bus, d.dev, d.fn))
638
639 # kernel does not have memmap region, pick one
640 if ourmem is None:
641     ourmem = alloc_mem(regions, total)
642 elif (total > ourmem[1]):
643     raise RuntimeError('Your memmap reservation is too small you need >="' +
644                        hex(total) + '"')
645
646 hvmem[0] = ourmem[0]
647
648 inmatereg = MemRegion(ourmem[0] + hvmem[1],
649                       ourmem[0] + hvmem[1] + inmatemem - 1,
650                       'JAILHOUSE Inmate Memory')
651 regions.append(inmatereg)
652
653 cpucount = count_cpus()
654
655 pm_timer_base = parse_ioports()
656
657 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
658                             True).rstrip()
659 if options.generate_collector is False and jh_enabled == '1':
660     print('ERROR: Jailhouse was enabled when collecting input files! '
661           'Disable jailhouse and try again.',
662           file=sys.stderr)
663     sys.exit(1)
664
665 f = open(options.file, 'w')
666
667 if options.generate_collector:
668     filelist = ' '.join(inputs['files'].union(inputs['dirs']))
669     filelist_opt = ' '.join(inputs['files_opt'])
670
671     tmpl = Template(filename=os.path.join(options.template_dir,
672                                           'jailhouse-config-collect.tmpl'))
673     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
674 else:
675     tmpl = Template(filename=os.path.join(options.template_dir,
676                                           'root-cell-config.c.tmpl'))
677     f.write(tmpl.render(regions=regions,
678                         ourmem=ourmem,
679                         argstr=' '.join(sys.argv),
680                         hvmem=hvmem,
681                         product=product,
682                         pcidevices=pcidevices,
683                         pcicaps=pcicaps,
684                         cpucount=cpucount,
685                         ioapic_id=ioapic_id,
686                         pm_timer_base=pm_timer_base,
687                         mmconfig=mmconfig,
688                         dmar_units=dmar_units))
689
690 f.close()