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