]> git.sur5r.net Git - u-boot/blob - drivers/mtd/spi/spi_flash.c
sf: Simplify lock ops detection code
[u-boot] / drivers / mtd / spi / spi_flash.c
1 /*
2  * SPI Flash Core
3  *
4  * Copyright (C) 2015 Jagan Teki <jteki@openedev.com>
5  * Copyright (C) 2013 Jagannadha Sutradharudu Teki, Xilinx Inc.
6  * Copyright (C) 2010 Reinhard Meyer, EMK Elektronik
7  * Copyright (C) 2008 Atmel Corporation
8  *
9  * SPDX-License-Identifier:     GPL-2.0+
10  */
11
12 #include <common.h>
13 #include <errno.h>
14 #include <malloc.h>
15 #include <mapmem.h>
16 #include <spi.h>
17 #include <spi_flash.h>
18 #include <linux/log2.h>
19 #include <dma.h>
20
21 #include "sf_internal.h"
22
23 DECLARE_GLOBAL_DATA_PTR;
24
25 static void spi_flash_addr(u32 addr, u8 *cmd)
26 {
27         /* cmd[0] is actual command */
28         cmd[1] = addr >> 16;
29         cmd[2] = addr >> 8;
30         cmd[3] = addr >> 0;
31 }
32
33 static int read_sr(struct spi_flash *flash, u8 *rs)
34 {
35         int ret;
36         u8 cmd;
37
38         cmd = CMD_READ_STATUS;
39         ret = spi_flash_read_common(flash, &cmd, 1, rs, 1);
40         if (ret < 0) {
41                 debug("SF: fail to read status register\n");
42                 return ret;
43         }
44
45         return 0;
46 }
47
48 static int read_fsr(struct spi_flash *flash, u8 *fsr)
49 {
50         int ret;
51         const u8 cmd = CMD_FLAG_STATUS;
52
53         ret = spi_flash_read_common(flash, &cmd, 1, fsr, 1);
54         if (ret < 0) {
55                 debug("SF: fail to read flag status register\n");
56                 return ret;
57         }
58
59         return 0;
60 }
61
62 static int write_sr(struct spi_flash *flash, u8 ws)
63 {
64         u8 cmd;
65         int ret;
66
67         cmd = CMD_WRITE_STATUS;
68         ret = spi_flash_write_common(flash, &cmd, 1, &ws, 1);
69         if (ret < 0) {
70                 debug("SF: fail to write status register\n");
71                 return ret;
72         }
73
74         return 0;
75 }
76
77 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
78 static int read_cr(struct spi_flash *flash, u8 *rc)
79 {
80         int ret;
81         u8 cmd;
82
83         cmd = CMD_READ_CONFIG;
84         ret = spi_flash_read_common(flash, &cmd, 1, rc, 1);
85         if (ret < 0) {
86                 debug("SF: fail to read config register\n");
87                 return ret;
88         }
89
90         return 0;
91 }
92
93 static int write_cr(struct spi_flash *flash, u8 wc)
94 {
95         u8 data[2];
96         u8 cmd;
97         int ret;
98
99         ret = read_sr(flash, &data[0]);
100         if (ret < 0)
101                 return ret;
102
103         cmd = CMD_WRITE_STATUS;
104         data[1] = wc;
105         ret = spi_flash_write_common(flash, &cmd, 1, &data, 2);
106         if (ret) {
107                 debug("SF: fail to write config register\n");
108                 return ret;
109         }
110
111         return 0;
112 }
113 #endif
114
115 #ifdef CONFIG_SPI_FLASH_STMICRO
116 static int read_evcr(struct spi_flash *flash, u8 *evcr)
117 {
118         int ret;
119         const u8 cmd = CMD_READ_EVCR;
120
121         ret = spi_flash_read_common(flash, &cmd, 1, evcr, 1);
122         if (ret < 0) {
123                 debug("SF: error reading EVCR\n");
124                 return ret;
125         }
126
127         return 0;
128 }
129
130 static int write_evcr(struct spi_flash *flash, u8 evcr)
131 {
132         u8 cmd;
133         int ret;
134
135         cmd = CMD_WRITE_EVCR;
136         ret = spi_flash_write_common(flash, &cmd, 1, &evcr, 1);
137         if (ret < 0) {
138                 debug("SF: error while writing EVCR register\n");
139                 return ret;
140         }
141
142         return 0;
143 }
144 #endif
145
146 #ifdef CONFIG_SPI_FLASH_BAR
147 static int spi_flash_write_bar(struct spi_flash *flash, u32 offset)
148 {
149         u8 cmd, bank_sel;
150         int ret;
151
152         bank_sel = offset / (SPI_FLASH_16MB_BOUN << flash->shift);
153         if (bank_sel == flash->bank_curr)
154                 goto bar_end;
155
156         cmd = flash->bank_write_cmd;
157         ret = spi_flash_write_common(flash, &cmd, 1, &bank_sel, 1);
158         if (ret < 0) {
159                 debug("SF: fail to write bank register\n");
160                 return ret;
161         }
162
163 bar_end:
164         flash->bank_curr = bank_sel;
165         return flash->bank_curr;
166 }
167
168 static int spi_flash_read_bar(struct spi_flash *flash,
169                               const struct spi_flash_info *info)
170 {
171         u8 curr_bank = 0;
172         int ret;
173
174         if (flash->size <= SPI_FLASH_16MB_BOUN)
175                 goto bar_end;
176
177         switch (JEDEC_MFR(info)) {
178         case SPI_FLASH_CFI_MFR_SPANSION:
179                 flash->bank_read_cmd = CMD_BANKADDR_BRRD;
180                 flash->bank_write_cmd = CMD_BANKADDR_BRWR;
181                 break;
182         default:
183                 flash->bank_read_cmd = CMD_EXTNADDR_RDEAR;
184                 flash->bank_write_cmd = CMD_EXTNADDR_WREAR;
185         }
186
187         ret = spi_flash_read_common(flash, &flash->bank_read_cmd, 1,
188                                     &curr_bank, 1);
189         if (ret) {
190                 debug("SF: fail to read bank addr register\n");
191                 return ret;
192         }
193
194 bar_end:
195         flash->bank_curr = curr_bank;
196         return 0;
197 }
198 #endif
199
200 #ifdef CONFIG_SF_DUAL_FLASH
201 static void spi_flash_dual(struct spi_flash *flash, u32 *addr)
202 {
203         struct spi_slave *spi = flash->spi;
204
205         switch (flash->dual_flash) {
206         case SF_DUAL_STACKED_FLASH:
207                 if (*addr >= (flash->size >> 1)) {
208                         *addr -= flash->size >> 1;
209                         spi->flags |= SPI_XFER_U_PAGE;
210                 } else {
211                         spi->flags &= ~SPI_XFER_U_PAGE;
212                 }
213                 break;
214         case SF_DUAL_PARALLEL_FLASH:
215                 *addr >>= flash->shift;
216                 break;
217         default:
218                 debug("SF: Unsupported dual_flash=%d\n", flash->dual_flash);
219                 break;
220         }
221 }
222 #endif
223
224 static int spi_flash_sr_ready(struct spi_flash *flash)
225 {
226         u8 sr;
227         int ret;
228
229         ret = read_sr(flash, &sr);
230         if (ret < 0)
231                 return ret;
232
233         return !(sr & STATUS_WIP);
234 }
235
236 static int spi_flash_fsr_ready(struct spi_flash *flash)
237 {
238         u8 fsr;
239         int ret;
240
241         ret = read_fsr(flash, &fsr);
242         if (ret < 0)
243                 return ret;
244
245         return fsr & STATUS_PEC;
246 }
247
248 static int spi_flash_ready(struct spi_flash *flash)
249 {
250         int sr, fsr;
251
252         sr = spi_flash_sr_ready(flash);
253         if (sr < 0)
254                 return sr;
255
256         fsr = 1;
257         if (flash->flags & SNOR_F_USE_FSR) {
258                 fsr = spi_flash_fsr_ready(flash);
259                 if (fsr < 0)
260                         return fsr;
261         }
262
263         return sr && fsr;
264 }
265
266 static int spi_flash_cmd_wait_ready(struct spi_flash *flash,
267                                         unsigned long timeout)
268 {
269         unsigned long timebase;
270         int ret;
271
272         timebase = get_timer(0);
273
274         while (get_timer(timebase) < timeout) {
275                 ret = spi_flash_ready(flash);
276                 if (ret < 0)
277                         return ret;
278                 if (ret)
279                         return 0;
280         }
281
282         printf("SF: Timeout!\n");
283
284         return -ETIMEDOUT;
285 }
286
287 int spi_flash_write_common(struct spi_flash *flash, const u8 *cmd,
288                 size_t cmd_len, const void *buf, size_t buf_len)
289 {
290         struct spi_slave *spi = flash->spi;
291         unsigned long timeout = SPI_FLASH_PROG_TIMEOUT;
292         int ret;
293
294         if (buf == NULL)
295                 timeout = SPI_FLASH_PAGE_ERASE_TIMEOUT;
296
297         ret = spi_claim_bus(spi);
298         if (ret) {
299                 debug("SF: unable to claim SPI bus\n");
300                 return ret;
301         }
302
303         ret = spi_flash_cmd_write_enable(flash);
304         if (ret < 0) {
305                 debug("SF: enabling write failed\n");
306                 return ret;
307         }
308
309         ret = spi_flash_cmd_write(spi, cmd, cmd_len, buf, buf_len);
310         if (ret < 0) {
311                 debug("SF: write cmd failed\n");
312                 return ret;
313         }
314
315         ret = spi_flash_cmd_wait_ready(flash, timeout);
316         if (ret < 0) {
317                 debug("SF: write %s timed out\n",
318                       timeout == SPI_FLASH_PROG_TIMEOUT ?
319                         "program" : "page erase");
320                 return ret;
321         }
322
323         spi_release_bus(spi);
324
325         return ret;
326 }
327
328 int spi_flash_cmd_erase_ops(struct spi_flash *flash, u32 offset, size_t len)
329 {
330         u32 erase_size, erase_addr;
331         u8 cmd[SPI_FLASH_CMD_LEN];
332         int ret = -1;
333
334         erase_size = flash->erase_size;
335         if (offset % erase_size || len % erase_size) {
336                 debug("SF: Erase offset/length not multiple of erase size\n");
337                 return -1;
338         }
339
340         if (flash->flash_is_locked) {
341                 if (flash->flash_is_locked(flash, offset, len) > 0) {
342                         printf("offset 0x%x is protected and cannot be erased\n",
343                                offset);
344                         return -EINVAL;
345                 }
346         }
347
348         cmd[0] = flash->erase_cmd;
349         while (len) {
350                 erase_addr = offset;
351
352 #ifdef CONFIG_SF_DUAL_FLASH
353                 if (flash->dual_flash > SF_SINGLE_FLASH)
354                         spi_flash_dual(flash, &erase_addr);
355 #endif
356 #ifdef CONFIG_SPI_FLASH_BAR
357                 ret = spi_flash_write_bar(flash, erase_addr);
358                 if (ret < 0)
359                         return ret;
360 #endif
361                 spi_flash_addr(erase_addr, cmd);
362
363                 debug("SF: erase %2x %2x %2x %2x (%x)\n", cmd[0], cmd[1],
364                       cmd[2], cmd[3], erase_addr);
365
366                 ret = spi_flash_write_common(flash, cmd, sizeof(cmd), NULL, 0);
367                 if (ret < 0) {
368                         debug("SF: erase failed\n");
369                         break;
370                 }
371
372                 offset += erase_size;
373                 len -= erase_size;
374         }
375
376         return ret;
377 }
378
379 int spi_flash_cmd_write_ops(struct spi_flash *flash, u32 offset,
380                 size_t len, const void *buf)
381 {
382         struct spi_slave *spi = flash->spi;
383         unsigned long byte_addr, page_size;
384         u32 write_addr;
385         size_t chunk_len, actual;
386         u8 cmd[SPI_FLASH_CMD_LEN];
387         int ret = -1;
388
389         page_size = flash->page_size;
390
391         if (flash->flash_is_locked) {
392                 if (flash->flash_is_locked(flash, offset, len) > 0) {
393                         printf("offset 0x%x is protected and cannot be written\n",
394                                offset);
395                         return -EINVAL;
396                 }
397         }
398
399         cmd[0] = flash->write_cmd;
400         for (actual = 0; actual < len; actual += chunk_len) {
401                 write_addr = offset;
402
403 #ifdef CONFIG_SF_DUAL_FLASH
404                 if (flash->dual_flash > SF_SINGLE_FLASH)
405                         spi_flash_dual(flash, &write_addr);
406 #endif
407 #ifdef CONFIG_SPI_FLASH_BAR
408                 ret = spi_flash_write_bar(flash, write_addr);
409                 if (ret < 0)
410                         return ret;
411 #endif
412                 byte_addr = offset % page_size;
413                 chunk_len = min(len - actual, (size_t)(page_size - byte_addr));
414
415                 if (spi->max_write_size)
416                         chunk_len = min(chunk_len,
417                                         (size_t)spi->max_write_size);
418
419                 spi_flash_addr(write_addr, cmd);
420
421                 debug("SF: 0x%p => cmd = { 0x%02x 0x%02x%02x%02x } chunk_len = %zu\n",
422                       buf + actual, cmd[0], cmd[1], cmd[2], cmd[3], chunk_len);
423
424                 ret = spi_flash_write_common(flash, cmd, sizeof(cmd),
425                                         buf + actual, chunk_len);
426                 if (ret < 0) {
427                         debug("SF: write failed\n");
428                         break;
429                 }
430
431                 offset += chunk_len;
432         }
433
434         return ret;
435 }
436
437 int spi_flash_read_common(struct spi_flash *flash, const u8 *cmd,
438                 size_t cmd_len, void *data, size_t data_len)
439 {
440         struct spi_slave *spi = flash->spi;
441         int ret;
442
443         ret = spi_claim_bus(spi);
444         if (ret) {
445                 debug("SF: unable to claim SPI bus\n");
446                 return ret;
447         }
448
449         ret = spi_flash_cmd_read(spi, cmd, cmd_len, data, data_len);
450         if (ret < 0) {
451                 debug("SF: read cmd failed\n");
452                 return ret;
453         }
454
455         spi_release_bus(spi);
456
457         return ret;
458 }
459
460 /*
461  * TODO: remove the weak after all the other spi_flash_copy_mmap
462  * implementations removed from drivers
463  */
464 void __weak spi_flash_copy_mmap(void *data, void *offset, size_t len)
465 {
466 #ifdef CONFIG_DMA
467         if (!dma_memcpy(data, offset, len))
468                 return;
469 #endif
470         memcpy(data, offset, len);
471 }
472
473 int spi_flash_cmd_read_ops(struct spi_flash *flash, u32 offset,
474                 size_t len, void *data)
475 {
476         struct spi_slave *spi = flash->spi;
477         u8 *cmd, cmdsz;
478         u32 remain_len, read_len, read_addr;
479         int bank_sel = 0;
480         int ret = -1;
481
482         /* Handle memory-mapped SPI */
483         if (flash->memory_map) {
484                 ret = spi_claim_bus(spi);
485                 if (ret) {
486                         debug("SF: unable to claim SPI bus\n");
487                         return ret;
488                 }
489                 spi_xfer(spi, 0, NULL, NULL, SPI_XFER_MMAP);
490                 spi_flash_copy_mmap(data, flash->memory_map + offset, len);
491                 spi_xfer(spi, 0, NULL, NULL, SPI_XFER_MMAP_END);
492                 spi_release_bus(spi);
493                 return 0;
494         }
495
496         cmdsz = SPI_FLASH_CMD_LEN + flash->dummy_byte;
497         cmd = calloc(1, cmdsz);
498         if (!cmd) {
499                 debug("SF: Failed to allocate cmd\n");
500                 return -ENOMEM;
501         }
502
503         cmd[0] = flash->read_cmd;
504         while (len) {
505                 read_addr = offset;
506
507 #ifdef CONFIG_SF_DUAL_FLASH
508                 if (flash->dual_flash > SF_SINGLE_FLASH)
509                         spi_flash_dual(flash, &read_addr);
510 #endif
511 #ifdef CONFIG_SPI_FLASH_BAR
512                 ret = spi_flash_write_bar(flash, read_addr);
513                 if (ret < 0)
514                         return ret;
515                 bank_sel = flash->bank_curr;
516 #endif
517                 remain_len = ((SPI_FLASH_16MB_BOUN << flash->shift) *
518                                 (bank_sel + 1)) - offset;
519                 if (len < remain_len)
520                         read_len = len;
521                 else
522                         read_len = remain_len;
523
524                 spi_flash_addr(read_addr, cmd);
525
526                 ret = spi_flash_read_common(flash, cmd, cmdsz, data, read_len);
527                 if (ret < 0) {
528                         debug("SF: read failed\n");
529                         break;
530                 }
531
532                 offset += read_len;
533                 len -= read_len;
534                 data += read_len;
535         }
536
537         free(cmd);
538         return ret;
539 }
540
541 #ifdef CONFIG_SPI_FLASH_SST
542 static int sst_byte_write(struct spi_flash *flash, u32 offset, const void *buf)
543 {
544         struct spi_slave *spi = flash->spi;
545         int ret;
546         u8 cmd[4] = {
547                 CMD_SST_BP,
548                 offset >> 16,
549                 offset >> 8,
550                 offset,
551         };
552
553         debug("BP[%02x]: 0x%p => cmd = { 0x%02x 0x%06x }\n",
554               spi_w8r8(spi, CMD_READ_STATUS), buf, cmd[0], offset);
555
556         ret = spi_flash_cmd_write_enable(flash);
557         if (ret)
558                 return ret;
559
560         ret = spi_flash_cmd_write(spi, cmd, sizeof(cmd), buf, 1);
561         if (ret)
562                 return ret;
563
564         return spi_flash_cmd_wait_ready(flash, SPI_FLASH_PROG_TIMEOUT);
565 }
566
567 int sst_write_wp(struct spi_flash *flash, u32 offset, size_t len,
568                 const void *buf)
569 {
570         struct spi_slave *spi = flash->spi;
571         size_t actual, cmd_len;
572         int ret;
573         u8 cmd[4];
574
575         ret = spi_claim_bus(spi);
576         if (ret) {
577                 debug("SF: Unable to claim SPI bus\n");
578                 return ret;
579         }
580
581         /* If the data is not word aligned, write out leading single byte */
582         actual = offset % 2;
583         if (actual) {
584                 ret = sst_byte_write(flash, offset, buf);
585                 if (ret)
586                         goto done;
587         }
588         offset += actual;
589
590         ret = spi_flash_cmd_write_enable(flash);
591         if (ret)
592                 goto done;
593
594         cmd_len = 4;
595         cmd[0] = CMD_SST_AAI_WP;
596         cmd[1] = offset >> 16;
597         cmd[2] = offset >> 8;
598         cmd[3] = offset;
599
600         for (; actual < len - 1; actual += 2) {
601                 debug("WP[%02x]: 0x%p => cmd = { 0x%02x 0x%06x }\n",
602                       spi_w8r8(spi, CMD_READ_STATUS), buf + actual,
603                       cmd[0], offset);
604
605                 ret = spi_flash_cmd_write(spi, cmd, cmd_len,
606                                         buf + actual, 2);
607                 if (ret) {
608                         debug("SF: sst word program failed\n");
609                         break;
610                 }
611
612                 ret = spi_flash_cmd_wait_ready(flash, SPI_FLASH_PROG_TIMEOUT);
613                 if (ret)
614                         break;
615
616                 cmd_len = 1;
617                 offset += 2;
618         }
619
620         if (!ret)
621                 ret = spi_flash_cmd_write_disable(flash);
622
623         /* If there is a single trailing byte, write it out */
624         if (!ret && actual != len)
625                 ret = sst_byte_write(flash, offset, buf + actual);
626
627  done:
628         debug("SF: sst: program %s %zu bytes @ 0x%zx\n",
629               ret ? "failure" : "success", len, offset - actual);
630
631         spi_release_bus(spi);
632         return ret;
633 }
634
635 int sst_write_bp(struct spi_flash *flash, u32 offset, size_t len,
636                 const void *buf)
637 {
638         struct spi_slave *spi = flash->spi;
639         size_t actual;
640         int ret;
641
642         ret = spi_claim_bus(spi);
643         if (ret) {
644                 debug("SF: Unable to claim SPI bus\n");
645                 return ret;
646         }
647
648         for (actual = 0; actual < len; actual++) {
649                 ret = sst_byte_write(flash, offset, buf + actual);
650                 if (ret) {
651                         debug("SF: sst byte program failed\n");
652                         break;
653                 }
654                 offset++;
655         }
656
657         if (!ret)
658                 ret = spi_flash_cmd_write_disable(flash);
659
660         debug("SF: sst: program %s %zu bytes @ 0x%zx\n",
661               ret ? "failure" : "success", len, offset - actual);
662
663         spi_release_bus(spi);
664         return ret;
665 }
666 #endif
667
668 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
669 static void stm_get_locked_range(struct spi_flash *flash, u8 sr, loff_t *ofs,
670                                  u64 *len)
671 {
672         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
673         int shift = ffs(mask) - 1;
674         int pow;
675
676         if (!(sr & mask)) {
677                 /* No protection */
678                 *ofs = 0;
679                 *len = 0;
680         } else {
681                 pow = ((sr & mask) ^ mask) >> shift;
682                 *len = flash->size >> pow;
683                 *ofs = flash->size - *len;
684         }
685 }
686
687 /*
688  * Return 1 if the entire region is locked, 0 otherwise
689  */
690 static int stm_is_locked_sr(struct spi_flash *flash, loff_t ofs, u64 len,
691                             u8 sr)
692 {
693         loff_t lock_offs;
694         u64 lock_len;
695
696         stm_get_locked_range(flash, sr, &lock_offs, &lock_len);
697
698         return (ofs + len <= lock_offs + lock_len) && (ofs >= lock_offs);
699 }
700
701 /*
702  * Check if a region of the flash is (completely) locked. See stm_lock() for
703  * more info.
704  *
705  * Returns 1 if entire region is locked, 0 if any portion is unlocked, and
706  * negative on errors.
707  */
708 int stm_is_locked(struct spi_flash *flash, u32 ofs, size_t len)
709 {
710         int status;
711         u8 sr;
712
713         status = read_sr(flash, &sr);
714         if (status < 0)
715                 return status;
716
717         return stm_is_locked_sr(flash, ofs, len, sr);
718 }
719
720 /*
721  * Lock a region of the flash. Compatible with ST Micro and similar flash.
722  * Supports only the block protection bits BP{0,1,2} in the status register
723  * (SR). Does not support these features found in newer SR bitfields:
724  *   - TB: top/bottom protect - only handle TB=0 (top protect)
725  *   - SEC: sector/block protect - only handle SEC=0 (block protect)
726  *   - CMP: complement protect - only support CMP=0 (range is not complemented)
727  *
728  * Sample table portion for 8MB flash (Winbond w25q64fw):
729  *
730  *   SEC  |  TB   |  BP2  |  BP1  |  BP0  |  Prot Length  | Protected Portion
731  *  --------------------------------------------------------------------------
732  *    X   |   X   |   0   |   0   |   0   |  NONE         | NONE
733  *    0   |   0   |   0   |   0   |   1   |  128 KB       | Upper 1/64
734  *    0   |   0   |   0   |   1   |   0   |  256 KB       | Upper 1/32
735  *    0   |   0   |   0   |   1   |   1   |  512 KB       | Upper 1/16
736  *    0   |   0   |   1   |   0   |   0   |  1 MB         | Upper 1/8
737  *    0   |   0   |   1   |   0   |   1   |  2 MB         | Upper 1/4
738  *    0   |   0   |   1   |   1   |   0   |  4 MB         | Upper 1/2
739  *    X   |   X   |   1   |   1   |   1   |  8 MB         | ALL
740  *
741  * Returns negative on errors, 0 on success.
742  */
743 int stm_lock(struct spi_flash *flash, u32 ofs, size_t len)
744 {
745         u8 status_old, status_new;
746         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
747         u8 shift = ffs(mask) - 1, pow, val;
748         int ret;
749
750         ret = read_sr(flash, &status_old);
751         if (ret < 0)
752                 return ret;
753
754         /* SPI NOR always locks to the end */
755         if (ofs + len != flash->size) {
756                 /* Does combined region extend to end? */
757                 if (!stm_is_locked_sr(flash, ofs + len, flash->size - ofs - len,
758                                       status_old))
759                         return -EINVAL;
760                 len = flash->size - ofs;
761         }
762
763         /*
764          * Need smallest pow such that:
765          *
766          *   1 / (2^pow) <= (len / size)
767          *
768          * so (assuming power-of-2 size) we do:
769          *
770          *   pow = ceil(log2(size / len)) = log2(size) - floor(log2(len))
771          */
772         pow = ilog2(flash->size) - ilog2(len);
773         val = mask - (pow << shift);
774         if (val & ~mask)
775                 return -EINVAL;
776
777         /* Don't "lock" with no region! */
778         if (!(val & mask))
779                 return -EINVAL;
780
781         status_new = (status_old & ~mask) | val;
782
783         /* Only modify protection if it will not unlock other areas */
784         if ((status_new & mask) <= (status_old & mask))
785                 return -EINVAL;
786
787         write_sr(flash, status_new);
788
789         return 0;
790 }
791
792 /*
793  * Unlock a region of the flash. See stm_lock() for more info
794  *
795  * Returns negative on errors, 0 on success.
796  */
797 int stm_unlock(struct spi_flash *flash, u32 ofs, size_t len)
798 {
799         uint8_t status_old, status_new;
800         u8 mask = SR_BP2 | SR_BP1 | SR_BP0;
801         u8 shift = ffs(mask) - 1, pow, val;
802         int ret;
803
804         ret = read_sr(flash, &status_old);
805         if (ret < 0)
806                 return ret;
807
808         /* Cannot unlock; would unlock larger region than requested */
809         if (stm_is_locked_sr(flash, ofs - flash->erase_size, flash->erase_size,
810                              status_old))
811                 return -EINVAL;
812         /*
813          * Need largest pow such that:
814          *
815          *   1 / (2^pow) >= (len / size)
816          *
817          * so (assuming power-of-2 size) we do:
818          *
819          *   pow = floor(log2(size / len)) = log2(size) - ceil(log2(len))
820          */
821         pow = ilog2(flash->size) - order_base_2(flash->size - (ofs + len));
822         if (ofs + len == flash->size) {
823                 val = 0; /* fully unlocked */
824         } else {
825                 val = mask - (pow << shift);
826                 /* Some power-of-two sizes are not supported */
827                 if (val & ~mask)
828                         return -EINVAL;
829         }
830
831         status_new = (status_old & ~mask) | val;
832
833         /* Only modify protection if it will not lock other areas */
834         if ((status_new & mask) >= (status_old & mask))
835                 return -EINVAL;
836
837         write_sr(flash, status_new);
838
839         return 0;
840 }
841 #endif
842
843
844 #ifdef CONFIG_SPI_FLASH_MACRONIX
845 static int macronix_quad_enable(struct spi_flash *flash)
846 {
847         u8 qeb_status;
848         int ret;
849
850         ret = read_sr(flash, &qeb_status);
851         if (ret < 0)
852                 return ret;
853
854         if (qeb_status & STATUS_QEB_MXIC)
855                 return 0;
856
857         ret = write_sr(flash, qeb_status | STATUS_QEB_MXIC);
858         if (ret < 0)
859                 return ret;
860
861         /* read SR and check it */
862         ret = read_sr(flash, &qeb_status);
863         if (!(ret >= 0 && (qeb_status & STATUS_QEB_MXIC))) {
864                 printf("SF: Macronix SR Quad bit not clear\n");
865                 return -EINVAL;
866         }
867
868         return ret;
869 }
870 #endif
871
872 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
873 static int spansion_quad_enable(struct spi_flash *flash)
874 {
875         u8 qeb_status;
876         int ret;
877
878         ret = read_cr(flash, &qeb_status);
879         if (ret < 0)
880                 return ret;
881
882         if (qeb_status & STATUS_QEB_WINSPAN)
883                 return 0;
884
885         ret = write_cr(flash, qeb_status | STATUS_QEB_WINSPAN);
886         if (ret < 0)
887                 return ret;
888
889         /* read CR and check it */
890         ret = read_cr(flash, &qeb_status);
891         if (!(ret >= 0 && (qeb_status & STATUS_QEB_WINSPAN))) {
892                 printf("SF: Spansion CR Quad bit not clear\n");
893                 return -EINVAL;
894         }
895
896         return ret;
897 }
898 #endif
899
900 #ifdef CONFIG_SPI_FLASH_STMICRO
901 static int micron_quad_enable(struct spi_flash *flash)
902 {
903         u8 qeb_status;
904         int ret;
905
906         ret = read_evcr(flash, &qeb_status);
907         if (ret < 0)
908                 return ret;
909
910         if (!(qeb_status & STATUS_QEB_MICRON))
911                 return 0;
912
913         ret = write_evcr(flash, qeb_status & ~STATUS_QEB_MICRON);
914         if (ret < 0)
915                 return ret;
916
917         /* read EVCR and check it */
918         ret = read_evcr(flash, &qeb_status);
919         if (!(ret >= 0 && !(qeb_status & STATUS_QEB_MICRON))) {
920                 printf("SF: Micron EVCR Quad bit not clear\n");
921                 return -EINVAL;
922         }
923
924         return ret;
925 }
926 #endif
927
928 static const struct spi_flash_info *spi_flash_read_id(struct spi_flash *flash)
929 {
930         int                             tmp;
931         u8                              id[5];
932         const struct spi_flash_info     *info;
933
934         tmp = spi_flash_cmd(flash->spi, CMD_READ_ID, id, 5);
935         if (tmp < 0) {
936                 printf("SF: error %d reading JEDEC ID\n", tmp);
937                 return ERR_PTR(tmp);
938         }
939
940         info = spi_flash_ids;
941         for (; info->name != NULL; info++) {
942                 if (info->id_len) {
943                         if (!memcmp(info->id, id, info->id_len))
944                                 return info;
945                 }
946         }
947
948         printf("SF: unrecognized JEDEC id bytes: %02x, %02x, %02x\n",
949                id[0], id[1], id[2]);
950         return ERR_PTR(-ENODEV);
951 }
952
953 static int set_quad_mode(struct spi_flash *flash,
954                          const struct spi_flash_info *info)
955 {
956         switch (JEDEC_MFR(info)) {
957 #ifdef CONFIG_SPI_FLASH_MACRONIX
958         case SPI_FLASH_CFI_MFR_MACRONIX:
959                 return macronix_quad_enable(flash);
960 #endif
961 #if defined(CONFIG_SPI_FLASH_SPANSION) || defined(CONFIG_SPI_FLASH_WINBOND)
962         case SPI_FLASH_CFI_MFR_SPANSION:
963         case SPI_FLASH_CFI_MFR_WINBOND:
964                 return spansion_quad_enable(flash);
965 #endif
966 #ifdef CONFIG_SPI_FLASH_STMICRO
967         case SPI_FLASH_CFI_MFR_STMICRO:
968                 return micron_quad_enable(flash);
969 #endif
970         default:
971                 printf("SF: Need set QEB func for %02x flash\n",
972                        JEDEC_MFR(info));
973                 return -1;
974         }
975 }
976
977 #if CONFIG_IS_ENABLED(OF_CONTROL)
978 int spi_flash_decode_fdt(const void *blob, struct spi_flash *flash)
979 {
980 #ifdef CONFIG_DM_SPI_FLASH
981         fdt_addr_t addr;
982         fdt_size_t size;
983         int node = flash->dev->of_offset;
984
985         addr = fdtdec_get_addr_size(blob, node, "memory-map", &size);
986         if (addr == FDT_ADDR_T_NONE) {
987                 debug("%s: Cannot decode address\n", __func__);
988                 return 0;
989         }
990
991         if (flash->size != size) {
992                 debug("%s: Memory map must cover entire device\n", __func__);
993                 return -1;
994         }
995         flash->memory_map = map_sysmem(addr, size);
996 #endif
997
998         return 0;
999 }
1000 #endif /* CONFIG_IS_ENABLED(OF_CONTROL) */
1001
1002 #ifdef CONFIG_SPI_FLASH_SPANSION
1003 static int spansion_s25fss_disable_4KB_erase(struct spi_slave *spi)
1004 {
1005         u8 cmd[4];
1006         u32 offset = 0x800004; /* CR3V register offset */
1007         u8 cr3v;
1008         int ret;
1009
1010         cmd[0] = CMD_SPANSION_RDAR;
1011         cmd[1] = offset >> 16;
1012         cmd[2] = offset >> 8;
1013         cmd[3] = offset >> 0;
1014
1015         ret = spi_flash_cmd_read(spi, cmd, 4, &cr3v, 1);
1016         if (ret)
1017                 return -EIO;
1018         /* CR3V bit3: 4-KB Erase */
1019         if (cr3v & 0x8)
1020                 return 0;
1021
1022         cmd[0] = CMD_SPANSION_WRAR;
1023         cr3v |= 0x8;
1024         ret = spi_flash_cmd_write(spi, cmd, 4, &cr3v, 1);
1025         if (ret)
1026                 return -EIO;
1027
1028         cmd[0] = CMD_SPANSION_RDAR;
1029         ret = spi_flash_cmd_read(spi, cmd, 4, &cr3v, 1);
1030         if (ret)
1031                 return -EIO;
1032         if (!(cr3v & 0x8))
1033                 return -EFAULT;
1034
1035         return 0;
1036 }
1037 #endif
1038
1039 int spi_flash_scan(struct spi_flash *flash)
1040 {
1041         struct spi_slave *spi = flash->spi;
1042         const struct spi_flash_info *info = NULL;
1043         int ret = -1;
1044
1045         info = spi_flash_read_id(flash);
1046         if (IS_ERR_OR_NULL(info))
1047                 return -ENOENT;
1048
1049 #ifdef CONFIG_SPI_FLASH_SPANSION
1050         /*
1051          * The S25FS-S family physical sectors may be configured as a
1052          * hybrid combination of eight 4-kB parameter sectors
1053          * at the top or bottom of the address space with all
1054          * but one of the remaining sectors being uniform size.
1055          * The Parameter Sector Erase commands (20h or 21h) must
1056          * be used to erase the 4-kB parameter sectors individually.
1057          * The Sector (uniform sector) Erase commands (D8h or DCh)
1058          * must be used to erase any of the remaining
1059          * sectors, including the portion of highest or lowest address
1060          * sector that is not overlaid by the parameter sectors.
1061          * The uniform sector erase command has no effect on parameter sectors.
1062          */
1063         if ((JEDEC_ID(info) == 0x0219 || (JEDEC_ID(info) == 0x0220)) &&
1064             (JEDEC_EXT(info) & 0xff00) == 0x4d00) {
1065                 int ret;
1066                 u8 idcode[5];
1067                 u8 id[6];
1068
1069                 /* Read the ID codes again, 5 bytes */
1070                 ret = spi_flash_cmd(flash->spi, CMD_READ_ID, idcode, sizeof(idcode));
1071                 if (ret)
1072                         return -EIO;
1073
1074                 /* Read the ID codes again, 6 bytes */
1075                 ret = spi_flash_cmd(flash->spi, CMD_READ_ID, id, sizeof(id));
1076                 if (ret)
1077                         return -EIO;
1078
1079                 ret = memcmp(id, idcode, 5);
1080                 if (ret)
1081                         return -EIO;
1082
1083                 /* 0x81: S25FS-S family 0x80: S25FL-S family */
1084                 if (id[5] == 0x81) {
1085                         ret = spansion_s25fss_disable_4KB_erase(spi);
1086                         if (ret)
1087                                 return ret;
1088                 }
1089         }
1090 #endif
1091         /* Flash powers up read-only, so clear BP# bits */
1092         if (JEDEC_MFR(info) == SPI_FLASH_CFI_MFR_ATMEL ||
1093             JEDEC_MFR(info) == SPI_FLASH_CFI_MFR_MACRONIX ||
1094             JEDEC_MFR(info) == SPI_FLASH_CFI_MFR_SST)
1095                 write_sr(flash, 0);
1096
1097         /* Assign spi data */
1098         flash->name = info->name;
1099         flash->memory_map = spi->memory_map;
1100         flash->dual_flash = spi->option;
1101
1102         /* Assign spi flash flags */
1103         if (info->flags & SST_WR)
1104                 flash->flags |= SNOR_F_SST_WR;
1105
1106         /* Assign spi_flash ops */
1107 #ifndef CONFIG_DM_SPI_FLASH
1108         flash->write = spi_flash_cmd_write_ops;
1109 #if defined(CONFIG_SPI_FLASH_SST)
1110         if (flash->flags & SNOR_F_SST_WR) {
1111                 if (spi->mode & SPI_TX_BYTE)
1112                         flash->write = sst_write_bp;
1113                 else
1114                         flash->write = sst_write_wp;
1115         }
1116 #endif
1117         flash->erase = spi_flash_cmd_erase_ops;
1118         flash->read = spi_flash_cmd_read_ops;
1119 #endif
1120
1121 #if defined(CONFIG_SPI_FLASH_STMICRO) || defined(CONFIG_SPI_FLASH_SST)
1122         /* NOR protection support for STmicro/Micron chips and similar */
1123         if (JEDEC_MFR(info) == SPI_FLASH_CFI_MFR_STMICRO ||
1124             JEDEC_MFR(info) == SPI_FLASH_CFI_MFR_SST) {
1125                 flash->flash_lock = stm_lock;
1126                 flash->flash_unlock = stm_unlock;
1127                 flash->flash_is_locked = stm_is_locked;
1128         }
1129 #endif
1130
1131         /* Compute the flash size */
1132         flash->shift = (flash->dual_flash & SF_DUAL_PARALLEL_FLASH) ? 1 : 0;
1133         flash->page_size = info->page_size;
1134         /*
1135          * The Spansion S25FL032P and S25FL064P have 256b pages, yet use the
1136          * 0x4d00 Extended JEDEC code. The rest of the Spansion flashes with
1137          * the 0x4d00 Extended JEDEC code have 512b pages. All of the others
1138          * have 256b pages.
1139          */
1140         if (JEDEC_EXT(info) == 0x4d00) {
1141                 if ((JEDEC_ID(info) != 0x0215) &&
1142                     (JEDEC_ID(info) != 0x0216))
1143                         flash->page_size = 512;
1144         }
1145         flash->page_size <<= flash->shift;
1146         flash->sector_size = info->sector_size << flash->shift;
1147         flash->size = flash->sector_size * info->nr_sectors << flash->shift;
1148 #ifdef CONFIG_SF_DUAL_FLASH
1149         if (flash->dual_flash & SF_DUAL_STACKED_FLASH)
1150                 flash->size <<= 1;
1151 #endif
1152
1153 #ifdef CONFIG_SPI_FLASH_USE_4K_SECTORS
1154         /* Compute erase sector and command */
1155         if (info->flags & SECT_4K) {
1156                 flash->erase_cmd = CMD_ERASE_4K;
1157                 flash->erase_size = 4096 << flash->shift;
1158         } else
1159 #endif
1160         {
1161                 flash->erase_cmd = CMD_ERASE_64K;
1162                 flash->erase_size = flash->sector_size;
1163         }
1164
1165         /* Now erase size becomes valid sector size */
1166         flash->sector_size = flash->erase_size;
1167
1168         /* Look for read commands */
1169         flash->read_cmd = CMD_READ_ARRAY_FAST;
1170         if (spi->mode & SPI_RX_SLOW)
1171                 flash->read_cmd = CMD_READ_ARRAY_SLOW;
1172         else if (spi->mode & SPI_RX_QUAD && info->flags & RD_QUAD)
1173                 flash->read_cmd = CMD_READ_QUAD_OUTPUT_FAST;
1174         else if (spi->mode & SPI_RX_DUAL && info->flags & RD_DUAL)
1175                 flash->read_cmd = CMD_READ_DUAL_OUTPUT_FAST;
1176
1177         /* Look for write commands */
1178         if (info->flags & WR_QPP && spi->mode & SPI_TX_QUAD)
1179                 flash->write_cmd = CMD_QUAD_PAGE_PROGRAM;
1180         else
1181                 /* Go for default supported write cmd */
1182                 flash->write_cmd = CMD_PAGE_PROGRAM;
1183
1184         /* Set the quad enable bit - only for quad commands */
1185         if ((flash->read_cmd == CMD_READ_QUAD_OUTPUT_FAST) ||
1186             (flash->read_cmd == CMD_READ_QUAD_IO_FAST) ||
1187             (flash->write_cmd == CMD_QUAD_PAGE_PROGRAM)) {
1188                 ret = set_quad_mode(flash, info);
1189                 if (ret) {
1190                         debug("SF: Fail to set QEB for %02x\n",
1191                               JEDEC_MFR(info));
1192                         return -EINVAL;
1193                 }
1194         }
1195
1196         /* Read dummy_byte: dummy byte is determined based on the
1197          * dummy cycles of a particular command.
1198          * Fast commands - dummy_byte = dummy_cycles/8
1199          * I/O commands- dummy_byte = (dummy_cycles * no.of lines)/8
1200          * For I/O commands except cmd[0] everything goes on no.of lines
1201          * based on particular command but incase of fast commands except
1202          * data all go on single line irrespective of command.
1203          */
1204         switch (flash->read_cmd) {
1205         case CMD_READ_QUAD_IO_FAST:
1206                 flash->dummy_byte = 2;
1207                 break;
1208         case CMD_READ_ARRAY_SLOW:
1209                 flash->dummy_byte = 0;
1210                 break;
1211         default:
1212                 flash->dummy_byte = 1;
1213         }
1214
1215 #ifdef CONFIG_SPI_FLASH_STMICRO
1216         if (info->flags & E_FSR)
1217                 flash->flags |= SNOR_F_USE_FSR;
1218 #endif
1219
1220         /* Configure the BAR - discover bank cmds and read current bank */
1221 #ifdef CONFIG_SPI_FLASH_BAR
1222         ret = spi_flash_read_bar(flash, info);
1223         if (ret < 0)
1224                 return ret;
1225 #endif
1226
1227 #if CONFIG_IS_ENABLED(OF_CONTROL)
1228         ret = spi_flash_decode_fdt(gd->fdt_blob, flash);
1229         if (ret) {
1230                 debug("SF: FDT decode error\n");
1231                 return -EINVAL;
1232         }
1233 #endif
1234
1235 #ifndef CONFIG_SPL_BUILD
1236         printf("SF: Detected %s with page size ", flash->name);
1237         print_size(flash->page_size, ", erase size ");
1238         print_size(flash->erase_size, ", total ");
1239         print_size(flash->size, "");
1240         if (flash->memory_map)
1241                 printf(", mapped at %p", flash->memory_map);
1242         puts("\n");
1243 #endif
1244
1245 #ifndef CONFIG_SPI_FLASH_BAR
1246         if (((flash->dual_flash == SF_SINGLE_FLASH) &&
1247              (flash->size > SPI_FLASH_16MB_BOUN)) ||
1248              ((flash->dual_flash > SF_SINGLE_FLASH) &&
1249              (flash->size > SPI_FLASH_16MB_BOUN << 1))) {
1250                 puts("SF: Warning - Only lower 16MiB accessible,");
1251                 puts(" Full access #define CONFIG_SPI_FLASH_BAR\n");
1252         }
1253 #endif
1254
1255         return ret;
1256 }