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