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