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