]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
tools: config create: change the way input files are handled
[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 from __future__ import print_function
16 import sys
17 import os
18 import re
19 import argparse
20 import struct
21 import fnmatch
22 from mako.template import Template
23
24 datadir = None
25
26 if datadir:
27     template_default_dir = datadir + "/jailhouse"
28 else:
29     template_default_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
30
31 cpuvendor = None
32
33 # pretend to be part of the jailhouse tool
34 sys.argv[0] = sys.argv[0].replace('-', ' ')
35
36 parser = argparse.ArgumentParser()
37 parser.add_argument('-g', '--generate-collector',
38                     help='generate a script to collect input files on '
39                          'a remote machine',
40                     action='store_true')
41 parser.add_argument('-r', '--root',
42                     help='gather information in ROOT/, the default is "/" '
43                          'which means creating a config for localhost',
44                     default='/',
45                     action='store',
46                     type=str)
47 parser.add_argument('-t', '--template-dir',
48                     help='the directory where the templates are located,'
49                          'the default is "' + template_default_dir + '"',
50                     default=template_default_dir,
51                     action='store',
52                     type=str)
53
54 memargs = [['--mem-inmates', '2M', 'inmate'],
55            ['--mem-hv', '64M', 'hypervisor']]
56
57 for entry in memargs:
58     parser.add_argument(entry[0],
59                         help='the amount of ' + entry[2] +
60                              ' memory, default is "' + entry[1] +
61                              '", format "xxx[K|M|G]"',
62                         default=entry[1],
63                         action='store',
64                         type=str)
65
66 parser.add_argument('file', metavar='FILE',
67                     help='name of file to write out',
68                     type=str)
69
70 options = parser.parse_args()
71
72 inputs = {'files': set(), 'files_opt': set(), 'files_intel': set()}
73
74 ## required files
75 inputs['files'].add('/proc/iomem')
76 inputs['files'].add('/proc/cpuinfo')
77 inputs['files'].add('/proc/cmdline')
78 inputs['files'].add('/proc/ioports')
79 inputs['files'].add('/sys/bus/pci/devices/*/config')
80 inputs['files'].add('/sys/bus/pci/devices/*/class')
81 inputs['files'].add('/sys/devices/system/cpu/cpu*/uevent')
82 inputs['files'].add('/sys/firmware/acpi/tables/MCFG')
83 ## optional files
84 inputs['files_opt'].add('/sys/class/dmi/id/product_name')
85 inputs['files_opt'].add('/sys/class/dmi/id/sys_vendor')
86 inputs['files_opt'].add('/sys/devices/jailhouse/enabled')
87 ## platform specific files
88 inputs['files_intel'].add('/sys/firmware/acpi/tables/DMAR')
89
90
91 def kmg_multiply(value, kmg):
92     if (kmg == 'K' or kmg == 'k'):
93         return 1024 * value
94     if (kmg == 'M' or kmg == 'm'):
95         return 1024**2 * value
96     if (kmg == 'G' or kmg == 'g'):
97         return 1024**3 * value
98     return value
99
100
101 def kmg_multiply_str(str):
102     m = re.match(r'([0-9a-fA-FxX]+)([KMG]?)', str)
103     if m is not None:
104         return kmg_multiply(int(m.group(1)), m.group(2))
105     raise RuntimeError('kmg_multiply_str can not parse input "' + str + '"')
106
107
108 def check_input_listed(name, optional=False):
109     set = inputs['files_opt']
110     if optional is False:
111         set = inputs['files']
112         global cpuvendor
113         if cpuvendor == 'GenuineIntel':
114             set = set.union(inputs['files_intel'])
115
116     for file in set:
117         if fnmatch.fnmatch(name, file):
118             return True
119     raise RuntimeError('"' + name + '" is not a listed input file')
120
121
122 def input_open(name, mode='r', optional=False):
123     check_input_listed(name, optional)
124     try:
125         f = open(options.root + name, mode)
126     except Exception as e:
127         if optional:
128             return open("/dev/null", mode)
129         raise e
130     return f
131
132
133 def input_readline(name, optional=False):
134     f = input_open(name, optional=optional)
135     line = f.readline()
136     f.close()
137     return line
138
139
140 def input_listdir(dir, wildcards):
141     for w in wildcards:
142         check_input_listed(os.path.join(dir, w))
143     dirs = os.listdir(options.root + dir)
144     dirs.sort()
145     return dirs
146
147
148 class PCICapability:
149     def __init__(self, id, start, len, flags, content, msix_address):
150         self.id = id
151         self.start = start
152         self.len = len
153         self.flags = flags
154         self.content = content
155         self.msix_address = msix_address
156         self.comments = []
157
158     def __eq__(self, other):
159         return self.id == other.id and self.start == other.start and \
160             self.len == other.len and self.flags == other.flags
161
162     RD = '0'
163     RW = 'JAILHOUSE_PCICAPS_WRITE'
164
165     @staticmethod
166     def parse_pcicaps(dir):
167         caps = []
168         f = input_open(os.path.join(dir, 'config'), 'rb')
169         f.seek(0x06)
170         (status,) = struct.unpack('<H', f.read(2))
171         # capability list supported?
172         if (status & (1 << 4)) == 0:
173             f.close()
174             return caps
175         # walk capability list
176         f.seek(0x34)
177         (next,) = struct.unpack('B', f.read(1))
178         while next != 0:
179             cap = next
180             msix_address = 0
181             f.seek(cap)
182             (id, next) = struct.unpack('<BB', f.read(2))
183             if id == 0x01:  # Power Management
184                 # this cap can be handed out completely
185                 len = 8
186                 flags = PCICapability.RW
187             elif id == 0x05:  # MSI
188                 # access will be moderated by hypervisor
189                 len = 10
190                 (msgctl,) = struct.unpack('<H', f.read(2))
191                 if (msgctl & (1 << 7)) != 0:  # 64-bit support
192                     len += 4
193                 if (msgctl & (1 << 8)) != 0:  # per-vector masking support
194                     len += 10
195                 flags = PCICapability.RW
196             elif id == 0x11:  # MSI-X
197                 # access will be moderated by hypervisor
198                 len = 12
199                 (table,) = struct.unpack('<xxI', f.read(6))
200                 f.seek(0x10 + (table & 7) * 4)
201                 (bar,) = struct.unpack('<I', f.read(4))
202                 if (bar & 0x3) != 0:
203                     raise RuntimeError('Invalid MSI-X BAR found')
204                 if (bar & 0x4) != 0:
205                     bar |= struct.unpack('<I', f.read(4))[0] << 32
206                 msix_address = (bar & 0xfffffffffffffff0) + table & 0xfffffff8
207                 flags = PCICapability.RW
208             else:
209                 # unknown/unhandled cap, mark its existence
210                 len = 2
211                 flags = PCICapability.RD
212             f.seek(cap + 2)
213             content = f.read(len - 2)
214             caps.append(PCICapability(id, cap, len, flags, content,
215                                       msix_address))
216         return caps
217
218
219 class PCIDevice:
220     def __init__(self, type, domain, bus, dev, fn, caps):
221         self.type = type
222         self.iommu = None
223         self.domain = domain
224         self.bus = bus
225         self.dev = dev
226         self.fn = fn
227         self.caps = caps
228         self.caps_start = 0
229         self.num_caps = len(caps)
230         self.num_msi_vectors = 0
231         self.msi_64bits = 0
232         self.num_msix_vectors = 0
233         self.msix_region_size = 0
234         self.msix_address = 0
235         for c in caps:
236             if c.id in (0x05, 0x11):
237                 msg_ctrl = struct.unpack('<H', c.content[:2])[0]
238                 if c.id == 0x05:  # MSI
239                     self.num_msi_vectors = 1 << ((msg_ctrl >> 1) & 0x7)
240                     self.msi_64bits = (msg_ctrl >> 7) & 1
241                 else:  # MSI-X
242                     vectors = (msg_ctrl & 0x7ff) + 1
243                     self.num_msix_vectors = vectors
244                     self.msix_region_size = (vectors * 16 + 0xfff) & 0xf000
245                     self.msix_address = c.msix_address
246
247     def __str__(self):
248         return 'PCIDevice: %02x:%02x.%x' % (self.bus, self.dev, self.fn)
249
250     def bdf(self):
251         return self.bus << 8 | self.dev << 3 | self.fn
252
253     @staticmethod
254     def parse_pcidevice_sysfsdir(basedir, dir):
255         dpath = os.path.join(basedir, dir)
256         dclass = input_readline(os.path.join(dpath, 'class'))
257         if re.match(r'0x0604..', dclass):
258             type = 'JAILHOUSE_PCI_TYPE_BRIDGE'
259         else:
260             type = 'JAILHOUSE_PCI_TYPE_DEVICE'
261         a = dir.split(':')
262         domain = int(a[0], 16)
263         bus = int(a[1], 16)
264         df = a[2].split('.')
265         caps = PCICapability.parse_pcicaps(dpath)
266         return PCIDevice(type, domain, bus, int(df[0], 16), int(df[1], 16),
267                          caps)
268
269
270 class MemRegion:
271     def __init__(self, start, stop, typestr, comments=None):
272         self.start = start
273         self.stop = stop
274         self.typestr = typestr
275         if comments is None:
276             self.comments = []
277         else:
278             self.comments = comments
279
280     def __str__(self):
281         return 'MemRegion: %08x-%08x : %s' % \
282             (self.start, self.stop, self.typestr)
283
284     def size(self):
285         # round up to full PAGE_SIZE
286         return int((self.stop - self.start + 0xfff) / 0x1000) * 0x1000
287
288     def flagstr(self, p=''):
289         if (
290             self.typestr == 'System RAM' or
291             self.typestr == 'RAM buffer' or
292             self.typestr == 'ACPI DMAR RMRR'
293         ):
294             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
295             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
296             return s
297         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
298
299
300 class IOMemRegionTree:
301     def __init__(self, region, level, linenum):
302         self.region = region
303         self.linenum = linenum
304         self.level = level
305         self.parent = None
306         self.children = set()
307
308     def __str__(self):
309         s = ''
310         if (self.region):
311             s = (' ' * (self.level - 1)) + str(self.region) + ' line %d' \
312                 % (self.linenum)
313             if self.parent and self.parent.region:
314                 s += '--> ' + self.parent.region.typestr + ' line %d' \
315                     % (self.parent.linenum)
316             s += '\n'
317         for c in self.children:
318             s += str(c)
319         return s
320
321     @staticmethod
322     def parse_iomem_line(line):
323         a = line.split(':', 1)
324         level = int(a[0].count(' ') / 2) + 1
325         region = a[0].split('-', 1)
326         a[1] = a[1].strip()
327         return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
328
329     @staticmethod
330     def parse_iomem_file():
331         root = IOMemRegionTree(None, 0, -1)
332         f = input_open('/proc/iomem')
333         lastlevel = 0
334         lastnode = root
335         linenum = 0
336         for line in f:
337             (level, r) = IOMemRegionTree.parse_iomem_line(line)
338             t = IOMemRegionTree(r, level, linenum)
339             if (t.level > lastlevel):
340                 t.parent = lastnode
341             if (t.level == lastlevel):
342                 t.parent = lastnode.parent
343             if (t.level < lastlevel):
344                 p = lastnode.parent
345                 while(t.level < p.level):
346                     p = p.parent
347                 t.parent = p.parent
348
349             t.parent.children.add(t)
350             lastnode = t
351             lastlevel = t.level
352             linenum += 1
353         f.close()
354
355         return linenum, root
356
357     # recurse down the tree
358     @staticmethod
359     def parse_iomem_tree(tree):
360         regions = []
361         linenumbers = []
362
363         for tree in tree.children:
364             r = tree.region
365             s = r.typestr
366
367             # System RAM on first level will be added without digging deeper
368             if (tree.level == 1 and s == 'System RAM'):
369                 regions.append(r)
370                 linenumbers.append(tree.linenum)
371                 continue
372
373             # blacklisted on all levels
374             if (
375                 (s.find('PCI MMCONFIG') >= 0) or
376                 (s.find('APIC') >= 0) or  # covers both APIC and IOAPIC
377                 (s.find('dmar') >= 0)
378             ):
379                 continue
380
381             # generally blacklisted, unless we find an HPET right behind it
382             # on the next level
383             if (s == 'reserved'):
384                 for subtree in tree.children:
385                     r2 = subtree.region
386                     if (r2.typestr.find('HPET') >= 0):
387                         regions.append(r2)
388                         linenumbers.append(subtree.linenum)
389                 continue
390
391             # if the tree continues recurse further down ...
392             if (len(tree.children) > 0):
393                 ln2, r2 = IOMemRegionTree.parse_iomem_tree(tree)
394                 linenumbers.extend(ln2)
395                 regions.extend(r2)
396                 continue
397
398             # add all remaining leaves
399             regions.append(r)
400             linenumbers.append(tree.linenum)
401
402         return linenumbers, regions
403
404
405 def parse_iomem(pcidevices):
406     (maxsz, tree) = IOMemRegionTree.parse_iomem_file()
407
408     # create a spare array so we can easiely keep the order from the file
409     regions = [None for x in range(maxsz)]
410
411     lines, regs = IOMemRegionTree.parse_iomem_tree(tree)
412     i = 0
413     for l in lines:
414         regions[l] = regs[i]
415         i += 1
416
417     # now prepare a non-sparse array for a return value,
418     # also filtering out MSI-X pages
419     ret = []
420     for r in regions:
421         if r:
422             for d in pcidevices:
423                 if d.msix_address >= r.start and d.msix_address <= r.stop:
424                     if d.msix_address > r.start:
425                         head_r = MemRegion(r.start, d.msix_address - 1,
426                                            r.typestr, r.comments)
427                         ret.append(head_r)
428                     if d.msix_address + d.msix_region_size < r.stop:
429                         tail_r = MemRegion(d.msix_address + d.msix_region_size,
430                                            r.stop, r.typestr, r.comments)
431                         ret.append(tail_r)
432                     r = None
433                     break
434             if r:
435                 ret.append(r)
436
437     # newer Linux kernels will report the first page as reserved
438     # it is needed for CPU init so include it anyways
439     if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
440         ret[0].start = 0
441
442     return ret
443
444
445 def parse_pcidevices():
446     devices = []
447     caps = []
448     basedir = '/sys/bus/pci/devices'
449     list = input_listdir(basedir, ['*/class', '*/config'])
450     for dir in list:
451         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
452         if d is not None:
453             if len(d.caps) > 0:
454                 duplicate = False
455                 # look for duplicate capability patterns
456                 for d2 in devices:
457                     if d2.caps == d.caps:
458                         # reused existing capability list, but record all users
459                         d2.caps[0].comments.append(str(d))
460                         d.caps_start = d2.caps_start
461                         duplicate = True
462                         break
463                 if not duplicate:
464                     d.caps[0].comments.append(str(d))
465                     d.caps_start = len(caps)
466                     caps.extend(d.caps)
467             devices.append(d)
468     return (devices, caps)
469
470
471 def parse_cmdline():
472     line = input_readline('/proc/cmdline')
473     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
474                  '([0-9a-fA-FxX]+)([KMG]?).*',
475                  line)
476     if m is not None:
477         size = kmg_multiply(int(m.group(1), 0), m.group(2))
478         start = kmg_multiply(int(m.group(3), 0), m.group(4))
479         return [start, size]
480     return None
481
482
483 def alloc_mem(regions, size):
484     mem = [0x3b000000, size]
485     for r in regions:
486         if (
487             r.typestr == 'System RAM' and
488             r.start <= mem[0] and
489             r.stop + 1 >= mem[0] + mem[1]
490         ):
491             if r.start < mem[0]:
492                 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
493                 regions.insert(regions.index(r), head_r)
494             if r.stop + 1 > mem[0] + mem[1]:
495                 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
496                                    r.comments)
497                 regions.insert(regions.index(r), tail_r)
498             regions.remove(r)
499             return mem
500     for r in reversed(regions):
501         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
502             mem[0] = r.start
503             r.start += mem[1]
504             return mem
505     raise RuntimeError('failed to allocate memory')
506
507
508 def count_cpus():
509     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
510     count = 0
511     for f in list:
512         if re.match(r'cpu[0-9]+', f):
513             count += 1
514     return count
515
516
517 def parse_dmar_devscope(f):
518     (scope_type, scope_len, bus, dev, fn) = \
519         struct.unpack('<BBxxxBBB', f.read(8))
520     if scope_len != 8:
521         raise RuntimeError('Unsupported DMAR Device Scope Structure')
522     return (scope_type, scope_len, bus, dev, fn)
523
524
525 # parsing of DMAR ACPI Table
526 # see Intel VT-d Spec chapter 8
527 def parse_dmar(pcidevices):
528     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
529     signature = f.read(4)
530     if signature != b'DMAR':
531         raise RuntimeError('DMAR: incorrect input file format %s' % signature)
532     (length,) = struct.unpack('<I', f.read(4))
533     f.seek(48)
534     length -= 48
535     units = []
536     regions = []
537     ioapic_id = 0
538
539     while length > 0:
540         offset = 0
541         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
542         offset += 4
543         length -= struct_len
544
545         # DMA Remapping Hardware Unit Definition
546         if struct_type == 0:
547             (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
548             if segment != 0:
549                 raise RuntimeError('We do not support multiple PCI segments')
550             if len(units) >= 8:
551                 raise RuntimeError('Too many DMAR units. '
552                                    'Raise JAILHOUSE_MAX_DMAR_UNITS.')
553             units.append(base)
554             if flags & 1:
555                 for d in pcidevices:
556                     if d.iommu is None:
557                         d.iommu = len(units) - 1
558             offset += 16 - offset
559             while offset < struct_len:
560                 (scope_type, scope_len, bus, dev, fn) =\
561                     parse_dmar_devscope(f)
562                 if scope_type == 1:
563                     for d in pcidevices:
564                         if d.bus == bus and d.dev == dev and d.fn == fn:
565                             d.iommu = len(units) - 1
566                 elif scope_type == 2:
567                     raise RuntimeError('Unsupported DMAR Device Scope type')
568                 elif scope_type == 3:
569                     if ioapic_id != 0:
570                         raise RuntimeError('We do not support more '
571                                            'than 1 IOAPIC')
572                     # encode the DMAR unit number into the device ID
573                     ioapic_id = ((len(units) - 1) << 16) | \
574                         (bus << 8) | (dev << 3) | fn
575                 offset += scope_len
576
577         # Reserved Memory Region Reporting Structure
578         if struct_type == 1:
579             f.seek(8 - offset, os.SEEK_CUR)
580             offset += 8 - offset
581             (base, limit) = struct.unpack('<QQ', f.read(16))
582             offset += 16
583
584             comments = []
585             while offset < struct_len:
586                 (scope_type, scope_len, bus, dev, fn) =\
587                     parse_dmar_devscope(f)
588                 if scope_type == 1:
589                     comments.append('PCI device: %02x:%02x.%x' %
590                                     (bus, dev, fn))
591                 else:
592                     comments.append('DMAR parser could not decode device path')
593                 offset += scope_len
594
595             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
596             regions.append(reg)
597
598         f.seek(struct_len - offset, os.SEEK_CUR)
599
600     return units, ioapic_id, regions
601
602
603 def parse_ioports():
604     pm_timer_base = None
605     f = input_open('/proc/ioports')
606     for line in f:
607         if line.endswith('ACPI PM_TMR\n'):
608             pm_timer_base = int(line.split('-')[0], 16)
609             break
610     f.close()
611     return pm_timer_base
612
613
614 class MMConfig:
615     def __init__(self, base, end_bus):
616         self.base = base
617         self.end_bus = end_bus
618
619     @staticmethod
620     def parse():
621         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
622         signature = f.read(4)
623         if signature != b'MCFG':
624             raise RuntimeError('MCFG: incorrect input file format %s' %
625                                signature)
626         (length,) = struct.unpack('<I', f.read(4))
627         if length > 60:
628             raise RuntimeError('Multiple MMCONFIG regions found! '
629                                'This is not supported')
630         f.seek(44)
631         (base, segment, start_bus, end_bus) = \
632             struct.unpack('<QHBB', f.read(12))
633         if segment != 0 or start_bus != 0:
634             raise RuntimeError('Invalid MCFG structure found')
635         return MMConfig(base, end_bus)
636
637
638 def get_cpu_vendor():
639     global cpuvendor
640     if cpuvendor is not None:
641         return cpuvendor
642     with input_open('/proc/cpuinfo', 'r') as f:
643         for line in f:
644             if not line.strip():
645                 continue
646             key, value = line.split(':')
647             if key.strip() == 'vendor_id':
648                 cpuvendor = value.strip()
649                 return cpuvendor
650
651
652 if options.generate_collector:
653     f = open(options.file, 'w')
654     filelist = ' '.join(inputs['files'])
655     filelist_opt = ' '.join(inputs['files_opt'])
656     filelist_intel = ' '.join(inputs['files_intel'])
657
658     tmpl = Template(filename=os.path.join(options.template_dir,
659                                           'jailhouse-config-collect.tmpl'))
660     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
661             filelist_intel=filelist_intel))
662     f.close()
663     sys.exit(0)
664
665 if ((options.root is '/') and (os.geteuid() is not 0)):
666     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
667     sys.exit(1)
668
669 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
670 if jh_enabled == '1':
671     print('ERROR: Jailhouse was enabled when collecting input files! '
672           'Disable jailhouse and try again.',
673           file=sys.stderr)
674     sys.exit(1)
675
676 (pcidevices, pcicaps) = parse_pcidevices()
677
678 product = [input_readline('/sys/class/dmi/id/sys_vendor',
679                           True).rstrip(),
680            input_readline('/sys/class/dmi/id/product_name',
681                           True).rstrip()
682            ]
683
684 inmatemem = kmg_multiply_str(options.mem_inmates)
685 hvmem = [0, kmg_multiply_str(options.mem_hv)]
686
687 regions = parse_iomem(pcidevices)
688 ourmem = parse_cmdline()
689 total = hvmem[1] + inmatemem
690
691 mmconfig = MMConfig.parse()
692
693 if get_cpu_vendor() == 'GenuineIntel':
694     (dmar_units, ioapic_id, rmrr_regs) = parse_dmar(pcidevices)
695 else:
696     (dmar_units, ioapic_id, rmrr_regs) = [], 0, []
697 regions += rmrr_regs
698
699 for d in pcidevices:
700     if get_cpu_vendor() == 'AuthenticAMD':
701         d.iommu = 0  # temporary workaround
702     if d.iommu is None:
703         raise RuntimeError('PCI device %02x:%02x.%x outside the scope of an '
704                            'IOMMU' % (d.bus, d.dev, d.fn))
705
706 # kernel does not have memmap region, pick one
707 if ourmem is None:
708     ourmem = alloc_mem(regions, total)
709 elif (total > ourmem[1]):
710     raise RuntimeError('Your memmap reservation is too small you need >="' +
711                        hex(total) + '"')
712
713 hvmem[0] = ourmem[0]
714
715 inmatereg = MemRegion(ourmem[0] + hvmem[1],
716                       ourmem[0] + hvmem[1] + inmatemem - 1,
717                       'JAILHOUSE Inmate Memory')
718 regions.append(inmatereg)
719
720 cpucount = count_cpus()
721
722 pm_timer_base = parse_ioports()
723
724
725 f = open(options.file, 'w')
726 tmpl = Template(filename=os.path.join(options.template_dir,
727                                       'root-cell-config.c.tmpl'))
728 f.write(tmpl.render(regions=regions,
729                     ourmem=ourmem,
730                     argstr=' '.join(sys.argv),
731                     hvmem=hvmem,
732                     product=product,
733                     pcidevices=pcidevices,
734                     pcicaps=pcicaps,
735                     cpucount=cpucount,
736                     ioapic_id=ioapic_id,
737                     pm_timer_base=pm_timer_base,
738                     mmconfig=mmconfig,
739                     dmar_units=dmar_units))
740
741 f.close()