]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
tools: config-create: Exclude DMAR units from memory regions
[jailhouse.git] / tools / jailhouse-config-create
1 #!/usr/bin/env python
2 #
3 # Jailhouse, a Linux-based partitioning hypervisor
4 #
5 # Copyright (c) Siemens AG, 2014
6 #
7 # This work is licensed under the terms of the GNU GPL, version 2.  See
8 # the COPYING file in the top-level directory.
9 #
10 # This script should help to create a basic jailhouse configuration file.
11 # It needs to be executed on the target machine, where it will gather
12 # information about the system. For more advanced scenarios you will have
13 # to change the generated C-code.
14
15 from __future__ import print_function
16 import sys
17 import os
18 import re
19 import argparse
20 import struct
21 from mako.template import Template
22
23 abspath = os.path.abspath(os.path.dirname(sys.argv[0]))
24
25 # pretend to be part of the jailhouse tool
26 sys.argv[0] = sys.argv[0].replace('-', ' ')
27
28 parser = argparse.ArgumentParser()
29 parser.add_argument('-g', '--generate-collector',
30                     help='generate a script to collect input files on '
31                          'a remote machine',
32                     action='store_true')
33 parser.add_argument('-r', '--root',
34                     help='gather information in ROOT/, the default is "/" '
35                          'which means creating a config for localhost',
36                     default='/',
37                     action='store',
38                     type=str)
39 parser.add_argument('-t', '--template-dir',
40                     help='the directory where the templates are located,'
41                          'the default is "' + abspath + '"',
42                     default=abspath,
43                     action='store',
44                     type=str)
45
46 memargs = [['--mem-inmates', '2M', 'inmate'],
47            ['--mem-hv', '64M', 'hypervisor']]
48
49 for entry in memargs:
50     parser.add_argument(entry[0],
51                         help='the amount of ' + entry[2] +
52                              ' memory, default is "' + entry[1] +
53                              '", format "xxx[K|M|G]"',
54                         default=entry[1],
55                         action='store',
56                         type=str)
57
58 parser.add_argument('file', metavar='FILE',
59                     help='name of file to write out',
60                     type=str)
61
62 options = parser.parse_args()
63
64 inputs = {'files': set(), 'files_opt': set(), 'dirs': set()}
65
66
67 class PCICapability:
68     def __init__(self, id, start, len, flags):
69         self.id = id
70         self.start = start
71         self.len = len
72         self.flags = flags
73         self.comments = []
74
75     def __eq__(self, other):
76         return self.id == other.id and self.start == other.start and \
77             self.len == other.len and self.flags == other.flags
78
79     RD = '0'
80     RW = 'JAILHOUSE_PCICAPS_WRITE'
81
82     @staticmethod
83     def parse_pcicaps(dir):
84         caps = []
85         f = input_open(os.path.join(dir, 'config'), 'rb')
86         f.seek(0x06)
87         (status,) = struct.unpack('<H', f.read(2))
88         # capability list supported?
89         if (status & (1 << 4)) == 0:
90             f.close()
91             return caps
92         # walk capability list
93         f.seek(0x34)
94         (next,) = struct.unpack('B', f.read(1))
95         while next != 0:
96             cap = next
97             f.seek(cap)
98             (id, next) = struct.unpack('<BB', f.read(2))
99             if id == 0x01:  # Power Management
100                 # this cap can be handed out completely
101                 len = 8
102                 flags = PCICapability.RW
103             elif id == 0x05:  # MSI
104                 # access will be moderated by hypervisor
105                 len = 10
106                 (msgctl,) = struct.unpack('<H', f.read(2))
107                 if (msgctl & (1 << 7)) != 0:  # 64-bit support
108                     len += 4
109                 if (msgctl & (1 << 8)) != 0:  # per-vector masking support
110                     len += 10
111                 flags = PCICapability.RW
112             elif id == 0x11:  # MSI-X
113                 # access will be moderated by hypervisor
114                 len = 12
115                 flags = PCICapability.RW
116             else:
117                 # unknown/unhandled cap, mark its existence
118                 len = 2
119                 flags = PCICapability.RD
120             caps.append(PCICapability(id, cap, len, flags))
121         return caps
122
123
124 class PCIDevice:
125     def __init__(self, type, domain, bus, dev, fn, caps):
126         self.type = type
127         self.domain = domain
128         self.bus = bus
129         self.dev = dev
130         self.fn = fn
131         self.caps = caps
132         self.caps_start = 0
133         self.num_caps = len(caps)
134
135     def __str__(self):
136         return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
137
138     def bdf(self):
139         return self.bus << 8 | self.dev << 3 | self.fn
140
141     @staticmethod
142     def parse_pcidevice_sysfsdir(basedir, dir):
143         dpath = os.path.join(basedir, dir)
144         dclass = input_readline(os.path.join(dpath, 'class'))
145         if re.match(r'0x0604..', dclass):
146             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
147         else:
148             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
149         a = dir.split(':')
150         domain = int(a[0], 16)
151         bus = int(a[1], 16)
152         df = a[2].split('.')
153         caps = PCICapability.parse_pcicaps(dpath)
154         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
155                          caps)
156
157
158 class MemRegion:
159     def __init__(self, start, stop, typestr, comments=None):
160         self.start = start
161         self.stop = stop
162         self.typestr = typestr
163         if comments is None:
164             self.comments = []
165         else:
166             self.comments = comments
167
168     def __str__(self):
169         return 'MemRegion: %08x-%08x : %s' % \
170             (self.start, self.stop, self.typestr)
171
172     def size(self):
173         # round up to full PAGE_SIZE
174         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
175
176     def flagstr(self, p=''):
177         if (
178             self.typestr == 'ACPI Tables' or
179             self.typestr == 'ACPI Non-volatile Storage'
180         ):
181             return 'JAILHOUSE_MEM_READ'
182         if (
183             self.typestr == 'System RAM' or
184             self.typestr == 'RAM buffer' or
185             self.typestr == 'ACPI DMAR RMRR'
186         ):
187             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
188             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
189             return s
190         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
191
192
193 class IOMemRegionTree:
194     def __init__(self, region, level, linenum):
195         self.region = region
196         self.linenum = linenum
197         self.level = level
198         self.parent = None
199         self.children = set()
200
201     def __str__(self):
202         s = ''
203         if (self.region):
204             s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
205                 % (self.linenum)
206             if self.parent and self.parent.region:
207                 s += '--> ' + self.parent.region.typestr + ' line %d' \
208                     % (self.parent.linenum)
209             s += '\n'
210         for c in self.children:
211             s += str(c)
212         return s
213
214     @staticmethod
215     def parse_iomem_line(line):
216         a = line.split(':', 1)
217         level = int(a[0].count(' ') / 2) + 1
218         region = a[0].split('-', 1)
219         a[1] = a[1].strip()
220         return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
221
222     @staticmethod
223     def parse_iomem_file():
224         root = IOMemRegionTree(None, 0, -1)
225         f = input_open('/proc/iomem')
226         lastlevel = 0
227         lastnode = root
228         linenum = 0
229         for line in f:
230             (level, r) = IOMemRegionTree.parse_iomem_line(line)
231             t = IOMemRegionTree(r, level, linenum)
232             if (t.level > lastlevel):
233                 t.parent = lastnode
234             if (t.level == lastlevel):
235                 t.parent = lastnode.parent
236             if (t.level < lastlevel):
237                 p = lastnode.parent
238                 while(t.level < p.level):
239                     p = p.parent
240                 t.parent = p.parent
241
242             t.parent.children.add(t)
243             lastnode = t
244             lastlevel = t.level
245             linenum += 1
246         f.close()
247
248         return linenum, root
249
250     # recurse down the tree
251     @staticmethod
252     def parse_iomem_tree(tree):
253         regions = []
254         linenumbers = []
255
256         for tree in tree.children:
257             r = tree.region
258             s = r.typestr
259
260             # System RAM on first level will be added without digging deeper
261             if (tree.level == 1 and s == 'System RAM'):
262                 regions.append(r)
263                 linenumbers.append(tree.linenum)
264                 continue
265
266             # blacklisted on all levels
267             if (
268                 (s.find('PCI MMCONFIG') >= 0) or
269                 (s.find('APIC') >= 0) or  # covers both APIC and IOAPIC
270                 (s.find('dmar') >= 0)
271             ):
272                 continue
273
274             # generally blacklisted, unless we find an HPET right behind it
275             # on the next level
276             if (s == 'reserved'):
277                 for subtree in tree.children:
278                     r2 = subtree.region
279                     if (r2.typestr.find('HPET') >= 0):
280                         regions.append(r2)
281                         linenumbers.append(subtree.linenum)
282                 continue
283
284             # if the tree continues recurse further down ...
285             if (len(tree.children) > 0):
286                 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
287                 linenumbers.extend(ln2)
288                 regions.extend(r2)
289                 continue
290
291             # add all remaining leaves
292             regions.append(r)
293             linenumbers.append(tree.linenum)
294
295         return linenumbers, regions
296
297
298 def parse_iomem():
299     (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
300
301     # create a spare array so we can easiely keep the order from the file
302     regions = [None for x in range(maxsz)]
303
304     lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
305     i = 0
306     for l in lines:
307         regions[l] = regs[i]
308         i += 1
309
310     # now prepare a non-sparse array for a return value
311     ret = []
312     for r in regions:
313         if r:
314             ret.append(r)
315
316     # newer Linux kernels will report the first page as reserved
317     # it is needed for CPU init so include it anyways
318     if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
319         ret[0].start = 0
320
321     return ret
322
323
324 def parse_pcidevices():
325     devices = []
326     caps = []
327     basedir = '/sys/bus/pci/devices'
328     list = input_listdir(basedir, ['*/class', '*/config'])
329     for dir in list:
330         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
331         if d is not None:
332             if len(d.caps) > 0:
333                 duplicate = False
334                 # look for duplicate capability patterns
335                 for d2 in devices:
336                     if d2.caps == d.caps:
337                         # reused existing capability list, but record all users
338                         d2.caps[0].comments.append(str(d))
339                         d.caps_start = d2.caps_start
340                         duplicate = True
341                         break
342                 if not duplicate:
343                     d.caps[0].comments.append(str(d))
344                     d.caps_start = len(caps)
345                     caps.extend(d.caps)
346             devices.append(d)
347     return (devices, caps)
348
349
350 def kmg_multiply(value, kmg):
351     if (kmg == 'K' or kmg == 'k'):
352         return 1024 * value
353     if (kmg == 'M' or kmg == 'm'):
354         return 1024**2 * value
355     if (kmg == 'G' or kmg == 'g'):
356         return 1024**3 * value
357     return value
358
359
360 def kmg_multiply_str(str):
361     m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
362     if m is not None:
363         return kmg_multiply(int(m.group(1)), m.group(2))
364     raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
365     return 0
366
367
368 def input_open(name, mode='r', optional=False):
369     inputs['files_opt' if optional else 'files'].add(name)
370     try:
371         f = open(options.root + name, mode)
372     except Exception as e:
373         if optional or options.generate_collector:
374             return open("/dev/null", mode)
375         raise e
376     return f
377
378
379 def input_readline(name, optional=False):
380     f = input_open(name, optional=optional)
381     line = f.readline()
382     f.close()
383     return line
384
385
386 def input_listdir(dir, wildcards):
387     for w in wildcards:
388         inputs['dirs'].add(os.path.join(dir, w))
389     if options.generate_collector:
390         return []
391     dirs = os.listdir(options.root + dir)
392     dirs.sort()
393     return dirs
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     offset = 0
429     (scope_type, scope_len, bus, dev, fn) = \
430         struct.unpack('<BBxxxBBB', f.read(8))
431     offset += 8
432     return (offset, 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                 (off, scope_type, scope_len, bus, dev, fn) =\
469                     parse_dmar_devscope(f)
470                 offset += off
471                 if scope_type == 3:
472                     if ioapic_id != 0:
473                         raise RuntimeError('We do not support more '
474                                            'than 1 IOAPIC')
475                     ioapic_id = (bus << 8) | (dev << 3) | fn
476                 f.seek(scope_len - 8, os.SEEK_CUR)
477                 offset += scope_len - 8
478
479         # Reserved Memory Region Reporting Structure
480         if struct_type == 1:
481             f.seek(8 - offset, os.SEEK_CUR)
482             offset += 8 - offset
483             (base, limit) = struct.unpack('<QQ', f.read(16))
484             offset += 16
485
486             comments = []
487             while offset < struct_len:
488                 (off, scope_type, scope_len, bus, dev, fn) =\
489                     parse_dmar_devscope(f)
490                 offset += off
491                 npath = (scope_len - 6)/2
492                 if scope_type == 1 and npath == 1:
493                     comments.append('PCI device: %02x:%02x.%x' %
494                                     (bus, dev, fn))
495                 else:
496                     comments.append('DMAR parser could not decode device path')
497                 f.seek(scope_len - off, os.SEEK_CUR)
498                 offset += scope_len - off
499
500             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
501             regions.append(reg)
502
503         f.seek(struct_len - offset, os.SEEK_CUR)
504
505     return units, ioapic_id, regions
506
507
508 def parse_ioports():
509     pm_timer_base = None
510     f = input_open('/proc/ioports')
511     for line in f:
512         if line.endswith('ACPI PM_TMR\n'):
513             pm_timer_base = int(line.split('-')[0], 16)
514             break
515     f.close()
516     return pm_timer_base
517
518
519 class MMConfig:
520     def __init__(self, base, end_bus):
521         self.base = base
522         self.end_bus = end_bus
523
524     @staticmethod
525     def parse():
526         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
527         signature = f.read(4)
528         if signature != b'MCFG':
529             if options.generate_collector:
530                 return MMConfig(0, 0)
531             raise RuntimeError('incorrect input file format %s' % signature)
532         (length,) = struct.unpack('<I', f.read(4))
533         if length > 60:
534             raise RuntimeError('Multiple MMCONFIG regions found! '
535                                'This is not supported')
536         f.seek(44)
537         (base, segment, start_bus, end_bus) = \
538             struct.unpack('<QHBB', f.read(12))
539         if segment != 0 or start_bus != 0:
540             raise RuntimeError('Invalid MCFG structure found')
541         return MMConfig(base, end_bus)
542
543
544 if (
545     (options.generate_collector is False) and (options.root is '/')
546     and (os.geteuid() is not 0)
547 ):
548     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
549     sys.exit(1)
550
551 (pcidevices, pcicaps) = parse_pcidevices()
552
553 product = [input_readline('/sys/class/dmi/id/sys_vendor',
554                           True).rstrip(),
555            input_readline('/sys/class/dmi/id/product_name',
556                           True).rstrip()
557            ]
558
559 inmatemem = kmg_multiply_str(options.mem_inmates)
560 hvmem = [0, kmg_multiply_str(options.mem_hv)]
561
562 regions = parse_iomem()
563 ourmem = parse_cmdline()
564 total = hvmem[1] + inmatemem
565
566 mmconfig = MMConfig.parse()
567
568 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar()
569 regions += rmrr_regs
570
571 # kernel does not have memmap region, pick one
572 if ourmem is None:
573     ourmem = alloc_mem(regions, total)
574 elif (total > ourmem[1]):
575     raise RuntimeError('Your memmap reservation is too small you need >="' +
576                        hex(total) + '"')
577
578 hvmem[0] = ourmem[0]
579
580 inmatereg = MemRegion(ourmem[0] + hvmem[1],
581                       ourmem[0] + hvmem[1] + inmatemem - 1,
582                       'JAILHOUSE Inmate Memory')
583 regions.append(inmatereg)
584
585 cpucount = count_cpus()
586
587 pm_timer_base = parse_ioports()
588
589 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
590                             True).rstrip()
591 if options.generate_collector is False and jh_enabled == '1':
592     print('ERROR: Jailhouse was enabled when collecting input files! '
593           'Disable jailhouse and try again.',
594           file=sys.stderr)
595     sys.exit(1)
596
597 f = open(options.file, 'w')
598
599 if options.generate_collector:
600     filelist = ' '.join(inputs['files'].union(inputs['dirs']))
601     filelist_opt = ' '.join(inputs['files_opt'])
602
603     tmpl = Template(filename=os.path.join(options.template_dir,
604                                           'jailhouse-config-collect.tmpl'))
605     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
606 else:
607     tmpl = Template(filename=os.path.join(options.template_dir,
608                                           'root-cell-config.c.tmpl'))
609     f.write(tmpl.render(regions=regions,
610                         ourmem=ourmem,
611                         argstr=' '.join(sys.argv),
612                         hvmem=hvmem,
613                         product=product,
614                         pcidevices=pcidevices,
615                         pcicaps=pcicaps,
616                         cpucount=cpucount,
617                         ioapic_id=ioapic_id,
618                         pm_timer_base=pm_timer_base,
619                         mmconfig=mmconfig,
620                         dmar_units=dmar_units))
621
622 f.close()