fat.c 16 KB

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