ff.c 154 KB

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