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