xref: /qemu/hw/xen/xen_pt_load_rom.c (revision ab9056ff)
1 /*
2  * This is splited from hw/i386/kvm/pci-assign.c
3  */
4 #include "qemu/osdep.h"
5 #include "qapi/error.h"
6 #include "hw/i386/pc.h"
7 #include "qemu/error-report.h"
8 #include "ui/console.h"
9 #include "hw/loader.h"
10 #include "monitor/monitor.h"
11 #include "qemu/range.h"
12 #include "hw/pci/pci.h"
13 #include "xen_pt.h"
14 
15 /*
16  * Scan the assigned devices for the devices that have an option ROM, and then
17  * load the corresponding ROM data to RAM. If an error occurs while loading an
18  * option ROM, we just ignore that option ROM and continue with the next one.
19  */
20 void *pci_assign_dev_load_option_rom(PCIDevice *dev,
21                                      int *size, unsigned int domain,
22                                      unsigned int bus, unsigned int slot,
23                                      unsigned int function)
24 {
25     char name[32], rom_file[64];
26     FILE *fp;
27     uint8_t val;
28     struct stat st;
29     void *ptr = NULL;
30     Object *owner = OBJECT(dev);
31 
32     /* If loading ROM from file, pci handles it */
33     if (dev->romfile || !dev->rom_bar) {
34         return NULL;
35     }
36 
37     snprintf(rom_file, sizeof(rom_file),
38              "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/rom",
39              domain, bus, slot, function);
40 
41     /* Write "1" to the ROM file to enable it */
42     fp = fopen(rom_file, "r+");
43     if (fp == NULL) {
44         if (errno != ENOENT) {
45             error_report("pci-assign: Cannot open %s: %s", rom_file, strerror(errno));
46         }
47         return NULL;
48     }
49     if (fstat(fileno(fp), &st) == -1) {
50         error_report("pci-assign: Cannot stat %s: %s", rom_file, strerror(errno));
51         goto close_rom;
52     }
53 
54     val = 1;
55     if (fwrite(&val, 1, 1, fp) != 1) {
56         goto close_rom;
57     }
58     fseek(fp, 0, SEEK_SET);
59 
60     snprintf(name, sizeof(name), "%s.rom", object_get_typename(owner));
61     memory_region_init_ram(&dev->rom, owner, name, st.st_size, &error_abort);
62     ptr = memory_region_get_ram_ptr(&dev->rom);
63     memset(ptr, 0xff, st.st_size);
64 
65     if (!fread(ptr, 1, st.st_size, fp)) {
66         error_report("pci-assign: Cannot read from host %s", rom_file);
67         error_printf("Device option ROM contents are probably invalid "
68                      "(check dmesg).\nSkip option ROM probe with rombar=0, "
69                      "or load from file with romfile=\n");
70         goto close_rom;
71     }
72 
73     pci_register_bar(dev, PCI_ROM_SLOT, 0, &dev->rom);
74     dev->has_rom = true;
75     *size = st.st_size;
76 close_rom:
77     /* Write "0" to disable ROM */
78     fseek(fp, 0, SEEK_SET);
79     val = 0;
80     if (!fwrite(&val, 1, 1, fp)) {
81         XEN_PT_WARN(dev, "%s\n", "Failed to disable pci-sysfs rom file");
82     }
83     fclose(fp);
84 
85     return ptr;
86 }
87