xref: /openbmc/qemu/hw/block/pflash_cfi01.c (revision db57fef1)
1 /*
2  *  CFI parallel flash with Intel command set emulation
3  *
4  *  Copyright (c) 2006 Thorsten Zitterell
5  *  Copyright (c) 2005 Jocelyn Mayer
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 /*
22  * For now, this code can emulate flashes of 1, 2 or 4 bytes width.
23  * Supported commands/modes are:
24  * - flash read
25  * - flash write
26  * - flash ID read
27  * - sector erase
28  * - CFI queries
29  *
30  * It does not support timings
31  * It does not support flash interleaving
32  * It does not implement software data protection as found in many real chips
33  * It does not implement erase suspend/resume commands
34  * It does not implement multiple sectors erase
35  *
36  * It does not implement much more ...
37  */
38 
39 #include "qemu/osdep.h"
40 #include "hw/block/block.h"
41 #include "hw/block/flash.h"
42 #include "hw/qdev-properties.h"
43 #include "sysemu/block-backend.h"
44 #include "qapi/error.h"
45 #include "qemu/error-report.h"
46 #include "qemu/bitops.h"
47 #include "qemu/error-report.h"
48 #include "qemu/host-utils.h"
49 #include "qemu/log.h"
50 #include "qemu/module.h"
51 #include "qemu/option.h"
52 #include "hw/sysbus.h"
53 #include "migration/vmstate.h"
54 #include "sysemu/blockdev.h"
55 #include "sysemu/runstate.h"
56 #include "trace.h"
57 
58 /* #define PFLASH_DEBUG */
59 #ifdef PFLASH_DEBUG
60 #define DPRINTF(fmt, ...)                                   \
61 do {                                                        \
62     fprintf(stderr, "PFLASH: " fmt , ## __VA_ARGS__);       \
63 } while (0)
64 #else
65 #define DPRINTF(fmt, ...) do { } while (0)
66 #endif
67 
68 #define PFLASH_BE          0
69 #define PFLASH_SECURE      1
70 
71 struct PFlashCFI01 {
72     /*< private >*/
73     SysBusDevice parent_obj;
74     /*< public >*/
75 
76     BlockBackend *blk;
77     uint32_t nb_blocs;
78     uint64_t sector_len;
79     uint8_t bank_width;
80     uint8_t device_width; /* If 0, device width not specified. */
81     uint8_t max_device_width;  /* max device width in bytes */
82     uint32_t features;
83     uint8_t wcycle; /* if 0, the flash is read normally */
84     int ro;
85     uint8_t cmd;
86     uint8_t status;
87     uint16_t ident0;
88     uint16_t ident1;
89     uint16_t ident2;
90     uint16_t ident3;
91     uint8_t cfi_table[0x52];
92     uint64_t counter;
93     unsigned int writeblock_size;
94     MemoryRegion mem;
95     char *name;
96     void *storage;
97     VMChangeStateEntry *vmstate;
98     bool old_multiple_chip_handling;
99 };
100 
101 static int pflash_post_load(void *opaque, int version_id);
102 
103 static const VMStateDescription vmstate_pflash = {
104     .name = "pflash_cfi01",
105     .version_id = 1,
106     .minimum_version_id = 1,
107     .post_load = pflash_post_load,
108     .fields = (VMStateField[]) {
109         VMSTATE_UINT8(wcycle, PFlashCFI01),
110         VMSTATE_UINT8(cmd, PFlashCFI01),
111         VMSTATE_UINT8(status, PFlashCFI01),
112         VMSTATE_UINT64(counter, PFlashCFI01),
113         VMSTATE_END_OF_LIST()
114     }
115 };
116 
117 /* Perform a CFI query based on the bank width of the flash.
118  * If this code is called we know we have a device_width set for
119  * this flash.
120  */
121 static uint32_t pflash_cfi_query(PFlashCFI01 *pfl, hwaddr offset)
122 {
123     int i;
124     uint32_t resp = 0;
125     hwaddr boff;
126 
127     /* Adjust incoming offset to match expected device-width
128      * addressing. CFI query addresses are always specified in terms of
129      * the maximum supported width of the device.  This means that x8
130      * devices and x8/x16 devices in x8 mode behave differently.  For
131      * devices that are not used at their max width, we will be
132      * provided with addresses that use higher address bits than
133      * expected (based on the max width), so we will shift them lower
134      * so that they will match the addresses used when
135      * device_width==max_device_width.
136      */
137     boff = offset >> (ctz32(pfl->bank_width) +
138                       ctz32(pfl->max_device_width) - ctz32(pfl->device_width));
139 
140     if (boff >= sizeof(pfl->cfi_table)) {
141         return 0;
142     }
143     /* Now we will construct the CFI response generated by a single
144      * device, then replicate that for all devices that make up the
145      * bus.  For wide parts used in x8 mode, CFI query responses
146      * are different than native byte-wide parts.
147      */
148     resp = pfl->cfi_table[boff];
149     if (pfl->device_width != pfl->max_device_width) {
150         /* The only case currently supported is x8 mode for a
151          * wider part.
152          */
153         if (pfl->device_width != 1 || pfl->bank_width > 4) {
154             DPRINTF("%s: Unsupported device configuration: "
155                     "device_width=%d, max_device_width=%d\n",
156                     __func__, pfl->device_width,
157                     pfl->max_device_width);
158             return 0;
159         }
160         /* CFI query data is repeated, rather than zero padded for
161          * wide devices used in x8 mode.
162          */
163         for (i = 1; i < pfl->max_device_width; i++) {
164             resp = deposit32(resp, 8 * i, 8, pfl->cfi_table[boff]);
165         }
166     }
167     /* Replicate responses for each device in bank. */
168     if (pfl->device_width < pfl->bank_width) {
169         for (i = pfl->device_width;
170              i < pfl->bank_width; i += pfl->device_width) {
171             resp = deposit32(resp, 8 * i, 8 * pfl->device_width, resp);
172         }
173     }
174 
175     return resp;
176 }
177 
178 
179 
180 /* Perform a device id query based on the bank width of the flash. */
181 static uint32_t pflash_devid_query(PFlashCFI01 *pfl, hwaddr offset)
182 {
183     int i;
184     uint32_t resp;
185     hwaddr boff;
186 
187     /* Adjust incoming offset to match expected device-width
188      * addressing. Device ID read addresses are always specified in
189      * terms of the maximum supported width of the device.  This means
190      * that x8 devices and x8/x16 devices in x8 mode behave
191      * differently. For devices that are not used at their max width,
192      * we will be provided with addresses that use higher address bits
193      * than expected (based on the max width), so we will shift them
194      * lower so that they will match the addresses used when
195      * device_width==max_device_width.
196      */
197     boff = offset >> (ctz32(pfl->bank_width) +
198                       ctz32(pfl->max_device_width) - ctz32(pfl->device_width));
199 
200     /* Mask off upper bits which may be used in to query block
201      * or sector lock status at other addresses.
202      * Offsets 2/3 are block lock status, is not emulated.
203      */
204     switch (boff & 0xFF) {
205     case 0:
206         resp = pfl->ident0;
207         trace_pflash_manufacturer_id(resp);
208         break;
209     case 1:
210         resp = pfl->ident1;
211         trace_pflash_device_id(resp);
212         break;
213     default:
214         trace_pflash_device_info(offset);
215         return 0;
216         break;
217     }
218     /* Replicate responses for each device in bank. */
219     if (pfl->device_width < pfl->bank_width) {
220         for (i = pfl->device_width;
221               i < pfl->bank_width; i += pfl->device_width) {
222             resp = deposit32(resp, 8 * i, 8 * pfl->device_width, resp);
223         }
224     }
225 
226     return resp;
227 }
228 
229 static uint32_t pflash_data_read(PFlashCFI01 *pfl, hwaddr offset,
230                                  int width, int be)
231 {
232     uint8_t *p;
233     uint32_t ret;
234 
235     p = pfl->storage;
236     switch (width) {
237     case 1:
238         ret = p[offset];
239         break;
240     case 2:
241         if (be) {
242             ret = p[offset] << 8;
243             ret |= p[offset + 1];
244         } else {
245             ret = p[offset];
246             ret |= p[offset + 1] << 8;
247         }
248         break;
249     case 4:
250         if (be) {
251             ret = p[offset] << 24;
252             ret |= p[offset + 1] << 16;
253             ret |= p[offset + 2] << 8;
254             ret |= p[offset + 3];
255         } else {
256             ret = p[offset];
257             ret |= p[offset + 1] << 8;
258             ret |= p[offset + 2] << 16;
259             ret |= p[offset + 3] << 24;
260         }
261         break;
262     default:
263         DPRINTF("BUG in %s\n", __func__);
264         abort();
265     }
266     trace_pflash_data_read(offset, width, ret);
267     return ret;
268 }
269 
270 static uint32_t pflash_read(PFlashCFI01 *pfl, hwaddr offset,
271                             int width, int be)
272 {
273     hwaddr boff;
274     uint32_t ret;
275 
276     ret = -1;
277     switch (pfl->cmd) {
278     default:
279         /* This should never happen : reset state & treat it as a read */
280         DPRINTF("%s: unknown command state: %x\n", __func__, pfl->cmd);
281         pfl->wcycle = 0;
282         /*
283          * The command 0x00 is not assigned by the CFI open standard,
284          * but QEMU historically uses it for the READ_ARRAY command (0xff).
285          */
286         pfl->cmd = 0x00;
287         /* fall through to read code */
288     case 0x00: /* This model reset value for READ_ARRAY (not CFI compliant) */
289         /* Flash area read */
290         ret = pflash_data_read(pfl, offset, width, be);
291         break;
292     case 0x10: /* Single byte program */
293     case 0x20: /* Block erase */
294     case 0x28: /* Block erase */
295     case 0x40: /* single byte program */
296     case 0x50: /* Clear status register */
297     case 0x60: /* Block /un)lock */
298     case 0x70: /* Status Register */
299     case 0xe8: /* Write block */
300         /* Status register read.  Return status from each device in
301          * bank.
302          */
303         ret = pfl->status;
304         if (pfl->device_width && width > pfl->device_width) {
305             int shift = pfl->device_width * 8;
306             while (shift + pfl->device_width * 8 <= width * 8) {
307                 ret |= pfl->status << shift;
308                 shift += pfl->device_width * 8;
309             }
310         } else if (!pfl->device_width && width > 2) {
311             /* Handle 32 bit flash cases where device width is not
312              * set. (Existing behavior before device width added.)
313              */
314             ret |= pfl->status << 16;
315         }
316         DPRINTF("%s: status %x\n", __func__, ret);
317         break;
318     case 0x90:
319         if (!pfl->device_width) {
320             /* Preserve old behavior if device width not specified */
321             boff = offset & 0xFF;
322             if (pfl->bank_width == 2) {
323                 boff = boff >> 1;
324             } else if (pfl->bank_width == 4) {
325                 boff = boff >> 2;
326             }
327 
328             switch (boff) {
329             case 0:
330                 ret = pfl->ident0 << 8 | pfl->ident1;
331                 trace_pflash_manufacturer_id(ret);
332                 break;
333             case 1:
334                 ret = pfl->ident2 << 8 | pfl->ident3;
335                 trace_pflash_device_id(ret);
336                 break;
337             default:
338                 trace_pflash_device_info(boff);
339                 ret = 0;
340                 break;
341             }
342         } else {
343             /* If we have a read larger than the bank_width, combine multiple
344              * manufacturer/device ID queries into a single response.
345              */
346             int i;
347             for (i = 0; i < width; i += pfl->bank_width) {
348                 ret = deposit32(ret, i * 8, pfl->bank_width * 8,
349                                 pflash_devid_query(pfl,
350                                                  offset + i * pfl->bank_width));
351             }
352         }
353         break;
354     case 0x98: /* Query mode */
355         if (!pfl->device_width) {
356             /* Preserve old behavior if device width not specified */
357             boff = offset & 0xFF;
358             if (pfl->bank_width == 2) {
359                 boff = boff >> 1;
360             } else if (pfl->bank_width == 4) {
361                 boff = boff >> 2;
362             }
363 
364             if (boff < sizeof(pfl->cfi_table)) {
365                 ret = pfl->cfi_table[boff];
366             } else {
367                 ret = 0;
368             }
369         } else {
370             /* If we have a read larger than the bank_width, combine multiple
371              * CFI queries into a single response.
372              */
373             int i;
374             for (i = 0; i < width; i += pfl->bank_width) {
375                 ret = deposit32(ret, i * 8, pfl->bank_width * 8,
376                                 pflash_cfi_query(pfl,
377                                                  offset + i * pfl->bank_width));
378             }
379         }
380 
381         break;
382     }
383     trace_pflash_io_read(offset, width, ret, pfl->cmd, pfl->wcycle);
384 
385     return ret;
386 }
387 
388 /* update flash content on disk */
389 static void pflash_update(PFlashCFI01 *pfl, int offset,
390                           int size)
391 {
392     int offset_end;
393     int ret;
394     if (pfl->blk) {
395         offset_end = offset + size;
396         /* widen to sector boundaries */
397         offset = QEMU_ALIGN_DOWN(offset, BDRV_SECTOR_SIZE);
398         offset_end = QEMU_ALIGN_UP(offset_end, BDRV_SECTOR_SIZE);
399         ret = blk_pwrite(pfl->blk, offset, pfl->storage + offset,
400                    offset_end - offset, 0);
401         if (ret < 0) {
402             /* TODO set error bit in status */
403             error_report("Could not update PFLASH: %s", strerror(-ret));
404         }
405     }
406 }
407 
408 static inline void pflash_data_write(PFlashCFI01 *pfl, hwaddr offset,
409                                      uint32_t value, int width, int be)
410 {
411     uint8_t *p = pfl->storage;
412 
413     trace_pflash_data_write(offset, width, value, pfl->counter);
414     switch (width) {
415     case 1:
416         p[offset] = value;
417         break;
418     case 2:
419         if (be) {
420             p[offset] = value >> 8;
421             p[offset + 1] = value;
422         } else {
423             p[offset] = value;
424             p[offset + 1] = value >> 8;
425         }
426         break;
427     case 4:
428         if (be) {
429             p[offset] = value >> 24;
430             p[offset + 1] = value >> 16;
431             p[offset + 2] = value >> 8;
432             p[offset + 3] = value;
433         } else {
434             p[offset] = value;
435             p[offset + 1] = value >> 8;
436             p[offset + 2] = value >> 16;
437             p[offset + 3] = value >> 24;
438         }
439         break;
440     }
441 
442 }
443 
444 static void pflash_write(PFlashCFI01 *pfl, hwaddr offset,
445                          uint32_t value, int width, int be)
446 {
447     uint8_t *p;
448     uint8_t cmd;
449 
450     cmd = value;
451 
452     trace_pflash_io_write(offset, width, value, pfl->wcycle);
453     if (!pfl->wcycle) {
454         /* Set the device in I/O access mode */
455         memory_region_rom_device_set_romd(&pfl->mem, false);
456     }
457 
458     switch (pfl->wcycle) {
459     case 0:
460         /* read mode */
461         switch (cmd) {
462         case 0x00: /* This model reset value for READ_ARRAY (not CFI) */
463             goto mode_read_array;
464         case 0x10: /* Single Byte Program */
465         case 0x40: /* Single Byte Program */
466             DPRINTF("%s: Single Byte Program\n", __func__);
467             break;
468         case 0x20: /* Block erase */
469             p = pfl->storage;
470             offset &= ~(pfl->sector_len - 1);
471 
472             DPRINTF("%s: block erase at " TARGET_FMT_plx " bytes %x\n",
473                     __func__, offset, (unsigned)pfl->sector_len);
474 
475             if (!pfl->ro) {
476                 memset(p + offset, 0xff, pfl->sector_len);
477                 pflash_update(pfl, offset, pfl->sector_len);
478             } else {
479                 pfl->status |= 0x20; /* Block erase error */
480             }
481             pfl->status |= 0x80; /* Ready! */
482             break;
483         case 0x50: /* Clear status bits */
484             DPRINTF("%s: Clear status bits\n", __func__);
485             pfl->status = 0x0;
486             goto mode_read_array;
487         case 0x60: /* Block (un)lock */
488             DPRINTF("%s: Block unlock\n", __func__);
489             break;
490         case 0x70: /* Status Register */
491             DPRINTF("%s: Read status register\n", __func__);
492             pfl->cmd = cmd;
493             return;
494         case 0x90: /* Read Device ID */
495             DPRINTF("%s: Read Device information\n", __func__);
496             pfl->cmd = cmd;
497             return;
498         case 0x98: /* CFI query */
499             DPRINTF("%s: CFI query\n", __func__);
500             break;
501         case 0xe8: /* Write to buffer */
502             DPRINTF("%s: Write to buffer\n", __func__);
503             /* FIXME should save @offset, @width for case 1+ */
504             qemu_log_mask(LOG_UNIMP,
505                           "%s: Write to buffer emulation is flawed\n",
506                           __func__);
507             pfl->status |= 0x80; /* Ready! */
508             break;
509         case 0xf0: /* Probe for AMD flash */
510             DPRINTF("%s: Probe for AMD flash\n", __func__);
511             goto mode_read_array;
512         case 0xff: /* Read Array */
513             DPRINTF("%s: Read array mode\n", __func__);
514             goto mode_read_array;
515         default:
516             goto error_flash;
517         }
518         pfl->wcycle++;
519         pfl->cmd = cmd;
520         break;
521     case 1:
522         switch (pfl->cmd) {
523         case 0x10: /* Single Byte Program */
524         case 0x40: /* Single Byte Program */
525             DPRINTF("%s: Single Byte Program\n", __func__);
526             if (!pfl->ro) {
527                 pflash_data_write(pfl, offset, value, width, be);
528                 pflash_update(pfl, offset, width);
529             } else {
530                 pfl->status |= 0x10; /* Programming error */
531             }
532             pfl->status |= 0x80; /* Ready! */
533             pfl->wcycle = 0;
534         break;
535         case 0x20: /* Block erase */
536         case 0x28:
537             if (cmd == 0xd0) { /* confirm */
538                 pfl->wcycle = 0;
539                 pfl->status |= 0x80;
540             } else if (cmd == 0xff) { /* Read Array */
541                 goto mode_read_array;
542             } else
543                 goto error_flash;
544 
545             break;
546         case 0xe8:
547             /* Mask writeblock size based on device width, or bank width if
548              * device width not specified.
549              */
550             /* FIXME check @offset, @width */
551             if (pfl->device_width) {
552                 value = extract32(value, 0, pfl->device_width * 8);
553             } else {
554                 value = extract32(value, 0, pfl->bank_width * 8);
555             }
556             DPRINTF("%s: block write of %x bytes\n", __func__, value);
557             pfl->counter = value;
558             pfl->wcycle++;
559             break;
560         case 0x60:
561             if (cmd == 0xd0) {
562                 pfl->wcycle = 0;
563                 pfl->status |= 0x80;
564             } else if (cmd == 0x01) {
565                 pfl->wcycle = 0;
566                 pfl->status |= 0x80;
567             } else if (cmd == 0xff) { /* Read Array */
568                 goto mode_read_array;
569             } else {
570                 DPRINTF("%s: Unknown (un)locking command\n", __func__);
571                 goto mode_read_array;
572             }
573             break;
574         case 0x98:
575             if (cmd == 0xff) { /* Read Array */
576                 goto mode_read_array;
577             } else {
578                 DPRINTF("%s: leaving query mode\n", __func__);
579             }
580             break;
581         default:
582             goto error_flash;
583         }
584         break;
585     case 2:
586         switch (pfl->cmd) {
587         case 0xe8: /* Block write */
588             /* FIXME check @offset, @width */
589             if (!pfl->ro) {
590                 /*
591                  * FIXME writing straight to memory is *wrong*.  We
592                  * should write to a buffer, and flush it to memory
593                  * only on confirm command (see below).
594                  */
595                 pflash_data_write(pfl, offset, value, width, be);
596             } else {
597                 pfl->status |= 0x10; /* Programming error */
598             }
599 
600             pfl->status |= 0x80;
601 
602             if (!pfl->counter) {
603                 hwaddr mask = pfl->writeblock_size - 1;
604                 mask = ~mask;
605 
606                 DPRINTF("%s: block write finished\n", __func__);
607                 pfl->wcycle++;
608                 if (!pfl->ro) {
609                     /* Flush the entire write buffer onto backing storage.  */
610                     /* FIXME premature! */
611                     pflash_update(pfl, offset & mask, pfl->writeblock_size);
612                 } else {
613                     pfl->status |= 0x10; /* Programming error */
614                 }
615             }
616 
617             pfl->counter--;
618             break;
619         default:
620             goto error_flash;
621         }
622         break;
623     case 3: /* Confirm mode */
624         switch (pfl->cmd) {
625         case 0xe8: /* Block write */
626             if (cmd == 0xd0) {
627                 /* FIXME this is where we should write out the buffer */
628                 pfl->wcycle = 0;
629                 pfl->status |= 0x80;
630             } else {
631                 qemu_log_mask(LOG_UNIMP,
632                     "%s: Aborting write to buffer not implemented,"
633                     " the data is already written to storage!\n"
634                     "Flash device reset into READ mode.\n",
635                     __func__);
636                 goto mode_read_array;
637             }
638             break;
639         default:
640             goto error_flash;
641         }
642         break;
643     default:
644         /* Should never happen */
645         DPRINTF("%s: invalid write state\n",  __func__);
646         goto mode_read_array;
647     }
648     return;
649 
650  error_flash:
651     qemu_log_mask(LOG_UNIMP, "%s: Unimplemented flash cmd sequence "
652                   "(offset " TARGET_FMT_plx ", wcycle 0x%x cmd 0x%x value 0x%x)"
653                   "\n", __func__, offset, pfl->wcycle, pfl->cmd, value);
654 
655  mode_read_array:
656     trace_pflash_reset();
657     memory_region_rom_device_set_romd(&pfl->mem, true);
658     pfl->wcycle = 0;
659     pfl->cmd = 0x00; /* This model reset value for READ_ARRAY (not CFI) */
660 }
661 
662 
663 static MemTxResult pflash_mem_read_with_attrs(void *opaque, hwaddr addr, uint64_t *value,
664                                               unsigned len, MemTxAttrs attrs)
665 {
666     PFlashCFI01 *pfl = opaque;
667     bool be = !!(pfl->features & (1 << PFLASH_BE));
668 
669     if ((pfl->features & (1 << PFLASH_SECURE)) && !attrs.secure) {
670         *value = pflash_data_read(opaque, addr, len, be);
671     } else {
672         *value = pflash_read(opaque, addr, len, be);
673     }
674     return MEMTX_OK;
675 }
676 
677 static MemTxResult pflash_mem_write_with_attrs(void *opaque, hwaddr addr, uint64_t value,
678                                                unsigned len, MemTxAttrs attrs)
679 {
680     PFlashCFI01 *pfl = opaque;
681     bool be = !!(pfl->features & (1 << PFLASH_BE));
682 
683     if ((pfl->features & (1 << PFLASH_SECURE)) && !attrs.secure) {
684         return MEMTX_ERROR;
685     } else {
686         pflash_write(opaque, addr, value, len, be);
687         return MEMTX_OK;
688     }
689 }
690 
691 static const MemoryRegionOps pflash_cfi01_ops = {
692     .read_with_attrs = pflash_mem_read_with_attrs,
693     .write_with_attrs = pflash_mem_write_with_attrs,
694     .endianness = DEVICE_NATIVE_ENDIAN,
695 };
696 
697 static void pflash_cfi01_realize(DeviceState *dev, Error **errp)
698 {
699     ERRP_GUARD();
700     PFlashCFI01 *pfl = PFLASH_CFI01(dev);
701     uint64_t total_len;
702     int ret;
703     uint64_t blocks_per_device, sector_len_per_device, device_len;
704     int num_devices;
705 
706     if (pfl->sector_len == 0) {
707         error_setg(errp, "attribute \"sector-length\" not specified or zero.");
708         return;
709     }
710     if (pfl->nb_blocs == 0) {
711         error_setg(errp, "attribute \"num-blocks\" not specified or zero.");
712         return;
713     }
714     if (pfl->name == NULL) {
715         error_setg(errp, "attribute \"name\" not specified.");
716         return;
717     }
718 
719     total_len = pfl->sector_len * pfl->nb_blocs;
720 
721     /* These are only used to expose the parameters of each device
722      * in the cfi_table[].
723      */
724     num_devices = pfl->device_width ? (pfl->bank_width / pfl->device_width) : 1;
725     if (pfl->old_multiple_chip_handling) {
726         blocks_per_device = pfl->nb_blocs / num_devices;
727         sector_len_per_device = pfl->sector_len;
728     } else {
729         blocks_per_device = pfl->nb_blocs;
730         sector_len_per_device = pfl->sector_len / num_devices;
731     }
732     device_len = sector_len_per_device * blocks_per_device;
733 
734     memory_region_init_rom_device(
735         &pfl->mem, OBJECT(dev),
736         &pflash_cfi01_ops,
737         pfl,
738         pfl->name, total_len, errp);
739     if (*errp) {
740         return;
741     }
742 
743     pfl->storage = memory_region_get_ram_ptr(&pfl->mem);
744     sysbus_init_mmio(SYS_BUS_DEVICE(dev), &pfl->mem);
745 
746     if (pfl->blk) {
747         uint64_t perm;
748         pfl->ro = blk_is_read_only(pfl->blk);
749         perm = BLK_PERM_CONSISTENT_READ | (pfl->ro ? 0 : BLK_PERM_WRITE);
750         ret = blk_set_perm(pfl->blk, perm, BLK_PERM_ALL, errp);
751         if (ret < 0) {
752             return;
753         }
754     } else {
755         pfl->ro = 0;
756     }
757 
758     if (pfl->blk) {
759         if (!blk_check_size_and_read_all(pfl->blk, pfl->storage, total_len,
760                                          errp)) {
761             vmstate_unregister_ram(&pfl->mem, DEVICE(pfl));
762             return;
763         }
764     }
765 
766     /* Default to devices being used at their maximum device width. This was
767      * assumed before the device_width support was added.
768      */
769     if (!pfl->max_device_width) {
770         pfl->max_device_width = pfl->device_width;
771     }
772 
773     pfl->wcycle = 0;
774     /*
775      * The command 0x00 is not assigned by the CFI open standard,
776      * but QEMU historically uses it for the READ_ARRAY command (0xff).
777      */
778     pfl->cmd = 0x00;
779     pfl->status = 0x80; /* WSM ready */
780     /* Hardcoded CFI table */
781     /* Standard "QRY" string */
782     pfl->cfi_table[0x10] = 'Q';
783     pfl->cfi_table[0x11] = 'R';
784     pfl->cfi_table[0x12] = 'Y';
785     /* Command set (Intel) */
786     pfl->cfi_table[0x13] = 0x01;
787     pfl->cfi_table[0x14] = 0x00;
788     /* Primary extended table address (none) */
789     pfl->cfi_table[0x15] = 0x31;
790     pfl->cfi_table[0x16] = 0x00;
791     /* Alternate command set (none) */
792     pfl->cfi_table[0x17] = 0x00;
793     pfl->cfi_table[0x18] = 0x00;
794     /* Alternate extended table (none) */
795     pfl->cfi_table[0x19] = 0x00;
796     pfl->cfi_table[0x1A] = 0x00;
797     /* Vcc min */
798     pfl->cfi_table[0x1B] = 0x45;
799     /* Vcc max */
800     pfl->cfi_table[0x1C] = 0x55;
801     /* Vpp min (no Vpp pin) */
802     pfl->cfi_table[0x1D] = 0x00;
803     /* Vpp max (no Vpp pin) */
804     pfl->cfi_table[0x1E] = 0x00;
805     /* Reserved */
806     pfl->cfi_table[0x1F] = 0x07;
807     /* Timeout for min size buffer write */
808     pfl->cfi_table[0x20] = 0x07;
809     /* Typical timeout for block erase */
810     pfl->cfi_table[0x21] = 0x0a;
811     /* Typical timeout for full chip erase (4096 ms) */
812     pfl->cfi_table[0x22] = 0x00;
813     /* Reserved */
814     pfl->cfi_table[0x23] = 0x04;
815     /* Max timeout for buffer write */
816     pfl->cfi_table[0x24] = 0x04;
817     /* Max timeout for block erase */
818     pfl->cfi_table[0x25] = 0x04;
819     /* Max timeout for chip erase */
820     pfl->cfi_table[0x26] = 0x00;
821     /* Device size */
822     pfl->cfi_table[0x27] = ctz32(device_len); /* + 1; */
823     /* Flash device interface (8 & 16 bits) */
824     pfl->cfi_table[0x28] = 0x02;
825     pfl->cfi_table[0x29] = 0x00;
826     /* Max number of bytes in multi-bytes write */
827     if (pfl->bank_width == 1) {
828         pfl->cfi_table[0x2A] = 0x08;
829     } else {
830         pfl->cfi_table[0x2A] = 0x0B;
831     }
832     pfl->writeblock_size = 1 << pfl->cfi_table[0x2A];
833     if (!pfl->old_multiple_chip_handling && num_devices > 1) {
834         pfl->writeblock_size *= num_devices;
835     }
836 
837     pfl->cfi_table[0x2B] = 0x00;
838     /* Number of erase block regions (uniform) */
839     pfl->cfi_table[0x2C] = 0x01;
840     /* Erase block region 1 */
841     pfl->cfi_table[0x2D] = blocks_per_device - 1;
842     pfl->cfi_table[0x2E] = (blocks_per_device - 1) >> 8;
843     pfl->cfi_table[0x2F] = sector_len_per_device >> 8;
844     pfl->cfi_table[0x30] = sector_len_per_device >> 16;
845 
846     /* Extended */
847     pfl->cfi_table[0x31] = 'P';
848     pfl->cfi_table[0x32] = 'R';
849     pfl->cfi_table[0x33] = 'I';
850 
851     pfl->cfi_table[0x34] = '1';
852     pfl->cfi_table[0x35] = '0';
853 
854     pfl->cfi_table[0x36] = 0x00;
855     pfl->cfi_table[0x37] = 0x00;
856     pfl->cfi_table[0x38] = 0x00;
857     pfl->cfi_table[0x39] = 0x00;
858 
859     pfl->cfi_table[0x3a] = 0x00;
860 
861     pfl->cfi_table[0x3b] = 0x00;
862     pfl->cfi_table[0x3c] = 0x00;
863 
864     pfl->cfi_table[0x3f] = 0x01; /* Number of protection fields */
865 }
866 
867 static void pflash_cfi01_system_reset(DeviceState *dev)
868 {
869     PFlashCFI01 *pfl = PFLASH_CFI01(dev);
870 
871     /*
872      * The command 0x00 is not assigned by the CFI open standard,
873      * but QEMU historically uses it for the READ_ARRAY command (0xff).
874      */
875     pfl->cmd = 0x00;
876     pfl->wcycle = 0;
877     memory_region_rom_device_set_romd(&pfl->mem, true);
878     /*
879      * The WSM ready timer occurs at most 150ns after system reset.
880      * This model deliberately ignores this delay.
881      */
882     pfl->status = 0x80;
883 }
884 
885 static Property pflash_cfi01_properties[] = {
886     DEFINE_PROP_DRIVE("drive", PFlashCFI01, blk),
887     /* num-blocks is the number of blocks actually visible to the guest,
888      * ie the total size of the device divided by the sector length.
889      * If we're emulating flash devices wired in parallel the actual
890      * number of blocks per indvidual device will differ.
891      */
892     DEFINE_PROP_UINT32("num-blocks", PFlashCFI01, nb_blocs, 0),
893     DEFINE_PROP_UINT64("sector-length", PFlashCFI01, sector_len, 0),
894     /* width here is the overall width of this QEMU device in bytes.
895      * The QEMU device may be emulating a number of flash devices
896      * wired up in parallel; the width of each individual flash
897      * device should be specified via device-width. If the individual
898      * devices have a maximum width which is greater than the width
899      * they are being used for, this maximum width should be set via
900      * max-device-width (which otherwise defaults to device-width).
901      * So for instance a 32-bit wide QEMU flash device made from four
902      * 16-bit flash devices used in 8-bit wide mode would be configured
903      * with width = 4, device-width = 1, max-device-width = 2.
904      *
905      * If device-width is not specified we default to backwards
906      * compatible behaviour which is a bad emulation of two
907      * 16 bit devices making up a 32 bit wide QEMU device. This
908      * is deprecated for new uses of this device.
909      */
910     DEFINE_PROP_UINT8("width", PFlashCFI01, bank_width, 0),
911     DEFINE_PROP_UINT8("device-width", PFlashCFI01, device_width, 0),
912     DEFINE_PROP_UINT8("max-device-width", PFlashCFI01, max_device_width, 0),
913     DEFINE_PROP_BIT("big-endian", PFlashCFI01, features, PFLASH_BE, 0),
914     DEFINE_PROP_BIT("secure", PFlashCFI01, features, PFLASH_SECURE, 0),
915     DEFINE_PROP_UINT16("id0", PFlashCFI01, ident0, 0),
916     DEFINE_PROP_UINT16("id1", PFlashCFI01, ident1, 0),
917     DEFINE_PROP_UINT16("id2", PFlashCFI01, ident2, 0),
918     DEFINE_PROP_UINT16("id3", PFlashCFI01, ident3, 0),
919     DEFINE_PROP_STRING("name", PFlashCFI01, name),
920     DEFINE_PROP_BOOL("old-multiple-chip-handling", PFlashCFI01,
921                      old_multiple_chip_handling, false),
922     DEFINE_PROP_END_OF_LIST(),
923 };
924 
925 static void pflash_cfi01_class_init(ObjectClass *klass, void *data)
926 {
927     DeviceClass *dc = DEVICE_CLASS(klass);
928 
929     dc->reset = pflash_cfi01_system_reset;
930     dc->realize = pflash_cfi01_realize;
931     device_class_set_props(dc, pflash_cfi01_properties);
932     dc->vmsd = &vmstate_pflash;
933     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
934 }
935 
936 
937 static const TypeInfo pflash_cfi01_info = {
938     .name           = TYPE_PFLASH_CFI01,
939     .parent         = TYPE_SYS_BUS_DEVICE,
940     .instance_size  = sizeof(PFlashCFI01),
941     .class_init     = pflash_cfi01_class_init,
942 };
943 
944 static void pflash_cfi01_register_types(void)
945 {
946     type_register_static(&pflash_cfi01_info);
947 }
948 
949 type_init(pflash_cfi01_register_types)
950 
951 PFlashCFI01 *pflash_cfi01_register(hwaddr base,
952                                    const char *name,
953                                    hwaddr size,
954                                    BlockBackend *blk,
955                                    uint32_t sector_len,
956                                    int bank_width,
957                                    uint16_t id0, uint16_t id1,
958                                    uint16_t id2, uint16_t id3,
959                                    int be)
960 {
961     DeviceState *dev = qdev_new(TYPE_PFLASH_CFI01);
962 
963     if (blk) {
964         qdev_prop_set_drive(dev, "drive", blk);
965     }
966     assert(QEMU_IS_ALIGNED(size, sector_len));
967     qdev_prop_set_uint32(dev, "num-blocks", size / sector_len);
968     qdev_prop_set_uint64(dev, "sector-length", sector_len);
969     qdev_prop_set_uint8(dev, "width", bank_width);
970     qdev_prop_set_bit(dev, "big-endian", !!be);
971     qdev_prop_set_uint16(dev, "id0", id0);
972     qdev_prop_set_uint16(dev, "id1", id1);
973     qdev_prop_set_uint16(dev, "id2", id2);
974     qdev_prop_set_uint16(dev, "id3", id3);
975     qdev_prop_set_string(dev, "name", name);
976     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
977 
978     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base);
979     return PFLASH_CFI01(dev);
980 }
981 
982 BlockBackend *pflash_cfi01_get_blk(PFlashCFI01 *fl)
983 {
984     return fl->blk;
985 }
986 
987 MemoryRegion *pflash_cfi01_get_memory(PFlashCFI01 *fl)
988 {
989     return &fl->mem;
990 }
991 
992 /*
993  * Handle -drive if=pflash for machines that use properties.
994  * If @dinfo is null, do nothing.
995  * Else if @fl's property "drive" is already set, fatal error.
996  * Else set it to the BlockBackend with @dinfo.
997  */
998 void pflash_cfi01_legacy_drive(PFlashCFI01 *fl, DriveInfo *dinfo)
999 {
1000     Location loc;
1001 
1002     if (!dinfo) {
1003         return;
1004     }
1005 
1006     loc_push_none(&loc);
1007     qemu_opts_loc_restore(dinfo->opts);
1008     if (fl->blk) {
1009         error_report("clashes with -machine");
1010         exit(1);
1011     }
1012     qdev_prop_set_drive_err(DEVICE(fl), "drive", blk_by_legacy_dinfo(dinfo),
1013                             &error_fatal);
1014     loc_pop(&loc);
1015 }
1016 
1017 static void postload_update_cb(void *opaque, int running, RunState state)
1018 {
1019     PFlashCFI01 *pfl = opaque;
1020 
1021     /* This is called after bdrv_invalidate_cache_all.  */
1022     qemu_del_vm_change_state_handler(pfl->vmstate);
1023     pfl->vmstate = NULL;
1024 
1025     DPRINTF("%s: updating bdrv for %s\n", __func__, pfl->name);
1026     pflash_update(pfl, 0, pfl->sector_len * pfl->nb_blocs);
1027 }
1028 
1029 static int pflash_post_load(void *opaque, int version_id)
1030 {
1031     PFlashCFI01 *pfl = opaque;
1032 
1033     if (!pfl->ro) {
1034         pfl->vmstate = qemu_add_vm_change_state_handler(postload_update_cb,
1035                                                         pfl);
1036     }
1037     return 0;
1038 }
1039