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(), 'files_opt': set(), 'dirs': set()}
60 def __init__(self, id, start, len, flags):
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
72 RW = 'JAILHOUSE_PCICAPS_WRITE'
75 def parse_pcicaps(dir):
77 f = input_open(dir + '/config', 'rb')
79 (status,) = struct.unpack('<H', f.read(2))
80 # capability list supported?
81 if (status & (1 << 4)) == 0:
84 # walk capability list
86 (next,) = struct.unpack('B', f.read(1))
90 (id, next) = struct.unpack('<BB', f.read(2))
91 if id == 0x01: # Power Management
92 # this cap can be handed out completely
94 flags = PCICapability.RW
95 elif id == 0x05: # MSI
96 # access will be moderated by hypervisor
98 (msgctl,) = struct.unpack('<H', f.read(2))
99 if (msgctl & (1 << 7)) != 0: # 64-bit support
101 if (msgctl & (1 << 8)) != 0: # per-vector masking support
103 flags = PCICapability.RW
104 elif id == 0x11: # MSI-X
105 # access will be moderated by hypervisor
107 flags = PCICapability.RW
109 # unknown/unhandled cap, mark its existence
111 flags = PCICapability.RD
112 caps.append(PCICapability(id, cap, len, flags))
117 def __init__(self, type, domain, bus, dev, fn, caps):
125 self.num_caps = len(caps)
128 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
131 return self.bus << 8 | self.dev << 3 | self.fn
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'
140 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
142 domain = int(a[0], 16)
145 caps = PCICapability.parse_pcicaps(dpath)
146 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
151 def __init__(self, start, stop, typestr, comments=[]):
154 self.typestr = typestr
155 self.comments = comments
158 return 'MemRegion: %08x-%08x : %s' % \
159 (self.start, self.stop, self.typestr)
162 # round up to full PAGE_SIZE
163 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
165 def flagstr(self, p=''):
167 self.typestr == 'ACPI Tables' or
168 self.typestr == 'ACPI Non-volatile Storage'
170 return 'JAILHOUSE_MEM_READ'
172 self.typestr == 'System RAM' or
173 self.typestr == 'RAM buffer' or
174 self.typestr == 'ACPI DMAR RMRR'
176 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
177 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
179 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
182 # return the first region with the given typestr
183 def find_region(regions, typestr):
185 if (r.typestr == typestr):
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:
195 region = a[0].split('-', 1)
197 return MemRegion(int(region[0], 16), int(region[1], 16), a[1])
202 f = input_open('/proc/iomem')
204 r = MemRegion.parse_iomem_line(line)
205 ## XXX what else to ignore??
208 r.typestr != 'Local APIC' and
209 r.typestr != 'reserved'
214 # newer Linux kernels will report the first page as reserved
215 # it is needed for CPU init so include it anyways
217 regions[0].typestr == 'System RAM' and
218 regions[0].start == 0x1000
225 def parse_pcidevices():
228 basedir = '/sys/bus/pci/devices'
229 list = input_listdir(basedir, ['*/class', '*/config'])
231 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
235 # look for duplicate capability patterns
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
244 d.caps[0].comments.append(str(d))
245 d.caps_start = len(caps)
248 return (devices, caps)
251 def kmg_multiply(value, kmg):
252 if (kmg == 'K' or kmg == 'k'):
254 if (kmg == 'M' or kmg == 'm'):
255 return 1024**2 * value
256 if (kmg == 'G' or kmg == 'g'):
257 return 1024**3 * value
261 def kmg_multiply_str(str):
262 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
264 return kmg_multiply(int(m.group(1)), m.group(2))
265 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
269 def input_open(name, mode='r', optional=False):
270 inputs['files_opt' if optional else 'files'].add(name)
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)
280 def input_readline(name, optional=False):
281 f = input_open(name, optional=optional)
287 def input_listdir(dir, wildcards):
289 inputs['dirs'].add(dir + '/' + w)
290 if options.generate_collector:
292 dirs = os.listdir(options.root + dir)
298 line = input_readline('/proc/cmdline')
299 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
300 '([0-9a-fA-FxX]+)([KMG]?).*',
303 size = kmg_multiply(int(m.group(1), 0), m.group(2))
304 start = kmg_multiply(int(m.group(3), 0), m.group(4))
309 def alloc_mem(regions, size):
311 for r in reversed(regions):
312 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
316 raise RuntimeError('failed to allocate memory')
320 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
323 if re.match(r'cpu[0-9]+', f):
328 def parse_dmar_devscope(f):
330 (scope_type, scope_len, bus, dev, fn) = \
331 struct.unpack('<BBxxxBBB', f.read(8))
333 return (offset, scope_type, scope_len, bus, dev, fn)
336 # parsing of DMAR ACPI Table
337 # see Intel VT-d Spec chapter 8
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:
344 raise RuntimeError('incorrect input file format %s' % signature)
345 (length,) = struct.unpack('<I', f.read(4))
353 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
357 # DMA Remapping Hardware Unit Definition
359 f.seek(16 - offset, os.SEEK_CUR)
360 offset += 16 - offset
361 while offset < struct_len:
362 (off, scope_type, scope_len, bus, dev, fn) =\
363 parse_dmar_devscope(f)
367 raise RuntimeError('We do not support more '
369 ioapic_id = (bus << 8) | (dev << 3) | fn
370 f.seek(scope_len - 8, os.SEEK_CUR)
371 offset += scope_len - 8
373 # Reserved Memory Region Reporting Structure
375 f.seek(8 - offset, os.SEEK_CUR)
377 (base, limit) = struct.unpack('<QQ', f.read(16))
381 while offset < struct_len:
382 (off, scope_type, scope_len, bus, dev, fn) =\
383 parse_dmar_devscope(f)
385 npath = (scope_len - 6)/2
386 if scope_type == 1 and npath == 1:
387 comments.append('PCI device: %02x:%02x.%x' %
390 comments.append('DMAR parser could not decode device path')
391 f.seek(scope_len - off, os.SEEK_CUR)
392 offset += scope_len - off
394 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
397 f.seek(struct_len - offset, os.SEEK_CUR)
399 return ioapic_id, regions
404 f = input_open('/proc/ioports')
406 if line.endswith('ACPI PM_TMR\n'):
407 pm_timer_base = int(line.split('-')[0], 16)
414 def __init__(self, base, end_bus):
416 self.end_bus = end_bus
420 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
421 signature = f.read(4)
422 if signature != b'MCFG':
423 if options.generate_collector:
424 return MMConfig(0, 0)
425 raise RuntimeError('incorrect input file format %s' % signature)
426 (length,) = struct.unpack('<I', f.read(4))
428 raise RuntimeError('Multiple MMCONFIG regions found! '
429 'This is not supported')
431 (base, segment, start_bus, end_bus) = \
432 struct.unpack('<QHBB', f.read(12))
433 if segment != 0 or start_bus != 0:
434 raise RuntimeError('Invalid MCFG structure found')
435 return MMConfig(base, end_bus)
438 (pcidevices, pcicaps) = parse_pcidevices()
440 product = [input_readline('/sys/class/dmi/id/sys_vendor',
442 input_readline('/sys/class/dmi/id/product_name',
446 inmatemem = kmg_multiply_str(options.mem_inmates)
447 hvmem = [0, kmg_multiply_str(options.mem_hv)]
449 regions = parse_iomem()
450 ourmem = parse_cmdline()
451 total = hvmem[1] + inmatemem
453 mmconfig = MMConfig.parse()
455 ioapic_id, rmrr_regs = parse_dmar()
458 # kernel does not have memmap region, pick one
460 ourmem = alloc_mem(regions, total)
461 elif (total > ourmem[1]):
462 raise RuntimeError('Your memmap reservation is too small you need >="' +
467 creg = MemRegion.find_region(regions, 'ACPI Tables')
469 confmem = [creg.start, creg.size()]
471 print('WARNING: Could not find "ACPI Tables" memory! '
472 'You need to set it manually.', file=sys.stderr)
474 inmatereg = MemRegion(ourmem[0] + hvmem[1],
475 ourmem[0] + hvmem[1] + inmatemem - 1,
476 'JAILHOUSE Inmate Memory')
477 regions.append(inmatereg)
479 cpucount = count_cpus()
481 pm_timer_base = parse_ioports()
483 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
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.',
491 f = open(options.file, 'w')
493 if options.generate_collector:
494 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
495 filelist_opt = ' '.join(inputs['files_opt'])
497 tmpl = Template(filename='jailhouse-config-collect.tmpl')
498 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
500 tmpl = Template(filename='root-cell-config.c.tmpl')
501 f.write(tmpl.render(regions=regions,
503 argstr=' '.join(sys.argv),
507 pcidevices=pcidevices,
511 pm_timer_base=pm_timer_base,