fat.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * fat.c
  4. *
  5. * R/O (V)FAT 12/16/32 filesystem implementation by Marcus Sundberg
  6. *
  7. * 2002-07-28 - rjones@nexus-tech.net - ported to ppcboot v1.1.6
  8. * 2003-03-10 - kharris@nexus-tech.net - ported to uboot
  9. */
  10. #include <common.h>
  11. #include <blk.h>
  12. #include <config.h>
  13. #include <exports.h>
  14. #include <fat.h>
  15. #include <fs.h>
  16. #include <log.h>
  17. #include <asm/byteorder.h>
  18. #include <part.h>
  19. #include <malloc.h>
  20. #include <memalign.h>
  21. #include <asm/cache.h>
  22. #include <linux/compiler.h>
  23. #include <linux/ctype.h>
  24. /*
  25. * Convert a string to lowercase. Converts at most 'len' characters,
  26. * 'len' may be larger than the length of 'str' if 'str' is NULL
  27. * terminated.
  28. */
  29. static void downcase(char *str, size_t len)
  30. {
  31. while (*str != '\0' && len--) {
  32. *str = tolower(*str);
  33. str++;
  34. }
  35. }
  36. static struct blk_desc *cur_dev;
  37. static struct disk_partition cur_part_info;
  38. #define DOS_BOOT_MAGIC_OFFSET 0x1fe
  39. #define DOS_FS_TYPE_OFFSET 0x36
  40. #define DOS_FS32_TYPE_OFFSET 0x52
  41. static int disk_read(__u32 block, __u32 nr_blocks, void *buf)
  42. {
  43. ulong ret;
  44. if (!cur_dev)
  45. return -1;
  46. ret = blk_dread(cur_dev, cur_part_info.start + block, nr_blocks, buf);
  47. if (ret != nr_blocks)
  48. return -1;
  49. return ret;
  50. }
  51. int fat_set_blk_dev(struct blk_desc *dev_desc, struct disk_partition *info)
  52. {
  53. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, dev_desc->blksz);
  54. cur_dev = dev_desc;
  55. cur_part_info = *info;
  56. /* Make sure it has a valid FAT header */
  57. if (disk_read(0, 1, buffer) != 1) {
  58. cur_dev = NULL;
  59. return -1;
  60. }
  61. /* Check if it's actually a DOS volume */
  62. if (memcmp(buffer + DOS_BOOT_MAGIC_OFFSET, "\x55\xAA", 2)) {
  63. cur_dev = NULL;
  64. return -1;
  65. }
  66. /* Check for FAT12/FAT16/FAT32 filesystem */
  67. if (!memcmp(buffer + DOS_FS_TYPE_OFFSET, "FAT", 3))
  68. return 0;
  69. if (!memcmp(buffer + DOS_FS32_TYPE_OFFSET, "FAT32", 5))
  70. return 0;
  71. cur_dev = NULL;
  72. return -1;
  73. }
  74. int fat_register_device(struct blk_desc *dev_desc, int part_no)
  75. {
  76. struct disk_partition info;
  77. /* First close any currently found FAT filesystem */
  78. cur_dev = NULL;
  79. /* Read the partition table, if present */
  80. if (part_get_info(dev_desc, part_no, &info)) {
  81. if (part_no != 0) {
  82. printf("** Partition %d not valid on device %d **\n",
  83. part_no, dev_desc->devnum);
  84. return -1;
  85. }
  86. info.start = 0;
  87. info.size = dev_desc->lba;
  88. info.blksz = dev_desc->blksz;
  89. info.name[0] = 0;
  90. info.type[0] = 0;
  91. info.bootable = 0;
  92. #if CONFIG_IS_ENABLED(PARTITION_UUIDS)
  93. info.uuid[0] = 0;
  94. #endif
  95. }
  96. return fat_set_blk_dev(dev_desc, &info);
  97. }
  98. /*
  99. * Extract zero terminated short name from a directory entry.
  100. */
  101. static void get_name(dir_entry *dirent, char *s_name)
  102. {
  103. char *ptr;
  104. memcpy(s_name, dirent->name, 8);
  105. s_name[8] = '\0';
  106. ptr = s_name;
  107. while (*ptr && *ptr != ' ')
  108. ptr++;
  109. if (dirent->lcase & CASE_LOWER_BASE)
  110. downcase(s_name, (unsigned)(ptr - s_name));
  111. if (dirent->ext[0] && dirent->ext[0] != ' ') {
  112. *ptr++ = '.';
  113. memcpy(ptr, dirent->ext, 3);
  114. if (dirent->lcase & CASE_LOWER_EXT)
  115. downcase(ptr, 3);
  116. ptr[3] = '\0';
  117. while (*ptr && *ptr != ' ')
  118. ptr++;
  119. }
  120. *ptr = '\0';
  121. if (*s_name == DELETED_FLAG)
  122. *s_name = '\0';
  123. else if (*s_name == aRING)
  124. *s_name = DELETED_FLAG;
  125. }
  126. static int flush_dirty_fat_buffer(fsdata *mydata);
  127. #if !CONFIG_IS_ENABLED(FAT_WRITE)
  128. /* Stub for read only operation */
  129. int flush_dirty_fat_buffer(fsdata *mydata)
  130. {
  131. (void)(mydata);
  132. return 0;
  133. }
  134. #endif
  135. /*
  136. * Get the entry at index 'entry' in a FAT (12/16/32) table.
  137. * On failure 0x00 is returned.
  138. */
  139. static __u32 get_fatent(fsdata *mydata, __u32 entry)
  140. {
  141. __u32 bufnum;
  142. __u32 offset, off8;
  143. __u32 ret = 0x00;
  144. if (CHECK_CLUST(entry, mydata->fatsize)) {
  145. printf("Error: Invalid FAT entry: 0x%08x\n", entry);
  146. return ret;
  147. }
  148. switch (mydata->fatsize) {
  149. case 32:
  150. bufnum = entry / FAT32BUFSIZE;
  151. offset = entry - bufnum * FAT32BUFSIZE;
  152. break;
  153. case 16:
  154. bufnum = entry / FAT16BUFSIZE;
  155. offset = entry - bufnum * FAT16BUFSIZE;
  156. break;
  157. case 12:
  158. bufnum = entry / FAT12BUFSIZE;
  159. offset = entry - bufnum * FAT12BUFSIZE;
  160. break;
  161. default:
  162. /* Unsupported FAT size */
  163. return ret;
  164. }
  165. debug("FAT%d: entry: 0x%08x = %d, offset: 0x%04x = %d\n",
  166. mydata->fatsize, entry, entry, offset, offset);
  167. /* Read a new block of FAT entries into the cache. */
  168. if (bufnum != mydata->fatbufnum) {
  169. __u32 getsize = FATBUFBLOCKS;
  170. __u8 *bufptr = mydata->fatbuf;
  171. __u32 fatlength = mydata->fatlength;
  172. __u32 startblock = bufnum * FATBUFBLOCKS;
  173. /* Cap length if fatlength is not a multiple of FATBUFBLOCKS */
  174. if (startblock + getsize > fatlength)
  175. getsize = fatlength - startblock;
  176. startblock += mydata->fat_sect; /* Offset from start of disk */
  177. /* Write back the fatbuf to the disk */
  178. if (flush_dirty_fat_buffer(mydata) < 0)
  179. return -1;
  180. if (disk_read(startblock, getsize, bufptr) < 0) {
  181. debug("Error reading FAT blocks\n");
  182. return ret;
  183. }
  184. mydata->fatbufnum = bufnum;
  185. }
  186. /* Get the actual entry from the table */
  187. switch (mydata->fatsize) {
  188. case 32:
  189. ret = FAT2CPU32(((__u32 *) mydata->fatbuf)[offset]);
  190. break;
  191. case 16:
  192. ret = FAT2CPU16(((__u16 *) mydata->fatbuf)[offset]);
  193. break;
  194. case 12:
  195. off8 = (offset * 3) / 2;
  196. /* fatbut + off8 may be unaligned, read in byte granularity */
  197. ret = mydata->fatbuf[off8] + (mydata->fatbuf[off8 + 1] << 8);
  198. if (offset & 0x1)
  199. ret >>= 4;
  200. ret &= 0xfff;
  201. }
  202. debug("FAT%d: ret: 0x%08x, entry: 0x%08x, offset: 0x%04x\n",
  203. mydata->fatsize, ret, entry, offset);
  204. return ret;
  205. }
  206. /*
  207. * Read at most 'size' bytes from the specified cluster into 'buffer'.
  208. * Return 0 on success, -1 otherwise.
  209. */
  210. static int
  211. get_cluster(fsdata *mydata, __u32 clustnum, __u8 *buffer, unsigned long size)
  212. {
  213. __u32 idx = 0;
  214. __u32 startsect;
  215. int ret;
  216. if (clustnum > 0) {
  217. startsect = clust_to_sect(mydata, clustnum);
  218. } else {
  219. startsect = mydata->rootdir_sect;
  220. }
  221. debug("gc - clustnum: %d, startsect: %d\n", clustnum, startsect);
  222. if ((unsigned long)buffer & (ARCH_DMA_MINALIGN - 1)) {
  223. ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
  224. debug("FAT: Misaligned buffer address (%p)\n", buffer);
  225. while (size >= mydata->sect_size) {
  226. ret = disk_read(startsect++, 1, tmpbuf);
  227. if (ret != 1) {
  228. debug("Error reading data (got %d)\n", ret);
  229. return -1;
  230. }
  231. memcpy(buffer, tmpbuf, mydata->sect_size);
  232. buffer += mydata->sect_size;
  233. size -= mydata->sect_size;
  234. }
  235. } else {
  236. idx = size / mydata->sect_size;
  237. if (idx == 0)
  238. ret = 0;
  239. else
  240. ret = disk_read(startsect, idx, buffer);
  241. if (ret != idx) {
  242. debug("Error reading data (got %d)\n", ret);
  243. return -1;
  244. }
  245. startsect += idx;
  246. idx *= mydata->sect_size;
  247. buffer += idx;
  248. size -= idx;
  249. }
  250. if (size) {
  251. ALLOC_CACHE_ALIGN_BUFFER(__u8, tmpbuf, mydata->sect_size);
  252. ret = disk_read(startsect, 1, tmpbuf);
  253. if (ret != 1) {
  254. debug("Error reading data (got %d)\n", ret);
  255. return -1;
  256. }
  257. memcpy(buffer, tmpbuf, size);
  258. }
  259. return 0;
  260. }
  261. /**
  262. * get_contents() - read from file
  263. *
  264. * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
  265. * into 'buffer'. Update the number of bytes read in *gotsize or return -1 on
  266. * fatal errors.
  267. *
  268. * @mydata: file system description
  269. * @dentprt: directory entry pointer
  270. * @pos: position from where to read
  271. * @buffer: buffer into which to read
  272. * @maxsize: maximum number of bytes to read
  273. * @gotsize: number of bytes actually read
  274. * Return: -1 on error, otherwise 0
  275. */
  276. static int get_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos,
  277. __u8 *buffer, loff_t maxsize, loff_t *gotsize)
  278. {
  279. loff_t filesize = FAT2CPU32(dentptr->size);
  280. unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
  281. __u32 curclust = START(dentptr);
  282. __u32 endclust, newclust;
  283. loff_t actsize;
  284. *gotsize = 0;
  285. debug("Filesize: %llu bytes\n", filesize);
  286. if (pos >= filesize) {
  287. debug("Read position past EOF: %llu\n", pos);
  288. return 0;
  289. }
  290. if (maxsize > 0 && filesize > pos + maxsize)
  291. filesize = pos + maxsize;
  292. debug("%llu bytes\n", filesize);
  293. actsize = bytesperclust;
  294. /* go to cluster at pos */
  295. while (actsize <= pos) {
  296. curclust = get_fatent(mydata, curclust);
  297. if (CHECK_CLUST(curclust, mydata->fatsize)) {
  298. debug("curclust: 0x%x\n", curclust);
  299. printf("Invalid FAT entry\n");
  300. return -1;
  301. }
  302. actsize += bytesperclust;
  303. }
  304. /* actsize > pos */
  305. actsize -= bytesperclust;
  306. filesize -= actsize;
  307. pos -= actsize;
  308. /* align to beginning of next cluster if any */
  309. if (pos) {
  310. __u8 *tmp_buffer;
  311. actsize = min(filesize, (loff_t)bytesperclust);
  312. tmp_buffer = malloc_cache_aligned(actsize);
  313. if (!tmp_buffer) {
  314. debug("Error: allocating buffer\n");
  315. return -1;
  316. }
  317. if (get_cluster(mydata, curclust, tmp_buffer, actsize) != 0) {
  318. printf("Error reading cluster\n");
  319. free(tmp_buffer);
  320. return -1;
  321. }
  322. filesize -= actsize;
  323. actsize -= pos;
  324. memcpy(buffer, tmp_buffer + pos, actsize);
  325. free(tmp_buffer);
  326. *gotsize += actsize;
  327. if (!filesize)
  328. return 0;
  329. buffer += actsize;
  330. curclust = get_fatent(mydata, curclust);
  331. if (CHECK_CLUST(curclust, mydata->fatsize)) {
  332. debug("curclust: 0x%x\n", curclust);
  333. printf("Invalid FAT entry\n");
  334. return -1;
  335. }
  336. }
  337. actsize = bytesperclust;
  338. endclust = curclust;
  339. do {
  340. /* search for consecutive clusters */
  341. while (actsize < filesize) {
  342. newclust = get_fatent(mydata, endclust);
  343. if ((newclust - 1) != endclust)
  344. goto getit;
  345. if (CHECK_CLUST(newclust, mydata->fatsize)) {
  346. debug("curclust: 0x%x\n", newclust);
  347. printf("Invalid FAT entry\n");
  348. return -1;
  349. }
  350. endclust = newclust;
  351. actsize += bytesperclust;
  352. }
  353. /* get remaining bytes */
  354. actsize = filesize;
  355. if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
  356. printf("Error reading cluster\n");
  357. return -1;
  358. }
  359. *gotsize += actsize;
  360. return 0;
  361. getit:
  362. if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
  363. printf("Error reading cluster\n");
  364. return -1;
  365. }
  366. *gotsize += (int)actsize;
  367. filesize -= actsize;
  368. buffer += actsize;
  369. curclust = get_fatent(mydata, endclust);
  370. if (CHECK_CLUST(curclust, mydata->fatsize)) {
  371. debug("curclust: 0x%x\n", curclust);
  372. printf("Invalid FAT entry\n");
  373. return -1;
  374. }
  375. actsize = bytesperclust;
  376. endclust = curclust;
  377. } while (1);
  378. }
  379. /*
  380. * Extract the file name information from 'slotptr' into 'l_name',
  381. * starting at l_name[*idx].
  382. * Return 1 if terminator (zero byte) is found, 0 otherwise.
  383. */
  384. static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
  385. {
  386. int j;
  387. for (j = 0; j <= 8; j += 2) {
  388. l_name[*idx] = slotptr->name0_4[j];
  389. if (l_name[*idx] == 0x00)
  390. return 1;
  391. (*idx)++;
  392. }
  393. for (j = 0; j <= 10; j += 2) {
  394. l_name[*idx] = slotptr->name5_10[j];
  395. if (l_name[*idx] == 0x00)
  396. return 1;
  397. (*idx)++;
  398. }
  399. for (j = 0; j <= 2; j += 2) {
  400. l_name[*idx] = slotptr->name11_12[j];
  401. if (l_name[*idx] == 0x00)
  402. return 1;
  403. (*idx)++;
  404. }
  405. return 0;
  406. }
  407. /* Calculate short name checksum */
  408. static __u8 mkcksum(const char name[8], const char ext[3])
  409. {
  410. int i;
  411. __u8 ret = 0;
  412. for (i = 0; i < 8; i++)
  413. ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + name[i];
  414. for (i = 0; i < 3; i++)
  415. ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + ext[i];
  416. return ret;
  417. }
  418. /*
  419. * Read boot sector and volume info from a FAT filesystem
  420. */
  421. static int
  422. read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
  423. {
  424. __u8 *block;
  425. volume_info *vistart;
  426. int ret = 0;
  427. if (cur_dev == NULL) {
  428. debug("Error: no device selected\n");
  429. return -1;
  430. }
  431. block = malloc_cache_aligned(cur_dev->blksz);
  432. if (block == NULL) {
  433. debug("Error: allocating block\n");
  434. return -1;
  435. }
  436. if (disk_read(0, 1, block) < 0) {
  437. debug("Error: reading block\n");
  438. goto fail;
  439. }
  440. memcpy(bs, block, sizeof(boot_sector));
  441. bs->reserved = FAT2CPU16(bs->reserved);
  442. bs->fat_length = FAT2CPU16(bs->fat_length);
  443. bs->secs_track = FAT2CPU16(bs->secs_track);
  444. bs->heads = FAT2CPU16(bs->heads);
  445. bs->total_sect = FAT2CPU32(bs->total_sect);
  446. /* FAT32 entries */
  447. if (bs->fat_length == 0) {
  448. /* Assume FAT32 */
  449. bs->fat32_length = FAT2CPU32(bs->fat32_length);
  450. bs->flags = FAT2CPU16(bs->flags);
  451. bs->root_cluster = FAT2CPU32(bs->root_cluster);
  452. bs->info_sector = FAT2CPU16(bs->info_sector);
  453. bs->backup_boot = FAT2CPU16(bs->backup_boot);
  454. vistart = (volume_info *)(block + sizeof(boot_sector));
  455. *fatsize = 32;
  456. } else {
  457. vistart = (volume_info *)&(bs->fat32_length);
  458. *fatsize = 0;
  459. }
  460. memcpy(volinfo, vistart, sizeof(volume_info));
  461. if (*fatsize == 32) {
  462. if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
  463. goto exit;
  464. } else {
  465. if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
  466. *fatsize = 12;
  467. goto exit;
  468. }
  469. if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
  470. *fatsize = 16;
  471. goto exit;
  472. }
  473. }
  474. debug("Error: broken fs_type sign\n");
  475. fail:
  476. ret = -1;
  477. exit:
  478. free(block);
  479. return ret;
  480. }
  481. static int get_fs_info(fsdata *mydata)
  482. {
  483. boot_sector bs;
  484. volume_info volinfo;
  485. int ret;
  486. ret = read_bootsectandvi(&bs, &volinfo, &mydata->fatsize);
  487. if (ret) {
  488. debug("Error: reading boot sector\n");
  489. return ret;
  490. }
  491. if (mydata->fatsize == 32) {
  492. mydata->fatlength = bs.fat32_length;
  493. mydata->total_sect = bs.total_sect;
  494. } else {
  495. mydata->fatlength = bs.fat_length;
  496. mydata->total_sect = (bs.sectors[1] << 8) + bs.sectors[0];
  497. if (!mydata->total_sect)
  498. mydata->total_sect = bs.total_sect;
  499. }
  500. if (!mydata->total_sect) /* unlikely */
  501. mydata->total_sect = (u32)cur_part_info.size;
  502. mydata->fats = bs.fats;
  503. mydata->fat_sect = bs.reserved;
  504. mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats;
  505. mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
  506. mydata->clust_size = bs.cluster_size;
  507. if (mydata->sect_size != cur_part_info.blksz) {
  508. printf("Error: FAT sector size mismatch (fs=%hu, dev=%lu)\n",
  509. mydata->sect_size, cur_part_info.blksz);
  510. return -1;
  511. }
  512. if (mydata->clust_size == 0) {
  513. printf("Error: FAT cluster size not set\n");
  514. return -1;
  515. }
  516. if ((unsigned int)mydata->clust_size * mydata->sect_size >
  517. MAX_CLUSTSIZE) {
  518. printf("Error: FAT cluster size too big (cs=%u, max=%u)\n",
  519. (unsigned int)mydata->clust_size * mydata->sect_size,
  520. MAX_CLUSTSIZE);
  521. return -1;
  522. }
  523. if (mydata->fatsize == 32) {
  524. mydata->data_begin = mydata->rootdir_sect -
  525. (mydata->clust_size * 2);
  526. mydata->root_cluster = bs.root_cluster;
  527. } else {
  528. mydata->rootdir_size = ((bs.dir_entries[1] * (int)256 +
  529. bs.dir_entries[0]) *
  530. sizeof(dir_entry)) /
  531. mydata->sect_size;
  532. mydata->data_begin = mydata->rootdir_sect +
  533. mydata->rootdir_size -
  534. (mydata->clust_size * 2);
  535. /*
  536. * The root directory is not cluster-aligned and may be on a
  537. * "negative" cluster, this will be handled specially in
  538. * next_cluster().
  539. */
  540. mydata->root_cluster = 0;
  541. }
  542. mydata->fatbufnum = -1;
  543. mydata->fat_dirty = 0;
  544. mydata->fatbuf = malloc_cache_aligned(FATBUFSIZE);
  545. if (mydata->fatbuf == NULL) {
  546. debug("Error: allocating memory\n");
  547. return -1;
  548. }
  549. debug("FAT%d, fat_sect: %d, fatlength: %d\n",
  550. mydata->fatsize, mydata->fat_sect, mydata->fatlength);
  551. debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
  552. "Data begins at: %d\n",
  553. mydata->root_cluster,
  554. mydata->rootdir_sect,
  555. mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
  556. debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
  557. mydata->clust_size);
  558. return 0;
  559. }
  560. /*
  561. * Directory iterator, to simplify filesystem traversal
  562. *
  563. * Implements an iterator pattern to traverse directory tables,
  564. * transparently handling directory tables split across multiple
  565. * clusters, and the difference between FAT12/FAT16 root directory
  566. * (contiguous) and subdirectories + FAT32 root (chained).
  567. *
  568. * Rough usage:
  569. *
  570. * for (fat_itr_root(&itr, fsdata); fat_itr_next(&itr); ) {
  571. * // to traverse down to a subdirectory pointed to by
  572. * // current iterator position:
  573. * fat_itr_child(&itr, &itr);
  574. * }
  575. *
  576. * For more complete example, see fat_itr_resolve()
  577. */
  578. typedef struct {
  579. fsdata *fsdata; /* filesystem parameters */
  580. unsigned start_clust; /* first cluster */
  581. unsigned clust; /* current cluster */
  582. unsigned next_clust; /* next cluster if remaining == 0 */
  583. int last_cluster; /* set once we've read last cluster */
  584. int is_root; /* is iterator at root directory */
  585. int remaining; /* remaining dent's in current cluster */
  586. /* current iterator position values: */
  587. dir_entry *dent; /* current directory entry */
  588. char l_name[VFAT_MAXLEN_BYTES]; /* long (vfat) name */
  589. char s_name[14]; /* short 8.3 name */
  590. char *name; /* l_name if there is one, else s_name */
  591. /* storage for current cluster in memory: */
  592. u8 block[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
  593. } fat_itr;
  594. static int fat_itr_isdir(fat_itr *itr);
  595. /**
  596. * fat_itr_root() - initialize an iterator to start at the root
  597. * directory
  598. *
  599. * @itr: iterator to initialize
  600. * @fsdata: filesystem data for the partition
  601. * @return 0 on success, else -errno
  602. */
  603. static int fat_itr_root(fat_itr *itr, fsdata *fsdata)
  604. {
  605. if (get_fs_info(fsdata))
  606. return -ENXIO;
  607. itr->fsdata = fsdata;
  608. itr->start_clust = 0;
  609. itr->clust = fsdata->root_cluster;
  610. itr->next_clust = fsdata->root_cluster;
  611. itr->dent = NULL;
  612. itr->remaining = 0;
  613. itr->last_cluster = 0;
  614. itr->is_root = 1;
  615. return 0;
  616. }
  617. /**
  618. * fat_itr_child() - initialize an iterator to descend into a sub-
  619. * directory
  620. *
  621. * Initializes 'itr' to iterate the contents of the directory at
  622. * the current cursor position of 'parent'. It is an error to
  623. * call this if the current cursor of 'parent' is pointing at a
  624. * regular file.
  625. *
  626. * Note that 'itr' and 'parent' can be the same pointer if you do
  627. * not need to preserve 'parent' after this call, which is useful
  628. * for traversing directory structure to resolve a file/directory.
  629. *
  630. * @itr: iterator to initialize
  631. * @parent: the iterator pointing at a directory entry in the
  632. * parent directory of the directory to iterate
  633. */
  634. static void fat_itr_child(fat_itr *itr, fat_itr *parent)
  635. {
  636. fsdata *mydata = parent->fsdata; /* for silly macros */
  637. unsigned clustnum = START(parent->dent);
  638. assert(fat_itr_isdir(parent));
  639. itr->fsdata = parent->fsdata;
  640. itr->start_clust = clustnum;
  641. if (clustnum > 0) {
  642. itr->clust = clustnum;
  643. itr->next_clust = clustnum;
  644. itr->is_root = 0;
  645. } else {
  646. itr->clust = parent->fsdata->root_cluster;
  647. itr->next_clust = parent->fsdata->root_cluster;
  648. itr->is_root = 1;
  649. }
  650. itr->dent = NULL;
  651. itr->remaining = 0;
  652. itr->last_cluster = 0;
  653. }
  654. static void *next_cluster(fat_itr *itr, unsigned *nbytes)
  655. {
  656. fsdata *mydata = itr->fsdata; /* for silly macros */
  657. int ret;
  658. u32 sect;
  659. u32 read_size;
  660. /* have we reached the end? */
  661. if (itr->last_cluster)
  662. return NULL;
  663. if (itr->is_root && itr->fsdata->fatsize != 32) {
  664. /*
  665. * The root directory is located before the data area and
  666. * cannot be indexed using the regular unsigned cluster
  667. * numbers (it may start at a "negative" cluster or not at a
  668. * cluster boundary at all), so consider itr->next_clust to be
  669. * a offset in cluster-sized units from the start of rootdir.
  670. */
  671. unsigned sect_offset = itr->next_clust * itr->fsdata->clust_size;
  672. unsigned remaining_sects = itr->fsdata->rootdir_size - sect_offset;
  673. sect = itr->fsdata->rootdir_sect + sect_offset;
  674. /* do not read past the end of rootdir */
  675. read_size = min_t(u32, itr->fsdata->clust_size,
  676. remaining_sects);
  677. } else {
  678. sect = clust_to_sect(itr->fsdata, itr->next_clust);
  679. read_size = itr->fsdata->clust_size;
  680. }
  681. debug("FAT read(sect=%d), clust_size=%d, read_size=%u, DIRENTSPERBLOCK=%zd\n",
  682. sect, itr->fsdata->clust_size, read_size, DIRENTSPERBLOCK);
  683. /*
  684. * NOTE: do_fat_read_at() had complicated logic to deal w/
  685. * vfat names that span multiple clusters in the fat16 case,
  686. * which get_dentfromdir() probably also needed (and was
  687. * missing). And not entirely sure what fat32 didn't have
  688. * the same issue.. We solve that by only caring about one
  689. * dent at a time and iteratively constructing the vfat long
  690. * name.
  691. */
  692. ret = disk_read(sect, read_size, itr->block);
  693. if (ret < 0) {
  694. debug("Error: reading block\n");
  695. return NULL;
  696. }
  697. *nbytes = read_size * itr->fsdata->sect_size;
  698. itr->clust = itr->next_clust;
  699. if (itr->is_root && itr->fsdata->fatsize != 32) {
  700. itr->next_clust++;
  701. if (itr->next_clust * itr->fsdata->clust_size >=
  702. itr->fsdata->rootdir_size) {
  703. debug("nextclust: 0x%x\n", itr->next_clust);
  704. itr->last_cluster = 1;
  705. }
  706. } else {
  707. itr->next_clust = get_fatent(itr->fsdata, itr->next_clust);
  708. if (CHECK_CLUST(itr->next_clust, itr->fsdata->fatsize)) {
  709. debug("nextclust: 0x%x\n", itr->next_clust);
  710. itr->last_cluster = 1;
  711. }
  712. }
  713. return itr->block;
  714. }
  715. static dir_entry *next_dent(fat_itr *itr)
  716. {
  717. if (itr->remaining == 0) {
  718. unsigned nbytes;
  719. struct dir_entry *dent = next_cluster(itr, &nbytes);
  720. /* have we reached the last cluster? */
  721. if (!dent) {
  722. /* a sign for no more entries left */
  723. itr->dent = NULL;
  724. return NULL;
  725. }
  726. itr->remaining = nbytes / sizeof(dir_entry) - 1;
  727. itr->dent = dent;
  728. } else {
  729. itr->remaining--;
  730. itr->dent++;
  731. }
  732. /* have we reached the last valid entry? */
  733. if (itr->dent->name[0] == 0)
  734. return NULL;
  735. return itr->dent;
  736. }
  737. static dir_entry *extract_vfat_name(fat_itr *itr)
  738. {
  739. struct dir_entry *dent = itr->dent;
  740. int seqn = itr->dent->name[0] & ~LAST_LONG_ENTRY_MASK;
  741. u8 chksum, alias_checksum = ((dir_slot *)dent)->alias_checksum;
  742. int n = 0;
  743. while (seqn--) {
  744. char buf[13];
  745. int idx = 0;
  746. slot2str((dir_slot *)dent, buf, &idx);
  747. if (n + idx >= sizeof(itr->l_name))
  748. return NULL;
  749. /* shift accumulated long-name up and copy new part in: */
  750. memmove(itr->l_name + idx, itr->l_name, n);
  751. memcpy(itr->l_name, buf, idx);
  752. n += idx;
  753. dent = next_dent(itr);
  754. if (!dent)
  755. return NULL;
  756. }
  757. /*
  758. * We are now at the short file name entry.
  759. * If it is marked as deleted, just skip it.
  760. */
  761. if (dent->name[0] == DELETED_FLAG ||
  762. dent->name[0] == aRING)
  763. return NULL;
  764. itr->l_name[n] = '\0';
  765. chksum = mkcksum(dent->name, dent->ext);
  766. /* checksum mismatch could mean deleted file, etc.. skip it: */
  767. if (chksum != alias_checksum) {
  768. debug("** chksum=%x, alias_checksum=%x, l_name=%s, s_name=%8s.%3s\n",
  769. chksum, alias_checksum, itr->l_name, dent->name, dent->ext);
  770. return NULL;
  771. }
  772. return dent;
  773. }
  774. /**
  775. * fat_itr_next() - step to the next entry in a directory
  776. *
  777. * Must be called once on a new iterator before the cursor is valid.
  778. *
  779. * @itr: the iterator to iterate
  780. * @return boolean, 1 if success or 0 if no more entries in the
  781. * current directory
  782. */
  783. static int fat_itr_next(fat_itr *itr)
  784. {
  785. dir_entry *dent;
  786. itr->name = NULL;
  787. /*
  788. * One logical directory entry consist of following slots:
  789. * name[0] Attributes
  790. * dent[N - N]: LFN[N - 1] N|0x40 ATTR_VFAT
  791. * ...
  792. * dent[N - 2]: LFN[1] 2 ATTR_VFAT
  793. * dent[N - 1]: LFN[0] 1 ATTR_VFAT
  794. * dent[N]: SFN ATTR_ARCH
  795. */
  796. while (1) {
  797. dent = next_dent(itr);
  798. if (!dent)
  799. return 0;
  800. if (dent->name[0] == DELETED_FLAG ||
  801. dent->name[0] == aRING)
  802. continue;
  803. if (dent->attr & ATTR_VOLUME) {
  804. if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
  805. (dent->name[0] & LAST_LONG_ENTRY_MASK)) {
  806. /* long file name */
  807. dent = extract_vfat_name(itr);
  808. /*
  809. * If succeeded, dent has a valid short file
  810. * name entry for the current entry.
  811. * If failed, itr points to a current bogus
  812. * entry. So after fetching a next one,
  813. * it may have a short file name entry
  814. * for this bogus entry so that we can still
  815. * check for a short name.
  816. */
  817. if (!dent)
  818. continue;
  819. itr->name = itr->l_name;
  820. break;
  821. } else {
  822. /* Volume label or VFAT entry, skip */
  823. continue;
  824. }
  825. }
  826. /* short file name */
  827. break;
  828. }
  829. get_name(dent, itr->s_name);
  830. if (!itr->name)
  831. itr->name = itr->s_name;
  832. return 1;
  833. }
  834. /**
  835. * fat_itr_isdir() - is current cursor position pointing to a directory
  836. *
  837. * @itr: the iterator
  838. * @return true if cursor is at a directory
  839. */
  840. static int fat_itr_isdir(fat_itr *itr)
  841. {
  842. return !!(itr->dent->attr & ATTR_DIR);
  843. }
  844. /*
  845. * Helpers:
  846. */
  847. #define TYPE_FILE 0x1
  848. #define TYPE_DIR 0x2
  849. #define TYPE_ANY (TYPE_FILE | TYPE_DIR)
  850. /**
  851. * fat_itr_resolve() - traverse directory structure to resolve the
  852. * requested path.
  853. *
  854. * Traverse directory structure to the requested path. If the specified
  855. * path is to a directory, this will descend into the directory and
  856. * leave it iterator at the start of the directory. If the path is to a
  857. * file, it will leave the iterator in the parent directory with current
  858. * cursor at file's entry in the directory.
  859. *
  860. * @itr: iterator initialized to root
  861. * @path: the requested path
  862. * @type: bitmask of allowable file types
  863. * @return 0 on success or -errno
  864. */
  865. static int fat_itr_resolve(fat_itr *itr, const char *path, unsigned type)
  866. {
  867. const char *next;
  868. /* chomp any extra leading slashes: */
  869. while (path[0] && ISDIRDELIM(path[0]))
  870. path++;
  871. /* are we at the end? */
  872. if (strlen(path) == 0) {
  873. if (!(type & TYPE_DIR))
  874. return -ENOENT;
  875. return 0;
  876. }
  877. /* find length of next path entry: */
  878. next = path;
  879. while (next[0] && !ISDIRDELIM(next[0]))
  880. next++;
  881. if (itr->is_root) {
  882. /* root dir doesn't have "." nor ".." */
  883. if ((((next - path) == 1) && !strncmp(path, ".", 1)) ||
  884. (((next - path) == 2) && !strncmp(path, "..", 2))) {
  885. /* point back to itself */
  886. itr->clust = itr->fsdata->root_cluster;
  887. itr->next_clust = itr->fsdata->root_cluster;
  888. itr->dent = NULL;
  889. itr->remaining = 0;
  890. itr->last_cluster = 0;
  891. if (next[0] == 0) {
  892. if (type & TYPE_DIR)
  893. return 0;
  894. else
  895. return -ENOENT;
  896. }
  897. return fat_itr_resolve(itr, next, type);
  898. }
  899. }
  900. while (fat_itr_next(itr)) {
  901. int match = 0;
  902. unsigned n = max(strlen(itr->name), (size_t)(next - path));
  903. /* check both long and short name: */
  904. if (!strncasecmp(path, itr->name, n))
  905. match = 1;
  906. else if (itr->name != itr->s_name &&
  907. !strncasecmp(path, itr->s_name, n))
  908. match = 1;
  909. if (!match)
  910. continue;
  911. if (fat_itr_isdir(itr)) {
  912. /* recurse into directory: */
  913. fat_itr_child(itr, itr);
  914. return fat_itr_resolve(itr, next, type);
  915. } else if (next[0]) {
  916. /*
  917. * If next is not empty then we have a case
  918. * like: /path/to/realfile/nonsense
  919. */
  920. debug("bad trailing path: %s\n", next);
  921. return -ENOENT;
  922. } else if (!(type & TYPE_FILE)) {
  923. return -ENOTDIR;
  924. } else {
  925. return 0;
  926. }
  927. }
  928. return -ENOENT;
  929. }
  930. int file_fat_detectfs(void)
  931. {
  932. boot_sector bs;
  933. volume_info volinfo;
  934. int fatsize;
  935. char vol_label[12];
  936. if (cur_dev == NULL) {
  937. printf("No current device\n");
  938. return 1;
  939. }
  940. #if defined(CONFIG_IDE) || \
  941. defined(CONFIG_SATA) || \
  942. defined(CONFIG_SCSI) || \
  943. defined(CONFIG_CMD_USB) || \
  944. defined(CONFIG_MMC)
  945. printf("Interface: ");
  946. switch (cur_dev->if_type) {
  947. case IF_TYPE_IDE:
  948. printf("IDE");
  949. break;
  950. case IF_TYPE_SATA:
  951. printf("SATA");
  952. break;
  953. case IF_TYPE_SCSI:
  954. printf("SCSI");
  955. break;
  956. case IF_TYPE_ATAPI:
  957. printf("ATAPI");
  958. break;
  959. case IF_TYPE_USB:
  960. printf("USB");
  961. break;
  962. case IF_TYPE_DOC:
  963. printf("DOC");
  964. break;
  965. case IF_TYPE_MMC:
  966. printf("MMC");
  967. break;
  968. default:
  969. printf("Unknown");
  970. }
  971. printf("\n Device %d: ", cur_dev->devnum);
  972. dev_print(cur_dev);
  973. #endif
  974. if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
  975. printf("\nNo valid FAT fs found\n");
  976. return 1;
  977. }
  978. memcpy(vol_label, volinfo.volume_label, 11);
  979. vol_label[11] = '\0';
  980. volinfo.fs_type[5] = '\0';
  981. printf("Filesystem: %s \"%s\"\n", volinfo.fs_type, vol_label);
  982. return 0;
  983. }
  984. int fat_exists(const char *filename)
  985. {
  986. fsdata fsdata;
  987. fat_itr *itr;
  988. int ret;
  989. itr = malloc_cache_aligned(sizeof(fat_itr));
  990. if (!itr)
  991. return 0;
  992. ret = fat_itr_root(itr, &fsdata);
  993. if (ret)
  994. goto out;
  995. ret = fat_itr_resolve(itr, filename, TYPE_ANY);
  996. free(fsdata.fatbuf);
  997. out:
  998. free(itr);
  999. return ret == 0;
  1000. }
  1001. int fat_size(const char *filename, loff_t *size)
  1002. {
  1003. fsdata fsdata;
  1004. fat_itr *itr;
  1005. int ret;
  1006. itr = malloc_cache_aligned(sizeof(fat_itr));
  1007. if (!itr)
  1008. return -ENOMEM;
  1009. ret = fat_itr_root(itr, &fsdata);
  1010. if (ret)
  1011. goto out_free_itr;
  1012. ret = fat_itr_resolve(itr, filename, TYPE_FILE);
  1013. if (ret) {
  1014. /*
  1015. * Directories don't have size, but fs_size() is not
  1016. * expected to fail if passed a directory path:
  1017. */
  1018. free(fsdata.fatbuf);
  1019. ret = fat_itr_root(itr, &fsdata);
  1020. if (ret)
  1021. goto out_free_itr;
  1022. ret = fat_itr_resolve(itr, filename, TYPE_DIR);
  1023. if (!ret)
  1024. *size = 0;
  1025. goto out_free_both;
  1026. }
  1027. *size = FAT2CPU32(itr->dent->size);
  1028. out_free_both:
  1029. free(fsdata.fatbuf);
  1030. out_free_itr:
  1031. free(itr);
  1032. return ret;
  1033. }
  1034. int file_fat_read_at(const char *filename, loff_t pos, void *buffer,
  1035. loff_t maxsize, loff_t *actread)
  1036. {
  1037. fsdata fsdata;
  1038. fat_itr *itr;
  1039. int ret;
  1040. itr = malloc_cache_aligned(sizeof(fat_itr));
  1041. if (!itr)
  1042. return -ENOMEM;
  1043. ret = fat_itr_root(itr, &fsdata);
  1044. if (ret)
  1045. goto out_free_itr;
  1046. ret = fat_itr_resolve(itr, filename, TYPE_FILE);
  1047. if (ret)
  1048. goto out_free_both;
  1049. debug("reading %s at pos %llu\n", filename, pos);
  1050. /* For saving default max clustersize memory allocated to malloc pool */
  1051. dir_entry *dentptr = itr->dent;
  1052. ret = get_contents(&fsdata, dentptr, pos, buffer, maxsize, actread);
  1053. out_free_both:
  1054. free(fsdata.fatbuf);
  1055. out_free_itr:
  1056. free(itr);
  1057. return ret;
  1058. }
  1059. int file_fat_read(const char *filename, void *buffer, int maxsize)
  1060. {
  1061. loff_t actread;
  1062. int ret;
  1063. ret = file_fat_read_at(filename, 0, buffer, maxsize, &actread);
  1064. if (ret)
  1065. return ret;
  1066. else
  1067. return actread;
  1068. }
  1069. int fat_read_file(const char *filename, void *buf, loff_t offset, loff_t len,
  1070. loff_t *actread)
  1071. {
  1072. int ret;
  1073. ret = file_fat_read_at(filename, offset, buf, len, actread);
  1074. if (ret)
  1075. printf("** Unable to read file %s **\n", filename);
  1076. return ret;
  1077. }
  1078. typedef struct {
  1079. struct fs_dir_stream parent;
  1080. struct fs_dirent dirent;
  1081. fsdata fsdata;
  1082. fat_itr itr;
  1083. } fat_dir;
  1084. int fat_opendir(const char *filename, struct fs_dir_stream **dirsp)
  1085. {
  1086. fat_dir *dir;
  1087. int ret;
  1088. dir = malloc_cache_aligned(sizeof(*dir));
  1089. if (!dir)
  1090. return -ENOMEM;
  1091. memset(dir, 0, sizeof(*dir));
  1092. ret = fat_itr_root(&dir->itr, &dir->fsdata);
  1093. if (ret)
  1094. goto fail_free_dir;
  1095. ret = fat_itr_resolve(&dir->itr, filename, TYPE_DIR);
  1096. if (ret)
  1097. goto fail_free_both;
  1098. *dirsp = (struct fs_dir_stream *)dir;
  1099. return 0;
  1100. fail_free_both:
  1101. free(dir->fsdata.fatbuf);
  1102. fail_free_dir:
  1103. free(dir);
  1104. return ret;
  1105. }
  1106. int fat_readdir(struct fs_dir_stream *dirs, struct fs_dirent **dentp)
  1107. {
  1108. fat_dir *dir = (fat_dir *)dirs;
  1109. struct fs_dirent *dent = &dir->dirent;
  1110. if (!fat_itr_next(&dir->itr))
  1111. return -ENOENT;
  1112. memset(dent, 0, sizeof(*dent));
  1113. strcpy(dent->name, dir->itr.name);
  1114. if (fat_itr_isdir(&dir->itr)) {
  1115. dent->type = FS_DT_DIR;
  1116. } else {
  1117. dent->type = FS_DT_REG;
  1118. dent->size = FAT2CPU32(dir->itr.dent->size);
  1119. }
  1120. *dentp = dent;
  1121. return 0;
  1122. }
  1123. void fat_closedir(struct fs_dir_stream *dirs)
  1124. {
  1125. fat_dir *dir = (fat_dir *)dirs;
  1126. free(dir->fsdata.fatbuf);
  1127. free(dir);
  1128. }
  1129. void fat_close(void)
  1130. {
  1131. }