ff.c 98 KB

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