ecp.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /*
  2. * ecp - copy a file fast (in big blocks), cope with errors, optionally verify.
  3. *
  4. * Transfers a block at a time. On error, retries one sector at a time,
  5. * and reports all errors on the retry.
  6. * Unlike dd, ecp ignores EOF, since it is sometimes reported on error.
  7. * Also unlike `dd conv=noerror,sync', ecp doesn't get stuck nor give up.
  8. *
  9. * Written by Geoff Collyer, originally to run on RSX-11M(!) in 1979.
  10. * Later simplified for UNIX and ultimately Plan 9.
  11. */
  12. #include <u.h>
  13. #include <libc.h>
  14. #include <ctype.h>
  15. /* fundamental constants */
  16. enum {
  17. No = 0,
  18. Yes,
  19. Noseek = 0, /* need not seek, may seek on seekable files */
  20. Mustseek,
  21. Enone = 0,
  22. Eio,
  23. };
  24. /* tunable parameters */
  25. enum {
  26. Defsectsz = 512, /* default sector size */
  27. /* 10K is a good size for HP WORM drives */
  28. Defblksz = 16*1024, /* default block (big-transfer) size */
  29. Mingoodblks = 3, /* after this many, go back to fast mode */
  30. };
  31. #define TTY "/dev/cons" /* plan 9 */
  32. #define badsect(errno) ((errno) != Enone) /* was last transfer in error? */
  33. /* disk address (in bytes or sectors), also type of 2nd arg. to seek */
  34. typedef uvlong Daddr;
  35. typedef vlong Sdaddr; /* signed disk address */
  36. typedef long Rdwrfn(int, void *, long); /* plan 9 read or write */
  37. typedef struct {
  38. char *name;
  39. int fd;
  40. Daddr startsect;
  41. int fast;
  42. int seekable;
  43. ulong maxconerrs; /* maximum consecutive errors */
  44. ulong conerrs; /* current consecutive errors */
  45. Daddr congoodblks;
  46. Daddr harderrs;
  47. Daddr lasterr; /* sector #s */
  48. Daddr lastgood;
  49. } File;
  50. /* exports */
  51. char *argv0;
  52. /* privates */
  53. static int reblock = No, progress = No, swizzle = No;
  54. static int reverse = No;
  55. static ulong sectsz = Defsectsz;
  56. static ulong blocksize = Defblksz;
  57. static char *buf, *vfybuf;
  58. static int blksects;
  59. /*
  60. * warning - print best error message possible and clear errno
  61. */
  62. void
  63. warning(char *s1, char *s2)
  64. {
  65. char err[100], msg[256];
  66. char *np, *ep = msg + sizeof msg - 1;
  67. errstr(err, sizeof err); /* save error string */
  68. np = seprint(msg, ep, "%s: ", argv0);
  69. np = seprint(np, ep, s1, s2);
  70. errstr(err, sizeof err); /* restore error string */
  71. seprint(np, ep, ": %r\n");
  72. fprint(2, "%s", msg);
  73. }
  74. int
  75. eopen(char *file, int mode)
  76. {
  77. int fd = open(file, mode);
  78. if (fd < 0)
  79. sysfatal("can't open %s: %r", file);
  80. return fd;
  81. }
  82. static int /* boolean */
  83. confirm(File *src, File *dest)
  84. {
  85. int absent, n, tty = eopen(TTY, 2);
  86. char c, junk;
  87. Dir *stp;
  88. if ((stp = dirstat(src->name)) == nil)
  89. sysfatal("no input file %s: %r", src->name);
  90. free(stp);
  91. stp = dirstat(dest->name);
  92. absent = (stp == nil);
  93. free(stp);
  94. fprint(2, "%s: copy %s to %s%s? ", argv0, src->name, dest->name,
  95. (absent? " (missing)": ""));
  96. n = read(tty, &c, 1);
  97. junk = c;
  98. if (n < 1)
  99. c = 'n';
  100. while (n > 0 && junk != '\n')
  101. n = read(tty, &junk, 1);
  102. close(tty);
  103. if (isascii(c) && isupper(c))
  104. c = tolower(c);
  105. return c == 'y';
  106. }
  107. static char *
  108. sectid(File *fp, Daddr sect)
  109. {
  110. static char sectname[256];
  111. if (fp->startsect == 0)
  112. snprint(sectname, sizeof sectname, "%s sector %llud",
  113. fp->name, sect);
  114. else
  115. snprint(sectname, sizeof sectname,
  116. "%s sector %llud (relative %llud)",
  117. fp->name, sect + fp->startsect, sect);
  118. return sectname;
  119. }
  120. static void
  121. io_expl(File *fp, char *rw, Daddr sect) /* explain an i/o error */
  122. {
  123. /* print only first 2 bad sectors in a range, if going forward */
  124. if (reverse || fp->conerrs == 0) {
  125. char msg[128];
  126. snprint(msg, sizeof msg, "%s %s", rw, sectid(fp, sect));
  127. warning("%s", msg);
  128. } else if (fp->conerrs == 1)
  129. fprint(2, "%s: ...\n", argv0);
  130. }
  131. static void
  132. repos(File *fp, Daddr sect)
  133. {
  134. if (!fp->seekable)
  135. sysfatal("%s: trying to seek on unseekable file", fp->name);
  136. if (seek(fp->fd, (sect+fp->startsect)*sectsz, 0) == -1)
  137. sysfatal("can't seek on %s: %r", fp->name);
  138. }
  139. static void
  140. rewind(File *fp)
  141. {
  142. repos(fp, 0);
  143. }
  144. static char magic[] = "\235any old ☺ rubbish\173";
  145. static char uniq[sizeof magic + 2*sizeof(ulong)];
  146. static char *
  147. putbe(char *p, ulong ul)
  148. {
  149. *p++ = ul>>24;
  150. *p++ = ul>>16;
  151. *p++ = ul>>8;
  152. *p++ = ul;
  153. return p;
  154. }
  155. /*
  156. * generate magic + unique string, add to start & end of buff.
  157. * return tail pointer.
  158. */
  159. static char *
  160. addmagic(char *buff, int bytes)
  161. {
  162. char *p, *tail;
  163. static ulong seq;
  164. strcpy(uniq, magic);
  165. p = putbe(uniq + sizeof magic - 1, time(0));
  166. putbe(p, ++seq);
  167. memcpy(buff, uniq, sizeof uniq);
  168. tail = buff + bytes - sizeof uniq;
  169. memcpy(tail, uniq, sizeof uniq);
  170. return tail;
  171. }
  172. /* verify magic + unique strings in buff */
  173. static int
  174. ismagicok(char *buff, char *tail)
  175. {
  176. return memcmp(buff, uniq, sizeof uniq) == 0 ||
  177. memcmp(tail, uniq, sizeof uniq) == 0;
  178. }
  179. /*
  180. * transfer (many) sectors. reblock input as needed.
  181. * returns Enone if no failures, others on failure with errstr set.
  182. */
  183. static int
  184. bio(File *fp, Rdwrfn *rdwr, char *buff, Daddr stsect, int sects, int mustseek)
  185. {
  186. int xfered;
  187. char *tail;
  188. ulong toread, bytes = sects * sectsz;
  189. static int reblocked = 0;
  190. if (mustseek) {
  191. if (!fp->seekable)
  192. sysfatal("%s: need to seek on unseekable file",
  193. fp->name);
  194. repos(fp, stsect);
  195. }
  196. if ((long)blocksize != blocksize || (long)bytes != bytes)
  197. sysfatal("i/o count too big: %lud", bytes);
  198. SET(tail);
  199. if (rdwr == read)
  200. tail = addmagic(buff, bytes);
  201. werrstr("");
  202. xfered = (*rdwr)(fp->fd, buff, bytes);
  203. if (xfered == bytes) {
  204. /* don't trust the hardware; it may lie */
  205. if (rdwr == read && ismagicok(buff, tail))
  206. fprint(2, "%s: `good' read didn't change buffer\n",
  207. argv0);
  208. return Enone; /* did as we asked */
  209. }
  210. if (xfered < 0)
  211. return Eio; /* out-and-out i/o error */
  212. /*
  213. * Kernel transferred less than asked. Shouldn't happen;
  214. * probably indicates disk driver error or trying to
  215. * transfer past the end of a disk partition. Treat as an
  216. * I/O error that reads zeros past the point of error,
  217. * unless reblocking input and this is a read.
  218. */
  219. if (rdwr == write)
  220. return Eio;
  221. if (!reblock) {
  222. memset(buff+xfered, '\0', bytes-xfered);
  223. return Eio; /* short read */
  224. }
  225. /* for pipes that return less than asked */
  226. if (progress && !reblocked) {
  227. fprint(2, "%s: reblocking input\n", argv0);
  228. reblocked++;
  229. }
  230. for (toread = bytes - xfered; toread != 0; toread -= xfered) {
  231. xfered = (*rdwr)(fp->fd, buff+bytes-toread, toread);
  232. if (xfered <= 0)
  233. break;
  234. }
  235. if (xfered < 0)
  236. return Eio; /* out-and-out i/o error */
  237. if (toread != 0) /* early EOF? */
  238. memset(buff+bytes-toread, '\0', toread);
  239. return Enone;
  240. }
  241. /* called only after a single-sector transfer */
  242. static int
  243. toomanyerrs(File *fp, Daddr sect)
  244. {
  245. if (sect == fp->lasterr+1)
  246. fp->conerrs++;
  247. else
  248. fp->conerrs = 0;
  249. fp->lasterr = sect;
  250. return fp->maxconerrs != 0 && fp->conerrs >= fp->maxconerrs &&
  251. fp->lastgood == -1;
  252. }
  253. static void
  254. ckendrange(File *fp)
  255. {
  256. if (!reverse && fp->conerrs > 0)
  257. fprint(2, "%s: %lld: ... last bad sector in range\n",
  258. argv0, fp->lasterr);
  259. }
  260. static int
  261. transfer(File *fp, Rdwrfn *rdwr, char *buff, Daddr stsect, int sects,
  262. int mustseek)
  263. {
  264. int res = bio(fp, rdwr, buff, stsect, sects, mustseek);
  265. if (badsect(res)) {
  266. fp->fast = 0; /* read single sectors for a while */
  267. fp->congoodblks = 0;
  268. } else
  269. fp->lastgood = stsect + sects - 1;
  270. return res;
  271. }
  272. /*
  273. * Read or write many sectors at once.
  274. * If it fails, retry the individual sectors and report errors.
  275. */
  276. static void
  277. bigxfer(File *fp, Rdwrfn *rdwr, char *buff, Daddr stsect, int sects,
  278. int mustseek)
  279. {
  280. int i, badsects = 0, wasfast = fp->fast;
  281. char *rw = (rdwr == read? "read": "write");
  282. if (fp->fast) {
  283. if (!badsect(transfer(fp, rdwr, buff, stsect, sects, mustseek)))
  284. return;
  285. if (progress)
  286. fprint(2, "%s: breaking up big transfer on %s error "
  287. "`%r' on %s\n", argv0, rw, sectid(fp, stsect));
  288. }
  289. for (i = 0; i < sects; i++)
  290. if (badsect(transfer(fp, rdwr, buff+i*sectsz, stsect+i, 1,
  291. Mustseek))) {
  292. io_expl(fp, rw, stsect+i);
  293. badsects++;
  294. fp->harderrs++;
  295. if (toomanyerrs(fp, stsect+i))
  296. sysfatal("more than %lud consecutive I/O errors",
  297. fp->maxconerrs);
  298. } else {
  299. ckendrange(fp);
  300. fp->conerrs = 0;
  301. }
  302. if (badsects == 0) {
  303. ckendrange(fp);
  304. fp->conerrs = 0;
  305. if (wasfast)
  306. fprint(2, "%s: %s error on big transfer at %s but none "
  307. "on retries!\n", argv0, rw, sectid(fp, stsect));
  308. ++fp->congoodblks;
  309. if (fp->congoodblks >= Mingoodblks) {
  310. fprint(2, "%s: %s: back to big transfers\n", argv0,
  311. fp->name);
  312. fp->fast = 1;
  313. }
  314. } else
  315. /*
  316. * the last sector could have been in error, so the seek pointer
  317. * may need to be corrected.
  318. */
  319. repos(fp, stsect + sects);
  320. }
  321. static void
  322. vrfyfailed(File *src, File *dest, Daddr stsect)
  323. {
  324. char *srcsect = strdup(sectid(src, stsect));
  325. fprint(2, "%s: verify failed at %s (%s)\n", argv0, srcsect,
  326. sectid(dest, stsect));
  327. free(srcsect);
  328. }
  329. /*
  330. * I've seen SCSI read errors that the kernel printed but then didn't
  331. * report to the program doing the read, so if a big verify fails,
  332. * break it up and verify each sector separately to isolate the bad sector(s).
  333. */
  334. int /* error count */
  335. verify(File *src, File *dest, char *buff, char *buft, Daddr stsect,
  336. int sectors)
  337. {
  338. int i, errors = 0;
  339. for (i = 0; i < sectors; i++)
  340. if (memcmp(buff + i*sectsz, buft + i*sectsz, sectsz) != 0)
  341. errors++;
  342. if (errors == 0)
  343. return errors; /* normal case */
  344. if (sectors == 1) {
  345. vrfyfailed(src, dest, stsect);
  346. return errors;
  347. }
  348. /* re-read and verify each sector individually */
  349. errors = 0;
  350. for (i = 0; i < sectors; i++) {
  351. int thissect = stsect + i;
  352. if (badsect(bio(src, read, buff, thissect, 1, Mustseek)))
  353. io_expl(src, "read", thissect);
  354. if (badsect(bio(dest, read, buft, thissect, 1, Mustseek)))
  355. io_expl(dest, "write", thissect);
  356. if (memcmp(buff, buft, sectsz) != 0) {
  357. vrfyfailed(src, dest, thissect);
  358. ++errors;
  359. }
  360. }
  361. if (errors == 0) {
  362. char *srcsect = strdup(sectid(src, stsect));
  363. fprint(2, "%s: verification failed on big read at %s (%s) "
  364. "but not on retries!\n", argv0, srcsect,
  365. sectid(dest, stsect));
  366. free(srcsect);
  367. }
  368. /*
  369. * the last sector of each could have been in error, so the seek
  370. * pointers may need to be corrected.
  371. */
  372. repos(src, stsect + sectors);
  373. repos(dest, stsect + sectors);
  374. return errors;
  375. }
  376. /*
  377. * start is starting sector of proposed transfer;
  378. * nsects is the total number of sectors being copied;
  379. * maxxfr is the block size in sectors.
  380. */
  381. int
  382. sectsleft(Daddr start, Daddr nsects, int maxxfr)
  383. {
  384. /* nsects-start is sectors to the end */
  385. if (start + maxxfr <= nsects - 1)
  386. return maxxfr;
  387. else
  388. return nsects - start;
  389. }
  390. enum {
  391. Rotbits = 3,
  392. };
  393. void
  394. swizzlebits(char *buff, int sects)
  395. {
  396. uchar *bp, *endbp;
  397. endbp = (uchar *)(buff+sects*sectsz);
  398. for (bp = (uchar *)buff; bp < endbp; bp++)
  399. *bp = ~(*bp>>Rotbits | *bp<<(8-Rotbits));
  400. }
  401. /*
  402. * copy at most blksects sectors, with error retries.
  403. * stsect is relative to the start of the copy; 0 is the first sector.
  404. * to get actual sector numbers, add e.g. dest->startsect.
  405. */
  406. static int
  407. copysects(File *src, File *dest, Daddr stsect, Daddr nsects, int mustseek)
  408. {
  409. int xfrsects = sectsleft(stsect, nsects, blksects);
  410. if (xfrsects > blksects) {
  411. fprint(2, "%s: block size of %d is too big.\n", argv0, xfrsects);
  412. exits("block size too big");
  413. }
  414. bigxfer(src, read, buf, stsect, xfrsects, mustseek);
  415. if (swizzle)
  416. swizzlebits(buf, xfrsects);
  417. bigxfer(dest, write, buf, stsect, xfrsects, mustseek);
  418. /* give a few reassurances at the start, then every 10MB */
  419. if (progress &&
  420. (stsect < blksects*10 || stsect%(10*1024*1024/sectsz) == 0))
  421. fprint(2, "%s: copied%s to relative sector %llud\n", argv0,
  422. (swizzle? " swizzled": ""), stsect + xfrsects - 1);
  423. return 0;
  424. }
  425. /*
  426. * verify at most blksects sectors, with error retries.
  427. * return error count.
  428. */
  429. static int
  430. vrfysects(File *src, File *dest, Daddr stsect, Daddr nsects, int mustseek)
  431. {
  432. int xfrsects = sectsleft(stsect, nsects, blksects);
  433. if (xfrsects > blksects) {
  434. fprint(2, "%s: block size of %d is too big.\n", argv0, xfrsects);
  435. exits("block size too big");
  436. }
  437. bigxfer(src, read, buf, stsect, xfrsects, mustseek);
  438. bigxfer(dest, read, vfybuf, stsect, xfrsects, mustseek);
  439. return verify(src, dest, buf, vfybuf, stsect, xfrsects);
  440. }
  441. static void
  442. setupfile(File *fp, int mode)
  443. {
  444. fp->fd = open(fp->name, mode);
  445. if (fp->fd < 0)
  446. sysfatal("can't open %s: %r", fp->name);
  447. fp->seekable = (seek(fp->fd, 0, 1) >= 0);
  448. if (fp->startsect != 0)
  449. rewind(fp);
  450. }
  451. static Daddr
  452. copyfile(File *src, File *dest, Daddr nsects, int plsverify)
  453. {
  454. Sdaddr stsect, vererrs = 0;
  455. Dir *stp;
  456. setupfile(src, OREAD);
  457. if ((stp = dirstat(dest->name)) == nil) {
  458. int fd = create(dest->name, ORDWR, 0666);
  459. if (fd >= 0)
  460. close(fd);
  461. }
  462. free(stp);
  463. setupfile(dest, ORDWR);
  464. if (progress)
  465. fprint(2, "%s: copying first sectors\n", argv0);
  466. if (reverse)
  467. for (stsect = (nsects/blksects)*blksects; stsect >= 0;
  468. stsect -= blksects)
  469. vererrs += copysects(src, dest, stsect, nsects, Mustseek);
  470. else {
  471. for (stsect = 0; stsect < nsects; stsect += blksects)
  472. vererrs += copysects(src, dest, stsect, nsects, Noseek);
  473. ckendrange(src);
  474. ckendrange(dest);
  475. }
  476. /*
  477. * verification is done as a separate pass rather than immediately after
  478. * writing, in part to defeat caching in clever disk controllers.
  479. * we really want to see the bits that hit the disk.
  480. */
  481. if (plsverify) {
  482. fprint(2, "%s: copy done; verifying...\n", argv0);
  483. rewind(src);
  484. rewind(dest);
  485. for (stsect = 0; stsect < nsects; stsect += blksects) /* forward */
  486. vererrs += vrfysects(src, dest, stsect, nsects, Noseek);
  487. if (vererrs <= 0)
  488. fprint(2, "%s: no", argv0);
  489. else
  490. fprint(2, "%s: %llud", argv0, vererrs);
  491. fprint(2, " error%s during verification\n",
  492. (vererrs != 1? "s": ""));
  493. }
  494. close(src->fd);
  495. close(dest->fd);
  496. return vererrs;
  497. }
  498. static void
  499. usage(void)
  500. {
  501. fprint(2, "usage: %s [-bcprvZ][-B blocksz][-e errs][-s sectsz]"
  502. "[-i issect][-o ossect] sectors from to\n", argv0);
  503. exits("usage");
  504. }
  505. void
  506. initfile(File *fp)
  507. {
  508. memset(fp, 0, sizeof *fp);
  509. fp->fast = 1;
  510. fp->lasterr = -1;
  511. fp->lastgood = -1;
  512. }
  513. void
  514. main(int argc, char **argv)
  515. {
  516. int errflg = 0, plsconfirm = No, plsverify = No;
  517. long lval;
  518. File src, dest;
  519. Sdaddr sect;
  520. initfile(&src);
  521. initfile(&dest);
  522. ARGBEGIN {
  523. case 'b':
  524. reblock = Yes;
  525. break;
  526. case 'B':
  527. lval = atol(EARGF(usage()));
  528. if (lval < 0)
  529. usage();
  530. blocksize = lval;
  531. break;
  532. case 'c':
  533. plsconfirm = Yes;
  534. break;
  535. case 'e':
  536. lval = atol(EARGF(usage()));
  537. if (lval < 0)
  538. usage();
  539. src.maxconerrs = lval;
  540. dest.maxconerrs = lval;
  541. break;
  542. case 'i':
  543. sect = atoll(EARGF(usage()));
  544. if (sect < 0)
  545. usage();
  546. src.startsect = sect;
  547. break;
  548. case 'o':
  549. sect = atoll(EARGF(usage()));
  550. if (sect < 0)
  551. usage();
  552. dest.startsect = sect;
  553. break;
  554. case 'p':
  555. progress = Yes;
  556. break;
  557. case 'r':
  558. reverse = Yes;
  559. break;
  560. case 's':
  561. sectsz = atol(EARGF(usage()));
  562. if (sectsz <= 0 || sectsz % 512 != 0)
  563. usage();
  564. break;
  565. case 'v':
  566. plsverify = Yes;
  567. break;
  568. case 'Z':
  569. swizzle = Yes;
  570. break;
  571. default:
  572. errflg++;
  573. break;
  574. } ARGEND
  575. if (errflg || argc != 3)
  576. usage();
  577. if (blocksize <= 0 || blocksize % sectsz != 0)
  578. sysfatal("block size not a multiple of sector size");
  579. if (!isascii(argv[0][0]) || !isdigit(argv[0][0])) {
  580. fprint(2, "%s: %s is not numeric\n", argv0, argv[0]);
  581. exits("non-numeric sector count");
  582. }
  583. src.name = argv[1];
  584. dest.name = argv[2];
  585. blksects = blocksize / sectsz;
  586. if (blksects < 1)
  587. blksects = 1;
  588. buf = malloc(blocksize);
  589. vfybuf = malloc(blocksize);
  590. if (buf == nil || vfybuf == nil)
  591. sysfatal("out of memory: %r");
  592. if (plsconfirm? confirm(&src, &dest): Yes)
  593. copyfile(&src, &dest, atoll(argv[0]), plsverify);
  594. exits(src.harderrs || dest.harderrs? "hard errors": 0);
  595. }