common: Drop net.h from common header
[platform/kernel/u-boot.git] / cmd / sf.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Command for accessing SPI flash.
4  *
5  * Copyright (C) 2008 Atmel Corporation
6  */
7
8 #include <common.h>
9 #include <div64.h>
10 #include <dm.h>
11 #include <flash.h>
12 #include <malloc.h>
13 #include <mapmem.h>
14 #include <spi.h>
15 #include <spi_flash.h>
16 #include <asm/cache.h>
17 #include <jffs2/jffs2.h>
18 #include <linux/mtd/mtd.h>
19
20 #include <asm/io.h>
21 #include <dm/device-internal.h>
22
23 #include "legacy-mtd-utils.h"
24
25 static struct spi_flash *flash;
26
27 /*
28  * This function computes the length argument for the erase command.
29  * The length on which the command is to operate can be given in two forms:
30  * 1. <cmd> offset len  - operate on <'offset',  'len')
31  * 2. <cmd> offset +len - operate on <'offset',  'round_up(len)')
32  * If the second form is used and the length doesn't fall on the
33  * sector boundary, than it will be adjusted to the next sector boundary.
34  * If it isn't in the flash, the function will fail (return -1).
35  * Input:
36  *    arg: length specification (i.e. both command arguments)
37  * Output:
38  *    len: computed length for operation
39  * Return:
40  *    1: success
41  *   -1: failure (bad format, bad address).
42  */
43 static int sf_parse_len_arg(char *arg, ulong *len)
44 {
45         char *ep;
46         char round_up_len; /* indicates if the "+length" form used */
47         ulong len_arg;
48
49         round_up_len = 0;
50         if (*arg == '+') {
51                 round_up_len = 1;
52                 ++arg;
53         }
54
55         len_arg = simple_strtoul(arg, &ep, 16);
56         if (ep == arg || *ep != '\0')
57                 return -1;
58
59         if (round_up_len && flash->sector_size > 0)
60                 *len = ROUND(len_arg, flash->sector_size);
61         else
62                 *len = len_arg;
63
64         return 1;
65 }
66
67 /**
68  * This function takes a byte length and a delta unit of time to compute the
69  * approximate bytes per second
70  *
71  * @param len           amount of bytes currently processed
72  * @param start_ms      start time of processing in ms
73  * @return bytes per second if OK, 0 on error
74  */
75 static ulong bytes_per_second(unsigned int len, ulong start_ms)
76 {
77         /* less accurate but avoids overflow */
78         if (len >= ((unsigned int) -1) / 1024)
79                 return len / (max(get_timer(start_ms) / 1024, 1UL));
80         else
81                 return 1024 * len / max(get_timer(start_ms), 1UL);
82 }
83
84 static int do_spi_flash_probe(int argc, char * const argv[])
85 {
86         unsigned int bus = CONFIG_SF_DEFAULT_BUS;
87         unsigned int cs = CONFIG_SF_DEFAULT_CS;
88         /* In DM mode, defaults speed and mode will be taken from DT */
89         unsigned int speed = CONFIG_SF_DEFAULT_SPEED;
90         unsigned int mode = CONFIG_SF_DEFAULT_MODE;
91         char *endp;
92 #ifdef CONFIG_DM_SPI_FLASH
93         struct udevice *new, *bus_dev;
94         int ret;
95 #else
96         struct spi_flash *new;
97 #endif
98
99         if (argc >= 2) {
100                 cs = simple_strtoul(argv[1], &endp, 0);
101                 if (*argv[1] == 0 || (*endp != 0 && *endp != ':'))
102                         return -1;
103                 if (*endp == ':') {
104                         if (endp[1] == 0)
105                                 return -1;
106
107                         bus = cs;
108                         cs = simple_strtoul(endp + 1, &endp, 0);
109                         if (*endp != 0)
110                                 return -1;
111                 }
112         }
113
114         if (argc >= 3) {
115                 speed = simple_strtoul(argv[2], &endp, 0);
116                 if (*argv[2] == 0 || *endp != 0)
117                         return -1;
118         }
119         if (argc >= 4) {
120                 mode = simple_strtoul(argv[3], &endp, 16);
121                 if (*argv[3] == 0 || *endp != 0)
122                         return -1;
123         }
124
125 #ifdef CONFIG_DM_SPI_FLASH
126         /* Remove the old device, otherwise probe will just be a nop */
127         ret = spi_find_bus_and_cs(bus, cs, &bus_dev, &new);
128         if (!ret) {
129                 device_remove(new, DM_REMOVE_NORMAL);
130         }
131         flash = NULL;
132         ret = spi_flash_probe_bus_cs(bus, cs, speed, mode, &new);
133         if (ret) {
134                 printf("Failed to initialize SPI flash at %u:%u (error %d)\n",
135                        bus, cs, ret);
136                 return 1;
137         }
138
139         flash = dev_get_uclass_priv(new);
140 #else
141         if (flash)
142                 spi_flash_free(flash);
143
144         new = spi_flash_probe(bus, cs, speed, mode);
145         flash = new;
146
147         if (!new) {
148                 printf("Failed to initialize SPI flash at %u:%u\n", bus, cs);
149                 return 1;
150         }
151
152         flash = new;
153 #endif
154
155         return 0;
156 }
157
158 /**
159  * Write a block of data to SPI flash, first checking if it is different from
160  * what is already there.
161  *
162  * If the data being written is the same, then *skipped is incremented by len.
163  *
164  * @param flash         flash context pointer
165  * @param offset        flash offset to write
166  * @param len           number of bytes to write
167  * @param buf           buffer to write from
168  * @param cmp_buf       read buffer to use to compare data
169  * @param skipped       Count of skipped data (incremented by this function)
170  * @return NULL if OK, else a string containing the stage which failed
171  */
172 static const char *spi_flash_update_block(struct spi_flash *flash, u32 offset,
173                 size_t len, const char *buf, char *cmp_buf, size_t *skipped)
174 {
175         char *ptr = (char *)buf;
176
177         debug("offset=%#x, sector_size=%#x, len=%#zx\n",
178               offset, flash->sector_size, len);
179         /* Read the entire sector so to allow for rewriting */
180         if (spi_flash_read(flash, offset, flash->sector_size, cmp_buf))
181                 return "read";
182         /* Compare only what is meaningful (len) */
183         if (memcmp(cmp_buf, buf, len) == 0) {
184                 debug("Skip region %x size %zx: no change\n",
185                       offset, len);
186                 *skipped += len;
187                 return NULL;
188         }
189         /* Erase the entire sector */
190         if (spi_flash_erase(flash, offset, flash->sector_size))
191                 return "erase";
192         /* If it's a partial sector, copy the data into the temp-buffer */
193         if (len != flash->sector_size) {
194                 memcpy(cmp_buf, buf, len);
195                 ptr = cmp_buf;
196         }
197         /* Write one complete sector */
198         if (spi_flash_write(flash, offset, flash->sector_size, ptr))
199                 return "write";
200
201         return NULL;
202 }
203
204 /**
205  * Update an area of SPI flash by erasing and writing any blocks which need
206  * to change. Existing blocks with the correct data are left unchanged.
207  *
208  * @param flash         flash context pointer
209  * @param offset        flash offset to write
210  * @param len           number of bytes to write
211  * @param buf           buffer to write from
212  * @return 0 if ok, 1 on error
213  */
214 static int spi_flash_update(struct spi_flash *flash, u32 offset,
215                 size_t len, const char *buf)
216 {
217         const char *err_oper = NULL;
218         char *cmp_buf;
219         const char *end = buf + len;
220         size_t todo;            /* number of bytes to do in this pass */
221         size_t skipped = 0;     /* statistics */
222         const ulong start_time = get_timer(0);
223         size_t scale = 1;
224         const char *start_buf = buf;
225         ulong delta;
226
227         if (end - buf >= 200)
228                 scale = (end - buf) / 100;
229         cmp_buf = memalign(ARCH_DMA_MINALIGN, flash->sector_size);
230         if (cmp_buf) {
231                 ulong last_update = get_timer(0);
232
233                 for (; buf < end && !err_oper; buf += todo, offset += todo) {
234                         todo = min_t(size_t, end - buf, flash->sector_size);
235                         if (get_timer(last_update) > 100) {
236                                 printf("   \rUpdating, %zu%% %lu B/s",
237                                        100 - (end - buf) / scale,
238                                         bytes_per_second(buf - start_buf,
239                                                          start_time));
240                                 last_update = get_timer(0);
241                         }
242                         err_oper = spi_flash_update_block(flash, offset, todo,
243                                         buf, cmp_buf, &skipped);
244                 }
245         } else {
246                 err_oper = "malloc";
247         }
248         free(cmp_buf);
249         putc('\r');
250         if (err_oper) {
251                 printf("SPI flash failed in %s step\n", err_oper);
252                 return 1;
253         }
254
255         delta = get_timer(start_time);
256         printf("%zu bytes written, %zu bytes skipped", len - skipped,
257                skipped);
258         printf(" in %ld.%lds, speed %ld B/s\n",
259                delta / 1000, delta % 1000, bytes_per_second(len, start_time));
260
261         return 0;
262 }
263
264 static int do_spi_flash_read_write(int argc, char * const argv[])
265 {
266         unsigned long addr;
267         void *buf;
268         char *endp;
269         int ret = 1;
270         int dev = 0;
271         loff_t offset, len, maxsize;
272
273         if (argc < 3)
274                 return -1;
275
276         addr = simple_strtoul(argv[1], &endp, 16);
277         if (*argv[1] == 0 || *endp != 0)
278                 return -1;
279
280         if (mtd_arg_off_size(argc - 2, &argv[2], &dev, &offset, &len,
281                              &maxsize, MTD_DEV_TYPE_NOR, flash->size))
282                 return -1;
283
284         /* Consistency checking */
285         if (offset + len > flash->size) {
286                 printf("ERROR: attempting %s past flash size (%#x)\n",
287                        argv[0], flash->size);
288                 return 1;
289         }
290
291         buf = map_physmem(addr, len, MAP_WRBACK);
292         if (!buf && addr) {
293                 puts("Failed to map physical memory\n");
294                 return 1;
295         }
296
297         if (strcmp(argv[0], "update") == 0) {
298                 ret = spi_flash_update(flash, offset, len, buf);
299         } else if (strncmp(argv[0], "read", 4) == 0 ||
300                         strncmp(argv[0], "write", 5) == 0) {
301                 int read;
302
303                 read = strncmp(argv[0], "read", 4) == 0;
304                 if (read)
305                         ret = spi_flash_read(flash, offset, len, buf);
306                 else
307                         ret = spi_flash_write(flash, offset, len, buf);
308
309                 printf("SF: %zu bytes @ %#x %s: ", (size_t)len, (u32)offset,
310                        read ? "Read" : "Written");
311                 if (ret)
312                         printf("ERROR %d\n", ret);
313                 else
314                         printf("OK\n");
315         }
316
317         unmap_physmem(buf, len);
318
319         return ret == 0 ? 0 : 1;
320 }
321
322 static int do_spi_flash_erase(int argc, char * const argv[])
323 {
324         int ret;
325         int dev = 0;
326         loff_t offset, len, maxsize;
327         ulong size;
328
329         if (argc < 3)
330                 return -1;
331
332         if (mtd_arg_off(argv[1], &dev, &offset, &len, &maxsize,
333                         MTD_DEV_TYPE_NOR, flash->size))
334                 return -1;
335
336         ret = sf_parse_len_arg(argv[2], &size);
337         if (ret != 1)
338                 return -1;
339
340         /* Consistency checking */
341         if (offset + size > flash->size) {
342                 printf("ERROR: attempting %s past flash size (%#x)\n",
343                        argv[0], flash->size);
344                 return 1;
345         }
346
347         ret = spi_flash_erase(flash, offset, size);
348         printf("SF: %zu bytes @ %#x Erased: %s\n", (size_t)size, (u32)offset,
349                ret ? "ERROR" : "OK");
350
351         return ret == 0 ? 0 : 1;
352 }
353
354 static int do_spi_protect(int argc, char * const argv[])
355 {
356         int ret = 0;
357         loff_t start, len;
358         bool prot = false;
359
360         if (argc != 4)
361                 return -1;
362
363         if (!str2off(argv[2], &start)) {
364                 puts("start sector is not a valid number\n");
365                 return 1;
366         }
367
368         if (!str2off(argv[3], &len)) {
369                 puts("len is not a valid number\n");
370                 return 1;
371         }
372
373         if (strcmp(argv[1], "lock") == 0)
374                 prot = true;
375         else if (strcmp(argv[1], "unlock") == 0)
376                 prot = false;
377         else
378                 return -1;  /* Unknown parameter */
379
380         ret = spi_flash_protect(flash, start, len, prot);
381
382         return ret == 0 ? 0 : 1;
383 }
384
385 #ifdef CONFIG_CMD_SF_TEST
386 enum {
387         STAGE_ERASE,
388         STAGE_CHECK,
389         STAGE_WRITE,
390         STAGE_READ,
391
392         STAGE_COUNT,
393 };
394
395 static char *stage_name[STAGE_COUNT] = {
396         "erase",
397         "check",
398         "write",
399         "read",
400 };
401
402 struct test_info {
403         int stage;
404         int bytes;
405         unsigned base_ms;
406         unsigned time_ms[STAGE_COUNT];
407 };
408
409 static void show_time(struct test_info *test, int stage)
410 {
411         uint64_t speed; /* KiB/s */
412         int bps;        /* Bits per second */
413
414         speed = (long long)test->bytes * 1000;
415         if (test->time_ms[stage])
416                 do_div(speed, test->time_ms[stage] * 1024);
417         bps = speed * 8;
418
419         printf("%d %s: %u ticks, %d KiB/s %d.%03d Mbps\n", stage,
420                stage_name[stage], test->time_ms[stage],
421                (int)speed, bps / 1000, bps % 1000);
422 }
423
424 static void spi_test_next_stage(struct test_info *test)
425 {
426         test->time_ms[test->stage] = get_timer(test->base_ms);
427         show_time(test, test->stage);
428         test->base_ms = get_timer(0);
429         test->stage++;
430 }
431
432 /**
433  * Run a test on the SPI flash
434  *
435  * @param flash         SPI flash to use
436  * @param buf           Source buffer for data to write
437  * @param len           Size of data to read/write
438  * @param offset        Offset within flash to check
439  * @param vbuf          Verification buffer
440  * @return 0 if ok, -1 on error
441  */
442 static int spi_flash_test(struct spi_flash *flash, uint8_t *buf, ulong len,
443                            ulong offset, uint8_t *vbuf)
444 {
445         struct test_info test;
446         int i;
447
448         printf("SPI flash test:\n");
449         memset(&test, '\0', sizeof(test));
450         test.base_ms = get_timer(0);
451         test.bytes = len;
452         if (spi_flash_erase(flash, offset, len)) {
453                 printf("Erase failed\n");
454                 return -1;
455         }
456         spi_test_next_stage(&test);
457
458         if (spi_flash_read(flash, offset, len, vbuf)) {
459                 printf("Check read failed\n");
460                 return -1;
461         }
462         for (i = 0; i < len; i++) {
463                 if (vbuf[i] != 0xff) {
464                         printf("Check failed at %d\n", i);
465                         print_buffer(i, vbuf + i, 1,
466                                      min_t(uint, len - i, 0x40), 0);
467                         return -1;
468                 }
469         }
470         spi_test_next_stage(&test);
471
472         if (spi_flash_write(flash, offset, len, buf)) {
473                 printf("Write failed\n");
474                 return -1;
475         }
476         memset(vbuf, '\0', len);
477         spi_test_next_stage(&test);
478
479         if (spi_flash_read(flash, offset, len, vbuf)) {
480                 printf("Read failed\n");
481                 return -1;
482         }
483         spi_test_next_stage(&test);
484
485         for (i = 0; i < len; i++) {
486                 if (buf[i] != vbuf[i]) {
487                         printf("Verify failed at %d, good data:\n", i);
488                         print_buffer(i, buf + i, 1,
489                                      min_t(uint, len - i, 0x40), 0);
490                         printf("Bad data:\n");
491                         print_buffer(i, vbuf + i, 1,
492                                      min_t(uint, len - i, 0x40), 0);
493                         return -1;
494                 }
495         }
496         printf("Test passed\n");
497         for (i = 0; i < STAGE_COUNT; i++)
498                 show_time(&test, i);
499
500         return 0;
501 }
502
503 static int do_spi_flash_test(int argc, char * const argv[])
504 {
505         unsigned long offset;
506         unsigned long len;
507         uint8_t *buf, *from;
508         char *endp;
509         uint8_t *vbuf;
510         int ret;
511
512         if (argc < 3)
513                 return -1;
514         offset = simple_strtoul(argv[1], &endp, 16);
515         if (*argv[1] == 0 || *endp != 0)
516                 return -1;
517         len = simple_strtoul(argv[2], &endp, 16);
518         if (*argv[2] == 0 || *endp != 0)
519                 return -1;
520
521         vbuf = memalign(ARCH_DMA_MINALIGN, len);
522         if (!vbuf) {
523                 printf("Cannot allocate memory (%lu bytes)\n", len);
524                 return 1;
525         }
526         buf = memalign(ARCH_DMA_MINALIGN, len);
527         if (!buf) {
528                 free(vbuf);
529                 printf("Cannot allocate memory (%lu bytes)\n", len);
530                 return 1;
531         }
532
533         from = map_sysmem(CONFIG_SYS_TEXT_BASE, 0);
534         memcpy(buf, from, len);
535         ret = spi_flash_test(flash, buf, len, offset, vbuf);
536         free(vbuf);
537         free(buf);
538         if (ret) {
539                 printf("Test failed\n");
540                 return 1;
541         }
542
543         return 0;
544 }
545 #endif /* CONFIG_CMD_SF_TEST */
546
547 static int do_spi_flash(cmd_tbl_t *cmdtp, int flag, int argc,
548                         char * const argv[])
549 {
550         const char *cmd;
551         int ret;
552
553         /* need at least two arguments */
554         if (argc < 2)
555                 goto usage;
556
557         cmd = argv[1];
558         --argc;
559         ++argv;
560
561         if (strcmp(cmd, "probe") == 0) {
562                 ret = do_spi_flash_probe(argc, argv);
563                 goto done;
564         }
565
566         /* The remaining commands require a selected device */
567         if (!flash) {
568                 puts("No SPI flash selected. Please run `sf probe'\n");
569                 return 1;
570         }
571
572         if (strcmp(cmd, "read") == 0 || strcmp(cmd, "write") == 0 ||
573             strcmp(cmd, "update") == 0)
574                 ret = do_spi_flash_read_write(argc, argv);
575         else if (strcmp(cmd, "erase") == 0)
576                 ret = do_spi_flash_erase(argc, argv);
577         else if (strcmp(cmd, "protect") == 0)
578                 ret = do_spi_protect(argc, argv);
579 #ifdef CONFIG_CMD_SF_TEST
580         else if (!strcmp(cmd, "test"))
581                 ret = do_spi_flash_test(argc, argv);
582 #endif
583         else
584                 ret = -1;
585
586 done:
587         if (ret != -1)
588                 return ret;
589
590 usage:
591         return CMD_RET_USAGE;
592 }
593
594 #ifdef CONFIG_CMD_SF_TEST
595 #define SF_TEST_HELP "\nsf test offset len              " \
596                 "- run a very basic destructive test"
597 #else
598 #define SF_TEST_HELP
599 #endif
600
601 U_BOOT_CMD(
602         sf,     5,      1,      do_spi_flash,
603         "SPI flash sub-system",
604         "probe [[bus:]cs] [hz] [mode]   - init flash device on given SPI bus\n"
605         "                                 and chip select\n"
606         "sf read addr offset|partition len      - read `len' bytes starting at\n"
607         "                                         `offset' or from start of mtd\n"
608         "                                         `partition'to memory at `addr'\n"
609         "sf write addr offset|partition len     - write `len' bytes from memory\n"
610         "                                         at `addr' to flash at `offset'\n"
611         "                                         or to start of mtd `partition'\n"
612         "sf erase offset|partition [+]len       - erase `len' bytes from `offset'\n"
613         "                                         or from start of mtd `partition'\n"
614         "                                        `+len' round up `len' to block size\n"
615         "sf update addr offset|partition len    - erase and write `len' bytes from memory\n"
616         "                                         at `addr' to flash at `offset'\n"
617         "                                         or to start of mtd `partition'\n"
618         "sf protect lock/unlock sector len      - protect/unprotect 'len' bytes starting\n"
619         "                                         at address 'sector'\n"
620         SF_TEST_HELP
621 );