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