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