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