]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
tools: config-create: Place hypervisor and inmates at default addresses
[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 = [0x3b000000, size]
450     for r in regions:
451         if (
452             r.typestr == 'System RAM' and
453             r.start <= mem[0] and
454             r.stop + 1 >= mem[0] + mem[1]
455            ):
456             if r.start < mem[0]:
457                 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
458                 regions.insert(regions.index(r), head_r)
459             if r.stop + 1 > mem[0] + mem[1]:
460                 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
461                                    r.comments)
462                 regions.insert(regions.index(r), tail_r)
463             regions.remove(r)
464             return mem
465     for r in reversed(regions):
466         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
467             mem[0] = r.start
468             r.start += mem[1]
469             return mem
470     raise RuntimeError('failed to allocate memory')
471
472
473 def count_cpus():
474     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
475     count = 0
476     for f in list:
477         if re.match(r'cpu[0-9]+', f):
478             count += 1
479     return count
480
481
482 def parse_dmar_devscope(f):
483     (scope_type, scope_len, bus, dev, fn) = \
484         struct.unpack('<BBxxxBBB', f.read(8))
485     if scope_len != 8:
486         raise RuntimeError('Unsupported DMAR Device Scope Structure')
487     return (scope_type, scope_len, bus, dev, fn)
488
489
490 # parsing of DMAR ACPI Table
491 # see Intel VT-d Spec chapter 8
492 def parse_dmar(pcidevices):
493     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb', True)
494     if get_cpu_vendor() == 'AuthenticAMD':
495         print('WARNING: AMD IOMMU support is not implemented yet')
496         return [], 0, []
497     signature = f.read(4)
498     if signature != b'DMAR':
499         if options.generate_collector:
500             return [], 0, []
501         raise RuntimeError('DMAR: incorrect input file format %s' % signature)
502     (length,) = struct.unpack('<I', f.read(4))
503     f.seek(48)
504     length -= 48
505     units = []
506     regions = []
507     ioapic_id = 0
508
509     while length > 0:
510         offset = 0
511         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
512         offset += 4
513         length -= struct_len
514
515         # DMA Remapping Hardware Unit Definition
516         if struct_type == 0:
517             (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
518             if segment != 0:
519                 raise RuntimeError('We do not support multiple PCI segments')
520             if len(units) >= 8:
521                 raise RuntimeError('Too many DMAR units. '
522                                    'Raise JAILHOUSE_MAX_DMAR_UNITS.')
523             units.append(base)
524             if flags & 1:
525                 for d in pcidevices:
526                     if d.iommu == None:
527                         d.iommu = len(units) - 1
528             offset += 16 - offset
529             while offset < struct_len:
530                 (scope_type, scope_len, bus, dev, fn) =\
531                     parse_dmar_devscope(f)
532                 if scope_type == 1:
533                     for d in pcidevices:
534                         if d.bus == bus and d.dev == dev and d.fn == fn:
535                             d.iommu = len(units) - 1
536                 elif scope_type == 2:
537                     raise RuntimeError('Unsupported DMAR Device Scope type')
538                 elif scope_type == 3:
539                     if ioapic_id != 0:
540                         raise RuntimeError('We do not support more '
541                                            'than 1 IOAPIC')
542                     # encode the DMAR unit number into the device ID
543                     ioapic_id = ((len(units) - 1) << 16) | \
544                         (bus << 8) | (dev << 3) | fn
545                 offset += scope_len
546
547         # Reserved Memory Region Reporting Structure
548         if struct_type == 1:
549             f.seek(8 - offset, os.SEEK_CUR)
550             offset += 8 - offset
551             (base, limit) = struct.unpack('<QQ', f.read(16))
552             offset += 16
553
554             comments = []
555             while offset < struct_len:
556                 (scope_type, scope_len, bus, dev, fn) =\
557                     parse_dmar_devscope(f)
558                 if scope_type == 1:
559                     comments.append('PCI device: %02x:%02x.%x' %
560                                     (bus, dev, fn))
561                 else:
562                     comments.append('DMAR parser could not decode device path')
563                 offset += scope_len
564
565             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
566             regions.append(reg)
567
568         f.seek(struct_len - offset, os.SEEK_CUR)
569
570     return units, ioapic_id, regions
571
572
573 def parse_ioports():
574     pm_timer_base = None
575     f = input_open('/proc/ioports')
576     for line in f:
577         if line.endswith('ACPI PM_TMR\n'):
578             pm_timer_base = int(line.split('-')[0], 16)
579             break
580     f.close()
581     return pm_timer_base
582
583
584 class MMConfig:
585     def __init__(self, base, end_bus):
586         self.base = base
587         self.end_bus = end_bus
588
589     @staticmethod
590     def parse():
591         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
592         signature = f.read(4)
593         if signature != b'MCFG':
594             if options.generate_collector:
595                 return MMConfig(0, 0)
596             raise RuntimeError('MCFG: incorrect input file format %s' %
597                                signature)
598         (length,) = struct.unpack('<I', f.read(4))
599         if length > 60:
600             raise RuntimeError('Multiple MMCONFIG regions found! '
601                                'This is not supported')
602         f.seek(44)
603         (base, segment, start_bus, end_bus) = \
604             struct.unpack('<QHBB', f.read(12))
605         if segment != 0 or start_bus != 0:
606             raise RuntimeError('Invalid MCFG structure found')
607         return MMConfig(base, end_bus)
608
609
610 if (
611     (options.generate_collector is False) and (options.root is '/')
612     and (os.geteuid() is not 0)
613 ):
614     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
615     sys.exit(1)
616
617 def get_cpu_vendor():
618     with input_open('/proc/cpuinfo', 'r') as f:
619         for line in f:
620             if not line.strip():
621                 continue
622             key, value = line.split(':')
623             if key.strip() == 'vendor_id':
624                 return value.strip()
625
626
627 (pcidevices, pcicaps) = parse_pcidevices()
628
629 product = [input_readline('/sys/class/dmi/id/sys_vendor',
630                           True).rstrip(),
631            input_readline('/sys/class/dmi/id/product_name',
632                           True).rstrip()
633            ]
634
635 inmatemem = kmg_multiply_str(options.mem_inmates)
636 hvmem = [0, kmg_multiply_str(options.mem_hv)]
637
638 regions = parse_iomem(pcidevices)
639 ourmem = parse_cmdline()
640 total = hvmem[1] + inmatemem
641
642 mmconfig = MMConfig.parse()
643
644 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar(pcidevices)
645 regions += rmrr_regs
646
647 for d in pcidevices:
648     if get_cpu_vendor() == 'AuthenticAMD':
649         d.iommu = 0  # temporary workaround
650     if d.iommu == None:
651         raise RuntimeError('PCI device %02x:%02x.%x outside the scope of an '
652                            'IOMMU' % (d.bus, d.dev, d.fn))
653
654 # kernel does not have memmap region, pick one
655 if ourmem is None:
656     ourmem = alloc_mem(regions, total)
657 elif (total > ourmem[1]):
658     raise RuntimeError('Your memmap reservation is too small you need >="' +
659                        hex(total) + '"')
660
661 hvmem[0] = ourmem[0]
662
663 inmatereg = MemRegion(ourmem[0] + hvmem[1],
664                       ourmem[0] + hvmem[1] + inmatemem - 1,
665                       'JAILHOUSE Inmate Memory')
666 regions.append(inmatereg)
667
668 cpucount = count_cpus()
669
670 pm_timer_base = parse_ioports()
671
672 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
673                             True).rstrip()
674 if options.generate_collector is False and jh_enabled == '1':
675     print('ERROR: Jailhouse was enabled when collecting input files! '
676           'Disable jailhouse and try again.',
677           file=sys.stderr)
678     sys.exit(1)
679
680 f = open(options.file, 'w')
681
682 if options.generate_collector:
683     filelist = ' '.join(inputs['files'].union(inputs['dirs']))
684     filelist_opt = ' '.join(inputs['files_opt'])
685
686     tmpl = Template(filename=os.path.join(options.template_dir,
687                                           'jailhouse-config-collect.tmpl'))
688     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
689 else:
690     tmpl = Template(filename=os.path.join(options.template_dir,
691                                           'root-cell-config.c.tmpl'))
692     f.write(tmpl.render(regions=regions,
693                         ourmem=ourmem,
694                         argstr=' '.join(sys.argv),
695                         hvmem=hvmem,
696                         product=product,
697                         pcidevices=pcidevices,
698                         pcicaps=pcicaps,
699                         cpucount=cpucount,
700                         ioapic_id=ioapic_id,
701                         pm_timer_base=pm_timer_base,
702                         mmconfig=mmconfig,
703                         dmar_units=dmar_units))
704
705 f.close()