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