sf.c 15 KB

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