fat.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /* fat.c - Read/write access to the FAT
  2. Copyright (C) 1993 Werner Almesberger <werner.almesberger@lrc.di.epfl.ch>
  3. Copyright (C) 1998 Roman Hodek <Roman.Hodek@informatik.uni-erlangen.de>
  4. Copyright (C) 2008-2013 Daniel Baumann <mail@daniel-baumann.ch>
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. On Debian systems, the complete text of the GNU General Public License
  16. can be found in /usr/share/common-licenses/GPL-3 file.
  17. */
  18. /* FAT32, VFAT, Atari format support, and various fixes additions May 1998
  19. * by Roman Hodek <Roman.Hodek@informatik.uni-erlangen.de> */
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <unistd.h>
  24. #include "common.h"
  25. #include "dosfsck.h"
  26. #include "io.h"
  27. #include "check.h"
  28. #include "fat.h"
  29. #include "ui.h"
  30. /**
  31. * Fetch the FAT entry for a specified cluster.
  32. *
  33. * @param[out] entry Cluster to which cluster of interest is linked
  34. * @param[in] fat FAT table for the partition
  35. * @param[in] cluster Cluster of interest
  36. * @param[in] fs Information from the FAT boot sectors (bits per FAT entry)
  37. */
  38. void get_fat(FAT_ENTRY * entry, void *fat, unsigned long cluster, DOS_FS * fs)
  39. {
  40. unsigned char *ptr;
  41. switch (fs->fat_bits) {
  42. case 12:
  43. ptr = &((unsigned char *)fat)[cluster * 3 / 2];
  44. entry->value = 0xfff & (cluster & 1 ? (ptr[0] >> 4) | (ptr[1] << 4) :
  45. (ptr[0] | ptr[1] << 8));
  46. break;
  47. case 16:
  48. entry->value = CF_LE_W(((unsigned short *)fat)[cluster]);
  49. break;
  50. case 32:
  51. /* According to M$, the high 4 bits of a FAT32 entry are reserved and
  52. * are not part of the cluster number. So we cut them off. */
  53. {
  54. unsigned long e = CF_LE_L(((unsigned int *)fat)[cluster]);
  55. entry->value = e & 0xfffffff;
  56. entry->reserved = e >> 28;
  57. }
  58. break;
  59. default:
  60. die("Bad FAT entry size: %d bits.", fs->fat_bits);
  61. }
  62. }
  63. /**
  64. * Build a bookkeeping structure from the partition's FAT table.
  65. * If the partition has multiple FATs and they don't agree, try to pick a winner,
  66. * and queue a command to overwrite the loser.
  67. * One error that is fixed here is a cluster that links to something out of range.
  68. *
  69. * @param[inout] fs Information about the filesystem
  70. */
  71. void read_fat(DOS_FS * fs)
  72. {
  73. int eff_size;
  74. unsigned long i;
  75. void *first, *second = NULL;
  76. int first_ok, second_ok;
  77. unsigned long total_num_clusters;
  78. /* Clean up from previous pass */
  79. if (fs->fat)
  80. free(fs->fat);
  81. if (fs->cluster_owner)
  82. free(fs->cluster_owner);
  83. fs->fat = NULL;
  84. fs->cluster_owner = NULL;
  85. total_num_clusters = fs->clusters + 2UL;
  86. eff_size = (total_num_clusters * fs->fat_bits + 7) / 8ULL;
  87. first = alloc(eff_size);
  88. fs_read(fs->fat_start, eff_size, first);
  89. if (fs->nfats > 1) {
  90. second = alloc(eff_size);
  91. fs_read(fs->fat_start + fs->fat_size, eff_size, second);
  92. }
  93. if (second && memcmp(first, second, eff_size) != 0) {
  94. FAT_ENTRY first_media, second_media;
  95. get_fat(&first_media, first, 0, fs);
  96. get_fat(&second_media, second, 0, fs);
  97. first_ok = (first_media.value & FAT_EXTD(fs)) == FAT_EXTD(fs);
  98. second_ok = (second_media.value & FAT_EXTD(fs)) == FAT_EXTD(fs);
  99. if (first_ok && !second_ok) {
  100. printf("FATs differ - using first FAT.\n");
  101. fs_write(fs->fat_start + fs->fat_size, eff_size, first);
  102. }
  103. if (!first_ok && second_ok) {
  104. printf("FATs differ - using second FAT.\n");
  105. fs_write(fs->fat_start, eff_size, second);
  106. memcpy(first, second, eff_size);
  107. }
  108. if (first_ok && second_ok) {
  109. if (interactive) {
  110. printf("FATs differ but appear to be intact. Use which FAT ?\n"
  111. "1) Use first FAT\n2) Use second FAT\n");
  112. if (get_key("12", "?") == '1') {
  113. fs_write(fs->fat_start + fs->fat_size, eff_size, first);
  114. } else {
  115. fs_write(fs->fat_start, eff_size, second);
  116. memcpy(first, second, eff_size);
  117. }
  118. } else {
  119. printf("FATs differ but appear to be intact. Using first "
  120. "FAT.\n");
  121. fs_write(fs->fat_start + fs->fat_size, eff_size, first);
  122. }
  123. }
  124. if (!first_ok && !second_ok) {
  125. printf("Both FATs appear to be corrupt. Giving up.\n");
  126. exit(1);
  127. }
  128. }
  129. if (second) {
  130. free(second);
  131. }
  132. fs->fat = (unsigned char *)first;
  133. fs->cluster_owner = alloc(total_num_clusters * sizeof(DOS_FILE *));
  134. memset(fs->cluster_owner, 0, (total_num_clusters * sizeof(DOS_FILE *)));
  135. /* Truncate any cluster chains that link to something out of range */
  136. for (i = 2; i < fs->clusters + 2; i++) {
  137. ui_print_progress(i - 2, fs->clusters - 2);
  138. FAT_ENTRY curEntry;
  139. get_fat(&curEntry, fs->fat, i, fs);
  140. if (curEntry.value == 1) {
  141. printf("Cluster %ld out of range (1). Setting to EOF.\n", i - 2);
  142. set_fat(fs, i, -1);
  143. }
  144. if (curEntry.value >= fs->clusters + 2 &&
  145. (curEntry.value < FAT_MIN_BAD(fs))) {
  146. printf("Cluster %ld out of range (%ld > %ld). Setting to EOF.\n",
  147. i - 2, curEntry.value, fs->clusters + 2 - 1);
  148. set_fat(fs, i, -1);
  149. }
  150. }
  151. }
  152. /**
  153. * Update the FAT entry for a specified cluster
  154. * (i.e., change the cluster it links to).
  155. * Queue a command to write out this change.
  156. *
  157. * @param[in,out] fs Information about the filesystem
  158. * @param[in] cluster Cluster to change
  159. * @param[in] new Cluster to link to
  160. * Special values:
  161. * 0 == free cluster
  162. * -1 == end-of-chain
  163. * -2 == bad cluster
  164. */
  165. void set_fat(DOS_FS * fs, unsigned long cluster, unsigned long new)
  166. {
  167. unsigned char *data = NULL;
  168. int size;
  169. loff_t offs;
  170. if ((long)new == -1)
  171. new = FAT_EOF(fs);
  172. else if ((long)new == -2)
  173. new = FAT_BAD(fs);
  174. switch (fs->fat_bits) {
  175. case 12:
  176. data = fs->fat + cluster * 3 / 2;
  177. offs = fs->fat_start + cluster * 3 / 2;
  178. if (cluster & 1) {
  179. FAT_ENTRY prevEntry;
  180. get_fat(&prevEntry, fs->fat, cluster - 1, fs);
  181. data[0] = ((new & 0xf) << 4) | (prevEntry.value >> 8);
  182. data[1] = new >> 4;
  183. } else {
  184. FAT_ENTRY subseqEntry;
  185. get_fat(&subseqEntry, fs->fat, cluster + 1, fs);
  186. data[0] = new & 0xff;
  187. data[1] = (new >> 8) | (cluster == fs->clusters - 1 ? 0 :
  188. (0xff & subseqEntry.value) << 4);
  189. }
  190. size = 2;
  191. break;
  192. case 16:
  193. data = fs->fat + cluster * 2;
  194. offs = fs->fat_start + cluster * 2;
  195. *(unsigned short *)data = CT_LE_W(new);
  196. size = 2;
  197. break;
  198. case 32:
  199. {
  200. FAT_ENTRY curEntry;
  201. get_fat(&curEntry, fs->fat, cluster, fs);
  202. data = fs->fat + cluster * 4;
  203. offs = fs->fat_start + cluster * 4;
  204. /* According to M$, the high 4 bits of a FAT32 entry are reserved and
  205. * are not part of the cluster number. So we never touch them. */
  206. *(unsigned long *)data = CT_LE_L((new & 0xfffffff) |
  207. (curEntry.reserved << 28));
  208. size = 4;
  209. }
  210. break;
  211. default:
  212. die("Bad FAT entry size: %d bits.", fs->fat_bits);
  213. }
  214. fs_write(offs, size, data);
  215. if (fs->nfats > 1) {
  216. fs_write(offs + fs->fat_size, size, data);
  217. }
  218. }
  219. int bad_cluster(DOS_FS * fs, unsigned long cluster)
  220. {
  221. FAT_ENTRY curEntry;
  222. get_fat(&curEntry, fs->fat, cluster, fs);
  223. return FAT_IS_BAD(fs, curEntry.value);
  224. }
  225. /**
  226. * Get the cluster to which the specified cluster is linked.
  227. * If the linked cluster is marked bad, abort.
  228. *
  229. * @param[in] fs Information about the filesystem
  230. * @param[in] cluster Cluster to follow
  231. *
  232. * @return -1 'cluster' is at the end of the chain
  233. * @return Other values Next cluster in this chain
  234. */
  235. unsigned long next_cluster(DOS_FS * fs, unsigned long cluster)
  236. {
  237. unsigned long value;
  238. FAT_ENTRY curEntry;
  239. get_fat(&curEntry, fs->fat, cluster, fs);
  240. value = curEntry.value;
  241. if (FAT_IS_BAD(fs, value))
  242. die("Internal error: next_cluster on bad cluster");
  243. return FAT_IS_EOF(fs, value) ? -1 : value;
  244. }
  245. loff_t cluster_start(DOS_FS * fs, unsigned long cluster)
  246. {
  247. return fs->data_start + ((loff_t) cluster -
  248. 2) * (unsigned long long)fs->cluster_size;
  249. }
  250. /**
  251. * Update internal bookkeeping to show that the specified cluster belongs
  252. * to the specified dentry.
  253. *
  254. * @param[in,out] fs Information about the filesystem
  255. * @param[in] cluster Cluster being assigned
  256. * @param[in] owner Information on dentry that owns this cluster
  257. * (may be NULL)
  258. */
  259. void set_owner(DOS_FS * fs, unsigned long cluster, DOS_FILE * owner)
  260. {
  261. if (fs->cluster_owner == NULL)
  262. die("Internal error: attempt to set owner in non-existent table");
  263. if (owner && fs->cluster_owner[cluster]
  264. && (fs->cluster_owner[cluster] != owner))
  265. die("Internal error: attempt to change file owner");
  266. fs->cluster_owner[cluster] = owner;
  267. }
  268. DOS_FILE *get_owner(DOS_FS * fs, unsigned long cluster)
  269. {
  270. if (fs->cluster_owner == NULL)
  271. return NULL;
  272. else
  273. return fs->cluster_owner[cluster];
  274. }
  275. void fix_bad(DOS_FS * fs)
  276. {
  277. unsigned long i;
  278. if (verbose)
  279. printf("Checking for bad clusters.\n");
  280. for (i = 2; i < fs->clusters + 2; i++) {
  281. FAT_ENTRY curEntry;
  282. get_fat(&curEntry, fs->fat, i, fs);
  283. if (!get_owner(fs, i) && !FAT_IS_BAD(fs, curEntry.value))
  284. if (!fs_test(cluster_start(fs, i), fs->cluster_size)) {
  285. printf("Cluster %lu is unreadable.\n", i);
  286. set_fat(fs, i, -2);
  287. }
  288. }
  289. }
  290. void reclaim_free(DOS_FS * fs)
  291. {
  292. int reclaimed;
  293. unsigned long i;
  294. if (verbose)
  295. printf("Checking for unused clusters.\n");
  296. reclaimed = 0;
  297. for (i = 2; i < fs->clusters + 2; i++) {
  298. FAT_ENTRY curEntry;
  299. get_fat(&curEntry, fs->fat, i, fs);
  300. if (!get_owner(fs, i) && curEntry.value &&
  301. !FAT_IS_BAD(fs, curEntry.value)) {
  302. set_fat(fs, i, 0);
  303. reclaimed++;
  304. }
  305. }
  306. if (reclaimed)
  307. printf("Reclaimed %d unused cluster%s (%llu bytes).\n", reclaimed,
  308. reclaimed == 1 ? "" : "s",
  309. (unsigned long long)reclaimed * fs->cluster_size);
  310. }
  311. /**
  312. * Assign the specified owner to all orphan chains (except cycles).
  313. * Break cross-links between orphan chains.
  314. *
  315. * @param[in,out] fs Information about the filesystem
  316. * @param[in] owner dentry to be assigned ownership of orphans
  317. * @param[in,out] num_refs For each orphan cluster [index], how many
  318. * clusters link to it.
  319. * @param[in] start_cluster Where to start scanning for orphans
  320. */
  321. static void tag_free(DOS_FS * fs, DOS_FILE * owner, unsigned long *num_refs,
  322. unsigned long start_cluster)
  323. {
  324. int prev;
  325. unsigned long i, walk;
  326. if (start_cluster == 0)
  327. start_cluster = 2;
  328. for (i = start_cluster; i < fs->clusters + 2; i++) {
  329. FAT_ENTRY curEntry;
  330. get_fat(&curEntry, fs->fat, i, fs);
  331. /* If the current entry is the head of an un-owned chain... */
  332. if (curEntry.value && !FAT_IS_BAD(fs, curEntry.value) &&
  333. !get_owner(fs, i) && !num_refs[i]) {
  334. prev = 0;
  335. /* Walk the chain, claiming ownership as we go */
  336. for (walk = i; walk != -1; walk = next_cluster(fs, walk)) {
  337. if (!get_owner(fs, walk)) {
  338. set_owner(fs, walk, owner);
  339. } else {
  340. /* We've run into cross-links between orphaned chains,
  341. * or a cycle with a tail.
  342. * Terminate this orphan chain (break the link)
  343. */
  344. set_fat(fs, prev, -1);
  345. /* This is not necessary because 'walk' is owned and thus
  346. * will never become the head of a chain (the only case
  347. * that would matter during reclaim to files).
  348. * It's easier to decrement than to prove that it's
  349. * unnecessary.
  350. */
  351. num_refs[walk]--;
  352. break;
  353. }
  354. prev = walk;
  355. }
  356. }
  357. }
  358. }
  359. /**
  360. * Recover orphan chains to files, handling any cycles or cross-links.
  361. *
  362. * @param[in,out] fs Information about the filesystem
  363. */
  364. void reclaim_file(DOS_FS * fs)
  365. {
  366. DOS_FILE orphan;
  367. int reclaimed, files;
  368. int changed = 0;
  369. unsigned long i, next, walk;
  370. unsigned long *num_refs = NULL; /* Only for orphaned clusters */
  371. unsigned long total_num_clusters;
  372. if (verbose)
  373. printf("Reclaiming unconnected clusters.\n");
  374. total_num_clusters = fs->clusters + 2UL;
  375. num_refs = alloc(total_num_clusters * sizeof(unsigned long));
  376. memset(num_refs, 0, (total_num_clusters * sizeof(unsigned long)));
  377. /* Guarantee that all orphan chains (except cycles) end cleanly
  378. * with an end-of-chain mark.
  379. */
  380. for (i = 2; i < total_num_clusters; i++) {
  381. FAT_ENTRY curEntry;
  382. get_fat(&curEntry, fs->fat, i, fs);
  383. next = curEntry.value;
  384. if (!get_owner(fs, i) && next && next < fs->clusters + 2) {
  385. /* Cluster is linked, but not owned (orphan) */
  386. FAT_ENTRY nextEntry;
  387. get_fat(&nextEntry, fs->fat, next, fs);
  388. /* Mark it end-of-chain if it links into an owned cluster,
  389. * a free cluster, or a bad cluster.
  390. */
  391. if (get_owner(fs, next) || !nextEntry.value ||
  392. FAT_IS_BAD(fs, nextEntry.value))
  393. set_fat(fs, i, -1);
  394. else
  395. num_refs[next]++;
  396. }
  397. }
  398. /* Scan until all the orphans are accounted for,
  399. * and all cycles and cross-links are broken
  400. */
  401. do {
  402. tag_free(fs, &orphan, num_refs, changed);
  403. changed = 0;
  404. /* Any unaccounted-for orphans must be part of a cycle */
  405. for (i = 2; i < total_num_clusters; i++) {
  406. FAT_ENTRY curEntry;
  407. get_fat(&curEntry, fs->fat, i, fs);
  408. if (curEntry.value && !FAT_IS_BAD(fs, curEntry.value) &&
  409. !get_owner(fs, i)) {
  410. if (!num_refs[curEntry.value]--)
  411. die("Internal error: num_refs going below zero");
  412. set_fat(fs, i, -1);
  413. changed = curEntry.value;
  414. printf("Broke cycle at cluster %lu in free chain.\n", i);
  415. /* If we've created a new chain head,
  416. * tag_free() can claim it
  417. */
  418. if (num_refs[curEntry.value] == 0)
  419. break;
  420. }
  421. }
  422. }
  423. while (changed);
  424. /* Now we can start recovery */
  425. files = reclaimed = 0;
  426. for (i = 2; i < total_num_clusters; i++)
  427. /* If this cluster is the head of an orphan chain... */
  428. if (get_owner(fs, i) == &orphan && !num_refs[i]) {
  429. DIR_ENT de;
  430. loff_t offset;
  431. files++;
  432. offset = alloc_rootdir_entry(fs, &de, "FSCK%04d");
  433. de.start = CT_LE_W(i & 0xffff);
  434. if (fs->fat_bits == 32)
  435. de.starthi = CT_LE_W(i >> 16);
  436. for (walk = i; walk > 0 && walk != -1;
  437. walk = next_cluster(fs, walk)) {
  438. de.size = CT_LE_L(CF_LE_L(de.size) + fs->cluster_size);
  439. reclaimed++;
  440. }
  441. fs_write(offset, sizeof(DIR_ENT), &de);
  442. }
  443. if (reclaimed)
  444. printf("Reclaimed %d unused cluster%s (%llu bytes) in %d chain%s.\n",
  445. reclaimed, reclaimed == 1 ? "" : "s",
  446. (unsigned long long)reclaimed * fs->cluster_size, files,
  447. files == 1 ? "" : "s");
  448. free(num_refs);
  449. }
  450. unsigned long update_free(DOS_FS * fs)
  451. {
  452. unsigned long i;
  453. unsigned long free = 0;
  454. int do_set = 0;
  455. for (i = 2; i < fs->clusters + 2; i++) {
  456. FAT_ENTRY curEntry;
  457. get_fat(&curEntry, fs->fat, i, fs);
  458. if (!get_owner(fs, i) && !FAT_IS_BAD(fs, curEntry.value))
  459. ++free;
  460. }
  461. if (!fs->fsinfo_start)
  462. return free;
  463. if (verbose)
  464. printf("Checking free cluster summary.\n");
  465. if (fs->free_clusters != 0xFFFFFFFF) {
  466. if (free != fs->free_clusters) {
  467. printf("Free cluster summary wrong (%ld vs. really %ld)\n",
  468. fs->free_clusters, free);
  469. if (interactive)
  470. printf("1) Correct\n2) Don't correct\n");
  471. else
  472. printf(" Auto-correcting.\n");
  473. if (!interactive || get_key("12", "?") == '1')
  474. do_set = 1;
  475. }
  476. } else {
  477. printf("Free cluster summary uninitialized (should be %ld)\n", free);
  478. if (rw) {
  479. if (interactive)
  480. printf("1) Set it\n2) Leave it uninitialized\n");
  481. else
  482. printf(" Auto-setting.\n");
  483. if (!interactive || get_key("12", "?") == '1')
  484. do_set = 1;
  485. }
  486. }
  487. if (do_set) {
  488. unsigned long le_free = CT_LE_L(free);
  489. fs->free_clusters = free;
  490. fs_write(fs->fsinfo_start + offsetof(struct info_sector, free_clusters),
  491. sizeof(le_free), &le_free);
  492. }
  493. return free;
  494. }