]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
core/configs/tools: Remove ACPI support from hypervisor
[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 # pretend to be part of the jailhouse tool
24 sys.argv[0] = sys.argv[0].replace('-', ' ')
25
26 parser = argparse.ArgumentParser()
27 parser.add_argument('-g', '--generate-collector',
28                     help='generate a script to collect input files on '
29                          'a remote machine',
30                     action='store_true')
31 parser.add_argument('-r', '--root',
32                     help='gather information in ROOT/, the default is "/" '
33                          'which means creating a config for localhost',
34                     default='/',
35                     action='store',
36                     type=str)
37
38 memargs = [['--mem-inmates', '2M', 'inmate'],
39            ['--mem-hv', '64M', 'hypervisor']]
40
41 for entry in memargs:
42     parser.add_argument(entry[0],
43                         help='the amount of ' + entry[2] +
44                              ' memory, default is "' + entry[1] +
45                              '", format "xxx[K|M|G]"',
46                         default=entry[1],
47                         action='store',
48                         type=str)
49
50 parser.add_argument('file', metavar='FILE',
51                     help='name of file to write out',
52                     type=str)
53
54 options = parser.parse_args()
55
56 inputs = {'files': set(), 'files_opt': set(), 'dirs': set()}
57
58
59 class PCICapability:
60     def __init__(self, id, start, len, flags):
61         self.id = id
62         self.start = start
63         self.len = len
64         self.flags = flags
65         self.comments = []
66
67     def __eq__(self, other):
68         return self.id == other.id and self.start == other.start and \
69             self.len == other.len and self.flags == other.flags
70
71     RD = '0'
72     RW = 'JAILHOUSE_PCICAPS_WRITE'
73
74     @staticmethod
75     def parse_pcicaps(dir):
76         caps = []
77         f = input_open(dir + '/config', 'rb')
78         f.seek(0x06)
79         (status,) = struct.unpack('<H', f.read(2))
80         # capability list supported?
81         if (status & (1 << 4)) == 0:
82             f.close()
83             return caps
84         # walk capability list
85         f.seek(0x34)
86         (next,) = struct.unpack('B', f.read(1))
87         while next != 0:
88             cap = next
89             f.seek(cap)
90             (id, next) = struct.unpack('<BB', f.read(2))
91             if id == 0x01:  # Power Management
92                 # this cap can be handed out completely
93                 len = 8
94                 flags = PCICapability.RW
95             elif id == 0x05:  # MSI
96                 # access will be moderated by hypervisor
97                 len = 10
98                 (msgctl,) = struct.unpack('<H', f.read(2))
99                 if (msgctl & (1 << 7)) != 0:  # 64-bit support
100                     len += 4
101                 if (msgctl & (1 << 8)) != 0:  # per-vector masking support
102                     len += 10
103                 flags = PCICapability.RW
104             elif id == 0x11:  # MSI-X
105                 # access will be moderated by hypervisor
106                 len = 12
107                 flags = PCICapability.RW
108             else:
109                 # unknown/unhandled cap, mark its existence
110                 len = 2
111                 flags = PCICapability.RD
112             caps.append(PCICapability(id, cap, len, flags))
113         return caps
114
115
116 class PCIDevice:
117     def __init__(self, type, domain, bus, dev, fn, caps):
118         self.type = type
119         self.domain = domain
120         self.bus = bus
121         self.dev = dev
122         self.fn = fn
123         self.caps = caps
124         self.caps_start = 0
125         self.num_caps = len(caps)
126
127     def __str__(self):
128         return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
129
130     def bdf(self):
131         return self.bus << 8 | self.dev << 3 | self.fn
132
133     @staticmethod
134     def parse_pcidevice_sysfsdir(basedir, dir):
135         dpath = basedir + '/' + dir
136         dclass = input_readline(dpath + '/class')
137         if re.match(r'0x0604..', dclass):
138             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
139         else:
140             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
141         a = dir.split(':')
142         domain = int(a[0], 16)
143         bus = int(a[1], 16)
144         df = a[2].split('.')
145         caps = PCICapability.parse_pcicaps(dpath)
146         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
147                          caps)
148
149
150 class MemRegion:
151     def __init__(self, start, stop, typestr, comments=[]):
152         self.start = start
153         self.stop = stop
154         self.typestr = typestr
155         self.comments = comments
156
157     def __str__(self):
158         return 'MemRegion: %08x-%08x : %s' % \
159             (self.start, self.stop, self.typestr)
160
161     def size(self):
162         # round up to full PAGE_SIZE
163         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
164
165     def flagstr(self, p=''):
166         if (
167             self.typestr == 'ACPI Tables' or
168             self.typestr == 'ACPI Non-volatile Storage'
169         ):
170             return 'JAILHOUSE_MEM_READ'
171         if (
172             self.typestr == 'System RAM' or
173             self.typestr == 'RAM buffer' or
174             self.typestr == 'ACPI DMAR RMRR'
175         ):
176             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
177             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
178             return s
179         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
180
181     @staticmethod
182     # return the first region with the given typestr
183     def find_region(regions, typestr):
184         for r in regions:
185             if (r.typestr == typestr):
186                 return r
187         return None
188
189     @staticmethod
190     def parse_iomem_line(line):
191         a = line.split(':', 1)
192         # HPET may be part of in reserved region
193         if a[0].startswith(' ') and a[1].find("HPET") < 0:
194             return None
195         region = a[0].split('-', 1)
196         a[1] = a[1].strip()
197         return MemRegion(int(region[0], 16), int(region[1], 16), a[1])
198
199
200 def parse_iomem():
201     regions = []
202     f = input_open('/proc/iomem')
203     for line in f:
204         r = MemRegion.parse_iomem_line(line)
205         ## XXX what else to ignore??
206         if (
207             r is not None and
208             r.typestr != 'Local APIC' and
209             r.typestr != 'reserved'
210         ):
211             regions.append(r)
212     f.close()
213
214     # newer Linux kernels will report the first page as reserved
215     # it is needed for CPU init so include it anyways
216     if (
217         regions[0].typestr == 'System RAM' and
218         regions[0].start == 0x1000
219     ):
220         regions[0].start = 0
221
222     return regions
223
224
225 def parse_pcidevices():
226     devices = []
227     caps = []
228     basedir = '/sys/bus/pci/devices'
229     list = input_listdir(basedir, ['*/class', '*/config'])
230     for dir in list:
231         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
232         if d is not None:
233             if len(d.caps) > 0:
234                 duplicate = False
235                 # look for duplicate capability patterns
236                 for d2 in devices:
237                     if d2.caps == d.caps:
238                         # reused existing capability list, but record all users
239                         d2.caps[0].comments.append(str(d))
240                         d.caps_start = d2.caps_start
241                         duplicate = True
242                         break
243                 if not duplicate:
244                     d.caps[0].comments.append(str(d))
245                     d.caps_start = len(caps)
246                     caps.extend(d.caps)
247             devices.append(d)
248     return (devices, caps)
249
250
251 def kmg_multiply(value, kmg):
252     if (kmg == 'K' or kmg == 'k'):
253         return 1024 * value
254     if (kmg == 'M' or kmg == 'm'):
255         return 1024**2 * value
256     if (kmg == 'G' or kmg == 'g'):
257         return 1024**3 * value
258     return value
259
260
261 def kmg_multiply_str(str):
262     m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
263     if m is not None:
264         return kmg_multiply(int(m.group(1)), m.group(2))
265     raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
266     return 0
267
268
269 def input_open(name, mode='r', optional=False):
270     inputs['files_opt' if optional else 'files'].add(name)
271     try:
272         f = open(options.root + name, mode)
273     except Exception as e:
274         if optional or options.generate_collector:
275             return open("/dev/null", mode)
276         raise e
277     return f
278
279
280 def input_readline(name, optional=False):
281     f = input_open(name, optional=optional)
282     line = f.readline()
283     f.close()
284     return line
285
286
287 def input_listdir(dir, wildcards):
288     for w in wildcards:
289         inputs['dirs'].add(dir + '/' + w)
290     if options.generate_collector:
291         return []
292     dirs = os.listdir(options.root + dir)
293     dirs.sort()
294     return dirs
295
296
297 def parse_cmdline():
298     line = input_readline('/proc/cmdline')
299     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
300                  '([0-9a-fA-FxX]+)([KMG]?).*',
301                  line)
302     if m is not None:
303         size = kmg_multiply(int(m.group(1), 0), m.group(2))
304         start = kmg_multiply(int(m.group(3), 0), m.group(4))
305         return [start, size]
306     return None
307
308
309 def alloc_mem(regions, size):
310     mem = [0, size]
311     for r in reversed(regions):
312         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
313             mem[0] = r.start
314             r.start += mem[1]
315             return mem
316     raise RuntimeError('failed to allocate memory')
317
318
319 def count_cpus():
320     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
321     count = 0
322     for f in list:
323         if re.match(r'cpu[0-9]+', f):
324             count += 1
325     return count
326
327
328 def parse_dmar_devscope(f):
329     offset = 0
330     (scope_type, scope_len, bus, dev, fn) = \
331         struct.unpack('<BBxxxBBB', f.read(8))
332     offset += 8
333     return (offset, scope_type, scope_len, bus, dev, fn)
334
335
336 # parsing of DMAR ACPI Table
337 # see Intel VT-d Spec chapter 8
338 def parse_dmar():
339     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
340     signature = f.read(4)
341     if signature != b'DMAR':
342         if options.generate_collector:
343             return [], 0, []
344         raise RuntimeError('incorrect input file format %s' % signature)
345     (length,) = struct.unpack('<I', f.read(4))
346     f.seek(48)
347     length -= 48
348     units = []
349     regions = []
350     ioapic_id = 0
351
352     while length > 0:
353         offset = 0
354         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
355         offset += 4
356         length -= struct_len
357
358         # DMA Remapping Hardware Unit Definition
359         if struct_type == 0:
360             (segment, base) = struct.unpack('<xxHQ', f.read(12))
361             if segment != 0:
362                 raise RuntimeError('We do not support multiple PCI segments')
363             if len(units) >= 8:
364                 raise RuntimeError('Too many DMAR units. '
365                                    'Raise JAILHOUSE_MAX_DMAR_UNITS.')
366             units.append(base)
367             offset += 16 - offset
368             while offset < struct_len:
369                 (off, scope_type, scope_len, bus, dev, fn) =\
370                     parse_dmar_devscope(f)
371                 offset += off
372                 if scope_type == 3:
373                     if ioapic_id != 0:
374                         raise RuntimeError('We do not support more '
375                                            'than 1 IOAPIC')
376                     ioapic_id = (bus << 8) | (dev << 3) | fn
377                 f.seek(scope_len - 8, os.SEEK_CUR)
378                 offset += scope_len - 8
379
380         # Reserved Memory Region Reporting Structure
381         if struct_type == 1:
382             f.seek(8 - offset, os.SEEK_CUR)
383             offset += 8 - offset
384             (base, limit) = struct.unpack('<QQ', f.read(16))
385             offset += 16
386
387             comments = []
388             while offset < struct_len:
389                 (off, scope_type, scope_len, bus, dev, fn) =\
390                     parse_dmar_devscope(f)
391                 offset += off
392                 npath = (scope_len - 6)/2
393                 if scope_type == 1 and npath == 1:
394                     comments.append('PCI device: %02x:%02x.%x' %
395                                     (bus, dev, fn))
396                 else:
397                     comments.append('DMAR parser could not decode device path')
398                 f.seek(scope_len - off, os.SEEK_CUR)
399                 offset += scope_len - off
400
401             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
402             regions.append(reg)
403
404         f.seek(struct_len - offset, os.SEEK_CUR)
405
406     return units, ioapic_id, regions
407
408
409 def parse_ioports():
410     pm_timer_base = None
411     f = input_open('/proc/ioports')
412     for line in f:
413         if line.endswith('ACPI PM_TMR\n'):
414             pm_timer_base = int(line.split('-')[0], 16)
415             break
416     f.close()
417     return pm_timer_base
418
419
420 class MMConfig:
421     def __init__(self, base, end_bus):
422         self.base = base
423         self.end_bus = end_bus
424
425     @staticmethod
426     def parse():
427         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
428         signature = f.read(4)
429         if signature != b'MCFG':
430             if options.generate_collector:
431                 return MMConfig(0, 0)
432             raise RuntimeError('incorrect input file format %s' % signature)
433         (length,) = struct.unpack('<I', f.read(4))
434         if length > 60:
435             raise RuntimeError('Multiple MMCONFIG regions found! '
436                                'This is not supported')
437         f.seek(44)
438         (base, segment, start_bus, end_bus) = \
439             struct.unpack('<QHBB', f.read(12))
440         if segment != 0 or start_bus != 0:
441             raise RuntimeError('Invalid MCFG structure found')
442         return MMConfig(base, end_bus)
443
444
445 (pcidevices, pcicaps) = parse_pcidevices()
446
447 product = [input_readline('/sys/class/dmi/id/sys_vendor',
448                           True).rstrip(),
449            input_readline('/sys/class/dmi/id/product_name',
450                           True).rstrip()
451            ]
452
453 inmatemem = kmg_multiply_str(options.mem_inmates)
454 hvmem = [0, kmg_multiply_str(options.mem_hv)]
455
456 regions = parse_iomem()
457 ourmem = parse_cmdline()
458 total = hvmem[1] + inmatemem
459
460 mmconfig = MMConfig.parse()
461
462 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar()
463 regions += rmrr_regs
464
465 # kernel does not have memmap region, pick one
466 if ourmem is None:
467     ourmem = alloc_mem(regions, total)
468 elif (total > ourmem[1]):
469     raise RuntimeError('Your memmap reservation is too small you need >="' +
470                        hex(total) + '"')
471
472 hvmem[0] = ourmem[0]
473
474 inmatereg = MemRegion(ourmem[0] + hvmem[1],
475                       ourmem[0] + hvmem[1] + inmatemem - 1,
476                       'JAILHOUSE Inmate Memory')
477 regions.append(inmatereg)
478
479 cpucount = count_cpus()
480
481 pm_timer_base = parse_ioports()
482
483 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
484                             True).rstrip()
485 if options.generate_collector is False and jh_enabled == '1':
486     print('ERROR: Jailhouse was enabled when collecting input files! '
487           'Disable jailhouse and try again.',
488           file=sys.stderr)
489     sys.exit(1)
490
491 f = open(options.file, 'w')
492
493 if options.generate_collector:
494     filelist = ' '.join(inputs['files'].union(inputs['dirs']))
495     filelist_opt = ' '.join(inputs['files_opt'])
496
497     tmpl = Template(filename='jailhouse-config-collect.tmpl')
498     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
499 else:
500     tmpl = Template(filename='root-cell-config.c.tmpl')
501     f.write(tmpl.render(regions=regions,
502                         ourmem=ourmem,
503                         argstr=' '.join(sys.argv),
504                         hvmem=hvmem,
505                         product=product,
506                         pcidevices=pcidevices,
507                         pcicaps=pcicaps,
508                         cpucount=cpucount,
509                         ioapic_id=ioapic_id,
510                         pm_timer_base=pm_timer_base,
511                         mmconfig=mmconfig,
512                         dmar_units=dmar_units))
513
514 f.close()