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