xref: /qemu/hw/nvram/fw_cfg.c (revision 7271a819)
1 /*
2  * QEMU Firmware configuration device emulation
3  *
4  * Copyright (c) 2008 Gleb Natapov
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu/osdep.h"
25 #include "hw/hw.h"
26 #include "sysemu/sysemu.h"
27 #include "sysemu/dma.h"
28 #include "hw/boards.h"
29 #include "hw/isa/isa.h"
30 #include "hw/nvram/fw_cfg.h"
31 #include "hw/sysbus.h"
32 #include "trace.h"
33 #include "qemu/error-report.h"
34 #include "qemu/config-file.h"
35 #include "qemu/cutils.h"
36 #include "qapi/error.h"
37 
38 #define FW_CFG_FILE_SLOTS_DFLT 0x20
39 
40 /* FW_CFG_VERSION bits */
41 #define FW_CFG_VERSION      0x01
42 #define FW_CFG_VERSION_DMA  0x02
43 
44 /* FW_CFG_DMA_CONTROL bits */
45 #define FW_CFG_DMA_CTL_ERROR   0x01
46 #define FW_CFG_DMA_CTL_READ    0x02
47 #define FW_CFG_DMA_CTL_SKIP    0x04
48 #define FW_CFG_DMA_CTL_SELECT  0x08
49 #define FW_CFG_DMA_CTL_WRITE   0x10
50 
51 #define FW_CFG_DMA_SIGNATURE 0x51454d5520434647ULL /* "QEMU CFG" */
52 
53 struct FWCfgEntry {
54     uint32_t len;
55     bool allow_write;
56     uint8_t *data;
57     void *callback_opaque;
58     FWCfgCallback select_cb;
59 };
60 
61 #define JPG_FILE 0
62 #define BMP_FILE 1
63 
64 static char *read_splashfile(char *filename, gsize *file_sizep,
65                              int *file_typep)
66 {
67     GError *err = NULL;
68     gboolean res;
69     gchar *content;
70     int file_type;
71     unsigned int filehead;
72     int bmp_bpp;
73 
74     res = g_file_get_contents(filename, &content, file_sizep, &err);
75     if (res == FALSE) {
76         error_report("failed to read splash file '%s'", filename);
77         g_error_free(err);
78         return NULL;
79     }
80 
81     /* check file size */
82     if (*file_sizep < 30) {
83         goto error;
84     }
85 
86     /* check magic ID */
87     filehead = ((content[0] & 0xff) + (content[1] << 8)) & 0xffff;
88     if (filehead == 0xd8ff) {
89         file_type = JPG_FILE;
90     } else if (filehead == 0x4d42) {
91         file_type = BMP_FILE;
92     } else {
93         goto error;
94     }
95 
96     /* check BMP bpp */
97     if (file_type == BMP_FILE) {
98         bmp_bpp = (content[28] + (content[29] << 8)) & 0xffff;
99         if (bmp_bpp != 24) {
100             goto error;
101         }
102     }
103 
104     /* return values */
105     *file_typep = file_type;
106 
107     return content;
108 
109 error:
110     error_report("splash file '%s' format not recognized; must be JPEG "
111                  "or 24 bit BMP", filename);
112     g_free(content);
113     return NULL;
114 }
115 
116 static void fw_cfg_bootsplash(FWCfgState *s)
117 {
118     int boot_splash_time = -1;
119     const char *boot_splash_filename = NULL;
120     char *p;
121     char *filename, *file_data;
122     gsize file_size;
123     int file_type;
124     const char *temp;
125 
126     /* get user configuration */
127     QemuOptsList *plist = qemu_find_opts("boot-opts");
128     QemuOpts *opts = QTAILQ_FIRST(&plist->head);
129     if (opts != NULL) {
130         temp = qemu_opt_get(opts, "splash");
131         if (temp != NULL) {
132             boot_splash_filename = temp;
133         }
134         temp = qemu_opt_get(opts, "splash-time");
135         if (temp != NULL) {
136             p = (char *)temp;
137             boot_splash_time = strtol(p, &p, 10);
138         }
139     }
140 
141     /* insert splash time if user configurated */
142     if (boot_splash_time >= 0) {
143         /* validate the input */
144         if (boot_splash_time > 0xffff) {
145             error_report("splash time is big than 65535, force it to 65535.");
146             boot_splash_time = 0xffff;
147         }
148         /* use little endian format */
149         qemu_extra_params_fw[0] = (uint8_t)(boot_splash_time & 0xff);
150         qemu_extra_params_fw[1] = (uint8_t)((boot_splash_time >> 8) & 0xff);
151         fw_cfg_add_file(s, "etc/boot-menu-wait", qemu_extra_params_fw, 2);
152     }
153 
154     /* insert splash file if user configurated */
155     if (boot_splash_filename != NULL) {
156         filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, boot_splash_filename);
157         if (filename == NULL) {
158             error_report("failed to find file '%s'.", boot_splash_filename);
159             return;
160         }
161 
162         /* loading file data */
163         file_data = read_splashfile(filename, &file_size, &file_type);
164         if (file_data == NULL) {
165             g_free(filename);
166             return;
167         }
168         g_free(boot_splash_filedata);
169         boot_splash_filedata = (uint8_t *)file_data;
170         boot_splash_filedata_size = file_size;
171 
172         /* insert data */
173         if (file_type == JPG_FILE) {
174             fw_cfg_add_file(s, "bootsplash.jpg",
175                     boot_splash_filedata, boot_splash_filedata_size);
176         } else {
177             fw_cfg_add_file(s, "bootsplash.bmp",
178                     boot_splash_filedata, boot_splash_filedata_size);
179         }
180         g_free(filename);
181     }
182 }
183 
184 static void fw_cfg_reboot(FWCfgState *s)
185 {
186     int reboot_timeout = -1;
187     char *p;
188     const char *temp;
189 
190     /* get user configuration */
191     QemuOptsList *plist = qemu_find_opts("boot-opts");
192     QemuOpts *opts = QTAILQ_FIRST(&plist->head);
193     if (opts != NULL) {
194         temp = qemu_opt_get(opts, "reboot-timeout");
195         if (temp != NULL) {
196             p = (char *)temp;
197             reboot_timeout = strtol(p, &p, 10);
198         }
199     }
200     /* validate the input */
201     if (reboot_timeout > 0xffff) {
202         error_report("reboot timeout is larger than 65535, force it to 65535.");
203         reboot_timeout = 0xffff;
204     }
205     fw_cfg_add_file(s, "etc/boot-fail-wait", g_memdup(&reboot_timeout, 4), 4);
206 }
207 
208 static void fw_cfg_write(FWCfgState *s, uint8_t value)
209 {
210     /* nothing, write support removed in QEMU v2.4+ */
211 }
212 
213 static inline uint16_t fw_cfg_file_slots(const FWCfgState *s)
214 {
215     return s->file_slots;
216 }
217 
218 /* Note: this function returns an exclusive limit. */
219 static inline uint32_t fw_cfg_max_entry(const FWCfgState *s)
220 {
221     return FW_CFG_FILE_FIRST + fw_cfg_file_slots(s);
222 }
223 
224 static int fw_cfg_select(FWCfgState *s, uint16_t key)
225 {
226     int arch, ret;
227     FWCfgEntry *e;
228 
229     s->cur_offset = 0;
230     if ((key & FW_CFG_ENTRY_MASK) >= fw_cfg_max_entry(s)) {
231         s->cur_entry = FW_CFG_INVALID;
232         ret = 0;
233     } else {
234         s->cur_entry = key;
235         ret = 1;
236         /* entry successfully selected, now run callback if present */
237         arch = !!(key & FW_CFG_ARCH_LOCAL);
238         e = &s->entries[arch][key & FW_CFG_ENTRY_MASK];
239         if (e->select_cb) {
240             e->select_cb(e->callback_opaque);
241         }
242     }
243 
244     trace_fw_cfg_select(s, key, ret);
245     return ret;
246 }
247 
248 static uint64_t fw_cfg_data_read(void *opaque, hwaddr addr, unsigned size)
249 {
250     FWCfgState *s = opaque;
251     int arch = !!(s->cur_entry & FW_CFG_ARCH_LOCAL);
252     FWCfgEntry *e = (s->cur_entry == FW_CFG_INVALID) ? NULL :
253                     &s->entries[arch][s->cur_entry & FW_CFG_ENTRY_MASK];
254     uint64_t value = 0;
255 
256     assert(size > 0 && size <= sizeof(value));
257     if (s->cur_entry != FW_CFG_INVALID && e->data && s->cur_offset < e->len) {
258         /* The least significant 'size' bytes of the return value are
259          * expected to contain a string preserving portion of the item
260          * data, padded with zeros on the right in case we run out early.
261          * In technical terms, we're composing the host-endian representation
262          * of the big endian interpretation of the fw_cfg string.
263          */
264         do {
265             value = (value << 8) | e->data[s->cur_offset++];
266         } while (--size && s->cur_offset < e->len);
267         /* If size is still not zero, we *did* run out early, so continue
268          * left-shifting, to add the appropriate number of padding zeros
269          * on the right.
270          */
271         value <<= 8 * size;
272     }
273 
274     trace_fw_cfg_read(s, value);
275     return value;
276 }
277 
278 static void fw_cfg_data_mem_write(void *opaque, hwaddr addr,
279                                   uint64_t value, unsigned size)
280 {
281     FWCfgState *s = opaque;
282     unsigned i = size;
283 
284     do {
285         fw_cfg_write(s, value >> (8 * --i));
286     } while (i);
287 }
288 
289 static void fw_cfg_dma_transfer(FWCfgState *s)
290 {
291     dma_addr_t len;
292     FWCfgDmaAccess dma;
293     int arch;
294     FWCfgEntry *e;
295     int read = 0, write = 0;
296     dma_addr_t dma_addr;
297 
298     /* Reset the address before the next access */
299     dma_addr = s->dma_addr;
300     s->dma_addr = 0;
301 
302     if (dma_memory_read(s->dma_as, dma_addr, &dma, sizeof(dma))) {
303         stl_be_dma(s->dma_as, dma_addr + offsetof(FWCfgDmaAccess, control),
304                    FW_CFG_DMA_CTL_ERROR);
305         return;
306     }
307 
308     dma.address = be64_to_cpu(dma.address);
309     dma.length = be32_to_cpu(dma.length);
310     dma.control = be32_to_cpu(dma.control);
311 
312     if (dma.control & FW_CFG_DMA_CTL_SELECT) {
313         fw_cfg_select(s, dma.control >> 16);
314     }
315 
316     arch = !!(s->cur_entry & FW_CFG_ARCH_LOCAL);
317     e = (s->cur_entry == FW_CFG_INVALID) ? NULL :
318         &s->entries[arch][s->cur_entry & FW_CFG_ENTRY_MASK];
319 
320     if (dma.control & FW_CFG_DMA_CTL_READ) {
321         read = 1;
322         write = 0;
323     } else if (dma.control & FW_CFG_DMA_CTL_WRITE) {
324         read = 0;
325         write = 1;
326     } else if (dma.control & FW_CFG_DMA_CTL_SKIP) {
327         read = 0;
328         write = 0;
329     } else {
330         dma.length = 0;
331     }
332 
333     dma.control = 0;
334 
335     while (dma.length > 0 && !(dma.control & FW_CFG_DMA_CTL_ERROR)) {
336         if (s->cur_entry == FW_CFG_INVALID || !e->data ||
337                                 s->cur_offset >= e->len) {
338             len = dma.length;
339 
340             /* If the access is not a read access, it will be a skip access,
341              * tested before.
342              */
343             if (read) {
344                 if (dma_memory_set(s->dma_as, dma.address, 0, len)) {
345                     dma.control |= FW_CFG_DMA_CTL_ERROR;
346                 }
347             }
348             if (write) {
349                 dma.control |= FW_CFG_DMA_CTL_ERROR;
350             }
351         } else {
352             if (dma.length <= (e->len - s->cur_offset)) {
353                 len = dma.length;
354             } else {
355                 len = (e->len - s->cur_offset);
356             }
357 
358             /* If the access is not a read access, it will be a skip access,
359              * tested before.
360              */
361             if (read) {
362                 if (dma_memory_write(s->dma_as, dma.address,
363                                     &e->data[s->cur_offset], len)) {
364                     dma.control |= FW_CFG_DMA_CTL_ERROR;
365                 }
366             }
367             if (write) {
368                 if (!e->allow_write ||
369                     len != dma.length ||
370                     dma_memory_read(s->dma_as, dma.address,
371                                     &e->data[s->cur_offset], len)) {
372                     dma.control |= FW_CFG_DMA_CTL_ERROR;
373                 }
374             }
375 
376             s->cur_offset += len;
377         }
378 
379         dma.address += len;
380         dma.length  -= len;
381 
382     }
383 
384     stl_be_dma(s->dma_as, dma_addr + offsetof(FWCfgDmaAccess, control),
385                 dma.control);
386 
387     trace_fw_cfg_read(s, 0);
388 }
389 
390 static uint64_t fw_cfg_dma_mem_read(void *opaque, hwaddr addr,
391                                     unsigned size)
392 {
393     /* Return a signature value (and handle various read sizes) */
394     return extract64(FW_CFG_DMA_SIGNATURE, (8 - addr - size) * 8, size * 8);
395 }
396 
397 static void fw_cfg_dma_mem_write(void *opaque, hwaddr addr,
398                                  uint64_t value, unsigned size)
399 {
400     FWCfgState *s = opaque;
401 
402     if (size == 4) {
403         if (addr == 0) {
404             /* FWCfgDmaAccess high address */
405             s->dma_addr = value << 32;
406         } else if (addr == 4) {
407             /* FWCfgDmaAccess low address */
408             s->dma_addr |= value;
409             fw_cfg_dma_transfer(s);
410         }
411     } else if (size == 8 && addr == 0) {
412         s->dma_addr = value;
413         fw_cfg_dma_transfer(s);
414     }
415 }
416 
417 static bool fw_cfg_dma_mem_valid(void *opaque, hwaddr addr,
418                                   unsigned size, bool is_write)
419 {
420     return !is_write || ((size == 4 && (addr == 0 || addr == 4)) ||
421                          (size == 8 && addr == 0));
422 }
423 
424 static bool fw_cfg_data_mem_valid(void *opaque, hwaddr addr,
425                                   unsigned size, bool is_write)
426 {
427     return addr == 0;
428 }
429 
430 static void fw_cfg_ctl_mem_write(void *opaque, hwaddr addr,
431                                  uint64_t value, unsigned size)
432 {
433     fw_cfg_select(opaque, (uint16_t)value);
434 }
435 
436 static bool fw_cfg_ctl_mem_valid(void *opaque, hwaddr addr,
437                                  unsigned size, bool is_write)
438 {
439     return is_write && size == 2;
440 }
441 
442 static void fw_cfg_comb_write(void *opaque, hwaddr addr,
443                               uint64_t value, unsigned size)
444 {
445     switch (size) {
446     case 1:
447         fw_cfg_write(opaque, (uint8_t)value);
448         break;
449     case 2:
450         fw_cfg_select(opaque, (uint16_t)value);
451         break;
452     }
453 }
454 
455 static bool fw_cfg_comb_valid(void *opaque, hwaddr addr,
456                                   unsigned size, bool is_write)
457 {
458     return (size == 1) || (is_write && size == 2);
459 }
460 
461 static const MemoryRegionOps fw_cfg_ctl_mem_ops = {
462     .write = fw_cfg_ctl_mem_write,
463     .endianness = DEVICE_BIG_ENDIAN,
464     .valid.accepts = fw_cfg_ctl_mem_valid,
465 };
466 
467 static const MemoryRegionOps fw_cfg_data_mem_ops = {
468     .read = fw_cfg_data_read,
469     .write = fw_cfg_data_mem_write,
470     .endianness = DEVICE_BIG_ENDIAN,
471     .valid = {
472         .min_access_size = 1,
473         .max_access_size = 1,
474         .accepts = fw_cfg_data_mem_valid,
475     },
476 };
477 
478 static const MemoryRegionOps fw_cfg_comb_mem_ops = {
479     .read = fw_cfg_data_read,
480     .write = fw_cfg_comb_write,
481     .endianness = DEVICE_LITTLE_ENDIAN,
482     .valid.accepts = fw_cfg_comb_valid,
483 };
484 
485 static const MemoryRegionOps fw_cfg_dma_mem_ops = {
486     .read = fw_cfg_dma_mem_read,
487     .write = fw_cfg_dma_mem_write,
488     .endianness = DEVICE_BIG_ENDIAN,
489     .valid.accepts = fw_cfg_dma_mem_valid,
490     .valid.max_access_size = 8,
491     .impl.max_access_size = 8,
492 };
493 
494 static void fw_cfg_reset(DeviceState *d)
495 {
496     FWCfgState *s = FW_CFG(d);
497 
498     /* we never register a read callback for FW_CFG_SIGNATURE */
499     fw_cfg_select(s, FW_CFG_SIGNATURE);
500 }
501 
502 /* Save restore 32 bit int as uint16_t
503    This is a Big hack, but it is how the old state did it.
504    Or we broke compatibility in the state, or we can't use struct tm
505  */
506 
507 static int get_uint32_as_uint16(QEMUFile *f, void *pv, size_t size,
508                                 VMStateField *field)
509 {
510     uint32_t *v = pv;
511     *v = qemu_get_be16(f);
512     return 0;
513 }
514 
515 static int put_unused(QEMUFile *f, void *pv, size_t size, VMStateField *field,
516                       QJSON *vmdesc)
517 {
518     fprintf(stderr, "uint32_as_uint16 is only used for backward compatibility.\n");
519     fprintf(stderr, "This functions shouldn't be called.\n");
520 
521     return 0;
522 }
523 
524 static const VMStateInfo vmstate_hack_uint32_as_uint16 = {
525     .name = "int32_as_uint16",
526     .get  = get_uint32_as_uint16,
527     .put  = put_unused,
528 };
529 
530 #define VMSTATE_UINT16_HACK(_f, _s, _t)                                    \
531     VMSTATE_SINGLE_TEST(_f, _s, _t, 0, vmstate_hack_uint32_as_uint16, uint32_t)
532 
533 
534 static bool is_version_1(void *opaque, int version_id)
535 {
536     return version_id == 1;
537 }
538 
539 bool fw_cfg_dma_enabled(void *opaque)
540 {
541     FWCfgState *s = opaque;
542 
543     return s->dma_enabled;
544 }
545 
546 static const VMStateDescription vmstate_fw_cfg_dma = {
547     .name = "fw_cfg/dma",
548     .needed = fw_cfg_dma_enabled,
549     .fields = (VMStateField[]) {
550         VMSTATE_UINT64(dma_addr, FWCfgState),
551         VMSTATE_END_OF_LIST()
552     },
553 };
554 
555 static const VMStateDescription vmstate_fw_cfg = {
556     .name = "fw_cfg",
557     .version_id = 2,
558     .minimum_version_id = 1,
559     .fields = (VMStateField[]) {
560         VMSTATE_UINT16(cur_entry, FWCfgState),
561         VMSTATE_UINT16_HACK(cur_offset, FWCfgState, is_version_1),
562         VMSTATE_UINT32_V(cur_offset, FWCfgState, 2),
563         VMSTATE_END_OF_LIST()
564     },
565     .subsections = (const VMStateDescription*[]) {
566         &vmstate_fw_cfg_dma,
567         NULL,
568     }
569 };
570 
571 static void fw_cfg_add_bytes_callback(FWCfgState *s, uint16_t key,
572                                       FWCfgCallback select_cb,
573                                       void *callback_opaque,
574                                       void *data, size_t len,
575                                       bool read_only)
576 {
577     int arch = !!(key & FW_CFG_ARCH_LOCAL);
578 
579     key &= FW_CFG_ENTRY_MASK;
580 
581     assert(key < fw_cfg_max_entry(s) && len < UINT32_MAX);
582     assert(s->entries[arch][key].data == NULL); /* avoid key conflict */
583 
584     s->entries[arch][key].data = data;
585     s->entries[arch][key].len = (uint32_t)len;
586     s->entries[arch][key].select_cb = select_cb;
587     s->entries[arch][key].callback_opaque = callback_opaque;
588     s->entries[arch][key].allow_write = !read_only;
589 }
590 
591 static void *fw_cfg_modify_bytes_read(FWCfgState *s, uint16_t key,
592                                               void *data, size_t len)
593 {
594     void *ptr;
595     int arch = !!(key & FW_CFG_ARCH_LOCAL);
596 
597     key &= FW_CFG_ENTRY_MASK;
598 
599     assert(key < fw_cfg_max_entry(s) && len < UINT32_MAX);
600 
601     /* return the old data to the function caller, avoid memory leak */
602     ptr = s->entries[arch][key].data;
603     s->entries[arch][key].data = data;
604     s->entries[arch][key].len = len;
605     s->entries[arch][key].callback_opaque = NULL;
606     s->entries[arch][key].allow_write = false;
607 
608     return ptr;
609 }
610 
611 void fw_cfg_add_bytes(FWCfgState *s, uint16_t key, void *data, size_t len)
612 {
613     fw_cfg_add_bytes_callback(s, key, NULL, NULL, data, len, true);
614 }
615 
616 void fw_cfg_add_string(FWCfgState *s, uint16_t key, const char *value)
617 {
618     size_t sz = strlen(value) + 1;
619 
620     fw_cfg_add_bytes(s, key, g_memdup(value, sz), sz);
621 }
622 
623 void fw_cfg_add_i16(FWCfgState *s, uint16_t key, uint16_t value)
624 {
625     uint16_t *copy;
626 
627     copy = g_malloc(sizeof(value));
628     *copy = cpu_to_le16(value);
629     fw_cfg_add_bytes(s, key, copy, sizeof(value));
630 }
631 
632 void fw_cfg_modify_i16(FWCfgState *s, uint16_t key, uint16_t value)
633 {
634     uint16_t *copy, *old;
635 
636     copy = g_malloc(sizeof(value));
637     *copy = cpu_to_le16(value);
638     old = fw_cfg_modify_bytes_read(s, key, copy, sizeof(value));
639     g_free(old);
640 }
641 
642 void fw_cfg_add_i32(FWCfgState *s, uint16_t key, uint32_t value)
643 {
644     uint32_t *copy;
645 
646     copy = g_malloc(sizeof(value));
647     *copy = cpu_to_le32(value);
648     fw_cfg_add_bytes(s, key, copy, sizeof(value));
649 }
650 
651 void fw_cfg_add_i64(FWCfgState *s, uint16_t key, uint64_t value)
652 {
653     uint64_t *copy;
654 
655     copy = g_malloc(sizeof(value));
656     *copy = cpu_to_le64(value);
657     fw_cfg_add_bytes(s, key, copy, sizeof(value));
658 }
659 
660 void fw_cfg_set_order_override(FWCfgState *s, int order)
661 {
662     assert(s->fw_cfg_order_override == 0);
663     s->fw_cfg_order_override = order;
664 }
665 
666 void fw_cfg_reset_order_override(FWCfgState *s)
667 {
668     assert(s->fw_cfg_order_override != 0);
669     s->fw_cfg_order_override = 0;
670 }
671 
672 /*
673  * This is the legacy order list.  For legacy systems, files are in
674  * the fw_cfg in the order defined below, by the "order" value.  Note
675  * that some entries (VGA ROMs, NIC option ROMS, etc.) go into a
676  * specific area, but there may be more than one and they occur in the
677  * order that the user specifies them on the command line.  Those are
678  * handled in a special manner, using the order override above.
679  *
680  * For non-legacy, the files are sorted by filename to avoid this kind
681  * of complexity in the future.
682  *
683  * This is only for x86, other arches don't implement versioning so
684  * they won't set legacy mode.
685  */
686 static struct {
687     const char *name;
688     int order;
689 } fw_cfg_order[] = {
690     { "etc/boot-menu-wait", 10 },
691     { "bootsplash.jpg", 11 },
692     { "bootsplash.bmp", 12 },
693     { "etc/boot-fail-wait", 15 },
694     { "etc/smbios/smbios-tables", 20 },
695     { "etc/smbios/smbios-anchor", 30 },
696     { "etc/e820", 40 },
697     { "etc/reserved-memory-end", 50 },
698     { "genroms/kvmvapic.bin", 55 },
699     { "genroms/linuxboot.bin", 60 },
700     { }, /* VGA ROMs from pc_vga_init come here, 70. */
701     { }, /* NIC option ROMs from pc_nic_init come here, 80. */
702     { "etc/system-states", 90 },
703     { }, /* User ROMs come here, 100. */
704     { }, /* Device FW comes here, 110. */
705     { "etc/extra-pci-roots", 120 },
706     { "etc/acpi/tables", 130 },
707     { "etc/table-loader", 140 },
708     { "etc/tpm/log", 150 },
709     { "etc/acpi/rsdp", 160 },
710     { "bootorder", 170 },
711 
712 #define FW_CFG_ORDER_OVERRIDE_LAST 200
713 };
714 
715 static int get_fw_cfg_order(FWCfgState *s, const char *name)
716 {
717     int i;
718 
719     if (s->fw_cfg_order_override > 0) {
720         return s->fw_cfg_order_override;
721     }
722 
723     for (i = 0; i < ARRAY_SIZE(fw_cfg_order); i++) {
724         if (fw_cfg_order[i].name == NULL) {
725             continue;
726         }
727 
728         if (strcmp(name, fw_cfg_order[i].name) == 0) {
729             return fw_cfg_order[i].order;
730         }
731     }
732 
733     /* Stick unknown stuff at the end. */
734     warn_report("Unknown firmware file in legacy mode: %s", name);
735     return FW_CFG_ORDER_OVERRIDE_LAST;
736 }
737 
738 void fw_cfg_add_file_callback(FWCfgState *s,  const char *filename,
739                               FWCfgCallback select_cb,
740                               void *callback_opaque,
741                               void *data, size_t len, bool read_only)
742 {
743     int i, index, count;
744     size_t dsize;
745     MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
746     int order = 0;
747 
748     if (!s->files) {
749         dsize = sizeof(uint32_t) + sizeof(FWCfgFile) * fw_cfg_file_slots(s);
750         s->files = g_malloc0(dsize);
751         fw_cfg_add_bytes(s, FW_CFG_FILE_DIR, s->files, dsize);
752     }
753 
754     count = be32_to_cpu(s->files->count);
755     assert(count < fw_cfg_file_slots(s));
756 
757     /* Find the insertion point. */
758     if (mc->legacy_fw_cfg_order) {
759         /*
760          * Sort by order. For files with the same order, we keep them
761          * in the sequence in which they were added.
762          */
763         order = get_fw_cfg_order(s, filename);
764         for (index = count;
765              index > 0 && order < s->entry_order[index - 1];
766              index--);
767     } else {
768         /* Sort by file name. */
769         for (index = count;
770              index > 0 && strcmp(filename, s->files->f[index - 1].name) < 0;
771              index--);
772     }
773 
774     /*
775      * Move all the entries from the index point and after down one
776      * to create a slot for the new entry.  Because calculations are
777      * being done with the index, make it so that "i" is the current
778      * index and "i - 1" is the one being copied from, thus the
779      * unusual start and end in the for statement.
780      */
781     for (i = count + 1; i > index; i--) {
782         s->files->f[i] = s->files->f[i - 1];
783         s->files->f[i].select = cpu_to_be16(FW_CFG_FILE_FIRST + i);
784         s->entries[0][FW_CFG_FILE_FIRST + i] =
785             s->entries[0][FW_CFG_FILE_FIRST + i - 1];
786         s->entry_order[i] = s->entry_order[i - 1];
787     }
788 
789     memset(&s->files->f[index], 0, sizeof(FWCfgFile));
790     memset(&s->entries[0][FW_CFG_FILE_FIRST + index], 0, sizeof(FWCfgEntry));
791 
792     pstrcpy(s->files->f[index].name, sizeof(s->files->f[index].name), filename);
793     for (i = 0; i <= count; i++) {
794         if (i != index &&
795             strcmp(s->files->f[index].name, s->files->f[i].name) == 0) {
796             error_report("duplicate fw_cfg file name: %s",
797                          s->files->f[index].name);
798             exit(1);
799         }
800     }
801 
802     fw_cfg_add_bytes_callback(s, FW_CFG_FILE_FIRST + index,
803                               select_cb,
804                               callback_opaque, data, len,
805                               read_only);
806 
807     s->files->f[index].size   = cpu_to_be32(len);
808     s->files->f[index].select = cpu_to_be16(FW_CFG_FILE_FIRST + index);
809     s->entry_order[index] = order;
810     trace_fw_cfg_add_file(s, index, s->files->f[index].name, len);
811 
812     s->files->count = cpu_to_be32(count+1);
813 }
814 
815 void fw_cfg_add_file(FWCfgState *s,  const char *filename,
816                      void *data, size_t len)
817 {
818     fw_cfg_add_file_callback(s, filename, NULL, NULL, data, len, true);
819 }
820 
821 void *fw_cfg_modify_file(FWCfgState *s, const char *filename,
822                         void *data, size_t len)
823 {
824     int i, index;
825     void *ptr = NULL;
826 
827     assert(s->files);
828 
829     index = be32_to_cpu(s->files->count);
830     assert(index < fw_cfg_file_slots(s));
831 
832     for (i = 0; i < index; i++) {
833         if (strcmp(filename, s->files->f[i].name) == 0) {
834             ptr = fw_cfg_modify_bytes_read(s, FW_CFG_FILE_FIRST + i,
835                                            data, len);
836             s->files->f[i].size   = cpu_to_be32(len);
837             return ptr;
838         }
839     }
840     /* add new one */
841     fw_cfg_add_file_callback(s, filename, NULL, NULL, data, len, true);
842     return NULL;
843 }
844 
845 static void fw_cfg_machine_reset(void *opaque)
846 {
847     void *ptr;
848     size_t len;
849     FWCfgState *s = opaque;
850     char *bootindex = get_boot_devices_list(&len, false);
851 
852     ptr = fw_cfg_modify_file(s, "bootorder", (uint8_t *)bootindex, len);
853     g_free(ptr);
854 }
855 
856 static void fw_cfg_machine_ready(struct Notifier *n, void *data)
857 {
858     FWCfgState *s = container_of(n, FWCfgState, machine_ready);
859     qemu_register_reset(fw_cfg_machine_reset, s);
860 }
861 
862 
863 
864 static void fw_cfg_common_realize(DeviceState *dev, Error **errp)
865 {
866     FWCfgState *s = FW_CFG(dev);
867     MachineState *machine = MACHINE(qdev_get_machine());
868     uint32_t version = FW_CFG_VERSION;
869 
870     if (!fw_cfg_find()) {
871         error_setg(errp, "at most one %s device is permitted", TYPE_FW_CFG);
872         return;
873     }
874 
875     fw_cfg_add_bytes(s, FW_CFG_SIGNATURE, (char *)"QEMU", 4);
876     fw_cfg_add_bytes(s, FW_CFG_UUID, &qemu_uuid, 16);
877     fw_cfg_add_i16(s, FW_CFG_NOGRAPHIC, (uint16_t)!machine->enable_graphics);
878     fw_cfg_add_i16(s, FW_CFG_BOOT_MENU, (uint16_t)boot_menu);
879     fw_cfg_bootsplash(s);
880     fw_cfg_reboot(s);
881 
882     if (s->dma_enabled) {
883         version |= FW_CFG_VERSION_DMA;
884     }
885 
886     fw_cfg_add_i32(s, FW_CFG_ID, version);
887 
888     s->machine_ready.notify = fw_cfg_machine_ready;
889     qemu_add_machine_init_done_notifier(&s->machine_ready);
890 }
891 
892 FWCfgState *fw_cfg_init_io_dma(uint32_t iobase, uint32_t dma_iobase,
893                                 AddressSpace *dma_as)
894 {
895     DeviceState *dev;
896     SysBusDevice *sbd;
897     FWCfgIoState *ios;
898     FWCfgState *s;
899     bool dma_requested = dma_iobase && dma_as;
900 
901     dev = qdev_create(NULL, TYPE_FW_CFG_IO);
902     if (!dma_requested) {
903         qdev_prop_set_bit(dev, "dma_enabled", false);
904     }
905 
906     object_property_add_child(OBJECT(qdev_get_machine()), TYPE_FW_CFG,
907                               OBJECT(dev), NULL);
908     qdev_init_nofail(dev);
909 
910     sbd = SYS_BUS_DEVICE(dev);
911     ios = FW_CFG_IO(dev);
912     sysbus_add_io(sbd, iobase, &ios->comb_iomem);
913 
914     s = FW_CFG(dev);
915 
916     if (s->dma_enabled) {
917         /* 64 bits for the address field */
918         s->dma_as = dma_as;
919         s->dma_addr = 0;
920         sysbus_add_io(sbd, dma_iobase, &s->dma_iomem);
921     }
922 
923     return s;
924 }
925 
926 FWCfgState *fw_cfg_init_io(uint32_t iobase)
927 {
928     return fw_cfg_init_io_dma(iobase, 0, NULL);
929 }
930 
931 FWCfgState *fw_cfg_init_mem_wide(hwaddr ctl_addr,
932                                  hwaddr data_addr, uint32_t data_width,
933                                  hwaddr dma_addr, AddressSpace *dma_as)
934 {
935     DeviceState *dev;
936     SysBusDevice *sbd;
937     FWCfgState *s;
938     bool dma_requested = dma_addr && dma_as;
939 
940     dev = qdev_create(NULL, TYPE_FW_CFG_MEM);
941     qdev_prop_set_uint32(dev, "data_width", data_width);
942     if (!dma_requested) {
943         qdev_prop_set_bit(dev, "dma_enabled", false);
944     }
945 
946     object_property_add_child(OBJECT(qdev_get_machine()), TYPE_FW_CFG,
947                               OBJECT(dev), NULL);
948     qdev_init_nofail(dev);
949 
950     sbd = SYS_BUS_DEVICE(dev);
951     sysbus_mmio_map(sbd, 0, ctl_addr);
952     sysbus_mmio_map(sbd, 1, data_addr);
953 
954     s = FW_CFG(dev);
955 
956     if (s->dma_enabled) {
957         s->dma_as = dma_as;
958         s->dma_addr = 0;
959         sysbus_mmio_map(sbd, 2, dma_addr);
960     }
961 
962     return s;
963 }
964 
965 FWCfgState *fw_cfg_init_mem(hwaddr ctl_addr, hwaddr data_addr)
966 {
967     return fw_cfg_init_mem_wide(ctl_addr, data_addr,
968                                 fw_cfg_data_mem_ops.valid.max_access_size,
969                                 0, NULL);
970 }
971 
972 
973 FWCfgState *fw_cfg_find(void)
974 {
975     /* Returns NULL unless there is exactly one fw_cfg device */
976     return FW_CFG(object_resolve_path_type("", TYPE_FW_CFG, NULL));
977 }
978 
979 
980 static void fw_cfg_class_init(ObjectClass *klass, void *data)
981 {
982     DeviceClass *dc = DEVICE_CLASS(klass);
983 
984     dc->reset = fw_cfg_reset;
985     dc->vmsd = &vmstate_fw_cfg;
986 }
987 
988 static const TypeInfo fw_cfg_info = {
989     .name          = TYPE_FW_CFG,
990     .parent        = TYPE_SYS_BUS_DEVICE,
991     .abstract      = true,
992     .instance_size = sizeof(FWCfgState),
993     .class_init    = fw_cfg_class_init,
994 };
995 
996 static void fw_cfg_file_slots_allocate(FWCfgState *s, Error **errp)
997 {
998     uint16_t file_slots_max;
999 
1000     if (fw_cfg_file_slots(s) < FW_CFG_FILE_SLOTS_MIN) {
1001         error_setg(errp, "\"file_slots\" must be at least 0x%x",
1002                    FW_CFG_FILE_SLOTS_MIN);
1003         return;
1004     }
1005 
1006     /* (UINT16_MAX & FW_CFG_ENTRY_MASK) is the highest inclusive selector value
1007      * that we permit. The actual (exclusive) value coming from the
1008      * configuration is (FW_CFG_FILE_FIRST + fw_cfg_file_slots(s)). */
1009     file_slots_max = (UINT16_MAX & FW_CFG_ENTRY_MASK) - FW_CFG_FILE_FIRST + 1;
1010     if (fw_cfg_file_slots(s) > file_slots_max) {
1011         error_setg(errp, "\"file_slots\" must not exceed 0x%" PRIx16,
1012                    file_slots_max);
1013         return;
1014     }
1015 
1016     s->entries[0] = g_new0(FWCfgEntry, fw_cfg_max_entry(s));
1017     s->entries[1] = g_new0(FWCfgEntry, fw_cfg_max_entry(s));
1018     s->entry_order = g_new0(int, fw_cfg_max_entry(s));
1019 }
1020 
1021 static Property fw_cfg_io_properties[] = {
1022     DEFINE_PROP_BOOL("dma_enabled", FWCfgIoState, parent_obj.dma_enabled,
1023                      true),
1024     DEFINE_PROP_UINT16("x-file-slots", FWCfgIoState, parent_obj.file_slots,
1025                        FW_CFG_FILE_SLOTS_DFLT),
1026     DEFINE_PROP_END_OF_LIST(),
1027 };
1028 
1029 static void fw_cfg_io_realize(DeviceState *dev, Error **errp)
1030 {
1031     FWCfgIoState *s = FW_CFG_IO(dev);
1032     Error *local_err = NULL;
1033 
1034     fw_cfg_file_slots_allocate(FW_CFG(s), &local_err);
1035     if (local_err) {
1036         error_propagate(errp, local_err);
1037         return;
1038     }
1039 
1040     /* when using port i/o, the 8-bit data register ALWAYS overlaps
1041      * with half of the 16-bit control register. Hence, the total size
1042      * of the i/o region used is FW_CFG_CTL_SIZE */
1043     memory_region_init_io(&s->comb_iomem, OBJECT(s), &fw_cfg_comb_mem_ops,
1044                           FW_CFG(s), "fwcfg", FW_CFG_CTL_SIZE);
1045 
1046     if (FW_CFG(s)->dma_enabled) {
1047         memory_region_init_io(&FW_CFG(s)->dma_iomem, OBJECT(s),
1048                               &fw_cfg_dma_mem_ops, FW_CFG(s), "fwcfg.dma",
1049                               sizeof(dma_addr_t));
1050     }
1051 
1052     fw_cfg_common_realize(dev, errp);
1053 }
1054 
1055 static void fw_cfg_io_class_init(ObjectClass *klass, void *data)
1056 {
1057     DeviceClass *dc = DEVICE_CLASS(klass);
1058 
1059     dc->realize = fw_cfg_io_realize;
1060     dc->props = fw_cfg_io_properties;
1061 }
1062 
1063 static const TypeInfo fw_cfg_io_info = {
1064     .name          = TYPE_FW_CFG_IO,
1065     .parent        = TYPE_FW_CFG,
1066     .instance_size = sizeof(FWCfgIoState),
1067     .class_init    = fw_cfg_io_class_init,
1068 };
1069 
1070 
1071 static Property fw_cfg_mem_properties[] = {
1072     DEFINE_PROP_UINT32("data_width", FWCfgMemState, data_width, -1),
1073     DEFINE_PROP_BOOL("dma_enabled", FWCfgMemState, parent_obj.dma_enabled,
1074                      true),
1075     DEFINE_PROP_UINT16("x-file-slots", FWCfgMemState, parent_obj.file_slots,
1076                        FW_CFG_FILE_SLOTS_DFLT),
1077     DEFINE_PROP_END_OF_LIST(),
1078 };
1079 
1080 static void fw_cfg_mem_realize(DeviceState *dev, Error **errp)
1081 {
1082     FWCfgMemState *s = FW_CFG_MEM(dev);
1083     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1084     const MemoryRegionOps *data_ops = &fw_cfg_data_mem_ops;
1085     Error *local_err = NULL;
1086 
1087     fw_cfg_file_slots_allocate(FW_CFG(s), &local_err);
1088     if (local_err) {
1089         error_propagate(errp, local_err);
1090         return;
1091     }
1092 
1093     memory_region_init_io(&s->ctl_iomem, OBJECT(s), &fw_cfg_ctl_mem_ops,
1094                           FW_CFG(s), "fwcfg.ctl", FW_CFG_CTL_SIZE);
1095     sysbus_init_mmio(sbd, &s->ctl_iomem);
1096 
1097     if (s->data_width > data_ops->valid.max_access_size) {
1098         /* memberwise copy because the "old_mmio" member is const */
1099         s->wide_data_ops.read       = data_ops->read;
1100         s->wide_data_ops.write      = data_ops->write;
1101         s->wide_data_ops.endianness = data_ops->endianness;
1102         s->wide_data_ops.valid      = data_ops->valid;
1103         s->wide_data_ops.impl       = data_ops->impl;
1104 
1105         s->wide_data_ops.valid.max_access_size = s->data_width;
1106         s->wide_data_ops.impl.max_access_size  = s->data_width;
1107         data_ops = &s->wide_data_ops;
1108     }
1109     memory_region_init_io(&s->data_iomem, OBJECT(s), data_ops, FW_CFG(s),
1110                           "fwcfg.data", data_ops->valid.max_access_size);
1111     sysbus_init_mmio(sbd, &s->data_iomem);
1112 
1113     if (FW_CFG(s)->dma_enabled) {
1114         memory_region_init_io(&FW_CFG(s)->dma_iomem, OBJECT(s),
1115                               &fw_cfg_dma_mem_ops, FW_CFG(s), "fwcfg.dma",
1116                               sizeof(dma_addr_t));
1117         sysbus_init_mmio(sbd, &FW_CFG(s)->dma_iomem);
1118     }
1119 
1120     fw_cfg_common_realize(dev, errp);
1121 }
1122 
1123 static void fw_cfg_mem_class_init(ObjectClass *klass, void *data)
1124 {
1125     DeviceClass *dc = DEVICE_CLASS(klass);
1126 
1127     dc->realize = fw_cfg_mem_realize;
1128     dc->props = fw_cfg_mem_properties;
1129 }
1130 
1131 static const TypeInfo fw_cfg_mem_info = {
1132     .name          = TYPE_FW_CFG_MEM,
1133     .parent        = TYPE_FW_CFG,
1134     .instance_size = sizeof(FWCfgMemState),
1135     .class_init    = fw_cfg_mem_class_init,
1136 };
1137 
1138 
1139 static void fw_cfg_register_types(void)
1140 {
1141     type_register_static(&fw_cfg_info);
1142     type_register_static(&fw_cfg_io_info);
1143     type_register_static(&fw_cfg_mem_info);
1144 }
1145 
1146 type_init(fw_cfg_register_types)
1147