]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
tools: config-create: Differentiate between optional and mandatory files during collect
[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 PCIDevice:
60     def __init__(self, type, domain, bus, dev, fn):
61         self.type = type
62         self.domain = domain
63         self.bus = bus
64         self.dev = dev
65         self.fn = fn
66
67     def __str__(self):
68         return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
69
70     def devfn(self):
71         return self.dev << 3 | self.fn
72
73     @staticmethod
74     def parse_pcidevice_sysfsdir(basedir, dir):
75         dclass = input_readline(basedir + '/' + dir + '/class')
76         if re.match(r'0x0604..', dclass):
77             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
78         else:
79             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
80         a = dir.split(':')
81         domain = int(a[0], 16)
82         bus = int(a[1], 16)
83         df = a[2].split('.')
84         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16))
85
86
87 class MemRegion:
88     def __init__(self, start, stop, typestr, comments=[]):
89         self.start = start
90         self.stop = stop
91         self.typestr = typestr
92         self.comments = comments
93
94     def __str__(self):
95         return 'MemRegion: %08x-%08x : %s' % \
96             (self.start, self.stop, self.typestr)
97
98     def size(self):
99         # round up to full PAGE_SIZE
100         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
101
102     def flagstr(self, p=''):
103         if (
104             self.typestr == 'ACPI Tables' or
105             self.typestr == 'ACPI Non-volatile Storage'
106         ):
107             return 'JAILHOUSE_MEM_READ'
108         if (
109             self.typestr == 'System RAM' or
110             self.typestr == 'RAM buffer' or
111             self.typestr == 'ACPI DMAR RMRR'
112         ):
113             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
114             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
115             return s
116         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
117
118     @staticmethod
119     # return the first region with the given typestr
120     def find_region(regions, typestr):
121         for r in regions:
122             if (r.typestr == typestr):
123                 return r
124         return None
125
126     @staticmethod
127     def parse_iomem_line(line):
128         a = line.split(':', 1)
129         # HPET may be part of in reserved region
130         if a[0].startswith(' ') and a[1].find("HPET") < 0:
131             return None
132         region = a[0].split('-', 1)
133         a[1] = a[1].strip()
134         return MemRegion(int(region[0], 16), int(region[1], 16), a[1])
135
136
137 def parse_iomem():
138     regions = []
139     f, e = input_open('/proc/iomem', False, 'r')
140     for line in f:
141         r = MemRegion.parse_iomem_line(line)
142         ## XXX what else to ignore??
143         if (
144             r is not None and
145             r.typestr != 'Local APIC' and
146             r.typestr != 'reserved'
147         ):
148             regions.append(r)
149     f.close()
150
151     # newer Linux kernels will report the first page as reserved
152     # it is needed for CPU init so include it anyways
153     if (
154         regions[0].typestr == 'System RAM' and
155         regions[0].start == 0x1000
156     ):
157         regions[0].start = 0
158
159     return regions
160
161
162 def parse_pcidevices():
163     devices = []
164     basedir = '/sys/bus/pci/devices'
165     list = input_listdir(basedir, ['*/class'])
166     for dir in list:
167         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
168         if d is not None:
169             devices.append(d)
170     return devices
171
172
173 def kmg_multiply(value, kmg):
174     if (kmg == 'K' or kmg == 'k'):
175         return 1024 * value
176     if (kmg == 'M' or kmg == 'm'):
177         return 1024**2 * value
178     if (kmg == 'G' or kmg == 'g'):
179         return 1024**3 * value
180     return value
181
182
183 def kmg_multiply_str(str):
184     m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
185     if m is not None:
186         return kmg_multiply(int(m.group(1)), m.group(2))
187     raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
188     return 0
189
190
191 def input_open(name, optional, *args):
192     inputs['files_opt' if optional else 'files'].add(name)
193     try:
194         f = open(options.root + name, *args)
195     except Exception as e:
196         if optional:
197             return None, e
198         raise e
199     return f, None
200
201
202 def input_readline(name, optional=False):
203     f, e = input_open(name, optional, 'r')
204     if f is None and optional:
205         return ''
206
207     line = f.readline()
208     f.close()
209     return line
210
211
212 def input_listdir(dir, wildcards):
213     for w in wildcards:
214         inputs['dirs'].add(dir + '/' + w)
215     if options.generate_collector:
216         return []
217     return os.listdir(options.root + dir)
218
219
220 def parse_cmdline():
221     line = input_readline('/proc/cmdline')
222     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
223                  '([0-9a-fA-FxX]+)([KMG]?).*',
224                  line)
225     if m is not None:
226         size = kmg_multiply(int(m.group(1), 0), m.group(2))
227         start = kmg_multiply(int(m.group(3), 0), m.group(4))
228         return [start, size]
229     return None
230
231
232 def alloc_mem(regions, size):
233     mem = [0, size]
234     for r in reversed(regions):
235         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
236             mem[0] = r.start
237             r.start += mem[1]
238             return mem
239     raise RuntimeError('failed to allocate memory')
240
241
242 def count_cpus():
243     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
244     count = 0
245     for f in list:
246         if re.match(r'cpu[0-9]+', f):
247             count += 1
248     return count
249
250
251 def parse_dmar_devscope(f):
252     offset = 0
253     (scope_type, scope_len, bus, dev, fn) = \
254         struct.unpack('<BBxxxBBB', f.read(8))
255     offset += 8
256     return (offset, scope_type, scope_len, bus, dev, fn)
257
258
259 # parsing of DMAR ACPI Table
260 # see Intel VT-d Spec chapter 8
261 def parse_dmar():
262     f, e = input_open('/sys/firmware/acpi/tables/DMAR', True, 'rb')
263     if not f:
264         if options.generate_collector:
265             return 0, []
266         if e:
267             raise e
268         raise RuntimeError('could not find DMAR ACPI table')
269
270     signature = f.read(4)
271     if signature != b'DMAR':
272         raise RuntimeError('incorrect input file format %s' % signature)
273     (length,) = struct.unpack('<I', f.read(4))
274     f.seek(48)
275     length -= 48
276     regions = []
277     ioapic_id = 0
278
279     while length > 0:
280         offset = 0
281         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
282         offset += 4
283         length -= struct_len
284
285         # DMA Remapping Hardware Unit Definition
286         if struct_type == 0:
287             f.seek(16 - offset, os.SEEK_CUR)
288             offset += 16 - offset
289             while offset < struct_len:
290                 (off, scope_type, scope_len, bus, dev, fn) =\
291                     parse_dmar_devscope(f)
292                 offset += off
293                 if scope_type == 3:
294                     if ioapic_id != 0:
295                         raise RuntimeError('We do not support more '
296                                            'than 1 IOAPIC')
297                     ioapic_id = (bus << 8) | (dev << 3) | fn
298                 f.seek(scope_len - 8, os.SEEK_CUR)
299                 offset += scope_len - 8
300
301         # Reserved Memory Region Reporting Structure
302         if struct_type == 1:
303             f.seek(8 - offset, os.SEEK_CUR)
304             offset += 8 - offset
305             (base, limit) = struct.unpack('<QQ', f.read(16))
306             offset += 16
307
308             comments = []
309             while offset < struct_len:
310                 (off, scope_type, scope_len, bus, dev, fn) =\
311                     parse_dmar_devscope(f)
312                 offset += off
313                 npath = (scope_len - 6)/2
314                 if scope_type == 1 and npath == 1:
315                     comments.append('PCI device: %02x:%02x.%x' %
316                                     (bus, dev, fn))
317                 else:
318                     comments.append('DMAR parser could not decode device path')
319                 f.seek(scope_len - off, os.SEEK_CUR)
320                 offset += scope_len - off
321
322             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
323             regions.append(reg)
324
325         f.seek(struct_len - offset, os.SEEK_CUR)
326
327     return ioapic_id, regions
328
329
330 def parse_ioports():
331     pm_timer_base = None
332     f, e = input_open('/proc/ioports', False, 'r')
333     for line in f:
334         if line.endswith('ACPI PM_TMR\n'):
335             pm_timer_base = int(line.split('-')[0], 16)
336             break
337     f.close()
338     return pm_timer_base
339
340
341 pcidevices = parse_pcidevices()
342
343 product = [input_readline('/sys/class/dmi/id/sys_vendor',
344                           True).rstrip(),
345            input_readline('/sys/class/dmi/id/product_name',
346                           True).rstrip()
347            ]
348
349 inmatemem = kmg_multiply_str(options.mem_inmates)
350 hvmem = [0, kmg_multiply_str(options.mem_hv)]
351
352 regions = parse_iomem()
353 ourmem = parse_cmdline()
354 total = hvmem[1] + inmatemem
355
356 ioapic_id, rmrr_regs = parse_dmar()
357 regions += rmrr_regs
358
359 # kernel does not have memmap region, pick one
360 if ourmem is None:
361     ourmem = alloc_mem(regions, total)
362 elif (total > ourmem[1]):
363     raise RuntimeError('Your memmap reservation is too small you need >="' +
364                        hex(total) + '"')
365
366 hvmem[0] = ourmem[0]
367
368 creg = MemRegion.find_region(regions, 'ACPI Tables')
369 if creg is None:
370     raise RuntimeError('could not find "ACPI Tables" memory')
371 confmem = [creg.start, creg.size()]
372 inmatereg = MemRegion(ourmem[0] + hvmem[1],
373                       ourmem[0] + hvmem[1] + inmatemem - 1,
374                       'JAILHOUSE Inmate Memory')
375 regions.append(inmatereg)
376
377 cpucount = count_cpus()
378
379 pm_timer_base = parse_ioports()
380
381 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
382                             True).rstrip()
383 if options.generate_collector is False and jh_enabled == '1':
384     print('ERROR: Jailhouse was enabled when collecting input files! '
385           'Disable jailhouse and try again.',
386           file=sys.stderr)
387     sys.exit(1)
388
389 f = open(options.file, 'w')
390
391 if options.generate_collector:
392     filelist = ' '.join(inputs['files'].union(inputs['dirs']))
393     filelist_opt = ' '.join(inputs['files_opt'])
394
395     tmpl = Template(filename='jailhouse-config-collect.tmpl')
396     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
397 else:
398     tmpl = Template(filename='root-cell-config.c.tmpl')
399     f.write(tmpl.render(regions=regions,
400                         ourmem=ourmem,
401                         argstr=' '.join(sys.argv),
402                         hvmem=hvmem,
403                         confmem=confmem,
404                         product=product,
405                         pcidevices=pcidevices,
406                         cpucount=cpucount,
407                         ioapic_id=ioapic_id,
408                         pm_timer_base=pm_timer_base))
409
410 f.close()