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