ff.c 116 KB

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