fat.c 30 KB

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