ff.c 97 KB

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