1
0

ff.c 148 KB

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