xref: /openbmc/qemu/hw/nvram/fw_cfg.c (revision 0b1183e3)
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     FWCfgReadCallback read_callback;
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->read_callback) {
240             e->read_callback(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_read_callback(FWCfgState *s, uint16_t key,
572                                            FWCfgReadCallback callback,
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].read_callback = callback;
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_read_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                               FWCfgReadCallback callback, void *callback_opaque,
740                               void *data, size_t len, bool read_only)
741 {
742     int i, index, count;
743     size_t dsize;
744     MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
745     int order = 0;
746 
747     if (!s->files) {
748         dsize = sizeof(uint32_t) + sizeof(FWCfgFile) * fw_cfg_file_slots(s);
749         s->files = g_malloc0(dsize);
750         fw_cfg_add_bytes(s, FW_CFG_FILE_DIR, s->files, dsize);
751     }
752 
753     count = be32_to_cpu(s->files->count);
754     assert(count < fw_cfg_file_slots(s));
755 
756     /* Find the insertion point. */
757     if (mc->legacy_fw_cfg_order) {
758         /*
759          * Sort by order. For files with the same order, we keep them
760          * in the sequence in which they were added.
761          */
762         order = get_fw_cfg_order(s, filename);
763         for (index = count;
764              index > 0 && order < s->entry_order[index - 1];
765              index--);
766     } else {
767         /* Sort by file name. */
768         for (index = count;
769              index > 0 && strcmp(filename, s->files->f[index - 1].name) < 0;
770              index--);
771     }
772 
773     /*
774      * Move all the entries from the index point and after down one
775      * to create a slot for the new entry.  Because calculations are
776      * being done with the index, make it so that "i" is the current
777      * index and "i - 1" is the one being copied from, thus the
778      * unusual start and end in the for statement.
779      */
780     for (i = count + 1; i > index; i--) {
781         s->files->f[i] = s->files->f[i - 1];
782         s->files->f[i].select = cpu_to_be16(FW_CFG_FILE_FIRST + i);
783         s->entries[0][FW_CFG_FILE_FIRST + i] =
784             s->entries[0][FW_CFG_FILE_FIRST + i - 1];
785         s->entry_order[i] = s->entry_order[i - 1];
786     }
787 
788     memset(&s->files->f[index], 0, sizeof(FWCfgFile));
789     memset(&s->entries[0][FW_CFG_FILE_FIRST + index], 0, sizeof(FWCfgEntry));
790 
791     pstrcpy(s->files->f[index].name, sizeof(s->files->f[index].name), filename);
792     for (i = 0; i <= count; i++) {
793         if (i != index &&
794             strcmp(s->files->f[index].name, s->files->f[i].name) == 0) {
795             error_report("duplicate fw_cfg file name: %s",
796                          s->files->f[index].name);
797             exit(1);
798         }
799     }
800 
801     fw_cfg_add_bytes_read_callback(s, FW_CFG_FILE_FIRST + index,
802                                    callback, callback_opaque, data, len,
803                                    read_only);
804 
805     s->files->f[index].size   = cpu_to_be32(len);
806     s->files->f[index].select = cpu_to_be16(FW_CFG_FILE_FIRST + index);
807     s->entry_order[index] = order;
808     trace_fw_cfg_add_file(s, index, s->files->f[index].name, len);
809 
810     s->files->count = cpu_to_be32(count+1);
811 }
812 
813 void fw_cfg_add_file(FWCfgState *s,  const char *filename,
814                      void *data, size_t len)
815 {
816     fw_cfg_add_file_callback(s, filename, NULL, NULL, data, len, true);
817 }
818 
819 void *fw_cfg_modify_file(FWCfgState *s, const char *filename,
820                         void *data, size_t len)
821 {
822     int i, index;
823     void *ptr = NULL;
824 
825     assert(s->files);
826 
827     index = be32_to_cpu(s->files->count);
828     assert(index < fw_cfg_file_slots(s));
829 
830     for (i = 0; i < index; i++) {
831         if (strcmp(filename, s->files->f[i].name) == 0) {
832             ptr = fw_cfg_modify_bytes_read(s, FW_CFG_FILE_FIRST + i,
833                                            data, len);
834             s->files->f[i].size   = cpu_to_be32(len);
835             return ptr;
836         }
837     }
838     /* add new one */
839     fw_cfg_add_file_callback(s, filename, NULL, NULL, data, len, true);
840     return NULL;
841 }
842 
843 static void fw_cfg_machine_reset(void *opaque)
844 {
845     void *ptr;
846     size_t len;
847     FWCfgState *s = opaque;
848     char *bootindex = get_boot_devices_list(&len, false);
849 
850     ptr = fw_cfg_modify_file(s, "bootorder", (uint8_t *)bootindex, len);
851     g_free(ptr);
852 }
853 
854 static void fw_cfg_machine_ready(struct Notifier *n, void *data)
855 {
856     FWCfgState *s = container_of(n, FWCfgState, machine_ready);
857     qemu_register_reset(fw_cfg_machine_reset, s);
858 }
859 
860 
861 
862 static void fw_cfg_common_realize(DeviceState *dev, Error **errp)
863 {
864     FWCfgState *s = FW_CFG(dev);
865     MachineState *machine = MACHINE(qdev_get_machine());
866     uint32_t version = FW_CFG_VERSION;
867 
868     if (!fw_cfg_find()) {
869         error_setg(errp, "at most one %s device is permitted", TYPE_FW_CFG);
870         return;
871     }
872 
873     fw_cfg_add_bytes(s, FW_CFG_SIGNATURE, (char *)"QEMU", 4);
874     fw_cfg_add_bytes(s, FW_CFG_UUID, &qemu_uuid, 16);
875     fw_cfg_add_i16(s, FW_CFG_NOGRAPHIC, (uint16_t)!machine->enable_graphics);
876     fw_cfg_add_i16(s, FW_CFG_BOOT_MENU, (uint16_t)boot_menu);
877     fw_cfg_bootsplash(s);
878     fw_cfg_reboot(s);
879 
880     if (s->dma_enabled) {
881         version |= FW_CFG_VERSION_DMA;
882     }
883 
884     fw_cfg_add_i32(s, FW_CFG_ID, version);
885 
886     s->machine_ready.notify = fw_cfg_machine_ready;
887     qemu_add_machine_init_done_notifier(&s->machine_ready);
888 }
889 
890 FWCfgState *fw_cfg_init_io_dma(uint32_t iobase, uint32_t dma_iobase,
891                                 AddressSpace *dma_as)
892 {
893     DeviceState *dev;
894     SysBusDevice *sbd;
895     FWCfgIoState *ios;
896     FWCfgState *s;
897     bool dma_requested = dma_iobase && dma_as;
898 
899     dev = qdev_create(NULL, TYPE_FW_CFG_IO);
900     if (!dma_requested) {
901         qdev_prop_set_bit(dev, "dma_enabled", false);
902     }
903 
904     object_property_add_child(OBJECT(qdev_get_machine()), TYPE_FW_CFG,
905                               OBJECT(dev), NULL);
906     qdev_init_nofail(dev);
907 
908     sbd = SYS_BUS_DEVICE(dev);
909     ios = FW_CFG_IO(dev);
910     sysbus_add_io(sbd, iobase, &ios->comb_iomem);
911 
912     s = FW_CFG(dev);
913 
914     if (s->dma_enabled) {
915         /* 64 bits for the address field */
916         s->dma_as = dma_as;
917         s->dma_addr = 0;
918         sysbus_add_io(sbd, dma_iobase, &s->dma_iomem);
919     }
920 
921     return s;
922 }
923 
924 FWCfgState *fw_cfg_init_io(uint32_t iobase)
925 {
926     return fw_cfg_init_io_dma(iobase, 0, NULL);
927 }
928 
929 FWCfgState *fw_cfg_init_mem_wide(hwaddr ctl_addr,
930                                  hwaddr data_addr, uint32_t data_width,
931                                  hwaddr dma_addr, AddressSpace *dma_as)
932 {
933     DeviceState *dev;
934     SysBusDevice *sbd;
935     FWCfgState *s;
936     bool dma_requested = dma_addr && dma_as;
937 
938     dev = qdev_create(NULL, TYPE_FW_CFG_MEM);
939     qdev_prop_set_uint32(dev, "data_width", data_width);
940     if (!dma_requested) {
941         qdev_prop_set_bit(dev, "dma_enabled", false);
942     }
943 
944     object_property_add_child(OBJECT(qdev_get_machine()), TYPE_FW_CFG,
945                               OBJECT(dev), NULL);
946     qdev_init_nofail(dev);
947 
948     sbd = SYS_BUS_DEVICE(dev);
949     sysbus_mmio_map(sbd, 0, ctl_addr);
950     sysbus_mmio_map(sbd, 1, data_addr);
951 
952     s = FW_CFG(dev);
953 
954     if (s->dma_enabled) {
955         s->dma_as = dma_as;
956         s->dma_addr = 0;
957         sysbus_mmio_map(sbd, 2, dma_addr);
958     }
959 
960     return s;
961 }
962 
963 FWCfgState *fw_cfg_init_mem(hwaddr ctl_addr, hwaddr data_addr)
964 {
965     return fw_cfg_init_mem_wide(ctl_addr, data_addr,
966                                 fw_cfg_data_mem_ops.valid.max_access_size,
967                                 0, NULL);
968 }
969 
970 
971 FWCfgState *fw_cfg_find(void)
972 {
973     /* Returns NULL unless there is exactly one fw_cfg device */
974     return FW_CFG(object_resolve_path_type("", TYPE_FW_CFG, NULL));
975 }
976 
977 
978 static void fw_cfg_class_init(ObjectClass *klass, void *data)
979 {
980     DeviceClass *dc = DEVICE_CLASS(klass);
981 
982     dc->reset = fw_cfg_reset;
983     dc->vmsd = &vmstate_fw_cfg;
984 }
985 
986 static const TypeInfo fw_cfg_info = {
987     .name          = TYPE_FW_CFG,
988     .parent        = TYPE_SYS_BUS_DEVICE,
989     .abstract      = true,
990     .instance_size = sizeof(FWCfgState),
991     .class_init    = fw_cfg_class_init,
992 };
993 
994 static void fw_cfg_file_slots_allocate(FWCfgState *s, Error **errp)
995 {
996     uint16_t file_slots_max;
997 
998     if (fw_cfg_file_slots(s) < FW_CFG_FILE_SLOTS_MIN) {
999         error_setg(errp, "\"file_slots\" must be at least 0x%x",
1000                    FW_CFG_FILE_SLOTS_MIN);
1001         return;
1002     }
1003 
1004     /* (UINT16_MAX & FW_CFG_ENTRY_MASK) is the highest inclusive selector value
1005      * that we permit. The actual (exclusive) value coming from the
1006      * configuration is (FW_CFG_FILE_FIRST + fw_cfg_file_slots(s)). */
1007     file_slots_max = (UINT16_MAX & FW_CFG_ENTRY_MASK) - FW_CFG_FILE_FIRST + 1;
1008     if (fw_cfg_file_slots(s) > file_slots_max) {
1009         error_setg(errp, "\"file_slots\" must not exceed 0x%" PRIx16,
1010                    file_slots_max);
1011         return;
1012     }
1013 
1014     s->entries[0] = g_new0(FWCfgEntry, fw_cfg_max_entry(s));
1015     s->entries[1] = g_new0(FWCfgEntry, fw_cfg_max_entry(s));
1016     s->entry_order = g_new0(int, fw_cfg_max_entry(s));
1017 }
1018 
1019 static Property fw_cfg_io_properties[] = {
1020     DEFINE_PROP_BOOL("dma_enabled", FWCfgIoState, parent_obj.dma_enabled,
1021                      true),
1022     DEFINE_PROP_UINT16("x-file-slots", FWCfgIoState, parent_obj.file_slots,
1023                        FW_CFG_FILE_SLOTS_DFLT),
1024     DEFINE_PROP_END_OF_LIST(),
1025 };
1026 
1027 static void fw_cfg_io_realize(DeviceState *dev, Error **errp)
1028 {
1029     FWCfgIoState *s = FW_CFG_IO(dev);
1030     Error *local_err = NULL;
1031 
1032     fw_cfg_file_slots_allocate(FW_CFG(s), &local_err);
1033     if (local_err) {
1034         error_propagate(errp, local_err);
1035         return;
1036     }
1037 
1038     /* when using port i/o, the 8-bit data register ALWAYS overlaps
1039      * with half of the 16-bit control register. Hence, the total size
1040      * of the i/o region used is FW_CFG_CTL_SIZE */
1041     memory_region_init_io(&s->comb_iomem, OBJECT(s), &fw_cfg_comb_mem_ops,
1042                           FW_CFG(s), "fwcfg", FW_CFG_CTL_SIZE);
1043 
1044     if (FW_CFG(s)->dma_enabled) {
1045         memory_region_init_io(&FW_CFG(s)->dma_iomem, OBJECT(s),
1046                               &fw_cfg_dma_mem_ops, FW_CFG(s), "fwcfg.dma",
1047                               sizeof(dma_addr_t));
1048     }
1049 
1050     fw_cfg_common_realize(dev, errp);
1051 }
1052 
1053 static void fw_cfg_io_class_init(ObjectClass *klass, void *data)
1054 {
1055     DeviceClass *dc = DEVICE_CLASS(klass);
1056 
1057     dc->realize = fw_cfg_io_realize;
1058     dc->props = fw_cfg_io_properties;
1059 }
1060 
1061 static const TypeInfo fw_cfg_io_info = {
1062     .name          = TYPE_FW_CFG_IO,
1063     .parent        = TYPE_FW_CFG,
1064     .instance_size = sizeof(FWCfgIoState),
1065     .class_init    = fw_cfg_io_class_init,
1066 };
1067 
1068 
1069 static Property fw_cfg_mem_properties[] = {
1070     DEFINE_PROP_UINT32("data_width", FWCfgMemState, data_width, -1),
1071     DEFINE_PROP_BOOL("dma_enabled", FWCfgMemState, parent_obj.dma_enabled,
1072                      true),
1073     DEFINE_PROP_UINT16("x-file-slots", FWCfgMemState, parent_obj.file_slots,
1074                        FW_CFG_FILE_SLOTS_DFLT),
1075     DEFINE_PROP_END_OF_LIST(),
1076 };
1077 
1078 static void fw_cfg_mem_realize(DeviceState *dev, Error **errp)
1079 {
1080     FWCfgMemState *s = FW_CFG_MEM(dev);
1081     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1082     const MemoryRegionOps *data_ops = &fw_cfg_data_mem_ops;
1083     Error *local_err = NULL;
1084 
1085     fw_cfg_file_slots_allocate(FW_CFG(s), &local_err);
1086     if (local_err) {
1087         error_propagate(errp, local_err);
1088         return;
1089     }
1090 
1091     memory_region_init_io(&s->ctl_iomem, OBJECT(s), &fw_cfg_ctl_mem_ops,
1092                           FW_CFG(s), "fwcfg.ctl", FW_CFG_CTL_SIZE);
1093     sysbus_init_mmio(sbd, &s->ctl_iomem);
1094 
1095     if (s->data_width > data_ops->valid.max_access_size) {
1096         /* memberwise copy because the "old_mmio" member is const */
1097         s->wide_data_ops.read       = data_ops->read;
1098         s->wide_data_ops.write      = data_ops->write;
1099         s->wide_data_ops.endianness = data_ops->endianness;
1100         s->wide_data_ops.valid      = data_ops->valid;
1101         s->wide_data_ops.impl       = data_ops->impl;
1102 
1103         s->wide_data_ops.valid.max_access_size = s->data_width;
1104         s->wide_data_ops.impl.max_access_size  = s->data_width;
1105         data_ops = &s->wide_data_ops;
1106     }
1107     memory_region_init_io(&s->data_iomem, OBJECT(s), data_ops, FW_CFG(s),
1108                           "fwcfg.data", data_ops->valid.max_access_size);
1109     sysbus_init_mmio(sbd, &s->data_iomem);
1110 
1111     if (FW_CFG(s)->dma_enabled) {
1112         memory_region_init_io(&FW_CFG(s)->dma_iomem, OBJECT(s),
1113                               &fw_cfg_dma_mem_ops, FW_CFG(s), "fwcfg.dma",
1114                               sizeof(dma_addr_t));
1115         sysbus_init_mmio(sbd, &FW_CFG(s)->dma_iomem);
1116     }
1117 
1118     fw_cfg_common_realize(dev, errp);
1119 }
1120 
1121 static void fw_cfg_mem_class_init(ObjectClass *klass, void *data)
1122 {
1123     DeviceClass *dc = DEVICE_CLASS(klass);
1124 
1125     dc->realize = fw_cfg_mem_realize;
1126     dc->props = fw_cfg_mem_properties;
1127 }
1128 
1129 static const TypeInfo fw_cfg_mem_info = {
1130     .name          = TYPE_FW_CFG_MEM,
1131     .parent        = TYPE_FW_CFG,
1132     .instance_size = sizeof(FWCfgMemState),
1133     .class_init    = fw_cfg_mem_class_init,
1134 };
1135 
1136 
1137 static void fw_cfg_register_types(void)
1138 {
1139     type_register_static(&fw_cfg_info);
1140     type_register_static(&fw_cfg_io_info);
1141     type_register_static(&fw_cfg_mem_info);
1142 }
1143 
1144 type_init(fw_cfg_register_types)
1145