1
0

nand.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. * nand - simple nand memory technology device manipulation tool
  3. *
  4. * Copyright (C) 2010 Waldemar Brodkorb <wbx@openadk.org>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. *
  20. * The code is based on the mtd-utils nandwrite and flash_erase_all.
  21. */
  22. #define _GNU_SOURCE
  23. #include <ctype.h>
  24. #include <errno.h>
  25. #include <err.h>
  26. #include <fcntl.h>
  27. #include <limits.h>
  28. #include <stdbool.h>
  29. #include <stddef.h>
  30. #include <stdint.h>
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <time.h>
  35. #include <unistd.h>
  36. #include <sys/stat.h>
  37. #include <sys/mount.h>
  38. #include <sys/ioctl.h>
  39. #include <sys/types.h>
  40. #include <sys/syscall.h>
  41. #include <getopt.h>
  42. #include "mtd/mtd-user.h"
  43. #include <linux/reboot.h>
  44. int nand_open(const char *, int);
  45. int nand_erase(const char *);
  46. int nand_info(const char *);
  47. int nand_write(const char*, const char *, int);
  48. void usage(void) __attribute__((noreturn));
  49. #define MAX_PAGE_SIZE 4096
  50. #define MAX_OOB_SIZE 128
  51. static unsigned char writebuf[MAX_PAGE_SIZE];
  52. static unsigned char oobbuf[MAX_OOB_SIZE];
  53. static unsigned char oobreadbuf[MAX_OOB_SIZE];
  54. static struct nand_oobinfo autoplace_oobinfo = {
  55. .useecc = MTD_NANDECC_AUTOPLACE
  56. };
  57. static void erase_buffer(void *buffer, size_t size)
  58. {
  59. const uint8_t kEraseByte = 0xff;
  60. if (buffer != NULL && size > 0) {
  61. memset(buffer, kEraseByte, size);
  62. }
  63. }
  64. int nand_open(const char *nand, int flags) {
  65. FILE *fp;
  66. char dev[PATH_MAX];
  67. int i;
  68. if ((fp = fopen("/proc/mtd", "r"))) {
  69. while (fgets(dev, sizeof(dev), fp)) {
  70. if (sscanf(dev, "mtd%d:", &i) && strstr(dev, nand)) {
  71. snprintf(dev, sizeof(dev), "/dev/mtd%d", i);
  72. fclose(fp);
  73. return open(dev, flags);
  74. }
  75. }
  76. fclose(fp);
  77. }
  78. return open(nand, flags);
  79. }
  80. int nand_info(const char *nand) {
  81. int fd, ret;
  82. mtd_info_t nandinfo;
  83. loff_t offset;
  84. if ((fd = nand_open(nand, O_RDONLY)) < 0) {
  85. fprintf(stderr, "nand: unable to open MTD device %s\n", nand);
  86. return 1;
  87. }
  88. if (ioctl(fd, MEMGETINFO, &nandinfo) != 0) {
  89. fprintf(stderr, "nand: unable to get MTD device info from %s\n", nand);
  90. return 1;
  91. }
  92. if (nandinfo.type == MTD_NANDFLASH) {
  93. fprintf(stdout, "MTD devise is NAND\n");
  94. } else {
  95. fprintf(stdout, "MTD devise is NOT NAND\n");
  96. return 1;
  97. }
  98. fprintf(stdout, "NAND block/erase size is: %u\n", nandinfo.erasesize);
  99. fprintf(stdout, "NAND page size is: %u\n", nandinfo.writesize);
  100. fprintf(stdout, "NAND OOB size is: %u\n", nandinfo.oobsize);
  101. fprintf(stdout, "NAND partition size is: %u\n", nandinfo.size);
  102. for (offset = 0; offset < nandinfo.size; offset += nandinfo.erasesize) {
  103. ret = ioctl(fd, MEMGETBADBLOCK, &offset);
  104. if (ret > 0) {
  105. printf("\nSkipping bad block at %llu\n", offset);
  106. continue;
  107. } else if (ret < 0) {
  108. if (errno == EOPNOTSUPP) {
  109. fprintf(stderr, "Bad block check not available\n");
  110. return 1;
  111. }
  112. }
  113. }
  114. return 0;
  115. }
  116. int nand_erase(const char *nand) {
  117. mtd_info_t meminfo;
  118. struct nand_oobinfo oobinfo;
  119. int fd, clmpos, clmlen;
  120. erase_info_t erase;
  121. clmpos = 0;
  122. clmlen = 8;
  123. erase_buffer(oobbuf, sizeof(oobbuf));
  124. if ((fd = nand_open(nand, O_RDWR)) < 0) {
  125. fprintf(stderr, "nand: %s: unable to open MTD device\n", nand);
  126. return 1;
  127. }
  128. if (ioctl(fd, MEMGETINFO, &meminfo) != 0) {
  129. fprintf(stderr, "nand: %s: unable to get MTD device info\n", nand);
  130. return 1;
  131. }
  132. erase.length = meminfo.erasesize;
  133. for (erase.start = 0; erase.start < meminfo.size; erase.start += meminfo.erasesize) {
  134. if (ioctl(fd, MEMERASE, &erase) != 0) {
  135. fprintf(stderr, "\nnand: %s: MTD Erase failure: %s\n", nand, strerror(errno));
  136. continue;
  137. }
  138. struct mtd_oob_buf oob;
  139. if (ioctl(fd, MEMGETOOBSEL, &oobinfo) != 0) {
  140. fprintf(stderr, "Unable to get NAND oobinfo\n");
  141. return 1;
  142. }
  143. if (oobinfo.useecc != MTD_NANDECC_AUTOPLACE) {
  144. fprintf(stderr, "NAND device/driver does not support autoplacement of OOB\n");
  145. return 1;
  146. }
  147. if (!oobinfo.oobfree[0][1]) {
  148. fprintf(stderr, "Autoplacement selected and no empty space in oob\n");
  149. return 1;
  150. }
  151. clmpos = oobinfo.oobfree[0][0];
  152. clmlen = oobinfo.oobfree[0][1];
  153. if (clmlen > 8)
  154. clmlen = 8;
  155. //fprintf(stdout, "Using clmlen: %d clmpos: %d\n", clmlen, clmpos);
  156. oob.ptr = oobbuf;
  157. oob.start = erase.start + clmpos;
  158. oob.length = clmlen;
  159. if (ioctl (fd, MEMWRITEOOB, &oob) != 0) {
  160. fprintf(stderr, "\nnand: %s: MTD writeoob failure: %s\n", nand, strerror(errno));
  161. continue;
  162. }
  163. }
  164. return 0;
  165. }
  166. int nand_write(const char *img, const char *nand, int quiet) {
  167. static bool pad = true;
  168. static const char *standard_input = "-";
  169. static bool markbad = true;
  170. static int mtdoffset = 0;
  171. int cnt = 0;
  172. int fd = -1;
  173. int ifd = -1;
  174. int imglen = 0, pagelen;
  175. bool baderaseblock = false;
  176. int blockstart = -1;
  177. struct mtd_info_user meminfo;
  178. struct mtd_oob_buf oob;
  179. loff_t offs;
  180. int ret, readlen;
  181. erase_buffer(oobbuf, sizeof(oobbuf));
  182. /* Open the device */
  183. if ((fd = nand_open(nand, O_RDWR | O_SYNC)) == -1) {
  184. perror(nand);
  185. exit (EXIT_FAILURE);
  186. }
  187. /* Fill in MTD device capability structure */
  188. if (ioctl(fd, MEMGETINFO, &meminfo) != 0) {
  189. perror("MEMGETINFO");
  190. close(fd);
  191. exit (EXIT_FAILURE);
  192. }
  193. /* Make sure device page sizes are valid */
  194. if (!(meminfo.oobsize == 16 && meminfo.writesize == 512) &&
  195. !(meminfo.oobsize == 8 && meminfo.writesize == 256) &&
  196. !(meminfo.oobsize == 64 && meminfo.writesize == 2048) &&
  197. !(meminfo.oobsize == 128 && meminfo.writesize == 4096)) {
  198. fprintf(stderr, "Unknown flash (not normal NAND)\n");
  199. close(fd);
  200. exit (EXIT_FAILURE);
  201. }
  202. oob.length = meminfo.oobsize;
  203. oob.ptr = oobbuf;
  204. /* Determine if we are reading from standard input or from a file. */
  205. if (strcmp(img, standard_input) == 0) {
  206. ifd = STDIN_FILENO;
  207. } else {
  208. ifd = open(img, O_RDONLY);
  209. }
  210. if (ifd == -1) {
  211. perror(img);
  212. goto restoreoob;
  213. }
  214. pagelen = meminfo.writesize;
  215. /*
  216. * For the standard input case, the input size is merely an
  217. * invariant placeholder and is set to the write page
  218. * size. Otherwise, just use the input file size.
  219. */
  220. if (ifd == STDIN_FILENO) {
  221. imglen = pagelen;
  222. } else {
  223. imglen = lseek(ifd, 0, SEEK_END);
  224. lseek (ifd, 0, SEEK_SET);
  225. }
  226. // Check, if file is page-aligned
  227. if ((!pad) && ((imglen % pagelen) != 0)) {
  228. fprintf (stderr, "Input file is not page-aligned. Use the padding "
  229. "option.\n");
  230. goto closeall;
  231. }
  232. // Check, if length fits into device
  233. if ( ((imglen / pagelen) * meminfo.writesize) > (meminfo.size - mtdoffset)) {
  234. fprintf (stderr, "Image %d bytes, NAND page %d bytes, OOB area %u bytes, device size %u bytes\n",
  235. imglen, pagelen, meminfo.writesize, meminfo.size);
  236. perror ("Input file does not fit into device");
  237. goto closeall;
  238. }
  239. /*
  240. * Get data from input and write to the device while there is
  241. * still input to read and we are still within the device
  242. * bounds. Note that in the case of standard input, the input
  243. * length is simply a quasi-boolean flag whose values are page
  244. * length or zero.
  245. */
  246. while (imglen && (mtdoffset < meminfo.size)) {
  247. // new eraseblock , check for bad block(s)
  248. // Stay in the loop to be sure if the mtdoffset changes because
  249. // of a bad block, that the next block that will be written to
  250. // is also checked. Thus avoiding errors if the block(s) after the
  251. // skipped block(s) is also bad
  252. while (blockstart != (mtdoffset & (~meminfo.erasesize + 1))) {
  253. blockstart = mtdoffset & (~meminfo.erasesize + 1);
  254. offs = blockstart;
  255. baderaseblock = false;
  256. if (quiet < 2)
  257. fprintf (stdout, "Writing data to block %d at offset 0x%x\n",
  258. blockstart / meminfo.erasesize, blockstart);
  259. /* Check all the blocks in an erase block for bad blocks */
  260. do {
  261. if ((ret = ioctl(fd, MEMGETBADBLOCK, &offs)) < 0) {
  262. perror("ioctl(MEMGETBADBLOCK)");
  263. goto closeall;
  264. }
  265. if (ret == 1) {
  266. baderaseblock = true;
  267. if (!quiet)
  268. fprintf (stderr, "Bad block at %x "
  269. "from %x will be skipped\n",
  270. (int) offs, blockstart);
  271. }
  272. if (baderaseblock) {
  273. mtdoffset = blockstart + meminfo.erasesize;
  274. }
  275. offs += meminfo.erasesize;
  276. } while ( offs < blockstart + meminfo.erasesize );
  277. }
  278. readlen = meminfo.writesize;
  279. if (ifd != STDIN_FILENO) {
  280. int tinycnt = 0;
  281. if (pad && (imglen < readlen))
  282. {
  283. readlen = imglen;
  284. erase_buffer(writebuf + readlen, meminfo.writesize - readlen);
  285. }
  286. /* Read Page Data from input file */
  287. while(tinycnt < readlen) {
  288. cnt = read(ifd, writebuf + tinycnt, readlen - tinycnt);
  289. if (cnt == 0) { // EOF
  290. break;
  291. } else if (cnt < 0) {
  292. perror ("File I/O error on input file");
  293. goto closeall;
  294. }
  295. tinycnt += cnt;
  296. }
  297. } else {
  298. int tinycnt = 0;
  299. while(tinycnt < readlen) {
  300. cnt = read(ifd, writebuf + tinycnt, readlen - tinycnt);
  301. if (cnt == 0) { // EOF
  302. break;
  303. } else if (cnt < 0) {
  304. perror ("File I/O error on stdin");
  305. goto closeall;
  306. }
  307. tinycnt += cnt;
  308. }
  309. /* No padding needed - we are done */
  310. if (tinycnt == 0) {
  311. imglen = 0;
  312. break;
  313. }
  314. /* No more bytes - we are done after writing the remaining bytes */
  315. if (cnt == 0) {
  316. imglen = 0;
  317. }
  318. /* Padding */
  319. if (pad && (tinycnt < readlen)) {
  320. erase_buffer(writebuf + tinycnt, meminfo.writesize - tinycnt);
  321. }
  322. }
  323. /* Write out the Page data */
  324. if (pwrite(fd, writebuf, meminfo.writesize, mtdoffset) != meminfo.writesize) {
  325. int rewind_blocks;
  326. off_t rewind_bytes;
  327. erase_info_t erase;
  328. perror ("pwrite");
  329. /* Must rewind to blockstart if we can */
  330. rewind_blocks = (mtdoffset - blockstart) / meminfo.writesize; /* Not including the one we just attempted */
  331. rewind_bytes = (rewind_blocks * meminfo.writesize) + readlen;
  332. if (lseek(ifd, -rewind_bytes, SEEK_CUR) == -1) {
  333. perror("lseek");
  334. fprintf(stderr, "Failed to seek backwards to recover from write error\n");
  335. goto closeall;
  336. }
  337. erase.start = blockstart;
  338. erase.length = meminfo.erasesize;
  339. fprintf(stderr, "Erasing failed write from %08lx-%08lx\n",
  340. (long)erase.start, (long)erase.start+erase.length-1);
  341. if (ioctl(fd, MEMERASE, &erase) != 0) {
  342. perror("MEMERASE");
  343. goto closeall;
  344. }
  345. if (markbad) {
  346. loff_t bad_addr = mtdoffset & (~(meminfo.erasesize) + 1);
  347. fprintf(stderr, "Marking block at %08lx bad\n", (long)bad_addr);
  348. if (ioctl(fd, MEMSETBADBLOCK, &bad_addr)) {
  349. perror("MEMSETBADBLOCK");
  350. /* But continue anyway */
  351. }
  352. }
  353. mtdoffset = blockstart + meminfo.erasesize;
  354. imglen += rewind_blocks * meminfo.writesize;
  355. continue;
  356. }
  357. if (ifd != STDIN_FILENO) {
  358. imglen -= readlen;
  359. }
  360. mtdoffset += meminfo.writesize;
  361. }
  362. closeall:
  363. close(ifd);
  364. restoreoob:
  365. close(fd);
  366. /*
  367. if ((ifd != STDIN_FILENO) && (imglen > 0)) {
  368. perror ("Data was only partially written due to error\n");
  369. exit (EXIT_FAILURE);
  370. }
  371. /* Return happy */
  372. return EXIT_SUCCESS;
  373. }
  374. void
  375. usage(void)
  376. {
  377. fprintf(stderr, "Usage: nand [<options> ...] <command> [<arguments> ...] <device>\n\n"
  378. "The device is in the format of mtdX (eg: mtd4) or its label.\n"
  379. "nand recognises these commands:\n"
  380. " erase erase all data on device\n"
  381. " info print information about device\n"
  382. " write <imagefile>|- write <imagefile> (use - for stdin) to device\n"
  383. "Following options are available:\n"
  384. " -q quiet mode\n"
  385. " -r reboot after successful command\n"
  386. "Example: To write linux.img to mtd partition labeled as linux\n"
  387. " nand write linux.img linux\n\n");
  388. exit(1);
  389. }
  390. int main(int argc, char **argv) {
  391. int ch, quiet, boot;
  392. char *device;
  393. enum {
  394. CMD_INFO,
  395. CMD_ERASE,
  396. CMD_WRITE,
  397. } cmd;
  398. boot = 0;
  399. quiet = 0;
  400. while ((ch = getopt(argc, argv, "Fqr:")) != -1)
  401. switch (ch) {
  402. case 'F':
  403. quiet = 1;
  404. /* FALLTHROUGH */
  405. case 'q':
  406. quiet++;
  407. break;
  408. case 'r':
  409. boot = 1;
  410. break;
  411. case '?':
  412. default:
  413. usage();
  414. }
  415. argc -= optind;
  416. argv += optind;
  417. if (argc < 2)
  418. usage();
  419. if ((strcmp(argv[0], "erase") == 0) && (argc == 2)) {
  420. cmd = CMD_ERASE;
  421. device = argv[1];
  422. } else if ((strcmp(argv[0], "info") == 0) && (argc == 2)) {
  423. cmd = CMD_INFO;
  424. device = argv[1];
  425. } else if ((strcmp(argv[0], "write") == 0) && (argc == 3)) {
  426. cmd = CMD_WRITE;
  427. device = argv[2];
  428. } else {
  429. usage();
  430. }
  431. sync();
  432. switch (cmd) {
  433. case CMD_INFO:
  434. if (quiet < 2)
  435. fprintf(stderr, "Info about %s ...\n", device);
  436. nand_info(device);
  437. break;
  438. case CMD_ERASE:
  439. if (quiet < 2)
  440. fprintf(stderr, "Erasing %s ...\n", device);
  441. nand_erase(device);
  442. break;
  443. case CMD_WRITE:
  444. if (quiet < 2)
  445. fprintf(stderr, "Writing from %s to %s ... ", argv[1], device);
  446. nand_erase(device);
  447. nand_write(argv[1], device, quiet);
  448. if (quiet < 2)
  449. fprintf(stderr, "\n");
  450. break;
  451. }
  452. sync();
  453. if (boot) {
  454. fprintf(stderr, "\nRebooting ... ");
  455. fflush(stdout);
  456. fflush(stderr);
  457. syscall(SYS_reboot,LINUX_REBOOT_MAGIC1,LINUX_REBOOT_MAGIC2,LINUX_REBOOT_CMD_RESTART,NULL);
  458. }
  459. return 0;
  460. }