fat.c 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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 !defined(CONFIG_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. printf("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. * Read at most 'maxsize' bytes from 'pos' in the file associated with 'dentptr'
  258. * into 'buffer'.
  259. * Update the number of bytes read in *gotsize or return -1 on fatal errors.
  260. */
  261. __u8 get_contents_vfatname_block[MAX_CLUSTSIZE]
  262. __aligned(ARCH_DMA_MINALIGN);
  263. static int get_contents(fsdata *mydata, dir_entry *dentptr, loff_t pos,
  264. __u8 *buffer, loff_t maxsize, loff_t *gotsize)
  265. {
  266. loff_t filesize = FAT2CPU32(dentptr->size);
  267. unsigned int bytesperclust = mydata->clust_size * mydata->sect_size;
  268. __u32 curclust = START(dentptr);
  269. __u32 endclust, newclust;
  270. loff_t actsize;
  271. *gotsize = 0;
  272. debug("Filesize: %llu bytes\n", filesize);
  273. if (pos >= filesize) {
  274. debug("Read position past EOF: %llu\n", pos);
  275. return 0;
  276. }
  277. if (maxsize > 0 && filesize > pos + maxsize)
  278. filesize = pos + maxsize;
  279. debug("%llu bytes\n", filesize);
  280. actsize = bytesperclust;
  281. /* go to cluster at pos */
  282. while (actsize <= pos) {
  283. curclust = get_fatent(mydata, curclust);
  284. if (CHECK_CLUST(curclust, mydata->fatsize)) {
  285. debug("curclust: 0x%x\n", curclust);
  286. debug("Invalid FAT entry\n");
  287. return 0;
  288. }
  289. actsize += bytesperclust;
  290. }
  291. /* actsize > pos */
  292. actsize -= bytesperclust;
  293. filesize -= actsize;
  294. pos -= actsize;
  295. /* align to beginning of next cluster if any */
  296. if (pos) {
  297. actsize = min(filesize, (loff_t)bytesperclust);
  298. if (get_cluster(mydata, curclust, get_contents_vfatname_block,
  299. (int)actsize) != 0) {
  300. printf("Error reading cluster\n");
  301. return -1;
  302. }
  303. filesize -= actsize;
  304. actsize -= pos;
  305. memcpy(buffer, get_contents_vfatname_block + pos, actsize);
  306. *gotsize += actsize;
  307. if (!filesize)
  308. return 0;
  309. buffer += actsize;
  310. curclust = get_fatent(mydata, curclust);
  311. if (CHECK_CLUST(curclust, mydata->fatsize)) {
  312. debug("curclust: 0x%x\n", curclust);
  313. debug("Invalid FAT entry\n");
  314. return 0;
  315. }
  316. }
  317. actsize = bytesperclust;
  318. endclust = curclust;
  319. do {
  320. /* search for consecutive clusters */
  321. while (actsize < filesize) {
  322. newclust = get_fatent(mydata, endclust);
  323. if ((newclust - 1) != endclust)
  324. goto getit;
  325. if (CHECK_CLUST(newclust, mydata->fatsize)) {
  326. debug("curclust: 0x%x\n", newclust);
  327. debug("Invalid FAT entry\n");
  328. return 0;
  329. }
  330. endclust = newclust;
  331. actsize += bytesperclust;
  332. }
  333. /* get remaining bytes */
  334. actsize = filesize;
  335. if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
  336. printf("Error reading cluster\n");
  337. return -1;
  338. }
  339. *gotsize += actsize;
  340. return 0;
  341. getit:
  342. if (get_cluster(mydata, curclust, buffer, (int)actsize) != 0) {
  343. printf("Error reading cluster\n");
  344. return -1;
  345. }
  346. *gotsize += (int)actsize;
  347. filesize -= actsize;
  348. buffer += actsize;
  349. curclust = get_fatent(mydata, endclust);
  350. if (CHECK_CLUST(curclust, mydata->fatsize)) {
  351. debug("curclust: 0x%x\n", curclust);
  352. printf("Invalid FAT entry\n");
  353. return 0;
  354. }
  355. actsize = bytesperclust;
  356. endclust = curclust;
  357. } while (1);
  358. }
  359. /*
  360. * Extract the file name information from 'slotptr' into 'l_name',
  361. * starting at l_name[*idx].
  362. * Return 1 if terminator (zero byte) is found, 0 otherwise.
  363. */
  364. static int slot2str(dir_slot *slotptr, char *l_name, int *idx)
  365. {
  366. int j;
  367. for (j = 0; j <= 8; j += 2) {
  368. l_name[*idx] = slotptr->name0_4[j];
  369. if (l_name[*idx] == 0x00)
  370. return 1;
  371. (*idx)++;
  372. }
  373. for (j = 0; j <= 10; j += 2) {
  374. l_name[*idx] = slotptr->name5_10[j];
  375. if (l_name[*idx] == 0x00)
  376. return 1;
  377. (*idx)++;
  378. }
  379. for (j = 0; j <= 2; j += 2) {
  380. l_name[*idx] = slotptr->name11_12[j];
  381. if (l_name[*idx] == 0x00)
  382. return 1;
  383. (*idx)++;
  384. }
  385. return 0;
  386. }
  387. /* Calculate short name checksum */
  388. static __u8 mkcksum(const char name[8], const char ext[3])
  389. {
  390. int i;
  391. __u8 ret = 0;
  392. for (i = 0; i < 8; i++)
  393. ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + name[i];
  394. for (i = 0; i < 3; i++)
  395. ret = (((ret & 1) << 7) | ((ret & 0xfe) >> 1)) + ext[i];
  396. return ret;
  397. }
  398. /*
  399. * TODO these should go away once fat_write is reworked to use the
  400. * directory iterator
  401. */
  402. __u8 get_dentfromdir_block[MAX_CLUSTSIZE]
  403. __aligned(ARCH_DMA_MINALIGN);
  404. __u8 do_fat_read_at_block[MAX_CLUSTSIZE]
  405. __aligned(ARCH_DMA_MINALIGN);
  406. /*
  407. * Read boot sector and volume info from a FAT filesystem
  408. */
  409. static int
  410. read_bootsectandvi(boot_sector *bs, volume_info *volinfo, int *fatsize)
  411. {
  412. __u8 *block;
  413. volume_info *vistart;
  414. int ret = 0;
  415. if (cur_dev == NULL) {
  416. debug("Error: no device selected\n");
  417. return -1;
  418. }
  419. block = malloc_cache_aligned(cur_dev->blksz);
  420. if (block == NULL) {
  421. debug("Error: allocating block\n");
  422. return -1;
  423. }
  424. if (disk_read(0, 1, block) < 0) {
  425. debug("Error: reading block\n");
  426. goto fail;
  427. }
  428. memcpy(bs, block, sizeof(boot_sector));
  429. bs->reserved = FAT2CPU16(bs->reserved);
  430. bs->fat_length = FAT2CPU16(bs->fat_length);
  431. bs->secs_track = FAT2CPU16(bs->secs_track);
  432. bs->heads = FAT2CPU16(bs->heads);
  433. bs->total_sect = FAT2CPU32(bs->total_sect);
  434. /* FAT32 entries */
  435. if (bs->fat_length == 0) {
  436. /* Assume FAT32 */
  437. bs->fat32_length = FAT2CPU32(bs->fat32_length);
  438. bs->flags = FAT2CPU16(bs->flags);
  439. bs->root_cluster = FAT2CPU32(bs->root_cluster);
  440. bs->info_sector = FAT2CPU16(bs->info_sector);
  441. bs->backup_boot = FAT2CPU16(bs->backup_boot);
  442. vistart = (volume_info *)(block + sizeof(boot_sector));
  443. *fatsize = 32;
  444. } else {
  445. vistart = (volume_info *)&(bs->fat32_length);
  446. *fatsize = 0;
  447. }
  448. memcpy(volinfo, vistart, sizeof(volume_info));
  449. if (*fatsize == 32) {
  450. if (strncmp(FAT32_SIGN, vistart->fs_type, SIGNLEN) == 0)
  451. goto exit;
  452. } else {
  453. if (strncmp(FAT12_SIGN, vistart->fs_type, SIGNLEN) == 0) {
  454. *fatsize = 12;
  455. goto exit;
  456. }
  457. if (strncmp(FAT16_SIGN, vistart->fs_type, SIGNLEN) == 0) {
  458. *fatsize = 16;
  459. goto exit;
  460. }
  461. }
  462. debug("Error: broken fs_type sign\n");
  463. fail:
  464. ret = -1;
  465. exit:
  466. free(block);
  467. return ret;
  468. }
  469. static int get_fs_info(fsdata *mydata)
  470. {
  471. boot_sector bs;
  472. volume_info volinfo;
  473. int ret;
  474. ret = read_bootsectandvi(&bs, &volinfo, &mydata->fatsize);
  475. if (ret) {
  476. debug("Error: reading boot sector\n");
  477. return ret;
  478. }
  479. if (mydata->fatsize == 32) {
  480. mydata->fatlength = bs.fat32_length;
  481. } else {
  482. mydata->fatlength = bs.fat_length;
  483. }
  484. mydata->fat_sect = bs.reserved;
  485. mydata->rootdir_sect = mydata->fat_sect + mydata->fatlength * bs.fats;
  486. mydata->sect_size = (bs.sector_size[1] << 8) + bs.sector_size[0];
  487. mydata->clust_size = bs.cluster_size;
  488. if (mydata->sect_size != cur_part_info.blksz) {
  489. printf("Error: FAT sector size mismatch (fs=%hu, dev=%lu)\n",
  490. mydata->sect_size, cur_part_info.blksz);
  491. return -1;
  492. }
  493. if (mydata->fatsize == 32) {
  494. mydata->data_begin = mydata->rootdir_sect -
  495. (mydata->clust_size * 2);
  496. mydata->root_cluster = bs.root_cluster;
  497. } else {
  498. mydata->rootdir_size = ((bs.dir_entries[1] * (int)256 +
  499. bs.dir_entries[0]) *
  500. sizeof(dir_entry)) /
  501. mydata->sect_size;
  502. mydata->data_begin = mydata->rootdir_sect +
  503. mydata->rootdir_size -
  504. (mydata->clust_size * 2);
  505. mydata->root_cluster =
  506. sect_to_clust(mydata, mydata->rootdir_sect);
  507. }
  508. mydata->fatbufnum = -1;
  509. mydata->fat_dirty = 0;
  510. mydata->fatbuf = malloc_cache_aligned(FATBUFSIZE);
  511. if (mydata->fatbuf == NULL) {
  512. debug("Error: allocating memory\n");
  513. return -1;
  514. }
  515. debug("FAT%d, fat_sect: %d, fatlength: %d\n",
  516. mydata->fatsize, mydata->fat_sect, mydata->fatlength);
  517. debug("Rootdir begins at cluster: %d, sector: %d, offset: %x\n"
  518. "Data begins at: %d\n",
  519. mydata->root_cluster,
  520. mydata->rootdir_sect,
  521. mydata->rootdir_sect * mydata->sect_size, mydata->data_begin);
  522. debug("Sector size: %d, cluster size: %d\n", mydata->sect_size,
  523. mydata->clust_size);
  524. return 0;
  525. }
  526. /*
  527. * Directory iterator, to simplify filesystem traversal
  528. *
  529. * Implements an iterator pattern to traverse directory tables,
  530. * transparently handling directory tables split across multiple
  531. * clusters, and the difference between FAT12/FAT16 root directory
  532. * (contiguous) and subdirectories + FAT32 root (chained).
  533. *
  534. * Rough usage:
  535. *
  536. * for (fat_itr_root(&itr, fsdata); fat_itr_next(&itr); ) {
  537. * // to traverse down to a subdirectory pointed to by
  538. * // current iterator position:
  539. * fat_itr_child(&itr, &itr);
  540. * }
  541. *
  542. * For more complete example, see fat_itr_resolve()
  543. */
  544. typedef struct {
  545. fsdata *fsdata; /* filesystem parameters */
  546. unsigned clust; /* current cluster */
  547. int last_cluster; /* set once we've read last cluster */
  548. int is_root; /* is iterator at root directory */
  549. int remaining; /* remaining dent's in current cluster */
  550. /* current iterator position values: */
  551. dir_entry *dent; /* current directory entry */
  552. char l_name[VFAT_MAXLEN_BYTES]; /* long (vfat) name */
  553. char s_name[14]; /* short 8.3 name */
  554. char *name; /* l_name if there is one, else s_name */
  555. /* storage for current cluster in memory: */
  556. u8 block[MAX_CLUSTSIZE] __aligned(ARCH_DMA_MINALIGN);
  557. } fat_itr;
  558. static int fat_itr_isdir(fat_itr *itr);
  559. /**
  560. * fat_itr_root() - initialize an iterator to start at the root
  561. * directory
  562. *
  563. * @itr: iterator to initialize
  564. * @fsdata: filesystem data for the partition
  565. * @return 0 on success, else -errno
  566. */
  567. static int fat_itr_root(fat_itr *itr, fsdata *fsdata)
  568. {
  569. if (get_fs_info(fsdata))
  570. return -ENXIO;
  571. itr->fsdata = fsdata;
  572. itr->clust = fsdata->root_cluster;
  573. itr->dent = NULL;
  574. itr->remaining = 0;
  575. itr->last_cluster = 0;
  576. itr->is_root = 1;
  577. return 0;
  578. }
  579. /**
  580. * fat_itr_child() - initialize an iterator to descend into a sub-
  581. * directory
  582. *
  583. * Initializes 'itr' to iterate the contents of the directory at
  584. * the current cursor position of 'parent'. It is an error to
  585. * call this if the current cursor of 'parent' is pointing at a
  586. * regular file.
  587. *
  588. * Note that 'itr' and 'parent' can be the same pointer if you do
  589. * not need to preserve 'parent' after this call, which is useful
  590. * for traversing directory structure to resolve a file/directory.
  591. *
  592. * @itr: iterator to initialize
  593. * @parent: the iterator pointing at a directory entry in the
  594. * parent directory of the directory to iterate
  595. */
  596. static void fat_itr_child(fat_itr *itr, fat_itr *parent)
  597. {
  598. fsdata *mydata = parent->fsdata; /* for silly macros */
  599. unsigned clustnum = START(parent->dent);
  600. assert(fat_itr_isdir(parent));
  601. itr->fsdata = parent->fsdata;
  602. if (clustnum > 0) {
  603. itr->clust = clustnum;
  604. itr->is_root = 0;
  605. } else {
  606. itr->clust = parent->fsdata->root_cluster;
  607. itr->is_root = 1;
  608. }
  609. itr->dent = NULL;
  610. itr->remaining = 0;
  611. itr->last_cluster = 0;
  612. }
  613. static void *next_cluster(fat_itr *itr)
  614. {
  615. fsdata *mydata = itr->fsdata; /* for silly macros */
  616. int ret;
  617. u32 sect;
  618. /* have we reached the end? */
  619. if (itr->last_cluster)
  620. return NULL;
  621. sect = clust_to_sect(itr->fsdata, itr->clust);
  622. debug("FAT read(sect=%d), clust_size=%d, DIRENTSPERBLOCK=%zd\n",
  623. sect, itr->fsdata->clust_size, DIRENTSPERBLOCK);
  624. /*
  625. * NOTE: do_fat_read_at() had complicated logic to deal w/
  626. * vfat names that span multiple clusters in the fat16 case,
  627. * which get_dentfromdir() probably also needed (and was
  628. * missing). And not entirely sure what fat32 didn't have
  629. * the same issue.. We solve that by only caring about one
  630. * dent at a time and iteratively constructing the vfat long
  631. * name.
  632. */
  633. ret = disk_read(sect, itr->fsdata->clust_size,
  634. itr->block);
  635. if (ret < 0) {
  636. debug("Error: reading block\n");
  637. return NULL;
  638. }
  639. if (itr->is_root && itr->fsdata->fatsize != 32) {
  640. itr->clust++;
  641. sect = clust_to_sect(itr->fsdata, itr->clust);
  642. if (sect - itr->fsdata->rootdir_sect >=
  643. itr->fsdata->rootdir_size) {
  644. debug("cursect: 0x%x\n", itr->clust);
  645. itr->last_cluster = 1;
  646. }
  647. } else {
  648. itr->clust = get_fatent(itr->fsdata, itr->clust);
  649. if (CHECK_CLUST(itr->clust, itr->fsdata->fatsize)) {
  650. debug("cursect: 0x%x\n", itr->clust);
  651. itr->last_cluster = 1;
  652. }
  653. }
  654. return itr->block;
  655. }
  656. static dir_entry *next_dent(fat_itr *itr)
  657. {
  658. if (itr->remaining == 0) {
  659. struct dir_entry *dent = next_cluster(itr);
  660. unsigned nbytes = itr->fsdata->sect_size *
  661. itr->fsdata->clust_size;
  662. /* have we reached the last cluster? */
  663. if (!dent)
  664. return NULL;
  665. itr->remaining = nbytes / sizeof(dir_entry) - 1;
  666. itr->dent = dent;
  667. } else {
  668. itr->remaining--;
  669. itr->dent++;
  670. }
  671. /* have we reached the last valid entry? */
  672. if (itr->dent->name[0] == 0)
  673. return NULL;
  674. return itr->dent;
  675. }
  676. static dir_entry *extract_vfat_name(fat_itr *itr)
  677. {
  678. struct dir_entry *dent = itr->dent;
  679. int seqn = itr->dent->name[0] & ~LAST_LONG_ENTRY_MASK;
  680. u8 chksum, alias_checksum = ((dir_slot *)dent)->alias_checksum;
  681. int n = 0;
  682. while (seqn--) {
  683. char buf[13];
  684. int idx = 0;
  685. slot2str((dir_slot *)dent, buf, &idx);
  686. /* shift accumulated long-name up and copy new part in: */
  687. memmove(itr->l_name + idx, itr->l_name, n);
  688. memcpy(itr->l_name, buf, idx);
  689. n += idx;
  690. dent = next_dent(itr);
  691. if (!dent)
  692. return NULL;
  693. }
  694. itr->l_name[n] = '\0';
  695. chksum = mkcksum(dent->name, dent->ext);
  696. /* checksum mismatch could mean deleted file, etc.. skip it: */
  697. if (chksum != alias_checksum) {
  698. debug("** chksum=%x, alias_checksum=%x, l_name=%s, s_name=%8s.%3s\n",
  699. chksum, alias_checksum, itr->l_name, dent->name, dent->ext);
  700. return NULL;
  701. }
  702. return dent;
  703. }
  704. /**
  705. * fat_itr_next() - step to the next entry in a directory
  706. *
  707. * Must be called once on a new iterator before the cursor is valid.
  708. *
  709. * @itr: the iterator to iterate
  710. * @return boolean, 1 if success or 0 if no more entries in the
  711. * current directory
  712. */
  713. static int fat_itr_next(fat_itr *itr)
  714. {
  715. dir_entry *dent;
  716. itr->name = NULL;
  717. while (1) {
  718. dent = next_dent(itr);
  719. if (!dent)
  720. return 0;
  721. if (dent->name[0] == DELETED_FLAG ||
  722. dent->name[0] == aRING)
  723. continue;
  724. if (dent->attr & ATTR_VOLUME) {
  725. if ((dent->attr & ATTR_VFAT) == ATTR_VFAT &&
  726. (dent->name[0] & LAST_LONG_ENTRY_MASK)) {
  727. dent = extract_vfat_name(itr);
  728. if (!dent)
  729. continue;
  730. itr->name = itr->l_name;
  731. break;
  732. } else {
  733. /* Volume label or VFAT entry, skip */
  734. continue;
  735. }
  736. }
  737. break;
  738. }
  739. get_name(dent, itr->s_name);
  740. if (!itr->name)
  741. itr->name = itr->s_name;
  742. return 1;
  743. }
  744. /**
  745. * fat_itr_isdir() - is current cursor position pointing to a directory
  746. *
  747. * @itr: the iterator
  748. * @return true if cursor is at a directory
  749. */
  750. static int fat_itr_isdir(fat_itr *itr)
  751. {
  752. return !!(itr->dent->attr & ATTR_DIR);
  753. }
  754. /*
  755. * Helpers:
  756. */
  757. #define TYPE_FILE 0x1
  758. #define TYPE_DIR 0x2
  759. #define TYPE_ANY (TYPE_FILE | TYPE_DIR)
  760. /**
  761. * fat_itr_resolve() - traverse directory structure to resolve the
  762. * requested path.
  763. *
  764. * Traverse directory structure to the requested path. If the specified
  765. * path is to a directory, this will descend into the directory and
  766. * leave it iterator at the start of the directory. If the path is to a
  767. * file, it will leave the iterator in the parent directory with current
  768. * cursor at file's entry in the directory.
  769. *
  770. * @itr: iterator initialized to root
  771. * @path: the requested path
  772. * @type: bitmask of allowable file types
  773. * @return 0 on success or -errno
  774. */
  775. static int fat_itr_resolve(fat_itr *itr, const char *path, unsigned type)
  776. {
  777. const char *next;
  778. /* chomp any extra leading slashes: */
  779. while (path[0] && ISDIRDELIM(path[0]))
  780. path++;
  781. /* are we at the end? */
  782. if (strlen(path) == 0) {
  783. if (!(type & TYPE_DIR))
  784. return -ENOENT;
  785. return 0;
  786. }
  787. /* find length of next path entry: */
  788. next = path;
  789. while (next[0] && !ISDIRDELIM(next[0]))
  790. next++;
  791. while (fat_itr_next(itr)) {
  792. int match = 0;
  793. unsigned n = max(strlen(itr->name), (size_t)(next - path));
  794. /* check both long and short name: */
  795. if (!strncasecmp(path, itr->name, n))
  796. match = 1;
  797. else if (itr->name != itr->s_name &&
  798. !strncasecmp(path, itr->s_name, n))
  799. match = 1;
  800. if (!match)
  801. continue;
  802. if (fat_itr_isdir(itr)) {
  803. /* recurse into directory: */
  804. fat_itr_child(itr, itr);
  805. return fat_itr_resolve(itr, next, type);
  806. } else if (next[0]) {
  807. /*
  808. * If next is not empty then we have a case
  809. * like: /path/to/realfile/nonsense
  810. */
  811. debug("bad trailing path: %s\n", next);
  812. return -ENOENT;
  813. } else if (!(type & TYPE_FILE)) {
  814. return -ENOTDIR;
  815. } else {
  816. return 0;
  817. }
  818. }
  819. return -ENOENT;
  820. }
  821. int file_fat_detectfs(void)
  822. {
  823. boot_sector bs;
  824. volume_info volinfo;
  825. int fatsize;
  826. char vol_label[12];
  827. if (cur_dev == NULL) {
  828. printf("No current device\n");
  829. return 1;
  830. }
  831. #if defined(CONFIG_IDE) || \
  832. defined(CONFIG_SATA) || \
  833. defined(CONFIG_SCSI) || \
  834. defined(CONFIG_CMD_USB) || \
  835. defined(CONFIG_MMC)
  836. printf("Interface: ");
  837. switch (cur_dev->if_type) {
  838. case IF_TYPE_IDE:
  839. printf("IDE");
  840. break;
  841. case IF_TYPE_SATA:
  842. printf("SATA");
  843. break;
  844. case IF_TYPE_SCSI:
  845. printf("SCSI");
  846. break;
  847. case IF_TYPE_ATAPI:
  848. printf("ATAPI");
  849. break;
  850. case IF_TYPE_USB:
  851. printf("USB");
  852. break;
  853. case IF_TYPE_DOC:
  854. printf("DOC");
  855. break;
  856. case IF_TYPE_MMC:
  857. printf("MMC");
  858. break;
  859. default:
  860. printf("Unknown");
  861. }
  862. printf("\n Device %d: ", cur_dev->devnum);
  863. dev_print(cur_dev);
  864. #endif
  865. if (read_bootsectandvi(&bs, &volinfo, &fatsize)) {
  866. printf("\nNo valid FAT fs found\n");
  867. return 1;
  868. }
  869. memcpy(vol_label, volinfo.volume_label, 11);
  870. vol_label[11] = '\0';
  871. volinfo.fs_type[5] = '\0';
  872. printf("Filesystem: %s \"%s\"\n", volinfo.fs_type, vol_label);
  873. return 0;
  874. }
  875. int fat_exists(const char *filename)
  876. {
  877. fsdata fsdata;
  878. fat_itr *itr;
  879. int ret;
  880. itr = malloc_cache_aligned(sizeof(fat_itr));
  881. if (!itr)
  882. return 0;
  883. ret = fat_itr_root(itr, &fsdata);
  884. if (ret)
  885. goto out;
  886. ret = fat_itr_resolve(itr, filename, TYPE_ANY);
  887. free(fsdata.fatbuf);
  888. out:
  889. free(itr);
  890. return ret == 0;
  891. }
  892. int fat_size(const char *filename, loff_t *size)
  893. {
  894. fsdata fsdata;
  895. fat_itr *itr;
  896. int ret;
  897. itr = malloc_cache_aligned(sizeof(fat_itr));
  898. if (!itr)
  899. return -ENOMEM;
  900. ret = fat_itr_root(itr, &fsdata);
  901. if (ret)
  902. goto out_free_itr;
  903. ret = fat_itr_resolve(itr, filename, TYPE_FILE);
  904. if (ret) {
  905. /*
  906. * Directories don't have size, but fs_size() is not
  907. * expected to fail if passed a directory path:
  908. */
  909. free(fsdata.fatbuf);
  910. fat_itr_root(itr, &fsdata);
  911. if (!fat_itr_resolve(itr, filename, TYPE_DIR)) {
  912. *size = 0;
  913. ret = 0;
  914. }
  915. goto out_free_both;
  916. }
  917. *size = FAT2CPU32(itr->dent->size);
  918. out_free_both:
  919. free(fsdata.fatbuf);
  920. out_free_itr:
  921. free(itr);
  922. return ret;
  923. }
  924. int file_fat_read_at(const char *filename, loff_t pos, void *buffer,
  925. loff_t maxsize, loff_t *actread)
  926. {
  927. fsdata fsdata;
  928. fat_itr *itr;
  929. int ret;
  930. itr = malloc_cache_aligned(sizeof(fat_itr));
  931. if (!itr)
  932. return -ENOMEM;
  933. ret = fat_itr_root(itr, &fsdata);
  934. if (ret)
  935. goto out_free_itr;
  936. ret = fat_itr_resolve(itr, filename, TYPE_FILE);
  937. if (ret)
  938. goto out_free_both;
  939. debug("reading %s at pos %llu\n", filename, pos);
  940. ret = get_contents(&fsdata, itr->dent, pos, buffer, maxsize, actread);
  941. out_free_both:
  942. free(fsdata.fatbuf);
  943. out_free_itr:
  944. free(itr);
  945. return ret;
  946. }
  947. int file_fat_read(const char *filename, void *buffer, int maxsize)
  948. {
  949. loff_t actread;
  950. int ret;
  951. ret = file_fat_read_at(filename, 0, buffer, maxsize, &actread);
  952. if (ret)
  953. return ret;
  954. else
  955. return actread;
  956. }
  957. int fat_read_file(const char *filename, void *buf, loff_t offset, loff_t len,
  958. loff_t *actread)
  959. {
  960. int ret;
  961. ret = file_fat_read_at(filename, offset, buf, len, actread);
  962. if (ret)
  963. printf("** Unable to read file %s **\n", filename);
  964. return ret;
  965. }
  966. typedef struct {
  967. struct fs_dir_stream parent;
  968. struct fs_dirent dirent;
  969. fsdata fsdata;
  970. fat_itr itr;
  971. } fat_dir;
  972. int fat_opendir(const char *filename, struct fs_dir_stream **dirsp)
  973. {
  974. fat_dir *dir;
  975. int ret;
  976. dir = malloc_cache_aligned(sizeof(*dir));
  977. if (!dir)
  978. return -ENOMEM;
  979. memset(dir, 0, sizeof(*dir));
  980. ret = fat_itr_root(&dir->itr, &dir->fsdata);
  981. if (ret)
  982. goto fail_free_dir;
  983. ret = fat_itr_resolve(&dir->itr, filename, TYPE_DIR);
  984. if (ret)
  985. goto fail_free_both;
  986. *dirsp = (struct fs_dir_stream *)dir;
  987. return 0;
  988. fail_free_both:
  989. free(dir->fsdata.fatbuf);
  990. fail_free_dir:
  991. free(dir);
  992. return ret;
  993. }
  994. int fat_readdir(struct fs_dir_stream *dirs, struct fs_dirent **dentp)
  995. {
  996. fat_dir *dir = (fat_dir *)dirs;
  997. struct fs_dirent *dent = &dir->dirent;
  998. if (!fat_itr_next(&dir->itr))
  999. return -ENOENT;
  1000. memset(dent, 0, sizeof(*dent));
  1001. strcpy(dent->name, dir->itr.name);
  1002. if (fat_itr_isdir(&dir->itr)) {
  1003. dent->type = FS_DT_DIR;
  1004. } else {
  1005. dent->type = FS_DT_REG;
  1006. dent->size = FAT2CPU32(dir->itr.dent->size);
  1007. }
  1008. *dentp = dent;
  1009. return 0;
  1010. }
  1011. void fat_closedir(struct fs_dir_stream *dirs)
  1012. {
  1013. fat_dir *dir = (fat_dir *)dirs;
  1014. free(dir->fsdata.fatbuf);
  1015. free(dir);
  1016. }
  1017. void fat_close(void)
  1018. {
  1019. }