xref: /openbmc/qemu/hw/block/pflash_cfi01.c (revision ce7325c1)
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             pfl->status |= 0x80; /* Ready! */
522             break;
523         case 0xf0: /* Probe for AMD flash */
524             trace_pflash_write(pfl->name, "probe for AMD flash");
525             goto mode_read_array;
526         case 0xff: /* Read Array */
527             trace_pflash_write(pfl->name, "read array mode");
528             goto mode_read_array;
529         default:
530             goto error_flash;
531         }
532         pfl->wcycle++;
533         pfl->cmd = cmd;
534         break;
535     case 1:
536         switch (pfl->cmd) {
537         case 0x10: /* Single Byte Program */
538         case 0x40: /* Single Byte Program */
539             trace_pflash_write(pfl->name, "single byte program (1)");
540             if (!pfl->ro) {
541                 pflash_data_write(pfl, offset, value, width, be);
542                 pflash_update(pfl, offset, width);
543             } else {
544                 pfl->status |= 0x10; /* Programming error */
545             }
546             pfl->status |= 0x80; /* Ready! */
547             pfl->wcycle = 0;
548         break;
549         case 0x20: /* Block erase */
550         case 0x28:
551             if (cmd == 0xd0) { /* confirm */
552                 pfl->wcycle = 0;
553                 pfl->status |= 0x80;
554             } else if (cmd == 0xff) { /* Read Array */
555                 goto mode_read_array;
556             } else
557                 goto error_flash;
558 
559             break;
560         case 0xe8:
561             /*
562              * Mask writeblock size based on device width, or bank width if
563              * device width not specified.
564              */
565             /* FIXME check @offset, @width */
566             if (pfl->device_width) {
567                 value = extract32(value, 0, pfl->device_width * 8);
568             } else {
569                 value = extract32(value, 0, pfl->bank_width * 8);
570             }
571             pfl->counter = value;
572             pfl->wcycle++;
573             break;
574         case 0x60:
575             if (cmd == 0xd0) {
576                 pfl->wcycle = 0;
577                 pfl->status |= 0x80;
578             } else if (cmd == 0x01) {
579                 pfl->wcycle = 0;
580                 pfl->status |= 0x80;
581             } else if (cmd == 0xff) { /* Read Array */
582                 goto mode_read_array;
583             } else {
584                 trace_pflash_write(pfl->name, "unknown (un)locking command");
585                 goto mode_read_array;
586             }
587             break;
588         case 0x98:
589             if (cmd == 0xff) { /* Read Array */
590                 goto mode_read_array;
591             } else {
592                 trace_pflash_write(pfl->name, "leaving query mode");
593             }
594             break;
595         default:
596             goto error_flash;
597         }
598         break;
599     case 2:
600         switch (pfl->cmd) {
601         case 0xe8: /* Block write */
602             /* FIXME check @offset, @width */
603             if (pfl->blk_offset == -1 && pfl->counter) {
604                 pflash_blk_write_start(pfl, offset);
605             }
606             if (!pfl->ro && (pfl->blk_offset != -1)) {
607                 pflash_data_write(pfl, offset, value, width, be);
608             } else {
609                 pfl->status |= 0x10; /* Programming error */
610             }
611 
612             pfl->status |= 0x80;
613 
614             if (!pfl->counter) {
615                 trace_pflash_write(pfl->name, "block write finished");
616                 pfl->wcycle++;
617             }
618 
619             pfl->counter--;
620             break;
621         default:
622             goto error_flash;
623         }
624         break;
625     case 3: /* Confirm mode */
626         switch (pfl->cmd) {
627         case 0xe8: /* Block write */
628             if ((cmd == 0xd0) && !(pfl->status & 0x10)) {
629                 pflash_blk_write_flush(pfl);
630                 pfl->wcycle = 0;
631                 pfl->status |= 0x80;
632             } else {
633                 pflash_blk_write_abort(pfl);
634                 goto mode_read_array;
635             }
636             break;
637         default:
638             pflash_blk_write_abort(pfl);
639             goto error_flash;
640         }
641         break;
642     default:
643         /* Should never happen */
644         trace_pflash_write(pfl->name, "invalid write state");
645         goto mode_read_array;
646     }
647     return;
648 
649  error_flash:
650     qemu_log_mask(LOG_UNIMP, "%s: Unimplemented flash cmd sequence "
651                   "(offset " HWADDR_FMT_plx ", wcycle 0x%x cmd 0x%x value 0x%x)"
652                   "\n", __func__, offset, pfl->wcycle, pfl->cmd, value);
653 
654  mode_read_array:
655     trace_pflash_mode_read_array(pfl->name);
656     memory_region_rom_device_set_romd(&pfl->mem, true);
657     pfl->wcycle = 0;
658     pfl->cmd = 0x00; /* This model reset value for READ_ARRAY (not CFI) */
659 }
660 
661 
662 static MemTxResult pflash_mem_read_with_attrs(void *opaque, hwaddr addr, uint64_t *value,
663                                               unsigned len, MemTxAttrs attrs)
664 {
665     PFlashCFI01 *pfl = opaque;
666     bool be = !!(pfl->features & (1 << PFLASH_BE));
667 
668     if ((pfl->features & (1 << PFLASH_SECURE)) && !attrs.secure) {
669         *value = pflash_data_read(opaque, addr, len, be);
670     } else {
671         *value = pflash_read(opaque, addr, len, be);
672     }
673     return MEMTX_OK;
674 }
675 
676 static MemTxResult pflash_mem_write_with_attrs(void *opaque, hwaddr addr, uint64_t value,
677                                                unsigned len, MemTxAttrs attrs)
678 {
679     PFlashCFI01 *pfl = opaque;
680     bool be = !!(pfl->features & (1 << PFLASH_BE));
681 
682     if ((pfl->features & (1 << PFLASH_SECURE)) && !attrs.secure) {
683         return MEMTX_ERROR;
684     } else {
685         pflash_write(opaque, addr, value, len, be);
686         return MEMTX_OK;
687     }
688 }
689 
690 static const MemoryRegionOps pflash_cfi01_ops = {
691     .read_with_attrs = pflash_mem_read_with_attrs,
692     .write_with_attrs = pflash_mem_write_with_attrs,
693     .endianness = DEVICE_NATIVE_ENDIAN,
694 };
695 
696 static void pflash_cfi01_fill_cfi_table(PFlashCFI01 *pfl)
697 {
698     uint64_t blocks_per_device, sector_len_per_device, device_len;
699     int num_devices;
700 
701     /*
702      * These are only used to expose the parameters of each device
703      * in the cfi_table[].
704      */
705     num_devices = pfl->device_width ? (pfl->bank_width / pfl->device_width) : 1;
706     if (pfl->old_multiple_chip_handling) {
707         blocks_per_device = pfl->nb_blocs / num_devices;
708         sector_len_per_device = pfl->sector_len;
709     } else {
710         blocks_per_device = pfl->nb_blocs;
711         sector_len_per_device = pfl->sector_len / num_devices;
712     }
713     device_len = sector_len_per_device * blocks_per_device;
714 
715     /* Hardcoded CFI table */
716     /* Standard "QRY" string */
717     pfl->cfi_table[0x10] = 'Q';
718     pfl->cfi_table[0x11] = 'R';
719     pfl->cfi_table[0x12] = 'Y';
720     /* Command set (Intel) */
721     pfl->cfi_table[0x13] = 0x01;
722     pfl->cfi_table[0x14] = 0x00;
723     /* Primary extended table address (none) */
724     pfl->cfi_table[0x15] = 0x31;
725     pfl->cfi_table[0x16] = 0x00;
726     /* Alternate command set (none) */
727     pfl->cfi_table[0x17] = 0x00;
728     pfl->cfi_table[0x18] = 0x00;
729     /* Alternate extended table (none) */
730     pfl->cfi_table[0x19] = 0x00;
731     pfl->cfi_table[0x1A] = 0x00;
732     /* Vcc min */
733     pfl->cfi_table[0x1B] = 0x45;
734     /* Vcc max */
735     pfl->cfi_table[0x1C] = 0x55;
736     /* Vpp min (no Vpp pin) */
737     pfl->cfi_table[0x1D] = 0x00;
738     /* Vpp max (no Vpp pin) */
739     pfl->cfi_table[0x1E] = 0x00;
740     /* Reserved */
741     pfl->cfi_table[0x1F] = 0x07;
742     /* Timeout for min size buffer write */
743     pfl->cfi_table[0x20] = 0x07;
744     /* Typical timeout for block erase */
745     pfl->cfi_table[0x21] = 0x0a;
746     /* Typical timeout for full chip erase (4096 ms) */
747     pfl->cfi_table[0x22] = 0x00;
748     /* Reserved */
749     pfl->cfi_table[0x23] = 0x04;
750     /* Max timeout for buffer write */
751     pfl->cfi_table[0x24] = 0x04;
752     /* Max timeout for block erase */
753     pfl->cfi_table[0x25] = 0x04;
754     /* Max timeout for chip erase */
755     pfl->cfi_table[0x26] = 0x00;
756     /* Device size */
757     pfl->cfi_table[0x27] = ctz32(device_len); /* + 1; */
758     /* Flash device interface (8 & 16 bits) */
759     pfl->cfi_table[0x28] = 0x02;
760     pfl->cfi_table[0x29] = 0x00;
761     /* Max number of bytes in multi-bytes write */
762     if (pfl->bank_width == 1) {
763         pfl->cfi_table[0x2A] = 0x08;
764     } else {
765         pfl->cfi_table[0x2A] = 0x0B;
766     }
767     pfl->writeblock_size = 1 << pfl->cfi_table[0x2A];
768     if (!pfl->old_multiple_chip_handling && num_devices > 1) {
769         pfl->writeblock_size *= num_devices;
770     }
771 
772     pfl->cfi_table[0x2B] = 0x00;
773     /* Number of erase block regions (uniform) */
774     pfl->cfi_table[0x2C] = 0x01;
775     /* Erase block region 1 */
776     pfl->cfi_table[0x2D] = blocks_per_device - 1;
777     pfl->cfi_table[0x2E] = (blocks_per_device - 1) >> 8;
778     pfl->cfi_table[0x2F] = sector_len_per_device >> 8;
779     pfl->cfi_table[0x30] = sector_len_per_device >> 16;
780 
781     /* Extended */
782     pfl->cfi_table[0x31] = 'P';
783     pfl->cfi_table[0x32] = 'R';
784     pfl->cfi_table[0x33] = 'I';
785 
786     pfl->cfi_table[0x34] = '1';
787     pfl->cfi_table[0x35] = '0';
788 
789     pfl->cfi_table[0x36] = 0x00;
790     pfl->cfi_table[0x37] = 0x00;
791     pfl->cfi_table[0x38] = 0x00;
792     pfl->cfi_table[0x39] = 0x00;
793 
794     pfl->cfi_table[0x3a] = 0x00;
795 
796     pfl->cfi_table[0x3b] = 0x00;
797     pfl->cfi_table[0x3c] = 0x00;
798 
799     pfl->cfi_table[0x3f] = 0x01; /* Number of protection fields */
800 }
801 
802 static void pflash_cfi01_realize(DeviceState *dev, Error **errp)
803 {
804     ERRP_GUARD();
805     PFlashCFI01 *pfl = PFLASH_CFI01(dev);
806     uint64_t total_len;
807     int ret;
808 
809     if (pfl->sector_len == 0) {
810         error_setg(errp, "attribute \"sector-length\" not specified or zero.");
811         return;
812     }
813     if (pfl->nb_blocs == 0) {
814         error_setg(errp, "attribute \"num-blocks\" not specified or zero.");
815         return;
816     }
817     if (pfl->name == NULL) {
818         error_setg(errp, "attribute \"name\" not specified.");
819         return;
820     }
821 
822     total_len = pfl->sector_len * pfl->nb_blocs;
823 
824     memory_region_init_rom_device(
825         &pfl->mem, OBJECT(dev),
826         &pflash_cfi01_ops,
827         pfl,
828         pfl->name, total_len, errp);
829     if (*errp) {
830         return;
831     }
832 
833     pfl->storage = memory_region_get_ram_ptr(&pfl->mem);
834     sysbus_init_mmio(SYS_BUS_DEVICE(dev), &pfl->mem);
835 
836     if (pfl->blk) {
837         uint64_t perm;
838         pfl->ro = !blk_supports_write_perm(pfl->blk);
839         perm = BLK_PERM_CONSISTENT_READ | (pfl->ro ? 0 : BLK_PERM_WRITE);
840         ret = blk_set_perm(pfl->blk, perm, BLK_PERM_ALL, errp);
841         if (ret < 0) {
842             return;
843         }
844     } else {
845         pfl->ro = false;
846     }
847 
848     if (pfl->blk) {
849         if (!blk_check_size_and_read_all(pfl->blk, dev, pfl->storage,
850                                          total_len, errp)) {
851             vmstate_unregister_ram(&pfl->mem, DEVICE(pfl));
852             return;
853         }
854     }
855 
856     /*
857      * Default to devices being used at their maximum device width. This was
858      * assumed before the device_width support was added.
859      */
860     if (!pfl->max_device_width) {
861         pfl->max_device_width = pfl->device_width;
862     }
863 
864     pfl->wcycle = 0;
865     /*
866      * The command 0x00 is not assigned by the CFI open standard,
867      * but QEMU historically uses it for the READ_ARRAY command (0xff).
868      */
869     pfl->cmd = 0x00;
870     pfl->status = 0x80; /* WSM ready */
871     pflash_cfi01_fill_cfi_table(pfl);
872 
873     pfl->blk_bytes = g_malloc(pfl->writeblock_size);
874     pfl->blk_offset = -1;
875 }
876 
877 static void pflash_cfi01_system_reset(DeviceState *dev)
878 {
879     PFlashCFI01 *pfl = PFLASH_CFI01(dev);
880 
881     trace_pflash_reset(pfl->name);
882     /*
883      * The command 0x00 is not assigned by the CFI open standard,
884      * but QEMU historically uses it for the READ_ARRAY command (0xff).
885      */
886     pfl->cmd = 0x00;
887     pfl->wcycle = 0;
888     memory_region_rom_device_set_romd(&pfl->mem, true);
889     /*
890      * The WSM ready timer occurs at most 150ns after system reset.
891      * This model deliberately ignores this delay.
892      */
893     pfl->status = 0x80;
894 
895     pfl->blk_offset = -1;
896 }
897 
898 static Property pflash_cfi01_properties[] = {
899     DEFINE_PROP_DRIVE("drive", PFlashCFI01, blk),
900     /* num-blocks is the number of blocks actually visible to the guest,
901      * ie the total size of the device divided by the sector length.
902      * If we're emulating flash devices wired in parallel the actual
903      * number of blocks per individual device will differ.
904      */
905     DEFINE_PROP_UINT32("num-blocks", PFlashCFI01, nb_blocs, 0),
906     DEFINE_PROP_UINT64("sector-length", PFlashCFI01, sector_len, 0),
907     /* width here is the overall width of this QEMU device in bytes.
908      * The QEMU device may be emulating a number of flash devices
909      * wired up in parallel; the width of each individual flash
910      * device should be specified via device-width. If the individual
911      * devices have a maximum width which is greater than the width
912      * they are being used for, this maximum width should be set via
913      * max-device-width (which otherwise defaults to device-width).
914      * So for instance a 32-bit wide QEMU flash device made from four
915      * 16-bit flash devices used in 8-bit wide mode would be configured
916      * with width = 4, device-width = 1, max-device-width = 2.
917      *
918      * If device-width is not specified we default to backwards
919      * compatible behaviour which is a bad emulation of two
920      * 16 bit devices making up a 32 bit wide QEMU device. This
921      * is deprecated for new uses of this device.
922      */
923     DEFINE_PROP_UINT8("width", PFlashCFI01, bank_width, 0),
924     DEFINE_PROP_UINT8("device-width", PFlashCFI01, device_width, 0),
925     DEFINE_PROP_UINT8("max-device-width", PFlashCFI01, max_device_width, 0),
926     DEFINE_PROP_BIT("big-endian", PFlashCFI01, features, PFLASH_BE, 0),
927     DEFINE_PROP_BIT("secure", PFlashCFI01, features, PFLASH_SECURE, 0),
928     DEFINE_PROP_UINT16("id0", PFlashCFI01, ident0, 0),
929     DEFINE_PROP_UINT16("id1", PFlashCFI01, ident1, 0),
930     DEFINE_PROP_UINT16("id2", PFlashCFI01, ident2, 0),
931     DEFINE_PROP_UINT16("id3", PFlashCFI01, ident3, 0),
932     DEFINE_PROP_STRING("name", PFlashCFI01, name),
933     DEFINE_PROP_BOOL("old-multiple-chip-handling", PFlashCFI01,
934                      old_multiple_chip_handling, false),
935     DEFINE_PROP_END_OF_LIST(),
936 };
937 
938 static void pflash_cfi01_class_init(ObjectClass *klass, void *data)
939 {
940     DeviceClass *dc = DEVICE_CLASS(klass);
941 
942     dc->reset = pflash_cfi01_system_reset;
943     dc->realize = pflash_cfi01_realize;
944     device_class_set_props(dc, pflash_cfi01_properties);
945     dc->vmsd = &vmstate_pflash;
946     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
947 }
948 
949 
950 static const TypeInfo pflash_cfi01_info = {
951     .name           = TYPE_PFLASH_CFI01,
952     .parent         = TYPE_SYS_BUS_DEVICE,
953     .instance_size  = sizeof(PFlashCFI01),
954     .class_init     = pflash_cfi01_class_init,
955 };
956 
957 static void pflash_cfi01_register_types(void)
958 {
959     type_register_static(&pflash_cfi01_info);
960 }
961 
962 type_init(pflash_cfi01_register_types)
963 
964 PFlashCFI01 *pflash_cfi01_register(hwaddr base,
965                                    const char *name,
966                                    hwaddr size,
967                                    BlockBackend *blk,
968                                    uint32_t sector_len,
969                                    int bank_width,
970                                    uint16_t id0, uint16_t id1,
971                                    uint16_t id2, uint16_t id3,
972                                    int be)
973 {
974     DeviceState *dev = qdev_new(TYPE_PFLASH_CFI01);
975 
976     if (blk) {
977         qdev_prop_set_drive(dev, "drive", blk);
978     }
979     assert(QEMU_IS_ALIGNED(size, sector_len));
980     qdev_prop_set_uint32(dev, "num-blocks", size / sector_len);
981     qdev_prop_set_uint64(dev, "sector-length", sector_len);
982     qdev_prop_set_uint8(dev, "width", bank_width);
983     qdev_prop_set_bit(dev, "big-endian", !!be);
984     qdev_prop_set_uint16(dev, "id0", id0);
985     qdev_prop_set_uint16(dev, "id1", id1);
986     qdev_prop_set_uint16(dev, "id2", id2);
987     qdev_prop_set_uint16(dev, "id3", id3);
988     qdev_prop_set_string(dev, "name", name);
989     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
990 
991     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base);
992     return PFLASH_CFI01(dev);
993 }
994 
995 BlockBackend *pflash_cfi01_get_blk(PFlashCFI01 *fl)
996 {
997     return fl->blk;
998 }
999 
1000 MemoryRegion *pflash_cfi01_get_memory(PFlashCFI01 *fl)
1001 {
1002     return &fl->mem;
1003 }
1004 
1005 /*
1006  * Handle -drive if=pflash for machines that use properties.
1007  * If @dinfo is null, do nothing.
1008  * Else if @fl's property "drive" is already set, fatal error.
1009  * Else set it to the BlockBackend with @dinfo.
1010  */
1011 void pflash_cfi01_legacy_drive(PFlashCFI01 *fl, DriveInfo *dinfo)
1012 {
1013     Location loc;
1014 
1015     if (!dinfo) {
1016         return;
1017     }
1018 
1019     loc_push_none(&loc);
1020     qemu_opts_loc_restore(dinfo->opts);
1021     if (fl->blk) {
1022         error_report("clashes with -machine");
1023         exit(1);
1024     }
1025     qdev_prop_set_drive_err(DEVICE(fl), "drive", blk_by_legacy_dinfo(dinfo),
1026                             &error_fatal);
1027     loc_pop(&loc);
1028 }
1029 
1030 static void postload_update_cb(void *opaque, bool running, RunState state)
1031 {
1032     PFlashCFI01 *pfl = opaque;
1033 
1034     /* This is called after bdrv_activate_all.  */
1035     qemu_del_vm_change_state_handler(pfl->vmstate);
1036     pfl->vmstate = NULL;
1037 
1038     trace_pflash_postload_cb(pfl->name);
1039     pflash_update(pfl, 0, pfl->sector_len * pfl->nb_blocs);
1040 }
1041 
1042 static int pflash_post_load(void *opaque, int version_id)
1043 {
1044     PFlashCFI01 *pfl = opaque;
1045 
1046     if (!pfl->ro) {
1047         pfl->vmstate = qemu_add_vm_change_state_handler(postload_update_cb,
1048                                                         pfl);
1049     }
1050     return 0;
1051 }
1052