fat.c 16 KB

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