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