ff.c 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - FAT file system module R0.09a (C)ChaN, 2012
  3. /-----------------------------------------------------------------------------/
  4. / FatFs module is a generic FAT file system module for small embedded systems.
  5. / This is a free software that opened for education, research and commercial
  6. / developments under license policy of following terms.
  7. /
  8. / Copyright (C) 2012, 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 products UNDER YOUR RESPONSIBILITY.
  13. / * Redistributions of source code must retain the above copyright notice.
  14. /
  15. /-----------------------------------------------------------------------------/
  16. / Feb 26,'06 R0.00 Prototype.
  17. /
  18. / Apr 29,'06 R0.01 First stable version.
  19. /
  20. / Jun 01,'06 R0.02 Added FAT12 support.
  21. / Removed unbuffered mode.
  22. / Fixed a problem on small (<32M) partition.
  23. / Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
  24. /
  25. / Sep 22,'06 R0.03 Added f_rename().
  26. / Changed option _FS_MINIMUM to _FS_MINIMIZE.
  27. / Dec 11,'06 R0.03a Improved cluster scan algorithm to write files fast.
  28. / Fixed f_mkdir() creates incorrect directory on FAT32.
  29. /
  30. / Feb 04,'07 R0.04 Supported multiple drive system.
  31. / Changed some interfaces for multiple drive system.
  32. / Changed f_mountdrv() to f_mount().
  33. / Added f_mkfs().
  34. / Apr 01,'07 R0.04a Supported multiple partitions on a physical drive.
  35. / Added a capability of extending file size to f_lseek().
  36. / Added minimization level 3.
  37. / Fixed an endian sensitive code in f_mkfs().
  38. / May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
  39. / Added FSInfo support.
  40. / Fixed DBCS name can result FR_INVALID_NAME.
  41. / Fixed short seek (<= csize) collapses the file object.
  42. /
  43. / Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs().
  44. / Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
  45. / Fixed f_mkdir() on FAT32 creates incorrect directory.
  46. / Feb 03,'08 R0.05a Added f_truncate() and f_utime().
  47. / Fixed off by one error at FAT sub-type determination.
  48. / Fixed btr in f_read() can be mistruncated.
  49. / Fixed cached sector is not flushed when create and close 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 or following cluster.
  53. /
  54. / Apr 01,'09 R0.07 Merged Tiny-FatFs as a configuration option. (_FS_TINY)
  55. / Added long file name feature.
  56. / Added multiple code page feature.
  57. / Added re-entrancy for multitask operation.
  58. / Added auto cluster size selection to f_mkfs().
  59. / Added rewind option to f_readdir().
  60. / Changed result code of critical errors.
  61. / Renamed string functions to avoid name collision.
  62. / Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
  63. / Added multiple sector size feature.
  64. / Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.
  65. / Fixed wrong cache control in f_lseek().
  66. / Added relative path feature.
  67. / Added f_chdir() and f_chdrive().
  68. / Added proper case conversion to extended char.
  69. / Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.
  70. / Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.
  71. / Fixed name matching error on the 13 char boundary.
  72. / Added a configuration option, _LFN_UNICODE.
  73. / Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.
  74. /
  75. / May 15,'10 R0.08 Added a memory configuration option. (_USE_LFN = 3)
  76. / Added file lock feature. (_FS_SHARE)
  77. / Added fast seek feature. (_USE_FASTSEEK)
  78. / Changed some types on the API, XCHAR->TCHAR.
  79. / Changed fname member in the FILINFO structure on Unicode cfg.
  80. / String functions support UTF-8 encoding files on Unicode cfg.
  81. / Aug 16,'10 R0.08a Added f_getcwd(). (_FS_RPATH = 2)
  82. / Added sector erase feature. (_USE_ERASE)
  83. / Moved file lock semaphore table from fs object to the bss.
  84. / Fixed a wrong directory entry is created on non-LFN cfg when the given name contains ';'.
  85. / Fixed f_mkfs() creates wrong FAT32 volume.
  86. / Jan 15,'11 R0.08b Fast seek feature is also applied to f_read() and f_write().
  87. / f_lseek() reports required table size on creating CLMP.
  88. / Extended format syntax of f_printf function.
  89. / Ignores duplicated directory separators in given path name.
  90. /
  91. / Sep 06,'11 R0.09 f_mkfs() supports multiple partition to finish the multiple partition feature.
  92. / Added f_fdisk(). (_MULTI_PARTITION = 2)
  93. / Aug 27,'12 R0.09a Fixed assertion failure due to OS/2 EA on FAT12/16 volume.
  94. / Changed f_open() and f_opendir reject null object pointer to avoid crash.
  95. / Changed option name _FS_SHARE to _FS_LOCK.
  96. /---------------------------------------------------------------------------*/
  97. #include "ff.h" /* FatFs configurations and declarations */
  98. #include "diskio.h" /* Declarations of low level disk I/O functions */
  99. /*--------------------------------------------------------------------------
  100. Module Private Definitions
  101. ---------------------------------------------------------------------------*/
  102. #if _FATFS != 4004 /* Revision ID */
  103. #error Wrong include file (ff.h).
  104. #endif
  105. /* Definitions on sector size */
  106. #if _MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096
  107. #error Wrong sector size.
  108. #endif
  109. #if _MAX_SS != 512
  110. #define SS(fs) ((fs)->ssize) /* Variable sector size */
  111. #else
  112. #define SS(fs) 512U /* Fixed sector size */
  113. #endif
  114. /* Reentrancy related */
  115. #if _FS_REENTRANT
  116. #if _USE_LFN == 1
  117. #error Static LFN work area must not be used in re-entrant configuration.
  118. #endif
  119. #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
  120. #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
  121. #else
  122. #define ENTER_FF(fs)
  123. #define LEAVE_FF(fs, res) return res
  124. #endif
  125. #define ABORT(fs, res) { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }
  126. /* File access control feature */
  127. #if _FS_LOCK
  128. #if _FS_READONLY
  129. #error _FS_LOCK must be 0 on read-only cfg.
  130. #endif
  131. typedef struct {
  132. FATFS *fs; /* File ID 1, volume (NULL:blank entry) */
  133. DWORD clu; /* File ID 2, directory */
  134. WORD idx; /* File ID 3, directory index */
  135. WORD ctr; /* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:write mode */
  136. } FILESEM;
  137. #endif
  138. /* DBCS code ranges and SBCS extend char conversion table */
  139. #if _CODE_PAGE == 932 /* Japanese Shift-JIS */
  140. #define _DF1S 0x81 /* DBC 1st byte range 1 start */
  141. #define _DF1E 0x9F /* DBC 1st byte range 1 end */
  142. #define _DF2S 0xE0 /* DBC 1st byte range 2 start */
  143. #define _DF2E 0xFC /* DBC 1st byte range 2 end */
  144. #define _DS1S 0x40 /* DBC 2nd byte range 1 start */
  145. #define _DS1E 0x7E /* DBC 2nd byte range 1 end */
  146. #define _DS2S 0x80 /* DBC 2nd byte range 2 start */
  147. #define _DS2E 0xFC /* DBC 2nd byte range 2 end */
  148. #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
  149. #define _DF1S 0x81
  150. #define _DF1E 0xFE
  151. #define _DS1S 0x40
  152. #define _DS1E 0x7E
  153. #define _DS2S 0x80
  154. #define _DS2E 0xFE
  155. #elif _CODE_PAGE == 949 /* Korean */
  156. #define _DF1S 0x81
  157. #define _DF1E 0xFE
  158. #define _DS1S 0x41
  159. #define _DS1E 0x5A
  160. #define _DS2S 0x61
  161. #define _DS2E 0x7A
  162. #define _DS3S 0x81
  163. #define _DS3E 0xFE
  164. #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
  165. #define _DF1S 0x81
  166. #define _DF1E 0xFE
  167. #define _DS1S 0x40
  168. #define _DS1E 0x7E
  169. #define _DS2S 0xA1
  170. #define _DS2E 0xFE
  171. #elif _CODE_PAGE == 437 /* U.S. (OEM) */
  172. #define _DF1S 0
  173. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F,0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  174. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  175. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  176. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  177. #elif _CODE_PAGE == 720 /* Arabic (OEM) */
  178. #define _DF1S 0
  179. #define _EXCVT {0x80,0x81,0x45,0x41,0x84,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x49,0x49,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  180. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  181. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  182. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  183. #elif _CODE_PAGE == 737 /* Greek (OEM) */
  184. #define _DF1S 0
  185. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
  186. 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  187. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  188. 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xE7,0xE8,0xF1,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  189. #elif _CODE_PAGE == 775 /* Baltic (OEM) */
  190. #define _DF1S 0
  191. #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  192. 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  193. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  194. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  195. #elif _CODE_PAGE == 850 /* Multilingual Latin 1 (OEM) */
  196. #define _DF1S 0
  197. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  198. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  199. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  200. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  201. #elif _CODE_PAGE == 852 /* Latin 2 (OEM) */
  202. #define _DF1S 0
  203. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F,0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0x9F, \
  204. 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
  205. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  206. 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
  207. #elif _CODE_PAGE == 855 /* Cyrillic (OEM) */
  208. #define _DF1S 0
  209. #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F,0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
  210. 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
  211. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
  212. 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
  213. #elif _CODE_PAGE == 857 /* Turkish (OEM) */
  214. #define _DF1S 0
  215. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x98,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
  216. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  217. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  218. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0x59,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  219. #elif _CODE_PAGE == 858 /* Multilingual Latin 1 + Euro (OEM) */
  220. #define _DF1S 0
  221. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  222. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  223. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  224. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  225. #elif _CODE_PAGE == 862 /* Hebrew (OEM) */
  226. #define _DF1S 0
  227. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  228. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  229. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  230. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  231. #elif _CODE_PAGE == 866 /* Russian (OEM) */
  232. #define _DF1S 0
  233. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  234. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  235. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  236. 0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  237. #elif _CODE_PAGE == 874 /* Thai (OEM, Windows) */
  238. #define _DF1S 0
  239. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  240. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  241. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  242. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  243. #elif _CODE_PAGE == 1250 /* Central Europe (Windows) */
  244. #define _DF1S 0
  245. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
  246. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xA3,0xB4,0xB5,0xB6,0xB7,0xB8,0xA5,0xAA,0xBB,0xBC,0xBD,0xBC,0xAF, \
  247. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  248. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
  249. #elif _CODE_PAGE == 1251 /* Cyrillic (Windows) */
  250. #define _DF1S 0
  251. #define _EXCVT {0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x80,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
  252. 0xA0,0xA2,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB2,0xA5,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xA3,0xBD,0xBD,0xAF, \
  253. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  254. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF}
  255. #elif _CODE_PAGE == 1252 /* Latin 1 (Windows) */
  256. #define _DF1S 0
  257. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0xAd,0x9B,0x8C,0x9D,0xAE,0x9F, \
  258. 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  259. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  260. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
  261. #elif _CODE_PAGE == 1253 /* Greek (Windows) */
  262. #define _DF1S 0
  263. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  264. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  265. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xA2,0xB8,0xB9,0xBA, \
  266. 0xE0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xFB,0xBC,0xFD,0xBF,0xFF}
  267. #elif _CODE_PAGE == 1254 /* Turkish (Windows) */
  268. #define _DF1S 0
  269. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x9D,0x9E,0x9F, \
  270. 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  271. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  272. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
  273. #elif _CODE_PAGE == 1255 /* Hebrew (Windows) */
  274. #define _DF1S 0
  275. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  276. 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  277. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  278. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  279. #elif _CODE_PAGE == 1256 /* Arabic (Windows) */
  280. #define _DF1S 0
  281. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \
  282. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  283. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  284. 0x41,0xE1,0x41,0xE3,0xE4,0xE5,0xE6,0x43,0x45,0x45,0x45,0x45,0xEC,0xED,0x49,0x49,0xF0,0xF1,0xF2,0xF3,0x4F,0xF5,0xF6,0xF7,0xF8,0x55,0xFA,0x55,0x55,0xFD,0xFE,0xFF}
  285. #elif _CODE_PAGE == 1257 /* Baltic (Windows) */
  286. #define _DF1S 0
  287. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  288. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xBC,0xBD,0xBE,0xAF, \
  289. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  290. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
  291. #elif _CODE_PAGE == 1258 /* Vietnam (OEM, Windows) */
  292. #define _DF1S 0
  293. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0xAC,0x9D,0x9E,0x9F, \
  294. 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  295. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  296. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xEC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xFE,0x9F}
  297. #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
  298. #if _USE_LFN
  299. #error Cannot use LFN feature without valid code page.
  300. #endif
  301. #define _DF1S 0
  302. #else
  303. #error Unknown code page
  304. #endif
  305. /* Character code support macros */
  306. #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
  307. #define IsLower(c) (((c)>='a')&&((c)<='z'))
  308. #define IsDigit(c) (((c)>='0')&&((c)<='9'))
  309. #if _DF1S /* Code page is DBCS */
  310. #ifdef _DF2S /* Two 1st byte areas */
  311. #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
  312. #else /* One 1st byte area */
  313. #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
  314. #endif
  315. #ifdef _DS3S /* Three 2nd byte areas */
  316. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
  317. #else /* Two 2nd byte areas */
  318. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
  319. #endif
  320. #else /* Code page is SBCS */
  321. #define IsDBCS1(c) 0
  322. #define IsDBCS2(c) 0
  323. #endif /* _DF1S */
  324. /* Name status flags */
  325. #define NS 11 /* Index of name status byte in fn[] */
  326. #define NS_LOSS 0x01 /* Out of 8.3 format */
  327. #define NS_LFN 0x02 /* Force to create LFN entry */
  328. #define NS_LAST 0x04 /* Last segment */
  329. #define NS_BODY 0x08 /* Lower case flag (body) */
  330. #define NS_EXT 0x10 /* Lower case flag (ext) */
  331. #define NS_DOT 0x20 /* Dot entry */
  332. /* FAT sub-type boundaries */
  333. /* Note that the FAT spec by Microsoft says 4085 but Windows works with 4087! */
  334. #define MIN_FAT16 4086 /* Minimum number of clusters for FAT16 */
  335. #define MIN_FAT32 65526 /* Minimum number of clusters for FAT32 */
  336. /* FatFs refers the members in the FAT structures as byte array instead of
  337. / structure member because the structure is not binary compatible between
  338. / different platforms */
  339. #define BS_jmpBoot 0 /* Jump instruction (3) */
  340. #define BS_OEMName 3 /* OEM name (8) */
  341. #define BPB_BytsPerSec 11 /* Sector size [byte] (2) */
  342. #define BPB_SecPerClus 13 /* Cluster size [sector] (1) */
  343. #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (2) */
  344. #define BPB_NumFATs 16 /* Number of FAT copies (1) */
  345. #define BPB_RootEntCnt 17 /* Number of root dir entries for FAT12/16 (2) */
  346. #define BPB_TotSec16 19 /* Volume size [sector] (2) */
  347. #define BPB_Media 21 /* Media descriptor (1) */
  348. #define BPB_FATSz16 22 /* FAT size [sector] (2) */
  349. #define BPB_SecPerTrk 24 /* Track size [sector] (2) */
  350. #define BPB_NumHeads 26 /* Number of heads (2) */
  351. #define BPB_HiddSec 28 /* Number of special hidden sectors (4) */
  352. #define BPB_TotSec32 32 /* Volume size [sector] (4) */
  353. #define BS_DrvNum 36 /* Physical drive number (2) */
  354. #define BS_BootSig 38 /* Extended boot signature (1) */
  355. #define BS_VolID 39 /* Volume serial number (4) */
  356. #define BS_VolLab 43 /* Volume label (8) */
  357. #define BS_FilSysType 54 /* File system type (1) */
  358. #define BPB_FATSz32 36 /* FAT size [sector] (4) */
  359. #define BPB_ExtFlags 40 /* Extended flags (2) */
  360. #define BPB_FSVer 42 /* File system version (2) */
  361. #define BPB_RootClus 44 /* Root dir first cluster (4) */
  362. #define BPB_FSInfo 48 /* Offset of FSInfo sector (2) */
  363. #define BPB_BkBootSec 50 /* Offset of backup boot sector (2) */
  364. #define BS_DrvNum32 64 /* Physical drive number (2) */
  365. #define BS_BootSig32 66 /* Extended boot signature (1) */
  366. #define BS_VolID32 67 /* Volume serial number (4) */
  367. #define BS_VolLab32 71 /* Volume label (8) */
  368. #define BS_FilSysType32 82 /* File system type (1) */
  369. #define FSI_LeadSig 0 /* FSI: Leading signature (4) */
  370. #define FSI_StrucSig 484 /* FSI: Structure signature (4) */
  371. #define FSI_Free_Count 488 /* FSI: Number of free clusters (4) */
  372. #define FSI_Nxt_Free 492 /* FSI: Last allocated cluster (4) */
  373. #define MBR_Table 446 /* MBR: Partition table offset (2) */
  374. #define SZ_PTE 16 /* MBR: Size of a partition table entry */
  375. #define BS_55AA 510 /* Boot sector signature (2) */
  376. #define DIR_Name 0 /* Short file name (11) */
  377. #define DIR_Attr 11 /* Attribute (1) */
  378. #define DIR_NTres 12 /* NT flag (1) */
  379. #define DIR_CrtTimeTenth 13 /* Created time sub-second (1) */
  380. #define DIR_CrtTime 14 /* Created time (2) */
  381. #define DIR_CrtDate 16 /* Created date (2) */
  382. #define DIR_LstAccDate 18 /* Last accessed date (2) */
  383. #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (2) */
  384. #define DIR_WrtTime 22 /* Modified time (2) */
  385. #define DIR_WrtDate 24 /* Modified date (2) */
  386. #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (2) */
  387. #define DIR_FileSize 28 /* File size (4) */
  388. #define LDIR_Ord 0 /* LFN entry order and LLE flag (1) */
  389. #define LDIR_Attr 11 /* LFN attribute (1) */
  390. #define LDIR_Type 12 /* LFN type (1) */
  391. #define LDIR_Chksum 13 /* Sum of corresponding SFN entry */
  392. #define LDIR_FstClusLO 26 /* Filled by zero (0) */
  393. #define SZ_DIR 32 /* Size of a directory entry */
  394. #define LLE 0x40 /* Last long entry flag in LDIR_Ord */
  395. #define DDE 0xE5 /* Deleted directory entry mark in DIR_Name[0] */
  396. #define NDDE 0x05 /* Replacement of the character collides with DDE */
  397. /*------------------------------------------------------------*/
  398. /* Module private work area */
  399. /*------------------------------------------------------------*/
  400. /* Note that uninitialized variables with static duration are
  401. / zeroed/nulled at start-up. If not, the compiler or start-up
  402. / routine is out of ANSI-C standard.
  403. */
  404. #if _VOLUMES
  405. static
  406. FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */
  407. #else
  408. #error Number of volumes must not be 0.
  409. #endif
  410. static
  411. WORD Fsid; /* File system mount ID */
  412. #if _FS_RPATH
  413. static
  414. BYTE CurrVol; /* Current drive */
  415. #endif
  416. #if _FS_LOCK
  417. static
  418. FILESEM Files[_FS_LOCK]; /* File lock semaphores */
  419. #endif
  420. #if _USE_LFN == 0 /* No LFN feature */
  421. #define DEF_NAMEBUF BYTE sfn[12]
  422. #define INIT_BUF(dobj) (dobj).fn = sfn
  423. #define FREE_BUF()
  424. #elif _USE_LFN == 1 /* LFN feature with static working buffer */
  425. static WCHAR LfnBuf[_MAX_LFN+1];
  426. #define DEF_NAMEBUF BYTE sfn[12]
  427. #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = LfnBuf; }
  428. #define FREE_BUF()
  429. #elif _USE_LFN == 2 /* LFN feature with dynamic working buffer on the stack */
  430. #define DEF_NAMEBUF BYTE sfn[12]; WCHAR lbuf[_MAX_LFN+1]
  431. #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = lbuf; }
  432. #define FREE_BUF()
  433. #elif _USE_LFN == 3 /* LFN feature with dynamic working buffer on the heap */
  434. #define DEF_NAMEBUF BYTE sfn[12]; WCHAR *lfn
  435. #define INIT_BUF(dobj) { lfn = ff_memalloc((_MAX_LFN + 1) * 2); \
  436. if (!lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); \
  437. (dobj).lfn = lfn; (dobj).fn = sfn; }
  438. #define FREE_BUF() ff_memfree(lfn)
  439. #else
  440. #error Wrong LFN configuration.
  441. #endif
  442. /*--------------------------------------------------------------------------
  443. Module Private Functions
  444. ---------------------------------------------------------------------------*/
  445. /*-----------------------------------------------------------------------*/
  446. /* String functions */
  447. /*-----------------------------------------------------------------------*/
  448. /* Copy memory to memory */
  449. static
  450. void mem_cpy (void* dst, const void* src, UINT cnt) {
  451. BYTE *d = (BYTE*)dst;
  452. const BYTE *s = (const BYTE*)src;
  453. #if _WORD_ACCESS == 1
  454. while (cnt >= sizeof (int)) {
  455. *(int*)d = *(int*)s;
  456. d += sizeof (int); s += sizeof (int);
  457. cnt -= sizeof (int);
  458. }
  459. #endif
  460. while (cnt--)
  461. *d++ = *s++;
  462. }
  463. /* Fill memory */
  464. static
  465. void mem_set (void* dst, int val, UINT cnt) {
  466. BYTE *d = (BYTE*)dst;
  467. while (cnt--)
  468. *d++ = (BYTE)val;
  469. }
  470. /* Compare memory to memory */
  471. static
  472. int mem_cmp (const void* dst, const void* src, UINT cnt) {
  473. const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;
  474. int r = 0;
  475. while (cnt-- && (r = *d++ - *s++) == 0) ;
  476. return r;
  477. }
  478. /* Check if chr is contained in the string */
  479. static
  480. int chk_chr (const char* str, int chr) {
  481. while (*str && *str != chr) str++;
  482. return *str;
  483. }
  484. /*-----------------------------------------------------------------------*/
  485. /* Request/Release grant to access the volume */
  486. /*-----------------------------------------------------------------------*/
  487. #if _FS_REENTRANT
  488. static
  489. int lock_fs (
  490. FATFS *fs /* File system object */
  491. )
  492. {
  493. return ff_req_grant(fs->sobj);
  494. }
  495. static
  496. void unlock_fs (
  497. FATFS *fs, /* File system object */
  498. FRESULT res /* Result code to be returned */
  499. )
  500. {
  501. if (fs &&
  502. res != FR_NOT_ENABLED &&
  503. res != FR_INVALID_DRIVE &&
  504. res != FR_INVALID_OBJECT &&
  505. res != FR_TIMEOUT) {
  506. ff_rel_grant(fs->sobj);
  507. }
  508. }
  509. #endif
  510. /*-----------------------------------------------------------------------*/
  511. /* File lock control functions */
  512. /*-----------------------------------------------------------------------*/
  513. #if _FS_LOCK
  514. static
  515. FRESULT chk_lock ( /* Check if the file can be accessed */
  516. DIR* dj, /* Directory object pointing the file to be checked */
  517. int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  518. )
  519. {
  520. UINT i, be;
  521. /* Search file semaphore table */
  522. for (i = be = 0; i < _FS_LOCK; i++) {
  523. if (Files[i].fs) { /* Existing entry */
  524. if (Files[i].fs == dj->fs && /* Check if the file matched with an open file */
  525. Files[i].clu == dj->sclust &&
  526. Files[i].idx == dj->index) break;
  527. } else { /* Blank entry */
  528. be++;
  529. }
  530. }
  531. if (i == _FS_LOCK) /* The file is not opened */
  532. return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new file? */
  533. /* The file has been opened. Reject any open against writing file and all write mode open */
  534. return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  535. }
  536. static
  537. int enq_lock (void) /* Check if an entry is available for a new file */
  538. {
  539. UINT i;
  540. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  541. return (i == _FS_LOCK) ? 0 : 1;
  542. }
  543. static
  544. UINT inc_lock ( /* Increment file open counter and returns its index (0:int error) */
  545. DIR* dj, /* Directory object pointing the file to register or increment */
  546. int acc /* Desired access mode (0:Read, !0:Write) */
  547. )
  548. {
  549. UINT i;
  550. for (i = 0; i < _FS_LOCK; i++) { /* Find the file */
  551. if (Files[i].fs == dj->fs &&
  552. Files[i].clu == dj->sclust &&
  553. Files[i].idx == dj->index) break;
  554. }
  555. if (i == _FS_LOCK) { /* Not opened. Register it as new. */
  556. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  557. if (i == _FS_LOCK) return 0; /* No space to register (int err) */
  558. Files[i].fs = dj->fs;
  559. Files[i].clu = dj->sclust;
  560. Files[i].idx = dj->index;
  561. Files[i].ctr = 0;
  562. }
  563. if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
  564. Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
  565. return i + 1;
  566. }
  567. static
  568. FRESULT dec_lock ( /* Decrement file open counter */
  569. UINT i /* Semaphore index */
  570. )
  571. {
  572. WORD n;
  573. FRESULT res;
  574. if (--i < _FS_LOCK) {
  575. n = Files[i].ctr;
  576. if (n == 0x100) n = 0;
  577. if (n) n--;
  578. Files[i].ctr = n;
  579. if (!n) Files[i].fs = 0;
  580. res = FR_OK;
  581. } else {
  582. res = FR_INT_ERR;
  583. }
  584. return res;
  585. }
  586. static
  587. void clear_lock ( /* Clear lock entries of the volume */
  588. FATFS *fs
  589. )
  590. {
  591. UINT i;
  592. for (i = 0; i < _FS_LOCK; i++) {
  593. if (Files[i].fs == fs) Files[i].fs = 0;
  594. }
  595. }
  596. #endif
  597. /*-----------------------------------------------------------------------*/
  598. /* Change window offset */
  599. /*-----------------------------------------------------------------------*/
  600. static
  601. FRESULT move_window (
  602. FATFS *fs, /* File system object */
  603. DWORD sector /* Sector number to make appearance in the fs->win[] */
  604. ) /* Move to zero only writes back dirty window */
  605. {
  606. DWORD wsect;
  607. wsect = fs->winsect;
  608. if (wsect != sector) { /* Changed current window */
  609. #if !_FS_READONLY
  610. if (fs->wflag) { /* Write back dirty window if needed */
  611. if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK)
  612. return FR_DISK_ERR;
  613. fs->wflag = 0;
  614. if (wsect < (fs->fatbase + fs->fsize)) { /* In FAT area */
  615. BYTE nf;
  616. for (nf = fs->n_fats; nf > 1; nf--) { /* Reflect the change to all FAT copies */
  617. wsect += fs->fsize;
  618. disk_write(fs->drv, fs->win, wsect, 1);
  619. }
  620. }
  621. }
  622. #endif
  623. if (sector) {
  624. if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK)
  625. return FR_DISK_ERR;
  626. fs->winsect = sector;
  627. }
  628. }
  629. return FR_OK;
  630. }
  631. /*-----------------------------------------------------------------------*/
  632. /* Clean-up cached data */
  633. /*-----------------------------------------------------------------------*/
  634. #if !_FS_READONLY
  635. static
  636. FRESULT sync ( /* FR_OK: successful, FR_DISK_ERR: failed */
  637. FATFS *fs /* File system object */
  638. )
  639. {
  640. FRESULT res;
  641. res = move_window(fs, 0);
  642. if (res == FR_OK) {
  643. /* Update FSInfo sector if needed */
  644. if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
  645. fs->winsect = 0;
  646. /* Create FSInfo structure */
  647. mem_set(fs->win, 0, 512);
  648. ST_WORD(fs->win+BS_55AA, 0xAA55);
  649. ST_DWORD(fs->win+FSI_LeadSig, 0x41615252);
  650. ST_DWORD(fs->win+FSI_StrucSig, 0x61417272);
  651. ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust);
  652. ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);
  653. /* Write it into the FSInfo sector */
  654. disk_write(fs->drv, fs->win, fs->fsi_sector, 1);
  655. fs->fsi_flag = 0;
  656. }
  657. /* Make sure that no pending write process in the physical drive */
  658. if (disk_ioctl(fs->drv, CTRL_SYNC, 0) != RES_OK)
  659. res = FR_DISK_ERR;
  660. }
  661. return res;
  662. }
  663. #endif
  664. /*-----------------------------------------------------------------------*/
  665. /* Get sector# from cluster# */
  666. /*-----------------------------------------------------------------------*/
  667. DWORD clust2sect ( /* !=0: Sector number, 0: Failed - invalid cluster# */
  668. FATFS *fs, /* File system object */
  669. DWORD clst /* Cluster# to be converted */
  670. )
  671. {
  672. clst -= 2;
  673. if (clst >= (fs->n_fatent - 2)) return 0; /* Invalid cluster# */
  674. return clst * fs->csize + fs->database;
  675. }
  676. /*-----------------------------------------------------------------------*/
  677. /* FAT access - Read value of a FAT entry */
  678. /*-----------------------------------------------------------------------*/
  679. DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status */
  680. FATFS *fs, /* File system object */
  681. DWORD clst /* Cluster# to get the link information */
  682. )
  683. {
  684. UINT wc, bc;
  685. BYTE *p;
  686. if (clst < 2 || clst >= fs->n_fatent) /* Check range */
  687. return 1;
  688. switch (fs->fs_type) {
  689. case FS_FAT12 :
  690. bc = (UINT)clst; bc += bc / 2;
  691. if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;
  692. wc = fs->win[bc % SS(fs)]; bc++;
  693. if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;
  694. wc |= fs->win[bc % SS(fs)] << 8;
  695. return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
  696. case FS_FAT16 :
  697. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)))) break;
  698. p = &fs->win[clst * 2 % SS(fs)];
  699. return LD_WORD(p);
  700. case FS_FAT32 :
  701. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)))) break;
  702. p = &fs->win[clst * 4 % SS(fs)];
  703. return LD_DWORD(p) & 0x0FFFFFFF;
  704. }
  705. return 0xFFFFFFFF; /* An error occurred at the disk I/O layer */
  706. }
  707. /*-----------------------------------------------------------------------*/
  708. /* FAT access - Change value of a FAT entry */
  709. /*-----------------------------------------------------------------------*/
  710. #if !_FS_READONLY
  711. FRESULT put_fat (
  712. FATFS *fs, /* File system object */
  713. DWORD clst, /* Cluster# to be changed in range of 2 to fs->n_fatent - 1 */
  714. DWORD val /* New value to mark the cluster */
  715. )
  716. {
  717. UINT bc;
  718. BYTE *p;
  719. FRESULT res;
  720. if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  721. res = FR_INT_ERR;
  722. } else {
  723. switch (fs->fs_type) {
  724. case FS_FAT12 :
  725. bc = (UINT)clst; bc += bc / 2;
  726. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  727. if (res != FR_OK) break;
  728. p = &fs->win[bc % SS(fs)];
  729. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  730. bc++;
  731. fs->wflag = 1;
  732. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  733. if (res != FR_OK) break;
  734. p = &fs->win[bc % SS(fs)];
  735. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  736. break;
  737. case FS_FAT16 :
  738. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  739. if (res != FR_OK) break;
  740. p = &fs->win[clst * 2 % SS(fs)];
  741. ST_WORD(p, (WORD)val);
  742. break;
  743. case FS_FAT32 :
  744. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  745. if (res != FR_OK) break;
  746. p = &fs->win[clst * 4 % SS(fs)];
  747. val |= LD_DWORD(p) & 0xF0000000;
  748. ST_DWORD(p, val);
  749. break;
  750. default :
  751. res = FR_INT_ERR;
  752. }
  753. fs->wflag = 1;
  754. }
  755. return res;
  756. }
  757. #endif /* !_FS_READONLY */
  758. /*-----------------------------------------------------------------------*/
  759. /* FAT handling - Remove a cluster chain */
  760. /*-----------------------------------------------------------------------*/
  761. #if !_FS_READONLY
  762. static
  763. FRESULT remove_chain (
  764. FATFS *fs, /* File system object */
  765. DWORD clst /* Cluster# to remove a chain from */
  766. )
  767. {
  768. FRESULT res;
  769. DWORD nxt;
  770. #if _USE_ERASE
  771. DWORD scl = clst, ecl = clst, rt[2];
  772. #endif
  773. if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  774. res = FR_INT_ERR;
  775. } else {
  776. res = FR_OK;
  777. while (clst < fs->n_fatent) { /* Not a last link? */
  778. nxt = get_fat(fs, clst); /* Get cluster status */
  779. if (nxt == 0) break; /* Empty cluster? */
  780. if (nxt == 1) { res = FR_INT_ERR; break; } /* Internal error? */
  781. if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */
  782. res = put_fat(fs, clst, 0); /* Mark the cluster "empty" */
  783. if (res != FR_OK) break;
  784. if (fs->free_clust != 0xFFFFFFFF) { /* Update FSInfo */
  785. fs->free_clust++;
  786. fs->fsi_flag = 1;
  787. }
  788. #if _USE_ERASE
  789. if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
  790. ecl = nxt;
  791. } else { /* End of contiguous clusters */
  792. rt[0] = clust2sect(fs, scl); /* Start sector */
  793. rt[1] = clust2sect(fs, ecl) + fs->csize - 1; /* End sector */
  794. disk_ioctl(fs->drv, CTRL_ERASE_SECTOR, rt); /* Erase the block */
  795. scl = ecl = nxt;
  796. }
  797. #endif
  798. clst = nxt; /* Next cluster */
  799. }
  800. }
  801. return res;
  802. }
  803. #endif
  804. /*-----------------------------------------------------------------------*/
  805. /* FAT handling - Stretch or Create a cluster chain */
  806. /*-----------------------------------------------------------------------*/
  807. #if !_FS_READONLY
  808. static
  809. DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  810. FATFS *fs, /* File system object */
  811. DWORD clst /* Cluster# to stretch. 0 means create a new chain. */
  812. )
  813. {
  814. DWORD cs, ncl, scl;
  815. FRESULT res;
  816. if (clst == 0) { /* Create a new chain */
  817. scl = fs->last_clust; /* Get suggested start point */
  818. if (!scl || scl >= fs->n_fatent) scl = 1;
  819. }
  820. else { /* Stretch the current chain */
  821. cs = get_fat(fs, clst); /* Check the cluster status */
  822. if (cs < 2) return 1; /* It is an invalid cluster */
  823. if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
  824. scl = clst;
  825. }
  826. ncl = scl; /* Start cluster */
  827. for (;;) {
  828. ncl++; /* Next cluster */
  829. if (ncl >= fs->n_fatent) { /* Wrap around */
  830. ncl = 2;
  831. if (ncl > scl) return 0; /* No free cluster */
  832. }
  833. cs = get_fat(fs, ncl); /* Get the cluster status */
  834. if (cs == 0) break; /* Found a free cluster */
  835. if (cs == 0xFFFFFFFF || cs == 1)/* An error occurred */
  836. return cs;
  837. if (ncl == scl) return 0; /* No free cluster */
  838. }
  839. res = put_fat(fs, ncl, 0x0FFFFFFF); /* Mark the new cluster "last link" */
  840. if (res == FR_OK && clst != 0) {
  841. res = put_fat(fs, clst, ncl); /* Link it to the previous one if needed */
  842. }
  843. if (res == FR_OK) {
  844. fs->last_clust = ncl; /* Update FSINFO */
  845. if (fs->free_clust != 0xFFFFFFFF) {
  846. fs->free_clust--;
  847. fs->fsi_flag = 1;
  848. }
  849. } else {
  850. ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1;
  851. }
  852. return ncl; /* Return new cluster number or error code */
  853. }
  854. #endif /* !_FS_READONLY */
  855. /*-----------------------------------------------------------------------*/
  856. /* FAT handling - Convert offset into cluster with link map table */
  857. /*-----------------------------------------------------------------------*/
  858. #if _USE_FASTSEEK
  859. static
  860. DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */
  861. FIL* fp, /* Pointer to the file object */
  862. DWORD ofs /* File offset to be converted to cluster# */
  863. )
  864. {
  865. DWORD cl, ncl, *tbl;
  866. tbl = fp->cltbl + 1; /* Top of CLMT */
  867. cl = ofs / SS(fp->fs) / fp->fs->csize; /* Cluster order from top of the file */
  868. for (;;) {
  869. ncl = *tbl++; /* Number of cluters in the fragment */
  870. if (!ncl) return 0; /* End of table? (error) */
  871. if (cl < ncl) break; /* In this fragment? */
  872. cl -= ncl; tbl++; /* Next fragment */
  873. }
  874. return cl + *tbl; /* Return the cluster number */
  875. }
  876. #endif /* _USE_FASTSEEK */
  877. /*-----------------------------------------------------------------------*/
  878. /* Directory handling - Set directory index */
  879. /*-----------------------------------------------------------------------*/
  880. static
  881. FRESULT dir_sdi (
  882. DIR *dj, /* Pointer to directory object */
  883. WORD idx /* Index of directory table */
  884. )
  885. {
  886. DWORD clst;
  887. WORD ic;
  888. dj->index = idx;
  889. clst = dj->sclust;
  890. if (clst == 1 || clst >= dj->fs->n_fatent) /* Check start cluster range */
  891. return FR_INT_ERR;
  892. if (!clst && dj->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */
  893. clst = dj->fs->dirbase;
  894. if (clst == 0) { /* Static table (root-dir in FAT12/16) */
  895. dj->clust = clst;
  896. if (idx >= dj->fs->n_rootdir) /* Index is out of range */
  897. return FR_INT_ERR;
  898. dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / SZ_DIR); /* Sector# */
  899. }
  900. else { /* Dynamic table (sub-dirs or root-dir in FAT32) */
  901. ic = SS(dj->fs) / SZ_DIR * dj->fs->csize; /* Entries per cluster */
  902. while (idx >= ic) { /* Follow cluster chain */
  903. clst = get_fat(dj->fs, clst); /* Get next cluster */
  904. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  905. if (clst < 2 || clst >= dj->fs->n_fatent) /* Reached to end of table or int error */
  906. return FR_INT_ERR;
  907. idx -= ic;
  908. }
  909. dj->clust = clst;
  910. dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / SZ_DIR); /* Sector# */
  911. }
  912. dj->dir = dj->fs->win + (idx % (SS(dj->fs) / SZ_DIR)) * SZ_DIR; /* Ptr to the entry in the sector */
  913. return FR_OK; /* Seek succeeded */
  914. }
  915. /*-----------------------------------------------------------------------*/
  916. /* Directory handling - Move directory table index next */
  917. /*-----------------------------------------------------------------------*/
  918. static
  919. FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not stretch */
  920. DIR *dj, /* Pointer to directory object */
  921. int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
  922. )
  923. {
  924. DWORD clst;
  925. WORD i;
  926. stretch = stretch; /* To suppress warning on read-only cfg. */
  927. i = dj->index + 1;
  928. if (!i || !dj->sect) /* Report EOT when index has reached 65535 */
  929. return FR_NO_FILE;
  930. if (!(i % (SS(dj->fs) / SZ_DIR))) { /* Sector changed? */
  931. dj->sect++; /* Next sector */
  932. if (dj->clust == 0) { /* Static table */
  933. if (i >= dj->fs->n_rootdir) /* Report EOT when end of table */
  934. return FR_NO_FILE;
  935. }
  936. else { /* Dynamic table */
  937. if (((i / (SS(dj->fs) / SZ_DIR)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
  938. clst = get_fat(dj->fs, dj->clust); /* Get next cluster */
  939. if (clst <= 1) return FR_INT_ERR;
  940. if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  941. if (clst >= dj->fs->n_fatent) { /* When it reached end of dynamic table */
  942. #if !_FS_READONLY
  943. BYTE c;
  944. if (!stretch) return FR_NO_FILE; /* When do not stretch, report EOT */
  945. clst = create_chain(dj->fs, dj->clust); /* Stretch cluster chain */
  946. if (clst == 0) return FR_DENIED; /* No free cluster */
  947. if (clst == 1) return FR_INT_ERR;
  948. if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  949. /* Clean-up stretched table */
  950. if (move_window(dj->fs, 0)) return FR_DISK_ERR; /* Flush active window */
  951. mem_set(dj->fs->win, 0, SS(dj->fs)); /* Clear window buffer */
  952. dj->fs->winsect = clust2sect(dj->fs, clst); /* Cluster start sector */
  953. for (c = 0; c < dj->fs->csize; c++) { /* Fill the new cluster with 0 */
  954. dj->fs->wflag = 1;
  955. if (move_window(dj->fs, 0)) return FR_DISK_ERR;
  956. dj->fs->winsect++;
  957. }
  958. dj->fs->winsect -= c; /* Rewind window address */
  959. #else
  960. return FR_NO_FILE; /* Report EOT */
  961. #endif
  962. }
  963. dj->clust = clst; /* Initialize data for new cluster */
  964. dj->sect = clust2sect(dj->fs, clst);
  965. }
  966. }
  967. }
  968. dj->index = i;
  969. dj->dir = dj->fs->win + (i % (SS(dj->fs) / SZ_DIR)) * SZ_DIR;
  970. return FR_OK;
  971. }
  972. /*-----------------------------------------------------------------------*/
  973. /* Directory handling - Load/Store start cluster number */
  974. /*-----------------------------------------------------------------------*/
  975. static
  976. DWORD ld_clust (
  977. FATFS *fs, /* Pointer to the fs object */
  978. BYTE *dir /* Pointer to the directory entry */
  979. )
  980. {
  981. DWORD cl;
  982. cl = LD_WORD(dir+DIR_FstClusLO);
  983. if (fs->fs_type == FS_FAT32)
  984. cl |= (DWORD)LD_WORD(dir+DIR_FstClusHI) << 16;
  985. return cl;
  986. }
  987. #if !_FS_READONLY
  988. static
  989. void st_clust (
  990. BYTE *dir, /* Pointer to the directory entry */
  991. DWORD cl /* Value to be set */
  992. )
  993. {
  994. ST_WORD(dir+DIR_FstClusLO, cl);
  995. ST_WORD(dir+DIR_FstClusHI, cl >> 16);
  996. }
  997. #endif
  998. /*-----------------------------------------------------------------------*/
  999. /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */
  1000. /*-----------------------------------------------------------------------*/
  1001. #if _USE_LFN
  1002. static
  1003. const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN chars in the directory entry */
  1004. static
  1005. int cmp_lfn ( /* 1:Matched, 0:Not matched */
  1006. WCHAR *lfnbuf, /* Pointer to the LFN to be compared */
  1007. BYTE *dir /* Pointer to the directory entry containing a part of LFN */
  1008. )
  1009. {
  1010. UINT i, s;
  1011. WCHAR wc, uc;
  1012. i = ((dir[LDIR_Ord] & ~LLE) - 1) * 13; /* Get offset in the LFN buffer */
  1013. s = 0; wc = 1;
  1014. do {
  1015. uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */
  1016. if (wc) { /* Last char has not been processed */
  1017. wc = ff_wtoupper(uc); /* Convert it to upper case */
  1018. if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++])) /* Compare it */
  1019. return 0; /* Not matched */
  1020. } else {
  1021. if (uc != 0xFFFF) return 0; /* Check filler */
  1022. }
  1023. } while (++s < 13); /* Repeat until all chars in the entry are checked */
  1024. if ((dir[LDIR_Ord] & LLE) && wc && lfnbuf[i]) /* Last segment matched but different length */
  1025. return 0;
  1026. return 1; /* The part of LFN matched */
  1027. }
  1028. static
  1029. int pick_lfn ( /* 1:Succeeded, 0:Buffer overflow */
  1030. WCHAR *lfnbuf, /* Pointer to the Unicode-LFN buffer */
  1031. BYTE *dir /* Pointer to the directory entry */
  1032. )
  1033. {
  1034. UINT i, s;
  1035. WCHAR wc, uc;
  1036. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  1037. s = 0; wc = 1;
  1038. do {
  1039. uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */
  1040. if (wc) { /* Last char has not been processed */
  1041. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1042. lfnbuf[i++] = wc = uc; /* Store it */
  1043. } else {
  1044. if (uc != 0xFFFF) return 0; /* Check filler */
  1045. }
  1046. } while (++s < 13); /* Read all character in the entry */
  1047. if (dir[LDIR_Ord] & LLE) { /* Put terminator if it is the last LFN part */
  1048. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1049. lfnbuf[i] = 0;
  1050. }
  1051. return 1;
  1052. }
  1053. #if !_FS_READONLY
  1054. static
  1055. void fit_lfn (
  1056. const WCHAR *lfnbuf, /* Pointer to the LFN buffer */
  1057. BYTE *dir, /* Pointer to the directory entry */
  1058. BYTE ord, /* LFN order (1-20) */
  1059. BYTE sum /* SFN sum */
  1060. )
  1061. {
  1062. UINT i, s;
  1063. WCHAR wc;
  1064. dir[LDIR_Chksum] = sum; /* Set check sum */
  1065. dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
  1066. dir[LDIR_Type] = 0;
  1067. ST_WORD(dir+LDIR_FstClusLO, 0);
  1068. i = (ord - 1) * 13; /* Get offset in the LFN buffer */
  1069. s = wc = 0;
  1070. do {
  1071. if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective char */
  1072. ST_WORD(dir+LfnOfs[s], wc); /* Put it */
  1073. if (!wc) wc = 0xFFFF; /* Padding chars following last char */
  1074. } while (++s < 13);
  1075. if (wc == 0xFFFF || !lfnbuf[i]) ord |= LLE; /* Bottom LFN part is the start of LFN sequence */
  1076. dir[LDIR_Ord] = ord; /* Set the LFN order */
  1077. }
  1078. #endif
  1079. #endif
  1080. /*-----------------------------------------------------------------------*/
  1081. /* Create numbered name */
  1082. /*-----------------------------------------------------------------------*/
  1083. #if _USE_LFN
  1084. void gen_numname (
  1085. BYTE *dst, /* Pointer to generated SFN */
  1086. const BYTE *src, /* Pointer to source SFN to be modified */
  1087. const WCHAR *lfn, /* Pointer to LFN */
  1088. WORD seq /* Sequence number */
  1089. )
  1090. {
  1091. BYTE ns[8], c;
  1092. UINT i, j;
  1093. mem_cpy(dst, src, 11);
  1094. if (seq > 5) { /* On many collisions, generate a hash number instead of sequential number */
  1095. do seq = (seq >> 1) + (seq << 15) + (WORD)*lfn++; while (*lfn);
  1096. }
  1097. /* itoa (hexdecimal) */
  1098. i = 7;
  1099. do {
  1100. c = (seq % 16) + '0';
  1101. if (c > '9') c += 7;
  1102. ns[i--] = c;
  1103. seq /= 16;
  1104. } while (seq);
  1105. ns[i] = '~';
  1106. /* Append the number */
  1107. for (j = 0; j < i && dst[j] != ' '; j++) {
  1108. if (IsDBCS1(dst[j])) {
  1109. if (j == i - 1) break;
  1110. j++;
  1111. }
  1112. }
  1113. do {
  1114. dst[j++] = (i < 8) ? ns[i++] : ' ';
  1115. } while (j < 8);
  1116. }
  1117. #endif
  1118. /*-----------------------------------------------------------------------*/
  1119. /* Calculate sum of an SFN */
  1120. /*-----------------------------------------------------------------------*/
  1121. #if _USE_LFN
  1122. static
  1123. BYTE sum_sfn (
  1124. const BYTE *dir /* Ptr to directory entry */
  1125. )
  1126. {
  1127. BYTE sum = 0;
  1128. UINT n = 11;
  1129. do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
  1130. return sum;
  1131. }
  1132. #endif
  1133. /*-----------------------------------------------------------------------*/
  1134. /* Directory handling - Find an object in the directory */
  1135. /*-----------------------------------------------------------------------*/
  1136. static
  1137. FRESULT dir_find (
  1138. DIR *dj /* Pointer to the directory object linked to the file name */
  1139. )
  1140. {
  1141. FRESULT res;
  1142. BYTE c, *dir;
  1143. #if _USE_LFN
  1144. BYTE a, ord, sum;
  1145. #endif
  1146. res = dir_sdi(dj, 0); /* Rewind directory object */
  1147. if (res != FR_OK) return res;
  1148. #if _USE_LFN
  1149. ord = sum = 0xFF;
  1150. #endif
  1151. do {
  1152. res = move_window(dj->fs, dj->sect);
  1153. if (res != FR_OK) break;
  1154. dir = dj->dir; /* Ptr to the directory entry of current index */
  1155. c = dir[DIR_Name];
  1156. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  1157. #if _USE_LFN /* LFN configuration */
  1158. a = dir[DIR_Attr] & AM_MASK;
  1159. if (c == DDE || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  1160. ord = 0xFF;
  1161. } else {
  1162. if (a == AM_LFN) { /* An LFN entry is found */
  1163. if (dj->lfn) {
  1164. if (c & LLE) { /* Is it start of LFN sequence? */
  1165. sum = dir[LDIR_Chksum];
  1166. c &= ~LLE; ord = c; /* LFN start order */
  1167. dj->lfn_idx = dj->index;
  1168. }
  1169. /* Check validity of the LFN entry and compare it with given name */
  1170. ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
  1171. }
  1172. } else { /* An SFN entry is found */
  1173. if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */
  1174. ord = 0xFF; dj->lfn_idx = 0xFFFF; /* Reset LFN sequence */
  1175. if (!(dj->fn[NS] & NS_LOSS) && !mem_cmp(dir, dj->fn, 11)) break; /* SFN matched? */
  1176. }
  1177. }
  1178. #else /* Non LFN configuration */
  1179. if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */
  1180. break;
  1181. #endif
  1182. res = dir_next(dj, 0); /* Next entry */
  1183. } while (res == FR_OK);
  1184. return res;
  1185. }
  1186. /*-----------------------------------------------------------------------*/
  1187. /* Read an object from the directory */
  1188. /*-----------------------------------------------------------------------*/
  1189. #if _FS_MINIMIZE <= 1
  1190. static
  1191. FRESULT dir_read (
  1192. DIR *dj /* Pointer to the directory object that pointing the entry to be read */
  1193. )
  1194. {
  1195. FRESULT res;
  1196. BYTE c, *dir;
  1197. #if _USE_LFN
  1198. BYTE a, ord = 0xFF, sum = 0xFF;
  1199. #endif
  1200. res = FR_NO_FILE;
  1201. while (dj->sect) {
  1202. res = move_window(dj->fs, dj->sect);
  1203. if (res != FR_OK) break;
  1204. dir = dj->dir; /* Ptr to the directory entry of current index */
  1205. c = dir[DIR_Name];
  1206. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  1207. #if _USE_LFN /* LFN configuration */
  1208. a = dir[DIR_Attr] & AM_MASK;
  1209. if (c == DDE || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  1210. ord = 0xFF;
  1211. } else {
  1212. if (a == AM_LFN) { /* An LFN entry is found */
  1213. if (c & LLE) { /* Is it start of LFN sequence? */
  1214. sum = dir[LDIR_Chksum];
  1215. c &= ~LLE; ord = c;
  1216. dj->lfn_idx = dj->index;
  1217. }
  1218. /* Check LFN validity and capture it */
  1219. ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
  1220. } else { /* An SFN entry is found */
  1221. if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */
  1222. dj->lfn_idx = 0xFFFF; /* It has no LFN. */
  1223. break;
  1224. }
  1225. }
  1226. #else /* Non LFN configuration */
  1227. if (c != DDE && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */
  1228. break;
  1229. #endif
  1230. res = dir_next(dj, 0); /* Next entry */
  1231. if (res != FR_OK) break;
  1232. }
  1233. if (res != FR_OK) dj->sect = 0;
  1234. return res;
  1235. }
  1236. #endif
  1237. /*-----------------------------------------------------------------------*/
  1238. /* Register an object to the directory */
  1239. /*-----------------------------------------------------------------------*/
  1240. #if !_FS_READONLY
  1241. static
  1242. FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
  1243. DIR *dj /* Target directory with object name to be created */
  1244. )
  1245. {
  1246. FRESULT res;
  1247. BYTE c, *dir;
  1248. #if _USE_LFN /* LFN configuration */
  1249. WORD n, ne, is;
  1250. BYTE sn[12], *fn, sum;
  1251. WCHAR *lfn;
  1252. fn = dj->fn; lfn = dj->lfn;
  1253. mem_cpy(sn, fn, 12);
  1254. if (_FS_RPATH && (sn[NS] & NS_DOT)) /* Cannot create dot entry */
  1255. return FR_INVALID_NAME;
  1256. if (sn[NS] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
  1257. fn[NS] = 0; dj->lfn = 0; /* Find only SFN */
  1258. for (n = 1; n < 100; n++) {
  1259. gen_numname(fn, sn, lfn, n); /* Generate a numbered name */
  1260. res = dir_find(dj); /* Check if the name collides with existing SFN */
  1261. if (res != FR_OK) break;
  1262. }
  1263. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  1264. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  1265. fn[NS] = sn[NS]; dj->lfn = lfn;
  1266. }
  1267. if (sn[NS] & NS_LFN) { /* When LFN is to be created, reserve an SFN + LFN entries. */
  1268. for (ne = 0; lfn[ne]; ne++) ;
  1269. ne = (ne + 25) / 13;
  1270. } else { /* Otherwise reserve only an SFN entry. */
  1271. ne = 1;
  1272. }
  1273. /* Reserve contiguous entries */
  1274. res = dir_sdi(dj, 0);
  1275. if (res != FR_OK) return res;
  1276. n = is = 0;
  1277. do {
  1278. res = move_window(dj->fs, dj->sect);
  1279. if (res != FR_OK) break;
  1280. c = *dj->dir; /* Check the entry status */
  1281. if (c == DDE || c == 0) { /* Is it a blank entry? */
  1282. if (n == 0) is = dj->index; /* First index of the contiguous entry */
  1283. if (++n == ne) break; /* A contiguous entry that required count is found */
  1284. } else {
  1285. n = 0; /* Not a blank entry. Restart to search */
  1286. }
  1287. res = dir_next(dj, 1); /* Next entry with table stretch */
  1288. } while (res == FR_OK);
  1289. if (res == FR_OK && ne > 1) { /* Initialize LFN entry if needed */
  1290. res = dir_sdi(dj, is);
  1291. if (res == FR_OK) {
  1292. sum = sum_sfn(dj->fn); /* Sum of the SFN tied to the LFN */
  1293. ne--;
  1294. do { /* Store LFN entries in bottom first */
  1295. res = move_window(dj->fs, dj->sect);
  1296. if (res != FR_OK) break;
  1297. fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum);
  1298. dj->fs->wflag = 1;
  1299. res = dir_next(dj, 0); /* Next entry */
  1300. } while (res == FR_OK && --ne);
  1301. }
  1302. }
  1303. #else /* Non LFN configuration */
  1304. res = dir_sdi(dj, 0);
  1305. if (res == FR_OK) {
  1306. do { /* Find a blank entry for the SFN */
  1307. res = move_window(dj->fs, dj->sect);
  1308. if (res != FR_OK) break;
  1309. c = *dj->dir;
  1310. if (c == DDE || c == 0) break; /* Is it a blank entry? */
  1311. res = dir_next(dj, 1); /* Next entry with table stretch */
  1312. } while (res == FR_OK);
  1313. }
  1314. #endif
  1315. if (res == FR_OK) { /* Initialize the SFN entry */
  1316. res = move_window(dj->fs, dj->sect);
  1317. if (res == FR_OK) {
  1318. dir = dj->dir;
  1319. mem_set(dir, 0, SZ_DIR); /* Clean the entry */
  1320. mem_cpy(dir, dj->fn, 11); /* Put SFN */
  1321. #if _USE_LFN
  1322. dir[DIR_NTres] = *(dj->fn+NS) & (NS_BODY | NS_EXT); /* Put NT flag */
  1323. #endif
  1324. dj->fs->wflag = 1;
  1325. }
  1326. }
  1327. return res;
  1328. }
  1329. #endif /* !_FS_READONLY */
  1330. /*-----------------------------------------------------------------------*/
  1331. /* Remove an object from the directory */
  1332. /*-----------------------------------------------------------------------*/
  1333. #if !_FS_READONLY && !_FS_MINIMIZE
  1334. static
  1335. FRESULT dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */
  1336. DIR *dj /* Directory object pointing the entry to be removed */
  1337. )
  1338. {
  1339. FRESULT res;
  1340. #if _USE_LFN /* LFN configuration */
  1341. WORD i;
  1342. i = dj->index; /* SFN index */
  1343. res = dir_sdi(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx)); /* Goto the SFN or top of the LFN entries */
  1344. if (res == FR_OK) {
  1345. do {
  1346. res = move_window(dj->fs, dj->sect);
  1347. if (res != FR_OK) break;
  1348. *dj->dir = DDE; /* Mark the entry "deleted" */
  1349. dj->fs->wflag = 1;
  1350. if (dj->index >= i) break; /* When reached SFN, all entries of the object has been deleted. */
  1351. res = dir_next(dj, 0); /* Next entry */
  1352. } while (res == FR_OK);
  1353. if (res == FR_NO_FILE) res = FR_INT_ERR;
  1354. }
  1355. #else /* Non LFN configuration */
  1356. res = dir_sdi(dj, dj->index);
  1357. if (res == FR_OK) {
  1358. res = move_window(dj->fs, dj->sect);
  1359. if (res == FR_OK) {
  1360. *dj->dir = DDE; /* Mark the entry "deleted" */
  1361. dj->fs->wflag = 1;
  1362. }
  1363. }
  1364. #endif
  1365. return res;
  1366. }
  1367. #endif /* !_FS_READONLY */
  1368. /*-----------------------------------------------------------------------*/
  1369. /* Pick a segment and create the object name in directory form */
  1370. /*-----------------------------------------------------------------------*/
  1371. static
  1372. FRESULT create_name (
  1373. DIR *dj, /* Pointer to the directory object */
  1374. const TCHAR **path /* Pointer to pointer to the segment in the path string */
  1375. )
  1376. {
  1377. #ifdef _EXCVT
  1378. static const BYTE excvt[] = _EXCVT; /* Upper conversion table for extended chars */
  1379. #endif
  1380. #if _USE_LFN /* LFN configuration */
  1381. BYTE b, cf;
  1382. WCHAR w, *lfn;
  1383. UINT i, ni, si, di;
  1384. const TCHAR *p;
  1385. /* Create LFN in Unicode */
  1386. for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */
  1387. lfn = dj->lfn;
  1388. si = di = 0;
  1389. for (;;) {
  1390. w = p[si++]; /* Get a character */
  1391. if (w < ' ' || w == '/' || w == '\\') break; /* Break on end of segment */
  1392. if (di >= _MAX_LFN) /* Reject too long name */
  1393. return FR_INVALID_NAME;
  1394. #if !_LFN_UNICODE
  1395. w &= 0xFF;
  1396. if (IsDBCS1(w)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  1397. b = (BYTE)p[si++]; /* Get 2nd byte */
  1398. if (!IsDBCS2(b))
  1399. return FR_INVALID_NAME; /* Reject invalid sequence */
  1400. w = (w << 8) + b; /* Create a DBC */
  1401. }
  1402. w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */
  1403. if (!w) return FR_INVALID_NAME; /* Reject invalid code */
  1404. #endif
  1405. if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal chars for LFN */
  1406. return FR_INVALID_NAME;
  1407. lfn[di++] = w; /* Store the Unicode char */
  1408. }
  1409. *path = &p[si]; /* Return pointer to the next segment */
  1410. cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */
  1411. #if _FS_RPATH
  1412. if ((di == 1 && lfn[di-1] == '.') || /* Is this a dot entry? */
  1413. (di == 2 && lfn[di-1] == '.' && lfn[di-2] == '.')) {
  1414. lfn[di] = 0;
  1415. for (i = 0; i < 11; i++)
  1416. dj->fn[i] = (i < di) ? '.' : ' ';
  1417. dj->fn[i] = cf | NS_DOT; /* This is a dot entry */
  1418. return FR_OK;
  1419. }
  1420. #endif
  1421. while (di) { /* Strip trailing spaces and dots */
  1422. w = lfn[di-1];
  1423. if (w != ' ' && w != '.') break;
  1424. di--;
  1425. }
  1426. if (!di) return FR_INVALID_NAME; /* Reject nul string */
  1427. lfn[di] = 0; /* LFN is created */
  1428. /* Create SFN in directory form */
  1429. mem_set(dj->fn, ' ', 11);
  1430. for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
  1431. if (si) cf |= NS_LOSS | NS_LFN;
  1432. while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
  1433. b = i = 0; ni = 8;
  1434. for (;;) {
  1435. w = lfn[si++]; /* Get an LFN char */
  1436. if (!w) break; /* Break on end of the LFN */
  1437. if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
  1438. cf |= NS_LOSS | NS_LFN; continue;
  1439. }
  1440. if (i >= ni || si == di) { /* Extension or end of SFN */
  1441. if (ni == 11) { /* Long extension */
  1442. cf |= NS_LOSS | NS_LFN; break;
  1443. }
  1444. if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */
  1445. if (si > di) break; /* No extension */
  1446. si = di; i = 8; ni = 11; /* Enter extension section */
  1447. b <<= 2; continue;
  1448. }
  1449. if (w >= 0x80) { /* Non ASCII char */
  1450. #ifdef _EXCVT
  1451. w = ff_convert(w, 0); /* Unicode -> OEM code */
  1452. if (w) w = excvt[w - 0x80]; /* Convert extended char to upper (SBCS) */
  1453. #else
  1454. w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
  1455. #endif
  1456. cf |= NS_LFN; /* Force create LFN entry */
  1457. }
  1458. if (_DF1S && w >= 0x100) { /* Double byte char (always false on SBCS cfg) */
  1459. if (i >= ni - 1) {
  1460. cf |= NS_LOSS | NS_LFN; i = ni; continue;
  1461. }
  1462. dj->fn[i++] = (BYTE)(w >> 8);
  1463. } else { /* Single byte char */
  1464. if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal chars for SFN */
  1465. w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  1466. } else {
  1467. if (IsUpper(w)) { /* ASCII large capital */
  1468. b |= 2;
  1469. } else {
  1470. if (IsLower(w)) { /* ASCII small capital */
  1471. b |= 1; w -= 0x20;
  1472. }
  1473. }
  1474. }
  1475. }
  1476. dj->fn[i++] = (BYTE)w;
  1477. }
  1478. if (dj->fn[0] == DDE) dj->fn[0] = NDDE; /* If the first char collides with deleted mark, replace it with 0x05 */
  1479. if (ni == 8) b <<= 2;
  1480. if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) /* Create LFN entry when there are composite capitals */
  1481. cf |= NS_LFN;
  1482. if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended char, NT flags are created */
  1483. if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */
  1484. if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */
  1485. }
  1486. dj->fn[NS] = cf; /* SFN is created */
  1487. return FR_OK;
  1488. #else /* Non-LFN configuration */
  1489. BYTE b, c, d, *sfn;
  1490. UINT ni, si, i;
  1491. const char *p;
  1492. /* Create file name in directory form */
  1493. for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */
  1494. sfn = dj->fn;
  1495. mem_set(sfn, ' ', 11);
  1496. si = i = b = 0; ni = 8;
  1497. #if _FS_RPATH
  1498. if (p[si] == '.') { /* Is this a dot entry? */
  1499. for (;;) {
  1500. c = (BYTE)p[si++];
  1501. if (c != '.' || si >= 3) break;
  1502. sfn[i++] = c;
  1503. }
  1504. if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
  1505. *path = &p[si]; /* Return pointer to the next segment */
  1506. sfn[NS] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of path */
  1507. return FR_OK;
  1508. }
  1509. #endif
  1510. for (;;) {
  1511. c = (BYTE)p[si++];
  1512. if (c <= ' ' || c == '/' || c == '\\') break; /* Break on end of segment */
  1513. if (c == '.' || i >= ni) {
  1514. if (ni != 8 || c != '.') return FR_INVALID_NAME;
  1515. i = 8; ni = 11;
  1516. b <<= 2; continue;
  1517. }
  1518. if (c >= 0x80) { /* Extended char? */
  1519. b |= 3; /* Eliminate NT flag */
  1520. #ifdef _EXCVT
  1521. c = excvt[c - 0x80]; /* Upper conversion (SBCS) */
  1522. #else
  1523. #if !_DF1S /* ASCII only cfg */
  1524. return FR_INVALID_NAME;
  1525. #endif
  1526. #endif
  1527. }
  1528. if (IsDBCS1(c)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  1529. d = (BYTE)p[si++]; /* Get 2nd byte */
  1530. if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */
  1531. return FR_INVALID_NAME;
  1532. sfn[i++] = c;
  1533. sfn[i++] = d;
  1534. } else { /* Single byte code */
  1535. if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) /* Reject illegal chrs for SFN */
  1536. return FR_INVALID_NAME;
  1537. if (IsUpper(c)) { /* ASCII large capital? */
  1538. b |= 2;
  1539. } else {
  1540. if (IsLower(c)) { /* ASCII small capital? */
  1541. b |= 1; c -= 0x20;
  1542. }
  1543. }
  1544. sfn[i++] = c;
  1545. }
  1546. }
  1547. *path = &p[si]; /* Return pointer to the next segment */
  1548. c = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */
  1549. if (!i) return FR_INVALID_NAME; /* Reject nul string */
  1550. if (sfn[0] == DDE) sfn[0] = NDDE; /* When first char collides with DDE, replace it with 0x05 */
  1551. if (ni == 8) b <<= 2;
  1552. if ((b & 0x03) == 0x01) c |= NS_EXT; /* NT flag (Name extension has only small capital) */
  1553. if ((b & 0x0C) == 0x04) c |= NS_BODY; /* NT flag (Name body has only small capital) */
  1554. sfn[NS] = c; /* Store NT flag, File name is created */
  1555. return FR_OK;
  1556. #endif
  1557. }
  1558. /*-----------------------------------------------------------------------*/
  1559. /* Get file information from directory entry */
  1560. /*-----------------------------------------------------------------------*/
  1561. #if _FS_MINIMIZE <= 1
  1562. static
  1563. void get_fileinfo ( /* No return code */
  1564. DIR *dj, /* Pointer to the directory object */
  1565. FILINFO *fno /* Pointer to the file information to be filled */
  1566. )
  1567. {
  1568. UINT i;
  1569. BYTE nt, *dir;
  1570. TCHAR *p, c;
  1571. p = fno->fname;
  1572. if (dj->sect) {
  1573. dir = dj->dir;
  1574. nt = dir[DIR_NTres]; /* NT flag */
  1575. for (i = 0; i < 8; i++) { /* Copy name body */
  1576. c = dir[i];
  1577. if (c == ' ') break;
  1578. if (c == NDDE) c = (TCHAR)DDE;
  1579. if (_USE_LFN && (nt & NS_BODY) && IsUpper(c)) c += 0x20;
  1580. #if _LFN_UNICODE
  1581. if (IsDBCS1(c) && i < 7 && IsDBCS2(dir[i+1]))
  1582. c = (c << 8) | dir[++i];
  1583. c = ff_convert(c, 1);
  1584. if (!c) c = '?';
  1585. #endif
  1586. *p++ = c;
  1587. }
  1588. if (dir[8] != ' ') { /* Copy name extension */
  1589. *p++ = '.';
  1590. for (i = 8; i < 11; i++) {
  1591. c = dir[i];
  1592. if (c == ' ') break;
  1593. if (_USE_LFN && (nt & NS_EXT) && IsUpper(c)) c += 0x20;
  1594. #if _LFN_UNICODE
  1595. if (IsDBCS1(c) && i < 10 && IsDBCS2(dir[i+1]))
  1596. c = (c << 8) | dir[++i];
  1597. c = ff_convert(c, 1);
  1598. if (!c) c = '?';
  1599. #endif
  1600. *p++ = c;
  1601. }
  1602. }
  1603. fno->fattrib = dir[DIR_Attr]; /* Attribute */
  1604. fno->fsize = LD_DWORD(dir+DIR_FileSize); /* Size */
  1605. fno->fdate = LD_WORD(dir+DIR_WrtDate); /* Date */
  1606. fno->ftime = LD_WORD(dir+DIR_WrtTime); /* Time */
  1607. }
  1608. *p = 0; /* Terminate SFN str by a \0 */
  1609. #if _USE_LFN
  1610. if (fno->lfname && fno->lfsize) {
  1611. TCHAR *tp = fno->lfname;
  1612. WCHAR w, *lfn;
  1613. i = 0;
  1614. if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */
  1615. lfn = dj->lfn;
  1616. while ((w = *lfn++) != 0) { /* Get an LFN char */
  1617. #if !_LFN_UNICODE
  1618. w = ff_convert(w, 0); /* Unicode -> OEM conversion */
  1619. if (!w) { i = 0; break; } /* Could not convert, no LFN */
  1620. if (_DF1S && w >= 0x100) /* Put 1st byte if it is a DBC (always false on SBCS cfg) */
  1621. tp[i++] = (TCHAR)(w >> 8);
  1622. #endif
  1623. if (i >= fno->lfsize - 1) { i = 0; break; } /* Buffer overflow, no LFN */
  1624. tp[i++] = (TCHAR)w;
  1625. }
  1626. }
  1627. tp[i] = 0; /* Terminate the LFN str by a \0 */
  1628. }
  1629. #endif
  1630. }
  1631. #endif /* _FS_MINIMIZE <= 1 */
  1632. /*-----------------------------------------------------------------------*/
  1633. /* Follow a file path */
  1634. /*-----------------------------------------------------------------------*/
  1635. static
  1636. FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  1637. DIR *dj, /* Directory object to return last directory and found object */
  1638. const TCHAR *path /* Full-path string to find a file or directory */
  1639. )
  1640. {
  1641. FRESULT res;
  1642. BYTE *dir, ns;
  1643. #if _FS_RPATH
  1644. if (*path == '/' || *path == '\\') { /* There is a heading separator */
  1645. path++; dj->sclust = 0; /* Strip it and start from the root dir */
  1646. } else { /* No heading separator */
  1647. dj->sclust = dj->fs->cdir; /* Start from the current dir */
  1648. }
  1649. #else
  1650. if (*path == '/' || *path == '\\') /* Strip heading separator if exist */
  1651. path++;
  1652. dj->sclust = 0; /* Start from the root dir */
  1653. #endif
  1654. if ((UINT)*path < ' ') { /* Nul path means the start directory itself */
  1655. res = dir_sdi(dj, 0);
  1656. dj->dir = 0;
  1657. } else { /* Follow path */
  1658. for (;;) {
  1659. res = create_name(dj, &path); /* Get a segment */
  1660. if (res != FR_OK) break;
  1661. res = dir_find(dj); /* Find it */
  1662. ns = *(dj->fn+NS);
  1663. if (res != FR_OK) { /* Failed to find the object */
  1664. if (res != FR_NO_FILE) break; /* Abort if any hard error occurred */
  1665. /* Object not found */
  1666. if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exit */
  1667. dj->sclust = 0; dj->dir = 0; /* It is the root dir */
  1668. res = FR_OK;
  1669. if (!(ns & NS_LAST)) continue;
  1670. } else { /* Could not find the object */
  1671. if (!(ns & NS_LAST)) res = FR_NO_PATH;
  1672. }
  1673. break;
  1674. }
  1675. if (ns & NS_LAST) break; /* Last segment match. Function completed. */
  1676. dir = dj->dir; /* There is next segment. Follow the sub directory */
  1677. if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */
  1678. res = FR_NO_PATH; break;
  1679. }
  1680. dj->sclust = ld_clust(dj->fs, dir);
  1681. }
  1682. }
  1683. return res;
  1684. }
  1685. /*-----------------------------------------------------------------------*/
  1686. /* Load a sector and check if it is an FAT Volume Boot Record */
  1687. /*-----------------------------------------------------------------------*/
  1688. static
  1689. BYTE check_fs ( /* 0:FAT-VBR, 1:Any BR but not FAT, 2:Not a BR, 3:Disk error */
  1690. FATFS *fs, /* File system object */
  1691. DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */
  1692. )
  1693. {
  1694. if (disk_read(fs->drv, fs->win, sect, 1) != RES_OK) /* Load boot record */
  1695. return 3;
  1696. if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */
  1697. return 2;
  1698. if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
  1699. return 0;
  1700. if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146)
  1701. return 0;
  1702. return 1;
  1703. }
  1704. /*-----------------------------------------------------------------------*/
  1705. /* Check if the file system object is valid or not */
  1706. /*-----------------------------------------------------------------------*/
  1707. static
  1708. FRESULT chk_mounted ( /* FR_OK(0): successful, !=0: any error occurred */
  1709. const TCHAR **path, /* Pointer to pointer to the path name (drive number) */
  1710. FATFS **rfs, /* Pointer to pointer to the found file system object */
  1711. BYTE wmode /* !=0: Check write protection for write access */
  1712. )
  1713. {
  1714. BYTE fmt, b, pi, *tbl;
  1715. UINT vol;
  1716. DSTATUS stat;
  1717. DWORD bsect, fasize, tsect, sysect, nclst, szbfat;
  1718. WORD nrsv;
  1719. const TCHAR *p = *path;
  1720. FATFS *fs;
  1721. /* Get logical drive number from the path name */
  1722. vol = p[0] - '0'; /* Is there a drive number? */
  1723. if (vol <= 9 && p[1] == ':') { /* Found a drive number, get and strip it */
  1724. p += 2; *path = p; /* Return pointer to the path name */
  1725. } else { /* No drive number is given */
  1726. #if _FS_RPATH
  1727. vol = CurrVol; /* Use current drive */
  1728. #else
  1729. vol = 0; /* Use drive 0 */
  1730. #endif
  1731. }
  1732. /* Check if the file system object is valid or not */
  1733. *rfs = 0;
  1734. if (vol >= _VOLUMES) /* Is the drive number valid? */
  1735. return FR_INVALID_DRIVE;
  1736. fs = FatFs[vol]; /* Get corresponding file system object */
  1737. if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */
  1738. ENTER_FF(fs); /* Lock file system */
  1739. *rfs = fs; /* Return pointer to the corresponding file system object */
  1740. if (fs->fs_type) { /* If the volume has been mounted */
  1741. stat = disk_status(fs->drv);
  1742. if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized (has not been changed), */
  1743. if (!_FS_READONLY && wmode && (stat & STA_PROTECT)) /* Check write protection if needed */
  1744. return FR_WRITE_PROTECTED;
  1745. return FR_OK; /* The file system object is valid */
  1746. }
  1747. }
  1748. /* The file system object is not valid. */
  1749. /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
  1750. fs->fs_type = 0; /* Clear the file system object */
  1751. fs->drv = LD2PD(vol); /* Bind the logical drive and a physical drive */
  1752. stat = disk_initialize(fs->drv); /* Initialize the physical drive */
  1753. if (stat & STA_NOINIT) /* Check if the initialization succeeded */
  1754. return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
  1755. if (!_FS_READONLY && wmode && (stat & STA_PROTECT)) /* Check disk write protection if needed */
  1756. return FR_WRITE_PROTECTED;
  1757. #if _MAX_SS != 512 /* Get disk sector size (variable sector size cfg only) */
  1758. if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &fs->ssize) != RES_OK)
  1759. return FR_DISK_ERR;
  1760. #endif
  1761. /* Search FAT partition on the drive. Supports only generic partitions, FDISK and SFD. */
  1762. fmt = check_fs(fs, bsect = 0); /* Load sector 0 and check if it is an FAT-VBR (in SFD) */
  1763. if (LD2PT(vol) && !fmt) fmt = 1; /* Force non-SFD if the volume is forced partition */
  1764. if (fmt == 1) { /* Not an FAT-VBR, the physical drive can be partitioned */
  1765. /* Check the partition listed in the partition table */
  1766. pi = LD2PT(vol);
  1767. if (pi) pi--;
  1768. tbl = &fs->win[MBR_Table + pi * SZ_PTE];/* Partition table */
  1769. if (tbl[4]) { /* Is the partition existing? */
  1770. bsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */
  1771. fmt = check_fs(fs, bsect); /* Check the partition */
  1772. }
  1773. }
  1774. if (fmt == 3) return FR_DISK_ERR;
  1775. if (fmt) return FR_NO_FILESYSTEM; /* No FAT volume is found */
  1776. /* An FAT volume is found. Following code initializes the file system object */
  1777. if (LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs)) /* (BPB_BytsPerSec must be equal to the physical sector size) */
  1778. return FR_NO_FILESYSTEM;
  1779. fasize = LD_WORD(fs->win+BPB_FATSz16); /* Number of sectors per FAT */
  1780. if (!fasize) fasize = LD_DWORD(fs->win+BPB_FATSz32);
  1781. fs->fsize = fasize;
  1782. fs->n_fats = b = fs->win[BPB_NumFATs]; /* Number of FAT copies */
  1783. if (b != 1 && b != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
  1784. fasize *= b; /* Number of sectors for FAT area */
  1785. fs->csize = b = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */
  1786. if (!b || (b & (b - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
  1787. fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt); /* Number of root directory entries */
  1788. if (fs->n_rootdir % (SS(fs) / SZ_DIR)) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be sector aligned) */
  1789. tsect = LD_WORD(fs->win+BPB_TotSec16); /* Number of sectors on the volume */
  1790. if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32);
  1791. nrsv = LD_WORD(fs->win+BPB_RsvdSecCnt); /* Number of reserved sectors */
  1792. if (!nrsv) return FR_NO_FILESYSTEM; /* (BPB_RsvdSecCnt must not be 0) */
  1793. /* Determine the FAT sub type */
  1794. sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZ_DIR); /* RSV+FAT+DIR */
  1795. if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  1796. nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
  1797. if (!nclst) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  1798. fmt = FS_FAT12;
  1799. if (nclst >= MIN_FAT16) fmt = FS_FAT16;
  1800. if (nclst >= MIN_FAT32) fmt = FS_FAT32;
  1801. /* Boundaries and Limits */
  1802. fs->n_fatent = nclst + 2; /* Number of FAT entries */
  1803. fs->database = bsect + sysect; /* Data start sector */
  1804. fs->fatbase = bsect + nrsv; /* FAT start sector */
  1805. if (fmt == FS_FAT32) {
  1806. if (fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
  1807. fs->dirbase = LD_DWORD(fs->win+BPB_RootClus); /* Root directory start cluster */
  1808. szbfat = fs->n_fatent * 4; /* (Required FAT size) */
  1809. } else {
  1810. if (!fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must not be 0) */
  1811. fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
  1812. szbfat = (fmt == FS_FAT16) ? /* (Required FAT size) */
  1813. fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  1814. }
  1815. if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) /* (BPB_FATSz must not be less than required) */
  1816. return FR_NO_FILESYSTEM;
  1817. #if !_FS_READONLY
  1818. /* Initialize cluster allocation information */
  1819. fs->free_clust = 0xFFFFFFFF;
  1820. fs->last_clust = 0;
  1821. /* Get fsinfo if available */
  1822. if (fmt == FS_FAT32) {
  1823. fs->fsi_flag = 0;
  1824. fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo);
  1825. if (disk_read(fs->drv, fs->win, fs->fsi_sector, 1) == RES_OK &&
  1826. LD_WORD(fs->win+BS_55AA) == 0xAA55 &&
  1827. LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 &&
  1828. LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) {
  1829. fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free);
  1830. fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count);
  1831. }
  1832. }
  1833. #endif
  1834. fs->fs_type = fmt; /* FAT sub-type */
  1835. fs->id = ++Fsid; /* File system mount ID */
  1836. fs->winsect = 0; /* Invalidate sector cache */
  1837. fs->wflag = 0;
  1838. #if _FS_RPATH
  1839. fs->cdir = 0; /* Current directory (root dir) */
  1840. #endif
  1841. #if _FS_LOCK /* Clear file lock semaphores */
  1842. clear_lock(fs);
  1843. #endif
  1844. return FR_OK;
  1845. }
  1846. /*-----------------------------------------------------------------------*/
  1847. /* Check if the file/dir object is valid or not */
  1848. /*-----------------------------------------------------------------------*/
  1849. static
  1850. FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
  1851. void* obj /* Pointer to the object FIL/DIR to check validity */
  1852. )
  1853. {
  1854. FIL *fil;
  1855. fil = (FIL*)obj; /* Assuming offset of fs and id in the FIL/DIR is identical */
  1856. if (!fil->fs || !fil->fs->fs_type || fil->fs->id != fil->id)
  1857. return FR_INVALID_OBJECT;
  1858. ENTER_FF(fil->fs); /* Lock file system */
  1859. if (disk_status(fil->fs->drv) & STA_NOINIT)
  1860. return FR_NOT_READY;
  1861. return FR_OK;
  1862. }
  1863. /*--------------------------------------------------------------------------
  1864. Public Functions
  1865. --------------------------------------------------------------------------*/
  1866. /*-----------------------------------------------------------------------*/
  1867. /* Mount/Unmount a Logical Drive */
  1868. /*-----------------------------------------------------------------------*/
  1869. FRESULT f_mount (
  1870. BYTE vol, /* Logical drive number to be mounted/unmounted */
  1871. FATFS *fs /* Pointer to new file system object (NULL for unmount)*/
  1872. )
  1873. {
  1874. FATFS *rfs;
  1875. if (vol >= _VOLUMES) /* Check if the drive number is valid */
  1876. return FR_INVALID_DRIVE;
  1877. rfs = FatFs[vol]; /* Get current fs object */
  1878. if (rfs) {
  1879. #if _FS_LOCK
  1880. clear_lock(rfs);
  1881. #endif
  1882. #if _FS_REENTRANT /* Discard sync object of the current volume */
  1883. if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR;
  1884. #endif
  1885. rfs->fs_type = 0; /* Clear old fs object */
  1886. }
  1887. if (fs) {
  1888. fs->fs_type = 0; /* Clear new fs object */
  1889. #if _FS_REENTRANT /* Create sync object for the new volume */
  1890. if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;
  1891. #endif
  1892. }
  1893. FatFs[vol] = fs; /* Register new fs object */
  1894. return FR_OK;
  1895. }
  1896. /*-----------------------------------------------------------------------*/
  1897. /* Open or Create a File */
  1898. /*-----------------------------------------------------------------------*/
  1899. FRESULT f_open (
  1900. FIL *fp, /* Pointer to the blank file object */
  1901. const TCHAR *path, /* Pointer to the file name */
  1902. BYTE mode /* Access mode and file open mode flags */
  1903. )
  1904. {
  1905. FRESULT res;
  1906. DIR dj;
  1907. BYTE *dir;
  1908. DEF_NAMEBUF;
  1909. if (!fp) return FR_INVALID_OBJECT;
  1910. fp->fs = 0; /* Clear file object */
  1911. #if !_FS_READONLY
  1912. mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW;
  1913. res = chk_mounted(&path, &dj.fs, (BYTE)(mode & ~FA_READ));
  1914. #else
  1915. mode &= FA_READ;
  1916. res = chk_mounted(&path, &dj.fs, 0);
  1917. #endif
  1918. if (res == FR_OK) {
  1919. INIT_BUF(dj);
  1920. res = follow_path(&dj, path); /* Follow the file path */
  1921. dir = dj.dir;
  1922. #if !_FS_READONLY /* R/W configuration */
  1923. if (res == FR_OK) {
  1924. if (!dir) /* Current dir itself */
  1925. res = FR_INVALID_NAME;
  1926. #if _FS_LOCK
  1927. else
  1928. res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  1929. #endif
  1930. }
  1931. /* Create or Open a file */
  1932. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  1933. DWORD dw, cl;
  1934. if (res != FR_OK) { /* No file, create new */
  1935. if (res == FR_NO_FILE) /* There is no file to open, create a new entry */
  1936. #if _FS_LOCK
  1937. res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
  1938. #else
  1939. res = dir_register(&dj);
  1940. #endif
  1941. mode |= FA_CREATE_ALWAYS; /* File is created */
  1942. dir = dj.dir; /* New entry */
  1943. }
  1944. else { /* Any object is already existing */
  1945. if (dir[DIR_Attr] & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
  1946. res = FR_DENIED;
  1947. } else {
  1948. if (mode & FA_CREATE_NEW) /* Cannot create as new file */
  1949. res = FR_EXIST;
  1950. }
  1951. }
  1952. if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */
  1953. dw = get_fattime(); /* Created time */
  1954. ST_DWORD(dir+DIR_CrtTime, dw);
  1955. dir[DIR_Attr] = 0; /* Reset attribute */
  1956. ST_DWORD(dir+DIR_FileSize, 0); /* size = 0 */
  1957. cl = ld_clust(dj.fs, dir); /* Get start cluster */
  1958. st_clust(dir, 0); /* cluster = 0 */
  1959. dj.fs->wflag = 1;
  1960. if (cl) { /* Remove the cluster chain if exist */
  1961. dw = dj.fs->winsect;
  1962. res = remove_chain(dj.fs, cl);
  1963. if (res == FR_OK) {
  1964. dj.fs->last_clust = cl - 1; /* Reuse the cluster hole */
  1965. res = move_window(dj.fs, dw);
  1966. }
  1967. }
  1968. }
  1969. }
  1970. else { /* Open an existing file */
  1971. if (res == FR_OK) { /* Follow succeeded */
  1972. if (dir[DIR_Attr] & AM_DIR) { /* It is a directory */
  1973. res = FR_NO_FILE;
  1974. } else {
  1975. if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
  1976. res = FR_DENIED;
  1977. }
  1978. }
  1979. }
  1980. if (res == FR_OK) {
  1981. if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */
  1982. mode |= FA__WRITTEN;
  1983. fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */
  1984. fp->dir_ptr = dir;
  1985. #if _FS_LOCK
  1986. fp->lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  1987. if (!fp->lockid) res = FR_INT_ERR;
  1988. #endif
  1989. }
  1990. #else /* R/O configuration */
  1991. if (res == FR_OK) { /* Follow succeeded */
  1992. dir = dj.dir;
  1993. if (!dir) { /* Current dir itself */
  1994. res = FR_INVALID_NAME;
  1995. } else {
  1996. if (dir[DIR_Attr] & AM_DIR) /* It is a directory */
  1997. res = FR_NO_FILE;
  1998. }
  1999. }
  2000. #endif
  2001. FREE_BUF();
  2002. if (res == FR_OK) {
  2003. fp->flag = mode; /* File access mode */
  2004. fp->sclust = ld_clust(dj.fs, dir); /* File start cluster */
  2005. fp->fsize = LD_DWORD(dir+DIR_FileSize); /* File size */
  2006. fp->fptr = 0; /* File pointer */
  2007. fp->dsect = 0;
  2008. #if _USE_FASTSEEK
  2009. fp->cltbl = 0; /* Normal seek mode */
  2010. #endif
  2011. fp->fs = dj.fs; fp->id = dj.fs->id; /* Validate file object */
  2012. }
  2013. }
  2014. LEAVE_FF(dj.fs, res);
  2015. }
  2016. /*-----------------------------------------------------------------------*/
  2017. /* Read File */
  2018. /*-----------------------------------------------------------------------*/
  2019. FRESULT f_read (
  2020. FIL *fp, /* Pointer to the file object */
  2021. void *buff, /* Pointer to data buffer */
  2022. UINT btr, /* Number of bytes to read */
  2023. UINT *br /* Pointer to number of bytes read */
  2024. )
  2025. {
  2026. FRESULT res;
  2027. DWORD clst, sect, remain;
  2028. UINT rcnt, cc;
  2029. BYTE csect, *rbuff = buff;
  2030. *br = 0; /* Clear read byte counter */
  2031. res = validate(fp); /* Check validity */
  2032. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2033. if (fp->flag & FA__ERROR) /* Aborted file? */
  2034. LEAVE_FF(fp->fs, FR_INT_ERR);
  2035. if (!(fp->flag & FA_READ)) /* Check access mode */
  2036. LEAVE_FF(fp->fs, FR_DENIED);
  2037. remain = fp->fsize - fp->fptr;
  2038. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  2039. for ( ; btr; /* Repeat until all data read */
  2040. rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  2041. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  2042. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  2043. if (!csect) { /* On the cluster boundary? */
  2044. if (fp->fptr == 0) { /* On the top of the file? */
  2045. clst = fp->sclust; /* Follow from the origin */
  2046. } else { /* Middle or end of the file */
  2047. #if _USE_FASTSEEK
  2048. if (fp->cltbl)
  2049. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  2050. else
  2051. #endif
  2052. clst = get_fat(fp->fs, fp->clust); /* Follow cluster chain on the FAT */
  2053. }
  2054. if (clst < 2) ABORT(fp->fs, FR_INT_ERR);
  2055. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2056. fp->clust = clst; /* Update current cluster */
  2057. }
  2058. sect = clust2sect(fp->fs, fp->clust); /* Get current sector */
  2059. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  2060. sect += csect;
  2061. cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */
  2062. if (cc) { /* Read maximum contiguous sectors directly */
  2063. if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  2064. cc = fp->fs->csize - csect;
  2065. if (disk_read(fp->fs->drv, rbuff, sect, (BYTE)cc) != RES_OK)
  2066. ABORT(fp->fs, FR_DISK_ERR);
  2067. #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
  2068. #if _FS_TINY
  2069. if (fp->fs->wflag && fp->fs->winsect - sect < cc)
  2070. mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs));
  2071. #else
  2072. if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc)
  2073. mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs));
  2074. #endif
  2075. #endif
  2076. rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
  2077. continue;
  2078. }
  2079. #if !_FS_TINY
  2080. if (fp->dsect != sect) { /* Load data sector if not in cache */
  2081. #if !_FS_READONLY
  2082. if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */
  2083. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2084. ABORT(fp->fs, FR_DISK_ERR);
  2085. fp->flag &= ~FA__DIRTY;
  2086. }
  2087. #endif
  2088. if (disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK) /* Fill sector cache */
  2089. ABORT(fp->fs, FR_DISK_ERR);
  2090. }
  2091. #endif
  2092. fp->dsect = sect;
  2093. }
  2094. rcnt = SS(fp->fs) - ((UINT)fp->fptr % SS(fp->fs)); /* Get partial sector data from sector buffer */
  2095. if (rcnt > btr) rcnt = btr;
  2096. #if _FS_TINY
  2097. if (move_window(fp->fs, fp->dsect)) /* Move sector window */
  2098. ABORT(fp->fs, FR_DISK_ERR);
  2099. mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  2100. #else
  2101. mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  2102. #endif
  2103. }
  2104. LEAVE_FF(fp->fs, FR_OK);
  2105. }
  2106. #if !_FS_READONLY
  2107. /*-----------------------------------------------------------------------*/
  2108. /* Write File */
  2109. /*-----------------------------------------------------------------------*/
  2110. FRESULT f_write (
  2111. FIL *fp, /* Pointer to the file object */
  2112. const void *buff, /* Pointer to the data to be written */
  2113. UINT btw, /* Number of bytes to write */
  2114. UINT *bw /* Pointer to number of bytes written */
  2115. )
  2116. {
  2117. FRESULT res;
  2118. DWORD clst, sect;
  2119. UINT wcnt, cc;
  2120. const BYTE *wbuff = buff;
  2121. BYTE csect;
  2122. *bw = 0; /* Clear write byte counter */
  2123. res = validate(fp); /* Check validity */
  2124. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2125. if (fp->flag & FA__ERROR) /* Aborted file? */
  2126. LEAVE_FF(fp->fs, FR_INT_ERR);
  2127. if (!(fp->flag & FA_WRITE)) /* Check access mode */
  2128. LEAVE_FF(fp->fs, FR_DENIED);
  2129. if ((DWORD)(fp->fsize + btw) < fp->fsize) btw = 0; /* File size cannot reach 4GB */
  2130. for ( ; btw; /* Repeat until all data written */
  2131. wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
  2132. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  2133. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  2134. if (!csect) { /* On the cluster boundary? */
  2135. if (fp->fptr == 0) { /* On the top of the file? */
  2136. clst = fp->sclust; /* Follow from the origin */
  2137. if (clst == 0) /* When no cluster is allocated, */
  2138. fp->sclust = clst = create_chain(fp->fs, 0); /* Create a new cluster chain */
  2139. } else { /* Middle or end of the file */
  2140. #if _USE_FASTSEEK
  2141. if (fp->cltbl)
  2142. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  2143. else
  2144. #endif
  2145. clst = create_chain(fp->fs, fp->clust); /* Follow or stretch cluster chain on the FAT */
  2146. }
  2147. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  2148. if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  2149. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2150. fp->clust = clst; /* Update current cluster */
  2151. }
  2152. #if _FS_TINY
  2153. if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0)) /* Write-back sector cache */
  2154. ABORT(fp->fs, FR_DISK_ERR);
  2155. #else
  2156. if (fp->flag & FA__DIRTY) { /* Write-back sector cache */
  2157. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2158. ABORT(fp->fs, FR_DISK_ERR);
  2159. fp->flag &= ~FA__DIRTY;
  2160. }
  2161. #endif
  2162. sect = clust2sect(fp->fs, fp->clust); /* Get current sector */
  2163. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  2164. sect += csect;
  2165. cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */
  2166. if (cc) { /* Write maximum contiguous sectors directly */
  2167. if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  2168. cc = fp->fs->csize - csect;
  2169. if (disk_write(fp->fs->drv, wbuff, sect, (BYTE)cc) != RES_OK)
  2170. ABORT(fp->fs, FR_DISK_ERR);
  2171. #if _FS_TINY
  2172. if (fp->fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  2173. mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs));
  2174. fp->fs->wflag = 0;
  2175. }
  2176. #else
  2177. if (fp->dsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  2178. mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));
  2179. fp->flag &= ~FA__DIRTY;
  2180. }
  2181. #endif
  2182. wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
  2183. continue;
  2184. }
  2185. #if _FS_TINY
  2186. if (fp->fptr >= fp->fsize) { /* Avoid silly cache filling at growing edge */
  2187. if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR);
  2188. fp->fs->winsect = sect;
  2189. }
  2190. #else
  2191. if (fp->dsect != sect) { /* Fill sector cache with file data */
  2192. if (fp->fptr < fp->fsize &&
  2193. disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK)
  2194. ABORT(fp->fs, FR_DISK_ERR);
  2195. }
  2196. #endif
  2197. fp->dsect = sect;
  2198. }
  2199. wcnt = SS(fp->fs) - ((UINT)fp->fptr % SS(fp->fs));/* Put partial sector into file I/O buffer */
  2200. if (wcnt > btw) wcnt = btw;
  2201. #if _FS_TINY
  2202. if (move_window(fp->fs, fp->dsect)) /* Move sector window */
  2203. ABORT(fp->fs, FR_DISK_ERR);
  2204. mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  2205. fp->fs->wflag = 1;
  2206. #else
  2207. mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  2208. fp->flag |= FA__DIRTY;
  2209. #endif
  2210. }
  2211. if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
  2212. fp->flag |= FA__WRITTEN; /* Set file change flag */
  2213. LEAVE_FF(fp->fs, FR_OK);
  2214. }
  2215. /*-----------------------------------------------------------------------*/
  2216. /* Synchronize the File Object */
  2217. /*-----------------------------------------------------------------------*/
  2218. FRESULT f_sync (
  2219. FIL *fp /* Pointer to the file object */
  2220. )
  2221. {
  2222. FRESULT res;
  2223. DWORD tim;
  2224. BYTE *dir;
  2225. res = validate(fp); /* Check validity of the object */
  2226. if (res == FR_OK) {
  2227. if (fp->flag & FA__WRITTEN) { /* Has the file been written? */
  2228. #if !_FS_TINY /* Write-back dirty buffer */
  2229. if (fp->flag & FA__DIRTY) {
  2230. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2231. LEAVE_FF(fp->fs, FR_DISK_ERR);
  2232. fp->flag &= ~FA__DIRTY;
  2233. }
  2234. #endif
  2235. /* Update the directory entry */
  2236. res = move_window(fp->fs, fp->dir_sect);
  2237. if (res == FR_OK) {
  2238. dir = fp->dir_ptr;
  2239. dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
  2240. ST_DWORD(dir+DIR_FileSize, fp->fsize); /* Update file size */
  2241. st_clust(dir, fp->sclust); /* Update start cluster */
  2242. tim = get_fattime(); /* Update updated time */
  2243. ST_DWORD(dir+DIR_WrtTime, tim);
  2244. ST_WORD(dir+DIR_LstAccDate, 0);
  2245. fp->flag &= ~FA__WRITTEN;
  2246. fp->fs->wflag = 1;
  2247. res = sync(fp->fs);
  2248. }
  2249. }
  2250. }
  2251. LEAVE_FF(fp->fs, res);
  2252. }
  2253. #endif /* !_FS_READONLY */
  2254. /*-----------------------------------------------------------------------*/
  2255. /* Close File */
  2256. /*-----------------------------------------------------------------------*/
  2257. FRESULT f_close (
  2258. FIL *fp /* Pointer to the file object to be closed */
  2259. )
  2260. {
  2261. FRESULT res;
  2262. #if _FS_READONLY
  2263. res = validate(fp);
  2264. {
  2265. #if _FS_REENTRANT
  2266. FATFS *fs = fp->fs;
  2267. #endif
  2268. if (res == FR_OK) fp->fs = 0; /* Discard file object */
  2269. LEAVE_FF(fs, res);
  2270. }
  2271. #else
  2272. res = f_sync(fp); /* Flush cached data */
  2273. #if _FS_LOCK
  2274. if (res == FR_OK) { /* Decrement open counter */
  2275. #if _FS_REENTRANT
  2276. FATFS *fs = fp->fs;;
  2277. res = validate(fp);
  2278. if (res == FR_OK) {
  2279. res = dec_lock(fp->lockid);
  2280. unlock_fs(fs, FR_OK);
  2281. }
  2282. #else
  2283. res = dec_lock(fp->lockid);
  2284. #endif
  2285. }
  2286. #endif
  2287. if (res == FR_OK) fp->fs = 0; /* Discard file object */
  2288. return res;
  2289. #endif
  2290. }
  2291. /*-----------------------------------------------------------------------*/
  2292. /* Current Drive/Directory Handlings */
  2293. /*-----------------------------------------------------------------------*/
  2294. #if _FS_RPATH >= 1
  2295. FRESULT f_chdrive (
  2296. BYTE drv /* Drive number */
  2297. )
  2298. {
  2299. if (drv >= _VOLUMES) return FR_INVALID_DRIVE;
  2300. CurrVol = drv;
  2301. return FR_OK;
  2302. }
  2303. FRESULT f_chdir (
  2304. const TCHAR *path /* Pointer to the directory path */
  2305. )
  2306. {
  2307. FRESULT res;
  2308. DIR dj;
  2309. DEF_NAMEBUF;
  2310. res = chk_mounted(&path, &dj.fs, 0);
  2311. if (res == FR_OK) {
  2312. INIT_BUF(dj);
  2313. res = follow_path(&dj, path); /* Follow the path */
  2314. FREE_BUF();
  2315. if (res == FR_OK) { /* Follow completed */
  2316. if (!dj.dir) {
  2317. dj.fs->cdir = dj.sclust; /* Start directory itself */
  2318. } else {
  2319. if (dj.dir[DIR_Attr] & AM_DIR) /* Reached to the directory */
  2320. dj.fs->cdir = ld_clust(dj.fs, dj.dir);
  2321. else
  2322. res = FR_NO_PATH; /* Reached but a file */
  2323. }
  2324. }
  2325. if (res == FR_NO_FILE) res = FR_NO_PATH;
  2326. }
  2327. LEAVE_FF(dj.fs, res);
  2328. }
  2329. #if _FS_RPATH >= 2
  2330. FRESULT f_getcwd (
  2331. TCHAR *path, /* Pointer to the directory path */
  2332. UINT sz_path /* Size of path */
  2333. )
  2334. {
  2335. FRESULT res;
  2336. DIR dj;
  2337. UINT i, n;
  2338. DWORD ccl;
  2339. TCHAR *tp;
  2340. FILINFO fno;
  2341. DEF_NAMEBUF;
  2342. *path = 0;
  2343. res = chk_mounted((const TCHAR**)&path, &dj.fs, 0); /* Get current volume */
  2344. if (res == FR_OK) {
  2345. INIT_BUF(dj);
  2346. i = sz_path; /* Bottom of buffer (dir stack base) */
  2347. dj.sclust = dj.fs->cdir; /* Start to follow upper dir from current dir */
  2348. while ((ccl = dj.sclust) != 0) { /* Repeat while current dir is a sub-dir */
  2349. res = dir_sdi(&dj, 1); /* Get parent dir */
  2350. if (res != FR_OK) break;
  2351. res = dir_read(&dj);
  2352. if (res != FR_OK) break;
  2353. dj.sclust = ld_clust(dj.fs, dj.dir); /* Goto parent dir */
  2354. res = dir_sdi(&dj, 0);
  2355. if (res != FR_OK) break;
  2356. do { /* Find the entry links to the child dir */
  2357. res = dir_read(&dj);
  2358. if (res != FR_OK) break;
  2359. if (ccl == ld_clust(dj.fs, dj.dir)) break; /* Found the entry */
  2360. res = dir_next(&dj, 0);
  2361. } while (res == FR_OK);
  2362. if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
  2363. if (res != FR_OK) break;
  2364. #if _USE_LFN
  2365. fno.lfname = path;
  2366. fno.lfsize = i;
  2367. #endif
  2368. get_fileinfo(&dj, &fno); /* Get the dir name and push it to the buffer */
  2369. tp = fno.fname;
  2370. if (_USE_LFN && *path) tp = path;
  2371. for (n = 0; tp[n]; n++) ;
  2372. if (i < n + 3) {
  2373. res = FR_NOT_ENOUGH_CORE; break;
  2374. }
  2375. while (n) path[--i] = tp[--n];
  2376. path[--i] = '/';
  2377. }
  2378. tp = path;
  2379. if (res == FR_OK) {
  2380. *tp++ = '0' + CurrVol; /* Put drive number */
  2381. *tp++ = ':';
  2382. if (i == sz_path) { /* Root-dir */
  2383. *tp++ = '/';
  2384. } else { /* Sub-dir */
  2385. do /* Add stacked path str */
  2386. *tp++ = path[i++];
  2387. while (i < sz_path);
  2388. }
  2389. }
  2390. *tp = 0;
  2391. FREE_BUF();
  2392. }
  2393. LEAVE_FF(dj.fs, res);
  2394. }
  2395. #endif /* _FS_RPATH >= 2 */
  2396. #endif /* _FS_RPATH >= 1 */
  2397. #if _FS_MINIMIZE <= 2
  2398. /*-----------------------------------------------------------------------*/
  2399. /* Seek File R/W Pointer */
  2400. /*-----------------------------------------------------------------------*/
  2401. FRESULT f_lseek (
  2402. FIL *fp, /* Pointer to the file object */
  2403. DWORD ofs /* File pointer from top of file */
  2404. )
  2405. {
  2406. FRESULT res;
  2407. res = validate(fp); /* Check validity of the object */
  2408. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2409. if (fp->flag & FA__ERROR) /* Check abort flag */
  2410. LEAVE_FF(fp->fs, FR_INT_ERR);
  2411. #if _USE_FASTSEEK
  2412. if (fp->cltbl) { /* Fast seek */
  2413. DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
  2414. if (ofs == CREATE_LINKMAP) { /* Create CLMT */
  2415. tbl = fp->cltbl;
  2416. tlen = *tbl++; ulen = 2; /* Given table size and required table size */
  2417. cl = fp->sclust; /* Top of the chain */
  2418. if (cl) {
  2419. do {
  2420. /* Get a fragment */
  2421. tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
  2422. do {
  2423. pcl = cl; ncl++;
  2424. cl = get_fat(fp->fs, cl);
  2425. if (cl <= 1) ABORT(fp->fs, FR_INT_ERR);
  2426. if (cl == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2427. } while (cl == pcl + 1);
  2428. if (ulen <= tlen) { /* Store the length and top of the fragment */
  2429. *tbl++ = ncl; *tbl++ = tcl;
  2430. }
  2431. } while (cl < fp->fs->n_fatent); /* Repeat until end of chain */
  2432. }
  2433. *fp->cltbl = ulen; /* Number of items used */
  2434. if (ulen <= tlen)
  2435. *tbl = 0; /* Terminate table */
  2436. else
  2437. res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
  2438. } else { /* Fast seek */
  2439. if (ofs > fp->fsize) /* Clip offset at the file size */
  2440. ofs = fp->fsize;
  2441. fp->fptr = ofs; /* Set file pointer */
  2442. if (ofs) {
  2443. fp->clust = clmt_clust(fp, ofs - 1);
  2444. dsc = clust2sect(fp->fs, fp->clust);
  2445. if (!dsc) ABORT(fp->fs, FR_INT_ERR);
  2446. dsc += (ofs - 1) / SS(fp->fs) & (fp->fs->csize - 1);
  2447. if (fp->fptr % SS(fp->fs) && dsc != fp->dsect) { /* Refill sector cache if needed */
  2448. #if !_FS_TINY
  2449. #if !_FS_READONLY
  2450. if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */
  2451. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2452. ABORT(fp->fs, FR_DISK_ERR);
  2453. fp->flag &= ~FA__DIRTY;
  2454. }
  2455. #endif
  2456. if (disk_read(fp->fs->drv, fp->buf, dsc, 1) != RES_OK) /* Load current sector */
  2457. ABORT(fp->fs, FR_DISK_ERR);
  2458. #endif
  2459. fp->dsect = dsc;
  2460. }
  2461. }
  2462. }
  2463. } else
  2464. #endif
  2465. /* Normal Seek */
  2466. {
  2467. DWORD clst, bcs, nsect, ifptr;
  2468. if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */
  2469. #if !_FS_READONLY
  2470. && !(fp->flag & FA_WRITE)
  2471. #endif
  2472. ) ofs = fp->fsize;
  2473. ifptr = fp->fptr;
  2474. fp->fptr = nsect = 0;
  2475. if (ofs) {
  2476. bcs = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */
  2477. if (ifptr > 0 &&
  2478. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  2479. fp->fptr = (ifptr - 1) & ~(bcs - 1); /* start from the current cluster */
  2480. ofs -= fp->fptr;
  2481. clst = fp->clust;
  2482. } else { /* When seek to back cluster, */
  2483. clst = fp->sclust; /* start from the first cluster */
  2484. #if !_FS_READONLY
  2485. if (clst == 0) { /* If no cluster chain, create a new chain */
  2486. clst = create_chain(fp->fs, 0);
  2487. if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  2488. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2489. fp->sclust = clst;
  2490. }
  2491. #endif
  2492. fp->clust = clst;
  2493. }
  2494. if (clst != 0) {
  2495. while (ofs > bcs) { /* Cluster following loop */
  2496. #if !_FS_READONLY
  2497. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  2498. clst = create_chain(fp->fs, clst); /* Force stretch if in write mode */
  2499. if (clst == 0) { /* When disk gets full, clip file size */
  2500. ofs = bcs; break;
  2501. }
  2502. } else
  2503. #endif
  2504. clst = get_fat(fp->fs, clst); /* Follow cluster chain if not in write mode */
  2505. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2506. if (clst <= 1 || clst >= fp->fs->n_fatent) ABORT(fp->fs, FR_INT_ERR);
  2507. fp->clust = clst;
  2508. fp->fptr += bcs;
  2509. ofs -= bcs;
  2510. }
  2511. fp->fptr += ofs;
  2512. if (ofs % SS(fp->fs)) {
  2513. nsect = clust2sect(fp->fs, clst); /* Current sector */
  2514. if (!nsect) ABORT(fp->fs, FR_INT_ERR);
  2515. nsect += ofs / SS(fp->fs);
  2516. }
  2517. }
  2518. }
  2519. if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) { /* Fill sector cache if needed */
  2520. #if !_FS_TINY
  2521. #if !_FS_READONLY
  2522. if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */
  2523. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2524. ABORT(fp->fs, FR_DISK_ERR);
  2525. fp->flag &= ~FA__DIRTY;
  2526. }
  2527. #endif
  2528. if (disk_read(fp->fs->drv, fp->buf, nsect, 1) != RES_OK) /* Fill sector cache */
  2529. ABORT(fp->fs, FR_DISK_ERR);
  2530. #endif
  2531. fp->dsect = nsect;
  2532. }
  2533. #if !_FS_READONLY
  2534. if (fp->fptr > fp->fsize) { /* Set file change flag if the file size is extended */
  2535. fp->fsize = fp->fptr;
  2536. fp->flag |= FA__WRITTEN;
  2537. }
  2538. #endif
  2539. }
  2540. LEAVE_FF(fp->fs, res);
  2541. }
  2542. #if _FS_MINIMIZE <= 1
  2543. /*-----------------------------------------------------------------------*/
  2544. /* Create a Directory Object */
  2545. /*-----------------------------------------------------------------------*/
  2546. FRESULT f_opendir (
  2547. DIR *dj, /* Pointer to directory object to create */
  2548. const TCHAR *path /* Pointer to the directory path */
  2549. )
  2550. {
  2551. FRESULT res;
  2552. FATFS *fs;
  2553. DEF_NAMEBUF;
  2554. if (!dj) return FR_INVALID_OBJECT;
  2555. res = chk_mounted(&path, &dj->fs, 0);
  2556. fs = dj->fs;
  2557. if (res == FR_OK) {
  2558. INIT_BUF(*dj);
  2559. res = follow_path(dj, path); /* Follow the path to the directory */
  2560. FREE_BUF();
  2561. if (res == FR_OK) { /* Follow completed */
  2562. if (dj->dir) { /* It is not the root dir */
  2563. if (dj->dir[DIR_Attr] & AM_DIR) { /* The object is a directory */
  2564. dj->sclust = ld_clust(fs, dj->dir);
  2565. } else { /* The object is not a directory */
  2566. res = FR_NO_PATH;
  2567. }
  2568. }
  2569. if (res == FR_OK) {
  2570. dj->id = fs->id;
  2571. res = dir_sdi(dj, 0); /* Rewind dir */
  2572. }
  2573. }
  2574. if (res == FR_NO_FILE) res = FR_NO_PATH;
  2575. if (res != FR_OK) dj->fs = 0; /* Invalidate the dir object if function faild */
  2576. } else {
  2577. dj->fs = 0;
  2578. }
  2579. LEAVE_FF(fs, res);
  2580. }
  2581. /*-----------------------------------------------------------------------*/
  2582. /* Read Directory Entry in Sequence */
  2583. /*-----------------------------------------------------------------------*/
  2584. FRESULT f_readdir (
  2585. DIR *dj, /* Pointer to the open directory object */
  2586. FILINFO *fno /* Pointer to file information to return */
  2587. )
  2588. {
  2589. FRESULT res;
  2590. DEF_NAMEBUF;
  2591. res = validate(dj); /* Check validity of the object */
  2592. if (res == FR_OK) {
  2593. if (!fno) {
  2594. res = dir_sdi(dj, 0); /* Rewind the directory object */
  2595. } else {
  2596. INIT_BUF(*dj);
  2597. res = dir_read(dj); /* Read an directory item */
  2598. if (res == FR_NO_FILE) { /* Reached end of dir */
  2599. dj->sect = 0;
  2600. res = FR_OK;
  2601. }
  2602. if (res == FR_OK) { /* A valid entry is found */
  2603. get_fileinfo(dj, fno); /* Get the object information */
  2604. res = dir_next(dj, 0); /* Increment index for next */
  2605. if (res == FR_NO_FILE) {
  2606. dj->sect = 0;
  2607. res = FR_OK;
  2608. }
  2609. }
  2610. FREE_BUF();
  2611. }
  2612. }
  2613. LEAVE_FF(dj->fs, res);
  2614. }
  2615. #if _FS_MINIMIZE == 0
  2616. /*-----------------------------------------------------------------------*/
  2617. /* Get File Status */
  2618. /*-----------------------------------------------------------------------*/
  2619. FRESULT f_stat (
  2620. const TCHAR *path, /* Pointer to the file path */
  2621. FILINFO *fno /* Pointer to file information to return */
  2622. )
  2623. {
  2624. FRESULT res;
  2625. DIR dj;
  2626. DEF_NAMEBUF;
  2627. res = chk_mounted(&path, &dj.fs, 0);
  2628. if (res == FR_OK) {
  2629. INIT_BUF(dj);
  2630. res = follow_path(&dj, path); /* Follow the file path */
  2631. if (res == FR_OK) { /* Follow completed */
  2632. if (dj.dir) /* Found an object */
  2633. get_fileinfo(&dj, fno);
  2634. else /* It is root dir */
  2635. res = FR_INVALID_NAME;
  2636. }
  2637. FREE_BUF();
  2638. }
  2639. LEAVE_FF(dj.fs, res);
  2640. }
  2641. #if !_FS_READONLY
  2642. /*-----------------------------------------------------------------------*/
  2643. /* Get Number of Free Clusters */
  2644. /*-----------------------------------------------------------------------*/
  2645. FRESULT f_getfree (
  2646. const TCHAR *path, /* Pointer to the logical drive number (root dir) */
  2647. DWORD *nclst, /* Pointer to the variable to return number of free clusters */
  2648. FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */
  2649. )
  2650. {
  2651. FRESULT res;
  2652. FATFS *fs;
  2653. DWORD n, clst, sect, stat;
  2654. UINT i;
  2655. BYTE fat, *p;
  2656. /* Get drive number */
  2657. res = chk_mounted(&path, fatfs, 0);
  2658. fs = *fatfs;
  2659. if (res == FR_OK) {
  2660. /* If free_clust is valid, return it without full cluster scan */
  2661. if (fs->free_clust <= fs->n_fatent - 2) {
  2662. *nclst = fs->free_clust;
  2663. } else {
  2664. /* Get number of free clusters */
  2665. fat = fs->fs_type;
  2666. n = 0;
  2667. if (fat == FS_FAT12) {
  2668. clst = 2;
  2669. do {
  2670. stat = get_fat(fs, clst);
  2671. if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  2672. if (stat == 1) { res = FR_INT_ERR; break; }
  2673. if (stat == 0) n++;
  2674. } while (++clst < fs->n_fatent);
  2675. } else {
  2676. clst = fs->n_fatent;
  2677. sect = fs->fatbase;
  2678. i = 0; p = 0;
  2679. do {
  2680. if (!i) {
  2681. res = move_window(fs, sect++);
  2682. if (res != FR_OK) break;
  2683. p = fs->win;
  2684. i = SS(fs);
  2685. }
  2686. if (fat == FS_FAT16) {
  2687. if (LD_WORD(p) == 0) n++;
  2688. p += 2; i -= 2;
  2689. } else {
  2690. if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++;
  2691. p += 4; i -= 4;
  2692. }
  2693. } while (--clst);
  2694. }
  2695. fs->free_clust = n;
  2696. if (fat == FS_FAT32) fs->fsi_flag = 1;
  2697. *nclst = n;
  2698. }
  2699. }
  2700. LEAVE_FF(fs, res);
  2701. }
  2702. /*-----------------------------------------------------------------------*/
  2703. /* Truncate File */
  2704. /*-----------------------------------------------------------------------*/
  2705. FRESULT f_truncate (
  2706. FIL *fp /* Pointer to the file object */
  2707. )
  2708. {
  2709. FRESULT res;
  2710. DWORD ncl;
  2711. if (!fp) return FR_INVALID_OBJECT;
  2712. res = validate(fp); /* Check validity of the object */
  2713. if (res == FR_OK) {
  2714. if (fp->flag & FA__ERROR) { /* Check abort flag */
  2715. res = FR_INT_ERR;
  2716. } else {
  2717. if (!(fp->flag & FA_WRITE)) /* Check access mode */
  2718. res = FR_DENIED;
  2719. }
  2720. }
  2721. if (res == FR_OK) {
  2722. if (fp->fsize > fp->fptr) {
  2723. fp->fsize = fp->fptr; /* Set file size to current R/W point */
  2724. fp->flag |= FA__WRITTEN;
  2725. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  2726. res = remove_chain(fp->fs, fp->sclust);
  2727. fp->sclust = 0;
  2728. } else { /* When truncate a part of the file, remove remaining clusters */
  2729. ncl = get_fat(fp->fs, fp->clust);
  2730. res = FR_OK;
  2731. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  2732. if (ncl == 1) res = FR_INT_ERR;
  2733. if (res == FR_OK && ncl < fp->fs->n_fatent) {
  2734. res = put_fat(fp->fs, fp->clust, 0x0FFFFFFF);
  2735. if (res == FR_OK) res = remove_chain(fp->fs, ncl);
  2736. }
  2737. }
  2738. }
  2739. if (res != FR_OK) fp->flag |= FA__ERROR;
  2740. }
  2741. LEAVE_FF(fp->fs, res);
  2742. }
  2743. /*-----------------------------------------------------------------------*/
  2744. /* Delete a File or Directory */
  2745. /*-----------------------------------------------------------------------*/
  2746. FRESULT f_unlink (
  2747. const TCHAR *path /* Pointer to the file or directory path */
  2748. )
  2749. {
  2750. FRESULT res;
  2751. DIR dj, sdj;
  2752. BYTE *dir;
  2753. DWORD dclst;
  2754. DEF_NAMEBUF;
  2755. res = chk_mounted(&path, &dj.fs, 1);
  2756. if (res == FR_OK) {
  2757. INIT_BUF(dj);
  2758. res = follow_path(&dj, path); /* Follow the file path */
  2759. if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
  2760. res = FR_INVALID_NAME; /* Cannot remove dot entry */
  2761. #if _FS_LOCK
  2762. if (res == FR_OK) res = chk_lock(&dj, 2); /* Cannot remove open file */
  2763. #endif
  2764. if (res == FR_OK) { /* The object is accessible */
  2765. dir = dj.dir;
  2766. if (!dir) {
  2767. res = FR_INVALID_NAME; /* Cannot remove the start directory */
  2768. } else {
  2769. if (dir[DIR_Attr] & AM_RDO)
  2770. res = FR_DENIED; /* Cannot remove R/O object */
  2771. }
  2772. dclst = ld_clust(dj.fs, dir);
  2773. if (res == FR_OK && (dir[DIR_Attr] & AM_DIR)) { /* Is it a sub-dir? */
  2774. if (dclst < 2) {
  2775. res = FR_INT_ERR;
  2776. } else {
  2777. mem_cpy(&sdj, &dj, sizeof (DIR)); /* Check if the sub-dir is empty or not */
  2778. sdj.sclust = dclst;
  2779. res = dir_sdi(&sdj, 2); /* Exclude dot entries */
  2780. if (res == FR_OK) {
  2781. res = dir_read(&sdj);
  2782. if (res == FR_OK /* Not empty dir */
  2783. #if _FS_RPATH
  2784. || dclst == dj.fs->cdir /* Current dir */
  2785. #endif
  2786. ) res = FR_DENIED;
  2787. if (res == FR_NO_FILE) res = FR_OK; /* Empty */
  2788. }
  2789. }
  2790. }
  2791. if (res == FR_OK) {
  2792. res = dir_remove(&dj); /* Remove the directory entry */
  2793. if (res == FR_OK) {
  2794. if (dclst) /* Remove the cluster chain if exist */
  2795. res = remove_chain(dj.fs, dclst);
  2796. if (res == FR_OK) res = sync(dj.fs);
  2797. }
  2798. }
  2799. }
  2800. FREE_BUF();
  2801. }
  2802. LEAVE_FF(dj.fs, res);
  2803. }
  2804. /*-----------------------------------------------------------------------*/
  2805. /* Create a Directory */
  2806. /*-----------------------------------------------------------------------*/
  2807. FRESULT f_mkdir (
  2808. const TCHAR *path /* Pointer to the directory path */
  2809. )
  2810. {
  2811. FRESULT res;
  2812. DIR dj;
  2813. BYTE *dir, n;
  2814. DWORD dsc, dcl, pcl, tim = get_fattime();
  2815. DEF_NAMEBUF;
  2816. res = chk_mounted(&path, &dj.fs, 1);
  2817. if (res == FR_OK) {
  2818. INIT_BUF(dj);
  2819. res = follow_path(&dj, path); /* Follow the file path */
  2820. if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
  2821. if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NS] & NS_DOT))
  2822. res = FR_INVALID_NAME;
  2823. if (res == FR_NO_FILE) { /* Can create a new directory */
  2824. dcl = create_chain(dj.fs, 0); /* Allocate a cluster for the new directory table */
  2825. res = FR_OK;
  2826. if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
  2827. if (dcl == 1) res = FR_INT_ERR;
  2828. if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
  2829. if (res == FR_OK) /* Flush FAT */
  2830. res = move_window(dj.fs, 0);
  2831. if (res == FR_OK) { /* Initialize the new directory table */
  2832. dsc = clust2sect(dj.fs, dcl);
  2833. dir = dj.fs->win;
  2834. mem_set(dir, 0, SS(dj.fs));
  2835. mem_set(dir+DIR_Name, ' ', 8+3); /* Create "." entry */
  2836. dir[DIR_Name] = '.';
  2837. dir[DIR_Attr] = AM_DIR;
  2838. ST_DWORD(dir+DIR_WrtTime, tim);
  2839. st_clust(dir, dcl);
  2840. mem_cpy(dir+SZ_DIR, dir, SZ_DIR); /* Create ".." entry */
  2841. dir[33] = '.'; pcl = dj.sclust;
  2842. if (dj.fs->fs_type == FS_FAT32 && pcl == dj.fs->dirbase)
  2843. pcl = 0;
  2844. st_clust(dir+SZ_DIR, pcl);
  2845. for (n = dj.fs->csize; n; n--) { /* Write dot entries and clear following sectors */
  2846. dj.fs->winsect = dsc++;
  2847. dj.fs->wflag = 1;
  2848. res = move_window(dj.fs, 0);
  2849. if (res != FR_OK) break;
  2850. mem_set(dir, 0, SS(dj.fs));
  2851. }
  2852. }
  2853. if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */
  2854. if (res != FR_OK) {
  2855. remove_chain(dj.fs, dcl); /* Could not register, remove cluster chain */
  2856. } else {
  2857. dir = dj.dir;
  2858. dir[DIR_Attr] = AM_DIR; /* Attribute */
  2859. ST_DWORD(dir+DIR_WrtTime, tim); /* Created time */
  2860. st_clust(dir, dcl); /* Table start cluster */
  2861. dj.fs->wflag = 1;
  2862. res = sync(dj.fs);
  2863. }
  2864. }
  2865. FREE_BUF();
  2866. }
  2867. LEAVE_FF(dj.fs, res);
  2868. }
  2869. /*-----------------------------------------------------------------------*/
  2870. /* Change Attribute */
  2871. /*-----------------------------------------------------------------------*/
  2872. FRESULT f_chmod (
  2873. const TCHAR *path, /* Pointer to the file path */
  2874. BYTE value, /* Attribute bits */
  2875. BYTE mask /* Attribute mask to change */
  2876. )
  2877. {
  2878. FRESULT res;
  2879. DIR dj;
  2880. BYTE *dir;
  2881. DEF_NAMEBUF;
  2882. res = chk_mounted(&path, &dj.fs, 1);
  2883. if (res == FR_OK) {
  2884. INIT_BUF(dj);
  2885. res = follow_path(&dj, path); /* Follow the file path */
  2886. FREE_BUF();
  2887. if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
  2888. res = FR_INVALID_NAME;
  2889. if (res == FR_OK) {
  2890. dir = dj.dir;
  2891. if (!dir) { /* Is it a root directory? */
  2892. res = FR_INVALID_NAME;
  2893. } else { /* File or sub directory */
  2894. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  2895. dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  2896. dj.fs->wflag = 1;
  2897. res = sync(dj.fs);
  2898. }
  2899. }
  2900. }
  2901. LEAVE_FF(dj.fs, res);
  2902. }
  2903. /*-----------------------------------------------------------------------*/
  2904. /* Change Timestamp */
  2905. /*-----------------------------------------------------------------------*/
  2906. FRESULT f_utime (
  2907. const TCHAR *path, /* Pointer to the file/directory name */
  2908. const FILINFO *fno /* Pointer to the time stamp to be set */
  2909. )
  2910. {
  2911. FRESULT res;
  2912. DIR dj;
  2913. BYTE *dir;
  2914. DEF_NAMEBUF;
  2915. res = chk_mounted(&path, &dj.fs, 1);
  2916. if (res == FR_OK) {
  2917. INIT_BUF(dj);
  2918. res = follow_path(&dj, path); /* Follow the file path */
  2919. FREE_BUF();
  2920. if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
  2921. res = FR_INVALID_NAME;
  2922. if (res == FR_OK) {
  2923. dir = dj.dir;
  2924. if (!dir) { /* Root directory */
  2925. res = FR_INVALID_NAME;
  2926. } else { /* File or sub-directory */
  2927. ST_WORD(dir+DIR_WrtTime, fno->ftime);
  2928. ST_WORD(dir+DIR_WrtDate, fno->fdate);
  2929. dj.fs->wflag = 1;
  2930. res = sync(dj.fs);
  2931. }
  2932. }
  2933. }
  2934. LEAVE_FF(dj.fs, res);
  2935. }
  2936. /*-----------------------------------------------------------------------*/
  2937. /* Rename File/Directory */
  2938. /*-----------------------------------------------------------------------*/
  2939. FRESULT f_rename (
  2940. const TCHAR *path_old, /* Pointer to the old name */
  2941. const TCHAR *path_new /* Pointer to the new name */
  2942. )
  2943. {
  2944. FRESULT res;
  2945. DIR djo, djn;
  2946. BYTE buf[21], *dir;
  2947. DWORD dw;
  2948. DEF_NAMEBUF;
  2949. res = chk_mounted(&path_old, &djo.fs, 1);
  2950. if (res == FR_OK) {
  2951. djn.fs = djo.fs;
  2952. INIT_BUF(djo);
  2953. res = follow_path(&djo, path_old); /* Check old object */
  2954. if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))
  2955. res = FR_INVALID_NAME;
  2956. #if _FS_LOCK
  2957. if (res == FR_OK) res = chk_lock(&djo, 2);
  2958. #endif
  2959. if (res == FR_OK) { /* Old object is found */
  2960. if (!djo.dir) { /* Is root dir? */
  2961. res = FR_NO_FILE;
  2962. } else {
  2963. mem_cpy(buf, djo.dir+DIR_Attr, 21); /* Save the object information except for name */
  2964. mem_cpy(&djn, &djo, sizeof (DIR)); /* Check new object */
  2965. res = follow_path(&djn, path_new);
  2966. if (res == FR_OK) res = FR_EXIST; /* The new object name is already existing */
  2967. if (res == FR_NO_FILE) { /* Is it a valid path and no name collision? */
  2968. /* Start critical section that an interruption or error can cause cross-link */
  2969. res = dir_register(&djn); /* Register the new entry */
  2970. if (res == FR_OK) {
  2971. dir = djn.dir; /* Copy object information except for name */
  2972. mem_cpy(dir+13, buf+2, 19);
  2973. dir[DIR_Attr] = buf[0] | AM_ARC;
  2974. djo.fs->wflag = 1;
  2975. if (djo.sclust != djn.sclust && (dir[DIR_Attr] & AM_DIR)) { /* Update .. entry in the directory if needed */
  2976. dw = clust2sect(djo.fs, ld_clust(djo.fs, dir));
  2977. if (!dw) {
  2978. res = FR_INT_ERR;
  2979. } else {
  2980. res = move_window(djo.fs, dw);
  2981. dir = djo.fs->win+SZ_DIR; /* .. entry */
  2982. if (res == FR_OK && dir[1] == '.') {
  2983. dw = (djo.fs->fs_type == FS_FAT32 && djn.sclust == djo.fs->dirbase) ? 0 : djn.sclust;
  2984. st_clust(dir, dw);
  2985. djo.fs->wflag = 1;
  2986. }
  2987. }
  2988. }
  2989. if (res == FR_OK) {
  2990. res = dir_remove(&djo); /* Remove old entry */
  2991. if (res == FR_OK)
  2992. res = sync(djo.fs);
  2993. }
  2994. }
  2995. /* End critical section */
  2996. }
  2997. }
  2998. }
  2999. FREE_BUF();
  3000. }
  3001. LEAVE_FF(djo.fs, res);
  3002. }
  3003. #endif /* !_FS_READONLY */
  3004. #endif /* _FS_MINIMIZE == 0 */
  3005. #endif /* _FS_MINIMIZE <= 1 */
  3006. #endif /* _FS_MINIMIZE <= 2 */
  3007. /*-----------------------------------------------------------------------*/
  3008. /* Forward data to the stream directly (available on only tiny cfg) */
  3009. /*-----------------------------------------------------------------------*/
  3010. #if _USE_FORWARD && _FS_TINY
  3011. FRESULT f_forward (
  3012. FIL *fp, /* Pointer to the file object */
  3013. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  3014. UINT btr, /* Number of bytes to forward */
  3015. UINT *bf /* Pointer to number of bytes forwarded */
  3016. )
  3017. {
  3018. FRESULT res;
  3019. DWORD remain, clst, sect;
  3020. UINT rcnt;
  3021. BYTE csect;
  3022. *bf = 0; /* Clear transfer byte counter */
  3023. if (!fp) return FR_INVALID_OBJECT;
  3024. res = validate(fp); /* Check validity of the object */
  3025. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  3026. if (fp->flag & FA__ERROR) /* Check error flag */
  3027. LEAVE_FF(fp->fs, FR_INT_ERR);
  3028. if (!(fp->flag & FA_READ)) /* Check access mode */
  3029. LEAVE_FF(fp->fs, FR_DENIED);
  3030. remain = fp->fsize - fp->fptr;
  3031. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  3032. for ( ; btr && (*func)(0, 0); /* Repeat until all data transferred or stream becomes busy */
  3033. fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) {
  3034. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  3035. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  3036. if (!csect) { /* On the cluster boundary? */
  3037. clst = (fp->fptr == 0) ? /* On the top of the file? */
  3038. fp->sclust : get_fat(fp->fs, fp->clust);
  3039. if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
  3040. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  3041. fp->clust = clst; /* Update current cluster */
  3042. }
  3043. }
  3044. sect = clust2sect(fp->fs, fp->clust); /* Get current data sector */
  3045. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  3046. sect += csect;
  3047. if (move_window(fp->fs, sect)) /* Move sector window */
  3048. ABORT(fp->fs, FR_DISK_ERR);
  3049. fp->dsect = sect;
  3050. rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs)); /* Forward data from sector window */
  3051. if (rcnt > btr) rcnt = btr;
  3052. rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);
  3053. if (!rcnt) ABORT(fp->fs, FR_INT_ERR);
  3054. }
  3055. LEAVE_FF(fp->fs, FR_OK);
  3056. }
  3057. #endif /* _USE_FORWARD */
  3058. #if _USE_MKFS && !_FS_READONLY
  3059. /*-----------------------------------------------------------------------*/
  3060. /* Create File System on the Drive */
  3061. /*-----------------------------------------------------------------------*/
  3062. #define N_ROOTDIR 512 /* Number of root dir entries for FAT12/16 */
  3063. #define N_FATS 1 /* Number of FAT copies (1 or 2) */
  3064. FRESULT f_mkfs (
  3065. BYTE drv, /* Logical drive number */
  3066. BYTE sfd, /* Partitioning rule 0:FDISK, 1:SFD */
  3067. UINT au /* Allocation unit size [bytes] */
  3068. )
  3069. {
  3070. static const WORD vst[] = { 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 0};
  3071. static const WORD cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512};
  3072. BYTE fmt, md, sys, *tbl, pdrv, part;
  3073. DWORD n_clst, vs, n, wsect;
  3074. UINT i;
  3075. DWORD b_vol, b_fat, b_dir, b_data; /* LBA */
  3076. DWORD n_vol, n_rsv, n_fat, n_dir; /* Size */
  3077. FATFS *fs;
  3078. DSTATUS stat;
  3079. /* Check mounted drive and clear work area */
  3080. if (drv >= _VOLUMES) return FR_INVALID_DRIVE;
  3081. if (sfd > 1) return FR_INVALID_PARAMETER;
  3082. if (au & (au - 1)) return FR_INVALID_PARAMETER;
  3083. fs = FatFs[drv];
  3084. if (!fs) return FR_NOT_ENABLED;
  3085. fs->fs_type = 0;
  3086. pdrv = LD2PD(drv); /* Physical drive */
  3087. part = LD2PT(drv); /* Partition (0:auto detect, 1-4:get from partition table)*/
  3088. /* Get disk statics */
  3089. stat = disk_initialize(pdrv);
  3090. if (stat & STA_NOINIT) return FR_NOT_READY;
  3091. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  3092. #if _MAX_SS != 512 /* Get disk sector size */
  3093. if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > _MAX_SS)
  3094. return FR_DISK_ERR;
  3095. #endif
  3096. if (_MULTI_PARTITION && part) {
  3097. /* Get partition information from partition table in the MBR */
  3098. if (disk_read(pdrv, fs->win, 0, 1) != RES_OK) return FR_DISK_ERR;
  3099. if (LD_WORD(fs->win+BS_55AA) != 0xAA55) return FR_MKFS_ABORTED;
  3100. tbl = &fs->win[MBR_Table + (part - 1) * SZ_PTE];
  3101. if (!tbl[4]) return FR_MKFS_ABORTED; /* No partition? */
  3102. b_vol = LD_DWORD(tbl+8); /* Volume start sector */
  3103. n_vol = LD_DWORD(tbl+12); /* Volume size */
  3104. } else {
  3105. /* Create a partition in this function */
  3106. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &n_vol) != RES_OK || n_vol < 128)
  3107. return FR_DISK_ERR;
  3108. b_vol = (sfd) ? 0 : 63; /* Volume start sector */
  3109. n_vol -= b_vol; /* Volume size */
  3110. }
  3111. if (!au) { /* AU auto selection */
  3112. vs = n_vol / (2000 / (SS(fs) / 512));
  3113. for (i = 0; vs < vst[i]; i++) ;
  3114. au = cst[i];
  3115. }
  3116. au /= SS(fs); /* Number of sectors per cluster */
  3117. if (au == 0) au = 1;
  3118. if (au > 128) au = 128;
  3119. /* Pre-compute number of clusters and FAT sub-type */
  3120. n_clst = n_vol / au;
  3121. fmt = FS_FAT12;
  3122. if (n_clst >= MIN_FAT16) fmt = FS_FAT16;
  3123. if (n_clst >= MIN_FAT32) fmt = FS_FAT32;
  3124. /* Determine offset and size of FAT structure */
  3125. if (fmt == FS_FAT32) {
  3126. n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);
  3127. n_rsv = 32;
  3128. n_dir = 0;
  3129. } else {
  3130. n_fat = (fmt == FS_FAT12) ? (n_clst * 3 + 1) / 2 + 3 : (n_clst * 2) + 4;
  3131. n_fat = (n_fat + SS(fs) - 1) / SS(fs);
  3132. n_rsv = 1;
  3133. n_dir = (DWORD)N_ROOTDIR * SZ_DIR / SS(fs);
  3134. }
  3135. b_fat = b_vol + n_rsv; /* FAT area start sector */
  3136. b_dir = b_fat + n_fat * N_FATS; /* Directory area start sector */
  3137. b_data = b_dir + n_dir; /* Data area start sector */
  3138. if (n_vol < b_data + au - b_vol) return FR_MKFS_ABORTED; /* Too small volume */
  3139. /* Align data start sector to erase block boundary (for flash memory media) */
  3140. if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &n) != RES_OK || !n || n > 32768) n = 1;
  3141. n = (b_data + n - 1) & ~(n - 1); /* Next nearest erase block from current data start */
  3142. n = (n - b_data) / N_FATS;
  3143. if (fmt == FS_FAT32) { /* FAT32: Move FAT offset */
  3144. n_rsv += n;
  3145. b_fat += n;
  3146. } else { /* FAT12/16: Expand FAT size */
  3147. n_fat += n;
  3148. }
  3149. /* Determine number of clusters and final check of validity of the FAT sub-type */
  3150. n_clst = (n_vol - n_rsv - n_fat * N_FATS - n_dir) / au;
  3151. if ( (fmt == FS_FAT16 && n_clst < MIN_FAT16)
  3152. || (fmt == FS_FAT32 && n_clst < MIN_FAT32))
  3153. return FR_MKFS_ABORTED;
  3154. switch (fmt) { /* Determine system ID for partition table */
  3155. case FS_FAT12: sys = 0x01; break;
  3156. case FS_FAT16: sys = (n_vol < 0x10000) ? 0x04 : 0x06; break;
  3157. default: sys = 0x0C;
  3158. }
  3159. if (_MULTI_PARTITION && part) {
  3160. /* Update system ID in the partition table */
  3161. tbl = &fs->win[MBR_Table + (part - 1) * SZ_PTE];
  3162. tbl[4] = sys;
  3163. if (disk_write(pdrv, fs->win, 0, 1) != RES_OK) return FR_DISK_ERR;
  3164. md = 0xF8;
  3165. } else {
  3166. if (sfd) { /* No partition table (SFD) */
  3167. md = 0xF0;
  3168. } else { /* Create partition table (FDISK) */
  3169. mem_set(fs->win, 0, SS(fs));
  3170. tbl = fs->win+MBR_Table; /* Create partition table for single partition in the drive */
  3171. tbl[1] = 1; /* Partition start head */
  3172. tbl[2] = 1; /* Partition start sector */
  3173. tbl[3] = 0; /* Partition start cylinder */
  3174. tbl[4] = sys; /* System type */
  3175. tbl[5] = 254; /* Partition end head */
  3176. n = (b_vol + n_vol) / 63 / 255;
  3177. tbl[6] = (BYTE)((n >> 2) | 63); /* Partition end sector */
  3178. tbl[7] = (BYTE)n; /* End cylinder */
  3179. ST_DWORD(tbl+8, 63); /* Partition start in LBA */
  3180. ST_DWORD(tbl+12, n_vol); /* Partition size in LBA */
  3181. ST_WORD(fs->win+BS_55AA, 0xAA55); /* MBR signature */
  3182. if (disk_write(pdrv, fs->win, 0, 1) != RES_OK) /* Write it to the MBR sector */
  3183. return FR_DISK_ERR;
  3184. md = 0xF8;
  3185. }
  3186. }
  3187. /* Create BPB in the VBR */
  3188. tbl = fs->win; /* Clear sector */
  3189. mem_set(tbl, 0, SS(fs));
  3190. mem_cpy(tbl, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code, OEM name */
  3191. i = SS(fs); /* Sector size */
  3192. ST_WORD(tbl+BPB_BytsPerSec, i);
  3193. tbl[BPB_SecPerClus] = (BYTE)au; /* Sectors per cluster */
  3194. ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv); /* Reserved sectors */
  3195. tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */
  3196. i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR; /* Number of rootdir entries */
  3197. ST_WORD(tbl+BPB_RootEntCnt, i);
  3198. if (n_vol < 0x10000) { /* Number of total sectors */
  3199. ST_WORD(tbl+BPB_TotSec16, n_vol);
  3200. } else {
  3201. ST_DWORD(tbl+BPB_TotSec32, n_vol);
  3202. }
  3203. tbl[BPB_Media] = md; /* Media descriptor */
  3204. ST_WORD(tbl+BPB_SecPerTrk, 63); /* Number of sectors per track */
  3205. ST_WORD(tbl+BPB_NumHeads, 255); /* Number of heads */
  3206. ST_DWORD(tbl+BPB_HiddSec, b_vol); /* Hidden sectors */
  3207. n = get_fattime(); /* Use current time as VSN */
  3208. if (fmt == FS_FAT32) {
  3209. ST_DWORD(tbl+BS_VolID32, n); /* VSN */
  3210. ST_DWORD(tbl+BPB_FATSz32, n_fat); /* Number of sectors per FAT */
  3211. ST_DWORD(tbl+BPB_RootClus, 2); /* Root directory start cluster (2) */
  3212. ST_WORD(tbl+BPB_FSInfo, 1); /* FSInfo record offset (VBR+1) */
  3213. ST_WORD(tbl+BPB_BkBootSec, 6); /* Backup boot record offset (VBR+6) */
  3214. tbl[BS_DrvNum32] = 0x80; /* Drive number */
  3215. tbl[BS_BootSig32] = 0x29; /* Extended boot signature */
  3216. mem_cpy(tbl+BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
  3217. } else {
  3218. ST_DWORD(tbl+BS_VolID, n); /* VSN */
  3219. ST_WORD(tbl+BPB_FATSz16, n_fat); /* Number of sectors per FAT */
  3220. tbl[BS_DrvNum] = 0x80; /* Drive number */
  3221. tbl[BS_BootSig] = 0x29; /* Extended boot signature */
  3222. mem_cpy(tbl+BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
  3223. }
  3224. ST_WORD(tbl+BS_55AA, 0xAA55); /* Signature (Offset is fixed here regardless of sector size) */
  3225. if (disk_write(pdrv, tbl, b_vol, 1) != RES_OK) /* Write it to the VBR sector */
  3226. return FR_DISK_ERR;
  3227. if (fmt == FS_FAT32) /* Write backup VBR if needed (VBR+6) */
  3228. disk_write(pdrv, tbl, b_vol + 6, 1);
  3229. /* Initialize FAT area */
  3230. wsect = b_fat;
  3231. for (i = 0; i < N_FATS; i++) { /* Initialize each FAT copy */
  3232. mem_set(tbl, 0, SS(fs)); /* 1st sector of the FAT */
  3233. n = md; /* Media descriptor byte */
  3234. if (fmt != FS_FAT32) {
  3235. n |= (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;
  3236. ST_DWORD(tbl+0, n); /* Reserve cluster #0-1 (FAT12/16) */
  3237. } else {
  3238. n |= 0xFFFFFF00;
  3239. ST_DWORD(tbl+0, n); /* Reserve cluster #0-1 (FAT32) */
  3240. ST_DWORD(tbl+4, 0xFFFFFFFF);
  3241. ST_DWORD(tbl+8, 0x0FFFFFFF); /* Reserve cluster #2 for root dir */
  3242. }
  3243. if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK)
  3244. return FR_DISK_ERR;
  3245. mem_set(tbl, 0, SS(fs)); /* Fill following FAT entries with zero */
  3246. for (n = 1; n < n_fat; n++) { /* This loop may take a time on FAT32 volume due to many single sector writes */
  3247. if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK)
  3248. return FR_DISK_ERR;
  3249. }
  3250. }
  3251. /* Initialize root directory */
  3252. i = (fmt == FS_FAT32) ? au : n_dir;
  3253. do {
  3254. if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK)
  3255. return FR_DISK_ERR;
  3256. } while (--i);
  3257. #if _USE_ERASE /* Erase data area if needed */
  3258. {
  3259. DWORD eb[2];
  3260. eb[0] = wsect; eb[1] = wsect + (n_clst - ((fmt == FS_FAT32) ? 1 : 0)) * au - 1;
  3261. disk_ioctl(pdrv, CTRL_ERASE_SECTOR, eb);
  3262. }
  3263. #endif
  3264. /* Create FSInfo if needed */
  3265. if (fmt == FS_FAT32) {
  3266. ST_DWORD(tbl+FSI_LeadSig, 0x41615252);
  3267. ST_DWORD(tbl+FSI_StrucSig, 0x61417272);
  3268. ST_DWORD(tbl+FSI_Free_Count, n_clst - 1); /* Number of free clusters */
  3269. ST_DWORD(tbl+FSI_Nxt_Free, 2); /* Last allocated cluster# */
  3270. ST_WORD(tbl+BS_55AA, 0xAA55);
  3271. disk_write(pdrv, tbl, b_vol + 1, 1); /* Write original (VBR+1) */
  3272. disk_write(pdrv, tbl, b_vol + 7, 1); /* Write backup (VBR+7) */
  3273. }
  3274. return (disk_ioctl(pdrv, CTRL_SYNC, 0) == RES_OK) ? FR_OK : FR_DISK_ERR;
  3275. }
  3276. #if _MULTI_PARTITION == 2
  3277. /*-----------------------------------------------------------------------*/
  3278. /* Divide Physical Drive */
  3279. /*-----------------------------------------------------------------------*/
  3280. FRESULT f_fdisk (
  3281. BYTE pdrv, /* Physical drive number */
  3282. const DWORD szt[], /* Pointer to the size table for each partitions */
  3283. void* work /* Pointer to the working buffer */
  3284. )
  3285. {
  3286. UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;
  3287. BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;
  3288. DSTATUS stat;
  3289. DWORD sz_disk, sz_part, s_part;
  3290. stat = disk_initialize(pdrv);
  3291. if (stat & STA_NOINIT) return FR_NOT_READY;
  3292. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  3293. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;
  3294. /* Determine CHS in the table regardless of the drive geometry */
  3295. for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;
  3296. if (n == 256) n--;
  3297. e_hd = n - 1;
  3298. sz_cyl = 63 * n;
  3299. tot_cyl = sz_disk / sz_cyl;
  3300. /* Create partition table */
  3301. mem_set(buf, 0, _MAX_SS);
  3302. p = buf + MBR_Table; b_cyl = 0;
  3303. for (i = 0; i < 4; i++, p += SZ_PTE) {
  3304. p_cyl = (szt[i] <= 100) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl;
  3305. if (!p_cyl) continue;
  3306. s_part = (DWORD)sz_cyl * b_cyl;
  3307. sz_part = (DWORD)sz_cyl * p_cyl;
  3308. if (i == 0) { /* Exclude first track of cylinder 0 */
  3309. s_hd = 1;
  3310. s_part += 63; sz_part -= 63;
  3311. } else {
  3312. s_hd = 0;
  3313. }
  3314. e_cyl = b_cyl + p_cyl - 1;
  3315. if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER;
  3316. /* Set partition table */
  3317. p[1] = s_hd; /* Start head */
  3318. p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */
  3319. p[3] = (BYTE)b_cyl; /* Start cylinder */
  3320. p[4] = 0x06; /* System type (temporary setting) */
  3321. p[5] = e_hd; /* End head */
  3322. p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */
  3323. p[7] = (BYTE)e_cyl; /* End cylinder */
  3324. ST_DWORD(p + 8, s_part); /* Start sector in LBA */
  3325. ST_DWORD(p + 12, sz_part); /* Partition size */
  3326. /* Next partition */
  3327. b_cyl += p_cyl;
  3328. }
  3329. ST_WORD(p, 0xAA55);
  3330. /* Write it to the MBR */
  3331. return (disk_write(pdrv, buf, 0, 1) || disk_ioctl(pdrv, CTRL_SYNC, 0)) ? FR_DISK_ERR : FR_OK;
  3332. }
  3333. #endif /* _MULTI_PARTITION == 2 */
  3334. #endif /* _USE_MKFS && !_FS_READONLY */
  3335. #if _USE_STRFUNC
  3336. /*-----------------------------------------------------------------------*/
  3337. /* Get a string from the file */
  3338. /*-----------------------------------------------------------------------*/
  3339. TCHAR* f_gets (
  3340. TCHAR* buff, /* Pointer to the string buffer to read */
  3341. int len, /* Size of string buffer (characters) */
  3342. FIL* fil /* Pointer to the file object */
  3343. )
  3344. {
  3345. int n = 0;
  3346. TCHAR c, *p = buff;
  3347. BYTE s[2];
  3348. UINT rc;
  3349. while (n < len - 1) { /* Read bytes until buffer gets filled */
  3350. f_read(fil, s, 1, &rc);
  3351. if (rc != 1) break; /* Break on EOF or error */
  3352. c = s[0];
  3353. #if _LFN_UNICODE /* Read a character in UTF-8 encoding */
  3354. if (c >= 0x80) {
  3355. if (c < 0xC0) continue; /* Skip stray trailer */
  3356. if (c < 0xE0) { /* Two-byte sequence */
  3357. f_read(fil, s, 1, &rc);
  3358. if (rc != 1) break;
  3359. c = ((c & 0x1F) << 6) | (s[0] & 0x3F);
  3360. if (c < 0x80) c = '?';
  3361. } else {
  3362. if (c < 0xF0) { /* Three-byte sequence */
  3363. f_read(fil, s, 2, &rc);
  3364. if (rc != 2) break;
  3365. c = (c << 12) | ((s[0] & 0x3F) << 6) | (s[1] & 0x3F);
  3366. if (c < 0x800) c = '?';
  3367. } else { /* Reject four-byte sequence */
  3368. c = '?';
  3369. }
  3370. }
  3371. }
  3372. #endif
  3373. #if _USE_STRFUNC >= 2
  3374. if (c == '\r') continue; /* Strip '\r' */
  3375. #endif
  3376. *p++ = c;
  3377. n++;
  3378. if (c == '\n') break; /* Break on EOL */
  3379. }
  3380. *p = 0;
  3381. return n ? buff : 0; /* When no data read (eof or error), return with error. */
  3382. }
  3383. #if !_FS_READONLY
  3384. #include <stdarg.h>
  3385. /*-----------------------------------------------------------------------*/
  3386. /* Put a character to the file */
  3387. /*-----------------------------------------------------------------------*/
  3388. int f_putc (
  3389. TCHAR c, /* A character to be output */
  3390. FIL* fil /* Pointer to the file object */
  3391. )
  3392. {
  3393. UINT bw, btw;
  3394. BYTE s[3];
  3395. #if _USE_STRFUNC >= 2
  3396. if (c == '\n') f_putc ('\r', fil); /* LF -> CRLF conversion */
  3397. #endif
  3398. #if _LFN_UNICODE /* Write the character in UTF-8 encoding */
  3399. if (c < 0x80) { /* 7-bit */
  3400. s[0] = (BYTE)c;
  3401. btw = 1;
  3402. } else {
  3403. if (c < 0x800) { /* 11-bit */
  3404. s[0] = (BYTE)(0xC0 | (c >> 6));
  3405. s[1] = (BYTE)(0x80 | (c & 0x3F));
  3406. btw = 2;
  3407. } else { /* 16-bit */
  3408. s[0] = (BYTE)(0xE0 | (c >> 12));
  3409. s[1] = (BYTE)(0x80 | ((c >> 6) & 0x3F));
  3410. s[2] = (BYTE)(0x80 | (c & 0x3F));
  3411. btw = 3;
  3412. }
  3413. }
  3414. #else /* Write the character without conversion */
  3415. s[0] = (BYTE)c;
  3416. btw = 1;
  3417. #endif
  3418. f_write(fil, s, btw, &bw); /* Write the char to the file */
  3419. return (bw == btw) ? 1 : EOF; /* Return the result */
  3420. }
  3421. /*-----------------------------------------------------------------------*/
  3422. /* Put a string to the file */
  3423. /*-----------------------------------------------------------------------*/
  3424. int f_puts (
  3425. const TCHAR* str, /* Pointer to the string to be output */
  3426. FIL* fil /* Pointer to the file object */
  3427. )
  3428. {
  3429. int n;
  3430. for (n = 0; *str; str++, n++) {
  3431. if (f_putc(*str, fil) == EOF) return EOF;
  3432. }
  3433. return n;
  3434. }
  3435. /*-----------------------------------------------------------------------*/
  3436. /* Put a formatted string to the file */
  3437. /*-----------------------------------------------------------------------*/
  3438. int f_printf (
  3439. FIL* fil, /* Pointer to the file object */
  3440. const TCHAR* str, /* Pointer to the format string */
  3441. ... /* Optional arguments... */
  3442. )
  3443. {
  3444. va_list arp;
  3445. BYTE f, r;
  3446. UINT i, j, w;
  3447. ULONG v;
  3448. TCHAR c, d, s[16], *p;
  3449. int res, chc, cc;
  3450. va_start(arp, str);
  3451. for (cc = res = 0; cc != EOF; res += cc) {
  3452. c = *str++;
  3453. if (c == 0) break; /* End of string */
  3454. if (c != '%') { /* Non escape character */
  3455. cc = f_putc(c, fil);
  3456. if (cc != EOF) cc = 1;
  3457. continue;
  3458. }
  3459. w = f = 0;
  3460. c = *str++;
  3461. if (c == '0') { /* Flag: '0' padding */
  3462. f = 1; c = *str++;
  3463. } else {
  3464. if (c == '-') { /* Flag: left justified */
  3465. f = 2; c = *str++;
  3466. }
  3467. }
  3468. while (IsDigit(c)) { /* Precision */
  3469. w = w * 10 + c - '0';
  3470. c = *str++;
  3471. }
  3472. if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
  3473. f |= 4; c = *str++;
  3474. }
  3475. if (!c) break;
  3476. d = c;
  3477. if (IsLower(d)) d -= 0x20;
  3478. switch (d) { /* Type is... */
  3479. case 'S' : /* String */
  3480. p = va_arg(arp, TCHAR*);
  3481. for (j = 0; p[j]; j++) ;
  3482. chc = 0;
  3483. if (!(f & 2)) {
  3484. while (j++ < w) chc += (cc = f_putc(' ', fil));
  3485. }
  3486. chc += (cc = f_puts(p, fil));
  3487. while (j++ < w) chc += (cc = f_putc(' ', fil));
  3488. if (cc != EOF) cc = chc;
  3489. continue;
  3490. case 'C' : /* Character */
  3491. cc = f_putc((TCHAR)va_arg(arp, int), fil); continue;
  3492. case 'B' : /* Binary */
  3493. r = 2; break;
  3494. case 'O' : /* Octal */
  3495. r = 8; break;
  3496. case 'D' : /* Signed decimal */
  3497. case 'U' : /* Unsigned decimal */
  3498. r = 10; break;
  3499. case 'X' : /* Hexdecimal */
  3500. r = 16; break;
  3501. default: /* Unknown type (pass-through) */
  3502. cc = f_putc(c, fil); continue;
  3503. }
  3504. /* Get an argument and put it in numeral */
  3505. v = (f & 4) ? (ULONG)va_arg(arp, long) : ((d == 'D') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int));
  3506. if (d == 'D' && (v & 0x80000000)) {
  3507. v = 0 - v;
  3508. f |= 8;
  3509. }
  3510. i = 0;
  3511. do {
  3512. d = (TCHAR)(v % r); v /= r;
  3513. if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
  3514. s[i++] = d + '0';
  3515. } while (v && i < sizeof s / sizeof s[0]);
  3516. if (f & 8) s[i++] = '-';
  3517. j = i; d = (f & 1) ? '0' : ' ';
  3518. res = 0;
  3519. while (!(f & 2) && j++ < w) res += (cc = f_putc(d, fil));
  3520. do res += (cc = f_putc(s[--i], fil)); while(i);
  3521. while (j++ < w) res += (cc = f_putc(' ', fil));
  3522. if (cc != EOF) cc = res;
  3523. }
  3524. va_end(arp);
  3525. return (cc == EOF) ? cc : res;
  3526. }
  3527. #endif /* !_FS_READONLY */
  3528. #endif /* _USE_STRFUNC */