]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
configs/tools: Exclude MSI-X table from memory regions
[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.domain = domain
188         self.bus = bus
189         self.dev = dev
190         self.fn = fn
191         self.caps = caps
192         self.caps_start = 0
193         self.num_caps = len(caps)
194         self.num_msi_vectors = 0
195         self.msi_64bits = 0
196         self.num_msix_vectors = 0
197         self.msix_region_size = 0
198         self.msix_address = 0
199         for c in caps:
200             if c.id in (0x05, 0x11):
201                 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
202                 if c.id == 0x05:  # MSI
203                     self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
204                     self.msi_64bits = (msg_ctrl >> 7) & 1
205                 else:  # MSI-X
206                     vectors = (msg_ctrl & 0x7ff) + 1
207                     self.num_msix_vectors = vectors
208                     self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
209                     self.msix_address = c.msix_address
210
211     def __str__(self):
212         return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
213
214     def bdf(self):
215         return self.bus << 8 | self.dev << 3 | self.fn
216
217     @staticmethod
218     def parse_pcidevice_sysfsdir(basedir, dir):
219         dpath = os.path.join(basedir, dir)
220         dclass = input_readline(os.path.join(dpath, 'class'))
221         if re.match(r'0x0604..', dclass):
222             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
223         else:
224             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
225         a = dir.split(':')
226         domain = int(a[0], 16)
227         bus = int(a[1], 16)
228         df = a[2].split('.')
229         caps = PCICapability.parse_pcicaps(dpath)
230         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
231                          caps)
232
233
234 class MemRegion:
235     def __init__(self, start, stop, typestr, comments=None):
236         self.start = start
237         self.stop = stop
238         self.typestr = typestr
239         if comments is None:
240             self.comments = []
241         else:
242             self.comments = comments
243
244     def __str__(self):
245         return 'MemRegion: %08x-%08x : %s' % \
246             (self.start, self.stop, self.typestr)
247
248     def size(self):
249         # round up to full PAGE_SIZE
250         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
251
252     def flagstr(self, p=''):
253         if (
254             self.typestr == 'System RAM' or
255             self.typestr == 'RAM buffer' or
256             self.typestr == 'ACPI DMAR RMRR'
257         ):
258             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
259             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
260             return s
261         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
262
263
264 class IOMemRegionTree:
265     def __init__(self, region, level, linenum):
266         self.region = region
267         self.linenum = linenum
268         self.level = level
269         self.parent = None
270         self.children = set()
271
272     def __str__(self):
273         s = ''
274         if (self.region):
275             s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
276                 % (self.linenum)
277             if self.parent and self.parent.region:
278                 s += '--> ' + self.parent.region.typestr + ' line %d' \
279                     % (self.parent.linenum)
280             s += '\n'
281         for c in self.children:
282             s += str(c)
283         return s
284
285     @staticmethod
286     def parse_iomem_line(line):
287         a = line.split(':', 1)
288         level = int(a[0].count(' ') / 2) + 1
289         region = a[0].split('-', 1)
290         a[1] = a[1].strip()
291         return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
292
293     @staticmethod
294     def parse_iomem_file():
295         root = IOMemRegionTree(None, 0, -1)
296         f = input_open('/proc/iomem')
297         lastlevel = 0
298         lastnode = root
299         linenum = 0
300         for line in f:
301             (level, r) = IOMemRegionTree.parse_iomem_line(line)
302             t = IOMemRegionTree(r, level, linenum)
303             if (t.level > lastlevel):
304                 t.parent = lastnode
305             if (t.level == lastlevel):
306                 t.parent = lastnode.parent
307             if (t.level < lastlevel):
308                 p = lastnode.parent
309                 while(t.level < p.level):
310                     p = p.parent
311                 t.parent = p.parent
312
313             t.parent.children.add(t)
314             lastnode = t
315             lastlevel = t.level
316             linenum += 1
317         f.close()
318
319         return linenum, root
320
321     # recurse down the tree
322     @staticmethod
323     def parse_iomem_tree(tree):
324         regions = []
325         linenumbers = []
326
327         for tree in tree.children:
328             r = tree.region
329             s = r.typestr
330
331             # System RAM on first level will be added without digging deeper
332             if (tree.level == 1 and s == 'System RAM'):
333                 regions.append(r)
334                 linenumbers.append(tree.linenum)
335                 continue
336
337             # blacklisted on all levels
338             if (
339                 (s.find('PCI MMCONFIG') >= 0) or
340                 (s.find('APIC') >= 0) or  # covers both APIC and IOAPIC
341                 (s.find('dmar') >= 0)
342             ):
343                 continue
344
345             # generally blacklisted, unless we find an HPET right behind it
346             # on the next level
347             if (s == 'reserved'):
348                 for subtree in tree.children:
349                     r2 = subtree.region
350                     if (r2.typestr.find('HPET') >= 0):
351                         regions.append(r2)
352                         linenumbers.append(subtree.linenum)
353                 continue
354
355             # if the tree continues recurse further down ...
356             if (len(tree.children) > 0):
357                 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
358                 linenumbers.extend(ln2)
359                 regions.extend(r2)
360                 continue
361
362             # add all remaining leaves
363             regions.append(r)
364             linenumbers.append(tree.linenum)
365
366         return linenumbers, regions
367
368
369 def parse_iomem(pcidevices):
370     (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
371
372     # create a spare array so we can easiely keep the order from the file
373     regions = [None for x in range(maxsz)]
374
375     lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
376     i = 0
377     for l in lines:
378         regions[l] = regs[i]
379         i += 1
380
381     # now prepare a non-sparse array for a return value,
382     # also filtering out MSI-X pages
383     ret = []
384     for r in regions:
385         if r:
386             for d in pcidevices:
387                 if d.msix_address >= r.start and d.msix_address <= r.stop:
388                     if d.msix_address > r.start:
389                         head_r = MemRegion(r.start, d.msix_address - 1,
390                                            r.typestr, r.comments)
391                         ret.append(head_r)
392                     if d.msix_address + d.msix_region_size < r.stop:
393                         tail_r = MemRegion(d.msix_address + d.msix_region_size,
394                                            r.stop, r.typestr, r.comments)
395                         ret.append(tail_r)
396                     r = None
397                     break
398             if r:
399                 ret.append(r)
400
401     # newer Linux kernels will report the first page as reserved
402     # it is needed for CPU init so include it anyways
403     if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
404         ret[0].start = 0
405
406     return ret
407
408
409 def parse_pcidevices():
410     devices = []
411     caps = []
412     basedir = '/sys/bus/pci/devices'
413     list = input_listdir(basedir, ['*/class', '*/config'])
414     for dir in list:
415         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
416         if d is not None:
417             if len(d.caps) > 0:
418                 duplicate = False
419                 # look for duplicate capability patterns
420                 for d2 in devices:
421                     if d2.caps == d.caps:
422                         # reused existing capability list, but record all users
423                         d2.caps[0].comments.append(str(d))
424                         d.caps_start = d2.caps_start
425                         duplicate = True
426                         break
427                 if not duplicate:
428                     d.caps[0].comments.append(str(d))
429                     d.caps_start = len(caps)
430                     caps.extend(d.caps)
431             devices.append(d)
432     return (devices, caps)
433
434
435 def parse_cmdline():
436     line = input_readline('/proc/cmdline')
437     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
438                  '([0-9a-fA-FxX]+)([KMG]?).*',
439                  line)
440     if m is not None:
441         size = kmg_multiply(int(m.group(1), 0), m.group(2))
442         start = kmg_multiply(int(m.group(3), 0), m.group(4))
443         return [start, size]
444     return None
445
446
447 def alloc_mem(regions, size):
448     mem = [0, size]
449     for r in reversed(regions):
450         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
451             mem[0] = r.start
452             r.start += mem[1]
453             return mem
454     raise RuntimeError('failed to allocate memory')
455
456
457 def count_cpus():
458     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
459     count = 0
460     for f in list:
461         if re.match(r'cpu[0-9]+', f):
462             count += 1
463     return count
464
465
466 def parse_dmar_devscope(f):
467     (scope_type, scope_len, bus, dev, fn) = \
468         struct.unpack('<BBxxxBBB', f.read(8))
469     if scope_len != 8:
470         raise RuntimeError('Unsupported DMAR Device Scope Structure')
471     return (scope_type, scope_len, bus, dev, fn)
472
473
474 # parsing of DMAR ACPI Table
475 # see Intel VT-d Spec chapter 8
476 def parse_dmar():
477     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb', True)
478     if get_cpu_vendor() == 'AuthenticAMD':
479         print('WARNING: AMD IOMMU support is not implemented yet')
480         return [], 0, []
481     signature = f.read(4)
482     if signature != b'DMAR':
483         if options.generate_collector:
484             return [], 0, []
485         raise RuntimeError('DMAR: incorrect input file format %s' % signature)
486     (length,) = struct.unpack('<I', f.read(4))
487     f.seek(48)
488     length -= 48
489     units = []
490     regions = []
491     ioapic_id = 0
492
493     while length > 0:
494         offset = 0
495         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
496         offset += 4
497         length -= struct_len
498
499         # DMA Remapping Hardware Unit Definition
500         if struct_type == 0:
501             (segment, base) = struct.unpack('<xxHQ', f.read(12))
502             if segment != 0:
503                 raise RuntimeError('We do not support multiple PCI segments')
504             if len(units) >= 8:
505                 raise RuntimeError('Too many DMAR units. '
506                                    'Raise JAILHOUSE_MAX_DMAR_UNITS.')
507             units.append(base)
508             offset += 16 - offset
509             while offset < struct_len:
510                 (scope_type, scope_len, bus, dev, fn) =\
511                     parse_dmar_devscope(f)
512                 if scope_type == 3:
513                     if ioapic_id != 0:
514                         raise RuntimeError('We do not support more '
515                                            'than 1 IOAPIC')
516                     ioapic_id = (bus << 8) | (dev << 3) | fn
517                 offset += scope_len
518
519         # Reserved Memory Region Reporting Structure
520         if struct_type == 1:
521             f.seek(8 - offset, os.SEEK_CUR)
522             offset += 8 - offset
523             (base, limit) = struct.unpack('<QQ', f.read(16))
524             offset += 16
525
526             comments = []
527             while offset < struct_len:
528                 (scope_type, scope_len, bus, dev, fn) =\
529                     parse_dmar_devscope(f)
530                 if scope_type == 1:
531                     comments.append('PCI device: %02x:%02x.%x' %
532                                     (bus, dev, fn))
533                 else:
534                     comments.append('DMAR parser could not decode device path')
535                 offset += scope_len
536
537             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
538             regions.append(reg)
539
540         f.seek(struct_len - offset, os.SEEK_CUR)
541
542     return units, ioapic_id, regions
543
544
545 def parse_ioports():
546     pm_timer_base = None
547     f = input_open('/proc/ioports')
548     for line in f:
549         if line.endswith('ACPI PM_TMR\n'):
550             pm_timer_base = int(line.split('-')[0], 16)
551             break
552     f.close()
553     return pm_timer_base
554
555
556 class MMConfig:
557     def __init__(self, base, end_bus):
558         self.base = base
559         self.end_bus = end_bus
560
561     @staticmethod
562     def parse():
563         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
564         signature = f.read(4)
565         if signature != b'MCFG':
566             if options.generate_collector:
567                 return MMConfig(0, 0)
568             raise RuntimeError('MCFG: incorrect input file format %s' %
569                                signature)
570         (length,) = struct.unpack('<I', f.read(4))
571         if length > 60:
572             raise RuntimeError('Multiple MMCONFIG regions found! '
573                                'This is not supported')
574         f.seek(44)
575         (base, segment, start_bus, end_bus) = \
576             struct.unpack('<QHBB', f.read(12))
577         if segment != 0 or start_bus != 0:
578             raise RuntimeError('Invalid MCFG structure found')
579         return MMConfig(base, end_bus)
580
581
582 if (
583     (options.generate_collector is False) and (options.root is '/')
584     and (os.geteuid() is not 0)
585 ):
586     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
587     sys.exit(1)
588
589 def get_cpu_vendor():
590     with input_open('/proc/cpuinfo', 'r') as f:
591         for line in f:
592             if not line.strip():
593                 continue
594             key, value = line.split(':')
595             if key.strip() == 'vendor_id':
596                 return value.strip()
597
598
599 (pcidevices, pcicaps) = parse_pcidevices()
600
601 product = [input_readline('/sys/class/dmi/id/sys_vendor',
602                           True).rstrip(),
603            input_readline('/sys/class/dmi/id/product_name',
604                           True).rstrip()
605            ]
606
607 inmatemem = kmg_multiply_str(options.mem_inmates)
608 hvmem = [0, kmg_multiply_str(options.mem_hv)]
609
610 regions = parse_iomem(pcidevices)
611 ourmem = parse_cmdline()
612 total = hvmem[1] + inmatemem
613
614 mmconfig = MMConfig.parse()
615
616 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar()
617 regions += rmrr_regs
618
619 # kernel does not have memmap region, pick one
620 if ourmem is None:
621     ourmem = alloc_mem(regions, total)
622 elif (total > ourmem[1]):
623     raise RuntimeError('Your memmap reservation is too small you need >="' +
624                        hex(total) + '"')
625
626 hvmem[0] = ourmem[0]
627
628 inmatereg = MemRegion(ourmem[0] + hvmem[1],
629                       ourmem[0] + hvmem[1] + inmatemem - 1,
630                       'JAILHOUSE Inmate Memory')
631 regions.append(inmatereg)
632
633 cpucount = count_cpus()
634
635 pm_timer_base = parse_ioports()
636
637 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
638                             True).rstrip()
639 if options.generate_collector is False and jh_enabled == '1':
640     print('ERROR: Jailhouse was enabled when collecting input files! '
641           'Disable jailhouse and try again.',
642           file=sys.stderr)
643     sys.exit(1)
644
645 f = open(options.file, 'w')
646
647 if options.generate_collector:
648     filelist = ' '.join(inputs['files'].union(inputs['dirs']))
649     filelist_opt = ' '.join(inputs['files_opt'])
650
651     tmpl = Template(filename=os.path.join(options.template_dir,
652                                           'jailhouse-config-collect.tmpl'))
653     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
654 else:
655     tmpl = Template(filename=os.path.join(options.template_dir,
656                                           'root-cell-config.c.tmpl'))
657     f.write(tmpl.render(regions=regions,
658                         ourmem=ourmem,
659                         argstr=' '.join(sys.argv),
660                         hvmem=hvmem,
661                         product=product,
662                         pcidevices=pcidevices,
663                         pcicaps=pcicaps,
664                         cpucount=cpucount,
665                         ioapic_id=ioapic_id,
666                         pm_timer_base=pm_timer_base,
667                         mmconfig=mmconfig,
668                         dmar_units=dmar_units))
669
670 f.close()