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