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