3 # Jailhouse, a Linux-based partitioning hypervisor
5 # Copyright (c) Siemens AG, 2014
7 # This work is licensed under the terms of the GNU GPL, version 2. See
8 # the COPYING file in the top-level directory.
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.
15 from __future__ import print_function
21 from mako.template import Template
23 # pretend to be part of the jailhouse tool
24 sys.argv[0] = sys.argv[0].replace('-', ' ')
26 parser = argparse.ArgumentParser()
27 parser.add_argument('-g', '--generate-collector',
28 help='generate a script to collect input files on '
31 parser.add_argument('-r', '--root',
32 help='gather information in ROOT/, the default is "/" '
33 'which means creating a config for localhost',
38 memargs = [['--mem-inmates', '2M', 'inmate'],
39 ['--mem-hv', '64M', 'hypervisor']]
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]"',
50 parser.add_argument('file', metavar='FILE',
51 help='name of file to write out',
54 options = parser.parse_args()
56 inputs = {'files': set(), 'dirs': set()}
60 def __init__(self, type, domain, bus, dev, fn):
68 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
71 return self.dev << 3 | self.fn
74 def parse_pcidevice_sysfsdir(basedir, dir):
75 dclass = input_readline(basedir + '/' + dir + '/class', False, False)
76 if re.match(r'0x0604..', dclass):
77 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
79 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
81 domain = int(a[0], 16)
84 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16))
88 def __init__(self, start, stop, typestr, comments=[]):
91 self.typestr = typestr
92 self.comments = comments
95 return 'MemRegion: %08x-%08x : %s' % \
96 (self.start, self.stop, self.typestr)
99 # round up to full PAGE_SIZE
100 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
102 def flagstr(self, p=''):
104 self.typestr == 'ACPI Tables' or
105 self.typestr == 'ACPI Non-volatile Storage'
107 return 'JAILHOUSE_MEM_READ'
109 self.typestr == 'System RAM' or
110 self.typestr == 'RAM buffer' or
111 self.typestr == 'ACPI DMAR RMRR'
113 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
114 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
116 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
119 # return the first region with the given typestr
120 def find_region(regions, typestr):
122 if (r.typestr == typestr):
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:
132 region = a[0].split('-', 1)
134 return MemRegion(int(region[0], 16), int(region[1], 16), a[1])
139 f, e = input_open('/proc/iomem', True, False, 'r')
141 r = MemRegion.parse_iomem_line(line)
142 ## XXX what else to ignore??
145 r.typestr != 'Local APIC' and
146 r.typestr != 'reserved'
151 # newer Linux kernels will report the first page as reserved
152 # it is needed for CPU init so include it anyways
154 regions[0].typestr == 'System RAM' and
155 regions[0].start == 0x1000
162 def parse_pcidevices():
164 basedir = '/sys/bus/pci/devices'
165 list = input_listdir(basedir, ['*/class'])
167 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
173 def kmg_multiply(value, kmg):
174 if (kmg == 'K' or kmg == 'k'):
176 if (kmg == 'M' or kmg == 'm'):
177 return 1024**2 * value
178 if (kmg == 'G' or kmg == 'g'):
179 return 1024**3 * value
183 def kmg_multiply_str(str):
184 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
186 return kmg_multiply(int(m.group(1)), m.group(2))
187 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
191 def input_open(name, record, optional, *args):
193 inputs['files'].add(name)
195 f = open(options.root + name, *args)
196 except Exception as e:
203 def input_readline(name, record=True, optional=False):
204 f, e = input_open(name, record, optional, 'r')
205 if f is None and optional:
213 def input_listdir(dir, wildcards):
215 inputs['dirs'].add(dir + '/' + w)
216 if options.generate_collector:
218 return os.listdir(options.root + dir)
222 line = input_readline('/proc/cmdline')
223 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
224 '([0-9a-fA-FxX]+)([KMG]?).*',
227 size = kmg_multiply(int(m.group(1), 0), m.group(2))
228 start = kmg_multiply(int(m.group(3), 0), m.group(4))
233 def alloc_mem(regions, size):
235 for r in reversed(regions):
236 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
240 raise RuntimeError('failed to allocate memory')
244 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
247 if re.match(r'cpu[0-9]+', f):
252 def parse_dmar_devscope(f):
254 (scope_type, scope_len, bus, dev, fn) = \
255 struct.unpack('<BBxxxBBB', f.read(8))
257 return (offset, scope_type, scope_len, bus, dev, fn)
260 # parsing of DMAR ACPI Table
261 # see Intel VT-d Spec chapter 8
263 f, e = input_open('/sys/firmware/acpi/tables/DMAR', True, True, 'rb')
265 if options.generate_collector:
269 raise RuntimeError('could not find DMAR ACPI table')
271 signature = f.read(4)
272 if signature != b'DMAR':
273 raise RuntimeError('incorrect input file format %s' % signature)
274 (length,) = struct.unpack('<I', f.read(4))
282 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
286 # DMA Remapping Hardware Unit Definition
288 f.seek(16 - offset, os.SEEK_CUR)
289 offset += 16 - offset
290 while offset < struct_len:
291 (off, scope_type, scope_len, bus, dev, fn) =\
292 parse_dmar_devscope(f)
296 raise RuntimeError('We do not support more '
298 ioapic_id = (bus << 8) | (dev << 3) | fn
299 f.seek(scope_len - 8, os.SEEK_CUR)
300 offset += scope_len - 8
302 # Reserved Memory Region Reporting Structure
304 f.seek(8 - offset, os.SEEK_CUR)
306 (base, limit) = struct.unpack('<QQ', f.read(16))
310 while offset < struct_len:
311 (off, scope_type, scope_len, bus, dev, fn) =\
312 parse_dmar_devscope(f)
314 npath = (scope_len - 6)/2
315 if scope_type == 1 and npath == 1:
316 comments.append('PCI device: %02x:%02x.%x' %
319 comments.append('DMAR parser could not decode device path')
320 f.seek(scope_len - off, os.SEEK_CUR)
321 offset += scope_len - off
323 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
326 f.seek(struct_len - offset, os.SEEK_CUR)
328 return ioapic_id, regions
333 f, e = input_open('/proc/ioports', True, False, 'r')
335 if line.endswith('ACPI PM_TMR\n'):
336 pm_timer_base = int(line.split('-')[0], 16)
342 pcidevices = parse_pcidevices()
344 product = [input_readline('/sys/class/dmi/id/sys_vendor',
345 True, True).rstrip(),
346 input_readline('/sys/class/dmi/id/product_name',
350 inmatemem = kmg_multiply_str(options.mem_inmates)
351 hvmem = [0, kmg_multiply_str(options.mem_hv)]
353 regions = parse_iomem()
354 ourmem = parse_cmdline()
355 total = hvmem[1] + inmatemem
357 ioapic_id, rmrr_regs = parse_dmar()
360 # kernel does not have memmap region, pick one
362 ourmem = alloc_mem(regions, total)
363 elif (total > ourmem[1]):
364 raise RuntimeError('Your memmap reservation is too small you need >="' +
369 creg = MemRegion.find_region(regions, 'ACPI Tables')
371 raise RuntimeError('could not find "ACPI Tables" memory')
372 confmem = [creg.start, creg.size()]
373 inmatereg = MemRegion(ourmem[0] + hvmem[1],
374 ourmem[0] + hvmem[1] + inmatemem - 1,
375 'JAILHOUSE Inmate Memory')
376 regions.append(inmatereg)
378 cpucount = count_cpus()
380 pm_timer_base = parse_ioports()
382 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
384 if options.generate_collector is False and jh_enabled == '1':
385 print('ERROR: Jailhouse was enabled when collecting input files! '
386 'Disable jailhouse and try again.',
390 f = open(options.file, 'w')
392 if options.generate_collector:
393 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
395 tmpl = Template(filename='jailhouse-config-collect.tmpl')
396 f.write(tmpl.render(filelist=filelist))
398 tmpl = Template(filename='root-cell-config.c.tmpl')
399 f.write(tmpl.render(regions=regions,
401 argstr=' '.join(sys.argv),
405 pcidevices=pcidevices,
408 pm_timer_base=pm_timer_base))