xref: /openbmc/qemu/hw/block/pflash_cfi02.c (revision 64c9a921)
1 /*
2  *  CFI parallel flash with AMD command set emulation
3  *
4  *  Copyright (c) 2005 Jocelyn Mayer
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 /*
21  * For now, this code can emulate flashes of 1, 2 or 4 bytes width.
22  * Supported commands/modes are:
23  * - flash read
24  * - flash write
25  * - flash ID read
26  * - sector erase
27  * - chip erase
28  * - unlock bypass command
29  * - CFI queries
30  *
31  * It does not support flash interleaving.
32  * It does not implement software data protection as found in many real chips
33  */
34 
35 #include "qemu/osdep.h"
36 #include "hw/block/block.h"
37 #include "hw/block/flash.h"
38 #include "hw/qdev-properties.h"
39 #include "hw/qdev-properties-system.h"
40 #include "qapi/error.h"
41 #include "qemu/error-report.h"
42 #include "qemu/bitmap.h"
43 #include "qemu/timer.h"
44 #include "sysemu/block-backend.h"
45 #include "qemu/host-utils.h"
46 #include "qemu/module.h"
47 #include "hw/sysbus.h"
48 #include "migration/vmstate.h"
49 #include "trace.h"
50 
51 #define PFLASH_DEBUG false
52 #define DPRINTF(fmt, ...)                                  \
53 do {                                                       \
54     if (PFLASH_DEBUG) {                                    \
55         fprintf(stderr, "PFLASH: " fmt, ## __VA_ARGS__);   \
56     }                                                      \
57 } while (0)
58 
59 #define PFLASH_LAZY_ROMD_THRESHOLD 42
60 
61 /*
62  * The size of the cfi_table indirectly depends on this and the start of the
63  * PRI table directly depends on it. 4 is the maximum size (and also what
64  * seems common) without changing the PRT table address.
65  */
66 #define PFLASH_MAX_ERASE_REGIONS 4
67 
68 /* Special write cycles for CFI queries. */
69 enum {
70     WCYCLE_CFI              = 7,
71     WCYCLE_AUTOSELECT_CFI   = 8,
72 };
73 
74 struct PFlashCFI02 {
75     /*< private >*/
76     SysBusDevice parent_obj;
77     /*< public >*/
78 
79     BlockBackend *blk;
80     uint32_t uniform_nb_blocs;
81     uint32_t uniform_sector_len;
82     uint32_t total_sectors;
83     uint32_t nb_blocs[PFLASH_MAX_ERASE_REGIONS];
84     uint32_t sector_len[PFLASH_MAX_ERASE_REGIONS];
85     uint32_t chip_len;
86     uint8_t mappings;
87     uint8_t width;
88     uint8_t be;
89     int wcycle; /* if 0, the flash is read normally */
90     int bypass;
91     int ro;
92     uint8_t cmd;
93     uint8_t status;
94     /* FIXME: implement array device properties */
95     uint16_t ident0;
96     uint16_t ident1;
97     uint16_t ident2;
98     uint16_t ident3;
99     uint16_t unlock_addr0;
100     uint16_t unlock_addr1;
101     uint8_t cfi_table[0x4d];
102     QEMUTimer timer;
103     /* The device replicates the flash memory across its memory space.  Emulate
104      * that by having a container (.mem) filled with an array of aliases
105      * (.mem_mappings) pointing to the flash memory (.orig_mem).
106      */
107     MemoryRegion mem;
108     MemoryRegion *mem_mappings;    /* array; one per mapping */
109     MemoryRegion orig_mem;
110     int rom_mode;
111     int read_counter; /* used for lazy switch-back to rom mode */
112     int sectors_to_erase;
113     uint64_t erase_time_remaining;
114     unsigned long *sector_erase_map;
115     char *name;
116     void *storage;
117 };
118 
119 /*
120  * Toggle status bit DQ7.
121  */
122 static inline void toggle_dq7(PFlashCFI02 *pfl)
123 {
124     pfl->status ^= 0x80;
125 }
126 
127 /*
128  * Set status bit DQ7 to bit 7 of value.
129  */
130 static inline void set_dq7(PFlashCFI02 *pfl, uint8_t value)
131 {
132     pfl->status &= 0x7F;
133     pfl->status |= value & 0x80;
134 }
135 
136 /*
137  * Toggle status bit DQ6.
138  */
139 static inline void toggle_dq6(PFlashCFI02 *pfl)
140 {
141     pfl->status ^= 0x40;
142 }
143 
144 /*
145  * Turn on DQ3.
146  */
147 static inline void assert_dq3(PFlashCFI02 *pfl)
148 {
149     pfl->status |= 0x08;
150 }
151 
152 /*
153  * Turn off DQ3.
154  */
155 static inline void reset_dq3(PFlashCFI02 *pfl)
156 {
157     pfl->status &= ~0x08;
158 }
159 
160 /*
161  * Toggle status bit DQ2.
162  */
163 static inline void toggle_dq2(PFlashCFI02 *pfl)
164 {
165     pfl->status ^= 0x04;
166 }
167 
168 /*
169  * Set up replicated mappings of the same region.
170  */
171 static void pflash_setup_mappings(PFlashCFI02 *pfl)
172 {
173     unsigned i;
174     hwaddr size = memory_region_size(&pfl->orig_mem);
175 
176     memory_region_init(&pfl->mem, OBJECT(pfl), "pflash", pfl->mappings * size);
177     pfl->mem_mappings = g_new(MemoryRegion, pfl->mappings);
178     for (i = 0; i < pfl->mappings; ++i) {
179         memory_region_init_alias(&pfl->mem_mappings[i], OBJECT(pfl),
180                                  "pflash-alias", &pfl->orig_mem, 0, size);
181         memory_region_add_subregion(&pfl->mem, i * size, &pfl->mem_mappings[i]);
182     }
183 }
184 
185 static void pflash_register_memory(PFlashCFI02 *pfl, int rom_mode)
186 {
187     memory_region_rom_device_set_romd(&pfl->orig_mem, rom_mode);
188     pfl->rom_mode = rom_mode;
189 }
190 
191 static size_t pflash_regions_count(PFlashCFI02 *pfl)
192 {
193     return pfl->cfi_table[0x2c];
194 }
195 
196 /*
197  * Returns the time it takes to erase the number of sectors scheduled for
198  * erasure based on CFI address 0x21 which is "Typical timeout per individual
199  * block erase 2^N ms."
200  */
201 static uint64_t pflash_erase_time(PFlashCFI02 *pfl)
202 {
203     /*
204      * If there are no sectors to erase (which can happen if all of the sectors
205      * to be erased are protected), then erase takes 100 us. Protected sectors
206      * aren't supported so this should never happen.
207      */
208     return ((1ULL << pfl->cfi_table[0x21]) * pfl->sectors_to_erase) * SCALE_US;
209 }
210 
211 /*
212  * Returns true if the device is currently in erase suspend mode.
213  */
214 static inline bool pflash_erase_suspend_mode(PFlashCFI02 *pfl)
215 {
216     return pfl->erase_time_remaining > 0;
217 }
218 
219 static void pflash_timer(void *opaque)
220 {
221     PFlashCFI02 *pfl = opaque;
222 
223     trace_pflash_timer_expired(pfl->cmd);
224     if (pfl->cmd == 0x30) {
225         /*
226          * Sector erase. If DQ3 is 0 when the timer expires, then the 50
227          * us erase timeout has expired so we need to start the timer for the
228          * sector erase algorithm. Otherwise, the erase completed and we should
229          * go back to read array mode.
230          */
231         if ((pfl->status & 0x08) == 0) {
232             assert_dq3(pfl);
233             uint64_t timeout = pflash_erase_time(pfl);
234             timer_mod(&pfl->timer,
235                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + timeout);
236             DPRINTF("%s: erase timeout fired; erasing %d sectors\n",
237                     __func__, pfl->sectors_to_erase);
238             return;
239         }
240         DPRINTF("%s: sector erase complete\n", __func__);
241         bitmap_zero(pfl->sector_erase_map, pfl->total_sectors);
242         pfl->sectors_to_erase = 0;
243         reset_dq3(pfl);
244     }
245 
246     /* Reset flash */
247     toggle_dq7(pfl);
248     if (pfl->bypass) {
249         pfl->wcycle = 2;
250     } else {
251         pflash_register_memory(pfl, 1);
252         pfl->wcycle = 0;
253     }
254     pfl->cmd = 0;
255 }
256 
257 /*
258  * Read data from flash.
259  */
260 static uint64_t pflash_data_read(PFlashCFI02 *pfl, hwaddr offset,
261                                  unsigned int width)
262 {
263     uint8_t *p = (uint8_t *)pfl->storage + offset;
264     uint64_t ret = pfl->be ? ldn_be_p(p, width) : ldn_le_p(p, width);
265     trace_pflash_data_read(offset, width, ret);
266     return ret;
267 }
268 
269 typedef struct {
270     uint32_t len;
271     uint32_t num;
272 } SectorInfo;
273 
274 /*
275  * offset should be a byte offset of the QEMU device and _not_ a device
276  * offset.
277  */
278 static SectorInfo pflash_sector_info(PFlashCFI02 *pfl, hwaddr offset)
279 {
280     assert(offset < pfl->chip_len);
281     hwaddr addr = 0;
282     uint32_t sector_num = 0;
283     for (int i = 0; i < pflash_regions_count(pfl); ++i) {
284         uint64_t region_size = (uint64_t)pfl->nb_blocs[i] * pfl->sector_len[i];
285         if (addr <= offset && offset < addr + region_size) {
286             return (SectorInfo) {
287                 .len = pfl->sector_len[i],
288                 .num = sector_num + (offset - addr) / pfl->sector_len[i],
289             };
290         }
291         sector_num += pfl->nb_blocs[i];
292         addr += region_size;
293     }
294     abort();
295 }
296 
297 /*
298  * Returns true if the offset refers to a flash sector that is currently being
299  * erased.
300  */
301 static bool pflash_sector_is_erasing(PFlashCFI02 *pfl, hwaddr offset)
302 {
303     long sector_num = pflash_sector_info(pfl, offset).num;
304     return test_bit(sector_num, pfl->sector_erase_map);
305 }
306 
307 static uint64_t pflash_read(void *opaque, hwaddr offset, unsigned int width)
308 {
309     PFlashCFI02 *pfl = opaque;
310     hwaddr boff;
311     uint64_t ret;
312 
313     /* Lazy reset to ROMD mode after a certain amount of read accesses */
314     if (!pfl->rom_mode && pfl->wcycle == 0 &&
315         ++pfl->read_counter > PFLASH_LAZY_ROMD_THRESHOLD) {
316         pflash_register_memory(pfl, 1);
317     }
318     offset &= pfl->chip_len - 1;
319     boff = offset & 0xFF;
320     if (pfl->width == 2) {
321         boff = boff >> 1;
322     } else if (pfl->width == 4) {
323         boff = boff >> 2;
324     }
325     switch (pfl->cmd) {
326     default:
327         /* This should never happen : reset state & treat it as a read*/
328         DPRINTF("%s: unknown command state: %x\n", __func__, pfl->cmd);
329         pfl->wcycle = 0;
330         pfl->cmd = 0;
331         /* fall through to the read code */
332     case 0x80: /* Erase (unlock) */
333         /* We accept reads during second unlock sequence... */
334     case 0x00:
335         if (pflash_erase_suspend_mode(pfl) &&
336             pflash_sector_is_erasing(pfl, offset)) {
337             /* Toggle bit 2, but not 6. */
338             toggle_dq2(pfl);
339             /* Status register read */
340             ret = pfl->status;
341             DPRINTF("%s: status %" PRIx64 "\n", __func__, ret);
342             break;
343         }
344         /* Flash area read */
345         ret = pflash_data_read(pfl, offset, width);
346         break;
347     case 0x90: /* flash ID read */
348         switch (boff) {
349         case 0x00:
350         case 0x01:
351             ret = boff & 0x01 ? pfl->ident1 : pfl->ident0;
352             break;
353         case 0x02:
354             ret = 0x00; /* Pretend all sectors are unprotected */
355             break;
356         case 0x0E:
357         case 0x0F:
358             ret = boff & 0x01 ? pfl->ident3 : pfl->ident2;
359             if (ret != (uint8_t)-1) {
360                 break;
361             }
362             /* Fall through to data read. */
363         default:
364             ret = pflash_data_read(pfl, offset, width);
365         }
366         DPRINTF("%s: ID " TARGET_FMT_plx " %" PRIx64 "\n", __func__, boff, ret);
367         break;
368     case 0x10: /* Chip Erase */
369     case 0x30: /* Sector Erase */
370         /* Toggle bit 2 during erase, but not program. */
371         toggle_dq2(pfl);
372         /* fall through */
373     case 0xA0: /* Program */
374         /* Toggle bit 6 */
375         toggle_dq6(pfl);
376         /* Status register read */
377         ret = pfl->status;
378         DPRINTF("%s: status %" PRIx64 "\n", __func__, ret);
379         break;
380     case 0x98:
381         /* CFI query mode */
382         if (boff < sizeof(pfl->cfi_table)) {
383             ret = pfl->cfi_table[boff];
384         } else {
385             ret = 0;
386         }
387         break;
388     }
389     trace_pflash_io_read(offset, width, ret, pfl->cmd, pfl->wcycle);
390 
391     return ret;
392 }
393 
394 /* update flash content on disk */
395 static void pflash_update(PFlashCFI02 *pfl, int offset, int size)
396 {
397     int offset_end;
398     int ret;
399     if (pfl->blk) {
400         offset_end = offset + size;
401         /* widen to sector boundaries */
402         offset = QEMU_ALIGN_DOWN(offset, BDRV_SECTOR_SIZE);
403         offset_end = QEMU_ALIGN_UP(offset_end, BDRV_SECTOR_SIZE);
404         ret = blk_pwrite(pfl->blk, offset, pfl->storage + offset,
405                    offset_end - offset, 0);
406         if (ret < 0) {
407             /* TODO set error bit in status */
408             error_report("Could not update PFLASH: %s", strerror(-ret));
409         }
410     }
411 }
412 
413 static void pflash_sector_erase(PFlashCFI02 *pfl, hwaddr offset)
414 {
415     SectorInfo sector_info = pflash_sector_info(pfl, offset);
416     uint64_t sector_len = sector_info.len;
417     offset &= ~(sector_len - 1);
418     DPRINTF("%s: start sector erase at %0*" PRIx64 "-%0*" PRIx64 "\n",
419             __func__, pfl->width * 2, offset,
420             pfl->width * 2, offset + sector_len - 1);
421     if (!pfl->ro) {
422         uint8_t *p = pfl->storage;
423         memset(p + offset, 0xff, sector_len);
424         pflash_update(pfl, offset, sector_len);
425     }
426     set_dq7(pfl, 0x00);
427     ++pfl->sectors_to_erase;
428     set_bit(sector_info.num, pfl->sector_erase_map);
429     /* Set (or reset) the 50 us timer for additional erase commands.  */
430     timer_mod(&pfl->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 50000);
431 }
432 
433 static void pflash_write(void *opaque, hwaddr offset, uint64_t value,
434                          unsigned int width)
435 {
436     PFlashCFI02 *pfl = opaque;
437     hwaddr boff;
438     uint8_t *p;
439     uint8_t cmd;
440 
441     trace_pflash_io_write(offset, width, value, pfl->wcycle);
442     cmd = value;
443     if (pfl->cmd != 0xA0) {
444         /* Reset does nothing during chip erase and sector erase. */
445         if (cmd == 0xF0 && pfl->cmd != 0x10 && pfl->cmd != 0x30) {
446             if (pfl->wcycle == WCYCLE_AUTOSELECT_CFI) {
447                 /* Return to autoselect mode. */
448                 pfl->wcycle = 3;
449                 pfl->cmd = 0x90;
450                 return;
451             }
452             goto reset_flash;
453         }
454     }
455     offset &= pfl->chip_len - 1;
456 
457     boff = offset;
458     if (pfl->width == 2) {
459         boff = boff >> 1;
460     } else if (pfl->width == 4) {
461         boff = boff >> 2;
462     }
463     /* Only the least-significant 11 bits are used in most cases. */
464     boff &= 0x7FF;
465     switch (pfl->wcycle) {
466     case 0:
467         /* Set the device in I/O access mode if required */
468         if (pfl->rom_mode)
469             pflash_register_memory(pfl, 0);
470         pfl->read_counter = 0;
471         /* We're in read mode */
472     check_unlock0:
473         if (boff == 0x55 && cmd == 0x98) {
474             /* Enter CFI query mode */
475             pfl->wcycle = WCYCLE_CFI;
476             pfl->cmd = 0x98;
477             return;
478         }
479         /* Handle erase resume in erase suspend mode, otherwise reset. */
480         if (cmd == 0x30) { /* Erase Resume */
481             if (pflash_erase_suspend_mode(pfl)) {
482                 /* Resume the erase. */
483                 timer_mod(&pfl->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
484                           pfl->erase_time_remaining);
485                 pfl->erase_time_remaining = 0;
486                 pfl->wcycle = 6;
487                 pfl->cmd = 0x30;
488                 set_dq7(pfl, 0x00);
489                 assert_dq3(pfl);
490                 return;
491             }
492             goto reset_flash;
493         }
494         /* Ignore erase suspend. */
495         if (cmd == 0xB0) { /* Erase Suspend */
496             return;
497         }
498         if (boff != pfl->unlock_addr0 || cmd != 0xAA) {
499             DPRINTF("%s: unlock0 failed " TARGET_FMT_plx " %02x %04x\n",
500                     __func__, boff, cmd, pfl->unlock_addr0);
501             goto reset_flash;
502         }
503         DPRINTF("%s: unlock sequence started\n", __func__);
504         break;
505     case 1:
506         /* We started an unlock sequence */
507     check_unlock1:
508         if (boff != pfl->unlock_addr1 || cmd != 0x55) {
509             DPRINTF("%s: unlock1 failed " TARGET_FMT_plx " %02x\n", __func__,
510                     boff, cmd);
511             goto reset_flash;
512         }
513         DPRINTF("%s: unlock sequence done\n", __func__);
514         break;
515     case 2:
516         /* We finished an unlock sequence */
517         if (!pfl->bypass && boff != pfl->unlock_addr0) {
518             DPRINTF("%s: command failed " TARGET_FMT_plx " %02x\n", __func__,
519                     boff, cmd);
520             goto reset_flash;
521         }
522         switch (cmd) {
523         case 0x20:
524             pfl->bypass = 1;
525             goto do_bypass;
526         case 0x80: /* Erase */
527         case 0x90: /* Autoselect */
528         case 0xA0: /* Program */
529             pfl->cmd = cmd;
530             DPRINTF("%s: starting command %02x\n", __func__, cmd);
531             break;
532         default:
533             DPRINTF("%s: unknown command %02x\n", __func__, cmd);
534             goto reset_flash;
535         }
536         break;
537     case 3:
538         switch (pfl->cmd) {
539         case 0x80: /* Erase */
540             /* We need another unlock sequence */
541             goto check_unlock0;
542         case 0xA0: /* Program */
543             if (pflash_erase_suspend_mode(pfl) &&
544                 pflash_sector_is_erasing(pfl, offset)) {
545                 /* Ignore writes to erasing sectors. */
546                 if (pfl->bypass) {
547                     goto do_bypass;
548                 }
549                 goto reset_flash;
550             }
551             trace_pflash_data_write(offset, width, value, 0);
552             if (!pfl->ro) {
553                 p = (uint8_t *)pfl->storage + offset;
554                 if (pfl->be) {
555                     uint64_t current = ldn_be_p(p, width);
556                     stn_be_p(p, width, current & value);
557                 } else {
558                     uint64_t current = ldn_le_p(p, width);
559                     stn_le_p(p, width, current & value);
560                 }
561                 pflash_update(pfl, offset, width);
562             }
563             /*
564              * While programming, status bit DQ7 should hold the opposite
565              * value from how it was programmed.
566              */
567             set_dq7(pfl, ~value);
568             /* Let's pretend write is immediate */
569             if (pfl->bypass)
570                 goto do_bypass;
571             goto reset_flash;
572         case 0x90: /* Autoselect */
573             if (pfl->bypass && cmd == 0x00) {
574                 /* Unlock bypass reset */
575                 goto reset_flash;
576             }
577             /*
578              * We can enter CFI query mode from autoselect mode, but we must
579              * return to autoselect mode after a reset.
580              */
581             if (boff == 0x55 && cmd == 0x98) {
582                 /* Enter autoselect CFI query mode */
583                 pfl->wcycle = WCYCLE_AUTOSELECT_CFI;
584                 pfl->cmd = 0x98;
585                 return;
586             }
587             /* fall through */
588         default:
589             DPRINTF("%s: invalid write for command %02x\n",
590                     __func__, pfl->cmd);
591             goto reset_flash;
592         }
593     case 4:
594         switch (pfl->cmd) {
595         case 0xA0: /* Program */
596             /* Ignore writes while flash data write is occurring */
597             /* As we suppose write is immediate, this should never happen */
598             return;
599         case 0x80: /* Erase */
600             goto check_unlock1;
601         default:
602             /* Should never happen */
603             DPRINTF("%s: invalid command state %02x (wc 4)\n",
604                     __func__, pfl->cmd);
605             goto reset_flash;
606         }
607         break;
608     case 5:
609         if (pflash_erase_suspend_mode(pfl)) {
610             /* Erasing is not supported in erase suspend mode. */
611             goto reset_flash;
612         }
613         switch (cmd) {
614         case 0x10: /* Chip Erase */
615             if (boff != pfl->unlock_addr0) {
616                 DPRINTF("%s: chip erase: invalid address " TARGET_FMT_plx "\n",
617                         __func__, offset);
618                 goto reset_flash;
619             }
620             /* Chip erase */
621             DPRINTF("%s: start chip erase\n", __func__);
622             if (!pfl->ro) {
623                 memset(pfl->storage, 0xff, pfl->chip_len);
624                 pflash_update(pfl, 0, pfl->chip_len);
625             }
626             set_dq7(pfl, 0x00);
627             /* Wait the time specified at CFI address 0x22. */
628             timer_mod(&pfl->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
629                       (1ULL << pfl->cfi_table[0x22]) * SCALE_MS);
630             break;
631         case 0x30: /* Sector erase */
632             pflash_sector_erase(pfl, offset);
633             break;
634         default:
635             DPRINTF("%s: invalid command %02x (wc 5)\n", __func__, cmd);
636             goto reset_flash;
637         }
638         pfl->cmd = cmd;
639         break;
640     case 6:
641         switch (pfl->cmd) {
642         case 0x10: /* Chip Erase */
643             /* Ignore writes during chip erase */
644             return;
645         case 0x30: /* Sector erase */
646             if (cmd == 0xB0) {
647                 /*
648                  * If erase suspend happens during the erase timeout (so DQ3 is
649                  * 0), then the device suspends erasing immediately. Set the
650                  * remaining time to be the total time to erase. Otherwise,
651                  * there is a maximum amount of time it can take to enter
652                  * suspend mode. Let's ignore that and suspend immediately and
653                  * set the remaining time to the actual time remaining on the
654                  * timer.
655                  */
656                 if ((pfl->status & 0x08) == 0) {
657                     pfl->erase_time_remaining = pflash_erase_time(pfl);
658                 } else {
659                     int64_t delta = timer_expire_time_ns(&pfl->timer) -
660                         qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
661                     /* Make sure we have a positive time remaining. */
662                     pfl->erase_time_remaining = delta <= 0 ? 1 : delta;
663                 }
664                 reset_dq3(pfl);
665                 timer_del(&pfl->timer);
666                 pfl->wcycle = 0;
667                 pfl->cmd = 0;
668                 return;
669             }
670             /*
671              * If DQ3 is 0, additional sector erase commands can be
672              * written and anything else (other than an erase suspend) resets
673              * the device.
674              */
675             if ((pfl->status & 0x08) == 0) {
676                 if (cmd == 0x30) {
677                     pflash_sector_erase(pfl, offset);
678                 } else {
679                     goto reset_flash;
680                 }
681             }
682             /* Ignore writes during the actual erase. */
683             return;
684         default:
685             /* Should never happen */
686             DPRINTF("%s: invalid command state %02x (wc 6)\n",
687                     __func__, pfl->cmd);
688             goto reset_flash;
689         }
690         break;
691     /* Special values for CFI queries */
692     case WCYCLE_CFI:
693     case WCYCLE_AUTOSELECT_CFI:
694         DPRINTF("%s: invalid write in CFI query mode\n", __func__);
695         goto reset_flash;
696     default:
697         /* Should never happen */
698         DPRINTF("%s: invalid write state (wc 7)\n",  __func__);
699         goto reset_flash;
700     }
701     pfl->wcycle++;
702 
703     return;
704 
705     /* Reset flash */
706  reset_flash:
707     trace_pflash_reset();
708     pfl->bypass = 0;
709     pfl->wcycle = 0;
710     pfl->cmd = 0;
711     return;
712 
713  do_bypass:
714     pfl->wcycle = 2;
715     pfl->cmd = 0;
716 }
717 
718 static const MemoryRegionOps pflash_cfi02_ops = {
719     .read = pflash_read,
720     .write = pflash_write,
721     .valid.min_access_size = 1,
722     .valid.max_access_size = 4,
723     .endianness = DEVICE_NATIVE_ENDIAN,
724 };
725 
726 static void pflash_cfi02_realize(DeviceState *dev, Error **errp)
727 {
728     ERRP_GUARD();
729     PFlashCFI02 *pfl = PFLASH_CFI02(dev);
730     int ret;
731 
732     if (pfl->uniform_sector_len == 0 && pfl->sector_len[0] == 0) {
733         error_setg(errp, "attribute \"sector-length\" not specified or zero.");
734         return;
735     }
736     if (pfl->uniform_nb_blocs == 0 && pfl->nb_blocs[0] == 0) {
737         error_setg(errp, "attribute \"num-blocks\" not specified or zero.");
738         return;
739     }
740     if (pfl->name == NULL) {
741         error_setg(errp, "attribute \"name\" not specified.");
742         return;
743     }
744 
745     int nb_regions;
746     pfl->chip_len = 0;
747     pfl->total_sectors = 0;
748     for (nb_regions = 0; nb_regions < PFLASH_MAX_ERASE_REGIONS; ++nb_regions) {
749         if (pfl->nb_blocs[nb_regions] == 0) {
750             break;
751         }
752         pfl->total_sectors += pfl->nb_blocs[nb_regions];
753         uint64_t sector_len_per_device = pfl->sector_len[nb_regions];
754 
755         /*
756          * The size of each flash sector must be a power of 2 and it must be
757          * aligned at the same power of 2.
758          */
759         if (sector_len_per_device & 0xff ||
760             sector_len_per_device >= (1 << 24) ||
761             !is_power_of_2(sector_len_per_device))
762         {
763             error_setg(errp, "unsupported configuration: "
764                        "sector length[%d] per device = %" PRIx64 ".",
765                        nb_regions, sector_len_per_device);
766             return;
767         }
768         if (pfl->chip_len & (sector_len_per_device - 1)) {
769             error_setg(errp, "unsupported configuration: "
770                        "flash region %d not correctly aligned.",
771                        nb_regions);
772             return;
773         }
774 
775         pfl->chip_len += (uint64_t)pfl->sector_len[nb_regions] *
776                           pfl->nb_blocs[nb_regions];
777     }
778 
779     uint64_t uniform_len = (uint64_t)pfl->uniform_nb_blocs *
780                            pfl->uniform_sector_len;
781     if (nb_regions == 0) {
782         nb_regions = 1;
783         pfl->nb_blocs[0] = pfl->uniform_nb_blocs;
784         pfl->sector_len[0] = pfl->uniform_sector_len;
785         pfl->chip_len = uniform_len;
786         pfl->total_sectors = pfl->uniform_nb_blocs;
787     } else if (uniform_len != 0 && uniform_len != pfl->chip_len) {
788         error_setg(errp, "\"num-blocks\"*\"sector-length\" "
789                    "different from \"num-blocks0\"*\'sector-length0\" + ... + "
790                    "\"num-blocks3\"*\"sector-length3\"");
791         return;
792     }
793 
794     memory_region_init_rom_device(&pfl->orig_mem, OBJECT(pfl),
795                                   &pflash_cfi02_ops, pfl, pfl->name,
796                                   pfl->chip_len, errp);
797     if (*errp) {
798         return;
799     }
800 
801     pfl->storage = memory_region_get_ram_ptr(&pfl->orig_mem);
802 
803     if (pfl->blk) {
804         uint64_t perm;
805         pfl->ro = !blk_supports_write_perm(pfl->blk);
806         perm = BLK_PERM_CONSISTENT_READ | (pfl->ro ? 0 : BLK_PERM_WRITE);
807         ret = blk_set_perm(pfl->blk, perm, BLK_PERM_ALL, errp);
808         if (ret < 0) {
809             return;
810         }
811     } else {
812         pfl->ro = 0;
813     }
814 
815     if (pfl->blk) {
816         if (!blk_check_size_and_read_all(pfl->blk, pfl->storage,
817                                          pfl->chip_len, errp)) {
818             vmstate_unregister_ram(&pfl->orig_mem, DEVICE(pfl));
819             return;
820         }
821     }
822 
823     /* Only 11 bits are used in the comparison. */
824     pfl->unlock_addr0 &= 0x7FF;
825     pfl->unlock_addr1 &= 0x7FF;
826 
827     /* Allocate memory for a bitmap for sectors being erased. */
828     pfl->sector_erase_map = bitmap_new(pfl->total_sectors);
829 
830     pflash_setup_mappings(pfl);
831     pfl->rom_mode = 1;
832     sysbus_init_mmio(SYS_BUS_DEVICE(dev), &pfl->mem);
833 
834     timer_init_ns(&pfl->timer, QEMU_CLOCK_VIRTUAL, pflash_timer, pfl);
835     pfl->wcycle = 0;
836     pfl->cmd = 0;
837     pfl->status = 0;
838 
839     /* Hardcoded CFI table (mostly from SG29 Spansion flash) */
840     const uint16_t pri_ofs = 0x40;
841     /* Standard "QRY" string */
842     pfl->cfi_table[0x10] = 'Q';
843     pfl->cfi_table[0x11] = 'R';
844     pfl->cfi_table[0x12] = 'Y';
845     /* Command set (AMD/Fujitsu) */
846     pfl->cfi_table[0x13] = 0x02;
847     pfl->cfi_table[0x14] = 0x00;
848     /* Primary extended table address */
849     pfl->cfi_table[0x15] = pri_ofs;
850     pfl->cfi_table[0x16] = pri_ofs >> 8;
851     /* Alternate command set (none) */
852     pfl->cfi_table[0x17] = 0x00;
853     pfl->cfi_table[0x18] = 0x00;
854     /* Alternate extended table (none) */
855     pfl->cfi_table[0x19] = 0x00;
856     pfl->cfi_table[0x1A] = 0x00;
857     /* Vcc min */
858     pfl->cfi_table[0x1B] = 0x27;
859     /* Vcc max */
860     pfl->cfi_table[0x1C] = 0x36;
861     /* Vpp min (no Vpp pin) */
862     pfl->cfi_table[0x1D] = 0x00;
863     /* Vpp max (no Vpp pin) */
864     pfl->cfi_table[0x1E] = 0x00;
865     /* Timeout per single byte/word write (128 ms) */
866     pfl->cfi_table[0x1F] = 0x07;
867     /* Timeout for min size buffer write (NA) */
868     pfl->cfi_table[0x20] = 0x00;
869     /* Typical timeout for block erase (512 ms) */
870     pfl->cfi_table[0x21] = 0x09;
871     /* Typical timeout for full chip erase (4096 ms) */
872     pfl->cfi_table[0x22] = 0x0C;
873     /* Reserved */
874     pfl->cfi_table[0x23] = 0x01;
875     /* Max timeout for buffer write (NA) */
876     pfl->cfi_table[0x24] = 0x00;
877     /* Max timeout for block erase */
878     pfl->cfi_table[0x25] = 0x0A;
879     /* Max timeout for chip erase */
880     pfl->cfi_table[0x26] = 0x0D;
881     /* Device size */
882     pfl->cfi_table[0x27] = ctz32(pfl->chip_len);
883     /* Flash device interface (8 & 16 bits) */
884     pfl->cfi_table[0x28] = 0x02;
885     pfl->cfi_table[0x29] = 0x00;
886     /* Max number of bytes in multi-bytes write */
887     /* XXX: disable buffered write as it's not supported */
888     //    pfl->cfi_table[0x2A] = 0x05;
889     pfl->cfi_table[0x2A] = 0x00;
890     pfl->cfi_table[0x2B] = 0x00;
891     /* Number of erase block regions */
892     pfl->cfi_table[0x2c] = nb_regions;
893     /* Erase block regions */
894     for (int i = 0; i < nb_regions; ++i) {
895         uint32_t sector_len_per_device = pfl->sector_len[i];
896         pfl->cfi_table[0x2d + 4 * i] = pfl->nb_blocs[i] - 1;
897         pfl->cfi_table[0x2e + 4 * i] = (pfl->nb_blocs[i] - 1) >> 8;
898         pfl->cfi_table[0x2f + 4 * i] = sector_len_per_device >> 8;
899         pfl->cfi_table[0x30 + 4 * i] = sector_len_per_device >> 16;
900     }
901     assert(0x2c + 4 * nb_regions < pri_ofs);
902 
903     /* Extended */
904     pfl->cfi_table[0x00 + pri_ofs] = 'P';
905     pfl->cfi_table[0x01 + pri_ofs] = 'R';
906     pfl->cfi_table[0x02 + pri_ofs] = 'I';
907 
908     /* Extended version 1.0 */
909     pfl->cfi_table[0x03 + pri_ofs] = '1';
910     pfl->cfi_table[0x04 + pri_ofs] = '0';
911 
912     /* Address sensitive unlock required. */
913     pfl->cfi_table[0x05 + pri_ofs] = 0x00;
914     /* Erase suspend to read/write. */
915     pfl->cfi_table[0x06 + pri_ofs] = 0x02;
916     /* Sector protect not supported. */
917     pfl->cfi_table[0x07 + pri_ofs] = 0x00;
918     /* Temporary sector unprotect not supported. */
919     pfl->cfi_table[0x08 + pri_ofs] = 0x00;
920 
921     /* Sector protect/unprotect scheme. */
922     pfl->cfi_table[0x09 + pri_ofs] = 0x00;
923 
924     /* Simultaneous operation not supported. */
925     pfl->cfi_table[0x0a + pri_ofs] = 0x00;
926     /* Burst mode not supported. */
927     pfl->cfi_table[0x0b + pri_ofs] = 0x00;
928     /* Page mode not supported. */
929     pfl->cfi_table[0x0c + pri_ofs] = 0x00;
930     assert(0x0c + pri_ofs < ARRAY_SIZE(pfl->cfi_table));
931 }
932 
933 static Property pflash_cfi02_properties[] = {
934     DEFINE_PROP_DRIVE("drive", PFlashCFI02, blk),
935     DEFINE_PROP_UINT32("num-blocks", PFlashCFI02, uniform_nb_blocs, 0),
936     DEFINE_PROP_UINT32("sector-length", PFlashCFI02, uniform_sector_len, 0),
937     DEFINE_PROP_UINT32("num-blocks0", PFlashCFI02, nb_blocs[0], 0),
938     DEFINE_PROP_UINT32("sector-length0", PFlashCFI02, sector_len[0], 0),
939     DEFINE_PROP_UINT32("num-blocks1", PFlashCFI02, nb_blocs[1], 0),
940     DEFINE_PROP_UINT32("sector-length1", PFlashCFI02, sector_len[1], 0),
941     DEFINE_PROP_UINT32("num-blocks2", PFlashCFI02, nb_blocs[2], 0),
942     DEFINE_PROP_UINT32("sector-length2", PFlashCFI02, sector_len[2], 0),
943     DEFINE_PROP_UINT32("num-blocks3", PFlashCFI02, nb_blocs[3], 0),
944     DEFINE_PROP_UINT32("sector-length3", PFlashCFI02, sector_len[3], 0),
945     DEFINE_PROP_UINT8("width", PFlashCFI02, width, 0),
946     DEFINE_PROP_UINT8("mappings", PFlashCFI02, mappings, 0),
947     DEFINE_PROP_UINT8("big-endian", PFlashCFI02, be, 0),
948     DEFINE_PROP_UINT16("id0", PFlashCFI02, ident0, 0),
949     DEFINE_PROP_UINT16("id1", PFlashCFI02, ident1, 0),
950     DEFINE_PROP_UINT16("id2", PFlashCFI02, ident2, 0),
951     DEFINE_PROP_UINT16("id3", PFlashCFI02, ident3, 0),
952     DEFINE_PROP_UINT16("unlock-addr0", PFlashCFI02, unlock_addr0, 0),
953     DEFINE_PROP_UINT16("unlock-addr1", PFlashCFI02, unlock_addr1, 0),
954     DEFINE_PROP_STRING("name", PFlashCFI02, name),
955     DEFINE_PROP_END_OF_LIST(),
956 };
957 
958 static void pflash_cfi02_unrealize(DeviceState *dev)
959 {
960     PFlashCFI02 *pfl = PFLASH_CFI02(dev);
961     timer_del(&pfl->timer);
962     g_free(pfl->sector_erase_map);
963 }
964 
965 static void pflash_cfi02_class_init(ObjectClass *klass, void *data)
966 {
967     DeviceClass *dc = DEVICE_CLASS(klass);
968 
969     dc->realize = pflash_cfi02_realize;
970     dc->unrealize = pflash_cfi02_unrealize;
971     device_class_set_props(dc, pflash_cfi02_properties);
972     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
973 }
974 
975 static const TypeInfo pflash_cfi02_info = {
976     .name           = TYPE_PFLASH_CFI02,
977     .parent         = TYPE_SYS_BUS_DEVICE,
978     .instance_size  = sizeof(PFlashCFI02),
979     .class_init     = pflash_cfi02_class_init,
980 };
981 
982 static void pflash_cfi02_register_types(void)
983 {
984     type_register_static(&pflash_cfi02_info);
985 }
986 
987 type_init(pflash_cfi02_register_types)
988 
989 PFlashCFI02 *pflash_cfi02_register(hwaddr base,
990                                    const char *name,
991                                    hwaddr size,
992                                    BlockBackend *blk,
993                                    uint32_t sector_len,
994                                    int nb_mappings, int width,
995                                    uint16_t id0, uint16_t id1,
996                                    uint16_t id2, uint16_t id3,
997                                    uint16_t unlock_addr0,
998                                    uint16_t unlock_addr1,
999                                    int be)
1000 {
1001     DeviceState *dev = qdev_new(TYPE_PFLASH_CFI02);
1002 
1003     if (blk) {
1004         qdev_prop_set_drive(dev, "drive", blk);
1005     }
1006     assert(QEMU_IS_ALIGNED(size, sector_len));
1007     qdev_prop_set_uint32(dev, "num-blocks", size / sector_len);
1008     qdev_prop_set_uint32(dev, "sector-length", sector_len);
1009     qdev_prop_set_uint8(dev, "width", width);
1010     qdev_prop_set_uint8(dev, "mappings", nb_mappings);
1011     qdev_prop_set_uint8(dev, "big-endian", !!be);
1012     qdev_prop_set_uint16(dev, "id0", id0);
1013     qdev_prop_set_uint16(dev, "id1", id1);
1014     qdev_prop_set_uint16(dev, "id2", id2);
1015     qdev_prop_set_uint16(dev, "id3", id3);
1016     qdev_prop_set_uint16(dev, "unlock-addr0", unlock_addr0);
1017     qdev_prop_set_uint16(dev, "unlock-addr1", unlock_addr1);
1018     qdev_prop_set_string(dev, "name", name);
1019     sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
1020 
1021     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base);
1022     return PFLASH_CFI02(dev);
1023 }
1024