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