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