sf.c 15 KB

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