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 abspath = os.path.abspath(os.path.dirname(sys.argv[0]))
25 # pretend to be part of the jailhouse tool
26 sys.argv[0] = sys.argv[0].replace('-', ' ')
28 parser = argparse.ArgumentParser()
29 parser.add_argument('-g', '--generate-collector',
30 help='generate a script to collect input files on '
33 parser.add_argument('-r', '--root',
34 help='gather information in ROOT/, the default is "/" '
35 'which means creating a config for localhost',
39 parser.add_argument('-t', '--template-dir',
40 help='the directory where the templates are located,'
41 'the default is "' + abspath + '"',
46 memargs = [['--mem-inmates', '2M', 'inmate'],
47 ['--mem-hv', '64M', 'hypervisor']]
50 parser.add_argument(entry[0],
51 help='the amount of ' + entry[2] +
52 ' memory, default is "' + entry[1] +
53 '", format "xxx[K|M|G]"',
58 parser.add_argument('file', metavar='FILE',
59 help='name of file to write out',
62 options = parser.parse_args()
64 inputs = {'files': set(), 'files_opt': set(), 'dirs': set()}
68 def __init__(self, id, start, len, flags):
75 def __eq__(self, other):
76 return self.id == other.id and self.start == other.start and \
77 self.len == other.len and self.flags == other.flags
80 RW = 'JAILHOUSE_PCICAPS_WRITE'
83 def parse_pcicaps(dir):
85 f = input_open(os.path.join(dir, 'config'), 'rb')
87 (status,) = struct.unpack('<H', f.read(2))
88 # capability list supported?
89 if (status & (1 << 4)) == 0:
92 # walk capability list
94 (next,) = struct.unpack('B', f.read(1))
98 (id, next) = struct.unpack('<BB', f.read(2))
99 if id == 0x01: # Power Management
100 # this cap can be handed out completely
102 flags = PCICapability.RW
103 elif id == 0x05: # MSI
104 # access will be moderated by hypervisor
106 (msgctl,) = struct.unpack('<H', f.read(2))
107 if (msgctl & (1 << 7)) != 0: # 64-bit support
109 if (msgctl & (1 << 8)) != 0: # per-vector masking support
111 flags = PCICapability.RW
112 elif id == 0x11: # MSI-X
113 # access will be moderated by hypervisor
115 flags = PCICapability.RW
117 # unknown/unhandled cap, mark its existence
119 flags = PCICapability.RD
120 caps.append(PCICapability(id, cap, len, flags))
125 def __init__(self, type, domain, bus, dev, fn, caps):
133 self.num_caps = len(caps)
136 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
139 return self.bus << 8 | self.dev << 3 | self.fn
142 def parse_pcidevice_sysfsdir(basedir, dir):
143 dpath = os.path.join(basedir, dir)
144 dclass = input_readline(os.path.join(dpath, 'class'))
145 if re.match(r'0x0604..', dclass):
146 type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
148 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
150 domain = int(a[0], 16)
153 caps = PCICapability.parse_pcicaps(dpath)
154 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
159 def __init__(self, start, stop, typestr, comments=[]):
162 self.typestr = typestr
163 self.comments = comments
166 return 'MemRegion: %08x-%08x : %s' % \
167 (self.start, self.stop, self.typestr)
170 # round up to full PAGE_SIZE
171 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
173 def flagstr(self, p=''):
175 self.typestr == 'ACPI Tables' or
176 self.typestr == 'ACPI Non-volatile Storage'
178 return 'JAILHOUSE_MEM_READ'
180 self.typestr == 'System RAM' or
181 self.typestr == 'RAM buffer' or
182 self.typestr == 'ACPI DMAR RMRR'
184 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
185 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
187 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
190 # return the first region with the given typestr
191 def find_region(regions, typestr):
193 if (r.typestr == typestr):
198 def parse_iomem_line(line):
199 a = line.split(':', 1)
200 # HPET may be part of in reserved region
201 if a[0].startswith(' ') and a[1].find("HPET") < 0:
203 region = a[0].split('-', 1)
205 return MemRegion(int(region[0], 16), int(region[1], 16), a[1])
210 f = input_open('/proc/iomem')
212 r = MemRegion.parse_iomem_line(line)
213 ## XXX what else to ignore??
216 r.typestr != 'Local APIC' and
217 r.typestr != 'reserved'
222 # newer Linux kernels will report the first page as reserved
223 # it is needed for CPU init so include it anyways
225 regions[0].typestr == 'System RAM' and
226 regions[0].start == 0x1000
233 def parse_pcidevices():
236 basedir = '/sys/bus/pci/devices'
237 list = input_listdir(basedir, ['*/class', '*/config'])
239 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
243 # look for duplicate capability patterns
245 if d2.caps == d.caps:
246 # reused existing capability list, but record all users
247 d2.caps[0].comments.append(str(d))
248 d.caps_start = d2.caps_start
252 d.caps[0].comments.append(str(d))
253 d.caps_start = len(caps)
256 return (devices, caps)
259 def kmg_multiply(value, kmg):
260 if (kmg == 'K' or kmg == 'k'):
262 if (kmg == 'M' or kmg == 'm'):
263 return 1024**2 * value
264 if (kmg == 'G' or kmg == 'g'):
265 return 1024**3 * value
269 def kmg_multiply_str(str):
270 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
272 return kmg_multiply(int(m.group(1)), m.group(2))
273 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
277 def input_open(name, mode='r', optional=False):
278 inputs['files_opt' if optional else 'files'].add(name)
280 f = open(options.root + name, mode)
281 except Exception as e:
282 if optional or options.generate_collector:
283 return open("/dev/null", mode)
288 def input_readline(name, optional=False):
289 f = input_open(name, optional=optional)
295 def input_listdir(dir, wildcards):
297 inputs['dirs'].add(os.path.join(dir, w))
298 if options.generate_collector:
300 dirs = os.listdir(options.root + dir)
306 line = input_readline('/proc/cmdline')
307 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
308 '([0-9a-fA-FxX]+)([KMG]?).*',
311 size = kmg_multiply(int(m.group(1), 0), m.group(2))
312 start = kmg_multiply(int(m.group(3), 0), m.group(4))
317 def alloc_mem(regions, size):
319 for r in reversed(regions):
320 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
324 raise RuntimeError('failed to allocate memory')
328 list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
331 if re.match(r'cpu[0-9]+', f):
336 def parse_dmar_devscope(f):
338 (scope_type, scope_len, bus, dev, fn) = \
339 struct.unpack('<BBxxxBBB', f.read(8))
341 return (offset, scope_type, scope_len, bus, dev, fn)
344 # parsing of DMAR ACPI Table
345 # see Intel VT-d Spec chapter 8
347 f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
348 signature = f.read(4)
349 if signature != b'DMAR':
350 if options.generate_collector:
352 raise RuntimeError('incorrect input file format %s' % signature)
353 (length,) = struct.unpack('<I', f.read(4))
362 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
366 # DMA Remapping Hardware Unit Definition
368 (segment, base) = struct.unpack('<xxHQ', f.read(12))
370 raise RuntimeError('We do not support multiple PCI segments')
372 raise RuntimeError('Too many DMAR units. '
373 'Raise JAILHOUSE_MAX_DMAR_UNITS.')
375 offset += 16 - offset
376 while offset < struct_len:
377 (off, scope_type, scope_len, bus, dev, fn) =\
378 parse_dmar_devscope(f)
382 raise RuntimeError('We do not support more '
384 ioapic_id = (bus << 8) | (dev << 3) | fn
385 f.seek(scope_len - 8, os.SEEK_CUR)
386 offset += scope_len - 8
388 # Reserved Memory Region Reporting Structure
390 f.seek(8 - offset, os.SEEK_CUR)
392 (base, limit) = struct.unpack('<QQ', f.read(16))
396 while offset < struct_len:
397 (off, scope_type, scope_len, bus, dev, fn) =\
398 parse_dmar_devscope(f)
400 npath = (scope_len - 6)/2
401 if scope_type == 1 and npath == 1:
402 comments.append('PCI device: %02x:%02x.%x' %
405 comments.append('DMAR parser could not decode device path')
406 f.seek(scope_len - off, os.SEEK_CUR)
407 offset += scope_len - off
409 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
412 f.seek(struct_len - offset, os.SEEK_CUR)
414 return units, ioapic_id, regions
419 f = input_open('/proc/ioports')
421 if line.endswith('ACPI PM_TMR\n'):
422 pm_timer_base = int(line.split('-')[0], 16)
429 def __init__(self, base, end_bus):
431 self.end_bus = end_bus
435 f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
436 signature = f.read(4)
437 if signature != b'MCFG':
438 if options.generate_collector:
439 return MMConfig(0, 0)
440 raise RuntimeError('incorrect input file format %s' % signature)
441 (length,) = struct.unpack('<I', f.read(4))
443 raise RuntimeError('Multiple MMCONFIG regions found! '
444 'This is not supported')
446 (base, segment, start_bus, end_bus) = \
447 struct.unpack('<QHBB', f.read(12))
448 if segment != 0 or start_bus != 0:
449 raise RuntimeError('Invalid MCFG structure found')
450 return MMConfig(base, end_bus)
453 (pcidevices, pcicaps) = parse_pcidevices()
455 product = [input_readline('/sys/class/dmi/id/sys_vendor',
457 input_readline('/sys/class/dmi/id/product_name',
461 inmatemem = kmg_multiply_str(options.mem_inmates)
462 hvmem = [0, kmg_multiply_str(options.mem_hv)]
464 regions = parse_iomem()
465 ourmem = parse_cmdline()
466 total = hvmem[1] + inmatemem
468 mmconfig = MMConfig.parse()
470 (dmar_units, ioapic_id, rmrr_regs) = parse_dmar()
473 # kernel does not have memmap region, pick one
475 ourmem = alloc_mem(regions, total)
476 elif (total > ourmem[1]):
477 raise RuntimeError('Your memmap reservation is too small you need >="' +
482 inmatereg = MemRegion(ourmem[0] + hvmem[1],
483 ourmem[0] + hvmem[1] + inmatemem - 1,
484 'JAILHOUSE Inmate Memory')
485 regions.append(inmatereg)
487 cpucount = count_cpus()
489 pm_timer_base = parse_ioports()
491 jh_enabled = input_readline('/sys/devices/jailhouse/enabled',
493 if options.generate_collector is False and jh_enabled == '1':
494 print('ERROR: Jailhouse was enabled when collecting input files! '
495 'Disable jailhouse and try again.',
499 f = open(options.file, 'w')
501 if options.generate_collector:
502 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
503 filelist_opt = ' '.join(inputs['files_opt'])
505 tmpl = Template(filename=os.path.join(options.template_dir,
506 'jailhouse-config-collect.tmpl'))
507 f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt))
509 tmpl = Template(filename=os.path.join(options.template_dir,
510 'root-cell-config.c.tmpl'))
511 f.write(tmpl.render(regions=regions,
513 argstr=' '.join(sys.argv),
516 pcidevices=pcidevices,
520 pm_timer_base=pm_timer_base,
522 dmar_units=dmar_units))