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