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