]> rtime.felk.cvut.cz Git - jailhouse.git/blob - tools/jailhouse-config-create
Revert "x86/tools/inmates: Account for 32-bit PM timers"
[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 == 'Kernel' or
292             self.typestr == 'RAM buffer' or
293             self.typestr == 'ACPI DMAR RMRR'
294         ):
295             s = 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE |\n'
296             s += p + '\t\tJAILHOUSE_MEM_EXECUTE | JAILHOUSE_MEM_DMA'
297             return s
298         return 'JAILHOUSE_MEM_READ | JAILHOUSE_MEM_WRITE'
299
300
301 class IOMemRegionTree:
302     def __init__(self, region, level):
303         self.region = region
304         self.level = level
305         self.parent = None
306         self.children = []
307
308     def __str__(self):
309         s = ''
310         if (self.region):
311             s = (' ' * (self.level - 1)) + str(self.region)
312             if self.parent and self.parent.region:
313                 s += ' --> ' + self.parent.region.typestr
314             s += '\n'
315         for c in self.children:
316             s += str(c)
317         return s
318
319     def regions_split_by_kernel(self):
320         kernel = [x for x in self.children if
321                     x.region.typestr.startswith('Kernel ')]
322
323         if (len(kernel) == 0):
324             return [self.region]
325
326         r = self.region
327         s = r.typestr
328
329         kernel_start = kernel[0].region.start
330         kernel_stop = kernel[len(kernel) - 1].region.stop
331
332         # align this for 16M, but only if we have enough space
333         kernel_stop = (kernel_stop & ~0xFFFFFF) + 0xFFFFFF
334         if (kernel_stop > r.stop):
335             kernel_stop = r.stop
336
337         before_kernel = None
338         after_kernel = None
339
340         # before Kernel if any
341         if (r.start < kernel_start):
342             before_kernel = MemRegion(r.start, kernel_start - 1, s)
343
344         kernel_region = MemRegion(kernel_start, kernel_stop, "Kernel")
345
346         # after Kernel if any
347         if (r.stop > kernel_stop):
348             after_kernel = MemRegion(kernel_stop + 1, r.stop, s)
349
350         return [before_kernel, kernel_region, after_kernel]
351
352     @staticmethod
353     def parse_iomem_line(line):
354         a = line.split(':', 1)
355         level = int(a[0].count(' ') / 2) + 1
356         region = a[0].split('-', 1)
357         a[1] = a[1].strip()
358         return level, MemRegion(int(region[0], 16), int(region[1], 16), a[1])
359
360     @staticmethod
361     def parse_iomem_file():
362         root = IOMemRegionTree(None, 0)
363         f = input_open('/proc/iomem')
364         lastlevel = 0
365         lastnode = root
366         for line in f:
367             (level, r) = IOMemRegionTree.parse_iomem_line(line)
368             t = IOMemRegionTree(r, level)
369             if (t.level > lastlevel):
370                 t.parent = lastnode
371             if (t.level == lastlevel):
372                 t.parent = lastnode.parent
373             if (t.level < lastlevel):
374                 p = lastnode.parent
375                 while(t.level < p.level):
376                     p = p.parent
377                 t.parent = p.parent
378
379             t.parent.children.append(t)
380             lastnode = t
381             lastlevel = t.level
382         f.close()
383
384         return root
385
386     # find HPET regions in tree
387     @staticmethod
388     def find_hpet_regions(tree):
389         regions = []
390
391         for tree in tree.children:
392             r = tree.region
393             s = r.typestr
394
395             if (s.find('HPET') >= 0):
396                 regions.append(r)
397
398             # if the tree continues recurse further down ...
399             if (len(tree.children) > 0):
400                 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
401
402         return regions
403
404     # recurse down the tree
405     @staticmethod
406     def parse_iomem_tree(tree):
407         regions = []
408
409         for tree in tree.children:
410             r = tree.region
411             s = r.typestr
412
413             # System RAM on the first level will be added completely,
414             # if they don't contain the kernel itself, if they do,
415             # we split them
416             if (tree.level == 1 and s == 'System RAM'):
417                 regions.extend(tree.regions_split_by_kernel())
418                 continue
419
420             # blacklisted on all levels
421             if (
422                 (s.find('PCI MMCONFIG') >= 0) or
423                 (s.find('APIC') >= 0) or  # covers both APIC and IOAPIC
424                 (s.find('dmar') >= 0)
425             ):
426                 continue
427
428             # generally blacklisted, unless we find an HPET behind it
429             if (s == 'reserved'):
430                 regions.extend(IOMemRegionTree.find_hpet_regions(tree))
431                 continue
432
433             # if the tree continues recurse further down ...
434             if (len(tree.children) > 0):
435                 regions.extend(IOMemRegionTree.parse_iomem_tree(tree))
436                 continue
437
438             # add all remaining leaves
439             regions.append(r)
440
441         return regions
442
443
444 def parse_iomem(pcidevices):
445     regions = IOMemRegionTree.parse_iomem_tree(
446                     IOMemRegionTree.parse_iomem_file())
447
448     # filter the list for MSI-X pages
449     ret = []
450     for r in regions:
451         for d in pcidevices:
452             if d.msix_address >= r.start and d.msix_address <= r.stop:
453                 if d.msix_address > r.start:
454                     head_r = MemRegion(r.start, d.msix_address - 1,
455                                        r.typestr, r.comments)
456                     ret.append(head_r)
457                 if d.msix_address + d.msix_region_size < r.stop:
458                     tail_r = MemRegion(d.msix_address + d.msix_region_size,
459                                        r.stop, r.typestr, r.comments)
460                     ret.append(tail_r)
461                 r = None
462                 break
463         if r:
464             ret.append(r)
465
466     # newer Linux kernels will report the first page as reserved
467     # it is needed for CPU init so include it anyways
468     if (ret[0].typestr == 'System RAM' and ret[0].start == 0x1000):
469         ret[0].start = 0
470
471     return ret
472
473
474 def parse_pcidevices():
475     devices = []
476     caps = []
477     basedir = '/sys/bus/pci/devices'
478     list = input_listdir(basedir, ['*/class', '*/config'])
479     for dir in list:
480         d = PCIDevice.parse_pcidevice_sysfsdir(basedir, dir)
481         if d is not None:
482             if len(d.caps) > 0:
483                 duplicate = False
484                 # look for duplicate capability patterns
485                 for d2 in devices:
486                     if d2.caps == d.caps:
487                         # reused existing capability list, but record all users
488                         d2.caps[0].comments.append(str(d))
489                         d.caps_start = d2.caps_start
490                         duplicate = True
491                         break
492                 if not duplicate:
493                     d.caps[0].comments.append(str(d))
494                     d.caps_start = len(caps)
495                     caps.extend(d.caps)
496             devices.append(d)
497     return (devices, caps)
498
499
500 def parse_kernel_cmdline():
501     line = input_readline('/proc/cmdline')
502     m = re.match(r'.*memmap=([0-9a-fA-FxX]+)([KMG]?)\$'
503                  '([0-9a-fA-FxX]+)([KMG]?).*',
504                  line)
505     if m is not None:
506         size = kmg_multiply(int(m.group(1), 0), m.group(2))
507         start = kmg_multiply(int(m.group(3), 0), m.group(4))
508         return [start, size]
509     return None
510
511
512 def alloc_mem(regions, size):
513     mem = [0x3b000000, size]
514     for r in regions:
515         if (
516             r.typestr == 'System RAM' and
517             r.start <= mem[0] and
518             r.stop + 1 >= mem[0] + mem[1]
519         ):
520             if r.start < mem[0]:
521                 head_r = MemRegion(r.start, mem[0] - 1, r.typestr, r.comments)
522                 regions.insert(regions.index(r), head_r)
523             if r.stop + 1 > mem[0] + mem[1]:
524                 tail_r = MemRegion(mem[0] + mem[1], r.stop, r.typestr,
525                                    r.comments)
526                 regions.insert(regions.index(r), tail_r)
527             regions.remove(r)
528             return mem
529     for r in reversed(regions):
530         if (r.typestr == 'System RAM' and r.size() >= mem[1]):
531             mem[0] = r.start
532             r.start += mem[1]
533             return mem
534     raise RuntimeError('failed to allocate memory')
535
536
537 def count_cpus():
538     list = input_listdir('/sys/devices/system/cpu', ['cpu*/uevent'])
539     count = 0
540     for f in list:
541         if re.match(r'cpu[0-9]+', f):
542             count += 1
543     return count
544
545
546 def parse_dmar_devscope(f):
547     (scope_type, scope_len, bus, dev, fn) = \
548         struct.unpack('<BBxxxBBB', f.read(8))
549     if scope_len != 8:
550         raise RuntimeError('Unsupported DMAR Device Scope Structure')
551     return (scope_type, scope_len, bus, dev, fn)
552
553
554 # parsing of DMAR ACPI Table
555 # see Intel VT-d Spec chapter 8
556 def parse_dmar(pcidevices):
557     f = input_open('/sys/firmware/acpi/tables/DMAR', 'rb')
558     signature = f.read(4)
559     if signature != b'DMAR':
560         raise RuntimeError('DMAR: incorrect input file format %s' % signature)
561     (length,) = struct.unpack('<I', f.read(4))
562     f.seek(48)
563     length -= 48
564     units = []
565     regions = []
566     ioapic_id = 0
567
568     while length > 0:
569         offset = 0
570         (struct_type, struct_len) = struct.unpack('<HH', f.read(4))
571         offset += 4
572         length -= struct_len
573
574         # DMA Remapping Hardware Unit Definition
575         if struct_type == 0:
576             (flags, segment, base) = struct.unpack('<BxHQ', f.read(12))
577             if segment != 0:
578                 raise RuntimeError('We do not support multiple PCI segments')
579             if len(units) >= 8:
580                 raise RuntimeError('Too many DMAR units. '
581                                    'Raise JAILHOUSE_MAX_DMAR_UNITS.')
582             units.append(base)
583             if flags & 1:
584                 for d in pcidevices:
585                     if d.iommu is None:
586                         d.iommu = len(units) - 1
587             offset += 16 - offset
588             while offset < struct_len:
589                 (scope_type, scope_len, bus, dev, fn) =\
590                     parse_dmar_devscope(f)
591                 if scope_type == 1:
592                     for d in pcidevices:
593                         if d.bus == bus and d.dev == dev and d.fn == fn:
594                             d.iommu = len(units) - 1
595                 elif scope_type == 2:
596                     raise RuntimeError('Unsupported DMAR Device Scope type')
597                 elif scope_type == 3:
598                     if ioapic_id != 0:
599                         raise RuntimeError('We do not support more '
600                                            'than 1 IOAPIC')
601                     # encode the DMAR unit number into the device ID
602                     ioapic_id = ((len(units) - 1) << 16) | \
603                         (bus << 8) | (dev << 3) | fn
604                 offset += scope_len
605
606         # Reserved Memory Region Reporting Structure
607         if struct_type == 1:
608             f.seek(8 - offset, os.SEEK_CUR)
609             offset += 8 - offset
610             (base, limit) = struct.unpack('<QQ', f.read(16))
611             offset += 16
612
613             comments = []
614             while offset < struct_len:
615                 (scope_type, scope_len, bus, dev, fn) =\
616                     parse_dmar_devscope(f)
617                 if scope_type == 1:
618                     comments.append('PCI device: %02x:%02x.%x' %
619                                     (bus, dev, fn))
620                 else:
621                     comments.append('DMAR parser could not decode device path')
622                 offset += scope_len
623
624             reg = MemRegion(base, limit, 'ACPI DMAR RMRR', comments)
625             regions.append(reg)
626
627         f.seek(struct_len - offset, os.SEEK_CUR)
628
629     return units, ioapic_id, regions
630
631
632 def parse_ioports():
633     pm_timer_base = None
634     f = input_open('/proc/ioports')
635     for line in f:
636         if line.endswith('ACPI PM_TMR\n'):
637             pm_timer_base = int(line.split('-')[0], 16)
638             break
639     f.close()
640     return pm_timer_base
641
642
643 class MMConfig:
644     def __init__(self, base, end_bus):
645         self.base = base
646         self.end_bus = end_bus
647
648     @staticmethod
649     def parse():
650         f = input_open('/sys/firmware/acpi/tables/MCFG', 'rb')
651         signature = f.read(4)
652         if signature != b'MCFG':
653             raise RuntimeError('MCFG: incorrect input file format %s' %
654                                signature)
655         (length,) = struct.unpack('<I', f.read(4))
656         if length > 60:
657             raise RuntimeError('Multiple MMCONFIG regions found! '
658                                'This is not supported')
659         f.seek(44)
660         (base, segment, start_bus, end_bus) = \
661             struct.unpack('<QHBB', f.read(12))
662         if segment != 0 or start_bus != 0:
663             raise RuntimeError('Invalid MCFG structure found')
664         return MMConfig(base, end_bus)
665
666
667 def get_cpu_vendor():
668     global cpuvendor
669     if cpuvendor is not None:
670         return cpuvendor
671     with input_open('/proc/cpuinfo', 'r') as f:
672         for line in f:
673             if not line.strip():
674                 continue
675             key, value = line.split(':')
676             if key.strip() == 'vendor_id':
677                 cpuvendor = value.strip()
678                 return cpuvendor
679
680
681 if options.generate_collector:
682     f = open(options.file, 'w')
683     filelist = ' '.join(inputs['files'])
684     filelist_opt = ' '.join(inputs['files_opt'])
685     filelist_intel = ' '.join(inputs['files_intel'])
686
687     tmpl = Template(filename=os.path.join(options.template_dir,
688                                           'jailhouse-config-collect.tmpl'))
689     f.write(tmpl.render(filelist=filelist, filelist_opt=filelist_opt,
690             filelist_intel=filelist_intel))
691     f.close()
692     sys.exit(0)
693
694 if ((options.root is '/') and (os.geteuid() is not 0)):
695     print('ERROR: You have to be root to work on "/"!', file=sys.stderr)
696     sys.exit(1)
697
698 jh_enabled = input_readline('/sys/devices/jailhouse/enabled', True).rstrip()
699 if jh_enabled == '1':
700     print('ERROR: Jailhouse was enabled when collecting input files! '
701           'Disable jailhouse and try again.',
702           file=sys.stderr)
703     sys.exit(1)
704
705 (pcidevices, pcicaps) = parse_pcidevices()
706
707 product = [input_readline('/sys/class/dmi/id/sys_vendor',
708                           True).rstrip(),
709            input_readline('/sys/class/dmi/id/product_name',
710                           True).rstrip()
711            ]
712
713 inmatemem = kmg_multiply_str(options.mem_inmates)
714 hvmem = [0, kmg_multiply_str(options.mem_hv)]
715
716 regions = parse_iomem(pcidevices)
717 ourmem = parse_kernel_cmdline()
718 total = hvmem[1] + inmatemem
719
720 mmconfig = MMConfig.parse()
721
722 if get_cpu_vendor() == 'GenuineIntel':
723     (dmar_units, ioapic_id, rmrr_regs) = parse_dmar(pcidevices)
724 else:
725     (dmar_units, ioapic_id, rmrr_regs) = [], 0, []
726 regions += rmrr_regs
727
728 for d in pcidevices:
729     if get_cpu_vendor() == 'AuthenticAMD':
730         d.iommu = 0  # temporary workaround
731     if d.iommu is None:
732         raise RuntimeError('PCI device %02x:%02x.%x outside the scope of an '
733                            'IOMMU' % (d.bus, d.dev, d.fn))
734
735 # kernel does not have memmap region, pick one
736 if ourmem is None:
737     ourmem = alloc_mem(regions, total)
738 elif (total > ourmem[1]):
739     raise RuntimeError('Your memmap reservation is too small you need >="' +
740                        hex(total) + '"')
741
742 hvmem[0] = ourmem[0]
743
744 inmatereg = MemRegion(ourmem[0] + hvmem[1],
745                       ourmem[0] + hvmem[1] + inmatemem - 1,
746                       'JAILHOUSE Inmate Memory')
747 regions.append(inmatereg)
748
749 cpucount = count_cpus()
750
751 pm_timer_base = parse_ioports()
752
753
754 f = open(options.file, 'w')
755 tmpl = Template(filename=os.path.join(options.template_dir,
756                                       'root-cell-config.c.tmpl'))
757 f.write(tmpl.render(regions=regions,
758                     ourmem=ourmem,
759                     argstr=' '.join(sys.argv),
760                     hvmem=hvmem,
761                     product=product,
762                     pcidevices=pcidevices,
763                     pcicaps=pcicaps,
764                     cpucount=cpucount,
765                     ioapic_id=ioapic_id,
766                     pm_timer_base=pm_timer_base,
767                     mmconfig=mmconfig,
768                     dmar_units=dmar_units))
769
770 f.close()