fat.c 30 KB

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