ff.c 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - FAT file system module R0.07a (C)ChaN, 2009
  3. /-----------------------------------------------------------------------------/
  4. / FatFs module is an open source software to implement FAT file system to
  5. / small embedded systems. This is a free software and is opened for education,
  6. / research and commercial developments under license policy of following trems.
  7. /
  8. / Copyright (C) 2009, ChaN, all right reserved.
  9. /
  10. / * The FatFs module is a free software and there is NO WARRANTY.
  11. / * No restriction on use. You can use, modify and redistribute it for
  12. / personal, non-profit or commercial use UNDER YOUR RESPONSIBILITY.
  13. / * Redistributions of source code must retain the above copyright notice.
  14. //-----------------------------------------------------------------------------/
  15. / Feb 26,'06 R0.00 Prototype.
  16. /
  17. / Apr 29,'06 R0.01 First stable version.
  18. /
  19. / Jun 01,'06 R0.02 Added FAT12 support.
  20. / Removed unbuffered mode.
  21. / Fixed a problem on small (<32M) patition.
  22. / Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
  23. /
  24. / Sep 22,'06 R0.03 Added f_rename().
  25. / Changed option _FS_MINIMUM to _FS_MINIMIZE.
  26. / Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast.
  27. / Fixed f_mkdir() creates incorrect directory on FAT32.
  28. /
  29. / Feb 04,'07 R0.04 Supported multiple drive system.
  30. / Changed some interfaces for multiple drive system.
  31. / Changed f_mountdrv() to f_mount().
  32. / Added f_mkfs().
  33. / Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive.
  34. / Added a capability of extending file size to f_lseek().
  35. / Added minimization level 3.
  36. / Fixed an endian sensitive code in f_mkfs().
  37. / May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
  38. / Added FSInfo support.
  39. / Fixed DBCS name can result FR_INVALID_NAME.
  40. / Fixed short seek (<= csize) collapses the file object.
  41. /
  42. / Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs().
  43. / Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
  44. / Fixed f_mkdir() on FAT32 creates incorrect directory.
  45. / Feb 03,'08 R0.05a Added f_truncate() and f_utime().
  46. / Fixed off by one error at FAT sub-type determination.
  47. / Fixed btr in f_read() can be mistruncated.
  48. / Fixed cached sector is not flushed when create and close
  49. / without write.
  50. /
  51. / Apr 01,'08 R0.06 Added fputc(), fputs(), fprintf() and fgets().
  52. / Improved performance of f_lseek() on moving to the same
  53. / or following cluster.
  54. /
  55. / Apr 01,'09 R0.07 Merged Tiny-FatFs as a buffer configuration option.
  56. / Added long file name support.
  57. / Added multiple code page support.
  58. / Added re-entrancy for multitask operation.
  59. / Added auto cluster size selection to f_mkfs().
  60. / Added rewind option to f_readdir().
  61. / Changed result code of critical errors.
  62. / Renamed string functions to avoid name collision.
  63. / Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
  64. / Added multiple sector size support.
  65. /---------------------------------------------------------------------------*/
  66. #include "ff.h" /* FatFs configurations and declarations */
  67. #include "diskio.h" /* Declarations of low level disk I/O functions */
  68. /*--------------------------------------------------------------------------
  69. Module Private Definitions
  70. ---------------------------------------------------------------------------*/
  71. #if _FS_REENTRANT
  72. #if _USE_LFN == 1
  73. #error Static LFN work area must not be used in re-entrant configuration.
  74. #endif
  75. #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
  76. #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
  77. #else
  78. #define ENTER_FF(fs)
  79. #define LEAVE_FF(fs, res) return res
  80. #endif
  81. #define ABORT(fs, res) { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }
  82. #ifndef NULL
  83. #define NULL 0
  84. #endif
  85. /*--------------------------------------------------------------------------
  86. Private Work Area
  87. ---------------------------------------------------------------------------*/
  88. static
  89. FATFS *FatFs[_DRIVES]; /* Pointer to the file system objects (logical drives) */
  90. static
  91. WORD Fsid; /* File system mount ID */
  92. #if _USE_LFN == 1 /* LFN with static LFN working buffer */
  93. static
  94. WORD LfnBuf[_MAX_LFN + 1];
  95. #define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR *lp = LfnBuf
  96. #define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp
  97. #elif _USE_LFN > 1 /* LFN with dynamic LFN working buffer */
  98. #define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR lbuf[_MAX_LFN + 1], *lp = lbuf
  99. #define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp
  100. #else /* No LFN */
  101. #define NAMEBUF(sp,lp) BYTE sp[12]
  102. #define INITBUF(dj,sp,lp) dj.fn = sp
  103. #endif
  104. /*--------------------------------------------------------------------------
  105. Private Functions
  106. ---------------------------------------------------------------------------*/
  107. /*-----------------------------------------------------------------------*/
  108. /* String functions */
  109. /*-----------------------------------------------------------------------*/
  110. /* Copy memory to memory */
  111. static
  112. void mem_cpy (void* dst, const void* src, int cnt) {
  113. char *d = (char*)dst;
  114. const char *s = (const char *)src;
  115. while (cnt--) *d++ = *s++;
  116. }
  117. /* Fill memory */
  118. static
  119. void mem_set (void* dst, int val, int cnt) {
  120. char *d = (char*)dst;
  121. while (cnt--) *d++ = (char)val;
  122. }
  123. /* Compare memory to memory */
  124. static
  125. int mem_cmp (const void* dst, const void* src, int cnt) {
  126. const char *d = (const char *)dst, *s = (const char *)src;
  127. int r = 0;
  128. while (cnt-- && (r = *d++ - *s++) == 0) ;
  129. return r;
  130. }
  131. /* Check if chr is contained in the string */
  132. static
  133. int chk_chr (const char* str, int chr) {
  134. while (*str && *str != chr) str++;
  135. return *str;
  136. }
  137. /*-----------------------------------------------------------------------*/
  138. /* Request/Release grant to access the volume */
  139. /*-----------------------------------------------------------------------*/
  140. #if _FS_REENTRANT
  141. static
  142. BOOL lock_fs (
  143. FATFS *fs /* File system object */
  144. )
  145. {
  146. return ff_req_grant(fs->sobj);
  147. }
  148. static
  149. void unlock_fs (
  150. FATFS *fs, /* File system object */
  151. FRESULT res /* Result code to be returned */
  152. )
  153. {
  154. if (res != FR_NOT_ENABLED &&
  155. res != FR_INVALID_DRIVE &&
  156. res != FR_INVALID_OBJECT &&
  157. res != FR_TIMEOUT) {
  158. ff_rel_grant(fs->sobj);
  159. }
  160. }
  161. #endif
  162. /*-----------------------------------------------------------------------*/
  163. /* Change window offset */
  164. /*-----------------------------------------------------------------------*/
  165. static
  166. FRESULT move_window (
  167. FATFS *fs, /* File system object */
  168. DWORD sector /* Sector number to make apperance in the fs->win[] */
  169. ) /* Move to zero only writes back dirty window */
  170. {
  171. DWORD wsect;
  172. wsect = fs->winsect;
  173. if (wsect != sector) { /* Changed current window */
  174. #if !_FS_READONLY
  175. if (fs->wflag) { /* Write back dirty window if needed */
  176. if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK)
  177. return FR_DISK_ERR;
  178. fs->wflag = 0;
  179. if (wsect < (fs->fatbase + fs->sects_fat)) { /* In FAT area */
  180. BYTE nf;
  181. for (nf = fs->n_fats; nf >= 2; nf--) { /* Refrect the change to FAT copy */
  182. wsect += fs->sects_fat;
  183. disk_write(fs->drive, fs->win, wsect, 1);
  184. }
  185. }
  186. }
  187. #endif
  188. if (sector) {
  189. if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK)
  190. return FR_DISK_ERR;
  191. fs->winsect = sector;
  192. }
  193. }
  194. return FR_OK;
  195. }
  196. /*-----------------------------------------------------------------------*/
  197. /* Clean-up cached data */
  198. /*-----------------------------------------------------------------------*/
  199. #if !_FS_READONLY
  200. static
  201. FRESULT sync ( /* FR_OK: successful, FR_DISK_ERR: failed */
  202. FATFS *fs /* File system object */
  203. )
  204. {
  205. FRESULT res;
  206. res = move_window(fs, 0);
  207. if (res == FR_OK) {
  208. /* Update FSInfo sector if needed */
  209. if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
  210. fs->winsect = 0;
  211. mem_set(fs->win, 0, 512);
  212. ST_WORD(fs->win+BS_55AA, 0xAA55);
  213. ST_DWORD(fs->win+FSI_LeadSig, 0x41615252);
  214. ST_DWORD(fs->win+FSI_StrucSig, 0x61417272);
  215. ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust);
  216. ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);
  217. disk_write(fs->drive, fs->win, fs->fsi_sector, 1);
  218. fs->fsi_flag = 0;
  219. }
  220. /* Make sure that no pending write process in the physical drive */
  221. if (disk_ioctl(fs->drive, CTRL_SYNC, (void*)NULL) != RES_OK)
  222. res = FR_DISK_ERR;
  223. }
  224. return res;
  225. }
  226. #endif
  227. /*-----------------------------------------------------------------------*/
  228. /* Get a cluster status */
  229. /*-----------------------------------------------------------------------*/
  230. static
  231. DWORD get_cluster ( /* 0xFFFFFFFF:Disk error, 1:Interal error, Else:Cluster status */
  232. FATFS *fs, /* File system object */
  233. DWORD clst /* Cluster# to get the link information */
  234. )
  235. {
  236. WORD wc, bc;
  237. DWORD fsect;
  238. if (clst < 2 || clst >= fs->max_clust) /* Check cluster address range */
  239. return 1;
  240. fsect = fs->fatbase;
  241. switch (fs->fs_type) {
  242. case FS_FAT12 :
  243. bc = (WORD)clst * 3 / 2;
  244. if (move_window(fs, fsect + (bc / SS(fs)))) break;
  245. wc = fs->win[bc & (SS(fs) - 1)]; bc++;
  246. if (move_window(fs, fsect + (bc / SS(fs)))) break;
  247. wc |= (WORD)fs->win[bc & (SS(fs) - 1)] << 8;
  248. return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
  249. case FS_FAT16 :
  250. if (move_window(fs, fsect + (clst / (SS(fs) / 2)))) break;
  251. return LD_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)]);
  252. case FS_FAT32 :
  253. if (move_window(fs, fsect + (clst / (SS(fs) / 4)))) break;
  254. return LD_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF;
  255. }
  256. return 0xFFFFFFFF; /* An error occured at the disk I/O layer */
  257. }
  258. /*-----------------------------------------------------------------------*/
  259. /* Change a cluster status */
  260. /*-----------------------------------------------------------------------*/
  261. #if !_FS_READONLY
  262. static
  263. FRESULT put_cluster (
  264. FATFS *fs, /* File system object */
  265. DWORD clst, /* Cluster# to be changed (must be 2 to fs->max_clust-1) */
  266. DWORD val /* New value to mark the cluster */
  267. )
  268. {
  269. WORD bc;
  270. BYTE *p;
  271. DWORD fsect;
  272. FRESULT res;
  273. if (clst < 2 || clst >= fs->max_clust) { /* Check cluster address range */
  274. res = FR_INT_ERR;
  275. } else {
  276. fsect = fs->fatbase;
  277. switch (fs->fs_type) {
  278. case FS_FAT12 :
  279. bc = (WORD)clst * 3 / 2;
  280. res = move_window(fs, fsect + (bc / SS(fs)));
  281. if (res != FR_OK) break;
  282. p = &fs->win[bc & (SS(fs) - 1)];
  283. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  284. bc++;
  285. fs->wflag = 1;
  286. res = move_window(fs, fsect + (bc / SS(fs)));
  287. if (res != FR_OK) break;
  288. p = &fs->win[bc & (SS(fs) - 1)];
  289. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  290. break;
  291. case FS_FAT16 :
  292. res = move_window(fs, fsect + (clst / (SS(fs) / 2)));
  293. if (res != FR_OK) break;
  294. ST_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)], (WORD)val);
  295. break;
  296. case FS_FAT32 :
  297. res = move_window(fs, fsect + (clst / (SS(fs) / 4)));
  298. if (res != FR_OK) break;
  299. ST_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)], val);
  300. break;
  301. default :
  302. res = FR_INT_ERR;
  303. }
  304. fs->wflag = 1;
  305. }
  306. return res;
  307. }
  308. #endif /* !_FS_READONLY */
  309. /*-----------------------------------------------------------------------*/
  310. /* Remove a cluster chain */
  311. /*-----------------------------------------------------------------------*/
  312. #if !_FS_READONLY
  313. static
  314. FRESULT remove_chain (
  315. FATFS *fs, /* File system object */
  316. DWORD clst /* Cluster# to remove chain from */
  317. )
  318. {
  319. FRESULT res;
  320. DWORD nxt;
  321. if (clst < 2 || clst >= fs->max_clust) { /* Check cluster address range */
  322. res = FR_INT_ERR;
  323. } else {
  324. res = FR_OK;
  325. while (clst < fs->max_clust) { /* Not a last link? */
  326. nxt = get_cluster(fs, clst); /* Get cluster status */
  327. if (nxt == 0) break; /* Empty cluster? */
  328. if (nxt == 1) { res = FR_INT_ERR; break; } /* Internal error? */
  329. if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */
  330. res = put_cluster(fs, clst, 0); /* Mark the cluster "empty" */
  331. if (res != FR_OK) break;
  332. if (fs->free_clust != 0xFFFFFFFF) { /* Update FSInfo */
  333. fs->free_clust++;
  334. fs->fsi_flag = 1;
  335. }
  336. clst = nxt; /* Next cluster */
  337. }
  338. }
  339. return res;
  340. }
  341. #endif
  342. /*-----------------------------------------------------------------------*/
  343. /* Stretch or create a cluster chain */
  344. /*-----------------------------------------------------------------------*/
  345. #if !_FS_READONLY
  346. static
  347. DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  348. FATFS *fs, /* File system object */
  349. DWORD clst /* Cluster# to stretch. 0 means create a new chain. */
  350. )
  351. {
  352. DWORD cs, ncl, scl, mcl;
  353. mcl = fs->max_clust;
  354. if (clst == 0) { /* Create new chain */
  355. scl = fs->last_clust; /* Get suggested start point */
  356. if (scl == 0 || scl >= mcl) scl = 1;
  357. }
  358. else { /* Stretch existing chain */
  359. cs = get_cluster(fs, clst); /* Check the cluster status */
  360. if (cs < 2) return 1; /* It is an invalid cluster */
  361. if (cs < mcl) return cs; /* It is already followed by next cluster */
  362. scl = clst;
  363. }
  364. ncl = scl; /* Start cluster */
  365. for (;;) {
  366. ncl++; /* Next cluster */
  367. if (ncl >= mcl) { /* Wrap around */
  368. ncl = 2;
  369. if (ncl > scl) return 0; /* No free custer */
  370. }
  371. cs = get_cluster(fs, ncl); /* Get the cluster status */
  372. if (cs == 0) break; /* Found a free cluster */
  373. if (cs == 0xFFFFFFFF || cs == 1)/* An error occured */
  374. return cs;
  375. if (ncl == scl) return 0; /* No free custer */
  376. }
  377. if (put_cluster(fs, ncl, 0x0FFFFFFF)) /* Mark the new cluster "in use" */
  378. return 0xFFFFFFFF;
  379. if (clst != 0) { /* Link it to previous one if needed */
  380. if (put_cluster(fs, clst, ncl))
  381. return 0xFFFFFFFF;
  382. }
  383. fs->last_clust = ncl; /* Update FSINFO */
  384. if (fs->free_clust != 0xFFFFFFFF) {
  385. fs->free_clust--;
  386. fs->fsi_flag = 1;
  387. }
  388. return ncl; /* Return new cluster number */
  389. }
  390. #endif /* !_FS_READONLY */
  391. /*-----------------------------------------------------------------------*/
  392. /* Get sector# from cluster# */
  393. /*-----------------------------------------------------------------------*/
  394. static
  395. DWORD clust2sect ( /* !=0: sector number, 0: failed - invalid cluster# */
  396. FATFS *fs, /* File system object */
  397. DWORD clst /* Cluster# to be converted */
  398. )
  399. {
  400. clst -= 2;
  401. if (clst >= (fs->max_clust - 2)) return 0; /* Invalid cluster# */
  402. return clst * fs->csize + fs->database;
  403. }
  404. /*-----------------------------------------------------------------------*/
  405. /* Seek directory index */
  406. /*-----------------------------------------------------------------------*/
  407. static
  408. FRESULT dir_seek (
  409. DIR *dj, /* Pointer to directory object */
  410. WORD idx /* Directory index number */
  411. )
  412. {
  413. DWORD clst;
  414. WORD ic;
  415. dj->index = idx;
  416. clst = dj->sclust;
  417. if (clst == 1 || clst >= dj->fs->max_clust) /* Check start cluster range */
  418. return FR_INT_ERR;
  419. if (clst == 0) { /* Static table */
  420. if (idx >= dj->fs->n_rootdir) /* Index is out of range */
  421. return FR_INT_ERR;
  422. dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / 32);
  423. }
  424. else { /* Dynamic table */
  425. ic = SS(dj->fs) / 32 * dj->fs->csize; /* Indexes per cluster */
  426. while (idx >= ic) { /* Follow cluster chain */
  427. clst = get_cluster(dj->fs, clst); /* Get next cluster */
  428. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  429. if (clst < 2 || clst >= dj->fs->max_clust) /* Reached to end of table or int error */
  430. return FR_INT_ERR;
  431. idx -= ic;
  432. }
  433. dj->clust = clst;
  434. dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / 32);
  435. }
  436. dj->dir = dj->fs->win + (idx % (SS(dj->fs) / 32)) * 32;
  437. return FR_OK; /* Seek succeeded */
  438. }
  439. /*-----------------------------------------------------------------------*/
  440. /* Move directory index next */
  441. /*-----------------------------------------------------------------------*/
  442. static
  443. FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not streach */
  444. DIR *dj, /* Pointer to directory object */
  445. BOOL streach /* FALSE: Do not streach table, TRUE: Streach table if needed */
  446. )
  447. {
  448. DWORD clst;
  449. WORD i;
  450. i = dj->index + 1;
  451. if (!i || !dj->sect) /* Report EOT when index has reached 65535 */
  452. return FR_NO_FILE;
  453. if (!(i % (SS(dj->fs) / 32))) { /* Sector changed? */
  454. dj->sect++; /* Next sector */
  455. if (dj->sclust == 0) { /* Static table */
  456. if (i >= dj->fs->n_rootdir) /* Report EOT when end of table */
  457. return FR_NO_FILE;
  458. }
  459. else { /* Dynamic table */
  460. if (((i / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
  461. clst = get_cluster(dj->fs, dj->clust); /* Get next cluster */
  462. if (clst <= 1) return FR_INT_ERR;
  463. if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  464. if (clst >= dj->fs->max_clust) { /* When it reached end of dinamic table */
  465. #if !_FS_READONLY
  466. BYTE c;
  467. if (!streach) return FR_NO_FILE; /* When do not streach, report EOT */
  468. clst = create_chain(dj->fs, dj->clust); /* Streach cluster chain */
  469. if (clst == 0) return FR_DENIED; /* No free cluster */
  470. if (clst == 1) return FR_INT_ERR;
  471. if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  472. /* Clean-up streached table */
  473. if (move_window(dj->fs, 0)) return FR_DISK_ERR; /* Flush active window */
  474. mem_set(dj->fs->win, 0, SS(dj->fs)); /* Clear window buffer */
  475. dj->fs->winsect = clust2sect(dj->fs, clst); /* Cluster start sector */
  476. for (c = 0; c < dj->fs->csize; c++) { /* Fill the new cluster with 0 */
  477. dj->fs->wflag = 1;
  478. if (move_window(dj->fs, 0)) return FR_DISK_ERR;
  479. dj->fs->winsect++;
  480. }
  481. dj->fs->winsect -= c; /* Rewind window address */
  482. #else
  483. return FR_NO_FILE; /* Report EOT */
  484. #endif
  485. }
  486. dj->clust = clst; /* Initialize data for new cluster */
  487. dj->sect = clust2sect(dj->fs, clst);
  488. }
  489. }
  490. }
  491. dj->index = i;
  492. dj->dir = dj->fs->win + (i % (SS(dj->fs) / 32)) * 32;
  493. return FR_OK;
  494. }
  495. /*-----------------------------------------------------------------------*/
  496. /* Test/Pick/Fit an LFN segment from/to directory entry */
  497. /*-----------------------------------------------------------------------*/
  498. #if _USE_LFN
  499. static
  500. const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN chars in the directory entry */
  501. static
  502. BOOL test_lfn ( /* TRUE:Matched, FALSE:Not matched */
  503. WCHAR *lfnbuf, /* Pointer to the LFN to be compared */
  504. BYTE *dir /* Pointer to the directory entry containing a part of LFN */
  505. )
  506. {
  507. int i, s;
  508. WCHAR wc1, wc2;
  509. i = ((dir[LDIR_Ord] & 0xBF) - 1) * 13; /* Offset in the LFN buffer */
  510. s = 0;
  511. do {
  512. if (i >= _MAX_LFN) return FALSE; /* Out of buffer range? */
  513. wc1 = LD_WORD(dir+LfnOfs[s]); /* Get both characters to compare */
  514. wc2 = lfnbuf[i++];
  515. if (IsLower(wc1)) wc1 -= 0x20; /* Compare it (ignore case) */
  516. if (IsLower(wc2)) wc2 -= 0x20;
  517. if (wc1 != wc2) return FALSE;
  518. } while (++s < 13 && wc1); /* Repeat until last char or a NUL char is processed */
  519. return TRUE; /* The LFN entry matched */
  520. }
  521. static
  522. BOOL pick_lfn ( /* TRUE:Succeeded, FALSE:Buffer overflow */
  523. WCHAR *lfnbuf, /* Pointer to the Unicode-LFN buffer */
  524. BYTE *dir /* Pointer to the directory entry */
  525. )
  526. {
  527. int i, s;
  528. WCHAR wchr;
  529. i = ((dir[LDIR_Ord] & 0xBF) - 1) * 13; /* Offset in the LFN buffer */
  530. s = 0;
  531. do {
  532. wchr = LD_WORD(dir+LfnOfs[s]); /* Get an LFN char */
  533. if (!wchr) break; /* End of LFN? */
  534. if (i >= _MAX_LFN) return FALSE; /* Buffer overflow */
  535. lfnbuf[i++] = wchr; /* Store it */
  536. } while (++s < 13); /* Repeat until last char is copied */
  537. if (dir[LDIR_Ord] & 0x40) lfnbuf[i] = 0; /* Put terminator if last LFN entry */
  538. return TRUE;
  539. }
  540. #if !_FS_READONLY
  541. static
  542. void fit_lfn (
  543. const WCHAR *lfnbuf, /* Pointer to the LFN buffer */
  544. BYTE *dir, /* Pointer to the directory entry */
  545. BYTE ord, /* LFN order (1-20) */
  546. BYTE sum /* SFN sum */
  547. )
  548. {
  549. int i, s;
  550. WCHAR wchr;
  551. dir[LDIR_Chksum] = sum; /* Set check sum */
  552. dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
  553. dir[LDIR_Type] = 0;
  554. ST_WORD(dir+LDIR_FstClusLO, 0);
  555. i = (ord - 1) * 13; /* Offset in the LFN buffer */
  556. s = wchr = 0;
  557. do {
  558. if (wchr != 0xFFFF) wchr = lfnbuf[i++]; /* Get an effective char */
  559. ST_WORD(dir+LfnOfs[s], wchr); /* Put it */
  560. if (!wchr) wchr = 0xFFFF; /* Padding chars following last char */
  561. } while (++s < 13);
  562. if (wchr == 0xFFFF || !lfnbuf[i]) ord |= 0x40;/* Bottom LFN part is the start of LFN sequence */
  563. dir[LDIR_Ord] = ord; /* Set the LFN order */
  564. }
  565. #endif
  566. #endif
  567. /*-----------------------------------------------------------------------*/
  568. /* Create numbered name */
  569. /*-----------------------------------------------------------------------*/
  570. #if _USE_LFN
  571. void gen_numname (
  572. BYTE *dst, /* Pointer to genartated SFN */
  573. const BYTE *src, /* Pointer to source SFN to be modified */
  574. const WCHAR *lfn, /* Pointer to LFN */
  575. WORD num /* Sequense number */
  576. )
  577. {
  578. char ns[8];
  579. int i, j;
  580. mem_cpy(dst, src, 11);
  581. if (num > 5) { /* On many collisions, generate a hash number instead of sequencial number */
  582. do num = (num >> 1) + (num << 15) + (WORD)*lfn++; while (*lfn);
  583. }
  584. /* itoa */
  585. i = 7;
  586. do {
  587. ns[i--] = (num % 10) + '0';
  588. num /= 10;
  589. } while (num);
  590. ns[i] = '~';
  591. /* Append the number */
  592. for (j = 0; j < i && dst[j] != ' '; j++) {
  593. if (IsDBCS1(dst[j])) {
  594. if (j == i - 1) break;
  595. j++;
  596. }
  597. }
  598. do {
  599. dst[j++] = (i < 8) ? ns[i++] : ' ';
  600. } while (j < 8);
  601. }
  602. #endif
  603. /*-----------------------------------------------------------------------*/
  604. /* Calculate sum of an SFN */
  605. /*-----------------------------------------------------------------------*/
  606. #if _USE_LFN
  607. static
  608. BYTE sum_sfn (
  609. const BYTE *dir /* Ptr to directory entry */
  610. )
  611. {
  612. BYTE sum = 0;
  613. int n = 11;
  614. do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
  615. return sum;
  616. }
  617. #endif
  618. /*-----------------------------------------------------------------------*/
  619. /* Find an object in the directory */
  620. /*-----------------------------------------------------------------------*/
  621. static
  622. FRESULT dir_find (
  623. DIR *dj /* Pointer to the directory object linked to the file name */
  624. )
  625. {
  626. FRESULT res;
  627. BYTE a, c, lfen, ord, sum, *dir;
  628. res = dir_seek(dj, 0); /* Rewind directory object */
  629. if (res != FR_OK) return res;
  630. ord = sum = 0xFF; lfen = *(dj->fn+11) & 1;
  631. do {
  632. res = move_window(dj->fs, dj->sect);
  633. if (res != FR_OK) break;
  634. dir = dj->dir; /* Ptr to the directory entry of current index */
  635. c = dir[DIR_Name];
  636. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  637. a = dir[DIR_Attr] & AM_MASK;
  638. #if _USE_LFN /* LFN configuration */
  639. if (c == 0xE5 || c == '.' || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  640. ord = 0xFF;
  641. } else {
  642. if (a == AM_LFN) { /* An LFN entry is found */
  643. if (dj->lfn) {
  644. if (c & 0x40) { /* Is it start of LFN sequence? */
  645. sum = dir[LDIR_Chksum];
  646. c &= 0xBF; ord = c; /* LFN start order */
  647. dj->lfn_idx = dj->index;
  648. }
  649. /* Check LFN validity. Compare LFN if it is out of 8.3 format */
  650. ord = (c == ord && sum == dir[LDIR_Chksum] && (!lfen || test_lfn(dj->lfn, dir))) ? ord - 1 : 0xFF;
  651. }
  652. } else { /* An SFN entry is found */
  653. if (ord || sum != sum_sfn(dir)) { /* Did not LFN match? */
  654. dj->lfn_idx = 0xFFFF;
  655. ord = 0xFF;
  656. }
  657. if (lfen) { /* Match LFN if it is out of 8.3 format */
  658. if (ord == 0) break;
  659. } else { /* Match SFN if LFN is in 8.3 format */
  660. if (!mem_cmp(dir, dj->fn, 11)) break;
  661. }
  662. }
  663. }
  664. #else /* Non LFN configuration */
  665. if (c != 0xE5 && c != '.' && !(a & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */
  666. break;
  667. #endif
  668. res = dir_next(dj, FALSE); /* Next entry */
  669. } while (res == FR_OK);
  670. return res;
  671. }
  672. /*-----------------------------------------------------------------------*/
  673. /* Read an object from the directory */
  674. /*-----------------------------------------------------------------------*/
  675. #if _FS_MINIMIZE <= 2
  676. static
  677. FRESULT dir_read (
  678. DIR *dj /* Pointer to the directory object to store read object name */
  679. )
  680. {
  681. FRESULT res;
  682. BYTE a, c, ord, sum, *dir;
  683. ord = sum = 0xFF;
  684. res = FR_NO_FILE;
  685. while (dj->sect) {
  686. res = move_window(dj->fs, dj->sect);
  687. if (res != FR_OK) break;
  688. dir = dj->dir; /* Ptr to the directory entry of current index */
  689. c = dir[DIR_Name];
  690. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  691. a = dir[DIR_Attr] & AM_MASK;
  692. #if _USE_LFN /* LFN configuration */
  693. if (c == 0xE5 || c == '.' || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  694. ord = 0xFF;
  695. } else {
  696. if (a == AM_LFN) { /* An LFN entry is found */
  697. if (c & 0x40) { /* Is it start of LFN sequence? */
  698. sum = dir[LDIR_Chksum];
  699. c &= 0xBF; ord = c;
  700. dj->lfn_idx = dj->index;
  701. }
  702. /* Check LFN validity and capture it */
  703. ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
  704. } else { /* An SFN entry is found */
  705. if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN entry? */
  706. dj->lfn_idx = 0xFFFF; /* No LFN. */
  707. break;
  708. }
  709. }
  710. #else /* Non LFN configuration */
  711. if (c != 0xE5 && c != '.' && !(a & AM_VOL)) /* Is it a valid entry? */
  712. break;
  713. #endif
  714. res = dir_next(dj, FALSE); /* Next entry */
  715. if (res != FR_OK) break;
  716. }
  717. if (res != FR_OK) dj->sect = 0;
  718. return res;
  719. }
  720. #endif
  721. /*-----------------------------------------------------------------------*/
  722. /* Register an object to the directory */
  723. /*-----------------------------------------------------------------------*/
  724. #if !_FS_READONLY
  725. static
  726. FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
  727. DIR *dj /* Target directory with object name to be created */
  728. )
  729. {
  730. FRESULT res;
  731. BYTE c, *dir;
  732. #if _USE_LFN /* LFN configuration */
  733. WORD n, ne, is;
  734. BYTE sn[12], *fn, sum;
  735. WCHAR *lfn;
  736. fn = dj->fn; lfn = dj->lfn;
  737. mem_cpy(sn, fn, 12);
  738. if (sn[11] & 1) { /* When LFN is out of 8.3 format, generate a numbered name */
  739. fn[11] = 0; dj->lfn = NULL; /* Find only SFN */
  740. for (n = 1; n < 100; n++) {
  741. gen_numname(fn, sn, lfn, n); /* Generate a numbered name */
  742. res = dir_find(dj); /* Check if the name collides with existing SFN */
  743. if (res != FR_OK) break;
  744. }
  745. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  746. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  747. fn[11] = sn[11]; dj->lfn = lfn;
  748. }
  749. if (sn[11] & 2) { /* When eliminate LFN, reserve only an SFN entry. */
  750. ne = 1;
  751. } else { /* Otherwise reserve an SFN + LFN entries. */
  752. for (ne = 0; lfn[ne]; ne++) ;
  753. ne = (ne + 25) / 13;
  754. }
  755. /* Reserve contiguous entries */
  756. res = dir_seek(dj, 0);
  757. if (res != FR_OK) return res;
  758. n = is = 0;
  759. do {
  760. res = move_window(dj->fs, dj->sect);
  761. if (res != FR_OK) break;
  762. c = *dj->dir; /* Check the entry status */
  763. if (c == 0xE5 || c == 0) { /* Is it a blank entry? */
  764. if (n == 0) is = dj->index; /* First index of the contigulus entry */
  765. if (++n == ne) break; /* A contiguous entry that requiered count is found */
  766. } else {
  767. n = 0; /* Not a blank entry. Restart to search */
  768. }
  769. res = dir_next(dj, TRUE); /* Next entry with table streach */
  770. } while (res == FR_OK);
  771. if (res == FR_OK && ne > 1) { /* Initialize LFN entry if needed */
  772. res = dir_seek(dj, is);
  773. if (res == FR_OK) {
  774. sum = sum_sfn(dj->fn); /* Sum of the SFN tied to the LFN */
  775. ne--;
  776. do { /* Store LFN entries in bottom first */
  777. res = move_window(dj->fs, dj->sect);
  778. if (res != FR_OK) break;
  779. fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum);
  780. dj->fs->wflag = 1;
  781. res = dir_next(dj, FALSE); /* Next entry */
  782. } while (res == FR_OK && --ne);
  783. }
  784. }
  785. #else /* Non LFN configuration */
  786. res = dir_seek(dj, 0);
  787. if (res == FR_OK) {
  788. do { /* Find a blank entry for the SFN */
  789. res = move_window(dj->fs, dj->sect);
  790. if (res != FR_OK) break;
  791. c = *dj->dir;
  792. if (c == 0xE5 || c == 0) break; /* Is it a blank entry? */
  793. res = dir_next(dj, TRUE); /* Next entry with table streach */
  794. } while (res == FR_OK);
  795. }
  796. #endif
  797. if (res == FR_OK) { /* Initialize the SFN entry */
  798. res = move_window(dj->fs, dj->sect);
  799. if (res == FR_OK) {
  800. dir = dj->dir;
  801. mem_set(dir, 0, 32); /* Clean the entry */
  802. mem_cpy(dir, dj->fn, 11); /* Put SFN */
  803. dir[DIR_NTres] = *(dj->fn+11) & 0x18; /* Put NT flag */
  804. dj->fs->wflag = 1;
  805. }
  806. }
  807. return res;
  808. }
  809. #endif /* !_FS_READONLY */
  810. /*-----------------------------------------------------------------------*/
  811. /* Remove an object from the directory */
  812. /*-----------------------------------------------------------------------*/
  813. #if !_FS_READONLY && !_FS_MINIMIZE
  814. static
  815. FRESULT dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */
  816. DIR *dj /* Directory object pointing the entry to be removed */
  817. )
  818. {
  819. FRESULT res;
  820. #if _USE_LFN /* LFN configuration */
  821. WORD i;
  822. i = dj->index; /* SFN index */
  823. res = dir_seek(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx)); /* Goto the SFN or top of the LFN entries */
  824. if (res == FR_OK) {
  825. do {
  826. res = move_window(dj->fs, dj->sect);
  827. if (res != FR_OK) break;
  828. *dj->dir = 0xE5; /* Mark the entry "deleted" */
  829. dj->fs->wflag = 1;
  830. if (dj->index >= i) break; /* When SFN is deleted, all entries of the object is deleted. */
  831. res = dir_next(dj, FALSE); /* Next entry */
  832. } while (res == FR_OK);
  833. if (res == FR_NO_FILE) res = FR_INT_ERR;
  834. }
  835. #else /* Non LFN configuration */
  836. res = dir_seek(dj, dj->index);
  837. if (res == FR_OK) {
  838. res = move_window(dj->fs, dj->sect);
  839. if (res == FR_OK) {
  840. *dj->dir = 0xE5; /* Mark the entry "deleted" */
  841. dj->fs->wflag = 1;
  842. }
  843. }
  844. #endif
  845. return res;
  846. }
  847. #endif /* !_FS_READONLY */
  848. /*-----------------------------------------------------------------------*/
  849. /* Pick a segment and create the object name in directory form */
  850. /*-----------------------------------------------------------------------*/
  851. static
  852. FRESULT create_name (
  853. DIR *dj, /* Pointer to the directory object */
  854. const char **path /* Pointer to pointer to the segment in the path string */
  855. )
  856. {
  857. #if _USE_LFN
  858. BYTE c, b, cf, *sfn;
  859. WCHAR w, *lfn;
  860. int i, ni, si, di;
  861. const char *p;
  862. /* Create LFN in Unicode */
  863. si = di = 0;
  864. p = *path;
  865. lfn = dj->lfn;
  866. for (;;) {
  867. w = (BYTE)p[si++]; /* Get a character */
  868. if (w < ' ' || w == '/' || w == '\\') break; /* Break on end of segment */
  869. if (IsDBCS1(w)) { /* If it is DBC 1st byte */
  870. c = p[si++]; /* Get 2nd byte */
  871. if (!IsDBCS2(c)) /* Reject invalid DBC */
  872. return FR_INVALID_NAME;
  873. w = (w << 8) + c;
  874. } else {
  875. if (chk_chr("\"*:<>\?|\x7F", w)) /* Reject unallowable chars for LFN */
  876. return FR_INVALID_NAME;
  877. }
  878. w = ff_convert(w, 1); /* Convert OEM to Unicode, store it */
  879. if (!w || di >= _MAX_LFN) /* Reject invalid code or too long name */
  880. return FR_INVALID_NAME;
  881. lfn[di++] = w;
  882. }
  883. *path = &p[si]; /* Rerurn pointer to the next segment */
  884. cf = (w < ' ') ? 4 : 0; /* Set last segment flag if end of path */
  885. while (di) { /* Strip trailing spaces and dots */
  886. w = lfn[di - 1];
  887. if (w != ' ' && w != '.') break;
  888. di--;
  889. }
  890. if (!di) return FR_INVALID_NAME; /* Reject null string */
  891. lfn[di] = 0; /* LFN is created */
  892. /* Create SFN in directory form */
  893. sfn = dj->fn;
  894. mem_set(sfn, ' ', 11);
  895. for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
  896. if (si) cf |= 1;
  897. while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
  898. b = i = 0; ni = 8;
  899. for (;;) {
  900. w = lfn[si++]; /* Get an LFN char */
  901. if (w == 0) break; /* Break when enf of the LFN */
  902. if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
  903. cf |= 1; continue;
  904. }
  905. if (i >= ni || si == di) { /* Here is extension or end of SFN */
  906. if (ni == 11) { /* Extension is longer than 3 bytes */
  907. cf |= 1; break;
  908. }
  909. if (si != di) cf |= 1; /* File name is longer than 8 bytes */
  910. if (si > di) break; /* No extension */
  911. si = di; i = 8; ni = 11; /* Enter extension section */
  912. b <<= 2; continue;
  913. }
  914. w = ff_convert(w, 0); /* Unicode -> OEM code */
  915. if (w >= 0x80) cf |= 0x20; /* If there is any extended char, force create an LFN */
  916. if (w >= 0x100) { /* Double byte char */
  917. if (i >= ni - 1) {
  918. cf |= 1; i = ni; continue;
  919. }
  920. sfn[i++] = (BYTE)(w >> 8);
  921. } else { /* Single byte char */
  922. if (chk_chr("+,;[=]", w)) { /* Replace unallowable chars for SFN */
  923. w = '_'; cf |= 1;
  924. } else {
  925. if (IsUpper(w)) { /* Large capital */
  926. b |= 2;
  927. } else {
  928. if (IsLower(w)) { /* Small capital */
  929. b |= 1; w -= 0x20;
  930. }
  931. }
  932. }
  933. }
  934. sfn[i++] = (BYTE)w;
  935. }
  936. if (sfn[0] == 0xE5) sfn[0] = 0x05; /* When first char collides with 0xE5, replace it with 0x05 */
  937. if (ni == 8) b <<= 2;
  938. if ((cf & 0x21) == 0) { /* When LFN is in 8.3 format without extended char, NT flags are created */
  939. if ((b & 0x03) == 0x01) cf |= 0x10; /* NT flag (Extension has only small capital) */
  940. if ((b & 0x0C) == 0x04) cf |= 0x08; /* NT flag (Filename has only small capital) */
  941. if ((b & 0x0C) != 0x0C && (b & 0x03) != 0x03) cf |= 2; /* Eliminate LFN when non composite capitals */
  942. }
  943. sfn[11] = cf; /* SFN is created */
  944. #else
  945. BYTE c, d, b, *sfn;
  946. int ni, si, i;
  947. const char *p;
  948. /* Create file name in directory form */
  949. sfn = dj->fn;
  950. mem_set(sfn, ' ', 11);
  951. si = i = b = 0; ni = 8;
  952. p = *path;
  953. for (;;) {
  954. c = p[si++];
  955. if (c < ' ' || c == '/' || c == '\\') break; /* Break on end of segment */
  956. if (c == '.' || i >= ni) {
  957. if (ni != 8 || c != '.') return FR_INVALID_NAME;
  958. i = 8; ni = 11;
  959. b <<= 2; continue;
  960. }
  961. if (c >= 0x80) b |= 3; /* If there is any extended char, eliminate NT flag */
  962. if (IsDBCS1(c)) { /* If it is DBC 1st byte */
  963. d = p[si++]; /* Get 2nd byte */
  964. if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */
  965. return FR_INVALID_NAME;
  966. sfn[i++] = c;
  967. sfn[i++] = d;
  968. } else {
  969. if (chk_chr(" +,;[=]\"*:<>\?|\x7F", c)) /* Reject unallowable chrs for SFN */
  970. return FR_INVALID_NAME;
  971. if (IsUpper(c)) {
  972. b |= 2;
  973. } else {
  974. if (IsLower(c)) {
  975. b |= 1; c -= 0x20;
  976. }
  977. }
  978. sfn[i++] = c;
  979. }
  980. }
  981. *path = &p[si]; /* Rerurn pointer to the next segment */
  982. c = (c < ' ') ? 4 : 0; /* Set last segment flag if end of path */
  983. if (!i) return FR_INVALID_NAME; /* Reject null string */
  984. if (sfn[0] == 0xE5) sfn[0] = 0x05; /* When first char collides with 0xE5, replace it with 0x05 */
  985. if (ni == 8) b <<= 2;
  986. if ((b & 0x03) == 0x01) c |= 0x10; /* NT flag (Extension has only small capital) */
  987. if ((b & 0x0C) == 0x04) c |= 0x08; /* NT flag (Filename has only small capital) */
  988. sfn[11] = c; /* Store NT flag, File name is created */
  989. #endif
  990. return FR_OK;
  991. }
  992. /*-----------------------------------------------------------------------*/
  993. /* Get file information from directory entry */
  994. /*-----------------------------------------------------------------------*/
  995. #if _FS_MINIMIZE <= 1
  996. static
  997. void get_fileinfo ( /* No return code */
  998. DIR *dj, /* Pointer to the directory object */
  999. FILINFO *fno /* Pointer to store the file information */
  1000. )
  1001. {
  1002. int i;
  1003. BYTE c, nt, *dir;
  1004. char *p;
  1005. p = fno->fname;
  1006. if (dj->sect) {
  1007. dir = dj->dir;
  1008. nt = dir[DIR_NTres]; /* NT flag */
  1009. for (i = 0; i < 8; i++) { /* Copy file name body */
  1010. c = dir[i];
  1011. if (c == ' ') break;
  1012. if (c == 0x05) c = 0xE5;
  1013. if ((nt & 0x08) && IsUpper(c)) c += 0x20;
  1014. *p++ = c;
  1015. }
  1016. if (dir[8] != ' ') { /* Copy file name extension */
  1017. *p++ = '.';
  1018. for (i = 8; i < 11; i++) {
  1019. c = dir[i];
  1020. if (c == ' ') break;
  1021. if ((nt & 0x10) && IsUpper(c)) c += 0x20;
  1022. *p++ = c;
  1023. }
  1024. }
  1025. fno->fattrib = dir[DIR_Attr]; /* Attribute */
  1026. fno->fsize = LD_DWORD(dir+DIR_FileSize); /* Size */
  1027. fno->fdate = LD_WORD(dir+DIR_WrtDate); /* Date */
  1028. fno->ftime = LD_WORD(dir+DIR_WrtTime); /* Time */
  1029. }
  1030. *p = 0;
  1031. #if _USE_LFN
  1032. p = fno->lfname;
  1033. if (p) {
  1034. WCHAR wchr, *lfn;
  1035. i = 0;
  1036. if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */
  1037. lfn = dj->lfn;
  1038. while ((wchr = *lfn++) != 0) { /* Get an LFN char */
  1039. wchr = ff_convert(wchr, 0); /* Unicode -> OEM code */
  1040. if (!wchr) { i = 0; break; } /* Conversion error, no LFN */
  1041. if (_DF1S && wchr >= 0x100) /* Put 1st byte if it is a DBC */
  1042. p[i++] = (char)(wchr >> 8);
  1043. p[i++] = (char)wchr;
  1044. if (i >= fno->lfsize) { i = 0; break; } /* Buffer overrun, no LFN */
  1045. }
  1046. }
  1047. p[i] = 0; /* Terminator */
  1048. }
  1049. #endif
  1050. }
  1051. #endif /* _FS_MINIMIZE <= 1 */
  1052. /*-----------------------------------------------------------------------*/
  1053. /* Follow a file path */
  1054. /*-----------------------------------------------------------------------*/
  1055. static
  1056. FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  1057. DIR *dj, /* Directory object to return last directory and found object */
  1058. const char *path /* Full-path string to find a file or directory */
  1059. )
  1060. {
  1061. FRESULT res;
  1062. BYTE *dir, last;
  1063. if (*path == '/' || *path == '\\' ) path++; /* Strip heading separator */
  1064. dj->sclust = /* Set start directory (root dir) */
  1065. (dj->fs->fs_type == FS_FAT32) ? dj->fs->dirbase : 0;
  1066. if ((BYTE)*path < ' ') { /* Null path means the root directory */
  1067. res = dir_seek(dj, 0);
  1068. dj->dir = NULL;
  1069. } else { /* Follow path */
  1070. for (;;) {
  1071. res = create_name(dj, &path); /* Get a segment */
  1072. if (res != FR_OK) break;
  1073. res = dir_find(dj); /* Find it */
  1074. last = *(dj->fn+11) & 4;
  1075. if (res != FR_OK) { /* Could not find the object */
  1076. if (res == FR_NO_FILE && !last)
  1077. res = FR_NO_PATH;
  1078. break;
  1079. }
  1080. if (last) break; /* Last segment match. Function completed. */
  1081. dir = dj->dir; /* There is next segment. Follow the sub directory */
  1082. if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */
  1083. res = FR_NO_PATH; break;
  1084. }
  1085. dj->sclust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
  1086. }
  1087. }
  1088. return res;
  1089. }
  1090. /*-----------------------------------------------------------------------*/
  1091. /* Load boot record and check if it is an FAT boot record */
  1092. /*-----------------------------------------------------------------------*/
  1093. static
  1094. BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record, 3:Error */
  1095. FATFS *fs, /* File system object */
  1096. DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */
  1097. )
  1098. {
  1099. if (disk_read(fs->drive, fs->win, sect, 1) != RES_OK) /* Load boot record */
  1100. return 3;
  1101. if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */
  1102. return 2;
  1103. if (!mem_cmp(&fs->win[BS_FilSysType], "FAT", 3)) /* Check FAT signature */
  1104. return 0;
  1105. if (!mem_cmp(&fs->win[BS_FilSysType32], "FAT32", 5) && !(fs->win[BPB_ExtFlags] & 0x80))
  1106. return 0;
  1107. return 1;
  1108. }
  1109. /*-----------------------------------------------------------------------*/
  1110. /* Make sure that the file system is valid */
  1111. /*-----------------------------------------------------------------------*/
  1112. static
  1113. FRESULT auto_mount ( /* FR_OK(0): successful, !=0: any error occured */
  1114. const char **path, /* Pointer to pointer to the path name (drive number) */
  1115. FATFS **rfs, /* Pointer to pointer to the found file system object */
  1116. BYTE chk_wp /* !=0: Check media write protection for write access */
  1117. )
  1118. {
  1119. FRESULT res;
  1120. BYTE vol, fmt, *tbl;
  1121. DSTATUS stat;
  1122. DWORD bsect, fsize, tsect, mclst;
  1123. const char *p = *path;
  1124. FATFS *fs;
  1125. /* Get logical drive number from the path name */
  1126. vol = p[0] - '0'; /* Is there a drive number? */
  1127. if (vol <= 9 && p[1] == ':') {
  1128. p += 2; /* Found a drive number, get and strip it */
  1129. *path = p; /* Return pointer to the path name */
  1130. } else {
  1131. vol = 0; /* No drive number is given, use drive number 0 as default */
  1132. }
  1133. /* Check if the logical drive number is valid or not */
  1134. if (vol >= _DRIVES) return FR_INVALID_DRIVE; /* Is the drive number valid? */
  1135. *rfs = fs = FatFs[vol]; /* Returen pointer to the corresponding file system object */
  1136. if (!fs) return FR_NOT_ENABLED; /* Is the file system object registered? */
  1137. ENTER_FF(fs); /* Lock file system */
  1138. if (fs->fs_type) { /* If the logical drive has been mounted */
  1139. stat = disk_status(fs->drive);
  1140. if (!(stat & STA_NOINIT)) { /* and physical drive is kept initialized (has not been changed), */
  1141. #if !_FS_READONLY
  1142. if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
  1143. return FR_WRITE_PROTECTED;
  1144. #endif
  1145. return FR_OK; /* The file system object is valid */
  1146. }
  1147. }
  1148. /* The logical drive must be re-mounted. Following code attempts to mount the volume */
  1149. fs->fs_type = 0; /* Clear the file system object */
  1150. fs->drive = LD2PD(vol); /* Bind the logical drive and a physical drive */
  1151. stat = disk_initialize(fs->drive); /* Initialize low level disk I/O layer */
  1152. if (stat & STA_NOINIT) /* Check if the drive is ready */
  1153. return FR_NOT_READY;
  1154. #if _MAX_SS != 512 /* Get disk sector size if needed */
  1155. if (disk_ioctl(fs->drive, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > _MAX_SS)
  1156. return FR_NO_FILESYSTEM;
  1157. #endif
  1158. #if !_FS_READONLY
  1159. if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
  1160. return FR_WRITE_PROTECTED;
  1161. #endif
  1162. /* Search FAT partition on the drive */
  1163. fmt = check_fs(fs, bsect = 0); /* Check sector 0 as an SFD format */
  1164. if (fmt == 1) { /* Not an FAT boot record, it may be patitioned */
  1165. /* Check a partition listed in top of the partition table */
  1166. tbl = &fs->win[MBR_Table + LD2PT(vol) * 16]; /* Partition table */
  1167. if (tbl[4]) { /* Is the partition existing? */
  1168. bsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */
  1169. fmt = check_fs(fs, bsect); /* Check the partition */
  1170. }
  1171. }
  1172. if (fmt == 3) return FR_DISK_ERR;
  1173. if (fmt || LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs)) /* No valid FAT patition is found */
  1174. return FR_NO_FILESYSTEM;
  1175. /* Initialize the file system object */
  1176. fsize = LD_WORD(fs->win+BPB_FATSz16); /* Number of sectors per FAT */
  1177. if (!fsize) fsize = LD_DWORD(fs->win+BPB_FATSz32);
  1178. fs->sects_fat = fsize;
  1179. fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */
  1180. fsize *= fs->n_fats; /* (Number of sectors in FAT area) */
  1181. fs->fatbase = bsect + LD_WORD(fs->win+BPB_RsvdSecCnt); /* FAT start sector (lba) */
  1182. fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */
  1183. fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt); /* Nmuber of root directory entries */
  1184. tsect = LD_WORD(fs->win+BPB_TotSec16); /* Number of sectors on the file system */
  1185. if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32);
  1186. fs->max_clust = mclst = (tsect /* Last cluster# + 1 */
  1187. - LD_WORD(fs->win+BPB_RsvdSecCnt) - fsize - fs->n_rootdir / (SS(fs)/32)
  1188. ) / fs->csize + 2;
  1189. fmt = FS_FAT12; /* Determine the FAT sub type */
  1190. if (mclst >= 0xFF7) fmt = FS_FAT16; /* Number of clusters >= 0xFF5 */
  1191. if (mclst >= 0xFFF7) fmt = FS_FAT32; /* Number of clusters >= 0xFFF5 */
  1192. if (fmt == FS_FAT32)
  1193. fs->dirbase = LD_DWORD(fs->win+BPB_RootClus); /* Root directory start cluster */
  1194. else
  1195. fs->dirbase = fs->fatbase + fsize; /* Root directory start sector (lba) */
  1196. fs->database = fs->fatbase + fsize + fs->n_rootdir / (SS(fs)/32); /* Data start sector (lba) */
  1197. #if !_FS_READONLY
  1198. /* Initialize allocation information */
  1199. fs->free_clust = 0xFFFFFFFF;
  1200. fs->wflag = 0;
  1201. /* Get fsinfo if needed */
  1202. if (fmt == FS_FAT32) {
  1203. fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo);
  1204. fs->fsi_flag = 0;
  1205. if (disk_read(fs->drive, fs->win, fs->fsi_sector, 1) == RES_OK &&
  1206. LD_WORD(fs->win+BS_55AA) == 0xAA55 &&
  1207. LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 &&
  1208. LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) {
  1209. fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free);
  1210. fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count);
  1211. }
  1212. }
  1213. #endif
  1214. fs->winsect = 0;
  1215. fs->fs_type = fmt; /* FAT syb-type */
  1216. fs->id = ++Fsid; /* File system mount ID */
  1217. res = FR_OK;
  1218. return res;
  1219. }
  1220. /*-----------------------------------------------------------------------*/
  1221. /* Check if the file/dir object is valid or not */
  1222. /*-----------------------------------------------------------------------*/
  1223. static
  1224. FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
  1225. FATFS *fs, /* Pointer to the file system object */
  1226. WORD id /* Member id of the target object to be checked */
  1227. )
  1228. {
  1229. if (!fs || !fs->fs_type || fs->id != id)
  1230. return FR_INVALID_OBJECT;
  1231. ENTER_FF(fs); /* Lock file system */
  1232. if (disk_status(fs->drive) & STA_NOINIT)
  1233. return FR_NOT_READY;
  1234. return FR_OK;
  1235. }
  1236. /*--------------------------------------------------------------------------
  1237. Public Functions
  1238. --------------------------------------------------------------------------*/
  1239. /*-----------------------------------------------------------------------*/
  1240. /* Mount/Unmount a Locical Drive */
  1241. /*-----------------------------------------------------------------------*/
  1242. FRESULT f_mount (
  1243. BYTE vol, /* Logical drive number to be mounted/unmounted */
  1244. FATFS *fs /* Pointer to new file system object (NULL for unmount)*/
  1245. )
  1246. {
  1247. FATFS *rfs;
  1248. if (vol >= _DRIVES) /* Check if the drive number is valid */
  1249. return FR_INVALID_DRIVE;
  1250. rfs = FatFs[vol]; /* Get current state */
  1251. if (rfs) {
  1252. #if _FS_REENTRANT /* Discard sync object of the current volume */
  1253. if (!ff_del_syncobj(fs->sobj)) return FR_INT_ERR;
  1254. #endif
  1255. rfs->fs_type = 0; /* Clear old fs object */
  1256. }
  1257. if (fs) {
  1258. fs->fs_type = 0; /* Clear new fs object */
  1259. #if _FS_REENTRANT /* Create sync object for the new volume */
  1260. if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;
  1261. #endif
  1262. }
  1263. FatFs[vol] = fs; /* Register new fs object */
  1264. return FR_OK;
  1265. }
  1266. /*-----------------------------------------------------------------------*/
  1267. /* Open or Create a File */
  1268. /*-----------------------------------------------------------------------*/
  1269. FRESULT f_open (
  1270. FIL *fp, /* Pointer to the blank file object */
  1271. const char *path, /* Pointer to the file name */
  1272. BYTE mode /* Access mode and file open mode flags */
  1273. )
  1274. {
  1275. FRESULT res;
  1276. DIR dj;
  1277. NAMEBUF(sfn, lfn);
  1278. BYTE *dir;
  1279. fp->fs = NULL; /* Clear file object */
  1280. #if !_FS_READONLY
  1281. mode &= (FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW);
  1282. res = auto_mount(&path, &dj.fs, (BYTE)(mode & (FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)));
  1283. #else
  1284. mode &= FA_READ;
  1285. res = auto_mount(&path, &dj.fs, 0);
  1286. #endif
  1287. if (res != FR_OK) LEAVE_FF(dj.fs, res);
  1288. INITBUF(dj, sfn, lfn);
  1289. res = follow_path(&dj, path); /* Follow the file path */
  1290. #if !_FS_READONLY
  1291. /* Create or Open a file */
  1292. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  1293. DWORD ps, cl;
  1294. if (res != FR_OK) { /* No file, create new */
  1295. if (res == FR_NO_FILE)
  1296. res = dir_register(&dj);
  1297. if (res != FR_OK) LEAVE_FF(dj.fs, res);
  1298. mode |= FA_CREATE_ALWAYS;
  1299. dir = dj.dir;
  1300. }
  1301. else { /* Any object is already existing */
  1302. if (mode & FA_CREATE_NEW) /* Cannot create new */
  1303. LEAVE_FF(dj.fs, FR_EXIST);
  1304. dir = dj.dir;
  1305. if (!dir || (dir[DIR_Attr] & (AM_RDO | AM_DIR))) /* Cannot overwrite it (R/O or DIR) */
  1306. LEAVE_FF(dj.fs, FR_DENIED);
  1307. if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero if needed */
  1308. cl = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO); /* Get start cluster */
  1309. ST_WORD(dir+DIR_FstClusHI, 0); /* cluster = 0 */
  1310. ST_WORD(dir+DIR_FstClusLO, 0);
  1311. ST_DWORD(dir+DIR_FileSize, 0); /* size = 0 */
  1312. dj.fs->wflag = 1;
  1313. ps = dj.fs->winsect; /* Remove the cluster chain */
  1314. if (cl) {
  1315. res = remove_chain(dj.fs, cl);
  1316. if (res) LEAVE_FF(dj.fs, res);
  1317. dj.fs->last_clust = cl - 1; /* Reuse the cluster hole */
  1318. }
  1319. res = move_window(dj.fs, ps);
  1320. if (res != FR_OK) LEAVE_FF(dj.fs, res);
  1321. }
  1322. }
  1323. if (mode & FA_CREATE_ALWAYS) {
  1324. dir[DIR_Attr] = 0; /* Reset attribute */
  1325. ps = get_fattime();
  1326. ST_DWORD(dir+DIR_CrtTime, ps); /* Created time */
  1327. dj.fs->wflag = 1;
  1328. mode |= FA__WRITTEN; /* Set file changed flag */
  1329. }
  1330. }
  1331. /* Open an existing file */
  1332. else {
  1333. #endif /* !_FS_READONLY */
  1334. if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */
  1335. dir = dj.dir;
  1336. if (!dir || (dir[DIR_Attr] & AM_DIR)) /* It is a directory */
  1337. LEAVE_FF(dj.fs, FR_NO_FILE);
  1338. #if !_FS_READONLY
  1339. if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
  1340. LEAVE_FF(dj.fs, FR_DENIED);
  1341. }
  1342. fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */
  1343. fp->dir_ptr = dj.dir;
  1344. #endif
  1345. fp->flag = mode; /* File access mode */
  1346. fp->org_clust = /* File start cluster */
  1347. ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
  1348. fp->fsize = LD_DWORD(dir+DIR_FileSize); /* File size */
  1349. fp->fptr = 0; fp->csect = 255; /* File pointer */
  1350. fp->dsect = 0;
  1351. fp->fs = dj.fs; fp->id = dj.fs->id; /* Owner file system object of the file */
  1352. LEAVE_FF(dj.fs, FR_OK);
  1353. }
  1354. /*-----------------------------------------------------------------------*/
  1355. /* Read File */
  1356. /*-----------------------------------------------------------------------*/
  1357. FRESULT f_read (
  1358. FIL *fp, /* Pointer to the file object */
  1359. void *buff, /* Pointer to data buffer */
  1360. UINT btr, /* Number of bytes to read */
  1361. UINT *br /* Pointer to number of bytes read */
  1362. )
  1363. {
  1364. FRESULT res;
  1365. DWORD clst, sect, remain;
  1366. UINT rcnt, cc;
  1367. BYTE *rbuff = buff;
  1368. *br = 0;
  1369. res = validate(fp->fs, fp->id); /* Check validity of the object */
  1370. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  1371. if (fp->flag & FA__ERROR) /* Check abort flag */
  1372. LEAVE_FF(fp->fs, FR_INT_ERR);
  1373. if (!(fp->flag & FA_READ)) /* Check access mode */
  1374. LEAVE_FF(fp->fs, FR_DENIED);
  1375. remain = fp->fsize - fp->fptr;
  1376. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  1377. for ( ; btr; /* Repeat until all data transferred */
  1378. rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  1379. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  1380. if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
  1381. clst = (fp->fptr == 0) ? /* On the top of the file? */
  1382. fp->org_clust : get_cluster(fp->fs, fp->curr_clust);
  1383. if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
  1384. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  1385. fp->curr_clust = clst; /* Update current cluster */
  1386. fp->csect = 0; /* Reset sector offset in the cluster */
  1387. }
  1388. sect = clust2sect(fp->fs, fp->curr_clust); /* Get current sector */
  1389. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  1390. sect += fp->csect;
  1391. cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */
  1392. if (cc) { /* Read maximum contiguous sectors directly */
  1393. if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  1394. cc = fp->fs->csize - fp->csect;
  1395. if (disk_read(fp->fs->drive, rbuff, sect, (BYTE)cc) != RES_OK)
  1396. ABORT(fp->fs, FR_DISK_ERR);
  1397. fp->csect += (BYTE)cc; /* Next sector address in the cluster */
  1398. rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
  1399. continue;
  1400. }
  1401. #if !_FS_TINY
  1402. #if !_FS_READONLY
  1403. if (fp->flag & FA__DIRTY) { /* Write sector I/O buffer if needed */
  1404. if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
  1405. ABORT(fp->fs, FR_DISK_ERR);
  1406. fp->flag &= (BYTE)~FA__DIRTY;
  1407. }
  1408. #endif
  1409. if (fp->dsect != sect) { /* Fill sector buffer with file data */
  1410. if (disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK)
  1411. ABORT(fp->fs, FR_DISK_ERR);
  1412. }
  1413. #endif
  1414. fp->dsect = sect;
  1415. fp->csect++; /* Next sector address in the cluster */
  1416. }
  1417. rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Get partial sector data from sector buffer */
  1418. if (rcnt > btr) rcnt = btr;
  1419. #if _FS_TINY
  1420. if (move_window(fp->fs, fp->dsect)) /* Move sector window */
  1421. ABORT(fp->fs, FR_DISK_ERR);
  1422. mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  1423. #else
  1424. mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  1425. #endif
  1426. }
  1427. LEAVE_FF(fp->fs, FR_OK);
  1428. }
  1429. #if !_FS_READONLY
  1430. /*-----------------------------------------------------------------------*/
  1431. /* Write File */
  1432. /*-----------------------------------------------------------------------*/
  1433. FRESULT f_write (
  1434. FIL *fp, /* Pointer to the file object */
  1435. const void *buff, /* Pointer to the data to be written */
  1436. UINT btw, /* Number of bytes to write */
  1437. UINT *bw /* Pointer to number of bytes written */
  1438. )
  1439. {
  1440. FRESULT res;
  1441. DWORD clst, sect;
  1442. UINT wcnt, cc;
  1443. const BYTE *wbuff = buff;
  1444. *bw = 0;
  1445. res = validate(fp->fs, fp->id); /* Check validity of the object */
  1446. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  1447. if (fp->flag & FA__ERROR) /* Check abort flag */
  1448. LEAVE_FF(fp->fs, FR_INT_ERR);
  1449. if (!(fp->flag & FA_WRITE)) /* Check access mode */
  1450. LEAVE_FF(fp->fs, FR_DENIED);
  1451. if (fp->fsize + btw < fp->fsize) btw = 0; /* File size cannot reach 4GB */
  1452. for ( ; btw; /* Repeat until all data transferred */
  1453. wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
  1454. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  1455. if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
  1456. if (fp->fptr == 0) { /* On the top of the file? */
  1457. clst = fp->org_clust; /* Follow from the origin */
  1458. if (clst == 0) /* When there is no cluster chain, */
  1459. fp->org_clust = clst = create_chain(fp->fs, 0); /* Create a new cluster chain */
  1460. } else { /* Middle or end of the file */
  1461. clst = create_chain(fp->fs, fp->curr_clust); /* Follow or streach cluster chain */
  1462. }
  1463. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  1464. if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  1465. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  1466. fp->curr_clust = clst; /* Update current cluster */
  1467. fp->csect = 0; /* Reset sector address in the cluster */
  1468. }
  1469. #if _FS_TINY
  1470. if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0)) /* Write back data buffer prior to following direct transfer */
  1471. ABORT(fp->fs, FR_DISK_ERR);
  1472. #else
  1473. if (fp->flag & FA__DIRTY) { /* Write back data buffer prior to following direct transfer */
  1474. if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
  1475. ABORT(fp->fs, FR_DISK_ERR);
  1476. fp->flag &= (BYTE)~FA__DIRTY;
  1477. }
  1478. #endif
  1479. sect = clust2sect(fp->fs, fp->curr_clust); /* Get current sector */
  1480. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  1481. sect += fp->csect;
  1482. cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */
  1483. if (cc) { /* Write maximum contiguous sectors directly */
  1484. if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  1485. cc = fp->fs->csize - fp->csect;
  1486. if (disk_write(fp->fs->drive, wbuff, sect, (BYTE)cc) != RES_OK)
  1487. ABORT(fp->fs, FR_DISK_ERR);
  1488. fp->csect += (BYTE)cc; /* Next sector address in the cluster */
  1489. wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
  1490. continue;
  1491. }
  1492. #if _FS_TINY
  1493. if (fp->fptr >= fp->fsize) { /* Avoid silly buffer filling at growing edge */
  1494. if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR);
  1495. fp->fs->winsect = sect;
  1496. }
  1497. #else
  1498. if (fp->dsect != sect) { /* Fill sector buffer with file data */
  1499. if (fp->fptr < fp->fsize &&
  1500. disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK)
  1501. ABORT(fp->fs, FR_DISK_ERR);
  1502. }
  1503. #endif
  1504. fp->dsect = sect;
  1505. fp->csect++; /* Next sector address in the cluster */
  1506. }
  1507. wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Put partial sector into file I/O buffer */
  1508. if (wcnt > btw) wcnt = btw;
  1509. #if _FS_TINY
  1510. if (move_window(fp->fs, fp->dsect)) /* Move sector window */
  1511. ABORT(fp->fs, FR_DISK_ERR);
  1512. mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  1513. fp->fs->wflag = 1;
  1514. #else
  1515. mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  1516. fp->flag |= FA__DIRTY;
  1517. #endif
  1518. }
  1519. if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
  1520. fp->flag |= FA__WRITTEN; /* Set file changed flag */
  1521. LEAVE_FF(fp->fs, FR_OK);
  1522. }
  1523. /*-----------------------------------------------------------------------*/
  1524. /* Synchronize the File Object */
  1525. /*-----------------------------------------------------------------------*/
  1526. FRESULT f_sync (
  1527. FIL *fp /* Pointer to the file object */
  1528. )
  1529. {
  1530. FRESULT res;
  1531. DWORD tim;
  1532. BYTE *dir;
  1533. res = validate(fp->fs, fp->id); /* Check validity of the object */
  1534. if (res == FR_OK) {
  1535. if (fp->flag & FA__WRITTEN) { /* Has the file been written? */
  1536. #if !_FS_TINY /* Write-back dirty buffer */
  1537. if (fp->flag & FA__DIRTY) {
  1538. if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
  1539. LEAVE_FF(fp->fs, FR_DISK_ERR);
  1540. fp->flag &= (BYTE)~FA__DIRTY;
  1541. }
  1542. #endif
  1543. /* Update the directory entry */
  1544. res = move_window(fp->fs, fp->dir_sect);
  1545. if (res == FR_OK) {
  1546. dir = fp->dir_ptr;
  1547. dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
  1548. ST_DWORD(dir+DIR_FileSize, fp->fsize); /* Update file size */
  1549. ST_WORD(dir+DIR_FstClusLO, fp->org_clust); /* Update start cluster */
  1550. ST_WORD(dir+DIR_FstClusHI, fp->org_clust >> 16);
  1551. tim = get_fattime(); /* Updated time */
  1552. ST_DWORD(dir+DIR_WrtTime, tim);
  1553. fp->flag &= (BYTE)~FA__WRITTEN;
  1554. fp->fs->wflag = 1;
  1555. res = sync(fp->fs);
  1556. }
  1557. }
  1558. }
  1559. LEAVE_FF(fp->fs, res);
  1560. }
  1561. #endif /* !_FS_READONLY */
  1562. /*-----------------------------------------------------------------------*/
  1563. /* Close File */
  1564. /*-----------------------------------------------------------------------*/
  1565. FRESULT f_close (
  1566. FIL *fp /* Pointer to the file object to be closed */
  1567. )
  1568. {
  1569. FRESULT res;
  1570. #if _FS_READONLY
  1571. res = validate(fp->fs, fp->id);
  1572. if (res == FR_OK) fp->fs = NULL;
  1573. LEAVE_FF(fp->fs, res);
  1574. #else
  1575. res = f_sync(fp);
  1576. if (res == FR_OK) fp->fs = NULL;
  1577. return res;
  1578. #endif
  1579. }
  1580. #if _FS_MINIMIZE <= 2
  1581. /*-----------------------------------------------------------------------*/
  1582. /* Seek File R/W Pointer */
  1583. /*-----------------------------------------------------------------------*/
  1584. FRESULT f_lseek (
  1585. FIL *fp, /* Pointer to the file object */
  1586. DWORD ofs /* File pointer from top of file */
  1587. )
  1588. {
  1589. FRESULT res;
  1590. DWORD clst, bcs, nsect, ifptr;
  1591. res = validate(fp->fs, fp->id); /* Check validity of the object */
  1592. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  1593. if (fp->flag & FA__ERROR) /* Check abort flag */
  1594. LEAVE_FF(fp->fs, FR_INT_ERR);
  1595. if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */
  1596. #if !_FS_READONLY
  1597. && !(fp->flag & FA_WRITE)
  1598. #endif
  1599. ) ofs = fp->fsize;
  1600. ifptr = fp->fptr;
  1601. fp->fptr = 0; fp->csect = 255;
  1602. nsect = 0;
  1603. if (ofs > 0) {
  1604. bcs = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */
  1605. if (ifptr > 0 &&
  1606. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  1607. fp->fptr = (ifptr - 1) & ~(bcs - 1); /* start from the current cluster */
  1608. ofs -= fp->fptr;
  1609. clst = fp->curr_clust;
  1610. } else { /* When seek to back cluster, */
  1611. clst = fp->org_clust; /* start from the first cluster */
  1612. #if !_FS_READONLY
  1613. if (clst == 0) { /* If no cluster chain, create a new chain */
  1614. clst = create_chain(fp->fs, 0);
  1615. if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  1616. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  1617. fp->org_clust = clst;
  1618. }
  1619. #endif
  1620. fp->curr_clust = clst;
  1621. }
  1622. if (clst != 0) {
  1623. while (ofs > bcs) { /* Cluster following loop */
  1624. #if !_FS_READONLY
  1625. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  1626. clst = create_chain(fp->fs, clst); /* Force streached if in write mode */
  1627. if (clst == 0) { /* When disk gets full, clip file size */
  1628. ofs = bcs; break;
  1629. }
  1630. } else
  1631. #endif
  1632. clst = get_cluster(fp->fs, clst); /* Follow cluster chain if not in write mode */
  1633. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  1634. if (clst <= 1 || clst >= fp->fs->max_clust) ABORT(fp->fs, FR_INT_ERR);
  1635. fp->curr_clust = clst;
  1636. fp->fptr += bcs;
  1637. ofs -= bcs;
  1638. }
  1639. fp->fptr += ofs;
  1640. fp->csect = (BYTE)(ofs / SS(fp->fs)); /* Sector offset in the cluster */
  1641. if (ofs % SS(fp->fs)) {
  1642. nsect = clust2sect(fp->fs, clst); /* Current sector */
  1643. if (!nsect) ABORT(fp->fs, FR_INT_ERR);
  1644. nsect += fp->csect;
  1645. fp->csect++;
  1646. }
  1647. }
  1648. }
  1649. if (nsect && nsect != fp->dsect && fp->fptr % SS(fp->fs)) {
  1650. #if !_FS_TINY
  1651. #if !_FS_READONLY
  1652. if (fp->flag & FA__DIRTY) { /* Write-back dirty buffer if needed */
  1653. if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
  1654. ABORT(fp->fs, FR_DISK_ERR);
  1655. fp->flag &= (BYTE)~FA__DIRTY;
  1656. }
  1657. #endif
  1658. if (disk_read(fp->fs->drive, fp->buf, nsect, 1) != RES_OK)
  1659. ABORT(fp->fs, FR_DISK_ERR);
  1660. #endif
  1661. fp->dsect = nsect;
  1662. }
  1663. #if !_FS_READONLY
  1664. if (fp->fptr > fp->fsize) { /* Set changed flag if the file size is extended */
  1665. fp->fsize = fp->fptr;
  1666. fp->flag |= FA__WRITTEN;
  1667. }
  1668. #endif
  1669. LEAVE_FF(fp->fs, res);
  1670. }
  1671. #if _FS_MINIMIZE <= 1
  1672. /*-----------------------------------------------------------------------*/
  1673. /* Create a Directroy Object */
  1674. /*-----------------------------------------------------------------------*/
  1675. FRESULT f_opendir (
  1676. DIR *dj, /* Pointer to directory object to create */
  1677. const char *path /* Pointer to the directory path */
  1678. )
  1679. {
  1680. FRESULT res;
  1681. NAMEBUF(sfn, lfn);
  1682. BYTE *dir;
  1683. res = auto_mount(&path, &dj->fs, 0);
  1684. if (res == FR_OK) {
  1685. INITBUF((*dj), sfn, lfn);
  1686. res = follow_path(dj, path); /* Follow the path to the directory */
  1687. if (res == FR_OK) { /* Follow completed */
  1688. dir = dj->dir;
  1689. if (dir) { /* It is not the root dir */
  1690. if (dir[DIR_Attr] & AM_DIR) { /* The object is a directory */
  1691. dj->sclust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
  1692. } else { /* The object is not a directory */
  1693. res = FR_NO_PATH;
  1694. }
  1695. } else { /* It is the root dir */
  1696. dj->sclust = (dj->fs->fs_type == FS_FAT32) ? dj->fs->dirbase : 0;
  1697. }
  1698. if (res == FR_OK) res = dir_seek(dj, 0);
  1699. dj->id = dj->fs->id;
  1700. } else {
  1701. if (res == FR_NO_FILE) res = FR_NO_PATH;
  1702. }
  1703. }
  1704. LEAVE_FF(dj->fs, res);
  1705. }
  1706. /*-----------------------------------------------------------------------*/
  1707. /* Read Directory Entry in Sequense */
  1708. /*-----------------------------------------------------------------------*/
  1709. FRESULT f_readdir (
  1710. DIR *dj, /* Pointer to the open directory object */
  1711. FILINFO *fno /* Pointer to file information to return */
  1712. )
  1713. {
  1714. FRESULT res;
  1715. NAMEBUF(sfn, lfn);
  1716. res = validate(dj->fs, dj->id); /* Check validity of the object */
  1717. if (res == FR_OK) {
  1718. INITBUF((*dj), sfn, lfn);
  1719. if (!fno) {
  1720. res = dir_seek(dj, 0);
  1721. } else {
  1722. res = dir_read(dj);
  1723. if (res == FR_NO_FILE) {
  1724. dj->sect = 0;
  1725. res = FR_OK;
  1726. }
  1727. if (res == FR_OK) { /* A valid entry is found */
  1728. get_fileinfo(dj, fno); /* Get the object information */
  1729. res = dir_next(dj, FALSE); /* Increment index for next */
  1730. if (res == FR_NO_FILE) {
  1731. dj->sect = 0;
  1732. res = FR_OK;
  1733. }
  1734. }
  1735. }
  1736. }
  1737. LEAVE_FF(dj->fs, res);
  1738. }
  1739. #if _FS_MINIMIZE == 0
  1740. /*-----------------------------------------------------------------------*/
  1741. /* Get File Status */
  1742. /*-----------------------------------------------------------------------*/
  1743. FRESULT f_stat (
  1744. const char *path, /* Pointer to the file path */
  1745. FILINFO *fno /* Pointer to file information to return */
  1746. )
  1747. {
  1748. FRESULT res;
  1749. DIR dj;
  1750. NAMEBUF(sfn, lfn);
  1751. res = auto_mount(&path, &dj.fs, 0);
  1752. if (res == FR_OK) {
  1753. INITBUF(dj, sfn, lfn);
  1754. res = follow_path(&dj, path); /* Follow the file path */
  1755. if (res == FR_OK) { /* Follwo completed */
  1756. if (dj.dir) /* Found an object */
  1757. get_fileinfo(&dj, fno);
  1758. else /* It is root dir */
  1759. res = FR_INVALID_NAME;
  1760. }
  1761. }
  1762. LEAVE_FF(dj.fs, res);
  1763. }
  1764. #if !_FS_READONLY
  1765. /*-----------------------------------------------------------------------*/
  1766. /* Truncate File */
  1767. /*-----------------------------------------------------------------------*/
  1768. FRESULT f_truncate (
  1769. FIL *fp /* Pointer to the file object */
  1770. )
  1771. {
  1772. FRESULT res;
  1773. DWORD ncl;
  1774. res = validate(fp->fs, fp->id); /* Check validity of the object */
  1775. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  1776. if (fp->flag & FA__ERROR) /* Check abort flag */
  1777. LEAVE_FF(fp->fs, FR_INT_ERR);
  1778. if (!(fp->flag & FA_WRITE)) /* Check access mode */
  1779. LEAVE_FF(fp->fs, FR_DENIED);
  1780. if (fp->fsize > fp->fptr) {
  1781. fp->fsize = fp->fptr; /* Set file size to current R/W point */
  1782. fp->flag |= FA__WRITTEN;
  1783. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  1784. res = remove_chain(fp->fs, fp->org_clust);
  1785. fp->org_clust = 0;
  1786. } else { /* When truncate a part of the file, remove remaining clusters */
  1787. ncl = get_cluster(fp->fs, fp->curr_clust);
  1788. res = FR_OK;
  1789. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  1790. if (ncl == 1) res = FR_INT_ERR;
  1791. if (res == FR_OK && ncl < fp->fs->max_clust) {
  1792. res = put_cluster(fp->fs, fp->curr_clust, 0x0FFFFFFF);
  1793. if (res == FR_OK) res = remove_chain(fp->fs, ncl);
  1794. }
  1795. }
  1796. }
  1797. if (res != FR_OK) fp->flag |= FA__ERROR;
  1798. LEAVE_FF(fp->fs, res);
  1799. }
  1800. /*-----------------------------------------------------------------------*/
  1801. /* Get Number of Free Clusters */
  1802. /*-----------------------------------------------------------------------*/
  1803. FRESULT f_getfree (
  1804. const char *path, /* Pointer to the logical drive number (root dir) */
  1805. DWORD *nclst, /* Pointer to the variable to return number of free clusters */
  1806. FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */
  1807. )
  1808. {
  1809. FRESULT res;
  1810. DWORD n, clst, sect;
  1811. BYTE fat, f, *p;
  1812. /* Get drive number */
  1813. res = auto_mount(&path, fatfs, 0);
  1814. if (res != FR_OK) LEAVE_FF(*fatfs, res);
  1815. /* If number of free cluster is valid, return it without cluster scan. */
  1816. if ((*fatfs)->free_clust <= (*fatfs)->max_clust - 2) {
  1817. *nclst = (*fatfs)->free_clust;
  1818. LEAVE_FF(*fatfs, FR_OK);
  1819. }
  1820. /* Get number of free clusters */
  1821. fat = (*fatfs)->fs_type;
  1822. n = 0;
  1823. if (fat == FS_FAT12) {
  1824. clst = 2;
  1825. do {
  1826. if ((WORD)get_cluster(*fatfs, clst) == 0) n++;
  1827. } while (++clst < (*fatfs)->max_clust);
  1828. } else {
  1829. clst = (*fatfs)->max_clust;
  1830. sect = (*fatfs)->fatbase;
  1831. f = 0; p = 0;
  1832. do {
  1833. if (!f) {
  1834. res = move_window(*fatfs, sect++);
  1835. if (res != FR_OK)
  1836. LEAVE_FF(*fatfs, res);
  1837. p = (*fatfs)->win;
  1838. }
  1839. if (fat == FS_FAT16) {
  1840. if (LD_WORD(p) == 0) n++;
  1841. p += 2; f += 1;
  1842. } else {
  1843. if (LD_DWORD(p) == 0) n++;
  1844. p += 4; f += 2;
  1845. }
  1846. } while (--clst);
  1847. }
  1848. (*fatfs)->free_clust = n;
  1849. if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;
  1850. *nclst = n;
  1851. LEAVE_FF(*fatfs, FR_OK);
  1852. }
  1853. /*-----------------------------------------------------------------------*/
  1854. /* Delete a File or Directory */
  1855. /*-----------------------------------------------------------------------*/
  1856. FRESULT f_unlink (
  1857. const char *path /* Pointer to the file or directory path */
  1858. )
  1859. {
  1860. FRESULT res;
  1861. DIR dj, sdj;
  1862. NAMEBUF(sfn, lfn);
  1863. BYTE *dir;
  1864. DWORD dclst;
  1865. res = auto_mount(&path, &dj.fs, 1);
  1866. if (res != FR_OK) LEAVE_FF(dj.fs, res);
  1867. INITBUF(dj, sfn, lfn);
  1868. res = follow_path(&dj, path); /* Follow the file path */
  1869. if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */
  1870. dir = dj.dir;
  1871. if (!dir) /* Is it the root directory? */
  1872. LEAVE_FF(dj.fs, FR_INVALID_NAME);
  1873. if (dir[DIR_Attr] & AM_RDO) /* Is it a R/O object? */
  1874. LEAVE_FF(dj.fs, FR_DENIED);
  1875. dclst = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
  1876. if (dir[DIR_Attr] & AM_DIR) { /* It is a sub-directory */
  1877. if (dclst < 2) LEAVE_FF(dj.fs, FR_INT_ERR);
  1878. mem_cpy(&sdj, &dj, sizeof(DIR)); /* Check if the sub-dir is empty or not */
  1879. sdj.sclust = dclst;
  1880. res = dir_seek(&sdj, 0);
  1881. if (res != FR_OK) LEAVE_FF(dj.fs, res);
  1882. res = dir_read(&sdj);
  1883. if (res == FR_OK) res = FR_DENIED; /* Not empty sub-dir */
  1884. if (res != FR_NO_FILE) LEAVE_FF(dj.fs, res);
  1885. }
  1886. res = dir_remove(&dj); /* Remove directory entry */
  1887. if (res == FR_OK) {
  1888. if (dclst)
  1889. res = remove_chain(dj.fs, dclst); /* Remove the cluster chain */
  1890. if (res == FR_OK) res = sync(dj.fs);
  1891. }
  1892. LEAVE_FF(dj.fs, FR_OK);
  1893. }
  1894. /*-----------------------------------------------------------------------*/
  1895. /* Create a Directory */
  1896. /*-----------------------------------------------------------------------*/
  1897. FRESULT f_mkdir (
  1898. const char *path /* Pointer to the directory path */
  1899. )
  1900. {
  1901. FRESULT res;
  1902. DIR dj;
  1903. NAMEBUF(sfn, lfn);
  1904. BYTE *dir, n;
  1905. DWORD dsect, dclst, pclst, tim;
  1906. res = auto_mount(&path, &dj.fs, 1);
  1907. if (res != FR_OK) LEAVE_FF(dj.fs, res);
  1908. INITBUF(dj, sfn, lfn);
  1909. res = follow_path(&dj, path); /* Follow the file path */
  1910. if (res == FR_OK) res = FR_EXIST; /* Any file or directory is already existing */
  1911. if (res != FR_NO_FILE) /* Any error occured */
  1912. LEAVE_FF(dj.fs, res);
  1913. dclst = create_chain(dj.fs, 0); /* Allocate a new cluster for new directory table */
  1914. res = FR_OK;
  1915. if (dclst == 0) res = FR_DENIED;
  1916. if (dclst == 1) res = FR_INT_ERR;
  1917. if (dclst == 0xFFFFFFFF) res = FR_DISK_ERR;
  1918. if (res == FR_OK)
  1919. res = move_window(dj.fs, 0);
  1920. if (res != FR_OK) LEAVE_FF(dj.fs, res);
  1921. dsect = clust2sect(dj.fs, dclst);
  1922. dir = dj.fs->win; /* Initialize the new directory table */
  1923. mem_set(dir, 0, SS(dj.fs));
  1924. mem_set(dir+DIR_Name, ' ', 8+3); /* Create "." entry */
  1925. dir[DIR_Name] = '.';
  1926. dir[DIR_Attr] = AM_DIR;
  1927. tim = get_fattime();
  1928. ST_DWORD(dir+DIR_WrtTime, tim);
  1929. ST_WORD(dir+DIR_FstClusLO, dclst);
  1930. ST_WORD(dir+DIR_FstClusHI, dclst >> 16);
  1931. mem_cpy(dir+32, dir, 32); /* Create ".." entry */
  1932. dir[33] = '.';
  1933. pclst = dj.sclust;
  1934. if (dj.fs->fs_type == FS_FAT32 && pclst == dj.fs->dirbase)
  1935. pclst = 0;
  1936. ST_WORD(dir+32+DIR_FstClusLO, pclst);
  1937. ST_WORD(dir+32+DIR_FstClusHI, pclst >> 16);
  1938. for (n = 0; n < dj.fs->csize; n++) { /* Write dot entries and clear left sectors */
  1939. dj.fs->winsect = dsect++;
  1940. dj.fs->wflag = 1;
  1941. res = move_window(dj.fs, 0);
  1942. if (res) LEAVE_FF(dj.fs, res);
  1943. mem_set(dir, 0, SS(dj.fs));
  1944. }
  1945. res = dir_register(&dj);
  1946. if (res != FR_OK) {
  1947. remove_chain(dj.fs, dclst);
  1948. } else {
  1949. dir = dj.dir;
  1950. dir[DIR_Attr] = AM_DIR; /* Attribute */
  1951. ST_DWORD(dir+DIR_WrtTime, tim); /* Crated time */
  1952. ST_WORD(dir+DIR_FstClusLO, dclst); /* Table start cluster */
  1953. ST_WORD(dir+DIR_FstClusHI, dclst >> 16);
  1954. dj.fs->wflag = 1;
  1955. res = sync(dj.fs);
  1956. }
  1957. LEAVE_FF(dj.fs, res);
  1958. }
  1959. /*-----------------------------------------------------------------------*/
  1960. /* Change File Attribute */
  1961. /*-----------------------------------------------------------------------*/
  1962. FRESULT f_chmod (
  1963. const char *path, /* Pointer to the file path */
  1964. BYTE value, /* Attribute bits */
  1965. BYTE mask /* Attribute mask to change */
  1966. )
  1967. {
  1968. FRESULT res;
  1969. DIR dj;
  1970. NAMEBUF(sfn, lfn);
  1971. BYTE *dir;
  1972. res = auto_mount(&path, &dj.fs, 1);
  1973. if (res == FR_OK) {
  1974. INITBUF(dj, sfn, lfn);
  1975. res = follow_path(&dj, path); /* Follow the file path */
  1976. if (res == FR_OK) {
  1977. dir = dj.dir;
  1978. if (!dir) { /* Is it a root directory? */
  1979. res = FR_INVALID_NAME;
  1980. } else { /* File or sub directory */
  1981. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  1982. dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  1983. dj.fs->wflag = 1;
  1984. res = sync(dj.fs);
  1985. }
  1986. }
  1987. }
  1988. LEAVE_FF(dj.fs, res);
  1989. }
  1990. /*-----------------------------------------------------------------------*/
  1991. /* Change Timestamp */
  1992. /*-----------------------------------------------------------------------*/
  1993. FRESULT f_utime (
  1994. const char *path, /* Pointer to the file/directory name */
  1995. const FILINFO *fno /* Pointer to the timestamp to be set */
  1996. )
  1997. {
  1998. FRESULT res;
  1999. DIR dj;
  2000. NAMEBUF(sfn, lfn);
  2001. BYTE *dir;
  2002. res = auto_mount(&path, &dj.fs, 1);
  2003. if (res == FR_OK) {
  2004. INITBUF(dj, sfn, lfn);
  2005. res = follow_path(&dj, path); /* Follow the file path */
  2006. if (res == FR_OK) {
  2007. dir = dj.dir;
  2008. if (!dir) { /* Root directory */
  2009. res = FR_INVALID_NAME;
  2010. } else { /* File or sub-directory */
  2011. ST_WORD(dir+DIR_WrtTime, fno->ftime);
  2012. ST_WORD(dir+DIR_WrtDate, fno->fdate);
  2013. dj.fs->wflag = 1;
  2014. res = sync(dj.fs);
  2015. }
  2016. }
  2017. }
  2018. LEAVE_FF(dj.fs, res);
  2019. }
  2020. /*-----------------------------------------------------------------------*/
  2021. /* Rename File/Directory */
  2022. /*-----------------------------------------------------------------------*/
  2023. FRESULT f_rename (
  2024. const char *path_old, /* Pointer to the old name */
  2025. const char *path_new /* Pointer to the new name */
  2026. )
  2027. {
  2028. FRESULT res;
  2029. DIR dj_old, dj_new;
  2030. NAMEBUF(sfn, lfn);
  2031. BYTE buf[21], *dir;
  2032. DWORD dw;
  2033. INITBUF(dj_old, sfn, lfn);
  2034. res = auto_mount(&path_old, &dj_old.fs, 1);
  2035. if (res == FR_OK) {
  2036. dj_new.fs = dj_old.fs;
  2037. res = follow_path(&dj_old, path_old); /* Check old object */
  2038. }
  2039. if (res != FR_OK) LEAVE_FF(dj_old.fs, res); /* The old object is not found */
  2040. if (!dj_old.dir) LEAVE_FF(dj_old.fs, FR_NO_FILE); /* Is root dir? */
  2041. mem_cpy(buf, dj_old.dir+DIR_Attr, 21); /* Save the object information */
  2042. mem_cpy(&dj_new, &dj_old, sizeof(DIR));
  2043. res = follow_path(&dj_new, path_new); /* Check new object */
  2044. if (res == FR_OK) res = FR_EXIST; /* The new object name is already existing */
  2045. if (res == FR_NO_FILE) { /* Is it a valid path and no name collision? */
  2046. res = dir_register(&dj_new); /* Register the new object */
  2047. if (res == FR_OK) {
  2048. dir = dj_new.dir; /* Copy object information into new entry */
  2049. mem_cpy(dir+13, buf+2, 19);
  2050. dir[DIR_Attr] = buf[0];
  2051. dj_old.fs->wflag = 1;
  2052. if (dir[DIR_Attr] & AM_DIR) { /* Update .. entry in the directory if needed */
  2053. dw = clust2sect(dj_new.fs, (DWORD)LD_WORD(dir+DIR_FstClusHI) | LD_WORD(dir+DIR_FstClusLO));
  2054. if (!dw) {
  2055. res = FR_INT_ERR;
  2056. } else {
  2057. res = move_window(dj_new.fs, dw);
  2058. dir = dj_new.fs->win+32;
  2059. if (res == FR_OK && dir[1] == '.') {
  2060. dw = (dj_new.fs->fs_type == FS_FAT32 && dj_new.sclust == dj_new.fs->dirbase) ? 0 : dj_new.sclust;
  2061. ST_WORD(dir+DIR_FstClusLO, dw);
  2062. ST_WORD(dir+DIR_FstClusHI, dw >> 16);
  2063. dj_new.fs->wflag = 1;
  2064. }
  2065. }
  2066. }
  2067. if (res == FR_OK) {
  2068. res = dir_remove(&dj_old); /* Remove old entry */
  2069. if (res == FR_OK)
  2070. res = sync(dj_old.fs);
  2071. }
  2072. }
  2073. }
  2074. LEAVE_FF(dj_old.fs, res);
  2075. }
  2076. #endif /* !_FS_READONLY */
  2077. #endif /* _FS_MINIMIZE == 0 */
  2078. #endif /* _FS_MINIMIZE <= 1 */
  2079. #endif /* _FS_MINIMIZE <= 2 */
  2080. /*-----------------------------------------------------------------------*/
  2081. /* Forward data to the stream directly (Available on only _FS_TINY cfg) */
  2082. /*-----------------------------------------------------------------------*/
  2083. #if _USE_FORWARD && _FS_TINY
  2084. FRESULT f_forward (
  2085. FIL *fp, /* Pointer to the file object */
  2086. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  2087. UINT btr, /* Number of bytes to forward */
  2088. UINT *bf /* Pointer to number of bytes forwarded */
  2089. )
  2090. {
  2091. FRESULT res;
  2092. DWORD remain, clst, sect;
  2093. UINT rcnt;
  2094. *bf = 0;
  2095. res = validate(fp->fs, fp->id); /* Check validity of the object */
  2096. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2097. if (fp->flag & FA__ERROR) /* Check error flag */
  2098. LEAVE_FF(fp->fs, FR_INT_ERR);
  2099. if (!(fp->flag & FA_READ)) /* Check access mode */
  2100. LEAVE_FF(fp->fs, FR_DENIED);
  2101. remain = fp->fsize - fp->fptr;
  2102. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  2103. for ( ; btr && (*func)(NULL, 0); /* Repeat until all data transferred or stream becomes busy */
  2104. fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) {
  2105. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  2106. if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
  2107. clst = (fp->fptr == 0) ? /* On the top of the file? */
  2108. fp->org_clust : get_cluster(fp->fs, fp->curr_clust);
  2109. if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
  2110. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2111. fp->curr_clust = clst; /* Update current cluster */
  2112. fp->csect = 0; /* Reset sector address in the cluster */
  2113. }
  2114. fp->csect++; /* Next sector address in the cluster */
  2115. }
  2116. sect = clust2sect(fp->fs, fp->curr_clust); /* Get current data sector */
  2117. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  2118. sect += fp->csect - 1;
  2119. if (move_window(fp->fs, sect)) /* Move sector window */
  2120. ABORT(fp->fs, FR_DISK_ERR);
  2121. fp->dsect = sect;
  2122. rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs)); /* Forward data from sector window */
  2123. if (rcnt > btr) rcnt = btr;
  2124. rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);
  2125. if (!rcnt) ABORT(fp->fs, FR_INT_ERR);
  2126. }
  2127. LEAVE_FF(fp->fs, FR_OK);
  2128. }
  2129. #endif /* _USE_FORWARD */
  2130. #if _USE_MKFS && !_FS_READONLY
  2131. /*-----------------------------------------------------------------------*/
  2132. /* Create File System on the Drive */
  2133. /*-----------------------------------------------------------------------*/
  2134. #define N_ROOTDIR 512 /* Multiple of 32 and <= 2048 */
  2135. #define N_FATS 1 /* 1 or 2 */
  2136. #define MAX_SECTOR 131072000UL /* Maximum partition size */
  2137. #define MIN_SECTOR 2000UL /* Minimum partition size */
  2138. FRESULT f_mkfs (
  2139. BYTE drv, /* Logical drive number */
  2140. BYTE partition, /* Partitioning rule 0:FDISK, 1:SFD */
  2141. WORD allocsize /* Allocation unit size [bytes] */
  2142. )
  2143. {
  2144. static const DWORD sstbl[] = { 2048000, 1024000, 512000, 256000, 128000, 64000, 32000, 16000, 8000, 4000, 0 };
  2145. static const WORD cstbl[] = { 32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512 };
  2146. BYTE fmt, m, *tbl;
  2147. DWORD b_part, b_fat, b_dir, b_data; /* Area offset (LBA) */
  2148. DWORD n_part, n_rsv, n_fat, n_dir; /* Area size */
  2149. DWORD n_clst, n;
  2150. WORD as;
  2151. FATFS *fs;
  2152. DSTATUS stat;
  2153. /* Check validity of the parameters */
  2154. if (drv >= _DRIVES) return FR_INVALID_DRIVE;
  2155. if (partition >= 2) return FR_MKFS_ABORTED;
  2156. /* Check mounted drive and clear work area */
  2157. fs = FatFs[drv];
  2158. if (!fs) return FR_NOT_ENABLED;
  2159. fs->fs_type = 0;
  2160. drv = LD2PD(drv);
  2161. /* Get disk statics */
  2162. stat = disk_initialize(drv);
  2163. if (stat & STA_NOINIT) return FR_NOT_READY;
  2164. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  2165. if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR)
  2166. return FR_MKFS_ABORTED;
  2167. if (n_part > MAX_SECTOR) n_part = MAX_SECTOR;
  2168. b_part = (!partition) ? 63 : 0; /* Boot sector */
  2169. n_part -= b_part;
  2170. #if _MAX_SS == 512
  2171. if (!allocsize) { /* Auto selection of cluster size */
  2172. for (n = 0; n_part < sstbl[n]; n++) ;
  2173. allocsize = cstbl[n];
  2174. }
  2175. #endif
  2176. for (as = 512; as <= 32768U && as != allocsize; as <<= 1);
  2177. if (as != allocsize) return FR_MKFS_ABORTED;
  2178. #if _MAX_SS != 512 /* Check disk sector size */
  2179. if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK
  2180. || SS(fs) > _MAX_SS
  2181. || SS(fs) > allocsize)
  2182. return FR_MKFS_ABORTED;
  2183. #endif
  2184. allocsize /= SS(fs); /* Number of sectors per cluster */
  2185. /* Pre-compute number of clusters and FAT type */
  2186. n_clst = n_part / allocsize;
  2187. fmt = FS_FAT12;
  2188. if (n_clst >= 0xFF5) fmt = FS_FAT16;
  2189. if (n_clst >= 0xFFF5) fmt = FS_FAT32;
  2190. /* Determine offset and size of FAT structure */
  2191. switch (fmt) {
  2192. case FS_FAT12:
  2193. n_fat = ((n_clst * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs);
  2194. n_rsv = 1 + partition;
  2195. n_dir = N_ROOTDIR * 32 / SS(fs);
  2196. break;
  2197. case FS_FAT16:
  2198. n_fat = ((n_clst * 2) + 4 + SS(fs) - 1) / SS(fs);
  2199. n_rsv = 1 + partition;
  2200. n_dir = N_ROOTDIR * 32 / SS(fs);
  2201. break;
  2202. default:
  2203. n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);
  2204. n_rsv = 33 - partition;
  2205. n_dir = 0;
  2206. }
  2207. b_fat = b_part + n_rsv; /* FATs start sector */
  2208. b_dir = b_fat + n_fat * N_FATS; /* Directory start sector */
  2209. b_data = b_dir + n_dir; /* Data start sector */
  2210. /* Align data start sector to erase block boundary (for flash memory media) */
  2211. if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED;
  2212. n = (b_data + n - 1) & ~(n - 1);
  2213. n_fat += (n - b_data) / N_FATS;
  2214. /* b_dir and b_data are no longer used below */
  2215. /* Determine number of cluster and final check of validity of the FAT type */
  2216. n_clst = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize;
  2217. if ( (fmt == FS_FAT16 && n_clst < 0xFF5)
  2218. || (fmt == FS_FAT32 && n_clst < 0xFFF5))
  2219. return FR_MKFS_ABORTED;
  2220. /* Create partition table if needed */
  2221. if (!partition) {
  2222. DWORD n_disk = b_part + n_part;
  2223. tbl = fs->win+MBR_Table;
  2224. ST_DWORD(tbl, 0x00010180); /* Partition start in CHS */
  2225. if (n_disk < 63UL * 255 * 1024) { /* Partition end in CHS */
  2226. n_disk = n_disk / 63 / 255;
  2227. tbl[7] = (BYTE)n_disk;
  2228. tbl[6] = (BYTE)((n_disk >> 2) | 63);
  2229. } else {
  2230. ST_WORD(&tbl[6], 0xFFFF);
  2231. }
  2232. tbl[5] = 254;
  2233. if (fmt != FS_FAT32) /* System ID */
  2234. tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06;
  2235. else
  2236. tbl[4] = 0x0c;
  2237. ST_DWORD(tbl+8, 63); /* Partition start in LBA */
  2238. ST_DWORD(tbl+12, n_part); /* Partition size in LBA */
  2239. ST_WORD(tbl+64, 0xAA55); /* Signature */
  2240. if (disk_write(drv, fs->win, 0, 1) != RES_OK)
  2241. return FR_DISK_ERR;
  2242. }
  2243. /* Create boot record */
  2244. tbl = fs->win; /* Clear buffer */
  2245. mem_set(tbl, 0, SS(fs));
  2246. ST_DWORD(tbl+BS_jmpBoot, 0x90FEEB); /* Boot code (jmp $, nop) */
  2247. ST_WORD(tbl+BPB_BytsPerSec, SS(fs)); /* Sector size */
  2248. tbl[BPB_SecPerClus] = (BYTE)allocsize; /* Sectors per cluster */
  2249. ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv); /* Reserved sectors */
  2250. tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */
  2251. ST_WORD(tbl+BPB_RootEntCnt, SS(fs) / 32 * n_dir); /* Number of rootdir entries */
  2252. if (n_part < 0x10000) { /* Number of total sectors */
  2253. ST_WORD(tbl+BPB_TotSec16, n_part);
  2254. } else {
  2255. ST_DWORD(tbl+BPB_TotSec32, n_part);
  2256. }
  2257. tbl[BPB_Media] = 0xF8; /* Media descripter */
  2258. ST_WORD(tbl+BPB_SecPerTrk, 63); /* Number of sectors per track */
  2259. ST_WORD(tbl+BPB_NumHeads, 255); /* Number of heads */
  2260. ST_DWORD(tbl+BPB_HiddSec, b_part); /* Hidden sectors */
  2261. n = get_fattime(); /* Use current time as a VSN */
  2262. if (fmt != FS_FAT32) {
  2263. ST_DWORD(tbl+BS_VolID, n); /* Volume serial number */
  2264. ST_WORD(tbl+BPB_FATSz16, n_fat); /* Number of secters per FAT */
  2265. tbl[BS_DrvNum] = 0x80; /* Drive number */
  2266. tbl[BS_BootSig] = 0x29; /* Extended boot signature */
  2267. mem_cpy(tbl+BS_VolLab, "NO NAME FAT ", 19); /* Volume lavel, FAT signature */
  2268. } else {
  2269. ST_DWORD(tbl+BS_VolID32, n); /* Volume serial number */
  2270. ST_DWORD(tbl+BPB_FATSz32, n_fat); /* Number of secters per FAT */
  2271. ST_DWORD(tbl+BPB_RootClus, 2); /* Root directory cluster (2) */
  2272. ST_WORD(tbl+BPB_FSInfo, 1); /* FSInfo record offset (bs+1) */
  2273. ST_WORD(tbl+BPB_BkBootSec, 6); /* Backup boot record offset (bs+6) */
  2274. tbl[BS_DrvNum32] = 0x80; /* Drive number */
  2275. tbl[BS_BootSig32] = 0x29; /* Extended boot signature */
  2276. mem_cpy(tbl+BS_VolLab32, "NO NAME FAT32 ", 19); /* Volume lavel, FAT signature */
  2277. }
  2278. ST_WORD(tbl+BS_55AA, 0xAA55); /* Signature */
  2279. if (disk_write(drv, tbl, b_part+0, 1) != RES_OK)
  2280. return FR_DISK_ERR;
  2281. if (fmt == FS_FAT32)
  2282. disk_write(drv, tbl, b_part+6, 1);
  2283. /* Initialize FAT area */
  2284. for (m = 0; m < N_FATS; m++) {
  2285. mem_set(tbl, 0, SS(fs)); /* 1st sector of the FAT */
  2286. if (fmt != FS_FAT32) {
  2287. n = (fmt == FS_FAT12) ? 0x00FFFFF8 : 0xFFFFFFF8;
  2288. ST_DWORD(tbl, n); /* Reserve cluster #0-1 (FAT12/16) */
  2289. } else {
  2290. ST_DWORD(tbl+0, 0xFFFFFFF8); /* Reserve cluster #0-1 (FAT32) */
  2291. ST_DWORD(tbl+4, 0xFFFFFFFF);
  2292. ST_DWORD(tbl+8, 0x0FFFFFFF); /* Reserve cluster #2 for root dir */
  2293. }
  2294. if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
  2295. return FR_DISK_ERR;
  2296. mem_set(tbl, 0, SS(fs)); /* Following FAT entries are filled by zero */
  2297. for (n = 1; n < n_fat; n++) {
  2298. if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
  2299. return FR_DISK_ERR;
  2300. }
  2301. }
  2302. /* Initialize Root directory */
  2303. m = (BYTE)((fmt == FS_FAT32) ? allocsize : n_dir);
  2304. do {
  2305. if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
  2306. return FR_DISK_ERR;
  2307. } while (--m);
  2308. /* Create FSInfo record if needed */
  2309. if (fmt == FS_FAT32) {
  2310. ST_WORD(tbl+BS_55AA, 0xAA55);
  2311. ST_DWORD(tbl+FSI_LeadSig, 0x41615252);
  2312. ST_DWORD(tbl+FSI_StrucSig, 0x61417272);
  2313. ST_DWORD(tbl+FSI_Free_Count, n_clst - 1);
  2314. ST_DWORD(tbl+FSI_Nxt_Free, 0xFFFFFFFF);
  2315. disk_write(drv, tbl, b_part+1, 1);
  2316. disk_write(drv, tbl, b_part+7, 1);
  2317. }
  2318. return (disk_ioctl(drv, CTRL_SYNC, (void*)NULL) == RES_OK) ? FR_OK : FR_DISK_ERR;
  2319. }
  2320. #endif /* _USE_MKFS && !_FS_READONLY */
  2321. #if _USE_STRFUNC
  2322. /*-----------------------------------------------------------------------*/
  2323. /* Get a string from the file */
  2324. /*-----------------------------------------------------------------------*/
  2325. char* f_gets (
  2326. char* buff, /* Pointer to the string buffer to read */
  2327. int len, /* Size of string buffer */
  2328. FIL* fil /* Pointer to the file object */
  2329. )
  2330. {
  2331. int i = 0;
  2332. char *p = buff;
  2333. UINT rc;
  2334. while (i < len - 1) { /* Read bytes until buffer gets filled */
  2335. f_read(fil, p, 1, &rc);
  2336. if (rc != 1) break; /* Break when no data to read */
  2337. #if _USE_STRFUNC >= 2
  2338. if (*p == '\r') continue; /* Strip '\r' */
  2339. #endif
  2340. i++;
  2341. if (*p++ == '\n') break; /* Break when reached end of line */
  2342. }
  2343. *p = 0;
  2344. return i ? buff : NULL; /* When no data read (eof or error), return with error. */
  2345. }
  2346. #if !_FS_READONLY
  2347. #include <stdarg.h>
  2348. /*-----------------------------------------------------------------------*/
  2349. /* Put a character to the file */
  2350. /*-----------------------------------------------------------------------*/
  2351. int f_putc (
  2352. int chr, /* A character to be output */
  2353. FIL* fil /* Ponter to the file object */
  2354. )
  2355. {
  2356. UINT bw;
  2357. char c;
  2358. #if _USE_STRFUNC >= 2
  2359. if (chr == '\n') f_putc ('\r', fil); /* LF -> CRLF conversion */
  2360. #endif
  2361. if (!fil) { /* Special value may be used to switch the destination to any other device */
  2362. /* put_console(chr); */
  2363. return chr;
  2364. }
  2365. c = (char)chr;
  2366. f_write(fil, &c, 1, &bw); /* Write a byte to the file */
  2367. return bw ? chr : EOF; /* Return the result */
  2368. }
  2369. /*-----------------------------------------------------------------------*/
  2370. /* Put a string to the file */
  2371. /*-----------------------------------------------------------------------*/
  2372. int f_puts (
  2373. const char* str, /* Pointer to the string to be output */
  2374. FIL* fil /* Pointer to the file object */
  2375. )
  2376. {
  2377. int n;
  2378. for (n = 0; *str; str++, n++) {
  2379. if (f_putc(*str, fil) == EOF) return EOF;
  2380. }
  2381. return n;
  2382. }
  2383. /*-----------------------------------------------------------------------*/
  2384. /* Put a formatted string to the file */
  2385. /*-----------------------------------------------------------------------*/
  2386. int f_printf (
  2387. FIL* fil, /* Pointer to the file object */
  2388. const char* str, /* Pointer to the format string */
  2389. ... /* Optional arguments... */
  2390. )
  2391. {
  2392. va_list arp;
  2393. UCHAR c, f, r;
  2394. ULONG val;
  2395. char s[16];
  2396. int i, w, res, cc;
  2397. va_start(arp, str);
  2398. for (cc = res = 0; cc != EOF; res += cc) {
  2399. c = *str++;
  2400. if (c == 0) break; /* End of string */
  2401. if (c != '%') { /* Non escape cahracter */
  2402. cc = f_putc(c, fil);
  2403. if (cc != EOF) cc = 1;
  2404. continue;
  2405. }
  2406. w = f = 0;
  2407. c = *str++;
  2408. if (c == '0') { /* Flag: '0' padding */
  2409. f = 1; c = *str++;
  2410. }
  2411. while (c >= '0' && c <= '9') { /* Precision */
  2412. w = w * 10 + (c - '0');
  2413. c = *str++;
  2414. }
  2415. if (c == 'l') { /* Prefix: Size is long int */
  2416. f |= 2; c = *str++;
  2417. }
  2418. if (c == 's') { /* Type is string */
  2419. cc = f_puts(va_arg(arp, char*), fil);
  2420. continue;
  2421. }
  2422. if (c == 'c') { /* Type is character */
  2423. cc = f_putc(va_arg(arp, int), fil);
  2424. if (cc != EOF) cc = 1;
  2425. continue;
  2426. }
  2427. r = 0;
  2428. if (c == 'd') r = 10; /* Type is signed decimal */
  2429. if (c == 'u') r = 10; /* Type is unsigned decimal */
  2430. if (c == 'X') r = 16; /* Type is unsigned hexdecimal */
  2431. if (r == 0) break; /* Unknown type */
  2432. if (f & 2) { /* Get the value */
  2433. val = (ULONG)va_arg(arp, long);
  2434. } else {
  2435. val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int);
  2436. }
  2437. /* Put numeral string */
  2438. if (c == 'd') {
  2439. if (val & 0x80000000) {
  2440. val = 0 - val;
  2441. f |= 4;
  2442. }
  2443. }
  2444. i = sizeof(s) - 1; s[i] = 0;
  2445. do {
  2446. c = (UCHAR)(val % r + '0');
  2447. if (c > '9') c += 7;
  2448. s[--i] = c;
  2449. val /= r;
  2450. } while (i && val);
  2451. if (i && (f & 4)) s[--i] = '-';
  2452. w = sizeof(s) - 1 - w;
  2453. while (i && i > w) s[--i] = (f & 1) ? '0' : ' ';
  2454. cc = f_puts(&s[i], fil);
  2455. }
  2456. va_end(arp);
  2457. return (cc == EOF) ? cc : res;
  2458. }
  2459. #endif /* !_FS_READONLY */
  2460. #endif /* _USE_STRFUNC */