ff.c 221 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594
  1. /* This file is part of ooFatFs, a customised version of FatFs
  2. * See https://github.com/micropython/oofatfs for details
  3. */
  4. /*----------------------------------------------------------------------------/
  5. / FatFs - Generic FAT file system module R0.12b /
  6. /-----------------------------------------------------------------------------/
  7. /
  8. / Copyright (C) 2016, ChaN, all right reserved.
  9. /
  10. / FatFs module is an open source software. Redistribution and use of FatFs in
  11. / source and binary forms, with or without modification, are permitted provided
  12. / that the following condition is met:
  13. / 1. Redistributions of source code must retain the above copyright notice,
  14. / this condition and the following disclaimer.
  15. /
  16. / This software is provided by the copyright holder and contributors "AS IS"
  17. / and any warranties related to this software are DISCLAIMED.
  18. / The copyright owner or contributors be NOT LIABLE for any damages caused
  19. / by use of this software.
  20. /----------------------------------------------------------------------------*/
  21. #include <string.h>
  22. #include "ff.h" /* Declarations of FatFs API */
  23. #include "diskio.h" /* Declarations of device I/O functions */
  24. // DIR has been renamed FF_DIR in the public API so it doesn't clash with POSIX
  25. #define DIR FF_DIR
  26. /*--------------------------------------------------------------------------
  27. Module Private Definitions
  28. ---------------------------------------------------------------------------*/
  29. #if _FATFS != 68020 /* Revision ID */
  30. #error Wrong include file (ff.h).
  31. #endif
  32. #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
  33. /* Reentrancy related */
  34. #if _FS_REENTRANT
  35. #if _USE_LFN == 1
  36. #error Static LFN work area cannot be used at thread-safe configuration
  37. #endif
  38. #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
  39. #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
  40. #else
  41. #define ENTER_FF(fs)
  42. #define LEAVE_FF(fs, res) return res
  43. #endif
  44. /* Definitions of sector size */
  45. #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)
  46. #error Wrong sector size configuration
  47. #endif
  48. #if _MAX_SS == _MIN_SS
  49. #define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
  50. #else
  51. #define SS(fs) ((fs)->ssize) /* Variable sector size */
  52. #endif
  53. /* Timestamp */
  54. #if _FS_NORTC == 1
  55. #if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31
  56. #error Invalid _FS_NORTC settings
  57. #endif
  58. #define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
  59. #else
  60. #define GET_FATTIME() get_fattime()
  61. #endif
  62. /* File lock controls */
  63. #if _FS_LOCK != 0
  64. #if _FS_READONLY
  65. #error _FS_LOCK must be 0 at read-only configuration
  66. #endif
  67. typedef struct {
  68. FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */
  69. DWORD clu; /* Object ID 2, directory (0:root) */
  70. DWORD ofs; /* Object ID 3, directory offset */
  71. WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
  72. } FILESEM;
  73. #endif
  74. /* DBCS code ranges and SBCS upper conversion tables */
  75. #if _CODE_PAGE == 932 /* Japanese Shift-JIS */
  76. #define _DF1S 0x81 /* DBC 1st byte range 1 start */
  77. #define _DF1E 0x9F /* DBC 1st byte range 1 end */
  78. #define _DF2S 0xE0 /* DBC 1st byte range 2 start */
  79. #define _DF2E 0xFC /* DBC 1st byte range 2 end */
  80. #define _DS1S 0x40 /* DBC 2nd byte range 1 start */
  81. #define _DS1E 0x7E /* DBC 2nd byte range 1 end */
  82. #define _DS2S 0x80 /* DBC 2nd byte range 2 start */
  83. #define _DS2E 0xFC /* DBC 2nd byte range 2 end */
  84. #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
  85. #define _DF1S 0x81
  86. #define _DF1E 0xFE
  87. #define _DS1S 0x40
  88. #define _DS1E 0x7E
  89. #define _DS2S 0x80
  90. #define _DS2E 0xFE
  91. #elif _CODE_PAGE == 949 /* Korean */
  92. #define _DF1S 0x81
  93. #define _DF1E 0xFE
  94. #define _DS1S 0x41
  95. #define _DS1E 0x5A
  96. #define _DS2S 0x61
  97. #define _DS2E 0x7A
  98. #define _DS3S 0x81
  99. #define _DS3E 0xFE
  100. #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
  101. #define _DF1S 0x81
  102. #define _DF1E 0xFE
  103. #define _DS1S 0x40
  104. #define _DS1E 0x7E
  105. #define _DS2S 0xA1
  106. #define _DS2E 0xFE
  107. #elif _CODE_PAGE == 437 /* U.S. */
  108. #define _DF1S 0
  109. #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  110. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  111. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  112. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  113. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  114. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  115. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  116. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  117. #elif _CODE_PAGE == 720 /* Arabic */
  118. #define _DF1S 0
  119. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  120. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  121. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  122. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  123. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  124. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  125. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  126. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  127. #elif _CODE_PAGE == 737 /* Greek */
  128. #define _DF1S 0
  129. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  130. 0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
  131. 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \
  132. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  133. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  134. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  135. 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  136. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  137. #elif _CODE_PAGE == 771 /* KBL */
  138. #define _DF1S 0
  139. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  140. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  141. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  142. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  143. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  144. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \
  145. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  146. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF}
  147. #elif _CODE_PAGE == 775 /* Baltic */
  148. #define _DF1S 0
  149. #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \
  150. 0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  151. 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  152. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  153. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  154. 0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  155. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \
  156. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  157. #elif _CODE_PAGE == 850 /* Latin 1 */
  158. #define _DF1S 0
  159. #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \
  160. 0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \
  161. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  162. 0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  163. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  164. 0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \
  165. 0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \
  166. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  167. #elif _CODE_PAGE == 852 /* Latin 2 */
  168. #define _DF1S 0
  169. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \
  170. 0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \
  171. 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \
  172. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
  173. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  174. 0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  175. 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \
  176. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
  177. #elif _CODE_PAGE == 855 /* Cyrillic */
  178. #define _DF1S 0
  179. #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \
  180. 0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
  181. 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \
  182. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
  183. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  184. 0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
  185. 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \
  186. 0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
  187. #elif _CODE_PAGE == 857 /* Turkish */
  188. #define _DF1S 0
  189. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \
  190. 0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
  191. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  192. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  193. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  194. 0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  195. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \
  196. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  197. #elif _CODE_PAGE == 860 /* Portuguese */
  198. #define _DF1S 0
  199. #define _EXCVT {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \
  200. 0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  201. 0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  202. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  203. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  204. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  205. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  206. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  207. #elif _CODE_PAGE == 861 /* Icelandic */
  208. #define _DF1S 0
  209. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \
  210. 0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  211. 0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  212. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  213. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  214. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  215. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  216. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  217. #elif _CODE_PAGE == 862 /* Hebrew */
  218. #define _DF1S 0
  219. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  220. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  221. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  222. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  223. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  224. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  225. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  226. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  227. #elif _CODE_PAGE == 863 /* Canadian-French */
  228. #define _DF1S 0
  229. #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \
  230. 0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \
  231. 0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  232. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  233. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  234. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  235. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  236. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  237. #elif _CODE_PAGE == 864 /* Arabic */
  238. #define _DF1S 0
  239. #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  240. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  241. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  242. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  243. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  244. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  245. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  246. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  247. #elif _CODE_PAGE == 865 /* Nordic */
  248. #define _DF1S 0
  249. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  250. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  251. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  252. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  253. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  254. 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, \
  256. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  257. #elif _CODE_PAGE == 866 /* Russian */
  258. #define _DF1S 0
  259. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  260. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  261. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  262. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  263. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  264. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  265. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  266. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  267. #elif _CODE_PAGE == 869 /* Greek 2 */
  268. #define _DF1S 0
  269. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  270. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \
  271. 0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  272. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  273. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  274. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \
  275. 0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \
  276. 0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF}
  277. #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
  278. #if _USE_LFN != 0
  279. #error Cannot enable LFN without valid code page.
  280. #endif
  281. #define _DF1S 0
  282. #else
  283. #error Unknown code page
  284. #endif
  285. /* Character code support macros */
  286. #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
  287. #define IsLower(c) (((c)>='a')&&((c)<='z'))
  288. #define IsDigit(c) (((c)>='0')&&((c)<='9'))
  289. #if _DF1S != 0 /* Code page is DBCS */
  290. #ifdef _DF2S /* Two 1st byte areas */
  291. #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
  292. #else /* One 1st byte area */
  293. #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
  294. #endif
  295. #ifdef _DS3S /* Three 2nd byte areas */
  296. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
  297. #else /* Two 2nd byte areas */
  298. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
  299. #endif
  300. #else /* Code page is SBCS */
  301. #define IsDBCS1(c) 0
  302. #define IsDBCS2(c) 0
  303. #endif /* _DF1S */
  304. /* File attribute bits (internal use) */
  305. #define AM_VOL 0x08 /* Volume label */
  306. #define AM_LFN 0x0F /* LFN entry */
  307. #define AM_MASK 0x3F /* Mask of defined bits */
  308. /* File access control and file status flags (internal use) */
  309. #define FA_SEEKEND 0x20 /* Seek to end of the file on file open */
  310. #define FA_MODIFIED 0x40 /* File has been modified */
  311. #define FA_DIRTY 0x80 /* FIL.buf[] needs to be written-back */
  312. /* Name status flags */
  313. #define NSFLAG 11 /* Index of name status byte in fn[] */
  314. #define NS_LOSS 0x01 /* Out of 8.3 format */
  315. #define NS_LFN 0x02 /* Force to create LFN entry */
  316. #define NS_LAST 0x04 /* Last segment */
  317. #define NS_BODY 0x08 /* Lower case flag (body) */
  318. #define NS_EXT 0x10 /* Lower case flag (ext) */
  319. #define NS_DOT 0x20 /* Dot entry */
  320. #define NS_NOLFN 0x40 /* Do not find LFN */
  321. #define NS_NONAME 0x80 /* Not followed */
  322. /* Limits and boundaries (differ from specs but correct for real DOS/Windows) */
  323. #define MAX_FAT12 0xFF5 /* Maximum number of FAT12 clusters */
  324. #define MAX_FAT16 0xFFF5 /* Maximum number of FAT16 clusters */
  325. #define MAX_FAT32 0xFFFFFF5 /* Maximum number of FAT32 clusters */
  326. #define MAX_EXFAT 0x7FFFFFFD /* Maximum number of exFAT clusters (limited by implementation) */
  327. #define MAX_DIR 0x200000 /* Maximum size of FAT directory */
  328. #define MAX_DIR_EX 0x10000000 /* Maximum size of exFAT directory */
  329. /* FatFs refers the members in the FAT structures as byte array instead of
  330. / structure members because the structure is not binary compatible between
  331. / different platforms */
  332. #define BS_JmpBoot 0 /* x86 jump instruction (3-byte) */
  333. #define BS_OEMName 3 /* OEM name (8-byte) */
  334. #define BPB_BytsPerSec 11 /* Sector size [byte] (WORD) */
  335. #define BPB_SecPerClus 13 /* Cluster size [sector] (BYTE) */
  336. #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (WORD) */
  337. #define BPB_NumFATs 16 /* Number of FATs (BYTE) */
  338. #define BPB_RootEntCnt 17 /* Size of root directory area for FAT12/16 [entry] (WORD) */
  339. #define BPB_TotSec16 19 /* Volume size (16-bit) [sector] (WORD) */
  340. #define BPB_Media 21 /* Media descriptor byte (BYTE) */
  341. #define BPB_FATSz16 22 /* FAT size (16-bit) [sector] (WORD) */
  342. #define BPB_SecPerTrk 24 /* Track size for int13h [sector] (WORD) */
  343. #define BPB_NumHeads 26 /* Number of heads for int13h (WORD) */
  344. #define BPB_HiddSec 28 /* Volume offset from top of the drive (DWORD) */
  345. #define BPB_TotSec32 32 /* Volume size (32-bit) [sector] (DWORD) */
  346. #define BS_DrvNum 36 /* Physical drive number for int13h (BYTE) */
  347. #define BS_NTres 37 /* Error flag (BYTE) */
  348. #define BS_BootSig 38 /* Extended boot signature (BYTE) */
  349. #define BS_VolID 39 /* Volume serial number (DWORD) */
  350. #define BS_VolLab 43 /* Volume label string (8-byte) */
  351. #define BS_FilSysType 54 /* File system type string (8-byte) */
  352. #define BS_BootCode 62 /* Boot code (448-byte) */
  353. #define BS_55AA 510 /* Signature word (WORD) */
  354. #define BPB_FATSz32 36 /* FAT32: FAT size [sector] (DWORD) */
  355. #define BPB_ExtFlags32 40 /* FAT32: Extended flags (WORD) */
  356. #define BPB_FSVer32 42 /* FAT32: File system version (WORD) */
  357. #define BPB_RootClus32 44 /* FAT32: Root directory cluster (DWORD) */
  358. #define BPB_FSInfo32 48 /* FAT32: Offset of FSINFO sector (WORD) */
  359. #define BPB_BkBootSec32 50 /* FAT32: Offset of backup boot sector (WORD) */
  360. #define BS_DrvNum32 64 /* FAT32: Physical drive number for int13h (BYTE) */
  361. #define BS_NTres32 65 /* FAT32: Error flag (BYTE) */
  362. #define BS_BootSig32 66 /* FAT32: Extended boot signature (BYTE) */
  363. #define BS_VolID32 67 /* FAT32: Volume serial number (DWORD) */
  364. #define BS_VolLab32 71 /* FAT32: Volume label string (8-byte) */
  365. #define BS_FilSysType32 82 /* FAT32: File system type string (8-byte) */
  366. #define BS_BootCode32 90 /* FAT32: Boot code (420-byte) */
  367. #define BPB_ZeroedEx 11 /* exFAT: MBZ field (53-byte) */
  368. #define BPB_VolOfsEx 64 /* exFAT: Volume offset from top of the drive [sector] (QWORD) */
  369. #define BPB_TotSecEx 72 /* exFAT: Volume size [sector] (QWORD) */
  370. #define BPB_FatOfsEx 80 /* exFAT: FAT offset from top of the volume [sector] (DWORD) */
  371. #define BPB_FatSzEx 84 /* exFAT: FAT size [sector] (DWORD) */
  372. #define BPB_DataOfsEx 88 /* exFAT: Data offset from top of the volume [sector] (DWORD) */
  373. #define BPB_NumClusEx 92 /* exFAT: Number of clusters (DWORD) */
  374. #define BPB_RootClusEx 96 /* exFAT: Root directory cluster (DWORD) */
  375. #define BPB_VolIDEx 100 /* exFAT: Volume serial number (DWORD) */
  376. #define BPB_FSVerEx 104 /* exFAT: File system version (WORD) */
  377. #define BPB_VolFlagEx 106 /* exFAT: Volume flags (BYTE) */
  378. #define BPB_ActFatEx 107 /* exFAT: Active FAT flags (BYTE) */
  379. #define BPB_BytsPerSecEx 108 /* exFAT: Log2 of sector size in byte (BYTE) */
  380. #define BPB_SecPerClusEx 109 /* exFAT: Log2 of cluster size in sector (BYTE) */
  381. #define BPB_NumFATsEx 110 /* exFAT: Number of FATs (BYTE) */
  382. #define BPB_DrvNumEx 111 /* exFAT: Physical drive number for int13h (BYTE) */
  383. #define BPB_PercInUseEx 112 /* exFAT: Percent in use (BYTE) */
  384. #define BPB_RsvdEx 113 /* exFAT: Reserved (7-byte) */
  385. #define BS_BootCodeEx 120 /* exFAT: Boot code (390-byte) */
  386. #define FSI_LeadSig 0 /* FAT32 FSI: Leading signature (DWORD) */
  387. #define FSI_StrucSig 484 /* FAT32 FSI: Structure signature (DWORD) */
  388. #define FSI_Free_Count 488 /* FAT32 FSI: Number of free clusters (DWORD) */
  389. #define FSI_Nxt_Free 492 /* FAT32 FSI: Last allocated cluster (DWORD) */
  390. #define MBR_Table 446 /* MBR: Offset of partition table in the MBR */
  391. #define SZ_PTE 16 /* MBR: Size of a partition table entry */
  392. #define PTE_Boot 0 /* MBR PTE: Boot indicator */
  393. #define PTE_StHead 1 /* MBR PTE: Start head */
  394. #define PTE_StSec 2 /* MBR PTE: Start sector */
  395. #define PTE_StCyl 3 /* MBR PTE: Start cylinder */
  396. #define PTE_System 4 /* MBR PTE: System ID */
  397. #define PTE_EdHead 5 /* MBR PTE: End head */
  398. #define PTE_EdSec 6 /* MBR PTE: End sector */
  399. #define PTE_EdCyl 7 /* MBR PTE: End cylinder */
  400. #define PTE_StLba 8 /* MBR PTE: Start in LBA */
  401. #define PTE_SizLba 12 /* MBR PTE: Size in LBA */
  402. #define DIR_Name 0 /* Short file name (11-byte) */
  403. #define DIR_Attr 11 /* Attribute (BYTE) */
  404. #define DIR_NTres 12 /* Lower case flag (BYTE) */
  405. #define DIR_CrtTime10 13 /* Created time sub-second (BYTE) */
  406. #define DIR_CrtTime 14 /* Created time (DWORD) */
  407. #define DIR_LstAccDate 18 /* Last accessed date (WORD) */
  408. #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (WORD) */
  409. #define DIR_ModTime 22 /* Modified time (DWORD) */
  410. #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (WORD) */
  411. #define DIR_FileSize 28 /* File size (DWORD) */
  412. #define LDIR_Ord 0 /* LFN entry order and LLE flag (BYTE) */
  413. #define LDIR_Attr 11 /* LFN attribute (BYTE) */
  414. #define LDIR_Type 12 /* LFN type (BYTE) */
  415. #define LDIR_Chksum 13 /* Checksum of the SFN entry (BYTE) */
  416. #define LDIR_FstClusLO 26 /* Must be zero (WORD) */
  417. #define XDIR_Type 0 /* Type of exFAT directory entry (BYTE) */
  418. #define XDIR_NumLabel 1 /* Number of volume label characters (BYTE) */
  419. #define XDIR_Label 2 /* Volume label (11-WORD) */
  420. #define XDIR_CaseSum 4 /* Sum of case conversion table (DWORD) */
  421. #define XDIR_NumSec 1 /* Number of secondary entries (BYTE) */
  422. #define XDIR_SetSum 2 /* Sum of the set of directory entries (WORD) */
  423. #define XDIR_Attr 4 /* File attribute (WORD) */
  424. #define XDIR_CrtTime 8 /* Created time (DWORD) */
  425. #define XDIR_ModTime 12 /* Modified time (DWORD) */
  426. #define XDIR_AccTime 16 /* Last accessed time (DWORD) */
  427. #define XDIR_CrtTime10 20 /* Created time subsecond (BYTE) */
  428. #define XDIR_ModTime10 21 /* Modified time subsecond (BYTE) */
  429. #define XDIR_CrtTZ 22 /* Created timezone (BYTE) */
  430. #define XDIR_ModTZ 23 /* Modified timezone (BYTE) */
  431. #define XDIR_AccTZ 24 /* Last accessed timezone (BYTE) */
  432. #define XDIR_GenFlags 33 /* Gneral secondary flags (WORD) */
  433. #define XDIR_NumName 35 /* Number of file name characters (BYTE) */
  434. #define XDIR_NameHash 36 /* Hash of file name (WORD) */
  435. #define XDIR_ValidFileSize 40 /* Valid file size (QWORD) */
  436. #define XDIR_FstClus 52 /* First cluster of the file data (DWORD) */
  437. #define XDIR_FileSize 56 /* File/Directory size (QWORD) */
  438. #define SZDIRE 32 /* Size of a directory entry */
  439. #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
  440. #define DDEM 0xE5 /* Deleted directory entry mark set to DIR_Name[0] */
  441. #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
  442. /*--------------------------------------------------------------------------
  443. Module Private Work Area
  444. ---------------------------------------------------------------------------*/
  445. /* Remark: Variables here without initial value shall be guaranteed zero/null
  446. / at start-up. If not, either the linker or start-up routine being used is
  447. / not compliance with C standard. */
  448. #if _VOLUMES < 1 || _VOLUMES > 9
  449. #error Wrong _VOLUMES setting
  450. #endif
  451. static WORD Fsid; /* File system mount ID */
  452. #if _FS_LOCK != 0
  453. static FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */
  454. #endif
  455. #if _USE_LFN == 0 /* Non-LFN configuration */
  456. #define DEF_NAMBUF
  457. #define INIT_NAMBUF(fs)
  458. #define FREE_NAMBUF()
  459. #else
  460. #if _MAX_LFN < 12 || _MAX_LFN > 255
  461. #error Wrong _MAX_LFN setting
  462. #endif
  463. #if _USE_LFN == 1 /* LFN enabled with static working buffer */
  464. #if _FS_EXFAT
  465. static BYTE DirBuf[SZDIRE*19]; /* Directory entry block scratchpad buffer (19 entries in size) */
  466. #endif
  467. static WCHAR LfnBuf[_MAX_LFN+1]; /* LFN enabled with static working buffer */
  468. #define DEF_NAMBUF
  469. #define INIT_NAMBUF(fs)
  470. #define FREE_NAMBUF()
  471. #elif _USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
  472. #if _FS_EXFAT
  473. #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1]; BYTE dbuf[SZDIRE*19];
  474. #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; (fs)->dirbuf = dbuf; }
  475. #define FREE_NAMBUF()
  476. #else
  477. #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1];
  478. #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; }
  479. #define FREE_NAMBUF()
  480. #endif
  481. #elif _USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
  482. #if _FS_EXFAT
  483. #define DEF_NAMBUF WCHAR *lfn;
  484. #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2 + SZDIRE*19); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; (fs)->dirbuf = (BYTE*)(lfn+_MAX_LFN+1); }
  485. #define FREE_NAMBUF() ff_memfree(lfn)
  486. #else
  487. #define DEF_NAMBUF WCHAR *lfn;
  488. #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; }
  489. #define FREE_NAMBUF() ff_memfree(lfn)
  490. #endif
  491. #else
  492. #error Wrong _USE_LFN setting
  493. #endif
  494. #endif
  495. #ifdef _EXCVT
  496. static const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for SBCS extended characters */
  497. #endif
  498. /*--------------------------------------------------------------------------
  499. Module Private Functions
  500. ---------------------------------------------------------------------------*/
  501. /*-----------------------------------------------------------------------*/
  502. /* Load/Store multi-byte word in the FAT structure */
  503. /*-----------------------------------------------------------------------*/
  504. static
  505. WORD ld_word (const BYTE* ptr) /* Load a 2-byte little-endian word */
  506. {
  507. WORD rv;
  508. rv = ptr[1];
  509. rv = rv << 8 | ptr[0];
  510. return rv;
  511. }
  512. static
  513. DWORD ld_dword (const BYTE* ptr) /* Load a 4-byte little-endian word */
  514. {
  515. DWORD rv;
  516. rv = ptr[3];
  517. rv = rv << 8 | ptr[2];
  518. rv = rv << 8 | ptr[1];
  519. rv = rv << 8 | ptr[0];
  520. return rv;
  521. }
  522. #if _FS_EXFAT
  523. static
  524. QWORD ld_qword (const BYTE* ptr) /* Load an 8-byte little-endian word */
  525. {
  526. QWORD rv;
  527. rv = ptr[7];
  528. rv = rv << 8 | ptr[6];
  529. rv = rv << 8 | ptr[5];
  530. rv = rv << 8 | ptr[4];
  531. rv = rv << 8 | ptr[3];
  532. rv = rv << 8 | ptr[2];
  533. rv = rv << 8 | ptr[1];
  534. rv = rv << 8 | ptr[0];
  535. return rv;
  536. }
  537. #endif
  538. #if !_FS_READONLY
  539. static
  540. void st_word (BYTE* ptr, WORD val) /* Store a 2-byte word in little-endian */
  541. {
  542. *ptr++ = (BYTE)val; val >>= 8;
  543. *ptr++ = (BYTE)val;
  544. }
  545. static
  546. void st_dword (BYTE* ptr, DWORD val) /* Store a 4-byte word in little-endian */
  547. {
  548. *ptr++ = (BYTE)val; val >>= 8;
  549. *ptr++ = (BYTE)val; val >>= 8;
  550. *ptr++ = (BYTE)val; val >>= 8;
  551. *ptr++ = (BYTE)val;
  552. }
  553. #if _FS_EXFAT
  554. static
  555. void st_qword (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-endian */
  556. {
  557. *ptr++ = (BYTE)val; val >>= 8;
  558. *ptr++ = (BYTE)val; val >>= 8;
  559. *ptr++ = (BYTE)val; val >>= 8;
  560. *ptr++ = (BYTE)val; val >>= 8;
  561. *ptr++ = (BYTE)val; val >>= 8;
  562. *ptr++ = (BYTE)val; val >>= 8;
  563. *ptr++ = (BYTE)val; val >>= 8;
  564. *ptr++ = (BYTE)val;
  565. }
  566. #endif
  567. #endif /* !_FS_READONLY */
  568. /*-----------------------------------------------------------------------*/
  569. /* String functions */
  570. /*-----------------------------------------------------------------------*/
  571. // These were originally provided by the FatFs library but we use externally
  572. // provided versions from C stdlib to (hopefully) reduce code size and use
  573. // more efficient versions.
  574. #define mem_cpy memcpy
  575. #define mem_set memset
  576. #define mem_cmp memcmp
  577. /* Check if chr is contained in the string */
  578. static
  579. int chk_chr (const char* str, int chr) { /* NZ:contained, ZR:not contained */
  580. while (*str && *str != chr) str++;
  581. return *str;
  582. }
  583. #if _FS_REENTRANT
  584. /*-----------------------------------------------------------------------*/
  585. /* Request/Release grant to access the volume */
  586. /*-----------------------------------------------------------------------*/
  587. static
  588. int lock_fs (
  589. FATFS* fs /* File system object */
  590. )
  591. {
  592. return ff_req_grant(fs->sobj);
  593. }
  594. static
  595. void unlock_fs (
  596. FATFS* fs, /* File system object */
  597. FRESULT res /* Result code to be returned */
  598. )
  599. {
  600. if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {
  601. ff_rel_grant(fs->sobj);
  602. }
  603. }
  604. #endif
  605. #if _FS_LOCK != 0
  606. /*-----------------------------------------------------------------------*/
  607. /* File lock control functions */
  608. /*-----------------------------------------------------------------------*/
  609. static
  610. FRESULT chk_lock ( /* Check if the file can be accessed */
  611. DIR* dp, /* Directory object pointing the file to be checked */
  612. int acc /* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */
  613. )
  614. {
  615. UINT i, be;
  616. /* Search file semaphore table */
  617. for (i = be = 0; i < _FS_LOCK; i++) {
  618. if (Files[i].fs) { /* Existing entry */
  619. if (Files[i].fs == dp->obj.fs && /* Check if the object matched with an open object */
  620. Files[i].clu == dp->obj.sclust &&
  621. Files[i].ofs == dp->dptr) break;
  622. } else { /* Blank entry */
  623. be = 1;
  624. }
  625. }
  626. if (i == _FS_LOCK) { /* The object is not opened */
  627. return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new object? */
  628. }
  629. /* The object has been opened. Reject any open against writing file and all write mode open */
  630. return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  631. }
  632. static
  633. int enq_lock (void) /* Check if an entry is available for a new object */
  634. {
  635. UINT i;
  636. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  637. return (i == _FS_LOCK) ? 0 : 1;
  638. }
  639. static
  640. UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
  641. DIR* dp, /* Directory object pointing the file to register or increment */
  642. int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  643. )
  644. {
  645. UINT i;
  646. for (i = 0; i < _FS_LOCK; i++) { /* Find the object */
  647. if (Files[i].fs == dp->obj.fs &&
  648. Files[i].clu == dp->obj.sclust &&
  649. Files[i].ofs == dp->dptr) break;
  650. }
  651. if (i == _FS_LOCK) { /* Not opened. Register it as new. */
  652. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  653. if (i == _FS_LOCK) return 0; /* No free entry to register (int err) */
  654. Files[i].fs = dp->obj.fs;
  655. Files[i].clu = dp->obj.sclust;
  656. Files[i].ofs = dp->dptr;
  657. Files[i].ctr = 0;
  658. }
  659. if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
  660. Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
  661. return i + 1;
  662. }
  663. static
  664. FRESULT dec_lock ( /* Decrement object open counter */
  665. UINT i /* Semaphore index (1..) */
  666. )
  667. {
  668. WORD n;
  669. FRESULT res;
  670. if (--i < _FS_LOCK) { /* Shift index number origin from 0 */
  671. n = Files[i].ctr;
  672. if (n == 0x100) n = 0; /* If write mode open, delete the entry */
  673. if (n > 0) n--; /* Decrement read mode open count */
  674. Files[i].ctr = n;
  675. if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */
  676. res = FR_OK;
  677. } else {
  678. res = FR_INT_ERR; /* Invalid index nunber */
  679. }
  680. return res;
  681. }
  682. static
  683. void clear_lock ( /* Clear lock entries of the volume */
  684. FATFS *fs
  685. )
  686. {
  687. UINT i;
  688. for (i = 0; i < _FS_LOCK; i++) {
  689. if (Files[i].fs == fs) Files[i].fs = 0;
  690. }
  691. }
  692. #endif /* _FS_LOCK != 0 */
  693. /*-----------------------------------------------------------------------*/
  694. /* Move/Flush disk access window in the file system object */
  695. /*-----------------------------------------------------------------------*/
  696. #if !_FS_READONLY
  697. static
  698. FRESULT sync_window ( /* Returns FR_OK or FR_DISK_ERROR */
  699. FATFS* fs /* File system object */
  700. )
  701. {
  702. DWORD wsect;
  703. UINT nf;
  704. FRESULT res = FR_OK;
  705. if (fs->wflag) { /* Write back the sector if it is dirty */
  706. wsect = fs->winsect; /* Current sector number */
  707. if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK) {
  708. res = FR_DISK_ERR;
  709. } else {
  710. fs->wflag = 0;
  711. if (wsect - fs->fatbase < fs->fsize) { /* Is it in the FAT area? */
  712. for (nf = fs->n_fats; nf >= 2; nf--) { /* Reflect the change to all FAT copies */
  713. wsect += fs->fsize;
  714. disk_write(fs->drv, fs->win, wsect, 1);
  715. }
  716. }
  717. }
  718. }
  719. return res;
  720. }
  721. #endif
  722. static
  723. FRESULT move_window ( /* Returns FR_OK or FR_DISK_ERROR */
  724. FATFS* fs, /* File system object */
  725. DWORD sector /* Sector number to make appearance in the fs->win[] */
  726. )
  727. {
  728. FRESULT res = FR_OK;
  729. if (sector != fs->winsect) { /* Window offset changed? */
  730. #if !_FS_READONLY
  731. res = sync_window(fs); /* Write-back changes */
  732. #endif
  733. if (res == FR_OK) { /* Fill sector window with new data */
  734. if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK) {
  735. sector = 0xFFFFFFFF; /* Invalidate window if data is not reliable */
  736. res = FR_DISK_ERR;
  737. }
  738. fs->winsect = sector;
  739. }
  740. }
  741. return res;
  742. }
  743. #if !_FS_READONLY
  744. /*-----------------------------------------------------------------------*/
  745. /* Synchronize file system and strage device */
  746. /*-----------------------------------------------------------------------*/
  747. static
  748. FRESULT sync_fs ( /* FR_OK:succeeded, !=0:error */
  749. FATFS* fs /* File system object */
  750. )
  751. {
  752. FRESULT res;
  753. res = sync_window(fs);
  754. if (res == FR_OK) {
  755. /* Update FSInfo sector if needed */
  756. if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) {
  757. /* Create FSInfo structure */
  758. mem_set(fs->win, 0, SS(fs));
  759. st_word(fs->win + BS_55AA, 0xAA55);
  760. st_dword(fs->win + FSI_LeadSig, 0x41615252);
  761. st_dword(fs->win + FSI_StrucSig, 0x61417272);
  762. st_dword(fs->win + FSI_Free_Count, fs->free_clst);
  763. st_dword(fs->win + FSI_Nxt_Free, fs->last_clst);
  764. /* Write it into the FSInfo sector */
  765. fs->winsect = fs->volbase + 1;
  766. disk_write(fs->drv, fs->win, fs->winsect, 1);
  767. fs->fsi_flag = 0;
  768. }
  769. /* Make sure that no pending write process in the physical drive */
  770. if (disk_ioctl(fs->drv, CTRL_SYNC, 0) != RES_OK) res = FR_DISK_ERR;
  771. }
  772. return res;
  773. }
  774. #endif
  775. /*-----------------------------------------------------------------------*/
  776. /* Get sector# from cluster# */
  777. /*-----------------------------------------------------------------------*/
  778. static
  779. DWORD clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
  780. FATFS* fs, /* File system object */
  781. DWORD clst /* Cluster# to be converted */
  782. )
  783. {
  784. clst -= 2;
  785. if (clst >= fs->n_fatent - 2) return 0; /* Invalid cluster# */
  786. return clst * fs->csize + fs->database;
  787. }
  788. /*-----------------------------------------------------------------------*/
  789. /* FAT access - Read value of a FAT entry */
  790. /*-----------------------------------------------------------------------*/
  791. static
  792. DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */
  793. _FDID* obj, /* Corresponding object */
  794. DWORD clst /* Cluster number to get the value */
  795. )
  796. {
  797. UINT wc, bc;
  798. DWORD val;
  799. FATFS *fs = obj->fs;
  800. if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */
  801. val = 1; /* Internal error */
  802. } else {
  803. val = 0xFFFFFFFF; /* Default value falls on disk error */
  804. switch (fs->fs_type) {
  805. case FS_FAT12 :
  806. bc = (UINT)clst; bc += bc / 2;
  807. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  808. wc = fs->win[bc++ % SS(fs)];
  809. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  810. wc |= fs->win[bc % SS(fs)] << 8;
  811. val = (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
  812. break;
  813. case FS_FAT16 :
  814. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
  815. val = ld_word(fs->win + clst * 2 % SS(fs));
  816. break;
  817. case FS_FAT32 :
  818. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  819. val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x0FFFFFFF;
  820. break;
  821. #if _FS_EXFAT
  822. case FS_EXFAT :
  823. if (obj->objsize) {
  824. DWORD cofs = clst - obj->sclust; /* Offset from start cluster */
  825. DWORD clen = (DWORD)((obj->objsize - 1) / SS(fs)) / fs->csize; /* Number of clusters - 1 */
  826. if (obj->stat == 2) { /* Is there no valid chain on the FAT? */
  827. if (cofs <= clen) {
  828. val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* Generate the value */
  829. break;
  830. }
  831. }
  832. if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the contiguous part? */
  833. val = clst + 1; /* Generate the value */
  834. break;
  835. }
  836. if (obj->stat != 2) { /* Get value from FAT if FAT chain is valid */
  837. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  838. val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x7FFFFFFF;
  839. break;
  840. }
  841. }
  842. /* go next */
  843. #endif
  844. default:
  845. val = 1; /* Internal error */
  846. }
  847. }
  848. return val;
  849. }
  850. #if !_FS_READONLY
  851. /*-----------------------------------------------------------------------*/
  852. /* FAT access - Change value of a FAT entry */
  853. /*-----------------------------------------------------------------------*/
  854. static
  855. FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */
  856. FATFS* fs, /* Corresponding file system object */
  857. DWORD clst, /* FAT index number (cluster number) to be changed */
  858. DWORD val /* New value to be set to the entry */
  859. )
  860. {
  861. UINT bc;
  862. BYTE *p;
  863. FRESULT res = FR_INT_ERR;
  864. if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */
  865. switch (fs->fs_type) {
  866. case FS_FAT12 : /* Bitfield items */
  867. bc = (UINT)clst; bc += bc / 2;
  868. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  869. if (res != FR_OK) break;
  870. p = fs->win + bc++ % SS(fs);
  871. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  872. fs->wflag = 1;
  873. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  874. if (res != FR_OK) break;
  875. p = fs->win + bc % SS(fs);
  876. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  877. fs->wflag = 1;
  878. break;
  879. case FS_FAT16 : /* WORD aligned items */
  880. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  881. if (res != FR_OK) break;
  882. st_word(fs->win + clst * 2 % SS(fs), (WORD)val);
  883. fs->wflag = 1;
  884. break;
  885. case FS_FAT32 : /* DWORD aligned items */
  886. #if _FS_EXFAT
  887. case FS_EXFAT :
  888. #endif
  889. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  890. if (res != FR_OK) break;
  891. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  892. val = (val & 0x0FFFFFFF) | (ld_dword(fs->win + clst * 4 % SS(fs)) & 0xF0000000);
  893. }
  894. st_dword(fs->win + clst * 4 % SS(fs), val);
  895. fs->wflag = 1;
  896. break;
  897. }
  898. }
  899. return res;
  900. }
  901. #endif /* !_FS_READONLY */
  902. #if _FS_EXFAT && !_FS_READONLY
  903. /*-----------------------------------------------------------------------*/
  904. /* exFAT: Accessing FAT and Allocation Bitmap */
  905. /*-----------------------------------------------------------------------*/
  906. /*---------------------------------------------*/
  907. /* exFAT: Find a contiguous free cluster block */
  908. /*---------------------------------------------*/
  909. static
  910. DWORD find_bitmap ( /* 0:No free cluster, 2..:Free cluster found, 0xFFFFFFFF:Disk error */
  911. FATFS* fs, /* File system object */
  912. DWORD clst, /* Cluster number to scan from */
  913. DWORD ncl /* Number of contiguous clusters to find (1..) */
  914. )
  915. {
  916. BYTE bm, bv;
  917. UINT i;
  918. DWORD val, scl, ctr;
  919. clst -= 2; /* The first bit in the bitmap corresponds to cluster #2 */
  920. if (clst >= fs->n_fatent - 2) clst = 0;
  921. scl = val = clst; ctr = 0;
  922. for (;;) {
  923. if (move_window(fs, fs->database + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF; /* (assuming bitmap is located top of the cluster heap) */
  924. i = val / 8 % SS(fs); bm = 1 << (val % 8);
  925. do {
  926. do {
  927. bv = fs->win[i] & bm; bm <<= 1; /* Get bit value */
  928. if (++val >= fs->n_fatent - 2) { /* Next cluster (with wrap-around) */
  929. val = 0; bm = 0; i = 4096;
  930. }
  931. if (!bv) { /* Is it a free cluster? */
  932. if (++ctr == ncl) return scl + 2; /* Check run length */
  933. } else {
  934. scl = val; ctr = 0; /* Encountered a live cluster, restart to scan */
  935. }
  936. if (val == clst) return 0; /* All cluster scanned? */
  937. } while (bm);
  938. bm = 1;
  939. } while (++i < SS(fs));
  940. }
  941. }
  942. /*------------------------------------*/
  943. /* exFAT: Set/Clear a block of bitmap */
  944. /*------------------------------------*/
  945. static
  946. FRESULT change_bitmap (
  947. FATFS* fs, /* File system object */
  948. DWORD clst, /* Cluster number to change from */
  949. DWORD ncl, /* Number of clusters to be changed */
  950. int bv /* bit value to be set (0 or 1) */
  951. )
  952. {
  953. BYTE bm;
  954. UINT i;
  955. DWORD sect;
  956. clst -= 2; /* The first bit corresponds to cluster #2 */
  957. sect = fs->database + clst / 8 / SS(fs); /* Sector address (assuming bitmap is located top of the cluster heap) */
  958. i = clst / 8 % SS(fs); /* Byte offset in the sector */
  959. bm = 1 << (clst % 8); /* Bit mask in the byte */
  960. for (;;) {
  961. if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;
  962. do {
  963. do {
  964. if (bv == (int)((fs->win[i] & bm) != 0)) return FR_INT_ERR; /* Is the bit expected value? */
  965. fs->win[i] ^= bm; /* Flip the bit */
  966. fs->wflag = 1;
  967. if (--ncl == 0) return FR_OK; /* All bits processed? */
  968. } while (bm <<= 1); /* Next bit */
  969. bm = 1;
  970. } while (++i < SS(fs)); /* Next byte */
  971. i = 0;
  972. }
  973. }
  974. /*---------------------------------------------*/
  975. /* Complement contiguous part of the FAT chain */
  976. /*---------------------------------------------*/
  977. static
  978. FRESULT fill_fat_chain (
  979. _FDID* obj /* Pointer to the corresponding object */
  980. )
  981. {
  982. FRESULT res;
  983. DWORD cl, n;
  984. if (obj->stat == 3) { /* Has the object been changed 'fragmented'? */
  985. for (cl = obj->sclust, n = obj->n_cont; n; cl++, n--) { /* Create cluster chain on the FAT */
  986. res = put_fat(obj->fs, cl, cl + 1);
  987. if (res != FR_OK) return res;
  988. }
  989. obj->stat = 0; /* Change status 'FAT chain is valid' */
  990. }
  991. return FR_OK;
  992. }
  993. #endif /* _FS_EXFAT && !_FS_READONLY */
  994. #if !_FS_READONLY
  995. /*-----------------------------------------------------------------------*/
  996. /* FAT handling - Remove a cluster chain */
  997. /*-----------------------------------------------------------------------*/
  998. static
  999. FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */
  1000. _FDID* obj, /* Corresponding object */
  1001. DWORD clst, /* Cluster to remove a chain from */
  1002. DWORD pclst /* Previous cluster of clst (0:an entire chain) */
  1003. )
  1004. {
  1005. FRESULT res = FR_OK;
  1006. DWORD nxt;
  1007. FATFS *fs = obj->fs;
  1008. #if _FS_EXFAT || _USE_TRIM
  1009. DWORD scl = clst, ecl = clst;
  1010. #endif
  1011. #if _USE_TRIM
  1012. DWORD rt[2];
  1013. #endif
  1014. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */
  1015. /* Mark the previous cluster 'EOC' on the FAT if it exists */
  1016. if (pclst && (!_FS_EXFAT || fs->fs_type != FS_EXFAT || obj->stat != 2)) {
  1017. res = put_fat(fs, pclst, 0xFFFFFFFF);
  1018. if (res != FR_OK) return res;
  1019. }
  1020. /* Remove the chain */
  1021. do {
  1022. nxt = get_fat(obj, clst); /* Get cluster status */
  1023. if (nxt == 0) break; /* Empty cluster? */
  1024. if (nxt == 1) return FR_INT_ERR; /* Internal error? */
  1025. if (nxt == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error? */
  1026. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  1027. res = put_fat(fs, clst, 0); /* Mark the cluster 'free' on the FAT */
  1028. if (res != FR_OK) return res;
  1029. }
  1030. if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
  1031. fs->free_clst++;
  1032. fs->fsi_flag |= 1;
  1033. }
  1034. #if _FS_EXFAT || _USE_TRIM
  1035. if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
  1036. ecl = nxt;
  1037. } else { /* End of contiguous cluster block */
  1038. #if _FS_EXFAT
  1039. if (fs->fs_type == FS_EXFAT) {
  1040. res = change_bitmap(fs, scl, ecl - scl + 1, 0); /* Mark the cluster block 'free' on the bitmap */
  1041. if (res != FR_OK) return res;
  1042. }
  1043. #endif
  1044. #if _USE_TRIM
  1045. rt[0] = clust2sect(fs, scl); /* Start sector */
  1046. rt[1] = clust2sect(fs, ecl) + fs->csize - 1; /* End sector */
  1047. disk_ioctl(fs->drv, CTRL_TRIM, rt); /* Inform device the block can be erased */
  1048. #endif
  1049. scl = ecl = nxt;
  1050. }
  1051. #endif
  1052. clst = nxt; /* Next cluster */
  1053. } while (clst < fs->n_fatent); /* Repeat while not the last link */
  1054. #if _FS_EXFAT
  1055. if (fs->fs_type == FS_EXFAT) {
  1056. if (pclst == 0) { /* Does object have no chain? */
  1057. obj->stat = 0; /* Change the object status 'initial' */
  1058. } else {
  1059. if (obj->stat == 3 && pclst >= obj->sclust && pclst <= obj->sclust + obj->n_cont) { /* Did the chain got contiguous? */
  1060. obj->stat = 2; /* Change the object status 'contiguous' */
  1061. }
  1062. }
  1063. }
  1064. #endif
  1065. return FR_OK;
  1066. }
  1067. /*-----------------------------------------------------------------------*/
  1068. /* FAT handling - Stretch a chain or Create a new chain */
  1069. /*-----------------------------------------------------------------------*/
  1070. static
  1071. DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  1072. _FDID* obj, /* Corresponding object */
  1073. DWORD clst /* Cluster# to stretch, 0:Create a new chain */
  1074. )
  1075. {
  1076. DWORD cs, ncl, scl;
  1077. FRESULT res;
  1078. FATFS *fs = obj->fs;
  1079. if (clst == 0) { /* Create a new chain */
  1080. scl = fs->last_clst; /* Get suggested cluster to start from */
  1081. if (scl == 0 || scl >= fs->n_fatent) scl = 1;
  1082. }
  1083. else { /* Stretch current chain */
  1084. cs = get_fat(obj, clst); /* Check the cluster status */
  1085. if (cs < 2) return 1; /* Invalid value */
  1086. if (cs == 0xFFFFFFFF) return cs; /* A disk error occurred */
  1087. if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
  1088. scl = clst;
  1089. }
  1090. #if _FS_EXFAT
  1091. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1092. ncl = find_bitmap(fs, scl, 1); /* Find a free cluster */
  1093. if (ncl == 0 || ncl == 0xFFFFFFFF) return ncl; /* No free cluster or hard error? */
  1094. res = change_bitmap(fs, ncl, 1, 1); /* Mark the cluster 'in use' */
  1095. if (res == FR_INT_ERR) return 1;
  1096. if (res == FR_DISK_ERR) return 0xFFFFFFFF;
  1097. if (clst == 0) { /* Is it a new chain? */
  1098. obj->stat = 2; /* Set status 'contiguous chain' */
  1099. } else { /* This is a stretched chain */
  1100. if (obj->stat == 2 && ncl != scl + 1) { /* Is the chain got fragmented? */
  1101. obj->n_cont = scl - obj->sclust; /* Set size of the contiguous part */
  1102. obj->stat = 3; /* Change status 'just fragmented' */
  1103. }
  1104. }
  1105. } else
  1106. #endif
  1107. { /* On the FAT12/16/32 volume */
  1108. ncl = scl; /* Start cluster */
  1109. for (;;) {
  1110. ncl++; /* Next cluster */
  1111. if (ncl >= fs->n_fatent) { /* Check wrap-around */
  1112. ncl = 2;
  1113. if (ncl > scl) return 0; /* No free cluster */
  1114. }
  1115. cs = get_fat(obj, ncl); /* Get the cluster status */
  1116. if (cs == 0) break; /* Found a free cluster */
  1117. if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* An error occurred */
  1118. if (ncl == scl) return 0; /* No free cluster */
  1119. }
  1120. }
  1121. if (_FS_EXFAT && fs->fs_type == FS_EXFAT && obj->stat == 2) { /* Is it a contiguous chain? */
  1122. res = FR_OK; /* FAT does not need to be written */
  1123. } else {
  1124. res = put_fat(fs, ncl, 0xFFFFFFFF); /* Mark the new cluster 'EOC' */
  1125. if (res == FR_OK && clst) {
  1126. res = put_fat(fs, clst, ncl); /* Link it from the previous one if needed */
  1127. }
  1128. }
  1129. if (res == FR_OK) { /* Update FSINFO if function succeeded. */
  1130. fs->last_clst = ncl;
  1131. if (fs->free_clst < fs->n_fatent - 2) fs->free_clst--;
  1132. fs->fsi_flag |= 1;
  1133. } else {
  1134. ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; /* Failed. Create error status */
  1135. }
  1136. return ncl; /* Return new cluster number or error status */
  1137. }
  1138. #endif /* !_FS_READONLY */
  1139. #if _USE_FASTSEEK
  1140. /*-----------------------------------------------------------------------*/
  1141. /* FAT handling - Convert offset into cluster with link map table */
  1142. /*-----------------------------------------------------------------------*/
  1143. static
  1144. DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */
  1145. FIL* fp, /* Pointer to the file object */
  1146. FSIZE_t ofs /* File offset to be converted to cluster# */
  1147. )
  1148. {
  1149. DWORD cl, ncl, *tbl;
  1150. FATFS *fs = fp->obj.fs;
  1151. tbl = fp->cltbl + 1; /* Top of CLMT */
  1152. cl = (DWORD)(ofs / SS(fs) / fs->csize); /* Cluster order from top of the file */
  1153. for (;;) {
  1154. ncl = *tbl++; /* Number of cluters in the fragment */
  1155. if (ncl == 0) return 0; /* End of table? (error) */
  1156. if (cl < ncl) break; /* In this fragment? */
  1157. cl -= ncl; tbl++; /* Next fragment */
  1158. }
  1159. return cl + *tbl; /* Return the cluster number */
  1160. }
  1161. #endif /* _USE_FASTSEEK */
  1162. /*-----------------------------------------------------------------------*/
  1163. /* Directory handling - Set directory index */
  1164. /*-----------------------------------------------------------------------*/
  1165. static
  1166. FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
  1167. DIR* dp, /* Pointer to directory object */
  1168. DWORD ofs /* Offset of directory table */
  1169. )
  1170. {
  1171. DWORD csz, clst;
  1172. FATFS *fs = dp->obj.fs;
  1173. if (ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR) || ofs % SZDIRE) { /* Check range of offset and alignment */
  1174. return FR_INT_ERR;
  1175. }
  1176. dp->dptr = ofs; /* Set current offset */
  1177. clst = dp->obj.sclust; /* Table start cluster (0:root) */
  1178. if (clst == 0 && fs->fs_type >= FS_FAT32) { /* Replace cluster# 0 with root cluster# */
  1179. clst = fs->dirbase;
  1180. if (_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */
  1181. }
  1182. if (clst == 0) { /* Static table (root-directory in FAT12/16) */
  1183. if (ofs / SZDIRE >= fs->n_rootdir) return FR_INT_ERR; /* Is index out of range? */
  1184. dp->sect = fs->dirbase;
  1185. } else { /* Dynamic table (sub-directory or root-directory in FAT32+) */
  1186. csz = (DWORD)fs->csize * SS(fs); /* Bytes per cluster */
  1187. while (ofs >= csz) { /* Follow cluster chain */
  1188. clst = get_fat(&dp->obj, clst); /* Get next cluster */
  1189. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1190. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Reached to end of table or internal error */
  1191. ofs -= csz;
  1192. }
  1193. dp->sect = clust2sect(fs, clst);
  1194. }
  1195. dp->clust = clst; /* Current cluster# */
  1196. if (!dp->sect) return FR_INT_ERR;
  1197. dp->sect += ofs / SS(fs); /* Sector# of the directory entry */
  1198. dp->dir = fs->win + (ofs % SS(fs)); /* Pointer to the entry in the win[] */
  1199. return FR_OK;
  1200. }
  1201. /*-----------------------------------------------------------------------*/
  1202. /* Directory handling - Move directory table index next */
  1203. /*-----------------------------------------------------------------------*/
  1204. static
  1205. FRESULT dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
  1206. DIR* dp, /* Pointer to the directory object */
  1207. int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
  1208. )
  1209. {
  1210. DWORD ofs, clst;
  1211. FATFS *fs = dp->obj.fs;
  1212. #if !_FS_READONLY
  1213. UINT n;
  1214. #endif
  1215. ofs = dp->dptr + SZDIRE; /* Next entry */
  1216. if (!dp->sect || ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR)) return FR_NO_FILE; /* Report EOT when offset has reached max value */
  1217. if (ofs % SS(fs) == 0) { /* Sector changed? */
  1218. dp->sect++; /* Next sector */
  1219. if (!dp->clust) { /* Static table */
  1220. if (ofs / SZDIRE >= fs->n_rootdir) { /* Report EOT if it reached end of static table */
  1221. dp->sect = 0; return FR_NO_FILE;
  1222. }
  1223. }
  1224. else { /* Dynamic table */
  1225. if ((ofs / SS(fs) & (fs->csize - 1)) == 0) { /* Cluster changed? */
  1226. clst = get_fat(&dp->obj, dp->clust); /* Get next cluster */
  1227. if (clst <= 1) return FR_INT_ERR; /* Internal error */
  1228. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1229. if (clst >= fs->n_fatent) { /* Reached end of dynamic table */
  1230. #if !_FS_READONLY
  1231. if (!stretch) { /* If no stretch, report EOT */
  1232. dp->sect = 0; return FR_NO_FILE;
  1233. }
  1234. clst = create_chain(&dp->obj, dp->clust); /* Allocate a cluster */
  1235. if (clst == 0) return FR_DENIED; /* No free cluster */
  1236. if (clst == 1) return FR_INT_ERR; /* Internal error */
  1237. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1238. /* Clean-up the stretched table */
  1239. if (_FS_EXFAT) dp->obj.stat |= 4; /* The directory needs to be updated */
  1240. if (sync_window(fs) != FR_OK) return FR_DISK_ERR; /* Flush disk access window */
  1241. mem_set(fs->win, 0, SS(fs)); /* Clear window buffer */
  1242. for (n = 0, fs->winsect = clust2sect(fs, clst); n < fs->csize; n++, fs->winsect++) { /* Fill the new cluster with 0 */
  1243. fs->wflag = 1;
  1244. if (sync_window(fs) != FR_OK) return FR_DISK_ERR;
  1245. }
  1246. fs->winsect -= n; /* Restore window offset */
  1247. #else
  1248. if (!stretch) dp->sect = 0; /* If no stretch, report EOT (this is to suppress warning) */
  1249. dp->sect = 0; return FR_NO_FILE; /* Report EOT */
  1250. #endif
  1251. }
  1252. dp->clust = clst; /* Initialize data for new cluster */
  1253. dp->sect = clust2sect(fs, clst);
  1254. }
  1255. }
  1256. }
  1257. dp->dptr = ofs; /* Current entry */
  1258. dp->dir = fs->win + ofs % SS(fs); /* Pointer to the entry in the win[] */
  1259. return FR_OK;
  1260. }
  1261. #if !_FS_READONLY
  1262. /*-----------------------------------------------------------------------*/
  1263. /* Directory handling - Reserve a block of directory entries */
  1264. /*-----------------------------------------------------------------------*/
  1265. static
  1266. FRESULT dir_alloc ( /* FR_OK(0):succeeded, !=0:error */
  1267. DIR* dp, /* Pointer to the directory object */
  1268. UINT nent /* Number of contiguous entries to allocate */
  1269. )
  1270. {
  1271. FRESULT res;
  1272. UINT n;
  1273. FATFS *fs = dp->obj.fs;
  1274. res = dir_sdi(dp, 0);
  1275. if (res == FR_OK) {
  1276. n = 0;
  1277. do {
  1278. res = move_window(fs, dp->sect);
  1279. if (res != FR_OK) break;
  1280. #if _FS_EXFAT
  1281. if ((fs->fs_type == FS_EXFAT) ? (int)((dp->dir[XDIR_Type] & 0x80) == 0) : (int)(dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0)) {
  1282. #else
  1283. if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) {
  1284. #endif
  1285. if (++n == nent) break; /* A block of contiguous free entries is found */
  1286. } else {
  1287. n = 0; /* Not a blank entry. Restart to search */
  1288. }
  1289. res = dir_next(dp, 1);
  1290. } while (res == FR_OK); /* Next entry with table stretch enabled */
  1291. }
  1292. if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */
  1293. return res;
  1294. }
  1295. #endif /* !_FS_READONLY */
  1296. /*-----------------------------------------------------------------------*/
  1297. /* FAT: Directory handling - Load/Store start cluster number */
  1298. /*-----------------------------------------------------------------------*/
  1299. static
  1300. DWORD ld_clust ( /* Returns the top cluster value of the SFN entry */
  1301. FATFS* fs, /* Pointer to the fs object */
  1302. const BYTE* dir /* Pointer to the key entry */
  1303. )
  1304. {
  1305. DWORD cl;
  1306. cl = ld_word(dir + DIR_FstClusLO);
  1307. if (fs->fs_type == FS_FAT32) {
  1308. cl |= (DWORD)ld_word(dir + DIR_FstClusHI) << 16;
  1309. }
  1310. return cl;
  1311. }
  1312. #if !_FS_READONLY
  1313. static
  1314. void st_clust (
  1315. FATFS* fs, /* Pointer to the fs object */
  1316. BYTE* dir, /* Pointer to the key entry */
  1317. DWORD cl /* Value to be set */
  1318. )
  1319. {
  1320. st_word(dir + DIR_FstClusLO, (WORD)cl);
  1321. if (fs->fs_type == FS_FAT32) {
  1322. st_word(dir + DIR_FstClusHI, (WORD)(cl >> 16));
  1323. }
  1324. }
  1325. #endif
  1326. #if _USE_LFN != 0
  1327. /*------------------------------------------------------------------------*/
  1328. /* FAT-LFN: LFN handling */
  1329. /*------------------------------------------------------------------------*/
  1330. static
  1331. const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */
  1332. /*--------------------------------------------------------*/
  1333. /* FAT-LFN: Compare a part of file name with an LFN entry */
  1334. /*--------------------------------------------------------*/
  1335. static
  1336. int cmp_lfn ( /* 1:matched, 0:not matched */
  1337. const WCHAR* lfnbuf, /* Pointer to the LFN working buffer to be compared */
  1338. BYTE* dir /* Pointer to the directory entry containing the part of LFN */
  1339. )
  1340. {
  1341. UINT i, s;
  1342. WCHAR wc, uc;
  1343. if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
  1344. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  1345. for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
  1346. uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
  1347. if (wc) {
  1348. if (i >= _MAX_LFN || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */
  1349. return 0; /* Not matched */
  1350. }
  1351. wc = uc;
  1352. } else {
  1353. if (uc != 0xFFFF) return 0; /* Check filler */
  1354. }
  1355. }
  1356. if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) return 0; /* Last segment matched but different length */
  1357. return 1; /* The part of LFN matched */
  1358. }
  1359. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
  1360. /*-----------------------------------------------------*/
  1361. /* FAT-LFN: Pick a part of file name from an LFN entry */
  1362. /*-----------------------------------------------------*/
  1363. static
  1364. int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */
  1365. WCHAR* lfnbuf, /* Pointer to the LFN working buffer */
  1366. BYTE* dir /* Pointer to the LFN entry */
  1367. )
  1368. {
  1369. UINT i, s;
  1370. WCHAR wc, uc;
  1371. if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
  1372. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  1373. for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
  1374. uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
  1375. if (wc) {
  1376. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1377. lfnbuf[i++] = wc = uc; /* Store it */
  1378. } else {
  1379. if (uc != 0xFFFF) return 0; /* Check filler */
  1380. }
  1381. }
  1382. if (dir[LDIR_Ord] & LLEF) { /* Put terminator if it is the last LFN part */
  1383. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1384. lfnbuf[i] = 0;
  1385. }
  1386. return 1; /* The part of LFN is valid */
  1387. }
  1388. #endif
  1389. #if !_FS_READONLY
  1390. /*-----------------------------------------*/
  1391. /* FAT-LFN: Create an entry of LFN entries */
  1392. /*-----------------------------------------*/
  1393. static
  1394. void put_lfn (
  1395. const WCHAR* lfn, /* Pointer to the LFN */
  1396. BYTE* dir, /* Pointer to the LFN entry to be created */
  1397. BYTE ord, /* LFN order (1-20) */
  1398. BYTE sum /* Checksum of the corresponding SFN */
  1399. )
  1400. {
  1401. UINT i, s;
  1402. WCHAR wc;
  1403. dir[LDIR_Chksum] = sum; /* Set checksum */
  1404. dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
  1405. dir[LDIR_Type] = 0;
  1406. st_word(dir + LDIR_FstClusLO, 0);
  1407. i = (ord - 1) * 13; /* Get offset in the LFN working buffer */
  1408. s = wc = 0;
  1409. do {
  1410. if (wc != 0xFFFF) wc = lfn[i++]; /* Get an effective character */
  1411. st_word(dir + LfnOfs[s], wc); /* Put it */
  1412. if (wc == 0) wc = 0xFFFF; /* Padding characters for left locations */
  1413. } while (++s < 13);
  1414. if (wc == 0xFFFF || !lfn[i]) ord |= LLEF; /* Last LFN part is the start of LFN sequence */
  1415. dir[LDIR_Ord] = ord; /* Set the LFN order */
  1416. }
  1417. #endif /* !_FS_READONLY */
  1418. #endif /* _USE_LFN != 0 */
  1419. #if _USE_LFN != 0 && !_FS_READONLY
  1420. /*-----------------------------------------------------------------------*/
  1421. /* FAT-LFN: Create a Numbered SFN */
  1422. /*-----------------------------------------------------------------------*/
  1423. static
  1424. void gen_numname (
  1425. BYTE* dst, /* Pointer to the buffer to store numbered SFN */
  1426. const BYTE* src, /* Pointer to SFN */
  1427. const WCHAR* lfn, /* Pointer to LFN */
  1428. UINT seq /* Sequence number */
  1429. )
  1430. {
  1431. BYTE ns[8], c;
  1432. UINT i, j;
  1433. WCHAR wc;
  1434. DWORD sr;
  1435. mem_cpy(dst, src, 11);
  1436. if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */
  1437. sr = seq;
  1438. while (*lfn) { /* Create a CRC */
  1439. wc = *lfn++;
  1440. for (i = 0; i < 16; i++) {
  1441. sr = (sr << 1) + (wc & 1);
  1442. wc >>= 1;
  1443. if (sr & 0x10000) sr ^= 0x11021;
  1444. }
  1445. }
  1446. seq = (UINT)sr;
  1447. }
  1448. /* itoa (hexdecimal) */
  1449. i = 7;
  1450. do {
  1451. c = (BYTE)((seq % 16) + '0');
  1452. if (c > '9') c += 7;
  1453. ns[i--] = c;
  1454. seq /= 16;
  1455. } while (seq);
  1456. ns[i] = '~';
  1457. /* Append the number */
  1458. for (j = 0; j < i && dst[j] != ' '; j++) {
  1459. if (IsDBCS1(dst[j])) {
  1460. if (j == i - 1) break;
  1461. j++;
  1462. }
  1463. }
  1464. do {
  1465. dst[j++] = (i < 8) ? ns[i++] : ' ';
  1466. } while (j < 8);
  1467. }
  1468. #endif /* _USE_LFN != 0 && !_FS_READONLY */
  1469. #if _USE_LFN != 0
  1470. /*-----------------------------------------------------------------------*/
  1471. /* FAT-LFN: Calculate checksum of an SFN entry */
  1472. /*-----------------------------------------------------------------------*/
  1473. static
  1474. BYTE sum_sfn (
  1475. const BYTE* dir /* Pointer to the SFN entry */
  1476. )
  1477. {
  1478. BYTE sum = 0;
  1479. UINT n = 11;
  1480. do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
  1481. return sum;
  1482. }
  1483. #endif /* _USE_LFN != 0 */
  1484. #if _FS_EXFAT
  1485. /*-----------------------------------------------------------------------*/
  1486. /* exFAT: Checksum */
  1487. /*-----------------------------------------------------------------------*/
  1488. static
  1489. WORD xdir_sum ( /* Get checksum of the directoly block */
  1490. const BYTE* dir /* Directory entry block to be calculated */
  1491. )
  1492. {
  1493. UINT i, szblk;
  1494. WORD sum;
  1495. szblk = (dir[XDIR_NumSec] + 1) * SZDIRE;
  1496. for (i = sum = 0; i < szblk; i++) {
  1497. if (i == XDIR_SetSum) { /* Skip sum field */
  1498. i++;
  1499. } else {
  1500. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + dir[i];
  1501. }
  1502. }
  1503. return sum;
  1504. }
  1505. static
  1506. WORD xname_sum ( /* Get check sum (to be used as hash) of the name */
  1507. const WCHAR* name /* File name to be calculated */
  1508. )
  1509. {
  1510. WCHAR chr;
  1511. WORD sum = 0;
  1512. while ((chr = *name++) != 0) {
  1513. chr = ff_wtoupper(chr); /* File name needs to be ignored case */
  1514. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr & 0xFF);
  1515. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr >> 8);
  1516. }
  1517. return sum;
  1518. }
  1519. #if !_FS_READONLY && _USE_MKFS
  1520. static
  1521. DWORD xsum32 (
  1522. BYTE dat, /* Data to be sumed */
  1523. DWORD sum /* Previous value */
  1524. )
  1525. {
  1526. sum = ((sum & 1) ? 0x80000000 : 0) + (sum >> 1) + dat;
  1527. return sum;
  1528. }
  1529. #endif
  1530. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
  1531. /*------------------------------------------------------*/
  1532. /* exFAT: Get object information from a directory block */
  1533. /*------------------------------------------------------*/
  1534. static
  1535. void get_xdir_info (
  1536. BYTE* dirb, /* Pointer to the direcotry entry block 85+C0+C1s */
  1537. FILINFO* fno /* Buffer to store the extracted file information */
  1538. )
  1539. {
  1540. UINT di, si;
  1541. WCHAR w;
  1542. #if !_LFN_UNICODE
  1543. UINT nc;
  1544. #endif
  1545. /* Get file name */
  1546. #if _LFN_UNICODE
  1547. if (dirb[XDIR_NumName] <= _MAX_LFN) {
  1548. for (si = SZDIRE * 2, di = 0; di < dirb[XDIR_NumName]; si += 2, di++) {
  1549. if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
  1550. w = ld_word(dirb + si); /* Get a character */
  1551. fno->fname[di] = w; /* Store it */
  1552. }
  1553. } else {
  1554. di = 0; /* Buffer overflow and inaccessible object */
  1555. }
  1556. #else
  1557. for (si = SZDIRE * 2, di = nc = 0; nc < dirb[XDIR_NumName]; si += 2, nc++) {
  1558. if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
  1559. w = ld_word(dirb + si); /* Get a character */
  1560. w = ff_convert(w, 0); /* Unicode -> OEM */
  1561. if (w == 0) { di = 0; break; } /* Could not be converted and inaccessible object */
  1562. if (_DF1S && w >= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
  1563. fno->fname[di++] = (char)(w >> 8);
  1564. }
  1565. if (di >= _MAX_LFN) { di = 0; break; } /* Buffer overflow and inaccessible object */
  1566. fno->fname[di++] = (char)w;
  1567. }
  1568. #endif
  1569. if (di == 0) fno->fname[di++] = '?'; /* Inaccessible object? */
  1570. fno->fname[di] = 0; /* Terminate file name */
  1571. fno->altname[0] = 0; /* No SFN */
  1572. fno->fattrib = dirb[XDIR_Attr]; /* Attribute */
  1573. fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(dirb + XDIR_FileSize); /* Size */
  1574. fno->ftime = ld_word(dirb + XDIR_ModTime + 0); /* Time */
  1575. fno->fdate = ld_word(dirb + XDIR_ModTime + 2); /* Date */
  1576. }
  1577. #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
  1578. /*-----------------------------------*/
  1579. /* exFAT: Get a directry entry block */
  1580. /*-----------------------------------*/
  1581. static
  1582. FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */
  1583. DIR* dp /* Pointer to the reading direcotry object pointing the 85 entry */
  1584. )
  1585. {
  1586. FRESULT res;
  1587. UINT i, nent;
  1588. BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */
  1589. /* Load 85 entry */
  1590. res = move_window(dp->obj.fs, dp->sect);
  1591. if (res != FR_OK) return res;
  1592. if (dp->dir[XDIR_Type] != 0x85) return FR_INT_ERR;
  1593. mem_cpy(dirb, dp->dir, SZDIRE);
  1594. nent = dirb[XDIR_NumSec] + 1;
  1595. /* Load C0 entry */
  1596. res = dir_next(dp, 0);
  1597. if (res != FR_OK) return res;
  1598. res = move_window(dp->obj.fs, dp->sect);
  1599. if (res != FR_OK) return res;
  1600. if (dp->dir[XDIR_Type] != 0xC0) return FR_INT_ERR;
  1601. mem_cpy(dirb + SZDIRE, dp->dir, SZDIRE);
  1602. /* Load C1 entries */
  1603. if (nent < 3 || nent > 19) return FR_NO_FILE;
  1604. i = SZDIRE * 2; nent *= SZDIRE;
  1605. do {
  1606. res = dir_next(dp, 0);
  1607. if (res != FR_OK) return res;
  1608. res = move_window(dp->obj.fs, dp->sect);
  1609. if (res != FR_OK) return res;
  1610. if (dp->dir[XDIR_Type] != 0xC1) return FR_INT_ERR;
  1611. mem_cpy(dirb + i, dp->dir, SZDIRE);
  1612. i += SZDIRE;
  1613. } while (i < nent);
  1614. /* Sanity check */
  1615. if (xdir_sum(dirb) != ld_word(dirb + XDIR_SetSum)) return FR_INT_ERR;
  1616. return FR_OK;
  1617. }
  1618. #if !_FS_READONLY || _FS_RPATH != 0
  1619. /*------------------------------------------------*/
  1620. /* exFAT: Load the object's directory entry block */
  1621. /*------------------------------------------------*/
  1622. static
  1623. FRESULT load_obj_dir (
  1624. DIR* dp, /* Blank directory object to be used to access containing direcotry */
  1625. const _FDID* obj /* Object with containing directory information */
  1626. )
  1627. {
  1628. FRESULT res;
  1629. /* Open object containing directory */
  1630. dp->obj.fs = obj->fs;
  1631. dp->obj.sclust = obj->c_scl;
  1632. dp->obj.stat = (BYTE)obj->c_size;
  1633. dp->obj.objsize = obj->c_size & 0xFFFFFF00;
  1634. dp->blk_ofs = obj->c_ofs;
  1635. res = dir_sdi(dp, dp->blk_ofs); /* Goto the block location */
  1636. if (res == FR_OK) {
  1637. res = load_xdir(dp); /* Load the object's entry block */
  1638. }
  1639. return res;
  1640. }
  1641. #endif
  1642. #if !_FS_READONLY
  1643. /*-----------------------------------------------*/
  1644. /* exFAT: Store the directory block to the media */
  1645. /*-----------------------------------------------*/
  1646. static
  1647. FRESULT store_xdir (
  1648. DIR* dp /* Pointer to the direcotry object */
  1649. )
  1650. {
  1651. FRESULT res;
  1652. UINT nent;
  1653. BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the direcotry entry block 85+C0+C1s */
  1654. /* Create set sum */
  1655. st_word(dirb + XDIR_SetSum, xdir_sum(dirb));
  1656. nent = dirb[XDIR_NumSec] + 1;
  1657. /* Store the set of directory to the volume */
  1658. res = dir_sdi(dp, dp->blk_ofs);
  1659. while (res == FR_OK) {
  1660. res = move_window(dp->obj.fs, dp->sect);
  1661. if (res != FR_OK) break;
  1662. mem_cpy(dp->dir, dirb, SZDIRE);
  1663. dp->obj.fs->wflag = 1;
  1664. if (--nent == 0) break;
  1665. dirb += SZDIRE;
  1666. res = dir_next(dp, 0);
  1667. }
  1668. return (res == FR_OK || res == FR_DISK_ERR) ? res : FR_INT_ERR;
  1669. }
  1670. /*-------------------------------------------*/
  1671. /* exFAT: Create a new directory enrty block */
  1672. /*-------------------------------------------*/
  1673. static
  1674. void create_xdir (
  1675. BYTE* dirb, /* Pointer to the direcotry entry block buffer */
  1676. const WCHAR* lfn /* Pointer to the nul terminated file name */
  1677. )
  1678. {
  1679. UINT i;
  1680. BYTE nb, nc;
  1681. WCHAR chr;
  1682. mem_set(dirb, 0, 2 * SZDIRE); /* Initialize 85+C0 entry */
  1683. dirb[XDIR_Type] = 0x85;
  1684. dirb[XDIR_Type + SZDIRE] = 0xC0;
  1685. st_word(dirb + XDIR_NameHash, xname_sum(lfn)); /* Set name hash */
  1686. i = SZDIRE * 2; /* C1 offset */
  1687. nc = 0; nb = 1; chr = 1;
  1688. do {
  1689. dirb[i++] = 0xC1; dirb[i++] = 0; /* Entry type C1 */
  1690. do { /* Fill name field */
  1691. if (chr && (chr = lfn[nc]) != 0) nc++; /* Get a character if exist */
  1692. st_word(dirb + i, chr); i += 2; /* Store it */
  1693. } while (i % SZDIRE);
  1694. nb++;
  1695. } while (lfn[nc]); /* Fill next entry if any char follows */
  1696. dirb[XDIR_NumName] = nc; /* Set name length */
  1697. dirb[XDIR_NumSec] = nb; /* Set number of C0+C1s */
  1698. }
  1699. #endif /* !_FS_READONLY */
  1700. #endif /* _FS_EXFAT */
  1701. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
  1702. /*-----------------------------------------------------------------------*/
  1703. /* Read an object from the directory */
  1704. /*-----------------------------------------------------------------------*/
  1705. static
  1706. FRESULT dir_read (
  1707. DIR* dp, /* Pointer to the directory object */
  1708. int vol /* Filtered by 0:file/directory or 1:volume label */
  1709. )
  1710. {
  1711. FRESULT res = FR_NO_FILE;
  1712. FATFS *fs = dp->obj.fs;
  1713. BYTE a, c;
  1714. #if _USE_LFN != 0
  1715. BYTE ord = 0xFF, sum = 0xFF;
  1716. #endif
  1717. while (dp->sect) {
  1718. res = move_window(fs, dp->sect);
  1719. if (res != FR_OK) break;
  1720. c = dp->dir[DIR_Name]; /* Test for the entry type */
  1721. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of the directory */
  1722. #if _FS_EXFAT
  1723. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1724. if (_USE_LABEL && vol) {
  1725. if (c == 0x83) break; /* Volume label entry? */
  1726. } else {
  1727. if (c == 0x85) { /* Start of the file entry block? */
  1728. dp->blk_ofs = dp->dptr; /* Get location of the block */
  1729. res = load_xdir(dp); /* Load the entry block */
  1730. if (res == FR_OK) {
  1731. dp->obj.attr = fs->dirbuf[XDIR_Attr] & AM_MASK; /* Get attribute */
  1732. }
  1733. break;
  1734. }
  1735. }
  1736. } else
  1737. #endif
  1738. { /* On the FAT12/16/32 volume */
  1739. dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK; /* Get attribute */
  1740. #if _USE_LFN != 0 /* LFN configuration */
  1741. if (c == DDEM || c == '.' || (int)((a & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */
  1742. ord = 0xFF;
  1743. } else {
  1744. if (a == AM_LFN) { /* An LFN entry is found */
  1745. if (c & LLEF) { /* Is it start of an LFN sequence? */
  1746. sum = dp->dir[LDIR_Chksum];
  1747. c &= (BYTE)~LLEF; ord = c;
  1748. dp->blk_ofs = dp->dptr;
  1749. }
  1750. /* Check LFN validity and capture it */
  1751. ord = (c == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  1752. } else { /* An SFN entry is found */
  1753. if (ord || sum != sum_sfn(dp->dir)) { /* Is there a valid LFN? */
  1754. dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */
  1755. }
  1756. break;
  1757. }
  1758. }
  1759. #else /* Non LFN configuration */
  1760. if (c != DDEM && c != '.' && a != AM_LFN && (int)((a & ~AM_ARC) == AM_VOL) == vol) { /* Is it a valid entry? */
  1761. break;
  1762. }
  1763. #endif
  1764. }
  1765. res = dir_next(dp, 0); /* Next entry */
  1766. if (res != FR_OK) break;
  1767. }
  1768. if (res != FR_OK) dp->sect = 0; /* Terminate the read operation on error or EOT */
  1769. return res;
  1770. }
  1771. #endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */
  1772. /*-----------------------------------------------------------------------*/
  1773. /* Directory handling - Find an object in the directory */
  1774. /*-----------------------------------------------------------------------*/
  1775. static
  1776. FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */
  1777. DIR* dp /* Pointer to the directory object with the file name */
  1778. )
  1779. {
  1780. FRESULT res;
  1781. FATFS *fs = dp->obj.fs;
  1782. BYTE c;
  1783. #if _USE_LFN != 0
  1784. BYTE a, ord, sum;
  1785. #endif
  1786. res = dir_sdi(dp, 0); /* Rewind directory object */
  1787. if (res != FR_OK) return res;
  1788. #if _FS_EXFAT
  1789. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1790. BYTE nc;
  1791. UINT di, ni;
  1792. WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */
  1793. while ((res = dir_read(dp, 0)) == FR_OK) { /* Read an item */
  1794. if (ld_word(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip the comparison if hash value mismatched */
  1795. for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */
  1796. if ((di % SZDIRE) == 0) di += 2;
  1797. if (ff_wtoupper(ld_word(fs->dirbuf + di)) != ff_wtoupper(fs->lfnbuf[ni])) break;
  1798. }
  1799. if (nc == 0 && !fs->lfnbuf[ni]) break; /* Name matched? */
  1800. }
  1801. return res;
  1802. }
  1803. #endif
  1804. /* On the FAT12/16/32 volume */
  1805. #if _USE_LFN != 0
  1806. ord = sum = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1807. #endif
  1808. do {
  1809. res = move_window(fs, dp->sect);
  1810. if (res != FR_OK) break;
  1811. c = dp->dir[DIR_Name];
  1812. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  1813. #if _USE_LFN != 0 /* LFN configuration */
  1814. dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK;
  1815. if (c == DDEM || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  1816. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1817. } else {
  1818. if (a == AM_LFN) { /* An LFN entry is found */
  1819. if (!(dp->fn[NSFLAG] & NS_NOLFN)) {
  1820. if (c & LLEF) { /* Is it start of LFN sequence? */
  1821. sum = dp->dir[LDIR_Chksum];
  1822. c &= (BYTE)~LLEF; ord = c; /* LFN start order */
  1823. dp->blk_ofs = dp->dptr; /* Start offset of LFN */
  1824. }
  1825. /* Check validity of the LFN entry and compare it with given name */
  1826. ord = (c == ord && sum == dp->dir[LDIR_Chksum] && cmp_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  1827. }
  1828. } else { /* An SFN entry is found */
  1829. if (!ord && sum == sum_sfn(dp->dir)) break; /* LFN matched? */
  1830. if (!(dp->fn[NSFLAG] & NS_LOSS) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */
  1831. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1832. }
  1833. }
  1834. #else /* Non LFN configuration */
  1835. dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK;
  1836. if (!(dp->dir[DIR_Attr] & AM_VOL) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */
  1837. #endif
  1838. res = dir_next(dp, 0); /* Next entry */
  1839. } while (res == FR_OK);
  1840. return res;
  1841. }
  1842. #if !_FS_READONLY
  1843. /*-----------------------------------------------------------------------*/
  1844. /* Register an object to the directory */
  1845. /*-----------------------------------------------------------------------*/
  1846. static
  1847. FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */
  1848. DIR* dp /* Target directory with object name to be created */
  1849. )
  1850. {
  1851. FRESULT res;
  1852. FATFS *fs = dp->obj.fs;
  1853. #if _USE_LFN != 0 /* LFN configuration */
  1854. UINT n, nlen, nent;
  1855. BYTE sn[12], sum;
  1856. if (dp->fn[NSFLAG] & (NS_DOT | NS_NONAME)) return FR_INVALID_NAME; /* Check name validity */
  1857. for (nlen = 0; fs->lfnbuf[nlen]; nlen++) ; /* Get lfn length */
  1858. #if _FS_EXFAT
  1859. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1860. DIR dj;
  1861. nent = (nlen + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */
  1862. res = dir_alloc(dp, nent); /* Allocate entries */
  1863. if (res != FR_OK) return res;
  1864. dp->blk_ofs = dp->dptr - SZDIRE * (nent - 1); /* Set block position */
  1865. if (dp->obj.sclust != 0 && (dp->obj.stat & 4)) { /* Has the sub-directory been stretched? */
  1866. dp->obj.stat &= 3;
  1867. dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase object size by cluster size */
  1868. res = fill_fat_chain(&dp->obj); /* Complement FAT chain if needed */
  1869. if (res != FR_OK) return res;
  1870. res = load_obj_dir(&dj, &dp->obj);
  1871. if (res != FR_OK) return res; /* Load the object status */
  1872. st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize); /* Update the allocation status */
  1873. st_qword(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize);
  1874. fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1;
  1875. res = store_xdir(&dj); /* Store the object status */
  1876. if (res != FR_OK) return res;
  1877. }
  1878. create_xdir(fs->dirbuf, fs->lfnbuf); /* Create on-memory directory block to be written later */
  1879. return FR_OK;
  1880. }
  1881. #endif
  1882. /* On the FAT12/16/32 volume */
  1883. mem_cpy(sn, dp->fn, 12);
  1884. if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
  1885. dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */
  1886. for (n = 1; n < 100; n++) {
  1887. gen_numname(dp->fn, sn, fs->lfnbuf, n); /* Generate a numbered name */
  1888. res = dir_find(dp); /* Check if the name collides with existing SFN */
  1889. if (res != FR_OK) break;
  1890. }
  1891. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  1892. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  1893. dp->fn[NSFLAG] = sn[NSFLAG];
  1894. }
  1895. /* Create an SFN with/without LFNs. */
  1896. nent = (sn[NSFLAG] & NS_LFN) ? (nlen + 12) / 13 + 1 : 1; /* Number of entries to allocate */
  1897. res = dir_alloc(dp, nent); /* Allocate entries */
  1898. if (res == FR_OK && --nent) { /* Set LFN entry if needed */
  1899. res = dir_sdi(dp, dp->dptr - nent * SZDIRE);
  1900. if (res == FR_OK) {
  1901. sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */
  1902. do { /* Store LFN entries in bottom first */
  1903. res = move_window(fs, dp->sect);
  1904. if (res != FR_OK) break;
  1905. put_lfn(fs->lfnbuf, dp->dir, (BYTE)nent, sum);
  1906. fs->wflag = 1;
  1907. res = dir_next(dp, 0); /* Next entry */
  1908. } while (res == FR_OK && --nent);
  1909. }
  1910. }
  1911. #else /* Non LFN configuration */
  1912. res = dir_alloc(dp, 1); /* Allocate an entry for SFN */
  1913. #endif
  1914. /* Set SFN entry */
  1915. if (res == FR_OK) {
  1916. res = move_window(fs, dp->sect);
  1917. if (res == FR_OK) {
  1918. mem_set(dp->dir, 0, SZDIRE); /* Clean the entry */
  1919. mem_cpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */
  1920. #if _USE_LFN != 0
  1921. dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */
  1922. #endif
  1923. fs->wflag = 1;
  1924. }
  1925. }
  1926. return res;
  1927. }
  1928. #endif /* !_FS_READONLY */
  1929. #if !_FS_READONLY && _FS_MINIMIZE == 0
  1930. /*-----------------------------------------------------------------------*/
  1931. /* Remove an object from the directory */
  1932. /*-----------------------------------------------------------------------*/
  1933. static
  1934. FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
  1935. DIR* dp /* Directory object pointing the entry to be removed */
  1936. )
  1937. {
  1938. FRESULT res;
  1939. FATFS *fs = dp->obj.fs;
  1940. #if _USE_LFN != 0 /* LFN configuration */
  1941. DWORD last = dp->dptr;
  1942. res = (dp->blk_ofs == 0xFFFFFFFF) ? FR_OK : dir_sdi(dp, dp->blk_ofs); /* Goto top of the entry block if LFN is exist */
  1943. if (res == FR_OK) {
  1944. do {
  1945. res = move_window(fs, dp->sect);
  1946. if (res != FR_OK) break;
  1947. /* Mark an entry 'deleted' */
  1948. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1949. dp->dir[XDIR_Type] &= 0x7F;
  1950. } else { /* On the FAT12/16/32 volume */
  1951. dp->dir[DIR_Name] = DDEM;
  1952. }
  1953. fs->wflag = 1;
  1954. if (dp->dptr >= last) break; /* If reached last entry then all entries of the object has been deleted. */
  1955. res = dir_next(dp, 0); /* Next entry */
  1956. } while (res == FR_OK);
  1957. if (res == FR_NO_FILE) res = FR_INT_ERR;
  1958. }
  1959. #else /* Non LFN configuration */
  1960. res = move_window(fs, dp->sect);
  1961. if (res == FR_OK) {
  1962. dp->dir[DIR_Name] = DDEM;
  1963. fs->wflag = 1;
  1964. }
  1965. #endif
  1966. return res;
  1967. }
  1968. #endif /* !_FS_READONLY && _FS_MINIMIZE == 0 */
  1969. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
  1970. /*-----------------------------------------------------------------------*/
  1971. /* Get file information from directory entry */
  1972. /*-----------------------------------------------------------------------*/
  1973. static
  1974. void get_fileinfo ( /* No return code */
  1975. DIR* dp, /* Pointer to the directory object */
  1976. FILINFO* fno /* Pointer to the file information to be filled */
  1977. )
  1978. {
  1979. UINT i, j;
  1980. TCHAR c;
  1981. DWORD tm;
  1982. #if _USE_LFN != 0
  1983. WCHAR w, lfv;
  1984. FATFS *fs = dp->obj.fs;
  1985. #endif
  1986. fno->fname[0] = 0; /* Invaidate file info */
  1987. if (!dp->sect) return; /* Exit if read pointer has reached end of directory */
  1988. #if _USE_LFN != 0 /* LFN configuration */
  1989. #if _FS_EXFAT
  1990. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1991. get_xdir_info(fs->dirbuf, fno);
  1992. return;
  1993. } else
  1994. #endif
  1995. { /* On the FAT12/16/32 volume */
  1996. if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */
  1997. i = j = 0;
  1998. while ((w = fs->lfnbuf[j++]) != 0) { /* Get an LFN character */
  1999. #if !_LFN_UNICODE
  2000. w = ff_convert(w, 0); /* Unicode -> OEM */
  2001. if (w == 0) { i = 0; break; } /* No LFN if it could not be converted */
  2002. if (_DF1S && w >= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
  2003. fno->fname[i++] = (char)(w >> 8);
  2004. }
  2005. #endif
  2006. if (i >= _MAX_LFN) { i = 0; break; } /* No LFN if buffer overflow */
  2007. fno->fname[i++] = (TCHAR)w;
  2008. }
  2009. fno->fname[i] = 0; /* Terminate the LFN */
  2010. }
  2011. }
  2012. i = j = 0;
  2013. lfv = fno->fname[i]; /* LFN is exist if non-zero */
  2014. while (i < 11) { /* Copy name body and extension */
  2015. c = (TCHAR)dp->dir[i++];
  2016. if (c == ' ') continue; /* Skip padding spaces */
  2017. if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
  2018. if (i == 9) { /* Insert a . if extension is exist */
  2019. if (!lfv) fno->fname[j] = '.';
  2020. fno->altname[j++] = '.';
  2021. }
  2022. #if _LFN_UNICODE
  2023. if (IsDBCS1(c) && i != 8 && i != 11 && IsDBCS2(dp->dir[i])) {
  2024. c = c << 8 | dp->dir[i++];
  2025. }
  2026. c = ff_convert(c, 1); /* OEM -> Unicode */
  2027. if (!c) c = '?';
  2028. #endif
  2029. fno->altname[j] = c;
  2030. if (!lfv) {
  2031. if (IsUpper(c) && (dp->dir[DIR_NTres] & (i >= 9 ? NS_EXT : NS_BODY))) {
  2032. c += 0x20; /* To lower */
  2033. }
  2034. fno->fname[j] = c;
  2035. }
  2036. j++;
  2037. }
  2038. if (!lfv) {
  2039. fno->fname[j] = 0;
  2040. if (!dp->dir[DIR_NTres]) j = 0; /* Altname is no longer needed if neither LFN nor case info is exist. */
  2041. }
  2042. fno->altname[j] = 0; /* Terminate the SFN */
  2043. #else /* Non-LFN configuration */
  2044. i = j = 0;
  2045. while (i < 11) { /* Copy name body and extension */
  2046. c = (TCHAR)dp->dir[i++];
  2047. if (c == ' ') continue; /* Skip padding spaces */
  2048. if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
  2049. if (i == 9) fno->fname[j++] = '.'; /* Insert a . if extension is exist */
  2050. fno->fname[j++] = c;
  2051. }
  2052. fno->fname[j] = 0;
  2053. #endif
  2054. fno->fattrib = dp->dir[DIR_Attr]; /* Attribute */
  2055. fno->fsize = ld_dword(dp->dir + DIR_FileSize); /* Size */
  2056. tm = ld_dword(dp->dir + DIR_ModTime); /* Timestamp */
  2057. fno->ftime = (WORD)tm; fno->fdate = (WORD)(tm >> 16);
  2058. }
  2059. #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
  2060. #if _USE_FIND && _FS_MINIMIZE <= 1
  2061. /*-----------------------------------------------------------------------*/
  2062. /* Pattern matching */
  2063. /*-----------------------------------------------------------------------*/
  2064. static
  2065. WCHAR get_achar ( /* Get a character and advances ptr 1 or 2 */
  2066. const TCHAR** ptr /* Pointer to pointer to the SBCS/DBCS/Unicode string */
  2067. )
  2068. {
  2069. #if !_LFN_UNICODE
  2070. WCHAR chr;
  2071. chr = (BYTE)*(*ptr)++; /* Get a byte */
  2072. if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */
  2073. #ifdef _EXCVT
  2074. if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */
  2075. #else
  2076. if (IsDBCS1(chr) && IsDBCS2(**ptr)) { /* Get DBC 2nd byte if needed */
  2077. chr = chr << 8 | (BYTE)*(*ptr)++;
  2078. }
  2079. #endif
  2080. return chr;
  2081. #else
  2082. return ff_wtoupper(*(*ptr)++); /* Get a word and to upper */
  2083. #endif
  2084. }
  2085. static
  2086. int pattern_matching ( /* 0:not matched, 1:matched */
  2087. const TCHAR* pat, /* Matching pattern */
  2088. const TCHAR* nam, /* String to be tested */
  2089. int skip, /* Number of pre-skip chars (number of ?s) */
  2090. int inf /* Infinite search (* specified) */
  2091. )
  2092. {
  2093. const TCHAR *pp, *np;
  2094. WCHAR pc, nc;
  2095. int nm, nx;
  2096. while (skip--) { /* Pre-skip name chars */
  2097. if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */
  2098. }
  2099. if (!*pat && inf) return 1; /* (short circuit) */
  2100. do {
  2101. pp = pat; np = nam; /* Top of pattern and name to match */
  2102. for (;;) {
  2103. if (*pp == '?' || *pp == '*') { /* Wildcard? */
  2104. nm = nx = 0;
  2105. do { /* Analyze the wildcard chars */
  2106. if (*pp++ == '?') nm++; else nx = 1;
  2107. } while (*pp == '?' || *pp == '*');
  2108. if (pattern_matching(pp, np, nm, nx)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */
  2109. nc = *np; break; /* Branch mismatched */
  2110. }
  2111. pc = get_achar(&pp); /* Get a pattern char */
  2112. nc = get_achar(&np); /* Get a name char */
  2113. if (pc != nc) break; /* Branch mismatched? */
  2114. if (pc == 0) return 1; /* Branch matched? (matched at end of both strings) */
  2115. }
  2116. get_achar(&nam); /* nam++ */
  2117. } while (inf && nc); /* Retry until end of name if infinite search is specified */
  2118. return 0;
  2119. }
  2120. #endif /* _USE_FIND && _FS_MINIMIZE <= 1 */
  2121. /*-----------------------------------------------------------------------*/
  2122. /* Pick a top segment and create the object name in directory form */
  2123. /*-----------------------------------------------------------------------*/
  2124. static
  2125. FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */
  2126. DIR* dp, /* Pointer to the directory object */
  2127. const TCHAR** path /* Pointer to pointer to the segment in the path string */
  2128. )
  2129. {
  2130. #if _USE_LFN != 0 /* LFN configuration */
  2131. BYTE b, cf;
  2132. WCHAR w, *lfn;
  2133. UINT i, ni, si, di;
  2134. const TCHAR *p;
  2135. /* Create LFN in Unicode */
  2136. p = *path; lfn = dp->obj.fs->lfnbuf; si = di = 0;
  2137. for (;;) {
  2138. w = p[si++]; /* Get a character */
  2139. if (w < ' ') break; /* Break if end of the path name */
  2140. if (w == '/' || w == '\\') { /* Break if a separator is found */
  2141. while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */
  2142. break;
  2143. }
  2144. if (di >= _MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */
  2145. #if !_LFN_UNICODE
  2146. w &= 0xFF;
  2147. if (IsDBCS1(w)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  2148. b = (BYTE)p[si++]; /* Get 2nd byte */
  2149. w = (w << 8) + b; /* Create a DBC */
  2150. if (!IsDBCS2(b)) return FR_INVALID_NAME; /* Reject invalid sequence */
  2151. }
  2152. w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */
  2153. if (!w) return FR_INVALID_NAME; /* Reject invalid code */
  2154. #endif
  2155. if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */
  2156. lfn[di++] = w; /* Store the Unicode character */
  2157. }
  2158. *path = &p[si]; /* Return pointer to the next segment */
  2159. cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
  2160. #if _FS_RPATH != 0
  2161. if ((di == 1 && lfn[di - 1] == '.') ||
  2162. (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */
  2163. lfn[di] = 0;
  2164. for (i = 0; i < 11; i++) /* Create dot name for SFN entry */
  2165. dp->fn[i] = (i < di) ? '.' : ' ';
  2166. dp->fn[i] = cf | NS_DOT; /* This is a dot entry */
  2167. return FR_OK;
  2168. }
  2169. #endif
  2170. while (di) { /* Snip off trailing spaces and dots if exist */
  2171. w = lfn[di - 1];
  2172. if (w != ' ' && w != '.') break;
  2173. di--;
  2174. }
  2175. lfn[di] = 0; /* LFN is created */
  2176. if (di == 0) return FR_INVALID_NAME; /* Reject nul name */
  2177. /* Create SFN in directory form */
  2178. mem_set(dp->fn, ' ', 11);
  2179. for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
  2180. if (si) cf |= NS_LOSS | NS_LFN;
  2181. while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
  2182. i = b = 0; ni = 8;
  2183. for (;;) {
  2184. w = lfn[si++]; /* Get an LFN character */
  2185. if (!w) break; /* Break on end of the LFN */
  2186. if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
  2187. cf |= NS_LOSS | NS_LFN; continue;
  2188. }
  2189. if (i >= ni || si == di) { /* Extension or end of SFN */
  2190. if (ni == 11) { /* Long extension */
  2191. cf |= NS_LOSS | NS_LFN; break;
  2192. }
  2193. if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */
  2194. if (si > di) break; /* No extension */
  2195. si = di; i = 8; ni = 11; /* Enter extension section */
  2196. b <<= 2; continue;
  2197. }
  2198. if (w >= 0x80) { /* Non ASCII character */
  2199. #ifdef _EXCVT
  2200. w = ff_convert(w, 0); /* Unicode -> OEM code */
  2201. if (w) w = ExCvt[w - 0x80]; /* Convert extended character to upper (SBCS) */
  2202. #else
  2203. w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
  2204. #endif
  2205. cf |= NS_LFN; /* Force create LFN entry */
  2206. }
  2207. if (_DF1S && w >= 0x100) { /* Is this DBC? (always false at SBCS cfg) */
  2208. if (i >= ni - 1) {
  2209. cf |= NS_LOSS | NS_LFN; i = ni; continue;
  2210. }
  2211. dp->fn[i++] = (BYTE)(w >> 8);
  2212. } else { /* SBC */
  2213. if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal characters for SFN */
  2214. w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  2215. } else {
  2216. if (IsUpper(w)) { /* ASCII large capital */
  2217. b |= 2;
  2218. } else {
  2219. if (IsLower(w)) { /* ASCII small capital */
  2220. b |= 1; w -= 0x20;
  2221. }
  2222. }
  2223. }
  2224. }
  2225. dp->fn[i++] = (BYTE)w;
  2226. }
  2227. if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2228. if (ni == 8) b <<= 2;
  2229. if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) cf |= NS_LFN; /* Create LFN entry when there are composite capitals */
  2230. if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
  2231. if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */
  2232. if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */
  2233. }
  2234. dp->fn[NSFLAG] = cf; /* SFN is created */
  2235. return FR_OK;
  2236. #else /* _USE_LFN != 0 : Non-LFN configuration */
  2237. BYTE c, d, *sfn;
  2238. UINT ni, si, i;
  2239. const char *p;
  2240. /* Create file name in directory form */
  2241. p = *path; sfn = dp->fn;
  2242. mem_set(sfn, ' ', 11);
  2243. si = i = 0; ni = 8;
  2244. #if _FS_RPATH != 0
  2245. if (p[si] == '.') { /* Is this a dot entry? */
  2246. for (;;) {
  2247. c = (BYTE)p[si++];
  2248. if (c != '.' || si >= 3) break;
  2249. sfn[i++] = c;
  2250. }
  2251. if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
  2252. *path = p + si; /* Return pointer to the next segment */
  2253. sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */
  2254. return FR_OK;
  2255. }
  2256. #endif
  2257. for (;;) {
  2258. c = (BYTE)p[si++];
  2259. if (c <= ' ') break; /* Break if end of the path name */
  2260. if (c == '/' || c == '\\') { /* Break if a separator is found */
  2261. while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */
  2262. break;
  2263. }
  2264. if (c == '.' || i >= ni) { /* End of body or over size? */
  2265. if (ni == 11 || c != '.') return FR_INVALID_NAME; /* Over size or invalid dot */
  2266. i = 8; ni = 11; /* Goto extension */
  2267. continue;
  2268. }
  2269. if (c >= 0x80) { /* Extended character? */
  2270. #ifdef _EXCVT
  2271. c = ExCvt[c - 0x80]; /* To upper extended characters (SBCS cfg) */
  2272. #else
  2273. #if !_DF1S
  2274. return FR_INVALID_NAME; /* Reject extended characters (ASCII only cfg) */
  2275. #endif
  2276. #endif
  2277. }
  2278. if (IsDBCS1(c)) { /* Check if it is a DBC 1st byte (always false at SBCS cfg.) */
  2279. d = (BYTE)p[si++]; /* Get 2nd byte */
  2280. if (!IsDBCS2(d) || i >= ni - 1) return FR_INVALID_NAME; /* Reject invalid DBC */
  2281. sfn[i++] = c;
  2282. sfn[i++] = d;
  2283. } else { /* SBC */
  2284. if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */
  2285. if (IsLower(c)) c -= 0x20; /* To upper */
  2286. sfn[i++] = c;
  2287. }
  2288. }
  2289. *path = p + si; /* Return pointer to the next segment */
  2290. if (i == 0) return FR_INVALID_NAME; /* Reject nul string */
  2291. if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2292. sfn[NSFLAG] = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
  2293. return FR_OK;
  2294. #endif /* _USE_LFN != 0 */
  2295. }
  2296. /*-----------------------------------------------------------------------*/
  2297. /* Follow a file path */
  2298. /*-----------------------------------------------------------------------*/
  2299. static
  2300. FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  2301. DIR* dp, /* Directory object to return last directory and found object */
  2302. const TCHAR* path /* Full-path string to find a file or directory */
  2303. )
  2304. {
  2305. FRESULT res;
  2306. BYTE ns;
  2307. _FDID *obj = &dp->obj;
  2308. FATFS *fs = obj->fs;
  2309. #if _FS_RPATH != 0
  2310. if (*path != '/' && *path != '\\') { /* Without heading separator */
  2311. obj->sclust = fs->cdir; /* Start from the current directory */
  2312. } else
  2313. #endif
  2314. { /* With heading separator */
  2315. while (*path == '/' || *path == '\\') path++; /* Strip heading separator */
  2316. obj->sclust = 0; /* Start from the root directory */
  2317. }
  2318. #if _FS_EXFAT && _FS_RPATH != 0
  2319. if (fs->fs_type == FS_EXFAT && obj->sclust) { /* Retrieve the sub-directory status if needed */
  2320. DIR dj;
  2321. obj->c_scl = fs->cdc_scl;
  2322. obj->c_size = fs->cdc_size;
  2323. obj->c_ofs = fs->cdc_ofs;
  2324. res = load_obj_dir(&dj, obj);
  2325. if (res != FR_OK) return res;
  2326. obj->objsize = ld_dword(fs->dirbuf + XDIR_FileSize);
  2327. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2328. }
  2329. #endif
  2330. if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */
  2331. dp->fn[NSFLAG] = NS_NONAME;
  2332. res = dir_sdi(dp, 0);
  2333. } else { /* Follow path */
  2334. for (;;) {
  2335. res = create_name(dp, &path); /* Get a segment name of the path */
  2336. if (res != FR_OK) break;
  2337. res = dir_find(dp); /* Find an object with the segment name */
  2338. ns = dp->fn[NSFLAG];
  2339. if (res != FR_OK) { /* Failed to find the object */
  2340. if (res == FR_NO_FILE) { /* Object is not found */
  2341. if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, stay there */
  2342. if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */
  2343. dp->fn[NSFLAG] = NS_NONAME;
  2344. res = FR_OK;
  2345. } else { /* Could not find the object */
  2346. if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */
  2347. }
  2348. }
  2349. break;
  2350. }
  2351. if (ns & NS_LAST) break; /* Last segment matched. Function completed. */
  2352. /* Get into the sub-directory */
  2353. if (!(obj->attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */
  2354. res = FR_NO_PATH; break;
  2355. }
  2356. #if _FS_EXFAT
  2357. if (fs->fs_type == FS_EXFAT) {
  2358. obj->c_scl = obj->sclust; /* Save containing directory information for next dir */
  2359. obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
  2360. obj->c_ofs = dp->blk_ofs;
  2361. obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Open next directory */
  2362. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2363. obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2364. } else
  2365. #endif
  2366. {
  2367. obj->sclust = ld_clust(fs, fs->win + dp->dptr % SS(fs)); /* Open next directory */
  2368. }
  2369. }
  2370. }
  2371. return res;
  2372. }
  2373. /*-----------------------------------------------------------------------*/
  2374. /* Load a sector and check if it is an FAT boot sector */
  2375. /*-----------------------------------------------------------------------*/
  2376. static
  2377. BYTE check_fs ( /* 0:FAT, 1:exFAT, 2:Valid BS but not FAT, 3:Not a BS, 4:Disk error */
  2378. FATFS* fs, /* File system object */
  2379. DWORD sect /* Sector# (lba) to check if it is an FAT-VBR or not */
  2380. )
  2381. {
  2382. fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */
  2383. if (move_window(fs, sect) != FR_OK) return 4; /* Load boot record */
  2384. if (ld_word(fs->win + BS_55AA) != 0xAA55) return 3; /* Check boot record signature (always placed at offset 510 even if the sector size is >512) */
  2385. if (fs->win[BS_JmpBoot] == 0xE9 || (fs->win[BS_JmpBoot] == 0xEB && fs->win[BS_JmpBoot + 2] == 0x90)) {
  2386. if ((ld_dword(fs->win + BS_FilSysType) & 0xFFFFFF) == 0x544146) return 0; /* Check "FAT" string */
  2387. if (ld_dword(fs->win + BS_FilSysType32) == 0x33544146) return 0; /* Check "FAT3" string */
  2388. }
  2389. #if _FS_EXFAT
  2390. if (!mem_cmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1;
  2391. #endif
  2392. return 2;
  2393. }
  2394. /*-----------------------------------------------------------------------*/
  2395. /* Find logical drive and check if the volume is mounted */
  2396. /*-----------------------------------------------------------------------*/
  2397. static
  2398. FRESULT find_volume ( /* FR_OK(0): successful, !=0: any error occurred */
  2399. FATFS* fs, /* Pointer to the file system object */
  2400. BYTE mode /* !=0: Check write protection for write access */
  2401. )
  2402. {
  2403. BYTE fmt, *pt;
  2404. DSTATUS stat;
  2405. DWORD bsect, fasize, tsect, sysect, nclst, szbfat, br[4];
  2406. WORD nrsv;
  2407. UINT i;
  2408. ENTER_FF(fs); /* Lock the volume */
  2409. mode &= (BYTE)~FA_READ; /* Desired access mode, write access or not */
  2410. if (fs->fs_type) { /* If the volume has been mounted */
  2411. disk_ioctl(fs->drv, IOCTL_STATUS, &stat);
  2412. if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */
  2413. if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check write protection if needed */
  2414. return FR_WRITE_PROTECTED;
  2415. }
  2416. return FR_OK; /* The file system object is valid */
  2417. }
  2418. }
  2419. /* The file system object is not valid. */
  2420. /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
  2421. fs->fs_type = 0; /* Clear the file system object */
  2422. disk_ioctl(fs->drv, IOCTL_INIT, &stat); /* Initialize the physical drive */
  2423. if (stat & STA_NOINIT) { /* Check if the initialization succeeded */
  2424. return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
  2425. }
  2426. if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check disk write protection if needed */
  2427. return FR_WRITE_PROTECTED;
  2428. }
  2429. #if _MAX_SS != _MIN_SS /* Get sector size (multiple sector size cfg only) */
  2430. if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK) return FR_DISK_ERR;
  2431. if (SS(fs) > _MAX_SS || SS(fs) < _MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;
  2432. #endif
  2433. /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */
  2434. bsect = 0;
  2435. fmt = check_fs(fs, bsect); /* Load sector 0 and check if it is an FAT-VBR as SFD */
  2436. if (fmt == 2 || (fmt < 2 && LD2PT(fs) != 0)) { /* Not an FAT-VBR or forced partition number */
  2437. for (i = 0; i < 4; i++) { /* Get partition offset */
  2438. pt = fs->win + (MBR_Table + i * SZ_PTE);
  2439. br[i] = pt[PTE_System] ? ld_dword(pt + PTE_StLba) : 0;
  2440. }
  2441. i = LD2PT(fs); /* Partition number: 0:auto, 1-4:forced */
  2442. if (i) i--;
  2443. do { /* Find an FAT volume */
  2444. bsect = br[i];
  2445. fmt = bsect ? check_fs(fs, bsect) : 3; /* Check the partition */
  2446. } while (!LD2PT(fs) && fmt >= 2 && ++i < 4);
  2447. }
  2448. if (fmt == 4) return FR_DISK_ERR; /* An error occured in the disk I/O layer */
  2449. if (fmt >= 2) return FR_NO_FILESYSTEM; /* No FAT volume is found */
  2450. /* An FAT volume is found. Following code initializes the file system object */
  2451. #if _FS_EXFAT
  2452. if (fmt == 1) {
  2453. QWORD maxlba;
  2454. for (i = BPB_ZeroedEx; i < BPB_ZeroedEx + 53 && fs->win[i] == 0; i++) ; /* Check zero filler */
  2455. if (i < BPB_ZeroedEx + 53) return FR_NO_FILESYSTEM;
  2456. if (ld_word(fs->win + BPB_FSVerEx) != 0x100) return FR_NO_FILESYSTEM; /* Check exFAT revision (Must be 1.0) */
  2457. if (1 << fs->win[BPB_BytsPerSecEx] != SS(fs)) /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
  2458. return FR_NO_FILESYSTEM;
  2459. maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA + 1 of the volume */
  2460. if (maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be handled in 32-bit LBA) */
  2461. fs->fsize = ld_dword(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */
  2462. fs->n_fats = fs->win[BPB_NumFATsEx]; /* Number of FATs */
  2463. if (fs->n_fats != 1) return FR_NO_FILESYSTEM; /* (Supports only 1 FAT) */
  2464. fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */
  2465. if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768) */
  2466. nclst = ld_dword(fs->win + BPB_NumClusEx); /* Number of clusters */
  2467. if (nclst > MAX_EXFAT) return FR_NO_FILESYSTEM; /* (Too many clusters) */
  2468. fs->n_fatent = nclst + 2;
  2469. /* Boundaries and Limits */
  2470. fs->volbase = bsect;
  2471. fs->database = bsect + ld_dword(fs->win + BPB_DataOfsEx);
  2472. fs->fatbase = bsect + ld_dword(fs->win + BPB_FatOfsEx);
  2473. if (maxlba < (QWORD)fs->database + nclst * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size requiered) */
  2474. fs->dirbase = ld_dword(fs->win + BPB_RootClusEx);
  2475. /* Check if bitmap location is in assumption (at the first cluster) */
  2476. if (move_window(fs, clust2sect(fs, fs->dirbase)) != FR_OK) return FR_DISK_ERR;
  2477. for (i = 0; i < SS(fs); i += SZDIRE) {
  2478. if (fs->win[i] == 0x81 && ld_dword(fs->win + i + 20) == 2) break; /* 81 entry with cluster #2? */
  2479. }
  2480. if (i == SS(fs)) return FR_NO_FILESYSTEM;
  2481. #if !_FS_READONLY
  2482. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
  2483. #endif
  2484. fmt = FS_EXFAT; /* FAT sub-type */
  2485. } else
  2486. #endif /* _FS_EXFAT */
  2487. {
  2488. if (ld_word(fs->win + BPB_BytsPerSec) != SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_BytsPerSec must be equal to the physical sector size) */
  2489. fasize = ld_word(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
  2490. if (fasize == 0) fasize = ld_dword(fs->win + BPB_FATSz32);
  2491. fs->fsize = fasize;
  2492. fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FATs */
  2493. if (fs->n_fats != 1 && fs->n_fats != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
  2494. fasize *= fs->n_fats; /* Number of sectors for FAT area */
  2495. fs->csize = fs->win[BPB_SecPerClus]; /* Cluster size */
  2496. if (fs->csize == 0 || (fs->csize & (fs->csize - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
  2497. fs->n_rootdir = ld_word(fs->win + BPB_RootEntCnt); /* Number of root directory entries */
  2498. if (fs->n_rootdir % (SS(fs) / SZDIRE)) return FR_NO_FILESYSTEM; /* (Must be sector aligned) */
  2499. tsect = ld_word(fs->win + BPB_TotSec16); /* Number of sectors on the volume */
  2500. if (tsect == 0) tsect = ld_dword(fs->win + BPB_TotSec32);
  2501. nrsv = ld_word(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
  2502. if (nrsv == 0) return FR_NO_FILESYSTEM; /* (Must not be 0) */
  2503. /* Determine the FAT sub type */
  2504. sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZDIRE); /* RSV + FAT + DIR */
  2505. if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  2506. nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
  2507. if (nclst == 0) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  2508. fmt = FS_FAT32;
  2509. if (nclst <= MAX_FAT16) fmt = FS_FAT16;
  2510. if (nclst <= MAX_FAT12) fmt = FS_FAT12;
  2511. /* Boundaries and Limits */
  2512. fs->n_fatent = nclst + 2; /* Number of FAT entries */
  2513. fs->volbase = bsect; /* Volume start sector */
  2514. fs->fatbase = bsect + nrsv; /* FAT start sector */
  2515. fs->database = bsect + sysect; /* Data start sector */
  2516. if (fmt == FS_FAT32) {
  2517. if (ld_word(fs->win + BPB_FSVer32) != 0) return FR_NO_FILESYSTEM; /* (Must be FAT32 revision 0.0) */
  2518. if (fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
  2519. fs->dirbase = ld_dword(fs->win + BPB_RootClus32); /* Root directory start cluster */
  2520. szbfat = fs->n_fatent * 4; /* (Needed FAT size) */
  2521. } else {
  2522. if (fs->n_rootdir == 0) return FR_NO_FILESYSTEM;/* (BPB_RootEntCnt must not be 0) */
  2523. fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
  2524. szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */
  2525. fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  2526. }
  2527. if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_FATSz must not be less than the size needed) */
  2528. #if !_FS_READONLY
  2529. /* Get FSINFO if available */
  2530. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
  2531. fs->fsi_flag = 0x80;
  2532. #if (_FS_NOFSINFO & 3) != 3
  2533. if (fmt == FS_FAT32 /* Enable FSINFO only if FAT32 and BPB_FSInfo32 == 1 */
  2534. && ld_word(fs->win + BPB_FSInfo32) == 1
  2535. && move_window(fs, bsect + 1) == FR_OK)
  2536. {
  2537. fs->fsi_flag = 0;
  2538. if (ld_word(fs->win + BS_55AA) == 0xAA55 /* Load FSINFO data if available */
  2539. && ld_dword(fs->win + FSI_LeadSig) == 0x41615252
  2540. && ld_dword(fs->win + FSI_StrucSig) == 0x61417272)
  2541. {
  2542. #if (_FS_NOFSINFO & 1) == 0
  2543. fs->free_clst = ld_dword(fs->win + FSI_Free_Count);
  2544. #endif
  2545. #if (_FS_NOFSINFO & 2) == 0
  2546. fs->last_clst = ld_dword(fs->win + FSI_Nxt_Free);
  2547. #endif
  2548. }
  2549. }
  2550. #endif /* (_FS_NOFSINFO & 3) != 3 */
  2551. #endif /* !_FS_READONLY */
  2552. }
  2553. fs->fs_type = fmt; /* FAT sub-type */
  2554. fs->id = ++Fsid; /* File system mount ID */
  2555. #if _USE_LFN == 1
  2556. fs->lfnbuf = LfnBuf; /* Static LFN working buffer */
  2557. #if _FS_EXFAT
  2558. fs->dirbuf = DirBuf; /* Static directory block working buuffer */
  2559. #endif
  2560. #endif
  2561. #if _FS_RPATH != 0
  2562. fs->cdir = 0; /* Initialize current directory */
  2563. #endif
  2564. #if _FS_LOCK != 0 /* Clear file lock semaphores */
  2565. clear_lock(fs);
  2566. #endif
  2567. return FR_OK;
  2568. }
  2569. /*-----------------------------------------------------------------------*/
  2570. /* Check if the file/directory object is valid or not */
  2571. /*-----------------------------------------------------------------------*/
  2572. static
  2573. FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */
  2574. _FDID* obj, /* Pointer to the _OBJ, the 1st member in the FIL/DIR object, to check validity */
  2575. FATFS** fs /* Pointer to pointer to the owner file system object to return */
  2576. )
  2577. {
  2578. FRESULT res;
  2579. DSTATUS stat;
  2580. if (!obj || !obj->fs || !obj->fs->fs_type || obj->fs->id != obj->id || disk_ioctl(obj->fs->drv, IOCTL_STATUS, &stat) != RES_OK || (stat & STA_NOINIT)) {
  2581. *fs = 0; /* The object is invalid */
  2582. res = FR_INVALID_OBJECT;
  2583. } else {
  2584. *fs = obj->fs; /* Owner file sytem object */
  2585. ENTER_FF(obj->fs); /* Lock file system */
  2586. res = FR_OK;
  2587. }
  2588. return res;
  2589. }
  2590. /*---------------------------------------------------------------------------
  2591. Public Functions (FatFs API)
  2592. ----------------------------------------------------------------------------*/
  2593. /*-----------------------------------------------------------------------*/
  2594. /* Mount/Unmount a Logical Drive */
  2595. /*-----------------------------------------------------------------------*/
  2596. FRESULT f_mount (
  2597. FATFS* fs /* Pointer to the file system object to mount */
  2598. )
  2599. {
  2600. FRESULT res;
  2601. fs->fs_type = 0; /* Clear new fs object */
  2602. #if _FS_REENTRANT /* Create sync object for the new volume */
  2603. if (!ff_cre_syncobj(fs, &fs->sobj)) return FR_INT_ERR;
  2604. #endif
  2605. res = find_volume(fs, 0); /* Force mounted the volume */
  2606. LEAVE_FF(fs, res);
  2607. }
  2608. FRESULT f_umount (
  2609. FATFS* fs /* Pointer to the file system object to unmount */
  2610. )
  2611. {
  2612. #if _FS_LOCK
  2613. clear_lock(fs);
  2614. #endif
  2615. #if _FS_REENTRANT /* Discard sync object of the current volume */
  2616. if (!ff_del_syncobj(fs->sobj)) return FR_INT_ERR;
  2617. #endif
  2618. fs->fs_type = 0; /* Clear old fs object */
  2619. return FR_OK;
  2620. }
  2621. /*-----------------------------------------------------------------------*/
  2622. /* Open or Create a File */
  2623. /*-----------------------------------------------------------------------*/
  2624. FRESULT f_open (
  2625. FATFS *fs,
  2626. FIL* fp, /* Pointer to the blank file object */
  2627. const TCHAR* path, /* Pointer to the file name */
  2628. BYTE mode /* Access mode and file open mode flags */
  2629. )
  2630. {
  2631. FRESULT res;
  2632. DIR dj;
  2633. #if !_FS_READONLY
  2634. DWORD dw, cl, bcs, clst, sc;
  2635. FSIZE_t ofs;
  2636. #endif
  2637. DEF_NAMBUF
  2638. if (!fp) return FR_INVALID_OBJECT;
  2639. /* Get logical drive */
  2640. mode &= _FS_READONLY ? FA_READ : FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_CREATE_NEW | FA_OPEN_ALWAYS | FA_OPEN_APPEND | FA_SEEKEND;
  2641. res = find_volume(fs, mode);
  2642. if (res == FR_OK) {
  2643. dj.obj.fs = fs;
  2644. INIT_NAMBUF(fs);
  2645. res = follow_path(&dj, path); /* Follow the file path */
  2646. #if !_FS_READONLY /* R/W configuration */
  2647. if (res == FR_OK) {
  2648. if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
  2649. res = FR_INVALID_NAME;
  2650. }
  2651. #if _FS_LOCK != 0
  2652. else {
  2653. res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  2654. }
  2655. #endif
  2656. }
  2657. /* Create or Open a file */
  2658. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  2659. if (res != FR_OK) { /* No file, create new */
  2660. if (res == FR_NO_FILE) /* There is no file to open, create a new entry */
  2661. #if _FS_LOCK != 0
  2662. res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
  2663. #else
  2664. res = dir_register(&dj);
  2665. #endif
  2666. mode |= FA_CREATE_ALWAYS; /* File is created */
  2667. }
  2668. else { /* Any object is already existing */
  2669. if (dj.obj.attr & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
  2670. res = FR_DENIED;
  2671. } else {
  2672. if (mode & FA_CREATE_NEW) res = FR_EXIST; /* Cannot create as new file */
  2673. }
  2674. }
  2675. if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */
  2676. dw = GET_FATTIME();
  2677. #if _FS_EXFAT
  2678. if (fs->fs_type == FS_EXFAT) {
  2679. /* Get current allocation info */
  2680. fp->obj.fs = fs;
  2681. fp->obj.sclust = ld_dword(fs->dirbuf + XDIR_FstClus);
  2682. fp->obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2683. fp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2684. /* Initialize directory entry block */
  2685. st_dword(fs->dirbuf + XDIR_CrtTime, dw); /* Set created time */
  2686. fs->dirbuf[XDIR_CrtTime10] = 0;
  2687. st_dword(fs->dirbuf + XDIR_ModTime, dw); /* Set modified time */
  2688. fs->dirbuf[XDIR_ModTime10] = 0;
  2689. fs->dirbuf[XDIR_Attr] = AM_ARC; /* Reset attribute */
  2690. st_dword(fs->dirbuf + XDIR_FstClus, 0); /* Reset file allocation info */
  2691. st_qword(fs->dirbuf + XDIR_FileSize, 0);
  2692. st_qword(fs->dirbuf + XDIR_ValidFileSize, 0);
  2693. fs->dirbuf[XDIR_GenFlags] = 1;
  2694. res = store_xdir(&dj);
  2695. if (res == FR_OK && fp->obj.sclust) { /* Remove the cluster chain if exist */
  2696. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  2697. fs->last_clst = fp->obj.sclust - 1; /* Reuse the cluster hole */
  2698. }
  2699. } else
  2700. #endif
  2701. {
  2702. /* Clean directory info */
  2703. st_dword(dj.dir + DIR_CrtTime, dw); /* Set created time */
  2704. st_dword(dj.dir + DIR_ModTime, dw); /* Set modified time */
  2705. dj.dir[DIR_Attr] = AM_ARC; /* Reset attribute */
  2706. cl = ld_clust(fs, dj.dir); /* Get cluster chain */
  2707. st_clust(fs, dj.dir, 0); /* Reset file allocation info */
  2708. st_dword(dj.dir + DIR_FileSize, 0);
  2709. fs->wflag = 1;
  2710. if (cl) { /* Remove the cluster chain if exist */
  2711. dw = fs->winsect;
  2712. res = remove_chain(&dj.obj, cl, 0);
  2713. if (res == FR_OK) {
  2714. res = move_window(fs, dw);
  2715. fs->last_clst = cl - 1; /* Reuse the cluster hole */
  2716. }
  2717. }
  2718. }
  2719. }
  2720. }
  2721. else { /* Open an existing file */
  2722. if (res == FR_OK) { /* Following succeeded */
  2723. if (dj.obj.attr & AM_DIR) { /* It is a directory */
  2724. res = FR_NO_FILE;
  2725. } else {
  2726. if ((mode & FA_WRITE) && (dj.obj.attr & AM_RDO)) { /* R/O violation */
  2727. res = FR_DENIED;
  2728. }
  2729. }
  2730. }
  2731. }
  2732. if (res == FR_OK) {
  2733. if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */
  2734. mode |= FA_MODIFIED;
  2735. fp->dir_sect = fs->winsect; /* Pointer to the directory entry */
  2736. fp->dir_ptr = dj.dir;
  2737. #if _FS_LOCK != 0
  2738. fp->obj.lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  2739. if (!fp->obj.lockid) res = FR_INT_ERR;
  2740. #endif
  2741. }
  2742. #else /* R/O configuration */
  2743. if (res == FR_OK) {
  2744. if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
  2745. res = FR_INVALID_NAME;
  2746. } else {
  2747. if (dj.obj.attr & AM_DIR) { /* It is a directory */
  2748. res = FR_NO_FILE;
  2749. }
  2750. }
  2751. }
  2752. #endif
  2753. if (res == FR_OK) {
  2754. #if _FS_EXFAT
  2755. if (fs->fs_type == FS_EXFAT) {
  2756. fp->obj.sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get allocation info */
  2757. fp->obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2758. fp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2759. fp->obj.c_scl = dj.obj.sclust;
  2760. fp->obj.c_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
  2761. fp->obj.c_ofs = dj.blk_ofs;
  2762. } else
  2763. #endif
  2764. {
  2765. fp->obj.sclust = ld_clust(fs, dj.dir); /* Get allocation info */
  2766. fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize);
  2767. }
  2768. #if _USE_FASTSEEK
  2769. fp->cltbl = 0; /* Disable fast seek mode */
  2770. #endif
  2771. fp->obj.fs = fs; /* Validate the file object */
  2772. fp->obj.id = fs->id;
  2773. fp->flag = mode; /* Set file access mode */
  2774. fp->err = 0; /* Clear error flag */
  2775. fp->sect = 0; /* Invalidate current data sector */
  2776. fp->fptr = 0; /* Set file pointer top of the file */
  2777. #if !_FS_READONLY
  2778. #if !_FS_TINY
  2779. mem_set(fp->buf, 0, _MAX_SS); /* Clear sector buffer */
  2780. #endif
  2781. if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
  2782. fp->fptr = fp->obj.objsize; /* Offset to seek */
  2783. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size in byte */
  2784. clst = fp->obj.sclust; /* Follow the cluster chain */
  2785. for (ofs = fp->obj.objsize; res == FR_OK && ofs > bcs; ofs -= bcs) {
  2786. clst = get_fat(&fp->obj, clst);
  2787. if (clst <= 1) res = FR_INT_ERR;
  2788. if (clst == 0xFFFFFFFF) res = FR_DISK_ERR;
  2789. }
  2790. fp->clust = clst;
  2791. if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */
  2792. if ((sc = clust2sect(fs, clst)) == 0) {
  2793. res = FR_INT_ERR;
  2794. } else {
  2795. fp->sect = sc + (DWORD)(ofs / SS(fs));
  2796. #if !_FS_TINY
  2797. if (disk_read(fs->drv, fp->buf, fp->sect, 1) != RES_OK) res = FR_DISK_ERR;
  2798. #endif
  2799. }
  2800. }
  2801. }
  2802. #endif
  2803. }
  2804. FREE_NAMBUF();
  2805. }
  2806. if (res != FR_OK) fp->obj.fs = 0; /* Invalidate file object on error */
  2807. LEAVE_FF(fs, res);
  2808. }
  2809. /*-----------------------------------------------------------------------*/
  2810. /* Read File */
  2811. /*-----------------------------------------------------------------------*/
  2812. FRESULT f_read (
  2813. FIL* fp, /* Pointer to the file object */
  2814. void* buff, /* Pointer to data buffer */
  2815. UINT btr, /* Number of bytes to read */
  2816. UINT* br /* Pointer to number of bytes read */
  2817. )
  2818. {
  2819. FRESULT res;
  2820. FATFS *fs;
  2821. DWORD clst, sect;
  2822. FSIZE_t remain;
  2823. UINT rcnt, cc, csect;
  2824. BYTE *rbuff = (BYTE*)buff;
  2825. *br = 0; /* Clear read byte counter */
  2826. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  2827. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  2828. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  2829. remain = fp->obj.objsize - fp->fptr;
  2830. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  2831. for ( ; btr; /* Repeat until all data read */
  2832. rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  2833. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  2834. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  2835. if (csect == 0) { /* On the cluster boundary? */
  2836. if (fp->fptr == 0) { /* On the top of the file? */
  2837. clst = fp->obj.sclust; /* Follow cluster chain from the origin */
  2838. } else { /* Middle or end of the file */
  2839. #if _USE_FASTSEEK
  2840. if (fp->cltbl) {
  2841. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  2842. } else
  2843. #endif
  2844. {
  2845. clst = get_fat(&fp->obj, fp->clust); /* Follow cluster chain on the FAT */
  2846. }
  2847. }
  2848. if (clst < 2) ABORT(fs, FR_INT_ERR);
  2849. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  2850. fp->clust = clst; /* Update current cluster */
  2851. }
  2852. sect = clust2sect(fs, fp->clust); /* Get current sector */
  2853. if (!sect) ABORT(fs, FR_INT_ERR);
  2854. sect += csect;
  2855. cc = btr / SS(fs); /* When remaining bytes >= sector size, */
  2856. if (cc) { /* Read maximum contiguous sectors directly */
  2857. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  2858. cc = fs->csize - csect;
  2859. }
  2860. if (disk_read(fs->drv, rbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  2861. #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
  2862. #if _FS_TINY
  2863. if (fs->wflag && fs->winsect - sect < cc) {
  2864. mem_cpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));
  2865. }
  2866. #else
  2867. if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {
  2868. mem_cpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));
  2869. }
  2870. #endif
  2871. #endif
  2872. rcnt = SS(fs) * cc; /* Number of bytes transferred */
  2873. continue;
  2874. }
  2875. #if !_FS_TINY
  2876. if (fp->sect != sect) { /* Load data sector if not in cache */
  2877. #if !_FS_READONLY
  2878. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  2879. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  2880. fp->flag &= (BYTE)~FA_DIRTY;
  2881. }
  2882. #endif
  2883. if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  2884. }
  2885. #endif
  2886. fp->sect = sect;
  2887. }
  2888. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  2889. if (rcnt > btr) rcnt = btr; /* Clip it by btr if needed */
  2890. #if _FS_TINY
  2891. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  2892. mem_cpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  2893. #else
  2894. mem_cpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  2895. #endif
  2896. }
  2897. LEAVE_FF(fs, FR_OK);
  2898. }
  2899. #if !_FS_READONLY
  2900. /*-----------------------------------------------------------------------*/
  2901. /* Write File */
  2902. /*-----------------------------------------------------------------------*/
  2903. FRESULT f_write (
  2904. FIL* fp, /* Pointer to the file object */
  2905. const void* buff, /* Pointer to the data to be written */
  2906. UINT btw, /* Number of bytes to write */
  2907. UINT* bw /* Pointer to number of bytes written */
  2908. )
  2909. {
  2910. FRESULT res;
  2911. FATFS *fs;
  2912. DWORD clst, sect;
  2913. UINT wcnt, cc, csect;
  2914. const BYTE *wbuff = (const BYTE*)buff;
  2915. *bw = 0; /* Clear write byte counter */
  2916. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  2917. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  2918. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  2919. /* Check fptr wrap-around (file size cannot reach 4GiB on FATxx) */
  2920. if ((!_FS_EXFAT || fs->fs_type != FS_EXFAT) && (DWORD)(fp->fptr + btw) < (DWORD)fp->fptr) {
  2921. btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr);
  2922. }
  2923. for ( ; btw; /* Repeat until all data written */
  2924. wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize, *bw += wcnt, btw -= wcnt) {
  2925. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  2926. csect = (UINT)(fp->fptr / SS(fs)) & (fs->csize - 1); /* Sector offset in the cluster */
  2927. if (csect == 0) { /* On the cluster boundary? */
  2928. if (fp->fptr == 0) { /* On the top of the file? */
  2929. clst = fp->obj.sclust; /* Follow from the origin */
  2930. if (clst == 0) { /* If no cluster is allocated, */
  2931. clst = create_chain(&fp->obj, 0); /* create a new cluster chain */
  2932. }
  2933. } else { /* On the middle or end of the file */
  2934. #if _USE_FASTSEEK
  2935. if (fp->cltbl) {
  2936. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  2937. } else
  2938. #endif
  2939. {
  2940. clst = create_chain(&fp->obj, fp->clust); /* Follow or stretch cluster chain on the FAT */
  2941. }
  2942. }
  2943. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  2944. if (clst == 1) ABORT(fs, FR_INT_ERR);
  2945. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  2946. fp->clust = clst; /* Update current cluster */
  2947. if (fp->obj.sclust == 0) fp->obj.sclust = clst; /* Set start cluster if the first write */
  2948. }
  2949. #if _FS_TINY
  2950. if (fs->winsect == fp->sect && sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Write-back sector cache */
  2951. #else
  2952. if (fp->flag & FA_DIRTY) { /* Write-back sector cache */
  2953. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  2954. fp->flag &= (BYTE)~FA_DIRTY;
  2955. }
  2956. #endif
  2957. sect = clust2sect(fs, fp->clust); /* Get current sector */
  2958. if (!sect) ABORT(fs, FR_INT_ERR);
  2959. sect += csect;
  2960. cc = btw / SS(fs); /* When remaining bytes >= sector size, */
  2961. if (cc) { /* Write maximum contiguous sectors directly */
  2962. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  2963. cc = fs->csize - csect;
  2964. }
  2965. if (disk_write(fs->drv, wbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  2966. #if _FS_MINIMIZE <= 2
  2967. #if _FS_TINY
  2968. if (fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  2969. mem_cpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));
  2970. fs->wflag = 0;
  2971. }
  2972. #else
  2973. if (fp->sect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  2974. mem_cpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));
  2975. fp->flag &= (BYTE)~FA_DIRTY;
  2976. }
  2977. #endif
  2978. #endif
  2979. wcnt = SS(fs) * cc; /* Number of bytes transferred */
  2980. continue;
  2981. }
  2982. #if _FS_TINY
  2983. if (fp->fptr >= fp->obj.objsize) { /* Avoid silly cache filling on the growing edge */
  2984. if (sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR);
  2985. fs->winsect = sect;
  2986. }
  2987. #else
  2988. if (fp->sect != sect && /* Fill sector cache with file data */
  2989. fp->fptr < fp->obj.objsize &&
  2990. disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) {
  2991. ABORT(fs, FR_DISK_ERR);
  2992. }
  2993. #endif
  2994. fp->sect = sect;
  2995. }
  2996. wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  2997. if (wcnt > btw) wcnt = btw; /* Clip it by btw if needed */
  2998. #if _FS_TINY
  2999. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  3000. mem_cpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3001. fs->wflag = 1;
  3002. #else
  3003. mem_cpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3004. fp->flag |= FA_DIRTY;
  3005. #endif
  3006. }
  3007. fp->flag |= FA_MODIFIED; /* Set file change flag */
  3008. LEAVE_FF(fs, FR_OK);
  3009. }
  3010. /*-----------------------------------------------------------------------*/
  3011. /* Synchronize the File */
  3012. /*-----------------------------------------------------------------------*/
  3013. FRESULT f_sync (
  3014. FIL* fp /* Pointer to the file object */
  3015. )
  3016. {
  3017. FRESULT res;
  3018. FATFS *fs;
  3019. DWORD tm;
  3020. BYTE *dir;
  3021. #if _FS_EXFAT
  3022. DEF_NAMBUF
  3023. #endif
  3024. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3025. if (res == FR_OK) {
  3026. if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
  3027. #if !_FS_TINY
  3028. if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
  3029. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
  3030. fp->flag &= (BYTE)~FA_DIRTY;
  3031. }
  3032. #endif
  3033. /* Update the directory entry */
  3034. tm = GET_FATTIME(); /* Modified time */
  3035. #if _FS_EXFAT
  3036. if (fs->fs_type == FS_EXFAT) {
  3037. res = fill_fat_chain(&fp->obj); /* Create FAT chain if needed */
  3038. if (res == FR_OK) {
  3039. DIR dj;
  3040. INIT_NAMBUF(fs);
  3041. res = load_obj_dir(&dj, &fp->obj); /* Load directory entry block */
  3042. if (res == FR_OK) {
  3043. fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive bit */
  3044. fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation info */
  3045. st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust);
  3046. st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize);
  3047. st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize);
  3048. st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */
  3049. fs->dirbuf[XDIR_ModTime10] = 0;
  3050. st_dword(fs->dirbuf + XDIR_AccTime, 0);
  3051. res = store_xdir(&dj); /* Restore it to the directory */
  3052. if (res == FR_OK) {
  3053. res = sync_fs(fs);
  3054. fp->flag &= (BYTE)~FA_MODIFIED;
  3055. }
  3056. }
  3057. FREE_NAMBUF();
  3058. }
  3059. } else
  3060. #endif
  3061. {
  3062. res = move_window(fs, fp->dir_sect);
  3063. if (res == FR_OK) {
  3064. dir = fp->dir_ptr;
  3065. dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
  3066. st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation info */
  3067. st_dword(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
  3068. st_dword(dir + DIR_ModTime, tm); /* Update modified time */
  3069. st_word(dir + DIR_LstAccDate, 0);
  3070. fs->wflag = 1;
  3071. res = sync_fs(fs); /* Restore it to the directory */
  3072. fp->flag &= (BYTE)~FA_MODIFIED;
  3073. }
  3074. }
  3075. }
  3076. }
  3077. LEAVE_FF(fs, res);
  3078. }
  3079. #endif /* !_FS_READONLY */
  3080. /*-----------------------------------------------------------------------*/
  3081. /* Close File */
  3082. /*-----------------------------------------------------------------------*/
  3083. FRESULT f_close (
  3084. FIL* fp /* Pointer to the file object to be closed */
  3085. )
  3086. {
  3087. FRESULT res;
  3088. FATFS *fs;
  3089. #if !_FS_READONLY
  3090. res = f_sync(fp); /* Flush cached data */
  3091. if (res == FR_OK)
  3092. #endif
  3093. {
  3094. res = validate(&fp->obj, &fs); /* Lock volume */
  3095. if (res == FR_OK) {
  3096. #if _FS_LOCK != 0
  3097. res = dec_lock(fp->obj.lockid); /* Decrement file open counter */
  3098. if (res == FR_OK)
  3099. #endif
  3100. {
  3101. fp->obj.fs = 0; /* Invalidate file object */
  3102. }
  3103. #if _FS_REENTRANT
  3104. unlock_fs(fs, FR_OK); /* Unlock volume */
  3105. #endif
  3106. }
  3107. }
  3108. return res;
  3109. }
  3110. #if _FS_RPATH >= 1
  3111. /*-----------------------------------------------------------------------*/
  3112. /* Change Current Directory or Current Drive, Get Current Directory */
  3113. /*-----------------------------------------------------------------------*/
  3114. FRESULT f_chdir (
  3115. FATFS *fs,
  3116. const TCHAR* path /* Pointer to the directory path */
  3117. )
  3118. {
  3119. FRESULT res;
  3120. DIR dj;
  3121. DEF_NAMBUF
  3122. /* Get logical drive */
  3123. res = find_volume(fs, 0);
  3124. if (res == FR_OK) {
  3125. dj.obj.fs = fs;
  3126. INIT_NAMBUF(fs);
  3127. res = follow_path(&dj, path); /* Follow the path */
  3128. if (res == FR_OK) { /* Follow completed */
  3129. if (dj.fn[NSFLAG] & NS_NONAME) {
  3130. fs->cdir = dj.obj.sclust; /* It is the start directory itself */
  3131. #if _FS_EXFAT
  3132. if (fs->fs_type == FS_EXFAT) {
  3133. fs->cdc_scl = dj.obj.c_scl;
  3134. fs->cdc_size = dj.obj.c_size;
  3135. fs->cdc_ofs = dj.obj.c_ofs;
  3136. }
  3137. #endif
  3138. } else {
  3139. if (dj.obj.attr & AM_DIR) { /* It is a sub-directory */
  3140. #if _FS_EXFAT
  3141. if (fs->fs_type == FS_EXFAT) {
  3142. fs->cdir = ld_dword(fs->dirbuf + XDIR_FstClus); /* Sub-directory cluster */
  3143. fs->cdc_scl = dj.obj.sclust; /* Save containing directory information */
  3144. fs->cdc_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
  3145. fs->cdc_ofs = dj.blk_ofs;
  3146. } else
  3147. #endif
  3148. {
  3149. fs->cdir = ld_clust(fs, dj.dir); /* Sub-directory cluster */
  3150. }
  3151. } else {
  3152. res = FR_NO_PATH; /* Reached but a file */
  3153. }
  3154. }
  3155. }
  3156. FREE_NAMBUF();
  3157. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3158. }
  3159. LEAVE_FF(fs, res);
  3160. }
  3161. #if _FS_RPATH >= 2
  3162. FRESULT f_getcwd (
  3163. FATFS *fs,
  3164. TCHAR* buff, /* Pointer to the directory path */
  3165. UINT len /* Size of path */
  3166. )
  3167. {
  3168. FRESULT res;
  3169. DIR dj;
  3170. UINT i, n;
  3171. DWORD ccl;
  3172. TCHAR *tp;
  3173. FILINFO fno;
  3174. DEF_NAMBUF
  3175. *buff = 0;
  3176. /* Get logical drive */
  3177. res = find_volume(fs, 0); /* Get current volume */
  3178. if (res == FR_OK) {
  3179. dj.obj.fs = fs;
  3180. INIT_NAMBUF(fs);
  3181. i = len; /* Bottom of buffer (directory stack base) */
  3182. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* (Cannot do getcwd on exFAT and returns root path) */
  3183. dj.obj.sclust = fs->cdir; /* Start to follow upper directory from current directory */
  3184. while ((ccl = dj.obj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
  3185. res = dir_sdi(&dj, 1 * SZDIRE); /* Get parent directory */
  3186. if (res != FR_OK) break;
  3187. res = move_window(fs, dj.sect);
  3188. if (res != FR_OK) break;
  3189. dj.obj.sclust = ld_clust(fs, dj.dir); /* Goto parent directory */
  3190. res = dir_sdi(&dj, 0);
  3191. if (res != FR_OK) break;
  3192. do { /* Find the entry links to the child directory */
  3193. res = dir_read(&dj, 0);
  3194. if (res != FR_OK) break;
  3195. if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */
  3196. res = dir_next(&dj, 0);
  3197. } while (res == FR_OK);
  3198. if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
  3199. if (res != FR_OK) break;
  3200. get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
  3201. for (n = 0; fno.fname[n]; n++) ;
  3202. if (i < n + 3) {
  3203. res = FR_NOT_ENOUGH_CORE; break;
  3204. }
  3205. while (n) buff[--i] = fno.fname[--n];
  3206. buff[--i] = '/';
  3207. }
  3208. }
  3209. tp = buff;
  3210. if (res == FR_OK) {
  3211. if (i == len) { /* Root-directory */
  3212. *tp++ = '/';
  3213. } else { /* Sub-directroy */
  3214. do /* Add stacked path str */
  3215. *tp++ = buff[i++];
  3216. while (i < len);
  3217. }
  3218. }
  3219. *tp = 0;
  3220. FREE_NAMBUF();
  3221. }
  3222. LEAVE_FF(fs, res);
  3223. }
  3224. #endif /* _FS_RPATH >= 2 */
  3225. #endif /* _FS_RPATH >= 1 */
  3226. #if _FS_MINIMIZE <= 2
  3227. /*-----------------------------------------------------------------------*/
  3228. /* Seek File R/W Pointer */
  3229. /*-----------------------------------------------------------------------*/
  3230. FRESULT f_lseek (
  3231. FIL* fp, /* Pointer to the file object */
  3232. FSIZE_t ofs /* File pointer from top of file */
  3233. )
  3234. {
  3235. FRESULT res;
  3236. FATFS *fs;
  3237. DWORD clst, bcs, nsect;
  3238. FSIZE_t ifptr;
  3239. #if _USE_FASTSEEK
  3240. DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
  3241. #endif
  3242. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3243. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  3244. #if _USE_FASTSEEK
  3245. if (fp->cltbl) { /* Fast seek */
  3246. if (ofs == CREATE_LINKMAP) { /* Create CLMT */
  3247. tbl = fp->cltbl;
  3248. tlen = *tbl++; ulen = 2; /* Given table size and required table size */
  3249. cl = fp->obj.sclust; /* Origin of the chain */
  3250. if (cl) {
  3251. do {
  3252. /* Get a fragment */
  3253. tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
  3254. do {
  3255. pcl = cl; ncl++;
  3256. cl = get_fat(&fp->obj, cl);
  3257. if (cl <= 1) ABORT(fs, FR_INT_ERR);
  3258. if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3259. } while (cl == pcl + 1);
  3260. if (ulen <= tlen) { /* Store the length and top of the fragment */
  3261. *tbl++ = ncl; *tbl++ = tcl;
  3262. }
  3263. } while (cl < fs->n_fatent); /* Repeat until end of chain */
  3264. }
  3265. *fp->cltbl = ulen; /* Number of items used */
  3266. if (ulen <= tlen) {
  3267. *tbl = 0; /* Terminate table */
  3268. } else {
  3269. res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
  3270. }
  3271. } else { /* Fast seek */
  3272. if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
  3273. fp->fptr = ofs; /* Set file pointer */
  3274. if (ofs) {
  3275. fp->clust = clmt_clust(fp, ofs - 1);
  3276. dsc = clust2sect(fs, fp->clust);
  3277. if (!dsc) ABORT(fs, FR_INT_ERR);
  3278. dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
  3279. if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
  3280. #if !_FS_TINY
  3281. #if !_FS_READONLY
  3282. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3283. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3284. fp->flag &= (BYTE)~FA_DIRTY;
  3285. }
  3286. #endif
  3287. if (disk_read(fs->drv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
  3288. #endif
  3289. fp->sect = dsc;
  3290. }
  3291. }
  3292. }
  3293. } else
  3294. #endif
  3295. /* Normal Seek */
  3296. {
  3297. #if _FS_EXFAT
  3298. if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4GiB-1 if at FATxx */
  3299. #endif
  3300. if (ofs > fp->obj.objsize && (_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
  3301. ofs = fp->obj.objsize;
  3302. }
  3303. ifptr = fp->fptr;
  3304. fp->fptr = nsect = 0;
  3305. if (ofs) {
  3306. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
  3307. if (ifptr > 0 &&
  3308. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  3309. fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
  3310. ofs -= fp->fptr;
  3311. clst = fp->clust;
  3312. } else { /* When seek to back cluster, */
  3313. clst = fp->obj.sclust; /* start from the first cluster */
  3314. #if !_FS_READONLY
  3315. if (clst == 0) { /* If no cluster chain, create a new chain */
  3316. clst = create_chain(&fp->obj, 0);
  3317. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3318. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3319. fp->obj.sclust = clst;
  3320. }
  3321. #endif
  3322. fp->clust = clst;
  3323. }
  3324. if (clst != 0) {
  3325. while (ofs > bcs) { /* Cluster following loop */
  3326. ofs -= bcs; fp->fptr += bcs;
  3327. #if !_FS_READONLY
  3328. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  3329. if (_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
  3330. fp->obj.objsize = fp->fptr;
  3331. fp->flag |= FA_MODIFIED;
  3332. }
  3333. clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
  3334. if (clst == 0) { /* Clip file size in case of disk full */
  3335. ofs = 0; break;
  3336. }
  3337. } else
  3338. #endif
  3339. {
  3340. clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
  3341. }
  3342. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3343. if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
  3344. fp->clust = clst;
  3345. }
  3346. fp->fptr += ofs;
  3347. if (ofs % SS(fs)) {
  3348. nsect = clust2sect(fs, clst); /* Current sector */
  3349. if (!nsect) ABORT(fs, FR_INT_ERR);
  3350. nsect += (DWORD)(ofs / SS(fs));
  3351. }
  3352. }
  3353. }
  3354. if (!_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
  3355. fp->obj.objsize = fp->fptr;
  3356. fp->flag |= FA_MODIFIED;
  3357. }
  3358. if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
  3359. #if !_FS_TINY
  3360. #if !_FS_READONLY
  3361. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3362. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3363. fp->flag &= (BYTE)~FA_DIRTY;
  3364. }
  3365. #endif
  3366. if (disk_read(fs->drv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  3367. #endif
  3368. fp->sect = nsect;
  3369. }
  3370. }
  3371. LEAVE_FF(fs, res);
  3372. }
  3373. #if _FS_MINIMIZE <= 1
  3374. /*-----------------------------------------------------------------------*/
  3375. /* Create a Directory Object */
  3376. /*-----------------------------------------------------------------------*/
  3377. FRESULT f_opendir (
  3378. FATFS *fs,
  3379. DIR* dp, /* Pointer to directory object to create */
  3380. const TCHAR* path /* Pointer to the directory path */
  3381. )
  3382. {
  3383. FRESULT res;
  3384. _FDID *obj;
  3385. DEF_NAMBUF
  3386. if (!dp) return FR_INVALID_OBJECT;
  3387. /* Get logical drive */
  3388. obj = &dp->obj;
  3389. res = find_volume(fs, 0);
  3390. if (res == FR_OK) {
  3391. obj->fs = fs;
  3392. INIT_NAMBUF(fs);
  3393. res = follow_path(dp, path); /* Follow the path to the directory */
  3394. if (res == FR_OK) { /* Follow completed */
  3395. if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is not the origin directory itself */
  3396. if (obj->attr & AM_DIR) { /* This object is a sub-directory */
  3397. #if _FS_EXFAT
  3398. if (fs->fs_type == FS_EXFAT) {
  3399. obj->c_scl = obj->sclust; /* Save containing directory inforamation */
  3400. obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
  3401. obj->c_ofs = dp->blk_ofs;
  3402. obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get object location and status */
  3403. obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  3404. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  3405. } else
  3406. #endif
  3407. {
  3408. obj->sclust = ld_clust(fs, dp->dir); /* Get object location */
  3409. }
  3410. } else { /* This object is a file */
  3411. res = FR_NO_PATH;
  3412. }
  3413. }
  3414. if (res == FR_OK) {
  3415. obj->id = fs->id;
  3416. res = dir_sdi(dp, 0); /* Rewind directory */
  3417. #if _FS_LOCK != 0
  3418. if (res == FR_OK) {
  3419. if (obj->sclust) {
  3420. obj->lockid = inc_lock(dp, 0); /* Lock the sub directory */
  3421. if (!obj->lockid) res = FR_TOO_MANY_OPEN_FILES;
  3422. } else {
  3423. obj->lockid = 0; /* Root directory need not to be locked */
  3424. }
  3425. }
  3426. #endif
  3427. }
  3428. }
  3429. FREE_NAMBUF();
  3430. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3431. }
  3432. if (res != FR_OK) obj->fs = 0; /* Invalidate the directory object if function faild */
  3433. LEAVE_FF(fs, res);
  3434. }
  3435. /*-----------------------------------------------------------------------*/
  3436. /* Close Directory */
  3437. /*-----------------------------------------------------------------------*/
  3438. FRESULT f_closedir (
  3439. DIR *dp /* Pointer to the directory object to be closed */
  3440. )
  3441. {
  3442. FRESULT res;
  3443. FATFS *fs;
  3444. res = validate(&dp->obj, &fs); /* Check validity of the file object */
  3445. if (res == FR_OK) {
  3446. #if _FS_LOCK != 0
  3447. if (dp->obj.lockid) { /* Decrement sub-directory open counter */
  3448. res = dec_lock(dp->obj.lockid);
  3449. }
  3450. if (res == FR_OK)
  3451. #endif
  3452. {
  3453. dp->obj.fs = 0; /* Invalidate directory object */
  3454. }
  3455. #if _FS_REENTRANT
  3456. unlock_fs(fs, FR_OK); /* Unlock volume */
  3457. #endif
  3458. }
  3459. return res;
  3460. }
  3461. /*-----------------------------------------------------------------------*/
  3462. /* Read Directory Entries in Sequence */
  3463. /*-----------------------------------------------------------------------*/
  3464. FRESULT f_readdir (
  3465. DIR* dp, /* Pointer to the open directory object */
  3466. FILINFO* fno /* Pointer to file information to return */
  3467. )
  3468. {
  3469. FRESULT res;
  3470. FATFS *fs;
  3471. DEF_NAMBUF
  3472. res = validate(&dp->obj, &fs); /* Check validity of the directory object */
  3473. if (res == FR_OK) {
  3474. if (!fno) {
  3475. res = dir_sdi(dp, 0); /* Rewind the directory object */
  3476. } else {
  3477. INIT_NAMBUF(fs);
  3478. res = dir_read(dp, 0); /* Read an item */
  3479. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
  3480. if (res == FR_OK) { /* A valid entry is found */
  3481. get_fileinfo(dp, fno); /* Get the object information */
  3482. res = dir_next(dp, 0); /* Increment index for next */
  3483. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
  3484. }
  3485. FREE_NAMBUF();
  3486. }
  3487. }
  3488. LEAVE_FF(fs, res);
  3489. }
  3490. #if _USE_FIND
  3491. /*-----------------------------------------------------------------------*/
  3492. /* Find Next File */
  3493. /*-----------------------------------------------------------------------*/
  3494. FRESULT f_findnext (
  3495. DIR* dp, /* Pointer to the open directory object */
  3496. FILINFO* fno /* Pointer to the file information structure */
  3497. )
  3498. {
  3499. FRESULT res;
  3500. for (;;) {
  3501. res = f_readdir(dp, fno); /* Get a directory item */
  3502. if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
  3503. if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for the file name */
  3504. #if _USE_LFN != 0 && _USE_FIND == 2
  3505. if (pattern_matching(dp->pat, fno->altname, 0, 0)) break; /* Test for alternative name if exist */
  3506. #endif
  3507. }
  3508. return res;
  3509. }
  3510. /*-----------------------------------------------------------------------*/
  3511. /* Find First File */
  3512. /*-----------------------------------------------------------------------*/
  3513. FRESULT f_findfirst (
  3514. DIR* dp, /* Pointer to the blank directory object */
  3515. FILINFO* fno, /* Pointer to the file information structure */
  3516. const TCHAR* path, /* Pointer to the directory to open */
  3517. const TCHAR* pattern /* Pointer to the matching pattern */
  3518. )
  3519. {
  3520. FRESULT res;
  3521. dp->pat = pattern; /* Save pointer to pattern string */
  3522. res = f_opendir(dp, path); /* Open the target directory */
  3523. if (res == FR_OK) {
  3524. res = f_findnext(dp, fno); /* Find the first item */
  3525. }
  3526. return res;
  3527. }
  3528. #endif /* _USE_FIND */
  3529. #if _FS_MINIMIZE == 0
  3530. /*-----------------------------------------------------------------------*/
  3531. /* Get File Status */
  3532. /*-----------------------------------------------------------------------*/
  3533. FRESULT f_stat (
  3534. FATFS *fs,
  3535. const TCHAR* path, /* Pointer to the file path */
  3536. FILINFO* fno /* Pointer to file information to return */
  3537. )
  3538. {
  3539. FRESULT res;
  3540. DIR dj;
  3541. DEF_NAMBUF
  3542. /* Get logical drive */
  3543. res = find_volume(fs, 0);
  3544. dj.obj.fs = fs;
  3545. if (res == FR_OK) {
  3546. INIT_NAMBUF(dj.obj.fs);
  3547. res = follow_path(&dj, path); /* Follow the file path */
  3548. if (res == FR_OK) { /* Follow completed */
  3549. if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
  3550. res = FR_INVALID_NAME;
  3551. } else { /* Found an object */
  3552. if (fno) get_fileinfo(&dj, fno);
  3553. }
  3554. }
  3555. FREE_NAMBUF();
  3556. }
  3557. LEAVE_FF(dj.obj.fs, res);
  3558. }
  3559. #if !_FS_READONLY
  3560. /*-----------------------------------------------------------------------*/
  3561. /* Get Number of Free Clusters */
  3562. /*-----------------------------------------------------------------------*/
  3563. FRESULT f_getfree (
  3564. FATFS *fs,
  3565. DWORD* nclst /* Pointer to a variable to return number of free clusters */
  3566. )
  3567. {
  3568. FRESULT res;
  3569. DWORD nfree, clst, sect, stat;
  3570. UINT i;
  3571. BYTE *p;
  3572. _FDID obj;
  3573. /* Get logical drive */
  3574. res = find_volume(fs, 0);
  3575. if (res == FR_OK) {
  3576. /* If free_clst is valid, return it without full cluster scan */
  3577. if (fs->free_clst <= fs->n_fatent - 2) {
  3578. *nclst = fs->free_clst;
  3579. } else {
  3580. /* Get number of free clusters */
  3581. nfree = 0;
  3582. if (fs->fs_type == FS_FAT12) { /* FAT12: Sector unalighed FAT entries */
  3583. clst = 2; obj.fs = fs;
  3584. do {
  3585. stat = get_fat(&obj, clst);
  3586. if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  3587. if (stat == 1) { res = FR_INT_ERR; break; }
  3588. if (stat == 0) nfree++;
  3589. } while (++clst < fs->n_fatent);
  3590. } else {
  3591. #if _FS_EXFAT
  3592. if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan bitmap table */
  3593. BYTE bm;
  3594. UINT b;
  3595. clst = fs->n_fatent - 2;
  3596. sect = fs->database;
  3597. i = 0;
  3598. do {
  3599. if (i == 0 && (res = move_window(fs, sect++)) != FR_OK) break;
  3600. for (b = 8, bm = fs->win[i]; b && clst; b--, clst--) {
  3601. if (!(bm & 1)) nfree++;
  3602. bm >>= 1;
  3603. }
  3604. i = (i + 1) % SS(fs);
  3605. } while (clst);
  3606. } else
  3607. #endif
  3608. { /* FAT16/32: Sector alighed FAT entries */
  3609. clst = fs->n_fatent; sect = fs->fatbase;
  3610. i = 0; p = 0;
  3611. do {
  3612. if (i == 0) {
  3613. res = move_window(fs, sect++);
  3614. if (res != FR_OK) break;
  3615. p = fs->win;
  3616. i = SS(fs);
  3617. }
  3618. if (fs->fs_type == FS_FAT16) {
  3619. if (ld_word(p) == 0) nfree++;
  3620. p += 2; i -= 2;
  3621. } else {
  3622. if ((ld_dword(p) & 0x0FFFFFFF) == 0) nfree++;
  3623. p += 4; i -= 4;
  3624. }
  3625. } while (--clst);
  3626. }
  3627. }
  3628. *nclst = nfree; /* Return the free clusters */
  3629. fs->free_clst = nfree; /* Now free_clst is valid */
  3630. fs->fsi_flag |= 1; /* FSInfo is to be updated */
  3631. }
  3632. }
  3633. LEAVE_FF(fs, res);
  3634. }
  3635. /*-----------------------------------------------------------------------*/
  3636. /* Truncate File */
  3637. /*-----------------------------------------------------------------------*/
  3638. FRESULT f_truncate (
  3639. FIL* fp /* Pointer to the file object */
  3640. )
  3641. {
  3642. FRESULT res;
  3643. FATFS *fs;
  3644. DWORD ncl;
  3645. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3646. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  3647. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3648. if (fp->obj.objsize > fp->fptr) {
  3649. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  3650. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  3651. fp->obj.sclust = 0;
  3652. } else { /* When truncate a part of the file, remove remaining clusters */
  3653. ncl = get_fat(&fp->obj, fp->clust);
  3654. res = FR_OK;
  3655. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3656. if (ncl == 1) res = FR_INT_ERR;
  3657. if (res == FR_OK && ncl < fs->n_fatent) {
  3658. res = remove_chain(&fp->obj, ncl, fp->clust);
  3659. }
  3660. }
  3661. fp->obj.objsize = fp->fptr; /* Set file size to current R/W point */
  3662. fp->flag |= FA_MODIFIED;
  3663. #if !_FS_TINY
  3664. if (res == FR_OK && (fp->flag & FA_DIRTY)) {
  3665. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) {
  3666. res = FR_DISK_ERR;
  3667. } else {
  3668. fp->flag &= (BYTE)~FA_DIRTY;
  3669. }
  3670. }
  3671. #endif
  3672. if (res != FR_OK) ABORT(fs, res);
  3673. }
  3674. LEAVE_FF(fs, res);
  3675. }
  3676. /*-----------------------------------------------------------------------*/
  3677. /* Delete a File/Directory */
  3678. /*-----------------------------------------------------------------------*/
  3679. FRESULT f_unlink (
  3680. FATFS *fs,
  3681. const TCHAR* path /* Pointer to the file or directory path */
  3682. )
  3683. {
  3684. FRESULT res;
  3685. DIR dj, sdj;
  3686. DWORD dclst = 0;
  3687. #if _FS_EXFAT
  3688. _FDID obj;
  3689. #endif
  3690. DEF_NAMBUF
  3691. /* Get logical drive */
  3692. res = find_volume(fs, FA_WRITE);
  3693. dj.obj.fs = fs;
  3694. if (res == FR_OK) {
  3695. INIT_NAMBUF(fs);
  3696. res = follow_path(&dj, path); /* Follow the file path */
  3697. if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {
  3698. res = FR_INVALID_NAME; /* Cannot remove dot entry */
  3699. }
  3700. #if _FS_LOCK != 0
  3701. if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */
  3702. #endif
  3703. if (res == FR_OK) { /* The object is accessible */
  3704. if (dj.fn[NSFLAG] & NS_NONAME) {
  3705. res = FR_INVALID_NAME; /* Cannot remove the origin directory */
  3706. } else {
  3707. if (dj.obj.attr & AM_RDO) {
  3708. res = FR_DENIED; /* Cannot remove R/O object */
  3709. }
  3710. }
  3711. if (res == FR_OK) {
  3712. #if _FS_EXFAT
  3713. obj.fs = fs;
  3714. if (fs->fs_type == FS_EXFAT) {
  3715. obj.sclust = dclst = ld_dword(fs->dirbuf + XDIR_FstClus);
  3716. obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  3717. obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  3718. } else
  3719. #endif
  3720. {
  3721. dclst = ld_clust(fs, dj.dir);
  3722. }
  3723. if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory ? */
  3724. #if _FS_RPATH != 0
  3725. if (dclst == fs->cdir) { /* Is it the current directory? */
  3726. res = FR_DENIED;
  3727. } else
  3728. #endif
  3729. {
  3730. sdj.obj.fs = fs; /* Open the sub-directory */
  3731. sdj.obj.sclust = dclst;
  3732. #if _FS_EXFAT
  3733. if (fs->fs_type == FS_EXFAT) {
  3734. sdj.obj.objsize = obj.objsize;
  3735. sdj.obj.stat = obj.stat;
  3736. }
  3737. #endif
  3738. res = dir_sdi(&sdj, 0);
  3739. if (res == FR_OK) {
  3740. res = dir_read(&sdj, 0); /* Read an item */
  3741. if (res == FR_OK) res = FR_DENIED; /* Not empty? */
  3742. if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
  3743. }
  3744. }
  3745. }
  3746. }
  3747. if (res == FR_OK) {
  3748. res = dir_remove(&dj); /* Remove the directory entry */
  3749. if (res == FR_OK && dclst) { /* Remove the cluster chain if exist */
  3750. #if _FS_EXFAT
  3751. res = remove_chain(&obj, dclst, 0);
  3752. #else
  3753. res = remove_chain(&dj.obj, dclst, 0);
  3754. #endif
  3755. }
  3756. if (res == FR_OK) res = sync_fs(fs);
  3757. }
  3758. }
  3759. FREE_NAMBUF();
  3760. }
  3761. LEAVE_FF(fs, res);
  3762. }
  3763. /*-----------------------------------------------------------------------*/
  3764. /* Create a Directory */
  3765. /*-----------------------------------------------------------------------*/
  3766. FRESULT f_mkdir (
  3767. FATFS *fs,
  3768. const TCHAR* path /* Pointer to the directory path */
  3769. )
  3770. {
  3771. FRESULT res;
  3772. DIR dj;
  3773. BYTE *dir;
  3774. UINT n;
  3775. DWORD dsc, dcl, pcl, tm;
  3776. DEF_NAMBUF
  3777. /* Get logical drive */
  3778. res = find_volume(fs, FA_WRITE);
  3779. dj.obj.fs = fs;
  3780. if (res == FR_OK) {
  3781. INIT_NAMBUF(fs);
  3782. res = follow_path(&dj, path); /* Follow the file path */
  3783. if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
  3784. if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) {
  3785. res = FR_INVALID_NAME;
  3786. }
  3787. if (res == FR_NO_FILE) { /* Can create a new directory */
  3788. dcl = create_chain(&dj.obj, 0); /* Allocate a cluster for the new directory table */
  3789. dj.obj.objsize = (DWORD)fs->csize * SS(fs);
  3790. res = FR_OK;
  3791. if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
  3792. if (dcl == 1) res = FR_INT_ERR;
  3793. if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3794. if (res == FR_OK) res = sync_window(fs); /* Flush FAT */
  3795. tm = GET_FATTIME();
  3796. if (res == FR_OK) { /* Initialize the new directory table */
  3797. dsc = clust2sect(fs, dcl);
  3798. dir = fs->win;
  3799. mem_set(dir, 0, SS(fs));
  3800. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  3801. mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */
  3802. dir[DIR_Name] = '.';
  3803. dir[DIR_Attr] = AM_DIR;
  3804. st_dword(dir + DIR_ModTime, tm);
  3805. st_clust(fs, dir, dcl);
  3806. mem_cpy(dir + SZDIRE, dir, SZDIRE); /* Create ".." entry */
  3807. dir[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
  3808. if (fs->fs_type == FS_FAT32 && pcl == fs->dirbase) pcl = 0;
  3809. st_clust(fs, dir + SZDIRE, pcl);
  3810. }
  3811. for (n = fs->csize; n; n--) { /* Write dot entries and clear following sectors */
  3812. fs->winsect = dsc++;
  3813. fs->wflag = 1;
  3814. res = sync_window(fs);
  3815. if (res != FR_OK) break;
  3816. mem_set(dir, 0, SS(fs));
  3817. }
  3818. }
  3819. if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */
  3820. if (res == FR_OK) {
  3821. #if _FS_EXFAT
  3822. if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
  3823. st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */
  3824. st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
  3825. st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)dj.obj.objsize); /* File size needs to be valid */
  3826. st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)dj.obj.objsize);
  3827. fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag (contiguous) */
  3828. fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
  3829. res = store_xdir(&dj);
  3830. } else
  3831. #endif
  3832. {
  3833. dir = dj.dir;
  3834. st_dword(dir + DIR_ModTime, tm); /* Created time */
  3835. st_clust(fs, dir, dcl); /* Table start cluster */
  3836. dir[DIR_Attr] = AM_DIR; /* Attribute */
  3837. fs->wflag = 1;
  3838. }
  3839. if (res == FR_OK) res = sync_fs(fs);
  3840. } else {
  3841. remove_chain(&dj.obj, dcl, 0); /* Could not register, remove cluster chain */
  3842. }
  3843. }
  3844. FREE_NAMBUF();
  3845. }
  3846. LEAVE_FF(fs, res);
  3847. }
  3848. /*-----------------------------------------------------------------------*/
  3849. /* Rename a File/Directory */
  3850. /*-----------------------------------------------------------------------*/
  3851. FRESULT f_rename (
  3852. FATFS *fs,
  3853. const TCHAR* path_old, /* Pointer to the object name to be renamed */
  3854. const TCHAR* path_new /* Pointer to the new name */
  3855. )
  3856. {
  3857. FRESULT res;
  3858. DIR djo, djn;
  3859. BYTE buf[_FS_EXFAT ? SZDIRE * 2 : 24], *dir;
  3860. DWORD dw;
  3861. DEF_NAMBUF
  3862. res = find_volume(fs, FA_WRITE);
  3863. if (res == FR_OK) {
  3864. djo.obj.fs = fs;
  3865. INIT_NAMBUF(fs);
  3866. res = follow_path(&djo, path_old); /* Check old object */
  3867. if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */
  3868. #if _FS_LOCK != 0
  3869. if (res == FR_OK) res = chk_lock(&djo, 2);
  3870. #endif
  3871. if (res == FR_OK) { /* Object to be renamed is found */
  3872. #if _FS_EXFAT
  3873. if (fs->fs_type == FS_EXFAT) { /* At exFAT */
  3874. BYTE nf, nn;
  3875. WORD nh;
  3876. mem_cpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
  3877. mem_cpy(&djn, &djo, sizeof djo);
  3878. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  3879. if (res == FR_OK) { /* Is new name already in use by any other object? */
  3880. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  3881. }
  3882. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  3883. res = dir_register(&djn); /* Register the new entry */
  3884. if (res == FR_OK) {
  3885. nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];
  3886. nh = ld_word(fs->dirbuf + XDIR_NameHash);
  3887. mem_cpy(fs->dirbuf, buf, SZDIRE * 2);
  3888. fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;
  3889. st_word(fs->dirbuf + XDIR_NameHash, nh);
  3890. /* Start of critical section where any interruption can cause a cross-link */
  3891. res = store_xdir(&djn);
  3892. }
  3893. }
  3894. } else
  3895. #endif
  3896. { /* At FAT12/FAT16/FAT32 */
  3897. mem_cpy(buf, djo.dir + DIR_Attr, 21); /* Save information about the object except name */
  3898. mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
  3899. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  3900. if (res == FR_OK) { /* Is new name already in use by any other object? */
  3901. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  3902. }
  3903. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  3904. res = dir_register(&djn); /* Register the new entry */
  3905. if (res == FR_OK) {
  3906. dir = djn.dir; /* Copy information about object except name */
  3907. mem_cpy(dir + 13, buf + 2, 19);
  3908. dir[DIR_Attr] = buf[0] | AM_ARC;
  3909. fs->wflag = 1;
  3910. if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */
  3911. dw = clust2sect(fs, ld_clust(fs, dir));
  3912. if (!dw) {
  3913. res = FR_INT_ERR;
  3914. } else {
  3915. /* Start of critical section where any interruption can cause a cross-link */
  3916. res = move_window(fs, dw);
  3917. dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */
  3918. if (res == FR_OK && dir[1] == '.') {
  3919. st_clust(fs, dir, djn.obj.sclust);
  3920. fs->wflag = 1;
  3921. }
  3922. }
  3923. }
  3924. }
  3925. }
  3926. }
  3927. if (res == FR_OK) {
  3928. res = dir_remove(&djo); /* Remove old entry */
  3929. if (res == FR_OK) {
  3930. res = sync_fs(fs);
  3931. }
  3932. }
  3933. /* End of critical section */
  3934. }
  3935. FREE_NAMBUF();
  3936. }
  3937. LEAVE_FF(fs, res);
  3938. }
  3939. #endif /* !_FS_READONLY */
  3940. #endif /* _FS_MINIMIZE == 0 */
  3941. #endif /* _FS_MINIMIZE <= 1 */
  3942. #endif /* _FS_MINIMIZE <= 2 */
  3943. #if _USE_CHMOD && !_FS_READONLY
  3944. /*-----------------------------------------------------------------------*/
  3945. /* Change Attribute */
  3946. /*-----------------------------------------------------------------------*/
  3947. FRESULT f_chmod (
  3948. FATFS *fs,
  3949. const TCHAR* path, /* Pointer to the file path */
  3950. BYTE attr, /* Attribute bits */
  3951. BYTE mask /* Attribute mask to change */
  3952. )
  3953. {
  3954. FRESULT res;
  3955. DIR dj;
  3956. DEF_NAMBUF
  3957. res = find_volume(fs, FA_WRITE); /* Get logical drive */
  3958. dj.obj.fs = fs;
  3959. if (res == FR_OK) {
  3960. INIT_NAMBUF(fs);
  3961. res = follow_path(&dj, path); /* Follow the file path */
  3962. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  3963. if (res == FR_OK) {
  3964. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  3965. #if _FS_EXFAT
  3966. if (fs->fs_type == FS_EXFAT) {
  3967. fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  3968. res = store_xdir(&dj);
  3969. } else
  3970. #endif
  3971. {
  3972. dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  3973. fs->wflag = 1;
  3974. }
  3975. if (res == FR_OK) res = sync_fs(fs);
  3976. }
  3977. FREE_NAMBUF();
  3978. }
  3979. LEAVE_FF(fs, res);
  3980. }
  3981. /*-----------------------------------------------------------------------*/
  3982. /* Change Timestamp */
  3983. /*-----------------------------------------------------------------------*/
  3984. FRESULT f_utime (
  3985. FATFS *fs,
  3986. const TCHAR* path, /* Pointer to the file/directory name */
  3987. const FILINFO* fno /* Pointer to the time stamp to be set */
  3988. )
  3989. {
  3990. FRESULT res;
  3991. DIR dj;
  3992. DEF_NAMBUF
  3993. res = find_volume(fs, FA_WRITE); /* Get logical drive */
  3994. dj.obj.fs = fs;
  3995. if (res == FR_OK) {
  3996. INIT_NAMBUF(fs);
  3997. res = follow_path(&dj, path); /* Follow the file path */
  3998. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  3999. if (res == FR_OK) {
  4000. #if _FS_EXFAT
  4001. if (fs->fs_type == FS_EXFAT) {
  4002. st_dword(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4003. res = store_xdir(&dj);
  4004. } else
  4005. #endif
  4006. {
  4007. st_dword(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4008. fs->wflag = 1;
  4009. }
  4010. if (res == FR_OK) res = sync_fs(fs);
  4011. }
  4012. FREE_NAMBUF();
  4013. }
  4014. LEAVE_FF(fs, res);
  4015. }
  4016. #endif /* _USE_CHMOD && !_FS_READONLY */
  4017. #if _USE_LABEL
  4018. /*-----------------------------------------------------------------------*/
  4019. /* Get Volume Label */
  4020. /*-----------------------------------------------------------------------*/
  4021. FRESULT f_getlabel (
  4022. FATFS *fs,
  4023. TCHAR* label, /* Pointer to a buffer to return the volume label */
  4024. DWORD* vsn /* Pointer to a variable to return the volume serial number */
  4025. )
  4026. {
  4027. FRESULT res;
  4028. DIR dj;
  4029. UINT si, di;
  4030. #if _LFN_UNICODE || _FS_EXFAT
  4031. WCHAR w;
  4032. #endif
  4033. /* Get logical drive */
  4034. res = find_volume(fs, 0);
  4035. /* Get volume label */
  4036. if (res == FR_OK && label) {
  4037. dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
  4038. res = dir_sdi(&dj, 0);
  4039. if (res == FR_OK) {
  4040. res = dir_read(&dj, 1); /* Find a volume label entry */
  4041. if (res == FR_OK) {
  4042. #if _FS_EXFAT
  4043. if (fs->fs_type == FS_EXFAT) {
  4044. for (si = di = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
  4045. w = ld_word(dj.dir + XDIR_Label + si * 2);
  4046. #if _LFN_UNICODE
  4047. label[di++] = w;
  4048. #else
  4049. w = ff_convert(w, 0); /* Unicode -> OEM */
  4050. if (w == 0) w = '?'; /* Replace wrong character */
  4051. if (_DF1S && w >= 0x100) label[di++] = (char)(w >> 8);
  4052. label[di++] = (char)w;
  4053. #endif
  4054. }
  4055. label[di] = 0;
  4056. } else
  4057. #endif
  4058. {
  4059. si = di = 0; /* Extract volume label from AM_VOL entry with code comversion */
  4060. do {
  4061. #if _LFN_UNICODE
  4062. w = (si < 11) ? dj.dir[si++] : ' ';
  4063. if (IsDBCS1(w) && si < 11 && IsDBCS2(dj.dir[si])) {
  4064. w = w << 8 | dj.dir[si++];
  4065. }
  4066. label[di++] = ff_convert(w, 1); /* OEM -> Unicode */
  4067. #else
  4068. label[di++] = dj.dir[si++];
  4069. #endif
  4070. } while (di < 11);
  4071. do { /* Truncate trailing spaces */
  4072. label[di] = 0;
  4073. if (di == 0) break;
  4074. } while (label[--di] == ' ');
  4075. }
  4076. }
  4077. }
  4078. if (res == FR_NO_FILE) { /* No label entry and return nul string */
  4079. label[0] = 0;
  4080. res = FR_OK;
  4081. }
  4082. }
  4083. /* Get volume serial number */
  4084. if (res == FR_OK && vsn) {
  4085. res = move_window(fs, fs->volbase);
  4086. if (res == FR_OK) {
  4087. switch (fs->fs_type) {
  4088. case FS_EXFAT: di = BPB_VolIDEx; break;
  4089. case FS_FAT32: di = BS_VolID32; break;
  4090. default: di = BS_VolID;
  4091. }
  4092. *vsn = ld_dword(fs->win + di);
  4093. }
  4094. }
  4095. LEAVE_FF(fs, res);
  4096. }
  4097. #if !_FS_READONLY
  4098. /*-----------------------------------------------------------------------*/
  4099. /* Set Volume Label */
  4100. /*-----------------------------------------------------------------------*/
  4101. FRESULT f_setlabel (
  4102. FATFS *fs,
  4103. const TCHAR* label /* Pointer to the volume label to set */
  4104. )
  4105. {
  4106. FRESULT res;
  4107. DIR dj;
  4108. BYTE dirvn[22];
  4109. UINT i, j, slen;
  4110. WCHAR w;
  4111. static const char badchr[] = "\"*+,.:;<=>\?[]|\x7F";
  4112. /* Get logical drive */
  4113. res = find_volume(fs, FA_WRITE);
  4114. if (res != FR_OK) LEAVE_FF(fs, res);
  4115. dj.obj.fs = fs;
  4116. /* Get length of given volume label */
  4117. for (slen = 0; (UINT)label[slen] >= ' '; slen++) { } /* Get name length */
  4118. #if _FS_EXFAT
  4119. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  4120. for (i = j = 0; i < slen; ) { /* Create volume label in directory form */
  4121. w = label[i++];
  4122. #if !_LFN_UNICODE
  4123. if (IsDBCS1(w)) {
  4124. w = (i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
  4125. }
  4126. w = ff_convert(w, 1);
  4127. #endif
  4128. if (w == 0 || chk_chr(badchr, w) || j == 22) { /* Check validity check validity of the volume label */
  4129. LEAVE_FF(fs, FR_INVALID_NAME);
  4130. }
  4131. st_word(dirvn + j, w); j += 2;
  4132. }
  4133. slen = j;
  4134. } else
  4135. #endif
  4136. { /* On the FAT12/16/32 volume */
  4137. for ( ; slen && label[slen - 1] == ' '; slen--) ; /* Remove trailing spaces */
  4138. if (slen) { /* Is there a volume label to be set? */
  4139. dirvn[0] = 0; i = j = 0; /* Create volume label in directory form */
  4140. do {
  4141. #if _LFN_UNICODE
  4142. w = ff_convert(ff_wtoupper(label[i++]), 0);
  4143. #else
  4144. w = (BYTE)label[i++];
  4145. if (IsDBCS1(w)) {
  4146. w = (j < 10 && i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
  4147. }
  4148. #if _USE_LFN != 0
  4149. w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0);
  4150. #else
  4151. if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */
  4152. #ifdef _EXCVT
  4153. if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */
  4154. #else
  4155. if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */
  4156. #endif
  4157. #endif
  4158. #endif
  4159. if (w == 0 || chk_chr(badchr, w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
  4160. LEAVE_FF(fs, FR_INVALID_NAME);
  4161. }
  4162. if (w >= 0x100) dirvn[j++] = (BYTE)(w >> 8);
  4163. dirvn[j++] = (BYTE)w;
  4164. } while (i < slen);
  4165. while (j < 11) dirvn[j++] = ' '; /* Fill remaining name field */
  4166. if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
  4167. }
  4168. }
  4169. /* Set volume label */
  4170. dj.obj.sclust = 0; /* Open root directory */
  4171. res = dir_sdi(&dj, 0);
  4172. if (res == FR_OK) {
  4173. res = dir_read(&dj, 1); /* Get volume label entry */
  4174. if (res == FR_OK) {
  4175. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4176. dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2); /* Change the volume label */
  4177. mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
  4178. } else {
  4179. if (slen) {
  4180. mem_cpy(dj.dir, dirvn, 11); /* Change the volume label */
  4181. } else {
  4182. dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
  4183. }
  4184. }
  4185. fs->wflag = 1;
  4186. res = sync_fs(fs);
  4187. } else { /* No volume label entry is found or error */
  4188. if (res == FR_NO_FILE) {
  4189. res = FR_OK;
  4190. if (slen) { /* Create a volume label entry */
  4191. res = dir_alloc(&dj, 1); /* Allocate an entry */
  4192. if (res == FR_OK) {
  4193. mem_set(dj.dir, 0, SZDIRE); /* Clear the entry */
  4194. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4195. dj.dir[XDIR_Type] = 0x83; /* Create 83 entry */
  4196. dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2);
  4197. mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
  4198. } else {
  4199. dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
  4200. mem_cpy(dj.dir, dirvn, 11);
  4201. }
  4202. fs->wflag = 1;
  4203. res = sync_fs(fs);
  4204. }
  4205. }
  4206. }
  4207. }
  4208. }
  4209. LEAVE_FF(fs, res);
  4210. }
  4211. #endif /* !_FS_READONLY */
  4212. #endif /* _USE_LABEL */
  4213. #if _USE_EXPAND && !_FS_READONLY
  4214. /*-----------------------------------------------------------------------*/
  4215. /* Allocate a Contiguous Blocks to the File */
  4216. /*-----------------------------------------------------------------------*/
  4217. FRESULT f_expand (
  4218. FIL* fp, /* Pointer to the file object */
  4219. FSIZE_t fsz, /* File size to be expanded to */
  4220. BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
  4221. )
  4222. {
  4223. FRESULT res;
  4224. FATFS *fs;
  4225. DWORD n, clst, stcl, scl, ncl, tcl, lclst;
  4226. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4227. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4228. if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
  4229. #if _FS_EXFAT
  4230. if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
  4231. #endif
  4232. n = (DWORD)fs->csize * SS(fs); /* Cluster size */
  4233. tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
  4234. stcl = fs->last_clst; lclst = 0;
  4235. if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
  4236. #if _FS_EXFAT
  4237. if (fs->fs_type == FS_EXFAT) {
  4238. scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
  4239. if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
  4240. if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
  4241. if (res == FR_OK) {
  4242. if (opt) {
  4243. res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
  4244. lclst = scl + tcl - 1;
  4245. } else {
  4246. lclst = scl - 1;
  4247. }
  4248. }
  4249. } else
  4250. #endif
  4251. {
  4252. scl = clst = stcl; ncl = 0;
  4253. for (;;) { /* Find a contiguous cluster block */
  4254. n = get_fat(&fp->obj, clst);
  4255. if (++clst >= fs->n_fatent) clst = 2;
  4256. if (n == 1) { res = FR_INT_ERR; break; }
  4257. if (n == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  4258. if (n == 0) { /* Is it a free cluster? */
  4259. if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
  4260. } else {
  4261. scl = clst; ncl = 0; /* Not a free cluster */
  4262. }
  4263. if (clst == stcl) { res = FR_DENIED; break; } /* No contiguous cluster? */
  4264. }
  4265. if (res == FR_OK) {
  4266. if (opt) {
  4267. for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
  4268. res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
  4269. if (res != FR_OK) break;
  4270. lclst = clst;
  4271. }
  4272. } else {
  4273. lclst = scl - 1;
  4274. }
  4275. }
  4276. }
  4277. if (res == FR_OK) {
  4278. fs->last_clst = lclst; /* Set suggested start cluster to start next */
  4279. if (opt) {
  4280. fp->obj.sclust = scl; /* Update object allocation information */
  4281. fp->obj.objsize = fsz;
  4282. if (_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
  4283. fp->flag |= FA_MODIFIED;
  4284. if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
  4285. fs->free_clst -= tcl;
  4286. fs->fsi_flag |= 1;
  4287. }
  4288. }
  4289. }
  4290. LEAVE_FF(fs, res);
  4291. }
  4292. #endif /* _USE_EXPAND && !_FS_READONLY */
  4293. #if _USE_FORWARD
  4294. /*-----------------------------------------------------------------------*/
  4295. /* Forward data to the stream directly */
  4296. /*-----------------------------------------------------------------------*/
  4297. FRESULT f_forward (
  4298. FIL* fp, /* Pointer to the file object */
  4299. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  4300. UINT btf, /* Number of bytes to forward */
  4301. UINT* bf /* Pointer to number of bytes forwarded */
  4302. )
  4303. {
  4304. FRESULT res;
  4305. FATFS *fs;
  4306. DWORD clst, sect;
  4307. FSIZE_t remain;
  4308. UINT rcnt, csect;
  4309. BYTE *dbuf;
  4310. *bf = 0; /* Clear transfer byte counter */
  4311. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4312. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4313. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  4314. remain = fp->obj.objsize - fp->fptr;
  4315. if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
  4316. for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream goes busy */
  4317. fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) {
  4318. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  4319. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  4320. if (csect == 0) { /* On the cluster boundary? */
  4321. clst = (fp->fptr == 0) ? /* On the top of the file? */
  4322. fp->obj.sclust : get_fat(&fp->obj, fp->clust);
  4323. if (clst <= 1) ABORT(fs, FR_INT_ERR);
  4324. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  4325. fp->clust = clst; /* Update current cluster */
  4326. }
  4327. }
  4328. sect = clust2sect(fs, fp->clust); /* Get current data sector */
  4329. if (!sect) ABORT(fs, FR_INT_ERR);
  4330. sect += csect;
  4331. #if _FS_TINY
  4332. if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
  4333. dbuf = fs->win;
  4334. #else
  4335. if (fp->sect != sect) { /* Fill sector cache with file data */
  4336. #if !_FS_READONLY
  4337. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  4338. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4339. fp->flag &= (BYTE)~FA_DIRTY;
  4340. }
  4341. #endif
  4342. if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4343. }
  4344. dbuf = fp->buf;
  4345. #endif
  4346. fp->sect = sect;
  4347. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  4348. if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
  4349. rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
  4350. if (!rcnt) ABORT(fs, FR_INT_ERR);
  4351. }
  4352. LEAVE_FF(fs, FR_OK);
  4353. }
  4354. #endif /* _USE_FORWARD */
  4355. #if _USE_MKFS && !_FS_READONLY
  4356. /*-----------------------------------------------------------------------*/
  4357. /* Create FAT file system on the logical drive */
  4358. /*-----------------------------------------------------------------------*/
  4359. FRESULT f_mkfs (
  4360. FATFS *fs,
  4361. BYTE opt, /* Format option */
  4362. DWORD au, /* Size of allocation unit [byte] */
  4363. void* work, /* Pointer to working buffer */
  4364. UINT len /* Size of working buffer */
  4365. )
  4366. {
  4367. const UINT n_fats = 1; /* Number of FATs for FAT12/16/32 volume (1 or 2) */
  4368. const UINT n_rootdir = 512; /* Number of root directory entries for FAT12/16 volume */
  4369. static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT12/16 volume (4Ks unit) */
  4370. static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */
  4371. BYTE fmt, sys, *buf, *pte, part; void *pdrv;
  4372. WORD ss;
  4373. DWORD szb_buf, sz_buf, sz_blk, n_clst, pau, sect, nsect, n;
  4374. DWORD b_vol, b_fat, b_data; /* Base LBA for volume, fat, data */
  4375. DWORD sz_vol, sz_rsv, sz_fat, sz_dir; /* Size for volume, fat, dir, data */
  4376. UINT i;
  4377. DSTATUS stat;
  4378. #if _USE_TRIM || _FS_EXFAT
  4379. DWORD tbl[3];
  4380. #endif
  4381. /* Check mounted drive and clear work area */
  4382. fs->fs_type = 0; /* Clear mounted volume */
  4383. pdrv = fs->drv; /* Physical drive */
  4384. part = LD2PT(fs); /* Partition (0:create as new, 1-4:get from partition table) */
  4385. /* Check physical drive status */
  4386. disk_ioctl(pdrv, IOCTL_INIT, &stat);
  4387. if (stat & STA_NOINIT) return FR_NOT_READY;
  4388. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  4389. if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk) != RES_OK || !sz_blk || sz_blk > 32768 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Erase block to align data area */
  4390. #if _MAX_SS != _MIN_SS /* Get sector size of the medium */
  4391. if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;
  4392. if (ss > _MAX_SS || ss < _MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
  4393. #else
  4394. ss = _MAX_SS;
  4395. #endif
  4396. if ((au != 0 && au < ss) || au > 0x1000000 || (au & (au - 1))) return FR_INVALID_PARAMETER; /* Check if au is valid */
  4397. au /= ss; /* Cluster size in unit of sector */
  4398. /* Get working buffer */
  4399. buf = (BYTE*)work; /* Working buffer */
  4400. sz_buf = len / ss; /* Size of working buffer (sector) */
  4401. szb_buf = sz_buf * ss; /* Size of working buffer (byte) */
  4402. if (!szb_buf) return FR_MKFS_ABORTED;
  4403. /* Determine where the volume to be located (b_vol, sz_vol) */
  4404. if (_MULTI_PARTITION && part != 0) {
  4405. /* Get partition information from partition table in the MBR */
  4406. if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Load MBR */
  4407. if (ld_word(buf + BS_55AA) != 0xAA55) return FR_MKFS_ABORTED; /* Check if MBR is valid */
  4408. pte = buf + (MBR_Table + (part - 1) * SZ_PTE);
  4409. if (!pte[PTE_System]) return FR_MKFS_ABORTED; /* No partition? */
  4410. b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */
  4411. sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */
  4412. } else {
  4413. /* Create a single-partition in this function */
  4414. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) return FR_DISK_ERR;
  4415. b_vol = (opt & FM_SFD) ? 0 : 63; /* Volume start sector */
  4416. if (sz_vol < b_vol) return FR_MKFS_ABORTED;
  4417. sz_vol -= b_vol; /* Volume size */
  4418. }
  4419. if (sz_vol < 50) return FR_MKFS_ABORTED; /* Check if volume size is >=50s */
  4420. /* Pre-determine the FAT type */
  4421. do {
  4422. if (_FS_EXFAT && (opt & FM_EXFAT)) { /* exFAT possible? */
  4423. if ((opt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || au > 128) { /* exFAT only, vol >= 64Ms or au > 128s ? */
  4424. fmt = FS_EXFAT; break;
  4425. }
  4426. }
  4427. if (au > 128) return FR_INVALID_PARAMETER; /* Too large au for FAT/FAT32 */
  4428. if (opt & FM_FAT32) { /* FAT32 possible? */
  4429. if ((opt & FM_ANY) == FM_FAT32 || !(opt & FM_FAT)) { /* FAT32 only or no-FAT? */
  4430. fmt = FS_FAT32; break;
  4431. }
  4432. }
  4433. if (!(opt & FM_FAT)) return FR_INVALID_PARAMETER; /* no-FAT? */
  4434. fmt = FS_FAT16;
  4435. } while (0);
  4436. #if _FS_EXFAT
  4437. if (fmt == FS_EXFAT) { /* Create an exFAT volume */
  4438. DWORD szb_bit, szb_case, sum, nb, cl;
  4439. WCHAR ch, si;
  4440. UINT j, st;
  4441. BYTE b;
  4442. if (sz_vol < 0x1000) return FR_MKFS_ABORTED; /* Too small volume? */
  4443. #if _USE_TRIM
  4444. tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
  4445. disk_ioctl(pdrv, CTRL_TRIM, tbl);
  4446. #endif
  4447. /* Determine FAT location, data location and number of clusters */
  4448. if (!au) { /* au auto-selection */
  4449. au = 8;
  4450. if (sz_vol >= 0x80000) au = 64; /* >= 512Ks */
  4451. if (sz_vol >= 0x4000000) au = 256; /* >= 64Ms */
  4452. }
  4453. b_fat = b_vol + 32; /* FAT start at offset 32 */
  4454. sz_fat = ((sz_vol / au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */
  4455. b_data = (b_fat + sz_fat + sz_blk - 1) & ~(sz_blk - 1); /* Align data area to the erase block boundary */
  4456. if (b_data >= sz_vol / 2) return FR_MKFS_ABORTED; /* Too small volume? */
  4457. n_clst = (sz_vol - (b_data - b_vol)) / au; /* Number of clusters */
  4458. if (n_clst <16) return FR_MKFS_ABORTED; /* Too few clusters? */
  4459. if (n_clst > MAX_EXFAT) return FR_MKFS_ABORTED; /* Too many clusters? */
  4460. szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */
  4461. tbl[0] = (szb_bit + au * ss - 1) / (au * ss); /* Number of allocation bitmap clusters */
  4462. /* Create a compressed up-case table */
  4463. sect = b_data + au * tbl[0]; /* Table start sector */
  4464. sum = 0; /* Table checksum to be stored in the 82 entry */
  4465. st = si = i = j = szb_case = 0;
  4466. do {
  4467. switch (st) {
  4468. case 0:
  4469. ch = ff_wtoupper(si); /* Get an up-case char */
  4470. if (ch != si) {
  4471. si++; break; /* Store the up-case char if exist */
  4472. }
  4473. for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */
  4474. if (j >= 128) {
  4475. ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 */
  4476. }
  4477. st = 1; /* Do not compress short run */
  4478. /* continue */
  4479. case 1:
  4480. ch = si++; /* Fill the short run */
  4481. if (--j == 0) st = 0;
  4482. break;
  4483. default:
  4484. ch = (WCHAR)j; si += j; /* Number of chars to skip */
  4485. st = 0;
  4486. }
  4487. sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */
  4488. sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);
  4489. i += 2; szb_case += 2;
  4490. if (!si || i == szb_buf) { /* Write buffered data when buffer full or end of process */
  4491. n = (i + ss - 1) / ss;
  4492. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4493. sect += n; i = 0;
  4494. }
  4495. } while (si);
  4496. tbl[1] = (szb_case + au * ss - 1) / (au * ss); /* Number of up-case table clusters */
  4497. tbl[2] = 1; /* Number of root dir clusters */
  4498. /* Initialize the allocation bitmap */
  4499. sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of sectors */
  4500. nb = tbl[0] + tbl[1] + tbl[2]; /* Number of clusters in-use by system */
  4501. do {
  4502. mem_set(buf, 0, szb_buf);
  4503. for (i = 0; nb >= 8 && i < szb_buf; buf[i++] = 0xFF, nb -= 8) ;
  4504. for (b = 1; nb && i < szb_buf; buf[i] |= b, b <<= 1, nb--) ;
  4505. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  4506. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4507. sect += n; nsect -= n;
  4508. } while (nsect);
  4509. /* Initialize the FAT */
  4510. sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */
  4511. j = nb = cl = 0;
  4512. do {
  4513. mem_set(buf, 0, szb_buf); i = 0; /* Clear work area and reset write index */
  4514. if (cl == 0) { /* Set entry 0 and 1 */
  4515. st_dword(buf + i, 0xFFFFFFF8); i += 4; cl++;
  4516. st_dword(buf + i, 0xFFFFFFFF); i += 4; cl++;
  4517. }
  4518. do { /* Create chains of bitmap, up-case and root dir */
  4519. while (nb && i < szb_buf) { /* Create a chain */
  4520. st_dword(buf + i, (nb > 1) ? cl + 1 : 0xFFFFFFFF);
  4521. i += 4; cl++; nb--;
  4522. }
  4523. if (!nb && j < 3) nb = tbl[j++]; /* Next chain */
  4524. } while (nb && i < szb_buf);
  4525. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  4526. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4527. sect += n; nsect -= n;
  4528. } while (nsect);
  4529. /* Initialize the root directory */
  4530. mem_set(buf, 0, szb_buf);
  4531. buf[SZDIRE * 0 + 0] = 0x83; /* 83 entry (volume label) */
  4532. buf[SZDIRE * 1 + 0] = 0x81; /* 81 entry (allocation bitmap) */
  4533. st_dword(buf + SZDIRE * 1 + 20, 2);
  4534. st_dword(buf + SZDIRE * 1 + 24, szb_bit);
  4535. buf[SZDIRE * 2 + 0] = 0x82; /* 82 entry (up-case table) */
  4536. st_dword(buf + SZDIRE * 2 + 4, sum);
  4537. st_dword(buf + SZDIRE * 2 + 20, 2 + tbl[0]);
  4538. st_dword(buf + SZDIRE * 2 + 24, szb_case);
  4539. sect = b_data + au * (tbl[0] + tbl[1]); nsect = au; /* Start of the root directory and number of sectors */
  4540. do { /* Fill root directory sectors */
  4541. n = (nsect > sz_buf) ? sz_buf : nsect;
  4542. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4543. mem_set(buf, 0, ss);
  4544. sect += n; nsect -= n;
  4545. } while (nsect);
  4546. /* Create two set of the exFAT VBR blocks */
  4547. sect = b_vol;
  4548. for (n = 0; n < 2; n++) {
  4549. /* Main record (+0) */
  4550. mem_set(buf, 0, ss);
  4551. mem_cpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
  4552. st_dword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */
  4553. st_dword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */
  4554. st_dword(buf + BPB_FatOfsEx, b_fat - b_vol); /* FAT offset [sector] */
  4555. st_dword(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */
  4556. st_dword(buf + BPB_DataOfsEx, b_data - b_vol); /* Data offset [sector] */
  4557. st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */
  4558. st_dword(buf + BPB_RootClusEx, 2 + tbl[0] + tbl[1]); /* Root dir cluster # */
  4559. st_dword(buf + BPB_VolIDEx, GET_FATTIME()); /* VSN */
  4560. st_word(buf + BPB_FSVerEx, 0x100); /* File system version (1.00) */
  4561. for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */
  4562. for (buf[BPB_SecPerClusEx] = 0, i = au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */
  4563. buf[BPB_NumFATsEx] = 1; /* Number of FATs */
  4564. buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */
  4565. st_word(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */
  4566. st_word(buf + BS_55AA, 0xAA55); /* Signature (placed here regardless of sector size) */
  4567. for (i = sum = 0; i < ss; i++) { /* VBR checksum */
  4568. if (i != BPB_VolFlagEx && i != BPB_VolFlagEx + 1 && i != BPB_PercInUseEx) sum = xsum32(buf[i], sum);
  4569. }
  4570. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4571. /* Extended bootstrap record (+1..+8) */
  4572. mem_set(buf, 0, ss);
  4573. st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */
  4574. for (j = 1; j < 9; j++) {
  4575. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  4576. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4577. }
  4578. /* OEM/Reserved record (+9..+10) */
  4579. mem_set(buf, 0, ss);
  4580. for ( ; j < 11; j++) {
  4581. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  4582. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4583. }
  4584. /* Sum record (+11) */
  4585. for (i = 0; i < ss; i += 4) st_dword(buf + i, sum); /* Fill with checksum value */
  4586. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4587. }
  4588. } else
  4589. #endif /* _FS_EXFAT */
  4590. { /* Create an FAT12/16/32 volume */
  4591. do {
  4592. pau = au;
  4593. /* Pre-determine number of clusters and FAT sub-type */
  4594. if (fmt == FS_FAT32) { /* FAT32 volume */
  4595. if (!pau) { /* au auto-selection */
  4596. n = sz_vol / 0x20000; /* Volume size in unit of 128KS */
  4597. for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */
  4598. }
  4599. n_clst = sz_vol / pau; /* Number of clusters */
  4600. sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */
  4601. sz_rsv = 32; /* Number of reserved sectors */
  4602. sz_dir = 0; /* No static directory */
  4603. if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) return FR_MKFS_ABORTED;
  4604. } else { /* FAT12/16 volume */
  4605. if (!pau) { /* au auto-selection */
  4606. n = sz_vol / 0x1000; /* Volume size in unit of 4KS */
  4607. for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */
  4608. }
  4609. n_clst = sz_vol / pau;
  4610. if (n_clst > MAX_FAT12) {
  4611. n = n_clst * 2 + 4; /* FAT size [byte] */
  4612. } else {
  4613. fmt = FS_FAT12;
  4614. n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */
  4615. }
  4616. sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */
  4617. sz_rsv = 1; /* Number of reserved sectors */
  4618. sz_dir = (DWORD)n_rootdir * SZDIRE / ss; /* Rootdir size [sector] */
  4619. }
  4620. b_fat = b_vol + sz_rsv; /* FAT base */
  4621. b_data = b_fat + sz_fat * n_fats + sz_dir; /* Data base */
  4622. /* Align data base to erase block boundary (for flash memory media) */
  4623. n = ((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data; /* Next nearest erase block from current data base */
  4624. if (fmt == FS_FAT32) { /* FAT32: Move FAT base */
  4625. sz_rsv += n; b_fat += n;
  4626. } else { /* FAT12/16: Expand FAT size */
  4627. sz_fat += n / n_fats;
  4628. }
  4629. /* Determine number of clusters and final check of validity of the FAT sub-type */
  4630. if (sz_vol < b_data + pau * 16 - b_vol) return FR_MKFS_ABORTED; /* Too small volume */
  4631. n_clst = (sz_vol - sz_rsv - sz_fat * n_fats - sz_dir) / pau;
  4632. if (fmt == FS_FAT32) {
  4633. if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32 */
  4634. if (!au && (au = pau / 2) != 0) continue; /* Adjust cluster size and retry */
  4635. return FR_MKFS_ABORTED;
  4636. }
  4637. }
  4638. if (fmt == FS_FAT16) {
  4639. if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */
  4640. if (!au && (pau * 2) <= 64) {
  4641. au = pau * 2; continue; /* Adjust cluster size and retry */
  4642. }
  4643. if ((opt & FM_FAT32)) {
  4644. fmt = FS_FAT32; continue; /* Switch type to FAT32 and retry */
  4645. }
  4646. if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  4647. return FR_MKFS_ABORTED;
  4648. }
  4649. if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */
  4650. if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  4651. return FR_MKFS_ABORTED;
  4652. }
  4653. }
  4654. if (fmt == FS_FAT12 && n_clst > MAX_FAT12) return FR_MKFS_ABORTED; /* Too many clusters for FAT12 */
  4655. /* Ok, it is the valid cluster configuration */
  4656. break;
  4657. } while (1);
  4658. #if _USE_TRIM
  4659. tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
  4660. disk_ioctl(pdrv, CTRL_TRIM, tbl);
  4661. #endif
  4662. /* Create FAT VBR */
  4663. mem_set(buf, 0, ss);
  4664. mem_cpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */
  4665. st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */
  4666. buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */
  4667. st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */
  4668. buf[BPB_NumFATs] = (BYTE)n_fats; /* Number of FATs */
  4669. st_word(buf + BPB_RootEntCnt, (WORD)((fmt == FS_FAT32) ? 0 : n_rootdir)); /* Number of root directory entries */
  4670. if (sz_vol < 0x10000) {
  4671. st_word(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */
  4672. } else {
  4673. st_dword(buf + BPB_TotSec32, sz_vol); /* Volume size in 32-bit LBA */
  4674. }
  4675. buf[BPB_Media] = 0xF8; /* Media descriptor byte */
  4676. st_word(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */
  4677. st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */
  4678. st_dword(buf + BPB_HiddSec, b_vol); /* Volume offset in the physical drive [sector] */
  4679. if (fmt == FS_FAT32) {
  4680. st_dword(buf + BS_VolID32, GET_FATTIME()); /* VSN */
  4681. st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */
  4682. st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */
  4683. st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */
  4684. st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */
  4685. buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */
  4686. buf[BS_BootSig32] = 0x29; /* Extended boot signature */
  4687. mem_cpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
  4688. } else {
  4689. st_dword(buf + BS_VolID, GET_FATTIME()); /* VSN */
  4690. st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */
  4691. buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */
  4692. buf[BS_BootSig] = 0x29; /* Extended boot signature */
  4693. mem_cpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
  4694. }
  4695. st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
  4696. if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the VBR sector */
  4697. /* Create FSINFO record if needed */
  4698. if (fmt == FS_FAT32) {
  4699. disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */
  4700. mem_set(buf, 0, ss);
  4701. st_dword(buf + FSI_LeadSig, 0x41615252);
  4702. st_dword(buf + FSI_StrucSig, 0x61417272);
  4703. st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
  4704. st_dword(buf + FSI_Nxt_Free, 2); /* Last allocated cluster# */
  4705. st_word(buf + BS_55AA, 0xAA55);
  4706. disk_write(pdrv, buf, b_vol + 7, 1); /* Write backup FSINFO (VBR + 7) */
  4707. disk_write(pdrv, buf, b_vol + 1, 1); /* Write original FSINFO (VBR + 1) */
  4708. }
  4709. /* Initialize FAT area */
  4710. mem_set(buf, 0, (UINT)szb_buf);
  4711. sect = b_fat; /* FAT start sector */
  4712. for (i = 0; i < n_fats; i++) { /* Initialize FATs each */
  4713. if (fmt == FS_FAT32) {
  4714. st_dword(buf + 0, 0xFFFFFFF8); /* Entry 0 */
  4715. st_dword(buf + 4, 0xFFFFFFFF); /* Entry 1 */
  4716. st_dword(buf + 8, 0x0FFFFFFF); /* Entry 2 (root directory) */
  4717. } else {
  4718. st_dword(buf + 0, (fmt == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* Entry 0 and 1 */
  4719. }
  4720. nsect = sz_fat; /* Number of FAT sectors */
  4721. do { /* Fill FAT sectors */
  4722. n = (nsect > sz_buf) ? sz_buf : nsect;
  4723. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
  4724. mem_set(buf, 0, ss);
  4725. sect += n; nsect -= n;
  4726. } while (nsect);
  4727. }
  4728. /* Initialize root directory (fill with zero) */
  4729. nsect = (fmt == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */
  4730. do {
  4731. n = (nsect > sz_buf) ? sz_buf : nsect;
  4732. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
  4733. sect += n; nsect -= n;
  4734. } while (nsect);
  4735. }
  4736. /* Determine system ID in the partition table */
  4737. if (_FS_EXFAT && fmt == FS_EXFAT) {
  4738. sys = 0x07; /* HPFS/NTFS/exFAT */
  4739. } else {
  4740. if (fmt == FS_FAT32) {
  4741. sys = 0x0C; /* FAT32X */
  4742. } else {
  4743. if (sz_vol >= 0x10000) {
  4744. sys = 0x06; /* FAT12/16 (>=64KS) */
  4745. } else {
  4746. sys = (fmt == FS_FAT16) ? 0x04 : 0x01; /* FAT16 (<64KS) : FAT12 (<64KS) */
  4747. }
  4748. }
  4749. }
  4750. if (_MULTI_PARTITION && part != 0) {
  4751. /* Update system ID in the partition table */
  4752. if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Read the MBR */
  4753. buf[MBR_Table + (part - 1) * SZ_PTE + PTE_System] = sys; /* Set system type */
  4754. if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it back to the MBR */
  4755. } else {
  4756. if (!(opt & FM_SFD)) {
  4757. /* Create partition table in FDISK format */
  4758. mem_set(buf, 0, ss);
  4759. st_word(buf + BS_55AA, 0xAA55); /* MBR signature */
  4760. pte = buf + MBR_Table; /* Create partition table for single partition in the drive */
  4761. pte[PTE_Boot] = 0; /* Boot indicator */
  4762. pte[PTE_StHead] = 1; /* Start head */
  4763. pte[PTE_StSec] = 1; /* Start sector */
  4764. pte[PTE_StCyl] = 0; /* Start cylinder */
  4765. pte[PTE_System] = sys; /* System type */
  4766. n = (b_vol + sz_vol) / (63 * 255); /* (End CHS is incorrect) */
  4767. pte[PTE_EdHead] = 254; /* End head */
  4768. pte[PTE_EdSec] = (BYTE)(n >> 2 | 63); /* End sector */
  4769. pte[PTE_EdCyl] = (BYTE)n; /* End cylinder */
  4770. st_dword(pte + PTE_StLba, b_vol); /* Start offset in LBA */
  4771. st_dword(pte + PTE_SizLba, sz_vol); /* Size in sectors */
  4772. if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
  4773. }
  4774. }
  4775. if (disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) return FR_DISK_ERR;
  4776. return FR_OK;
  4777. }
  4778. #if _MULTI_PARTITION
  4779. /*-----------------------------------------------------------------------*/
  4780. /* Create partition table on the physical drive */
  4781. /*-----------------------------------------------------------------------*/
  4782. FRESULT f_fdisk (
  4783. void *pdrv, /* Physical drive number */
  4784. const DWORD* szt, /* Pointer to the size table for each partitions */
  4785. void* work /* Pointer to the working buffer */
  4786. )
  4787. {
  4788. UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;
  4789. BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;
  4790. DSTATUS stat;
  4791. DWORD sz_disk, sz_part, s_part;
  4792. disk_ioctl(pdrv, IOCTL_INIT, &stat);
  4793. if (stat & STA_NOINIT) return FR_NOT_READY;
  4794. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  4795. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;
  4796. /* Determine the CHS without any care of the drive geometry */
  4797. for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;
  4798. if (n == 256) n--;
  4799. e_hd = n - 1;
  4800. sz_cyl = 63 * n;
  4801. tot_cyl = sz_disk / sz_cyl;
  4802. /* Create partition table */
  4803. mem_set(buf, 0, _MAX_SS);
  4804. p = buf + MBR_Table; b_cyl = 0;
  4805. for (i = 0; i < 4; i++, p += SZ_PTE) {
  4806. p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl;
  4807. if (!p_cyl) continue;
  4808. s_part = (DWORD)sz_cyl * b_cyl;
  4809. sz_part = (DWORD)sz_cyl * p_cyl;
  4810. if (i == 0) { /* Exclude first track of cylinder 0 */
  4811. s_hd = 1;
  4812. s_part += 63; sz_part -= 63;
  4813. } else {
  4814. s_hd = 0;
  4815. }
  4816. e_cyl = b_cyl + p_cyl - 1;
  4817. if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER;
  4818. /* Set partition table */
  4819. p[1] = s_hd; /* Start head */
  4820. p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */
  4821. p[3] = (BYTE)b_cyl; /* Start cylinder */
  4822. p[4] = 0x06; /* System type (temporary setting) */
  4823. p[5] = e_hd; /* End head */
  4824. p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */
  4825. p[7] = (BYTE)e_cyl; /* End cylinder */
  4826. st_dword(p + 8, s_part); /* Start sector in LBA */
  4827. st_dword(p + 12, sz_part); /* Partition size */
  4828. /* Next partition */
  4829. b_cyl += p_cyl;
  4830. }
  4831. st_word(p, 0xAA55);
  4832. /* Write it to the MBR */
  4833. return (disk_write(pdrv, buf, 0, 1) != RES_OK || disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) ? FR_DISK_ERR : FR_OK;
  4834. }
  4835. #endif /* _MULTI_PARTITION */
  4836. #endif /* _USE_MKFS && !_FS_READONLY */