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.
20 from mako.template import Template
22 # pretend to be part of the jailhouse tool
23 sys.argv[0] = sys.argv[0].replace('-', ' ')
25 parser = argparse.ArgumentParser()
26 parser.add_argument('-g', '--generate-collector',
27 help='generate a script to collect input files on '
30 parser.add_argument('-r', '--root',
31 help='gather information in ROOT/, the default is "/" '
32 'which means creating a config for localhost',
37 memargs = [['--mem-inmates', '2M', 'inmate'],
38 ['--mem-hv', '64M', 'hypervisor']]
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]"',
49 parser.add_argument('file', metavar='FILE',
50 help='name of file to write out',
53 options = parser.parse_args()
55 inputs = {'files': set(), 'dirs': set()}
59 def __init__(self, type, domain, bus, dev, fn):
67 return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
70 return self.dev << 3 | self.fn
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'
78 type = 'JAILHOUSE_PCI_TYPE_DEVICE'
80 domain = int(a[0], 16)
83 return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16))
87 def __init__(self, start, stop, typestr, comments=[]):
90 self.typestr = typestr
91 self.comments = comments
94 return 'MemRegion: %08x-%08x : %s' % \
95 (self.start, self.stop, self.typestr)
98 # round up to full PAGE_SIZE
99 return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
101 def flagstr(self, p=''):
103 self.typestr == 'ACPI Tables' or
104 self.typestr == 'ACPI Non-volatile Storage'
106 return 'JAILHOUSE_MEM_READ'
108 self.typestr == 'System RAM' or
109 self.typestr == 'RAM buffer' or
110 self.typestr == 'ACPI DMAR RMRR'
112 s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
113 s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
115 return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
118 # return the first region with the given typestr
119 def find_region(regions, typestr):
121 if (r.typestr == typestr):
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:
131 region = a[0].split('-', 1)
133 return MemRegion(int(region[0], 16), int(region[1], 16), a[1])
138 f, e = input_open('/proc/iomem', True, False, 'r')
140 r = MemRegion.parse_iomem_line(line)
141 ## XXX what else to ignore??
144 r.typestr != 'Local APIC' and
145 r.typestr != 'reserved'
150 # newer Linux kernels will report the first page as reserved
151 # it is needed for CPU init so include it anyways
153 regions[0].typestr == 'System RAM' and
154 regions[0].start == 0x1000
161 def parse_pcidevices():
163 basedir = '/sys/bus/pci/devices'
164 list = input_listdir(basedir, ['*/class'])
166 d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
172 def kmg_multiply(value, kmg):
173 if (kmg == 'K' or kmg == 'k'):
175 if (kmg == 'M' or kmg == 'm'):
176 return 1024**2 * value
177 if (kmg == 'G' or kmg == 'g'):
178 return 1024**3 * value
182 def kmg_multiply_str(str):
183 m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
185 return kmg_multiply(int(m.group(1)), m.group(2))
186 raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
190 def input_open(name, record, optional, *args):
192 inputs['files'].add(name)
194 f = open(options.root + name, *args)
195 except Exception as e:
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:
212 def input_listdir(dir, wildcards):
214 inputs['dirs'].add(dir + '/' + w)
215 return os.listdir(options.root + dir)
219 line = input_readline('/proc/cmdline')
220 m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
221 '([0-9a-fA-FxX]+)([KMG]?).*',
224 size = kmg_multiply(int(m.group(1), 0), m.group(2))
225 start = kmg_multiply(int(m.group(3), 0), m.group(4))
230 def alloc_mem(regions, size):
232 for r in reversed(regions):
233 if (r.typestr == 'System RAM' and r.size() >= mem[1]):
237 raise RuntimeError('failed to allocate memory')
241 list = input_listdir('/sys/devices/system/cpu', ['cpu*/topology/core_id'])
244 if re.match(r'cpu[0-9]+', f):
249 def parse_dmar_devscope(f):
251 (scope_type, scope_len, bus, dev, fn) = \
252 struct.unpack('<BBxxxBBB', f.read(8))
254 return (offset, scope_type, scope_len, bus, dev, fn)
257 # parsing of DMAR ACPI Table
258 # see Intel VT-d Spec chapter 8
260 f, e = input_open('/sys/firmware/acpi/tables/DMAR', True, True, 'rb')
262 if options.generate_collector:
266 raise RuntimeError('could not find DMAR ACPI table')
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))
279 (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
283 # DMA Remapping Hardware Unit Definition
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)
293 raise RuntimeError('We do not support more '
295 ioapic_id = (bus << 8) | (dev << 3) | fn
296 f.seek(scope_len - 8, os.SEEK_CUR)
297 offset += scope_len - 8
299 # Reserved Memory Region Reporting Structure
301 f.seek(8 - offset, os.SEEK_CUR)
303 (base, limit) = struct.unpack('<QQ', f.read(16))
307 while offset < struct_len:
308 (off, scope_type, scope_len, bus, dev, fn) =\
309 parse_dmar_devscope(f)
311 npath = (scope_len - 6)/2
312 if scope_type == 1 and npath == 1:
313 comments.append('PCI device: %02x:%02x.%x' %
316 comments.append('DMAR parser could not decode device path')
317 f.seek(scope_len - off, os.SEEK_CUR)
318 offset += scope_len - off
320 reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
323 f.seek(struct_len - offset, os.SEEK_CUR)
325 return ioapic_id, regions
327 pcidevices = parse_pcidevices()
329 product = [input_readline('/sys/class/dmi/id/sys_vendor',
330 True, True).rstrip(),
331 input_readline('/sys/class/dmi/id/product_name',
335 inmatemem = kmg_multiply_str(options.mem_inmates)
336 hvmem = [0, kmg_multiply_str(options.mem_hv)]
338 regions = parse_iomem()
339 ourmem = parse_cmdline()
340 total = hvmem[1] + inmatemem
342 ioapic_id, rmrr_regs = parse_dmar()
345 # kernel does not have memmap region, pick one
347 ourmem = alloc_mem(regions, total)
348 elif (total > ourmem[1]):
349 raise RuntimeError('Your memmap reservation is too small you need >="' +
354 creg = MemRegion.find_region(regions, 'ACPI Tables')
356 raise RuntimeError('could not find "ACPI Tables" memory')
357 confmem = [creg.start, creg.size()]
358 inmatereg = MemRegion(ourmem[0] + hvmem[1],
359 ourmem[0] + hvmem[1] + inmatemem - 1,
360 'JAILHOUSE Inmate Memory')
361 regions.append(inmatereg)
363 cpucount = count_cpus()
365 f = open(options.file, 'w')
367 if options.generate_collector:
368 filelist = ' '.join(inputs['files'].union(inputs['dirs']))
370 tmpl = Template(filename='jailhouse-config-collect.tmpl')
371 f.write(tmpl.render(filelist=filelist))
373 tmpl = Template(filename='root-cell-config.c.tmpl')
374 f.write(tmpl.render(regions=regions,
376 argstr=' '.join(sys.argv),
380 pcidevices=pcidevices,
382 ioapic_id=ioapic_id))