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