ff.c 254 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - Generic FAT Filesystem Module R0.16 w/patch 1 /
  3. /-----------------------------------------------------------------------------/
  4. /
  5. / Copyright (C) 2025, ChaN, all right reserved.
  6. /
  7. / FatFs module is an open source software. Redistribution and use of FatFs in
  8. / source and binary forms, with or without modification, are permitted provided
  9. / that the following condition is met:
  10. /
  11. / 1. Redistributions of source code must retain the above copyright notice,
  12. / this condition and the following disclaimer.
  13. /
  14. / This software is provided by the copyright holder and contributors "AS IS"
  15. / and any warranties related to this software are DISCLAIMED.
  16. / The copyright owner or contributors be NOT LIABLE for any damages caused
  17. / by use of this software.
  18. /
  19. /----------------------------------------------------------------------------*/
  20. #include <string.h>
  21. #include "ff.h" /* Basic definitions and declarations of API */
  22. #include "diskio.h" /* Declarations of MAI */
  23. /*--------------------------------------------------------------------------
  24. Module Private Definitions
  25. ---------------------------------------------------------------------------*/
  26. #if FF_DEFINED != 80386 /* Revision ID */
  27. #error Wrong include file (ff.h).
  28. #endif
  29. /* Limits and boundaries */
  30. #define MAX_DIR 0x200000 /* Max size of FAT directory (byte) */
  31. #define MAX_DIR_EX 0x10000000 /* Max size of exFAT directory (byte) */
  32. #define MAX_FAT12 0xFF5 /* Max FAT12 clusters (differs from specs, but right for real DOS/Windows behavior) */
  33. #define MAX_FAT16 0xFFF5 /* Max FAT16 clusters (differs from specs, but right for real DOS/Windows behavior) */
  34. #define MAX_FAT32 0x0FFFFFF5 /* Max FAT32 clusters (not defined in specs, practical limit) */
  35. #define MAX_EXFAT 0x7FFFFFFD /* Max exFAT clusters (differs from specs, implementation limit) */
  36. #define MIN_FAT12 32 /* Min FAT12 clusters (Not defined in specs, implementation limit) */
  37. #define MIN_VOLUME 64 /* Min volume sectors (Not defined in specs, implementation limit) */
  38. /* Character code support macros */
  39. #define IsUpper(c) ((c) >= 'A' && (c) <= 'Z')
  40. #define IsLower(c) ((c) >= 'a' && (c) <= 'z')
  41. #define IsDigit(c) ((c) >= '0' && (c) <= '9')
  42. #define IsSeparator(c) ((c) == '/' || (c) == '\\')
  43. #define IsTerminator(c) ((UINT)(c) < (FF_USE_LFN ? ' ' : '!'))
  44. #define IsSurrogate(c) ((c) >= 0xD800 && (c) <= 0xDFFF)
  45. #define IsSurrogateH(c) ((c) >= 0xD800 && (c) <= 0xDBFF)
  46. #define IsSurrogateL(c) ((c) >= 0xDC00 && (c) <= 0xDFFF)
  47. /* Additional file access control and file status flags for internal use */
  48. #define FA_SEEKEND 0x20 /* Seek to end of the file on file open */
  49. #define FA_MODIFIED 0x40 /* File has been modified */
  50. #define FA_DIRTY 0x80 /* FIL.buf[] needs to be written-back */
  51. /* Additional file attribute bits for internal use */
  52. #define AM_VOL 0x08 /* Volume label */
  53. #define AM_LFN 0x0F /* LFN entry */
  54. #define AM_MASK 0x3F /* Mask of defined bits in FAT */
  55. #define AM_MASKX 0x37 /* Mask of defined bits in exFAT */
  56. /* Name status flags in fn[11] */
  57. #define NSFLAG 11 /* Index of the name status byte */
  58. #define NS_LOSS 0x01 /* Out of 8.3 format */
  59. #define NS_LFN 0x02 /* Force to create LFN entry */
  60. #define NS_LAST 0x04 /* Last segment */
  61. #define NS_BODY 0x08 /* Lower case flag (body) */
  62. #define NS_EXT 0x10 /* Lower case flag (ext) */
  63. #define NS_DOT 0x20 /* Dot entry */
  64. #define NS_NOLFN 0x40 /* Do not find LFN */
  65. #define NS_NONAME 0x80 /* Not followed */
  66. /* exFAT directory entry types */
  67. #define ET_BITMAP 0x81 /* Allocation bitmap */
  68. #define ET_UPCASE 0x82 /* Up-case table */
  69. #define ET_VLABEL 0x83 /* Volume label */
  70. #define ET_FILEDIR 0x85 /* File and directory */
  71. #define ET_STREAM 0xC0 /* Stream extension */
  72. #define ET_FILENAME 0xC1 /* Name extension */
  73. /* FatFs refers the FAT structures as simple byte array instead of structure member
  74. / because the C structure is not binary compatible between different platforms */
  75. #define BS_JmpBoot 0 /* x86 jump instruction (3-byte) */
  76. #define BS_OEMName 3 /* OEM name (8-byte) */
  77. #define BPB_BytsPerSec 11 /* Sector size [byte] (WORD) */
  78. #define BPB_SecPerClus 13 /* Cluster size [sector] (BYTE) */
  79. #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (WORD) */
  80. #define BPB_NumFATs 16 /* Number of FATs (BYTE) */
  81. #define BPB_RootEntCnt 17 /* Size of root directory area for FAT [entry] (WORD) */
  82. #define BPB_TotSec16 19 /* Volume size (16-bit) [sector] (WORD) */
  83. #define BPB_Media 21 /* Media descriptor byte (BYTE) */
  84. #define BPB_FATSz16 22 /* FAT size (16-bit) [sector] (WORD) */
  85. #define BPB_SecPerTrk 24 /* Number of sectors per track for int13h [sector] (WORD) */
  86. #define BPB_NumHeads 26 /* Number of heads for int13h (WORD) */
  87. #define BPB_HiddSec 28 /* Volume offset from top of the drive (DWORD) */
  88. #define BPB_TotSec32 32 /* Volume size (32-bit) [sector] (DWORD) */
  89. #define BS_DrvNum 36 /* Physical drive number for int13h (BYTE) */
  90. #define BS_NTres 37 /* WindowsNT error flag (BYTE) */
  91. #define BS_BootSig 38 /* Extended boot signature (BYTE) */
  92. #define BS_VolID 39 /* Volume serial number (DWORD) */
  93. #define BS_VolLab 43 /* Volume label string (8-byte) */
  94. #define BS_FilSysType 54 /* Filesystem type string (8-byte) */
  95. #define BS_BootCode 62 /* Boot code (448-byte) */
  96. #define BS_55AA 510 /* Boot signature (WORD, for VBR and MBR) */
  97. #define BPB_FATSz32 36 /* FAT32: FAT size [sector] (DWORD) */
  98. #define BPB_ExtFlags32 40 /* FAT32: Extended flags (WORD) */
  99. #define BPB_FSVer32 42 /* FAT32: Filesystem version (WORD) */
  100. #define BPB_RootClus32 44 /* FAT32: Root directory cluster (DWORD) */
  101. #define BPB_FSInfo32 48 /* FAT32: Offset of FSINFO sector (WORD) */
  102. #define BPB_BkBootSec32 50 /* FAT32: Offset of backup boot sector (WORD) */
  103. #define BS_DrvNum32 64 /* FAT32: Physical drive number for int13h (BYTE) */
  104. #define BS_NTres32 65 /* FAT32: Error flag (BYTE) */
  105. #define BS_BootSig32 66 /* FAT32: Extended boot signature (BYTE) */
  106. #define BS_VolID32 67 /* FAT32: Volume serial number (DWORD) */
  107. #define BS_VolLab32 71 /* FAT32: Volume label string (8-byte) */
  108. #define BS_FilSysType32 82 /* FAT32: Filesystem type string (8-byte) */
  109. #define BS_BootCode32 90 /* FAT32: Boot code (420-byte) */
  110. #define BPB_ZeroedEx 11 /* exFAT: MBZ field (53-byte) */
  111. #define BPB_VolOfsEx 64 /* exFAT: Volume offset from top of the drive [sector] (QWORD) */
  112. #define BPB_TotSecEx 72 /* exFAT: Volume size [sector] (QWORD) */
  113. #define BPB_FatOfsEx 80 /* exFAT: FAT offset from top of the volume [sector] (DWORD) */
  114. #define BPB_FatSzEx 84 /* exFAT: FAT size [sector] (DWORD) */
  115. #define BPB_DataOfsEx 88 /* exFAT: Data offset from top of the volume [sector] (DWORD) */
  116. #define BPB_NumClusEx 92 /* exFAT: Number of clusters (DWORD) */
  117. #define BPB_RootClusEx 96 /* exFAT: Root directory start cluster (DWORD) */
  118. #define BPB_VolIDEx 100 /* exFAT: Volume serial number (DWORD) */
  119. #define BPB_FSVerEx 104 /* exFAT: Filesystem version (WORD) */
  120. #define BPB_VolFlagEx 106 /* exFAT: Volume flags (WORD, out of check sum calculation) */
  121. #define BPB_BytsPerSecEx 108 /* exFAT: Log2 of sector size in unit of byte (BYTE) */
  122. #define BPB_SecPerClusEx 109 /* exFAT: Log2 of cluster size in unit of sector (BYTE) */
  123. #define BPB_NumFATsEx 110 /* exFAT: Number of FATs (BYTE) */
  124. #define BPB_DrvNumEx 111 /* exFAT: Physical drive number for int13h (BYTE) */
  125. #define BPB_PercInUseEx 112 /* exFAT: Percent in use (BYTE, out of check sum calculation) */
  126. #define BPB_RsvdEx 113 /* exFAT: Reserved (7-byte) */
  127. #define BS_BootCodeEx 120 /* exFAT: Boot code (390-byte) */
  128. #define DIR_Name 0 /* Short file name (11-byte) */
  129. #define DIR_Attr 11 /* Attribute (BYTE) */
  130. #define DIR_NTres 12 /* Low case flags of SFN (BYTE) */
  131. #define DIR_CrtTime10 13 /* Created time sub-second (BYTE) */
  132. #define DIR_CrtTime 14 /* Created time (DWORD) */
  133. #define DIR_LstAccDate 18 /* Last accessed date (WORD) */
  134. #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (WORD) */
  135. #define DIR_ModTime 22 /* Modified time (DWORD) */
  136. #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (WORD) */
  137. #define DIR_FileSize 28 /* File size (DWORD) */
  138. #define LDIR_Ord 0 /* LFN: LFN order and LLE flag (BYTE) */
  139. #define LDIR_Attr 11 /* LFN: LFN attribute (BYTE) */
  140. #define LDIR_Type 12 /* LFN: Entry type (BYTE) */
  141. #define LDIR_Chksum 13 /* LFN: Checksum of the SFN (BYTE) */
  142. #define LDIR_FstClusLO 26 /* LFN: MBZ field (WORD) */
  143. #define XDIR_Type 0 /* exFAT: Type of exFAT directory entry (BYTE) */
  144. #define XDIR_NumLabel 1 /* exFAT: Number of volume label characters (BYTE) */
  145. #define XDIR_Label 2 /* exFAT: Volume label (11-WORD) */
  146. #define XDIR_CaseSum 4 /* exFAT: Sum of case conversion table (DWORD) */
  147. #define XDIR_NumSec 1 /* exFAT: Number of secondary entries (BYTE) */
  148. #define XDIR_SetSum 2 /* exFAT: Sum of the set of directory entries (WORD) */
  149. #define XDIR_Attr 4 /* exFAT: File attribute (WORD) */
  150. #define XDIR_CrtTime 8 /* exFAT: Created time (DWORD) */
  151. #define XDIR_ModTime 12 /* exFAT: Modified time (DWORD) */
  152. #define XDIR_AccTime 16 /* exFAT: Last accessed time (DWORD) */
  153. #define XDIR_CrtTime10 20 /* exFAT: Created time subsecond (BYTE) */
  154. #define XDIR_ModTime10 21 /* exFAT: Modified time subsecond (BYTE) */
  155. #define XDIR_CrtTZ 22 /* exFAT: Created timezone (BYTE) */
  156. #define XDIR_ModTZ 23 /* exFAT: Modified timezone (BYTE) */
  157. #define XDIR_AccTZ 24 /* exFAT: Last accessed timezone (BYTE) */
  158. #define XDIR_GenFlags 33 /* exFAT: General secondary flags (BYTE) */
  159. #define XDIR_NumName 35 /* exFAT: Number of file name characters (BYTE) */
  160. #define XDIR_NameHash 36 /* exFAT: Hash of file name (WORD) */
  161. #define XDIR_ValidFileSize 40 /* exFAT: Valid file size (QWORD) */
  162. #define XDIR_FstClus 52 /* exFAT: First cluster of the file data (DWORD) */
  163. #define XDIR_FileSize 56 /* exFAT: File/Directory size (QWORD) */
  164. #define SZDIRE 32 /* Size of a directory entry */
  165. #define DDEM 0xE5 /* Deleted directory entry mark set to DIR_Name[0] */
  166. #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
  167. #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
  168. #define FSI_LeadSig 0 /* FAT32 FSI: Leading signature (DWORD) */
  169. #define FSI_StrucSig 484 /* FAT32 FSI: Structure signature (DWORD) */
  170. #define FSI_Free_Count 488 /* FAT32 FSI: Number of free clusters (DWORD) */
  171. #define FSI_Nxt_Free 492 /* FAT32 FSI: Last allocated cluster (DWORD) */
  172. #define FSI_TrailSig 508 /* FAT32 FSI: Trailing signature (DWORD) */
  173. #define MBR_Table 446 /* MBR: Offset of partition table in the MBR */
  174. #define SZ_PTE 16 /* MBR: Size of a partition table entry */
  175. #define PTE_Boot 0 /* MBR PTE: Boot indicator */
  176. #define PTE_StHead 1 /* MBR PTE: Start head in CHS */
  177. #define PTE_StSec 2 /* MBR PTE: Start sector in CHS */
  178. #define PTE_StCyl 3 /* MBR PTE: Start cylinder in CHS */
  179. #define PTE_System 4 /* MBR PTE: System ID */
  180. #define PTE_EdHead 5 /* MBR PTE: End head in CHS */
  181. #define PTE_EdSec 6 /* MBR PTE: End sector in CHS */
  182. #define PTE_EdCyl 7 /* MBR PTE: End cylinder in CHS */
  183. #define PTE_StLba 8 /* MBR PTE: Start in LBA */
  184. #define PTE_SizLba 12 /* MBR PTE: Size in LBA */
  185. #define GPTH_Sign 0 /* GPT HDR: Signature (8-byte) */
  186. #define GPTH_Rev 8 /* GPT HDR: Revision (DWORD) */
  187. #define GPTH_Size 12 /* GPT HDR: Header size (DWORD) */
  188. #define GPTH_Bcc 16 /* GPT HDR: Header BCC (DWORD) */
  189. #define GPTH_CurLba 24 /* GPT HDR: This header LBA (QWORD) */
  190. #define GPTH_BakLba 32 /* GPT HDR: Another header LBA (QWORD) */
  191. #define GPTH_FstLba 40 /* GPT HDR: First LBA for partition data (QWORD) */
  192. #define GPTH_LstLba 48 /* GPT HDR: Last LBA for partition data (QWORD) */
  193. #define GPTH_DskGuid 56 /* GPT HDR: Disk GUID (16-byte) */
  194. #define GPTH_PtOfs 72 /* GPT HDR: Partition table LBA (QWORD) */
  195. #define GPTH_PtNum 80 /* GPT HDR: Number of table entries (DWORD) */
  196. #define GPTH_PteSize 84 /* GPT HDR: Size of table entry (DWORD) */
  197. #define GPTH_PtBcc 88 /* GPT HDR: Partition table BCC (DWORD) */
  198. #define SZ_GPTE 128 /* GPT PTE: Size of a GPT partition table entry */
  199. #define GPTE_PtGuid 0 /* GPT PTE: Partition type GUID (16-byte) */
  200. #define GPTE_UpGuid 16 /* GPT PTE: Partition unique GUID (16-byte) */
  201. #define GPTE_FstLba 32 /* GPT PTE: First LBA of partition (QWORD) */
  202. #define GPTE_LstLba 40 /* GPT PTE: Last LBA of partition (QWORD) */
  203. #define GPTE_Flags 48 /* GPT PTE: Partition flags (QWORD) */
  204. #define GPTE_Name 56 /* GPT PTE: Partition name */
  205. /* Post process on fatal error in the file operations */
  206. #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
  207. /* Re-entrancy related */
  208. #if FF_FS_REENTRANT
  209. #if FF_USE_LFN == 1
  210. #error Static LFN work area cannot be used in thread-safe configuration
  211. #endif
  212. #define LEAVE_FF(fs, res) { unlock_volume(fs, res); return res; }
  213. #else
  214. #define LEAVE_FF(fs, res) return res
  215. #endif
  216. /* Definitions of logical drive to physical location conversion */
  217. #if FF_MULTI_PARTITION
  218. #define LD2PD(vol) VolToPart[vol].pd /* Get physical drive number from the mapping table */
  219. #define LD2PT(vol) VolToPart[vol].pt /* Get partition number from the mapping table (0:auto search, 1-:forced partition number) */
  220. #else
  221. #define LD2PD(vol) (BYTE)(vol) /* Each logical drive is associated with the same physical drive number */
  222. #define LD2PT(vol) 0 /* Auto partition search */
  223. #endif
  224. /* Definitions of sector size */
  225. #if (FF_MAX_SS < FF_MIN_SS) || (FF_MAX_SS != 512 && FF_MAX_SS != 1024 && FF_MAX_SS != 2048 && FF_MAX_SS != 4096) || (FF_MIN_SS != 512 && FF_MIN_SS != 1024 && FF_MIN_SS != 2048 && FF_MIN_SS != 4096)
  226. #error Wrong sector size configuration
  227. #endif
  228. #if FF_MAX_SS == FF_MIN_SS
  229. #define SS(fs) ((UINT)FF_MAX_SS) /* Fixed sector size */
  230. #else
  231. #define SS(fs) ((fs)->ssize) /* Variable sector size */
  232. #endif
  233. /* Timestamp */
  234. #if FF_FS_NORTC == 1
  235. #if FF_NORTC_YEAR < 1980 || FF_NORTC_YEAR > 2107 || FF_NORTC_MON < 1 || FF_NORTC_MON > 12 || FF_NORTC_MDAY < 1 || FF_NORTC_MDAY > 31
  236. #error Invalid FF_FS_NORTC settings
  237. #endif
  238. #define GET_FATTIME() ((DWORD)(FF_NORTC_YEAR - 1980) << 25 | (DWORD)FF_NORTC_MON << 21 | (DWORD)FF_NORTC_MDAY << 16)
  239. #else
  240. #define GET_FATTIME() get_fattime()
  241. #endif
  242. /* File lock controls */
  243. #if FF_FS_LOCK
  244. #if FF_FS_READONLY
  245. #error FF_FS_LOCK must be 0 at read-only configuration
  246. #endif
  247. typedef struct { /* Open object identifier with status */
  248. FATFS* fs; /* Object ID 1, volume (NULL:blank entry) */
  249. DWORD clu; /* Object ID 2, containing directory (0:root) */
  250. DWORD ofs; /* Object ID 3, offset in the directory */
  251. UINT ctr; /* Object open status, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
  252. } FILESEM;
  253. #endif
  254. /* SBCS up-case tables (\x80-\xFF) */
  255. #define TBL_CT437 {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  256. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  257. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  258. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  259. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  260. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  261. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  262. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  263. #define TBL_CT720 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  264. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  265. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  266. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  267. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  268. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  269. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  270. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  271. #define TBL_CT737 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  272. 0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
  273. 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \
  274. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  275. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  276. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  277. 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  278. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  279. #define TBL_CT771 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  280. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  281. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  282. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  283. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  284. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \
  285. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  286. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF}
  287. #define TBL_CT775 {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \
  288. 0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  289. 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  290. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  291. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  292. 0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  293. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \
  294. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  295. #define TBL_CT850 {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \
  296. 0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \
  297. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  298. 0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  299. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  300. 0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \
  301. 0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \
  302. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  303. #define TBL_CT852 {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \
  304. 0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \
  305. 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \
  306. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
  307. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  308. 0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  309. 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \
  310. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
  311. #define TBL_CT855 {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \
  312. 0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
  313. 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \
  314. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
  315. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  316. 0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
  317. 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \
  318. 0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
  319. #define TBL_CT857 {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \
  320. 0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
  321. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  322. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  323. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  324. 0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  325. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \
  326. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  327. #define TBL_CT860 {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \
  328. 0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  329. 0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  330. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  331. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  332. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  333. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  334. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  335. #define TBL_CT861 {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \
  336. 0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  337. 0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  338. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  339. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  340. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  341. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  342. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  343. #define TBL_CT862 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  344. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  345. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  346. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  347. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  348. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  349. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  350. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  351. #define TBL_CT863 {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \
  352. 0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \
  353. 0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  354. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  355. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  356. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  357. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  358. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  359. #define TBL_CT864 {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  360. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  361. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  362. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  363. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  364. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  365. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  366. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  367. #define TBL_CT865 {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  368. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  369. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  370. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  371. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  372. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  373. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  374. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  375. #define TBL_CT866 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  376. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  377. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  378. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  379. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  380. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  381. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  382. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  383. #define TBL_CT869 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  384. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \
  385. 0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  386. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  387. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  388. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \
  389. 0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \
  390. 0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF}
  391. /* DBCS code range |----- 1st byte -----| |----------- 2nd byte -----------| */
  392. /* <------> <------> <------> <------> <------> */
  393. #define TBL_DC932 {0x81, 0x9F, 0xE0, 0xFC, 0x40, 0x7E, 0x80, 0xFC, 0x00, 0x00}
  394. #define TBL_DC936 {0x81, 0xFE, 0x00, 0x00, 0x40, 0x7E, 0x80, 0xFE, 0x00, 0x00}
  395. #define TBL_DC949 {0x81, 0xFE, 0x00, 0x00, 0x41, 0x5A, 0x61, 0x7A, 0x81, 0xFE}
  396. #define TBL_DC950 {0x81, 0xFE, 0x00, 0x00, 0x40, 0x7E, 0xA1, 0xFE, 0x00, 0x00}
  397. /* Macros for table definitions */
  398. #define MERGE_2STR(a, b) a ## b
  399. #define MKCVTBL(hd, cp) MERGE_2STR(hd, cp)
  400. /*--------------------------------------------------------------------------
  401. Module Private Work Area
  402. ---------------------------------------------------------------------------*/
  403. /* Remark: Variables defined here without initial value shall be guaranteed
  404. / zero/null at start-up. If not, the linker option or start-up routine is
  405. / not compliance with C standard. */
  406. /*--------------------------------*/
  407. /* File/Volume controls */
  408. /*--------------------------------*/
  409. #if FF_VOLUMES < 1 || FF_VOLUMES > 10
  410. #error Wrong FF_VOLUMES setting
  411. #endif
  412. static FATFS *FatFs[FF_VOLUMES]; /* Pointer to the filesystem objects (logical drives) */
  413. static WORD Fsid; /* Filesystem mount ID */
  414. #if FF_FS_RPATH
  415. static BYTE CurrVol; /* Current drive number set by f_chdrive() */
  416. #endif
  417. #if FF_FS_LOCK
  418. static FILESEM Files[FF_FS_LOCK]; /* Open object lock semaphores */
  419. #if FF_FS_REENTRANT
  420. static volatile BYTE SysLock; /* System lock flag to protect Files[] (0:no mutex, 1:unlocked, 2:locked) */
  421. static volatile BYTE SysLockVolume; /* Volume id who is locking Files[] */
  422. #endif
  423. #endif
  424. #if FF_STR_VOLUME_ID
  425. #ifdef FF_VOLUME_STRS
  426. static const char *const VolumeStr[FF_VOLUMES] = {FF_VOLUME_STRS}; /* Pre-defined volume ID */
  427. #endif
  428. #endif
  429. #if FF_LBA64
  430. #if FF_MIN_GPT > 0x100000000
  431. #error Wrong FF_MIN_GPT setting
  432. #endif
  433. static const BYTE GUID_MS_Basic[16] = {0xA2,0xA0,0xD0,0xEB,0xE5,0xB9,0x33,0x44,0x87,0xC0,0x68,0xB6,0xB7,0x26,0x99,0xC7};
  434. #endif
  435. /*--------------------------------*/
  436. /* LFN/Directory working buffer */
  437. /*--------------------------------*/
  438. #if FF_USE_LFN == 0 /* Non-LFN configuration */
  439. #if FF_FS_EXFAT
  440. #error LFN must be enabled when enable exFAT
  441. #endif
  442. #define DEF_NAMEBUFF
  443. #define INIT_NAMEBUFF(fs)
  444. #define FREE_NAMEBUFF()
  445. #define LEAVE_MKFS(res) return res
  446. #else /* LFN configurations */
  447. #if FF_MAX_LFN < 12 || FF_MAX_LFN > 255
  448. #error Wrong setting of FF_MAX_LFN
  449. #endif
  450. #if FF_LFN_BUF < FF_SFN_BUF || FF_SFN_BUF < 12
  451. #error Wrong setting of FF_LFN_BUF or FF_SFN_BUF
  452. #endif
  453. #if FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3
  454. #error Wrong setting of FF_LFN_UNICODE
  455. #endif
  456. static const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* FAT: Offset of LFN characters in the directory entry */
  457. #define MAXDIRB(nc) ((nc + 44U) / 15 * SZDIRE) /* exFAT: Size of directory entry block scratchpad buffer needed for the name length */
  458. #if FF_USE_LFN == 1 /* LFN enabled with static working buffer */
  459. #if FF_FS_EXFAT
  460. static BYTE DirBuf[MAXDIRB(FF_MAX_LFN)]; /* Directory entry block scratchpad buffer */
  461. #endif
  462. static WCHAR LfnBuf[FF_MAX_LFN + 1]; /* LFN working buffer */
  463. #define DEF_NAMEBUFF
  464. #define INIT_NAMEBUFF(fs)
  465. #define FREE_NAMEBUFF()
  466. #define LEAVE_MKFS(res) return res
  467. #elif FF_USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
  468. #if FF_FS_EXFAT
  469. #define DEF_NAMEBUFF WCHAR lbuf[FF_MAX_LFN+1]; BYTE dbuf[MAXDIRB(FF_MAX_LFN)]; /* LFN working buffer and directory entry block scratchpad buffer */
  470. #define INIT_NAMEBUFF(fs) { (fs)->lfnbuf = lbuf; (fs)->dirbuf = dbuf; }
  471. #define FREE_NAMEBUFF()
  472. #else
  473. #define DEF_NAMEBUFF WCHAR lbuf[FF_MAX_LFN+1]; /* LFN working buffer */
  474. #define INIT_NAMEBUFF(fs) { (fs)->lfnbuf = lbuf; }
  475. #define FREE_NAMEBUFF()
  476. #endif
  477. #define LEAVE_MKFS(res) return res
  478. #elif FF_USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
  479. #if FF_FS_EXFAT
  480. #define DEF_NAMEBUFF WCHAR *lfn; /* Pointer to LFN working buffer and directory entry block scratchpad buffer */
  481. #define INIT_NAMEBUFF(fs) { lfn = ff_memalloc((FF_MAX_LFN+1)*2 + MAXDIRB(FF_MAX_LFN)); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; (fs)->dirbuf = (BYTE*)(lfn+FF_MAX_LFN+1); }
  482. #define FREE_NAMEBUFF() ff_memfree(lfn)
  483. #else
  484. #define DEF_NAMEBUFF WCHAR *lfn; /* Pointer to LFN working buffer */
  485. #define INIT_NAMEBUFF(fs) { lfn = ff_memalloc((FF_MAX_LFN+1)*2); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; }
  486. #define FREE_NAMEBUFF() ff_memfree(lfn)
  487. #endif
  488. #define LEAVE_MKFS(res) { if (!work) ff_memfree(buf); return res; }
  489. #define MAX_MALLOC 0x8000 /* Must be >=FF_MAX_SS */
  490. #else
  491. #error Wrong setting of FF_USE_LFN
  492. #endif /* FF_USE_LFN == 1 */
  493. #endif /* FF_USE_LFN == 0 */
  494. /*--------------------------------*/
  495. /* Code conversion tables */
  496. /*--------------------------------*/
  497. #if FF_CODE_PAGE == 0 /* Run-time code page configuration */
  498. #define CODEPAGE CodePage
  499. static WORD CodePage; /* Current code page */
  500. static const BYTE* ExCvt; /* Pointer to SBCS up-case table Ct???[] (null:disabled) */
  501. static const BYTE* DbcTbl; /* Pointer to DBCS code range table Dc???[] (null:disabled) */
  502. static const BYTE Ct437[] = TBL_CT437;
  503. static const BYTE Ct720[] = TBL_CT720;
  504. static const BYTE Ct737[] = TBL_CT737;
  505. static const BYTE Ct771[] = TBL_CT771;
  506. static const BYTE Ct775[] = TBL_CT775;
  507. static const BYTE Ct850[] = TBL_CT850;
  508. static const BYTE Ct852[] = TBL_CT852;
  509. static const BYTE Ct855[] = TBL_CT855;
  510. static const BYTE Ct857[] = TBL_CT857;
  511. static const BYTE Ct860[] = TBL_CT860;
  512. static const BYTE Ct861[] = TBL_CT861;
  513. static const BYTE Ct862[] = TBL_CT862;
  514. static const BYTE Ct863[] = TBL_CT863;
  515. static const BYTE Ct864[] = TBL_CT864;
  516. static const BYTE Ct865[] = TBL_CT865;
  517. static const BYTE Ct866[] = TBL_CT866;
  518. static const BYTE Ct869[] = TBL_CT869;
  519. static const BYTE Dc932[] = TBL_DC932;
  520. static const BYTE Dc936[] = TBL_DC936;
  521. static const BYTE Dc949[] = TBL_DC949;
  522. static const BYTE Dc950[] = TBL_DC950;
  523. #elif FF_CODE_PAGE < 900 /* Static code page configuration (SBCS) */
  524. #define CODEPAGE FF_CODE_PAGE
  525. static const BYTE ExCvt[] = MKCVTBL(TBL_CT, FF_CODE_PAGE);
  526. #else /* Static code page configuration (DBCS) */
  527. #define CODEPAGE FF_CODE_PAGE
  528. static const BYTE DbcTbl[] = MKCVTBL(TBL_DC, FF_CODE_PAGE);
  529. #endif
  530. /*--------------------------------------------------------------------------
  531. Module Private Functions
  532. ---------------------------------------------------------------------------*/
  533. /*-----------------------------------------------------------------------*/
  534. /* Load/Store multi-byte word in the FAT structure */
  535. /*-----------------------------------------------------------------------*/
  536. static WORD ld_16 (const BYTE* ptr) /* Load a 2-byte little-endian word */
  537. {
  538. WORD rv;
  539. rv = ptr[1];
  540. rv = rv << 8 | ptr[0];
  541. return rv;
  542. }
  543. static DWORD ld_32 (const BYTE* ptr) /* Load a 4-byte little-endian word */
  544. {
  545. DWORD rv;
  546. rv = ptr[3];
  547. rv = rv << 8 | ptr[2];
  548. rv = rv << 8 | ptr[1];
  549. rv = rv << 8 | ptr[0];
  550. return rv;
  551. }
  552. #if FF_FS_EXFAT
  553. static QWORD ld_64 (const BYTE* ptr) /* Load an 8-byte little-endian word */
  554. {
  555. QWORD rv;
  556. rv = ptr[7];
  557. rv = rv << 8 | ptr[6];
  558. rv = rv << 8 | ptr[5];
  559. rv = rv << 8 | ptr[4];
  560. rv = rv << 8 | ptr[3];
  561. rv = rv << 8 | ptr[2];
  562. rv = rv << 8 | ptr[1];
  563. rv = rv << 8 | ptr[0];
  564. return rv;
  565. }
  566. #endif
  567. #if !FF_FS_READONLY
  568. static void st_16 (BYTE* ptr, WORD val) /* Store a 2-byte word in little-endian */
  569. {
  570. *ptr++ = (BYTE)val; val >>= 8;
  571. *ptr++ = (BYTE)val;
  572. }
  573. static void st_32 (BYTE* ptr, DWORD val) /* Store a 4-byte word in little-endian */
  574. {
  575. *ptr++ = (BYTE)val; val >>= 8;
  576. *ptr++ = (BYTE)val; val >>= 8;
  577. *ptr++ = (BYTE)val; val >>= 8;
  578. *ptr++ = (BYTE)val;
  579. }
  580. #if FF_FS_EXFAT
  581. static void st_64 (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-endian */
  582. {
  583. *ptr++ = (BYTE)val; val >>= 8;
  584. *ptr++ = (BYTE)val; val >>= 8;
  585. *ptr++ = (BYTE)val; val >>= 8;
  586. *ptr++ = (BYTE)val; val >>= 8;
  587. *ptr++ = (BYTE)val; val >>= 8;
  588. *ptr++ = (BYTE)val; val >>= 8;
  589. *ptr++ = (BYTE)val; val >>= 8;
  590. *ptr++ = (BYTE)val;
  591. }
  592. #endif
  593. #endif /* !FF_FS_READONLY */
  594. /*-----------------------------------------------------------------------*/
  595. /* String functions */
  596. /*-----------------------------------------------------------------------*/
  597. /* Test if the byte is DBC 1st byte */
  598. static int dbc_1st (BYTE c)
  599. {
  600. #if FF_CODE_PAGE == 0 /* Variable code page */
  601. if (DbcTbl && c >= DbcTbl[0]) {
  602. if (c <= DbcTbl[1]) return 1; /* 1st byte range 1 */
  603. if (c >= DbcTbl[2] && c <= DbcTbl[3]) return 1; /* 1st byte range 2 */
  604. }
  605. #elif FF_CODE_PAGE >= 900 /* DBCS fixed code page */
  606. if (c >= DbcTbl[0]) {
  607. if (c <= DbcTbl[1]) return 1;
  608. if (c >= DbcTbl[2] && c <= DbcTbl[3]) return 1;
  609. }
  610. #else /* SBCS fixed code page */
  611. if (c != 0) return 0; /* Always false */
  612. #endif
  613. return 0;
  614. }
  615. /* Test if the byte is DBC 2nd byte */
  616. static int dbc_2nd (BYTE c)
  617. {
  618. #if FF_CODE_PAGE == 0 /* Variable code page */
  619. if (DbcTbl && c >= DbcTbl[4]) {
  620. if (c <= DbcTbl[5]) return 1; /* 2nd byte range 1 */
  621. if (c >= DbcTbl[6] && c <= DbcTbl[7]) return 1; /* 2nd byte range 2 */
  622. if (c >= DbcTbl[8] && c <= DbcTbl[9]) return 1; /* 2nd byte range 3 */
  623. }
  624. #elif FF_CODE_PAGE >= 900 /* DBCS fixed code page */
  625. if (c >= DbcTbl[4]) {
  626. if (c <= DbcTbl[5]) return 1;
  627. if (c >= DbcTbl[6] && c <= DbcTbl[7]) return 1;
  628. if (c >= DbcTbl[8] && c <= DbcTbl[9]) return 1;
  629. }
  630. #else /* SBCS fixed code page */
  631. if (c != 0) return 0; /* Always false */
  632. #endif
  633. return 0;
  634. }
  635. #if FF_USE_LFN
  636. /* Get a Unicode code point from the TCHAR string in defined API encodeing */
  637. static DWORD tchar2uni ( /* Returns a character in UTF-16 encoding (>=0x10000 on surrogate pair, 0xFFFFFFFF on decode error) */
  638. const TCHAR** str /* Pointer to pointer to TCHAR string in configured encoding */
  639. )
  640. {
  641. DWORD uc;
  642. const TCHAR *p = *str;
  643. #if FF_LFN_UNICODE == 1 /* UTF-16 input */
  644. WCHAR wc;
  645. uc = *p++; /* Get an encoding unit */
  646. if (IsSurrogate(uc)) { /* Surrogate? */
  647. wc = *p++; /* Get low surrogate */
  648. if (!IsSurrogateH(uc) || !IsSurrogateL(wc)) return 0xFFFFFFFF; /* Wrong surrogate? */
  649. uc = uc << 16 | wc;
  650. }
  651. #elif FF_LFN_UNICODE == 2 /* UTF-8 input */
  652. BYTE tb;
  653. int nf;
  654. uc = (BYTE)*p++; /* Get an encoding unit */
  655. if (uc & 0x80) { /* Multiple byte code? */
  656. if ((uc & 0xE0) == 0xC0) { /* 2-byte sequence? */
  657. uc &= 0x1F; nf = 1;
  658. } else if ((uc & 0xF0) == 0xE0) { /* 3-byte sequence? */
  659. uc &= 0x0F; nf = 2;
  660. } else if ((uc & 0xF8) == 0xF0) { /* 4-byte sequence? */
  661. uc &= 0x07; nf = 3;
  662. } else { /* Wrong sequence */
  663. return 0xFFFFFFFF;
  664. }
  665. do { /* Get and merge trailing bytes */
  666. tb = (BYTE)*p++;
  667. if ((tb & 0xC0) != 0x80) return 0xFFFFFFFF; /* Wrong sequence? */
  668. uc = uc << 6 | (tb & 0x3F);
  669. } while (--nf != 0);
  670. if (uc < 0x80 || IsSurrogate(uc) || uc >= 0x110000) return 0xFFFFFFFF; /* Wrong code? */
  671. if (uc >= 0x010000) uc = 0xD800DC00 | ((uc - 0x10000) << 6 & 0x3FF0000) | (uc & 0x3FF); /* Make a surrogate pair if needed */
  672. }
  673. #elif FF_LFN_UNICODE == 3 /* UTF-32 input */
  674. uc = (TCHAR)*p++; /* Get a unit */
  675. if (uc >= 0x110000 || IsSurrogate(uc)) return 0xFFFFFFFF; /* Wrong code? */
  676. if (uc >= 0x010000) uc = 0xD800DC00 | ((uc - 0x10000) << 6 & 0x3FF0000) | (uc & 0x3FF); /* Make a surrogate pair if needed */
  677. #else /* ANSI/OEM input */
  678. BYTE sb;
  679. WCHAR wc;
  680. wc = (BYTE)*p++; /* Get a byte */
  681. if (dbc_1st((BYTE)wc)) { /* Is it a DBC 1st byte? */
  682. sb = (BYTE)*p++; /* Get 2nd byte */
  683. if (!dbc_2nd(sb)) return 0xFFFFFFFF; /* Invalid code? */
  684. wc = (wc << 8) + sb; /* Make a DBC */
  685. }
  686. if (wc != 0) {
  687. wc = ff_oem2uni(wc, CODEPAGE); /* ANSI/OEM ==> Unicode */
  688. if (wc == 0) return 0xFFFFFFFF; /* Invalid code? */
  689. }
  690. uc = wc;
  691. #endif
  692. *str = p; /* Next read pointer */
  693. return uc;
  694. }
  695. /* Store a Unicode char in defined API encoding */
  696. static UINT put_utf ( /* Returns number of encoding units written (0:buffer overflow or wrong encoding) */
  697. DWORD chr, /* UTF-16 encoded character (Surrogate pair if >=0x10000) */
  698. TCHAR* buf, /* Output buffer */
  699. UINT szb /* Size of the buffer */
  700. )
  701. {
  702. #if FF_LFN_UNICODE == 1 /* UTF-16 output */
  703. WCHAR hs, wc;
  704. hs = (WCHAR)(chr >> 16);
  705. wc = (WCHAR)chr;
  706. if (hs == 0) { /* Single encoding unit? */
  707. if (szb < 1 || IsSurrogate(wc)) return 0; /* Buffer overflow or wrong code? */
  708. *buf = wc;
  709. return 1;
  710. }
  711. if (szb < 2 || !IsSurrogateH(hs) || !IsSurrogateL(wc)) return 0; /* Buffer overflow or wrong surrogate? */
  712. *buf++ = hs;
  713. *buf++ = wc;
  714. return 2;
  715. #elif FF_LFN_UNICODE == 2 /* UTF-8 output */
  716. DWORD hc;
  717. if (chr < 0x80) { /* Single byte code? */
  718. if (szb < 1) return 0; /* Buffer overflow? */
  719. *buf = (TCHAR)chr;
  720. return 1;
  721. }
  722. if (chr < 0x800) { /* 2-byte sequence? */
  723. if (szb < 2) return 0; /* Buffer overflow? */
  724. *buf++ = (TCHAR)(0xC0 | (chr >> 6 & 0x1F));
  725. *buf++ = (TCHAR)(0x80 | (chr >> 0 & 0x3F));
  726. return 2;
  727. }
  728. if (chr < 0x10000) { /* 3-byte sequence? */
  729. if (szb < 3 || IsSurrogate(chr)) return 0; /* Buffer overflow or wrong code? */
  730. *buf++ = (TCHAR)(0xE0 | (chr >> 12 & 0x0F));
  731. *buf++ = (TCHAR)(0x80 | (chr >> 6 & 0x3F));
  732. *buf++ = (TCHAR)(0x80 | (chr >> 0 & 0x3F));
  733. return 3;
  734. }
  735. /* 4-byte sequence */
  736. if (szb < 4) return 0; /* Buffer overflow? */
  737. hc = ((chr & 0xFFFF0000) - 0xD8000000) >> 6; /* Get high 10 bits */
  738. chr = (chr & 0xFFFF) - 0xDC00; /* Get low 10 bits */
  739. if (hc >= 0x100000 || chr >= 0x400) return 0; /* Wrong surrogate? */
  740. chr = (hc | chr) + 0x10000;
  741. *buf++ = (TCHAR)(0xF0 | (chr >> 18 & 0x07));
  742. *buf++ = (TCHAR)(0x80 | (chr >> 12 & 0x3F));
  743. *buf++ = (TCHAR)(0x80 | (chr >> 6 & 0x3F));
  744. *buf++ = (TCHAR)(0x80 | (chr >> 0 & 0x3F));
  745. return 4;
  746. #elif FF_LFN_UNICODE == 3 /* UTF-32 output */
  747. DWORD hc;
  748. if (szb < 1) return 0; /* Buffer overflow? */
  749. if (chr >= 0x10000) { /* Out of BMP? */
  750. hc = ((chr & 0xFFFF0000) - 0xD8000000) >> 6; /* Get high 10 bits */
  751. chr = (chr & 0xFFFF) - 0xDC00; /* Get low 10 bits */
  752. if (hc >= 0x100000 || chr >= 0x400) return 0; /* Wrong surrogate? */
  753. chr = (hc | chr) + 0x10000;
  754. }
  755. *buf++ = (TCHAR)chr;
  756. return 1;
  757. #else /* ANSI/OEM output */
  758. WCHAR wc;
  759. wc = ff_uni2oem(chr, CODEPAGE);
  760. if (wc >= 0x100) { /* Is this a DBC? */
  761. if (szb < 2) return 0;
  762. *buf++ = (char)(wc >> 8); /* Store DBC 1st byte */
  763. *buf++ = (TCHAR)wc; /* Store DBC 2nd byte */
  764. return 2;
  765. }
  766. if (wc == 0 || szb < 1) return 0; /* Invalid character or buffer overflow? */
  767. *buf++ = (TCHAR)wc; /* Store the character */
  768. return 1;
  769. #endif
  770. }
  771. #endif /* FF_USE_LFN */
  772. #if FF_FS_REENTRANT
  773. /*-----------------------------------------------------------------------*/
  774. /* Request/Release grant to access the volume */
  775. /*-----------------------------------------------------------------------*/
  776. static int lock_volume ( /* 1:Ok, 0:timeout */
  777. FATFS* fs, /* Filesystem object to lock */
  778. int syslock /* System lock required */
  779. )
  780. {
  781. int rv;
  782. #if FF_FS_LOCK
  783. rv = ff_mutex_take(fs->ldrv); /* Lock the volume */
  784. if (rv && syslock) { /* System lock reqiered? */
  785. rv = ff_mutex_take(FF_VOLUMES); /* Lock the system */
  786. if (rv) {
  787. SysLockVolume = fs->ldrv;
  788. SysLock = 2; /* System lock succeeded */
  789. } else {
  790. ff_mutex_give(fs->ldrv); /* Failed system lock */
  791. }
  792. }
  793. #else
  794. rv = syslock ? ff_mutex_take(fs->ldrv) : ff_mutex_take(fs->ldrv); /* Lock the volume (this is to prevent compiler warning) */
  795. #endif
  796. return rv;
  797. }
  798. static void unlock_volume (
  799. FATFS* fs, /* Filesystem object */
  800. FRESULT res /* Result code to be returned */
  801. )
  802. {
  803. if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {
  804. #if FF_FS_LOCK
  805. if (SysLock == 2 && SysLockVolume == fs->ldrv) { /* Unlock system if it has been locked by this task */
  806. SysLock = 1;
  807. ff_mutex_give(FF_VOLUMES);
  808. }
  809. #endif
  810. ff_mutex_give(fs->ldrv); /* Unlock the volume */
  811. }
  812. }
  813. #endif
  814. #if FF_FS_LOCK
  815. /*-----------------------------------------------------------------------*/
  816. /* File sharing control functions */
  817. /*-----------------------------------------------------------------------*/
  818. static FRESULT chk_share ( /* Check if the file can be accessed */
  819. DIR* dp, /* Directory object pointing the file to be checked */
  820. int acc /* Desired access type (0:Read mode open, 1:Write mode open, 2:Delete or rename) */
  821. )
  822. {
  823. UINT i, be;
  824. /* Search open object table for the object */
  825. be = 0;
  826. for (i = 0; i < FF_FS_LOCK; i++) {
  827. if (Files[i].fs) { /* Existing entry */
  828. if (Files[i].fs == dp->obj.fs && /* Check if the object matches with an open object */
  829. Files[i].clu == dp->obj.sclust &&
  830. Files[i].ofs == dp->dptr) break;
  831. } else { /* Blank entry */
  832. be = 1;
  833. }
  834. }
  835. if (i == FF_FS_LOCK) { /* The object has not been opened */
  836. return (!be && acc != 2) ? FR_TOO_MANY_OPEN_FILES : FR_OK; /* Is there a blank entry for new object? */
  837. }
  838. /* The object was opened. Reject any open against writing file and all write mode open */
  839. return (acc != 0 || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  840. }
  841. static int enq_share (void) /* Check if an entry is available for a new object */
  842. {
  843. UINT i;
  844. for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ; /* Find a free entry */
  845. return (i == FF_FS_LOCK) ? 0 : 1;
  846. }
  847. static UINT inc_share ( /* Increment object open counter and returns its index (0:Internal error) */
  848. DIR* dp, /* Directory object pointing the file to register or increment */
  849. int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  850. )
  851. {
  852. UINT i;
  853. for (i = 0; i < FF_FS_LOCK; i++) { /* Find the object */
  854. if (Files[i].fs == dp->obj.fs
  855. && Files[i].clu == dp->obj.sclust
  856. && Files[i].ofs == dp->dptr) break;
  857. }
  858. if (i == FF_FS_LOCK) { /* Not opened. Register it as new. */
  859. for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ; /* Find a free entry */
  860. if (i == FF_FS_LOCK) return 0; /* No free entry to register (int err) */
  861. Files[i].fs = dp->obj.fs;
  862. Files[i].clu = dp->obj.sclust;
  863. Files[i].ofs = dp->dptr;
  864. Files[i].ctr = 0;
  865. }
  866. if (acc >= 1 && Files[i].ctr) return 0; /* Access violation (int err) */
  867. Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
  868. return i + 1; /* Index number origin from 1 */
  869. }
  870. static FRESULT dec_share ( /* Decrement object open counter */
  871. UINT i /* Semaphore index (1..) */
  872. )
  873. {
  874. UINT n;
  875. FRESULT res;
  876. if (--i < FF_FS_LOCK) { /* Index number origin from 0 */
  877. n = Files[i].ctr;
  878. if (n == 0x100) n = 0; /* If write mode open, delete the object semaphore */
  879. if (n > 0) n--; /* Decrement read mode open count */
  880. Files[i].ctr = n;
  881. if (n == 0) { /* Delete the object semaphore if open count becomes zero */
  882. Files[i].fs = 0; /* Free the entry <<<If this memory write operation is not in atomic, FF_FS_REENTRANT == 1 and FF_VOLUMES > 1, there is a potential error in this process >>> */
  883. }
  884. res = FR_OK;
  885. } else {
  886. res = FR_INT_ERR; /* Invalid index number */
  887. }
  888. return res;
  889. }
  890. static void clear_share ( /* Clear all lock entries of the volume */
  891. FATFS* fs
  892. )
  893. {
  894. UINT i;
  895. for (i = 0; i < FF_FS_LOCK; i++) {
  896. if (Files[i].fs == fs) Files[i].fs = 0;
  897. }
  898. }
  899. #endif /* FF_FS_LOCK */
  900. /*-----------------------------------------------------------------------*/
  901. /* Move/Flush disk access window in the filesystem object */
  902. /*-----------------------------------------------------------------------*/
  903. #if !FF_FS_READONLY
  904. static FRESULT sync_window ( /* Returns FR_OK or FR_DISK_ERR */
  905. FATFS* fs /* Filesystem object */
  906. )
  907. {
  908. FRESULT res = FR_OK;
  909. if (fs->wflag) { /* Is the disk access window dirty? */
  910. if (disk_write(fs->pdrv, fs->win, fs->winsect, 1) == RES_OK) { /* Write it back into the volume */
  911. fs->wflag = 0; /* Clear window dirty flag */
  912. if (fs->winsect - fs->fatbase < fs->fsize) { /* Is it in the 1st FAT? */
  913. if (fs->n_fats == 2) disk_write(fs->pdrv, fs->win, fs->winsect + fs->fsize, 1); /* Reflect it to 2nd FAT if needed */
  914. }
  915. } else {
  916. res = FR_DISK_ERR;
  917. }
  918. }
  919. return res;
  920. }
  921. #endif
  922. static FRESULT move_window ( /* Returns FR_OK or FR_DISK_ERR */
  923. FATFS* fs, /* Filesystem object */
  924. LBA_t sect /* Sector LBA to make appearance in the fs->win[] */
  925. )
  926. {
  927. FRESULT res = FR_OK;
  928. if (sect != fs->winsect) { /* Window offset changed? */
  929. #if !FF_FS_READONLY
  930. res = sync_window(fs); /* Flush the window */
  931. #endif
  932. if (res == FR_OK) { /* Fill sector window with new data */
  933. if (disk_read(fs->pdrv, fs->win, sect, 1) != RES_OK) {
  934. sect = (LBA_t)0 - 1; /* Invalidate window if read data is not valid */
  935. res = FR_DISK_ERR;
  936. }
  937. fs->winsect = sect;
  938. }
  939. }
  940. return res;
  941. }
  942. #if !FF_FS_READONLY
  943. /*-----------------------------------------------------------------------*/
  944. /* Synchronize filesystem and data on the storage */
  945. /*-----------------------------------------------------------------------*/
  946. static FRESULT sync_fs ( /* Returns FR_OK or FR_DISK_ERR */
  947. FATFS* fs /* Filesystem object */
  948. )
  949. {
  950. FRESULT res;
  951. res = sync_window(fs);
  952. if (res == FR_OK) {
  953. if (fs->fsi_flag == 1) { /* Allocation changed? */
  954. fs->fsi_flag = 0;
  955. if (fs->fs_type == FS_FAT32) { /* FAT32: Update FSInfo sector */
  956. /* Create FSInfo structure */
  957. memset(fs->win, 0, sizeof fs->win);
  958. st_32(fs->win + FSI_LeadSig, 0x41615252); /* Leading signature */
  959. st_32(fs->win + FSI_StrucSig, 0x61417272); /* Structure signature */
  960. st_32(fs->win + FSI_Free_Count, fs->free_clst); /* Number of free clusters */
  961. st_32(fs->win + FSI_Nxt_Free, fs->last_clst); /* Last allocated culuster */
  962. st_32(fs->win + FSI_TrailSig, 0xAA550000); /* Trailing signature */
  963. disk_write(fs->pdrv, fs->win, fs->winsect = fs->volbase + 1, 1); /* Write it into the FSInfo sector (Next to VBR) */
  964. }
  965. #if FF_FS_EXFAT
  966. else if (fs->fs_type == FS_EXFAT) { /* exFAT: Update PercInUse field in BPB */
  967. if (disk_read(fs->pdrv, fs->win, fs->winsect = fs->volbase, 1) == RES_OK) { /* Load VBR */
  968. BYTE perc_inuse = (fs->free_clst <= fs->n_fatent - 2) ? (BYTE)((QWORD)(fs->n_fatent - 2 - fs->free_clst) * 100 / (fs->n_fatent - 2)) : 0xFF; /* Precent in use 0-100 or 0xFF(unknown) */
  969. if (fs->win[BPB_PercInUseEx] != perc_inuse) { /* Write it back into VBR if needed */
  970. fs->win[BPB_PercInUseEx] = perc_inuse;
  971. disk_write(fs->pdrv, fs->win, fs->winsect, 1);
  972. }
  973. }
  974. }
  975. #endif
  976. }
  977. /* Make sure that no pending write process in the lower layer */
  978. if (disk_ioctl(fs->pdrv, CTRL_SYNC, 0) != RES_OK) res = FR_DISK_ERR;
  979. }
  980. return res;
  981. }
  982. #endif
  983. /*-----------------------------------------------------------------------*/
  984. /* Get physical sector number from cluster number */
  985. /*-----------------------------------------------------------------------*/
  986. static LBA_t clst2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
  987. FATFS* fs, /* Filesystem object */
  988. DWORD clst /* Cluster# to be converted */
  989. )
  990. {
  991. clst -= 2; /* Cluster number is origin from 2 */
  992. if (clst >= fs->n_fatent - 2) return 0; /* Is it invalid cluster number? */
  993. return fs->database + (LBA_t)fs->csize * clst; /* Start sector number of the cluster */
  994. }
  995. /*-----------------------------------------------------------------------*/
  996. /* FAT access - Read value of an FAT entry */
  997. /*-----------------------------------------------------------------------*/
  998. static DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */
  999. FFOBJID* obj, /* Corresponding object */
  1000. DWORD clst /* Cluster number to get the value */
  1001. )
  1002. {
  1003. UINT wc, bc;
  1004. DWORD val;
  1005. FATFS *fs = obj->fs;
  1006. if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */
  1007. val = 1; /* Internal error */
  1008. } else {
  1009. val = 0xFFFFFFFF; /* Default value falls on disk error */
  1010. switch (fs->fs_type) {
  1011. case FS_FAT12 :
  1012. bc = (UINT)clst; bc += bc / 2;
  1013. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  1014. wc = fs->win[bc++ % SS(fs)]; /* Get 1st byte of the entry */
  1015. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  1016. wc |= fs->win[bc % SS(fs)] << 8; /* Merge 2nd byte of the entry */
  1017. val = (clst & 1) ? (wc >> 4) : (wc & 0xFFF); /* Adjust bit position */
  1018. break;
  1019. case FS_FAT16 :
  1020. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
  1021. val = ld_16(fs->win + clst * 2 % SS(fs)); /* Simple WORD array */
  1022. break;
  1023. case FS_FAT32 :
  1024. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  1025. val = ld_32(fs->win + clst * 4 % SS(fs)) & 0x0FFFFFFF; /* Simple DWORD array but mask out upper 4 bits */
  1026. break;
  1027. #if FF_FS_EXFAT
  1028. case FS_EXFAT :
  1029. if ((obj->objsize != 0 && obj->sclust != 0) || obj->stat == 0) { /* Object except root dir must have valid data length */
  1030. DWORD cofs = clst - obj->sclust; /* Offset from start cluster */
  1031. DWORD clen = (DWORD)((LBA_t)((obj->objsize - 1) / SS(fs)) / fs->csize); /* Number of clusters - 1 */
  1032. if (obj->stat == 2 && cofs <= clen) { /* Is it a contiguous chain? */
  1033. val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* No data on the FAT, generate the value */
  1034. break;
  1035. }
  1036. if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the 1st fragment? */
  1037. val = clst + 1; /* Generate the value */
  1038. break;
  1039. }
  1040. if (obj->stat != 2) { /* Get value from FAT if FAT chain is valid */
  1041. if (obj->n_frag != 0) { /* Is it on the growing edge? */
  1042. val = 0x7FFFFFFF; /* Generate EOC */
  1043. } else {
  1044. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  1045. val = ld_32(fs->win + clst * 4 % SS(fs)) & 0x7FFFFFFF;
  1046. }
  1047. break;
  1048. }
  1049. }
  1050. val = 1; /* Internal error */
  1051. break;
  1052. #endif
  1053. default:
  1054. val = 1; /* Internal error */
  1055. }
  1056. }
  1057. return val;
  1058. }
  1059. #if !FF_FS_READONLY
  1060. /*-----------------------------------------------------------------------*/
  1061. /* FAT access - Change value of an FAT entry */
  1062. /*-----------------------------------------------------------------------*/
  1063. static FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */
  1064. FATFS* fs, /* Corresponding filesystem object */
  1065. DWORD clst, /* FAT index number (cluster number) to be changed */
  1066. DWORD val /* New value to be set to the entry */
  1067. )
  1068. {
  1069. UINT bc;
  1070. BYTE *p;
  1071. FRESULT res = FR_INT_ERR;
  1072. if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */
  1073. switch (fs->fs_type) {
  1074. case FS_FAT12:
  1075. bc = (UINT)clst; bc += bc / 2; /* bc: byte offset of the entry */
  1076. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  1077. if (res != FR_OK) break;
  1078. p = fs->win + bc++ % SS(fs);
  1079. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; /* Update 1st byte */
  1080. fs->wflag = 1;
  1081. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  1082. if (res != FR_OK) break;
  1083. p = fs->win + bc % SS(fs);
  1084. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); /* Update 2nd byte */
  1085. fs->wflag = 1;
  1086. break;
  1087. case FS_FAT16:
  1088. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  1089. if (res != FR_OK) break;
  1090. st_16(fs->win + clst * 2 % SS(fs), (WORD)val); /* Simple WORD array */
  1091. fs->wflag = 1;
  1092. break;
  1093. case FS_FAT32:
  1094. #if FF_FS_EXFAT
  1095. case FS_EXFAT:
  1096. #endif
  1097. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  1098. if (res != FR_OK) break;
  1099. if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  1100. val = (val & 0x0FFFFFFF) | (ld_32(fs->win + clst * 4 % SS(fs)) & 0xF0000000);
  1101. }
  1102. st_32(fs->win + clst * 4 % SS(fs), val);
  1103. fs->wflag = 1;
  1104. break;
  1105. }
  1106. }
  1107. return res;
  1108. }
  1109. #endif /* !FF_FS_READONLY */
  1110. #if FF_FS_EXFAT && !FF_FS_READONLY
  1111. /*-----------------------------------------------------------------------*/
  1112. /* exFAT: Accessing FAT and Allocation Bitmap */
  1113. /*-----------------------------------------------------------------------*/
  1114. /*--------------------------------------*/
  1115. /* Find a contiguous free cluster block */
  1116. /*--------------------------------------*/
  1117. static DWORD find_bitmap ( /* 0:Not found, 2..:Cluster block found, 0xFFFFFFFF:Disk error */
  1118. FATFS* fs, /* Filesystem object */
  1119. DWORD clst, /* Cluster number to scan from */
  1120. DWORD ncl /* Number of contiguous clusters to find (1..) */
  1121. )
  1122. {
  1123. BYTE bm, bv;
  1124. UINT i;
  1125. DWORD val, scl, ctr;
  1126. clst -= 2; /* The first bit in the bitmap corresponds to cluster #2 */
  1127. if (clst >= fs->n_fatent - 2) clst = 0;
  1128. scl = val = clst; ctr = 0;
  1129. for (;;) {
  1130. if (move_window(fs, fs->bitbase + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF;
  1131. i = val / 8 % SS(fs); bm = 1 << (val % 8);
  1132. do {
  1133. do {
  1134. bv = fs->win[i] & bm; bm <<= 1; /* Get bit value */
  1135. if (++val >= fs->n_fatent - 2) { /* Next cluster (with wrap-around) */
  1136. val = 0; bm = 0; i = SS(fs);
  1137. }
  1138. if (bv == 0) { /* Is it a free cluster? */
  1139. if (++ctr == ncl) return scl + 2; /* Check if run length is sufficient for required */
  1140. } else {
  1141. scl = val; ctr = 0; /* Encountered a cluster in-use, restart to scan */
  1142. }
  1143. if (val == clst) return 0; /* All cluster scanned? */
  1144. } while (bm != 0);
  1145. bm = 1;
  1146. } while (++i < SS(fs));
  1147. }
  1148. }
  1149. /*----------------------------------------*/
  1150. /* Set/Clear a block of allocation bitmap */
  1151. /*----------------------------------------*/
  1152. static FRESULT change_bitmap (
  1153. FATFS* fs, /* Filesystem object */
  1154. DWORD clst, /* Cluster number to change from */
  1155. DWORD ncl, /* Number of clusters to be changed */
  1156. int bv /* bit value to be set (0 or 1) */
  1157. )
  1158. {
  1159. BYTE bm;
  1160. UINT i;
  1161. LBA_t sect;
  1162. clst -= 2; /* The first bit corresponds to cluster #2 */
  1163. sect = fs->bitbase + clst / 8 / SS(fs); /* Sector address */
  1164. i = clst / 8 % SS(fs); /* Byte offset in the sector */
  1165. bm = 1 << (clst % 8); /* Bit mask in the byte */
  1166. for (;;) {
  1167. if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;
  1168. do {
  1169. do {
  1170. if (bv == (int)((fs->win[i] & bm) != 0)) return FR_INT_ERR; /* Is the bit expected value? */
  1171. fs->win[i] ^= bm; /* Flip the bit */
  1172. fs->wflag = 1;
  1173. if (--ncl == 0) return FR_OK; /* All bits processed? */
  1174. } while (bm <<= 1); /* Next bit */
  1175. bm = 1;
  1176. } while (++i < SS(fs)); /* Next byte */
  1177. i = 0;
  1178. }
  1179. }
  1180. /*---------------------------------------------*/
  1181. /* Fill the first fragment of the FAT chain */
  1182. /*---------------------------------------------*/
  1183. static FRESULT fill_first_frag (
  1184. FFOBJID* obj /* Pointer to the corresponding object */
  1185. )
  1186. {
  1187. FRESULT res;
  1188. DWORD cl, n;
  1189. if (obj->stat == 3) { /* Has the object been changed 'fragmented' in this session? */
  1190. for (cl = obj->sclust, n = obj->n_cont; n; cl++, n--) { /* Create cluster chain on the FAT */
  1191. res = put_fat(obj->fs, cl, cl + 1);
  1192. if (res != FR_OK) return res;
  1193. }
  1194. obj->stat = 0; /* Change status 'FAT chain is valid' */
  1195. }
  1196. return FR_OK;
  1197. }
  1198. /*---------------------------------------------*/
  1199. /* Fill the last fragment of the FAT chain */
  1200. /*---------------------------------------------*/
  1201. static FRESULT fill_last_frag (
  1202. FFOBJID* obj, /* Pointer to the corresponding object */
  1203. DWORD lcl, /* Last cluster of the fragment */
  1204. DWORD term /* Value to set the last FAT entry */
  1205. )
  1206. {
  1207. FRESULT res;
  1208. while (obj->n_frag > 0) { /* Create the chain of last fragment */
  1209. res = put_fat(obj->fs, lcl - obj->n_frag + 1, (obj->n_frag > 1) ? lcl - obj->n_frag + 2 : term);
  1210. if (res != FR_OK) return res;
  1211. obj->n_frag--;
  1212. }
  1213. return FR_OK;
  1214. }
  1215. #endif /* FF_FS_EXFAT && !FF_FS_READONLY */
  1216. #if !FF_FS_READONLY
  1217. /*-----------------------------------------------------------------------*/
  1218. /* FAT handling - Remove a cluster chain */
  1219. /*-----------------------------------------------------------------------*/
  1220. static FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */
  1221. FFOBJID* obj, /* Corresponding object */
  1222. DWORD clst, /* Cluster to remove a chain from */
  1223. DWORD pclst /* Previous cluster of clst (0 if entire chain) */
  1224. )
  1225. {
  1226. FRESULT res = FR_OK;
  1227. DWORD nxt;
  1228. FATFS *fs = obj->fs;
  1229. #if FF_FS_EXFAT || FF_USE_TRIM
  1230. DWORD scl = clst, ecl = clst;
  1231. #endif
  1232. #if FF_USE_TRIM
  1233. LBA_t rt[2];
  1234. #endif
  1235. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */
  1236. /* Mark the previous cluster 'EOC' on the FAT if it exists */
  1237. if (pclst != 0 && (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT || obj->stat != 2)) {
  1238. res = put_fat(fs, pclst, 0xFFFFFFFF);
  1239. if (res != FR_OK) return res;
  1240. }
  1241. /* Remove the chain */
  1242. do {
  1243. nxt = get_fat(obj, clst); /* Get cluster status */
  1244. if (nxt == 0) break; /* Empty cluster? */
  1245. if (nxt == 1) return FR_INT_ERR; /* Internal error? */
  1246. if (nxt == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error? */
  1247. if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  1248. res = put_fat(fs, clst, 0); /* Mark the cluster 'free' on the FAT */
  1249. if (res != FR_OK) return res;
  1250. }
  1251. if (fs->free_clst < fs->n_fatent - 2) { /* Update allocation information if it is valid */
  1252. fs->free_clst++;
  1253. fs->fsi_flag |= 1;
  1254. }
  1255. #if FF_FS_EXFAT || FF_USE_TRIM
  1256. if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
  1257. ecl = nxt;
  1258. } else { /* End of contiguous cluster block */
  1259. #if FF_FS_EXFAT
  1260. if (fs->fs_type == FS_EXFAT) {
  1261. res = change_bitmap(fs, scl, ecl - scl + 1, 0); /* Mark the cluster block 'free' on the bitmap */
  1262. if (res != FR_OK) return res;
  1263. }
  1264. #endif
  1265. #if FF_USE_TRIM
  1266. rt[0] = clst2sect(fs, scl); /* Start of data area to be freed */
  1267. rt[1] = clst2sect(fs, ecl) + fs->csize - 1; /* End of data area to be freed */
  1268. disk_ioctl(fs->pdrv, CTRL_TRIM, rt); /* Inform storage device that the data in the block may be erased */
  1269. #endif
  1270. scl = ecl = nxt;
  1271. }
  1272. #endif
  1273. clst = nxt; /* Next cluster */
  1274. } while (clst < fs->n_fatent); /* Repeat until the last link */
  1275. #if FF_FS_EXFAT
  1276. /* Some post processes for chain status */
  1277. if (fs->fs_type == FS_EXFAT) {
  1278. if (pclst == 0) { /* Has the entire chain been removed? */
  1279. obj->stat = 0; /* Change the chain status 'initial' */
  1280. } else {
  1281. if (obj->stat == 0) { /* Is it a fragmented chain from the beginning of this session? */
  1282. clst = obj->sclust; /* Follow the chain to check if it gets contiguous */
  1283. while (clst != pclst) {
  1284. nxt = get_fat(obj, clst);
  1285. if (nxt < 2) return FR_INT_ERR;
  1286. if (nxt == 0xFFFFFFFF) return FR_DISK_ERR;
  1287. if (nxt != clst + 1) break; /* Not contiguous? */
  1288. clst++;
  1289. }
  1290. if (clst == pclst) { /* Has the chain got contiguous again? */
  1291. obj->stat = 2; /* Change the chain status 'contiguous' */
  1292. }
  1293. } else {
  1294. if (obj->stat == 3 && pclst >= obj->sclust && pclst <= obj->sclust + obj->n_cont) { /* Was the chain fragmented in this session and got contiguous again? */
  1295. obj->stat = 2; /* Change the chain status 'contiguous' */
  1296. }
  1297. }
  1298. }
  1299. }
  1300. #endif
  1301. return FR_OK;
  1302. }
  1303. /*-----------------------------------------------------------------------*/
  1304. /* FAT handling - Stretch a chain or Create a new chain */
  1305. /*-----------------------------------------------------------------------*/
  1306. static DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  1307. FFOBJID* obj, /* Corresponding object */
  1308. DWORD clst /* Cluster# to stretch, 0:Create a new chain */
  1309. )
  1310. {
  1311. DWORD cs, ncl, scl;
  1312. FRESULT res;
  1313. FATFS *fs = obj->fs;
  1314. if (clst == 0) { /* Create a new chain */
  1315. scl = fs->last_clst; /* Suggested cluster to start to find */
  1316. if (scl == 0 || scl >= fs->n_fatent) scl = 1;
  1317. }
  1318. else { /* Stretch a chain */
  1319. cs = get_fat(obj, clst); /* Check the cluster status */
  1320. if (cs < 2) return 1; /* Test for insanity */
  1321. if (cs == 0xFFFFFFFF) return cs; /* Test for disk error */
  1322. if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
  1323. scl = clst; /* Cluster to start to find */
  1324. }
  1325. if (fs->free_clst == 0) return 0; /* No free cluster */
  1326. #if FF_FS_EXFAT
  1327. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1328. ncl = find_bitmap(fs, scl, 1); /* Find a free cluster */
  1329. if (ncl == 0 || ncl == 0xFFFFFFFF) return ncl; /* No free cluster or hard error? */
  1330. res = change_bitmap(fs, ncl, 1, 1); /* Mark the cluster 'in use' */
  1331. if (res == FR_INT_ERR) return 1;
  1332. if (res == FR_DISK_ERR) return 0xFFFFFFFF;
  1333. if (clst == 0) { /* Is it a new chain? */
  1334. obj->stat = 2; /* Set status 'contiguous' */
  1335. } else { /* It is a stretched chain */
  1336. if (obj->stat == 2 && ncl != scl + 1) { /* Is the chain got fragmented? */
  1337. obj->n_cont = scl - obj->sclust; /* Set size of the contiguous part */
  1338. obj->stat = 3; /* Change status 'just fragmented' */
  1339. }
  1340. }
  1341. if (obj->stat != 2) { /* Is the file non-contiguous? */
  1342. if (ncl == clst + 1) { /* Is the cluster next to previous one? */
  1343. obj->n_frag = obj->n_frag ? obj->n_frag + 1 : 2; /* Increment size of last framgent */
  1344. } else { /* New fragment */
  1345. if (obj->n_frag == 0) obj->n_frag = 1;
  1346. res = fill_last_frag(obj, clst, ncl); /* Fill last fragment on the FAT and link it to new one */
  1347. if (res == FR_OK) obj->n_frag = 1;
  1348. }
  1349. }
  1350. } else
  1351. #endif
  1352. { /* On the FAT/FAT32 volume */
  1353. ncl = 0;
  1354. if (scl == clst) { /* Stretching an existing chain? */
  1355. ncl = scl + 1; /* Test if next cluster is free */
  1356. if (ncl >= fs->n_fatent) ncl = 2;
  1357. cs = get_fat(obj, ncl); /* Get next cluster status */
  1358. if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* Test for error */
  1359. if (cs != 0) { /* Not free? */
  1360. cs = fs->last_clst; /* Start at suggested cluster if it is valid */
  1361. if (cs >= 2 && cs < fs->n_fatent) scl = cs;
  1362. ncl = 0;
  1363. }
  1364. }
  1365. if (ncl == 0) { /* The new cluster cannot be contiguous and find another fragment */
  1366. ncl = scl; /* Start cluster */
  1367. for (;;) {
  1368. ncl++; /* Next cluster */
  1369. if (ncl >= fs->n_fatent) { /* Check wrap-around */
  1370. ncl = 2;
  1371. if (ncl > scl) return 0; /* No free cluster found? */
  1372. }
  1373. cs = get_fat(obj, ncl); /* Get the cluster status */
  1374. if (cs == 0) break; /* Found a free cluster? */
  1375. if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* Test for error */
  1376. if (ncl == scl) return 0; /* No free cluster found? */
  1377. }
  1378. }
  1379. res = put_fat(fs, ncl, 0xFFFFFFFF); /* Mark the new cluster 'EOC' */
  1380. if (res == FR_OK && clst != 0) {
  1381. res = put_fat(fs, clst, ncl); /* Link it from the previous one if needed */
  1382. }
  1383. }
  1384. if (res == FR_OK) { /* Update allocation information if the function succeeded */
  1385. fs->last_clst = ncl;
  1386. if (fs->free_clst > 0 && fs->free_clst <= fs->n_fatent - 2) {
  1387. fs->free_clst--;
  1388. fs->fsi_flag |= 1;
  1389. }
  1390. } else {
  1391. ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; /* Failed. Generate error status */
  1392. }
  1393. return ncl; /* Return new cluster number or error status */
  1394. }
  1395. #endif /* !FF_FS_READONLY */
  1396. #if FF_USE_FASTSEEK
  1397. /*-----------------------------------------------------------------------*/
  1398. /* FAT handling - Convert offset into cluster with link map table */
  1399. /*-----------------------------------------------------------------------*/
  1400. static DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */
  1401. FIL* fp, /* Pointer to the file object */
  1402. FSIZE_t ofs /* File offset to be converted to cluster# */
  1403. )
  1404. {
  1405. DWORD cl, ncl;
  1406. DWORD *tbl;
  1407. FATFS *fs = fp->obj.fs;
  1408. tbl = fp->cltbl + 1; /* Top of CLMT */
  1409. cl = (DWORD)(ofs / SS(fs) / fs->csize); /* Cluster order from top of the file */
  1410. for (;;) {
  1411. ncl = *tbl++; /* Number of cluters in the fragment */
  1412. if (ncl == 0) return 0; /* End of table? (error) */
  1413. if (cl < ncl) break; /* In this fragment? */
  1414. cl -= ncl; tbl++; /* Next fragment */
  1415. }
  1416. return cl + *tbl; /* Return the cluster number */
  1417. }
  1418. #endif /* FF_USE_FASTSEEK */
  1419. /*-----------------------------------------------------------------------*/
  1420. /* Directory handling - Fill a cluster with zeros */
  1421. /*-----------------------------------------------------------------------*/
  1422. #if !FF_FS_READONLY
  1423. static FRESULT dir_clear ( /* Returns FR_OK or FR_DISK_ERR */
  1424. FATFS *fs, /* Filesystem object */
  1425. DWORD clst /* Directory table to clear */
  1426. )
  1427. {
  1428. LBA_t sect;
  1429. UINT n, szb;
  1430. BYTE *ibuf;
  1431. if (sync_window(fs) != FR_OK) return FR_DISK_ERR; /* Flush disk access window */
  1432. sect = clst2sect(fs, clst); /* Top of the cluster */
  1433. fs->winsect = sect; /* Set window to top of the cluster */
  1434. memset(fs->win, 0, sizeof fs->win); /* Clear window buffer */
  1435. #if FF_USE_LFN == 3 /* Quick table clear by using multi-secter write */
  1436. /* Allocate a temporary buffer */
  1437. for (szb = ((DWORD)fs->csize * SS(fs) >= MAX_MALLOC) ? MAX_MALLOC : fs->csize * SS(fs), ibuf = 0; szb > SS(fs) && (ibuf = ff_memalloc(szb)) == 0; szb /= 2) ;
  1438. if (szb > SS(fs)) { /* Buffer allocated? */
  1439. memset(ibuf, 0, szb);
  1440. szb /= SS(fs); /* Bytes -> Sectors */
  1441. for (n = 0; n < fs->csize && disk_write(fs->pdrv, ibuf, sect + n, szb) == RES_OK; n += szb) ; /* Fill the cluster with 0 */
  1442. ff_memfree(ibuf);
  1443. } else
  1444. #endif
  1445. {
  1446. ibuf = fs->win; szb = 1; /* Use window buffer (many single-sector writes may take a time) */
  1447. for (n = 0; n < fs->csize && disk_write(fs->pdrv, ibuf, sect + n, szb) == RES_OK; n += szb) ; /* Fill the cluster with 0 */
  1448. }
  1449. return (n == fs->csize) ? FR_OK : FR_DISK_ERR;
  1450. }
  1451. #endif /* !FF_FS_READONLY */
  1452. /*-----------------------------------------------------------------------*/
  1453. /* Directory handling - Set directory index */
  1454. /*-----------------------------------------------------------------------*/
  1455. static FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
  1456. DIR* dp, /* Pointer to directory object */
  1457. DWORD ofs /* Offset of directory table */
  1458. )
  1459. {
  1460. DWORD csz, clst;
  1461. FATFS *fs = dp->obj.fs;
  1462. if (ofs >= (DWORD)((FF_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR) || ofs % SZDIRE) { /* Check range of offset and alignment */
  1463. return FR_INT_ERR;
  1464. }
  1465. dp->dptr = ofs; /* Set current offset */
  1466. clst = dp->obj.sclust; /* Table start cluster (0:root) */
  1467. if (clst == 0 && fs->fs_type >= FS_FAT32) { /* Replace cluster# 0 with root cluster# */
  1468. clst = (DWORD)fs->dirbase;
  1469. if (FF_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */
  1470. }
  1471. if (clst == 0) { /* Static table (root-directory on the FAT volume) */
  1472. if (ofs / SZDIRE >= fs->n_rootdir) return FR_INT_ERR; /* Is index out of range? */
  1473. dp->sect = fs->dirbase;
  1474. } else { /* Dynamic table (sub-directory or root-directory on the FAT32/exFAT volume) */
  1475. csz = (DWORD)fs->csize * SS(fs); /* Bytes per cluster */
  1476. while (ofs >= csz) { /* Follow cluster chain */
  1477. clst = get_fat(&dp->obj, clst); /* Get next cluster */
  1478. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1479. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Reached to end of table or internal error */
  1480. ofs -= csz;
  1481. }
  1482. dp->sect = clst2sect(fs, clst);
  1483. }
  1484. dp->clust = clst; /* Current cluster# */
  1485. if (dp->sect == 0) return FR_INT_ERR;
  1486. dp->sect += ofs / SS(fs); /* Sector# of the directory entry */
  1487. dp->dir = fs->win + (ofs % SS(fs)); /* Pointer to the entry in the win[] */
  1488. return FR_OK;
  1489. }
  1490. /*-----------------------------------------------------------------------*/
  1491. /* Directory handling - Move directory table index next */
  1492. /*-----------------------------------------------------------------------*/
  1493. static FRESULT dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
  1494. DIR* dp, /* Pointer to the directory object */
  1495. int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
  1496. )
  1497. {
  1498. DWORD ofs, clst;
  1499. FATFS *fs = dp->obj.fs;
  1500. ofs = dp->dptr + SZDIRE; /* Next entry */
  1501. if (ofs >= (DWORD)((FF_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR)) dp->sect = 0; /* Disable it if the offset reached the max value */
  1502. if (dp->sect == 0) return FR_NO_FILE; /* Report EOT if it has been disabled */
  1503. if (ofs % SS(fs) == 0) { /* Sector changed? */
  1504. dp->sect++; /* Next sector */
  1505. if (dp->clust == 0) { /* Static table */
  1506. if (ofs / SZDIRE >= fs->n_rootdir) { /* Report EOT if it reached end of static table */
  1507. dp->sect = 0; return FR_NO_FILE;
  1508. }
  1509. }
  1510. else { /* Dynamic table */
  1511. if ((ofs / SS(fs) & (fs->csize - 1)) == 0) { /* Cluster changed? */
  1512. clst = get_fat(&dp->obj, dp->clust); /* Get next cluster */
  1513. if (clst <= 1) return FR_INT_ERR; /* Internal error */
  1514. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1515. if (clst >= fs->n_fatent) { /* It reached end of dynamic table */
  1516. #if !FF_FS_READONLY
  1517. if (!stretch) { /* If no stretch, report EOT */
  1518. dp->sect = 0; return FR_NO_FILE;
  1519. }
  1520. clst = create_chain(&dp->obj, dp->clust); /* Allocate a cluster */
  1521. if (clst == 0) return FR_DENIED; /* No free cluster */
  1522. if (clst == 1) return FR_INT_ERR; /* Internal error */
  1523. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1524. if (dir_clear(fs, clst) != FR_OK) return FR_DISK_ERR; /* Clean up the stretched table */
  1525. if (FF_FS_EXFAT) dp->obj.stat |= 4; /* exFAT: The directory has been stretched */
  1526. #else
  1527. if (!stretch) dp->sect = 0; /* (this line is to suppress compiler warning) */
  1528. dp->sect = 0; return FR_NO_FILE; /* Report EOT */
  1529. #endif
  1530. }
  1531. dp->clust = clst; /* Initialize data for new cluster */
  1532. dp->sect = clst2sect(fs, clst);
  1533. }
  1534. }
  1535. }
  1536. dp->dptr = ofs; /* Current entry */
  1537. dp->dir = fs->win + ofs % SS(fs); /* Pointer to the entry in the win[] */
  1538. return FR_OK;
  1539. }
  1540. #if !FF_FS_READONLY
  1541. /*-----------------------------------------------------------------------*/
  1542. /* Directory handling - Reserve a block of directory entries */
  1543. /*-----------------------------------------------------------------------*/
  1544. static FRESULT dir_alloc ( /* FR_OK(0):succeeded, !=0:error */
  1545. DIR* dp, /* Pointer to the directory object */
  1546. UINT n_ent /* Number of contiguous entries to allocate */
  1547. )
  1548. {
  1549. FRESULT res;
  1550. UINT n;
  1551. FATFS *fs = dp->obj.fs;
  1552. res = dir_sdi(dp, 0);
  1553. if (res == FR_OK) {
  1554. n = 0;
  1555. do {
  1556. res = move_window(fs, dp->sect);
  1557. if (res != FR_OK) break;
  1558. #if FF_FS_EXFAT
  1559. if ((fs->fs_type == FS_EXFAT) ? (int)((dp->dir[XDIR_Type] & 0x80) == 0) : (int)(dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0)) { /* Is the entry free? */
  1560. #else
  1561. if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) { /* Is the entry free? */
  1562. #endif
  1563. if (++n == n_ent) break; /* Is a block of contiguous free entries found? */
  1564. } else {
  1565. n = 0; /* Not a free entry, restart to search */
  1566. }
  1567. res = dir_next(dp, 1); /* Next entry with table stretch enabled */
  1568. } while (res == FR_OK);
  1569. }
  1570. if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */
  1571. return res;
  1572. }
  1573. #endif /* !FF_FS_READONLY */
  1574. /*-----------------------------------------------------------------------*/
  1575. /* FAT: Directory handling - Load/Store start cluster number */
  1576. /*-----------------------------------------------------------------------*/
  1577. static DWORD ld_clust ( /* Returns the top cluster value of the SFN entry */
  1578. FATFS* fs, /* Pointer to the fs object */
  1579. const BYTE* dir /* Pointer to the key entry */
  1580. )
  1581. {
  1582. DWORD cl;
  1583. cl = ld_16(dir + DIR_FstClusLO);
  1584. if (fs->fs_type == FS_FAT32) {
  1585. cl |= (DWORD)ld_16(dir + DIR_FstClusHI) << 16;
  1586. }
  1587. return cl;
  1588. }
  1589. #if !FF_FS_READONLY
  1590. static void st_clust (
  1591. FATFS* fs, /* Pointer to the fs object */
  1592. BYTE* dir, /* Pointer to the key entry */
  1593. DWORD cl /* Value to be set */
  1594. )
  1595. {
  1596. st_16(dir + DIR_FstClusLO, (WORD)cl);
  1597. if (fs->fs_type == FS_FAT32) {
  1598. st_16(dir + DIR_FstClusHI, (WORD)(cl >> 16));
  1599. }
  1600. }
  1601. #endif
  1602. #if FF_USE_LFN
  1603. /*--------------------------------------------------------*/
  1604. /* FAT-LFN: Compare a part of file name with an LFN entry */
  1605. /*--------------------------------------------------------*/
  1606. static int cmp_lfn ( /* 1:matched, 0:not matched */
  1607. const WCHAR* lfnbuf, /* Pointer to the LFN to be compared */
  1608. BYTE* dir /* Pointer to the LFN entry */
  1609. )
  1610. {
  1611. UINT ni, di;
  1612. WCHAR pchr, chr;
  1613. if (ld_16(dir + LDIR_FstClusLO) != 0) return 0; /* Check if LDIR_FstClusLO is 0 */
  1614. ni = (UINT)((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the name to be compared */
  1615. for (pchr = 1, di = 0; di < 13; di++) { /* Process all characters in the entry */
  1616. chr = ld_16(dir + LfnOfs[di]); /* Pick a character from the entry */
  1617. if (pchr != 0) {
  1618. if (ni >= FF_MAX_LFN + 1 || ff_wtoupper(chr) != ff_wtoupper(lfnbuf[ni++])) { /* Compare it with name */
  1619. return 0; /* Not matched */
  1620. }
  1621. pchr = chr;
  1622. } else {
  1623. if (chr != 0xFFFF) return 0; /* Check filler */
  1624. }
  1625. }
  1626. if ((dir[LDIR_Ord] & LLEF) && pchr && lfnbuf[ni]) return 0; /* Last name segment matched but different length */
  1627. return 1; /* The part of LFN matched */
  1628. }
  1629. #if FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 || FF_USE_LABEL || FF_FS_EXFAT
  1630. /*-----------------------------------------------------*/
  1631. /* FAT-LFN: Pick a part of file name from an LFN entry */
  1632. /*-----------------------------------------------------*/
  1633. static int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */
  1634. WCHAR* lfnbuf, /* Pointer to the name buffer to be stored */
  1635. const BYTE* dir /* Pointer to the LFN entry */
  1636. )
  1637. {
  1638. UINT ni, di;
  1639. WCHAR pchr, chr;
  1640. if (ld_16(dir + LDIR_FstClusLO) != 0) return 0; /* Check if LDIR_FstClusLO is 0 */
  1641. ni = (UINT)((dir[LDIR_Ord] & ~LLEF) - 1) * 13; /* Offset in the name buffer */
  1642. for (pchr = 1, di = 0; di < 13; di++) { /* Process all characters in the entry */
  1643. chr = ld_16(dir + LfnOfs[di]); /* Pick a character from the entry */
  1644. if (pchr != 0) {
  1645. if (ni >= FF_MAX_LFN + 1) return 0; /* Buffer overflow? */
  1646. lfnbuf[ni++] = pchr = chr; /* Store it */
  1647. } else {
  1648. if (chr != 0xFFFF) return 0; /* Check filler */
  1649. }
  1650. }
  1651. if (dir[LDIR_Ord] & LLEF && pchr != 0) { /* Put terminator if it is the last LFN part and not terminated */
  1652. if (ni >= FF_MAX_LFN + 1) return 0; /* Buffer overflow? */
  1653. lfnbuf[ni] = 0;
  1654. }
  1655. return 1; /* The part of LFN is valid */
  1656. }
  1657. #endif
  1658. #if !FF_FS_READONLY
  1659. /*-----------------------------------------*/
  1660. /* FAT-LFN: Create an entry of LFN entries */
  1661. /*-----------------------------------------*/
  1662. static void put_lfn (
  1663. const WCHAR* lfn, /* Pointer to the LFN */
  1664. BYTE* dir, /* Pointer to the LFN entry to be created */
  1665. BYTE ord, /* LFN order (1-20) */
  1666. BYTE sum /* Checksum of the corresponding SFN */
  1667. )
  1668. {
  1669. UINT ni, di;
  1670. WCHAR chr;
  1671. dir[LDIR_Chksum] = sum; /* Set checksum */
  1672. dir[LDIR_Attr] = AM_LFN; /* Set attribute */
  1673. dir[LDIR_Type] = 0;
  1674. st_16(dir + LDIR_FstClusLO, 0);
  1675. ni = (UINT)(ord - 1) * 13; /* Offset in the name */
  1676. di = chr = 0;
  1677. do { /* Fill the directory entry */
  1678. if (chr != 0xFFFF) chr = lfn[ni++]; /* Get an effective character */
  1679. st_16(dir + LfnOfs[di], chr); /* Set it */
  1680. if (chr == 0) chr = 0xFFFF; /* Padding characters after the terminator */
  1681. } while (++di < 13);
  1682. if (chr == 0xFFFF || !lfn[ni]) ord |= LLEF; /* Last LFN part is the start of an enrty set */
  1683. dir[LDIR_Ord] = ord; /* Set order in the entry set */
  1684. }
  1685. #endif /* !FF_FS_READONLY */
  1686. #endif /* FF_USE_LFN */
  1687. #if FF_USE_LFN && !FF_FS_READONLY
  1688. /*-----------------------------------------------------------------------*/
  1689. /* FAT-LFN: Create a Numbered SFN */
  1690. /*-----------------------------------------------------------------------*/
  1691. static void gen_numname (
  1692. BYTE* dst, /* Pointer to the buffer to store numbered SFN */
  1693. const BYTE* src, /* Pointer to SFN in directory form */
  1694. const WCHAR* lfn, /* Pointer to LFN */
  1695. WORD seq /* Sequence number */
  1696. )
  1697. {
  1698. BYTE ns[8], c;
  1699. UINT i, j;
  1700. memcpy(dst, src, 11); /* Prepare the SFN to be modified */
  1701. if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */
  1702. WCHAR wc;
  1703. DWORD crc_sreg = seq;
  1704. while (*lfn) { /* Create a CRC value as a hash of LFN */
  1705. wc = *lfn++;
  1706. for (i = 0; i < 16; i++) {
  1707. crc_sreg = (crc_sreg << 1) + (wc & 1);
  1708. wc >>= 1;
  1709. if (crc_sreg & 0x10000) crc_sreg ^= 0x11021;
  1710. }
  1711. }
  1712. seq = (WORD)crc_sreg;
  1713. }
  1714. /* Make suffix (~ + 4-digit hexadecimal) */
  1715. i = 7;
  1716. do {
  1717. c = (BYTE)((seq % 16) + '0'); seq /= 16;
  1718. if (c > '9') c += 7;
  1719. ns[i--] = c;
  1720. } while (i && seq);
  1721. ns[i] = '~';
  1722. /* Append the suffix to the SFN body */
  1723. for (j = 0; j < i && dst[j] != ' '; j++) { /* Find the offset to append */
  1724. if (dbc_1st(dst[j])) { /* To avoid DBC break up */
  1725. if (j == i - 1) break;
  1726. j++;
  1727. }
  1728. }
  1729. do { /* Append the suffix */
  1730. dst[j++] = (i < 8) ? ns[i++] : ' ';
  1731. } while (j < 8);
  1732. }
  1733. #endif /* FF_USE_LFN && !FF_FS_READONLY */
  1734. #if FF_USE_LFN
  1735. /*-----------------------------------------------------------------------*/
  1736. /* FAT-LFN: Calculate checksum of an SFN entry */
  1737. /*-----------------------------------------------------------------------*/
  1738. static BYTE sum_sfn (
  1739. const BYTE* dir /* Pointer to the SFN entry */
  1740. )
  1741. {
  1742. BYTE sum = 0;
  1743. UINT n = 11;
  1744. do {
  1745. sum = (sum >> 1) + (sum << 7) + *dir++;
  1746. } while (--n);
  1747. return sum;
  1748. }
  1749. #endif /* FF_USE_LFN */
  1750. #if FF_FS_EXFAT
  1751. /*-----------------------------------------------------------------------*/
  1752. /* exFAT: Checksum */
  1753. /*-----------------------------------------------------------------------*/
  1754. static WORD xdir_sum ( /* Get checksum of the directoly entry block */
  1755. const BYTE* dir /* Directory entry block to be calculated */
  1756. )
  1757. {
  1758. UINT i, szblk;
  1759. WORD sum;
  1760. szblk = ((UINT)dir[XDIR_NumSec] + 1) * SZDIRE; /* Number of bytes of the entry block */
  1761. for (i = sum = 0; i < szblk; i++) {
  1762. if (i == XDIR_SetSum) { /* Skip 2-byte sum field */
  1763. i++;
  1764. } else {
  1765. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + dir[i];
  1766. }
  1767. }
  1768. return sum;
  1769. }
  1770. static WORD xname_sum ( /* Get check sum (to be used as hash) of the file name */
  1771. const WCHAR* name /* File name to be calculated */
  1772. )
  1773. {
  1774. WCHAR chr;
  1775. WORD sum = 0;
  1776. while ((chr = *name++) != 0) {
  1777. chr = (WCHAR)ff_wtoupper(chr); /* File name needs to be up-case converted */
  1778. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr & 0xFF);
  1779. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr >> 8);
  1780. }
  1781. return sum;
  1782. }
  1783. #if !FF_FS_READONLY && FF_USE_MKFS
  1784. static DWORD xsum32 ( /* Returns 32-bit checksum */
  1785. BYTE dat, /* Byte to be calculated (byte-by-byte processing) */
  1786. DWORD sum /* Previous sum value */
  1787. )
  1788. {
  1789. sum = ((sum & 1) ? 0x80000000 : 0) + (sum >> 1) + dat;
  1790. return sum;
  1791. }
  1792. #endif
  1793. /*------------------------------------*/
  1794. /* exFAT: Get a directory entry block */
  1795. /*------------------------------------*/
  1796. static FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */
  1797. DIR* dp /* Reading directory object pointing top of the entry block to load */
  1798. )
  1799. {
  1800. FRESULT res;
  1801. UINT i, sz_ent;
  1802. BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory directory entry block 85+C0+C1s */
  1803. /* Load file-directory entry */
  1804. res = move_window(dp->obj.fs, dp->sect);
  1805. if (res != FR_OK) return res;
  1806. if (dp->dir[XDIR_Type] != ET_FILEDIR) return FR_INT_ERR; /* Invalid order? */
  1807. memcpy(dirb + 0 * SZDIRE, dp->dir, SZDIRE);
  1808. sz_ent = ((UINT)dirb[XDIR_NumSec] + 1) * SZDIRE; /* Size of this entry block */
  1809. if (sz_ent < 3 * SZDIRE || sz_ent > 19 * SZDIRE) return FR_INT_ERR; /* Invalid block size? */
  1810. /* Load stream extension entry */
  1811. res = dir_next(dp, 0);
  1812. if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */
  1813. if (res != FR_OK) return res;
  1814. res = move_window(dp->obj.fs, dp->sect);
  1815. if (res != FR_OK) return res;
  1816. if (dp->dir[XDIR_Type] != ET_STREAM) return FR_INT_ERR; /* Invalid order? */
  1817. memcpy(dirb + 1 * SZDIRE, dp->dir, SZDIRE);
  1818. if (MAXDIRB(dirb[XDIR_NumName]) > sz_ent) return FR_INT_ERR; /* Invalid block size for the name? */
  1819. /* Load file name entries */
  1820. i = 2 * SZDIRE; /* Name offset to load */
  1821. do {
  1822. res = dir_next(dp, 0);
  1823. if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */
  1824. if (res != FR_OK) return res;
  1825. res = move_window(dp->obj.fs, dp->sect);
  1826. if (res != FR_OK) return res;
  1827. if (dp->dir[XDIR_Type] != ET_FILENAME) return FR_INT_ERR; /* Invalid order? */
  1828. if (i < MAXDIRB(FF_MAX_LFN)) memcpy(dirb + i, dp->dir, SZDIRE); /* Load name entries only if the object is accessible */
  1829. } while ((i += SZDIRE) < sz_ent);
  1830. /* Sanity check (do it for only accessible object) */
  1831. if (i <= MAXDIRB(FF_MAX_LFN)) {
  1832. if (xdir_sum(dirb) != ld_16(dirb + XDIR_SetSum)) return FR_INT_ERR;
  1833. }
  1834. return FR_OK;
  1835. }
  1836. /*------------------------------------------------------------------*/
  1837. /* exFAT: Initialize object allocation info with loaded entry block */
  1838. /*------------------------------------------------------------------*/
  1839. static void init_alloc_info (
  1840. FFOBJID* dobj, /* Object allocation information to be initialized */
  1841. DIR* sdir /* Additional source about containing direcotry */
  1842. )
  1843. {
  1844. FATFS *fs = dobj->fs;
  1845. if (sdir) { /* Initialize the containing directory. This block needs to precede the followings. */
  1846. dobj->c_scl = sdir->obj.sclust;
  1847. dobj->c_size = ((DWORD)sdir->obj.objsize & 0xFFFFFF00) | sdir->obj.stat;
  1848. dobj->c_ofs = sdir->blk_ofs;
  1849. }
  1850. dobj->sclust = ld_32(fs->dirbuf + XDIR_FstClus); /* Start cluster */
  1851. dobj->objsize = ld_64(fs->dirbuf + XDIR_FileSize); /* Size */
  1852. dobj->stat = fs->dirbuf[XDIR_GenFlags] & 2; /* Allocation status */
  1853. dobj->n_frag = 0; /* No last fragment info */
  1854. }
  1855. #if !FF_FS_READONLY || FF_FS_RPATH
  1856. /*------------------------------------------------*/
  1857. /* exFAT: Load the object's directory entry block */
  1858. /*------------------------------------------------*/
  1859. static FRESULT load_obj_xdir (
  1860. DIR* dp, /* Blank directory object to be used to access containing directory */
  1861. const FFOBJID* obj /* Object with its containing directory information */
  1862. )
  1863. {
  1864. FRESULT res;
  1865. /* Open object containing directory */
  1866. dp->obj.fs = obj->fs;
  1867. dp->obj.sclust = obj->c_scl;
  1868. dp->obj.stat = (BYTE)obj->c_size;
  1869. dp->obj.objsize = obj->c_size & 0xFFFFFF00;
  1870. dp->obj.n_frag = 0;
  1871. dp->blk_ofs = obj->c_ofs;
  1872. res = dir_sdi(dp, dp->blk_ofs); /* Goto object's entry block */
  1873. if (res == FR_OK) {
  1874. res = load_xdir(dp); /* Load the object's entry block */
  1875. }
  1876. return res;
  1877. }
  1878. #endif
  1879. #if !FF_FS_READONLY
  1880. /*----------------------------------------*/
  1881. /* exFAT: Store the directory entry block */
  1882. /*----------------------------------------*/
  1883. static FRESULT store_xdir (
  1884. DIR* dp /* Pointer to the directory object */
  1885. )
  1886. {
  1887. FRESULT res;
  1888. UINT nent;
  1889. BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the entry set 85+C0+C1s */
  1890. st_16(dirb + XDIR_SetSum, xdir_sum(dirb)); /* Create check sum */
  1891. /* Store the entry set to the directory */
  1892. nent = dirb[XDIR_NumSec] + 1; /* Number of entries */
  1893. res = dir_sdi(dp, dp->blk_ofs); /* Top of the entry set */
  1894. while (res == FR_OK) {
  1895. /* Set an entry to the directory */
  1896. res = move_window(dp->obj.fs, dp->sect);
  1897. if (res != FR_OK) break;
  1898. memcpy(dp->dir, dirb, SZDIRE);
  1899. dp->obj.fs->wflag = 1;
  1900. if (--nent == 0) break; /* All done? */
  1901. dirb += SZDIRE;
  1902. res = dir_next(dp, 0); /* Next entry */
  1903. }
  1904. return (res == FR_OK || res == FR_DISK_ERR) ? res : FR_INT_ERR;
  1905. }
  1906. /*-------------------------------------------*/
  1907. /* exFAT: Create a new directory entry block */
  1908. /*-------------------------------------------*/
  1909. static void create_xdir (
  1910. BYTE* dirb, /* Pointer to the directory entry block buffer */
  1911. const WCHAR* lfn /* Pointer to the object name */
  1912. )
  1913. {
  1914. UINT i;
  1915. BYTE n_c1, nlen;
  1916. WCHAR chr;
  1917. /* Create file-directory and stream-extension entry (1st and 2nd entry) */
  1918. memset(dirb, 0, 2 * SZDIRE);
  1919. dirb[0 * SZDIRE + XDIR_Type] = ET_FILEDIR;
  1920. dirb[1 * SZDIRE + XDIR_Type] = ET_STREAM;
  1921. /* Create file name entries (3rd enrty and follows) */
  1922. i = SZDIRE * 2; /* Top of file name entries */
  1923. nlen = n_c1 = 0; chr = 1;
  1924. do {
  1925. dirb[i++] = ET_FILENAME; dirb[i++] = 0;
  1926. do { /* Fill name field */
  1927. if (chr != 0 && (chr = lfn[nlen]) != 0) nlen++; /* Get a character if exist */
  1928. st_16(dirb + i, chr); /* Store it */
  1929. i += 2;
  1930. } while (i % SZDIRE != 0);
  1931. n_c1++;
  1932. } while (lfn[nlen]); /* Fill next C1 entry if any char follows */
  1933. dirb[XDIR_NumName] = nlen; /* Set name length */
  1934. dirb[XDIR_NumSec] = 1 + n_c1; /* Set secondary count (C0 + C1s) */
  1935. st_16(dirb + XDIR_NameHash, xname_sum(lfn)); /* Set name hash */
  1936. }
  1937. #endif /* !FF_FS_READONLY */
  1938. #endif /* FF_FS_EXFAT */
  1939. #if FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 || FF_USE_LABEL || FF_FS_EXFAT
  1940. /*-----------------------------------------------------------------------*/
  1941. /* Read an object from the directory */
  1942. /*-----------------------------------------------------------------------*/
  1943. #define DIR_READ_FILE(dp) dir_read(dp, 0)
  1944. #define DIR_READ_LABEL(dp) dir_read(dp, 1)
  1945. static FRESULT dir_read (
  1946. DIR* dp, /* Pointer to the directory object */
  1947. int vol /* Filtered by 0:file/directory or 1:volume label */
  1948. )
  1949. {
  1950. FRESULT res = FR_NO_FILE;
  1951. FATFS *fs = dp->obj.fs;
  1952. BYTE attr, et;
  1953. #if FF_USE_LFN
  1954. BYTE ord = 0xFF, sum = 0xFF;
  1955. #endif
  1956. while (dp->sect) {
  1957. res = move_window(fs, dp->sect);
  1958. if (res != FR_OK) break;
  1959. et = dp->dir[DIR_Name]; /* Test for the entry type */
  1960. if (et == 0) {
  1961. res = FR_NO_FILE; break; /* Reached to end of the directory */
  1962. }
  1963. #if FF_FS_EXFAT
  1964. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1965. if (FF_USE_LABEL && vol) {
  1966. if (et == ET_VLABEL) break; /* Volume label entry? */
  1967. } else {
  1968. if (et == ET_FILEDIR) { /* Start of the file entry block? */
  1969. dp->blk_ofs = dp->dptr; /* Get location of the block */
  1970. res = load_xdir(dp); /* Load the entry block */
  1971. if (res == FR_OK) {
  1972. dp->obj.attr = fs->dirbuf[XDIR_Attr] & AM_MASK; /* Get attribute */
  1973. }
  1974. break;
  1975. }
  1976. }
  1977. } else
  1978. #endif
  1979. { /* On the FAT/FAT32 volume */
  1980. dp->obj.attr = attr = dp->dir[DIR_Attr] & AM_MASK; /* Get attribute */
  1981. #if FF_USE_LFN /* LFN configuration */
  1982. if (et == DDEM || et == '.' || (int)((attr & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */
  1983. ord = 0xFF;
  1984. } else {
  1985. if (attr == AM_LFN) { /* An LFN entry is found */
  1986. if (et & LLEF) { /* Is it start of an LFN sequence? */
  1987. sum = dp->dir[LDIR_Chksum];
  1988. et &= (BYTE)~LLEF; ord = et;
  1989. dp->blk_ofs = dp->dptr;
  1990. }
  1991. /* Check LFN validity and capture it */
  1992. ord = (et == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  1993. } else { /* An SFN entry is found */
  1994. if (ord != 0 || sum != sum_sfn(dp->dir)) { /* Is there a valid LFN? */
  1995. dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */
  1996. }
  1997. break;
  1998. }
  1999. }
  2000. #else /* Non LFN configuration */
  2001. if (et != DDEM && et != '.' && attr != AM_LFN && (int)((attr & ~AM_ARC) == AM_VOL) == vol) { /* Is it a valid entry? */
  2002. break;
  2003. }
  2004. #endif
  2005. }
  2006. res = dir_next(dp, 0); /* Next entry */
  2007. if (res != FR_OK) break;
  2008. }
  2009. if (res != FR_OK) dp->sect = 0; /* Terminate the read operation on error or EOT */
  2010. return res;
  2011. }
  2012. #endif /* FF_FS_MINIMIZE <= 1 || FF_USE_LABEL || FF_FS_RPATH >= 2 */
  2013. /*-----------------------------------------------------------------------*/
  2014. /* Directory handling - Find an object in the directory */
  2015. /*-----------------------------------------------------------------------*/
  2016. static FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */
  2017. DIR* dp /* Pointer to the directory object with the file name */
  2018. )
  2019. {
  2020. FRESULT res;
  2021. FATFS *fs = dp->obj.fs;
  2022. BYTE et;
  2023. #if FF_USE_LFN
  2024. BYTE attr, ord, sum;
  2025. #endif
  2026. res = dir_sdi(dp, 0); /* Rewind directory object */
  2027. if (res != FR_OK) return res;
  2028. #if FF_FS_EXFAT
  2029. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  2030. BYTE nc;
  2031. UINT di, ni;
  2032. WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */
  2033. while ((res = DIR_READ_FILE(dp)) == FR_OK) { /* Read an item */
  2034. #if FF_MAX_LFN < 255
  2035. if (fs->dirbuf[XDIR_NumName] > FF_MAX_LFN) continue; /* Skip comparison if inaccessible object name */
  2036. #endif
  2037. if (ld_16(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip comparison if hash mismatched */
  2038. for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */
  2039. if ((di % SZDIRE) == 0) di += 2;
  2040. if (ff_wtoupper(ld_16(fs->dirbuf + di)) != ff_wtoupper(fs->lfnbuf[ni])) break;
  2041. }
  2042. if (nc == 0 && !fs->lfnbuf[ni]) break; /* Name matched? */
  2043. }
  2044. return res;
  2045. }
  2046. #endif
  2047. /* On the FAT/FAT32 volume */
  2048. #if FF_USE_LFN
  2049. ord = sum = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  2050. #endif
  2051. do {
  2052. res = move_window(fs, dp->sect);
  2053. if (res != FR_OK) break;
  2054. et = dp->dir[DIR_Name]; /* Entry type */
  2055. if (et == 0) { res = FR_NO_FILE; break; } /* Reached end of directory table */
  2056. #if FF_USE_LFN /* LFN configuration */
  2057. dp->obj.attr = attr = dp->dir[DIR_Attr] & AM_MASK;
  2058. if (et == DDEM || ((attr & AM_VOL) && attr != AM_LFN)) { /* An entry without valid data */
  2059. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  2060. } else {
  2061. if (attr == AM_LFN) { /* Is it an LFN entry? */
  2062. if (!(dp->fn[NSFLAG] & NS_NOLFN)) {
  2063. if (et & LLEF) { /* Is it start of an entry set? */
  2064. et &= (BYTE)~LLEF;
  2065. ord = et; /* Number of LFN entries */
  2066. dp->blk_ofs = dp->dptr; /* Start offset of LFN */
  2067. sum = dp->dir[LDIR_Chksum]; /* Sum of the SFN */
  2068. }
  2069. /* Check validity of the LFN entry and compare it with given name */
  2070. ord = (et == ord && sum == dp->dir[LDIR_Chksum] && cmp_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  2071. }
  2072. } else { /* SFN entry */
  2073. if (ord == 0 && sum == sum_sfn(dp->dir)) break; /* LFN matched? */
  2074. if (!(dp->fn[NSFLAG] & NS_LOSS) && !memcmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */
  2075. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Not matched, reset LFN sequence */
  2076. }
  2077. }
  2078. #else /* Non LFN configuration */
  2079. dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK;
  2080. if (!(dp->dir[DIR_Attr] & AM_VOL) && !memcmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */
  2081. #endif
  2082. res = dir_next(dp, 0); /* Next entry */
  2083. } while (res == FR_OK);
  2084. return res;
  2085. }
  2086. #if !FF_FS_READONLY
  2087. /*-----------------------------------------------------------------------*/
  2088. /* Register an object to the directory */
  2089. /*-----------------------------------------------------------------------*/
  2090. static FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */
  2091. DIR* dp /* Target directory with object name to be created */
  2092. )
  2093. {
  2094. FRESULT res;
  2095. FATFS *fs = dp->obj.fs;
  2096. #if FF_USE_LFN /* LFN configuration */
  2097. UINT n, len, n_ent;
  2098. BYTE sn[12];
  2099. if (dp->fn[NSFLAG] & (NS_DOT | NS_NONAME)) return FR_INVALID_NAME; /* Check name validity */
  2100. for (len = 0; fs->lfnbuf[len]; len++) ; /* Get lfn length */
  2101. #if FF_FS_EXFAT
  2102. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  2103. n_ent = (len + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */
  2104. res = dir_alloc(dp, n_ent); /* Allocate directory entries */
  2105. if (res != FR_OK) return res;
  2106. dp->blk_ofs = dp->dptr - SZDIRE * (n_ent - 1); /* Set the allocated entry block offset */
  2107. if (dp->obj.stat & 4) { /* Has the directory been stretched by new allocation? */
  2108. dp->obj.stat &= ~4;
  2109. res = fill_first_frag(&dp->obj); /* Fill the first fragment on the FAT if needed */
  2110. if (res != FR_OK) return res;
  2111. res = fill_last_frag(&dp->obj, dp->clust, 0xFFFFFFFF); /* Fill the last fragment on the FAT if needed */
  2112. if (res != FR_OK) return res;
  2113. if (dp->obj.sclust != 0) { /* Is it a sub-directory? */
  2114. DIR dj;
  2115. res = load_obj_xdir(&dj, &dp->obj); /* Load the object status */
  2116. if (res != FR_OK) return res;
  2117. dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase the directory size by cluster size */
  2118. st_64(fs->dirbuf + XDIR_FileSize, dp->obj.objsize);
  2119. st_64(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize);
  2120. fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1; /* Update the allocation status */
  2121. res = store_xdir(&dj); /* Store the object status */
  2122. if (res != FR_OK) return res;
  2123. #if FF_FS_RPATH /* Refrect changes to the current dir chain if the stretched dir is in it */
  2124. for (n = 1; n <= fs->xcwds.depth && dp->obj.sclust != fs->xcwds.tbl[n].d_scl; n++) ; /* Check if the dir is in the current dir path */
  2125. if (n <= fs->xcwds.depth) { /* If exist, update it */
  2126. fs->xcwds.tbl[n].d_size = (DWORD)dp->obj.objsize | dp->obj.stat;
  2127. }
  2128. #endif
  2129. }
  2130. }
  2131. create_xdir(fs->dirbuf, fs->lfnbuf); /* Create on-memory directory block to be written later */
  2132. return FR_OK;
  2133. }
  2134. #endif
  2135. /* On the FAT/FAT32 volume */
  2136. memcpy(sn, dp->fn, 12);
  2137. if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
  2138. dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */
  2139. for (n = 1; n < 100; n++) {
  2140. gen_numname(dp->fn, sn, fs->lfnbuf, (WORD)n); /* Generate a numbered name */
  2141. res = dir_find(dp); /* Check if the name collides with existing SFN */
  2142. if (res != FR_OK) break;
  2143. }
  2144. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  2145. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  2146. dp->fn[NSFLAG] = sn[NSFLAG];
  2147. }
  2148. /* Create an SFN with/without LFNs. */
  2149. n_ent = (sn[NSFLAG] & NS_LFN) ? (len + 12) / 13 + 1 : 1; /* Number of entries to allocate */
  2150. res = dir_alloc(dp, n_ent); /* Allocate entries */
  2151. if (res == FR_OK && --n_ent) { /* Set LFN entry if needed */
  2152. res = dir_sdi(dp, dp->dptr - n_ent * SZDIRE);
  2153. if (res == FR_OK) {
  2154. BYTE sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */
  2155. do { /* Store LFN entries in bottom first */
  2156. res = move_window(fs, dp->sect);
  2157. if (res != FR_OK) break;
  2158. put_lfn(fs->lfnbuf, dp->dir, (BYTE)n_ent, sum);
  2159. fs->wflag = 1;
  2160. res = dir_next(dp, 0); /* Next entry */
  2161. } while (res == FR_OK && --n_ent);
  2162. }
  2163. }
  2164. #else /* Non LFN configuration */
  2165. res = dir_alloc(dp, 1); /* Allocate an entry for SFN */
  2166. #endif
  2167. /* Set SFN entry */
  2168. if (res == FR_OK) {
  2169. res = move_window(fs, dp->sect);
  2170. if (res == FR_OK) {
  2171. memset(dp->dir, 0, SZDIRE); /* Clean the entry */
  2172. memcpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */
  2173. #if FF_USE_LFN
  2174. dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put low-case flags */
  2175. #endif
  2176. fs->wflag = 1;
  2177. }
  2178. }
  2179. return res;
  2180. }
  2181. #endif /* !FF_FS_READONLY */
  2182. #if !FF_FS_READONLY && FF_FS_MINIMIZE == 0
  2183. /*-----------------------------------------------------------------------*/
  2184. /* Remove an object from the directory */
  2185. /*-----------------------------------------------------------------------*/
  2186. static FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
  2187. DIR* dp /* Directory object pointing the entry to be removed */
  2188. )
  2189. {
  2190. FRESULT res;
  2191. FATFS *fs = dp->obj.fs;
  2192. #if FF_USE_LFN /* LFN configuration */
  2193. DWORD last = dp->dptr;
  2194. res = (dp->blk_ofs == 0xFFFFFFFF) ? FR_OK : dir_sdi(dp, dp->blk_ofs); /* Goto top of the entry block if LFN is exist */
  2195. if (res == FR_OK) {
  2196. do {
  2197. res = move_window(fs, dp->sect);
  2198. if (res != FR_OK) break;
  2199. if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  2200. dp->dir[XDIR_Type] &= 0x7F; /* Clear the entry InUse flag. */
  2201. } else { /* On the FAT/FAT32 volume */
  2202. dp->dir[DIR_Name] = DDEM; /* Mark the entry 'deleted'. */
  2203. }
  2204. fs->wflag = 1;
  2205. if (dp->dptr >= last) break; /* If reached last entry then all entries of the object has been deleted. */
  2206. res = dir_next(dp, 0); /* Next entry */
  2207. } while (res == FR_OK);
  2208. if (res == FR_NO_FILE) res = FR_INT_ERR;
  2209. }
  2210. #else /* Non LFN configuration */
  2211. res = move_window(fs, dp->sect);
  2212. if (res == FR_OK) {
  2213. dp->dir[DIR_Name] = DDEM; /* Mark the entry 'deleted'.*/
  2214. fs->wflag = 1;
  2215. }
  2216. #endif
  2217. return res;
  2218. }
  2219. #endif /* !FF_FS_READONLY && FF_FS_MINIMIZE == 0 */
  2220. #if FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2
  2221. /*-----------------------------------------------------------------------*/
  2222. /* Get file information from directory entry */
  2223. /*-----------------------------------------------------------------------*/
  2224. static void get_fileinfo (
  2225. DIR* dp, /* Pointer to the directory object */
  2226. FILINFO* fno /* Pointer to the file information to be filled */
  2227. )
  2228. {
  2229. UINT si, di;
  2230. #if FF_USE_LFN
  2231. WCHAR wc, hs;
  2232. FATFS *fs = dp->obj.fs;
  2233. UINT nw;
  2234. #else
  2235. TCHAR c;
  2236. #endif
  2237. fno->fname[0] = 0;
  2238. if (dp->sect == 0) return; /* Exit if read pointer has reached end of directory */
  2239. #if FF_USE_LFN /* LFN configuration */
  2240. #if FF_FS_EXFAT
  2241. if (fs->fs_type == FS_EXFAT) { /* exFAT volume */
  2242. UINT nc = 0;
  2243. si = SZDIRE * 2; di = 0; /* 1st C1 entry in the entry block */
  2244. hs = 0;
  2245. while (nc < fs->dirbuf[XDIR_NumName]) {
  2246. if (si >= MAXDIRB(FF_MAX_LFN)) { /* Truncated directory block? */
  2247. di = 0; break;
  2248. }
  2249. if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
  2250. wc = ld_16(fs->dirbuf + si); si += 2; nc++; /* Get a character */
  2251. if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */
  2252. hs = wc; continue; /* Get low surrogate */
  2253. }
  2254. nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */
  2255. if (nw == 0) { /* Buffer overflow or wrong char? */
  2256. di = 0; break;
  2257. }
  2258. di += nw;
  2259. hs = 0;
  2260. }
  2261. if (hs != 0) di = 0; /* Broken surrogate pair? */
  2262. if (di == 0) fno->fname[di++] = '\?'; /* Inaccessible object name? */
  2263. fno->fname[di] = 0; /* Terminate the name */
  2264. fno->altname[0] = 0; /* exFAT does not support SFN */
  2265. fno->fattrib = fs->dirbuf[XDIR_Attr] & AM_MASKX; /* Attribute */
  2266. fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_64(fs->dirbuf + XDIR_FileSize); /* Size */
  2267. fno->ftime = ld_16(fs->dirbuf + XDIR_ModTime + 0); /* Last modified time */
  2268. fno->fdate = ld_16(fs->dirbuf + XDIR_ModTime + 2); /* Last modified date */
  2269. #if FF_FS_CRTIME
  2270. fno->crtime = ld_16(fs->dirbuf + XDIR_CrtTime + 0); /* Created time */
  2271. fno->crdate = ld_16(fs->dirbuf + XDIR_CrtTime + 2); /* Created date */
  2272. #endif
  2273. return;
  2274. } else
  2275. #endif
  2276. { /* FAT/FAT32 volume */
  2277. if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */
  2278. si = di = 0;
  2279. hs = 0;
  2280. while (fs->lfnbuf[si] != 0) {
  2281. wc = fs->lfnbuf[si++]; /* Get an LFN character (UTF-16) */
  2282. if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */
  2283. hs = wc; continue; /* Get low surrogate */
  2284. }
  2285. nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */
  2286. if (nw == 0) { /* Buffer overflow or wrong char? */
  2287. di = 0; break;
  2288. }
  2289. di += nw;
  2290. hs = 0;
  2291. }
  2292. if (hs != 0) di = 0; /* Broken surrogate pair? */
  2293. fno->fname[di] = 0; /* Terminate the LFN (null string means LFN is invalid) */
  2294. }
  2295. }
  2296. si = di = 0;
  2297. while (si < 11) { /* Get SFN from SFN entry */
  2298. wc = dp->dir[si++]; /* Get a char */
  2299. if (wc == ' ') continue; /* Skip padding spaces */
  2300. if (wc == RDDEM) wc = DDEM; /* Restore replaced DDEM character */
  2301. if (si == 9 && di < FF_SFN_BUF) fno->altname[di++] = '.'; /* Insert a . if extension is exist */
  2302. #if FF_LFN_UNICODE >= 1 /* Unicode output */
  2303. if (dbc_1st((BYTE)wc) && si != 8 && si != 11 && dbc_2nd(dp->dir[si])) { /* Make a DBC if needed */
  2304. wc = wc << 8 | dp->dir[si++];
  2305. }
  2306. wc = ff_oem2uni(wc, CODEPAGE); /* ANSI/OEM -> Unicode */
  2307. if (wc == 0) { /* Wrong char in the current code page? */
  2308. di = 0; break;
  2309. }
  2310. nw = put_utf(wc, &fno->altname[di], FF_SFN_BUF - di); /* Store it in API encoding */
  2311. if (nw == 0) { /* Buffer overflow? */
  2312. di = 0; break;
  2313. }
  2314. di += nw;
  2315. #else /* ANSI/OEM output */
  2316. fno->altname[di++] = (TCHAR)wc; /* Store it without any conversion */
  2317. #endif
  2318. }
  2319. fno->altname[di] = 0; /* Terminate the SFN (null string means SFN is invalid) */
  2320. if (!fno->fname[0]) { /* If LFN is invalid, altname[] needs to be copied to fname[] */
  2321. if (di == 0) { /* If LFN and SFN both are invalid, */
  2322. fno->fname[di++] = '\?'; /* This object is inaccessible due to wrong buffer or locale settings */
  2323. } else {
  2324. BYTE lcflg = NS_BODY;
  2325. for (si = di = 0; fno->altname[si]; si++, di++) { /* Copy altname[] to fname[] with case information */
  2326. wc = (WCHAR)fno->altname[si];
  2327. if (wc == '.') lcflg = NS_EXT;
  2328. if (IsUpper(wc) && (dp->dir[DIR_NTres] & lcflg)) wc += 0x20;
  2329. fno->fname[di] = (TCHAR)wc;
  2330. }
  2331. }
  2332. fno->fname[di] = 0; /* Terminate the LFN */
  2333. if (!dp->dir[DIR_NTres]) fno->altname[0] = 0; /* Altname is not needed if neither LFN nor case info is exist. */
  2334. }
  2335. #else /* Non-LFN configuration */
  2336. si = di = 0;
  2337. while (si < 11) { /* Copy name body and extension */
  2338. c = (TCHAR)dp->dir[si++];
  2339. if (c == ' ') continue; /* Skip padding spaces */
  2340. if (c == RDDEM) c = DDEM; /* Restore replaced DDEM character */
  2341. if (si == 9) fno->fname[di++] = '.';/* Insert a . if extension is exist */
  2342. fno->fname[di++] = c;
  2343. }
  2344. fno->fname[di] = 0; /* Terminate the SFN */
  2345. #endif
  2346. fno->fattrib = dp->dir[DIR_Attr] & AM_MASK; /* Attribute */
  2347. fno->fsize = ld_32(dp->dir + DIR_FileSize); /* Size */
  2348. fno->ftime = ld_16(dp->dir + DIR_ModTime + 0); /* Last modified time */
  2349. fno->fdate = ld_16(dp->dir + DIR_ModTime + 2); /* Last Modified date */
  2350. #if FF_FS_CRTIME
  2351. fno->crtime = ld_16(dp->dir + DIR_CrtTime + 0); /* Created time */
  2352. fno->crdate = ld_16(dp->dir + DIR_CrtTime + 2); /* Created date */
  2353. #endif
  2354. }
  2355. #endif /* FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 */
  2356. #if FF_USE_FIND && FF_FS_MINIMIZE <= 1
  2357. /*-----------------------------------------------------------------------*/
  2358. /* Pattern matching */
  2359. /*-----------------------------------------------------------------------*/
  2360. #define FIND_RECURS 4 /* Maximum number of wildcard terms in the pattern to limit recursion */
  2361. static DWORD get_achar ( /* Get a character and advance ptr */
  2362. const TCHAR** ptr /* Pointer to pointer to the ANSI/OEM or Unicode string */
  2363. )
  2364. {
  2365. DWORD chr;
  2366. #if FF_USE_LFN && FF_LFN_UNICODE >= 1 /* Unicode input */
  2367. chr = tchar2uni(ptr);
  2368. if (chr == 0xFFFFFFFF) chr = 0; /* Wrong UTF encoding is recognized as end of the string */
  2369. chr = ff_wtoupper(chr);
  2370. #else /* ANSI/OEM input */
  2371. chr = (BYTE)*(*ptr)++; /* Get a byte */
  2372. if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */
  2373. #if FF_CODE_PAGE == 0
  2374. if (ExCvt && chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper (SBCS extended char) */
  2375. #elif FF_CODE_PAGE < 900
  2376. if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper (SBCS extended char) */
  2377. #endif
  2378. #if FF_CODE_PAGE == 0 || FF_CODE_PAGE >= 900
  2379. if (dbc_1st((BYTE)chr)) { /* Get DBC 2nd byte if needed */
  2380. chr = dbc_2nd((BYTE)**ptr) ? chr << 8 | (BYTE)*(*ptr)++ : 0;
  2381. }
  2382. #endif
  2383. #endif
  2384. return chr;
  2385. }
  2386. static int pattern_match ( /* 0:mismatched, 1:matched */
  2387. const TCHAR* pat, /* Matching pattern */
  2388. const TCHAR* nam, /* String to be tested */
  2389. UINT skip, /* Number of pre-skip chars (number of ?s, b8:infinite (* specified)) */
  2390. UINT recur /* Recursion count */
  2391. )
  2392. {
  2393. const TCHAR *pptr;
  2394. const TCHAR *nptr;
  2395. DWORD pchr, nchr;
  2396. UINT sk;
  2397. while ((skip & 0xFF) != 0) { /* Pre-skip name chars */
  2398. if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */
  2399. skip--;
  2400. }
  2401. if (*pat == 0 && skip) return 1; /* Matched? (short circuit) */
  2402. do {
  2403. pptr = pat; nptr = nam; /* Top of pattern and name to match */
  2404. for (;;) {
  2405. if (*pptr == '\?' || *pptr == '*') { /* Wildcard term? */
  2406. if (recur == 0) return 0; /* Too many wildcard terms? */
  2407. sk = 0;
  2408. do { /* Analyze the wildcard term */
  2409. if (*pptr++ == '\?') {
  2410. sk++;
  2411. } else {
  2412. sk |= 0x100;
  2413. }
  2414. } while (*pptr == '\?' || *pptr == '*');
  2415. if (pattern_match(pptr, nptr, sk, recur - 1)) return 1; /* Test new branch (recursive call) */
  2416. nchr = *nptr; break; /* Branch mismatched */
  2417. }
  2418. pchr = get_achar(&pptr); /* Get a pattern char */
  2419. nchr = get_achar(&nptr); /* Get a name char */
  2420. if (pchr != nchr) break; /* Branch mismatched? */
  2421. if (pchr == 0) return 1; /* Branch matched? (matched at end of both strings) */
  2422. }
  2423. get_achar(&nam); /* nam++ */
  2424. } while (skip && nchr); /* Retry until end of name if infinite search is specified */
  2425. return 0;
  2426. }
  2427. #endif /* FF_USE_FIND && FF_FS_MINIMIZE <= 1 */
  2428. /*-----------------------------------------------------------------------*/
  2429. /* Pick a top segment and create the object name in directory form */
  2430. /*-----------------------------------------------------------------------*/
  2431. static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */
  2432. DIR* dp, /* Pointer to the directory object */
  2433. const TCHAR** path /* Pointer to pointer to the segment in the path string */
  2434. )
  2435. {
  2436. #if FF_USE_LFN /* LFN configuration */
  2437. BYTE b, cf;
  2438. WCHAR wc;
  2439. WCHAR *lfn;
  2440. const TCHAR* p;
  2441. DWORD uc;
  2442. UINT i, ni, si, di;
  2443. /* Create an LFN into LFN working buffer */
  2444. p = *path; lfn = dp->obj.fs->lfnbuf; di = 0;
  2445. for (;;) {
  2446. uc = tchar2uni(&p); /* Get a character */
  2447. if (uc == 0xFFFFFFFF) return FR_INVALID_NAME; /* Invalid code or UTF decode error */
  2448. if (uc >= 0x10000) lfn[di++] = (WCHAR)(uc >> 16); /* Store high surrogate if needed */
  2449. wc = (WCHAR)uc;
  2450. if (wc < ' ' || IsSeparator(wc)) break; /* Break if end of the path or a separator is found */
  2451. if (wc < 0x80 && strchr("*:<>|\"\?\x7F", (int)wc)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */
  2452. if (di >= FF_MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */
  2453. lfn[di++] = wc; /* Store the Unicode character */
  2454. }
  2455. if (wc < ' ') { /* Stopped at end of the path? */
  2456. cf = NS_LAST; /* Last segment */
  2457. } else { /* Stopped at a separator */
  2458. while (IsSeparator(*p)) p++; /* Skip duplicated separators if exist */
  2459. cf = 0; /* Next segment may follow */
  2460. if (IsTerminator(*p)) cf = NS_LAST; /* Ignore terminating separator */
  2461. }
  2462. *path = p; /* Return pointer to the next segment */
  2463. #if FF_FS_RPATH
  2464. if ((di == 1 && lfn[di - 1] == '.') ||
  2465. (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */
  2466. lfn[di] = 0;
  2467. for (i = 0; i < 11; i++) { /* Create dot name for SFN entry */
  2468. dp->fn[i] = (i < di) ? '.' : ' ';
  2469. }
  2470. dp->fn[i] = cf | NS_DOT; /* This is a dot entry */
  2471. return FR_OK;
  2472. }
  2473. #endif
  2474. while (di) { /* Snip off trailing spaces and dots if exist */
  2475. wc = lfn[di - 1];
  2476. if (wc != ' ' && wc != '.') break;
  2477. di--;
  2478. }
  2479. lfn[di] = 0; /* LFN is created into the working buffer */
  2480. if (di == 0) return FR_INVALID_NAME; /* Reject null name */
  2481. /* Create SFN in directory form */
  2482. for (si = 0; lfn[si] == ' '; si++) ; /* Remove leading spaces */
  2483. if (si > 0 || lfn[si] == '.') cf |= NS_LOSS | NS_LFN; /* Is there any leading space or dot? */
  2484. while (di > 0 && lfn[di - 1] != '.') di--; /* Find last dot (di<=si: no extension) */
  2485. memset(dp->fn, ' ', 11);
  2486. i = b = 0; ni = 8;
  2487. for (;;) {
  2488. wc = lfn[si++]; /* Get an LFN character */
  2489. if (wc == 0) break; /* Break on end of the LFN */
  2490. if (wc == ' ' || (wc == '.' && si != di)) { /* Remove embedded spaces and dots */
  2491. cf |= NS_LOSS | NS_LFN;
  2492. continue;
  2493. }
  2494. if (i >= ni || si == di) { /* End of field? */
  2495. if (ni == 11) { /* Name extension overflow? */
  2496. cf |= NS_LOSS | NS_LFN;
  2497. break;
  2498. }
  2499. if (si != di) cf |= NS_LOSS | NS_LFN; /* Name body overflow? */
  2500. if (si > di) break; /* No name extension? */
  2501. si = di; i = 8; ni = 11; b <<= 2; /* Enter name extension */
  2502. continue;
  2503. }
  2504. if (wc >= 0x80) { /* Is this an extended character? */
  2505. cf |= NS_LFN; /* LFN entry needs to be created */
  2506. #if FF_CODE_PAGE == 0
  2507. if (ExCvt) { /* In SBCS cfg */
  2508. wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */
  2509. if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */
  2510. } else { /* In DBCS cfg */
  2511. wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */
  2512. }
  2513. #elif FF_CODE_PAGE < 900 /* In SBCS cfg */
  2514. wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */
  2515. if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */
  2516. #else /* In DBCS cfg */
  2517. wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */
  2518. #endif
  2519. }
  2520. if (wc >= 0x100) { /* Is this a DBC? */
  2521. if (i >= ni - 1) { /* Field overflow? */
  2522. cf |= NS_LOSS | NS_LFN;
  2523. i = ni; continue; /* Next field */
  2524. }
  2525. dp->fn[i++] = (BYTE)(wc >> 8); /* Put 1st byte */
  2526. } else { /* SBC */
  2527. if (wc == 0 || strchr("+,;=[]", (int)wc)) { /* Replace illegal characters for SFN */
  2528. wc = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  2529. } else {
  2530. if (IsUpper(wc)) { /* ASCII upper case? */
  2531. b |= 2;
  2532. }
  2533. if (IsLower(wc)) { /* ASCII lower case? */
  2534. b |= 1; wc -= 0x20;
  2535. }
  2536. }
  2537. }
  2538. dp->fn[i++] = (BYTE)wc;
  2539. }
  2540. if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2541. if (ni == 8) b <<= 2; /* Shift capital flags if no extension */
  2542. if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) cf |= NS_LFN; /* LFN entry needs to be created if composite capitals */
  2543. if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
  2544. if (b & 0x01) cf |= NS_EXT; /* NT flag (Extension has small capital letters only) */
  2545. if (b & 0x04) cf |= NS_BODY; /* NT flag (Body has small capital letters only) */
  2546. }
  2547. dp->fn[NSFLAG] = cf; /* SFN is created into dp->fn[] */
  2548. return FR_OK;
  2549. #else /* FF_USE_LFN : Non-LFN configuration */
  2550. BYTE c, d;
  2551. BYTE *sfn;
  2552. UINT ni, si, i;
  2553. const char *p;
  2554. /* Create file name in directory form */
  2555. p = *path; sfn = dp->fn;
  2556. memset(sfn, ' ', 11);
  2557. si = i = 0; ni = 8;
  2558. #if FF_FS_RPATH
  2559. if (p[si] == '.') { /* Is this a dot entry? */
  2560. for (;;) { /* Copy one or two dots */
  2561. c = (BYTE)p[si++];
  2562. if (c != '.' || si >= 3) break;
  2563. sfn[i++] = c;
  2564. }
  2565. if (IsSeparator(c)) {
  2566. while (IsSeparator(p[si])) si++; /* Skip duplicated separators */
  2567. if ((BYTE)p[si] <= ' ') c = 0; /* Terminate if no segment follows */
  2568. } else if (c > ' ') { /* Not in dot name */
  2569. return FR_INVALID_NAME;
  2570. }
  2571. *path = p + si; /* Return pointer to the next segment */
  2572. sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */
  2573. return FR_OK;
  2574. }
  2575. #endif
  2576. for (;;) {
  2577. c = (BYTE)p[si++]; /* Get a byte */
  2578. if (c <= ' ') break; /* Break if end of the path name */
  2579. if (IsSeparator(c)) { /* Break if a separator is found */
  2580. while (IsSeparator(p[si])) si++; /* Skip duplicated separators */
  2581. break;
  2582. }
  2583. if (c == '.' || i >= ni) { /* End of body or field overflow? */
  2584. if (ni == 11 || c != '.') return FR_INVALID_NAME; /* Field overflow or invalid dot? */
  2585. i = 8; ni = 11; /* Enter file extension field */
  2586. continue;
  2587. }
  2588. #if FF_CODE_PAGE == 0
  2589. if (ExCvt && c >= 0x80) { /* Is SBC extended character? */
  2590. c = ExCvt[c & 0x7F]; /* To upper SBC extended character */
  2591. }
  2592. #elif FF_CODE_PAGE < 900
  2593. if (c >= 0x80) { /* Is SBC extended character? */
  2594. c = ExCvt[c & 0x7F]; /* To upper SBC extended character */
  2595. }
  2596. #endif
  2597. if (dbc_1st(c)) { /* Check if it is a DBC 1st byte */
  2598. d = (BYTE)p[si++]; /* Get 2nd byte */
  2599. if (!dbc_2nd(d) || i >= ni - 1) return FR_INVALID_NAME; /* Reject invalid DBC */
  2600. sfn[i++] = c;
  2601. sfn[i++] = d;
  2602. } else { /* SBC */
  2603. if (strchr("*+,:;<=>[]|\"\?\x7F", (int)c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */
  2604. if (IsLower(c)) c -= 0x20; /* To upper */
  2605. sfn[i++] = c;
  2606. }
  2607. }
  2608. *path = &p[si]; /* Return pointer to the next segment */
  2609. if (i == 0) return FR_INVALID_NAME; /* Reject nul string */
  2610. if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2611. sfn[NSFLAG] = (c <= ' ' || p[si] <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
  2612. return FR_OK;
  2613. #endif /* FF_USE_LFN */
  2614. }
  2615. /*-----------------------------------------------------------------------*/
  2616. /* Follow a file path */
  2617. /*-----------------------------------------------------------------------*/
  2618. static FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  2619. DIR* dp, /* Directory object to return last directory and found object */
  2620. const TCHAR* path /* Full-path string to find a file or directory */
  2621. )
  2622. {
  2623. FRESULT res;
  2624. BYTE ns;
  2625. FATFS *fs = dp->obj.fs;
  2626. /* Determins the start directory (current directory or forced root directory) */
  2627. #if FF_FS_RPATH
  2628. if (!IsSeparator(*path) && (FF_STR_VOLUME_ID != 2 || !IsTerminator(*path))) { /* Without heading separator */
  2629. dp->obj.sclust = fs->cdir; /* Start at the current directory */
  2630. } else
  2631. #endif
  2632. { /* With heading separator */
  2633. while (IsSeparator(*path)) path++; /* Strip heading separators */
  2634. dp->obj.sclust = 0; /* Start at the root directory */
  2635. }
  2636. #if FF_FS_EXFAT
  2637. dp->obj.n_frag = 0; /* Invalidate last fragment counter of the object */
  2638. #if FF_FS_RPATH
  2639. if (fs->fs_type == FS_EXFAT) { /* exFAT: Retrieve the start-directory's status */
  2640. if (dp->obj.sclust) { /* Start directory is a sub-directory */
  2641. /* Load the current directory chain into working buffer and initialize directory object as current dir */
  2642. memcpy(&fs->xcwds2, &fs->xcwds, sizeof fs->xcwds2);
  2643. dp->obj.stat = (BYTE)fs->xcwds2.tbl[fs->xcwds2.depth].d_size;
  2644. dp->obj.objsize = fs->xcwds2.tbl[fs->xcwds2.depth].d_size & 0xFFFFFF00;
  2645. dp->obj.c_scl = fs->xcwds2.tbl[fs->xcwds2.depth - 1].d_scl;
  2646. dp->obj.c_size = fs->xcwds2.tbl[fs->xcwds2.depth - 1].d_size & 0xFFFFFF00;
  2647. dp->obj.c_ofs = fs->xcwds2.tbl[fs->xcwds2.depth - 1].nxt_ofs;
  2648. } else { /* Start directory is the root directory */
  2649. /* Clear the directory path working buffer as root directory */
  2650. memset(&fs->xcwds2, 0, sizeof fs->xcwds2);
  2651. }
  2652. }
  2653. #endif
  2654. #endif
  2655. if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */
  2656. dp->fn[NSFLAG] = NS_NONAME;
  2657. res = dir_sdi(dp, 0);
  2658. } else { /* Follow path */
  2659. for (;;) {
  2660. res = create_name(dp, &path); /* Get a segment name of the path */
  2661. if (res != FR_OK) break;
  2662. ns = dp->fn[NSFLAG];
  2663. #if FF_FS_EXFAT && FF_FS_RPATH
  2664. if (fs->fs_type == FS_EXFAT && (ns & NS_DOT)) { /* Is it a dot name? */
  2665. /* There is no dot entry in exFAT volume, so it needs to follow the parent directory with recorded path */
  2666. if (fs->lfnbuf[1] == '.' && fs->xcwds2.depth) { /* ".." in the sub-dir? */
  2667. fs->xcwds2.depth--; /* Get into the parent directory and load the directory info */
  2668. dp->obj.sclust = fs->xcwds2.tbl[fs->xcwds2.depth].d_scl;
  2669. dp->obj.stat = (BYTE)fs->xcwds2.tbl[fs->xcwds2.depth].d_size;
  2670. dp->obj.objsize = fs->xcwds2.tbl[fs->xcwds2.depth].d_size & 0xFFFFFF00;
  2671. if (fs->xcwds2.depth) { /* Load containing dir info if needed */
  2672. dp->obj.c_scl = fs->xcwds2.tbl[fs->xcwds2.depth - 1].d_scl;
  2673. dp->obj.c_size = fs->xcwds2.tbl[fs->xcwds2.depth - 1].d_size;
  2674. dp->obj.c_ofs = fs->xcwds2.tbl[fs->xcwds2.depth - 1].nxt_ofs;
  2675. }
  2676. }
  2677. dp->obj.attr |= AM_DIR; /* This is a directory */
  2678. dp->fn[NSFLAG] |= NS_NONAME; /* but dot names in exFAT volume are not directory entry */
  2679. if (ns & NS_LAST) break; /* Last segment? */
  2680. continue; /* Follow next segment */
  2681. }
  2682. #endif
  2683. res = dir_find(dp); /* Find an object with the segment name */
  2684. if (res != FR_OK) { /* Failed to find the object */
  2685. if (res == FR_NO_FILE) { /* Object is not found */
  2686. if (FF_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, stay there (may be root dir in FAT volume) */
  2687. if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */
  2688. dp->fn[NSFLAG] = NS_NONAME;
  2689. res = FR_OK;
  2690. } else { /* Could not find the object */
  2691. if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */
  2692. }
  2693. }
  2694. break;
  2695. }
  2696. #if FF_FS_EXFAT && FF_FS_RPATH
  2697. if (fs->fs_type == FS_EXFAT && (dp->obj.attr & AM_DIR)) { /* Record the path if it is a sub-directory */
  2698. fs->xcwds2.tbl[fs->xcwds2.depth].nxt_ofs = dp->blk_ofs;
  2699. if (++fs->xcwds2.depth >= sizeof fs->xcwds2.tbl / sizeof fs->xcwds2.tbl[0]) { /* Is it too deep path? */
  2700. res = FR_NOT_ENOUGH_CORE; break;
  2701. }
  2702. fs->xcwds2.tbl[fs->xcwds2.depth].d_scl = ld_32(fs->dirbuf + XDIR_FstClus);
  2703. fs->xcwds2.tbl[fs->xcwds2.depth].d_size = ld_32(fs->dirbuf + XDIR_FileSize) | (fs->dirbuf[XDIR_GenFlags] & 2);
  2704. }
  2705. #endif
  2706. if (ns & NS_LAST) break; /* If last segment matched, the function completed */
  2707. /* Get into the sub-directory */
  2708. if (!(dp->obj.attr & AM_DIR)) {
  2709. res = FR_NO_PATH; break; /* It is not a sub-directory and cannot follow the path */
  2710. }
  2711. #if FF_FS_EXFAT
  2712. if (fs->fs_type == FS_EXFAT) {
  2713. init_alloc_info(&dp->obj, dp); /* Open next directory */
  2714. } else
  2715. #endif
  2716. {
  2717. dp->obj.sclust = ld_clust(fs, fs->win + dp->dptr % SS(fs)); /* Open next directory */
  2718. }
  2719. }
  2720. }
  2721. return res;
  2722. }
  2723. /*-----------------------------------------------------------------------*/
  2724. /* Get logical drive number from path name */
  2725. /*-----------------------------------------------------------------------*/
  2726. static int get_ldnumber ( /* Returns logical drive number (-1:invalid drive number or null pointer) */
  2727. const TCHAR** path /* Pointer to pointer to the path name */
  2728. )
  2729. {
  2730. const TCHAR *tp;
  2731. const TCHAR *tt;
  2732. TCHAR chr;
  2733. int i;
  2734. #if FF_STR_VOLUME_ID /* Find string volume ID */
  2735. const char *vsp;
  2736. char vchr;
  2737. #endif
  2738. tt = tp = *path;
  2739. if (!tp) return -1; /* Invalid path name? */
  2740. do { /* Find a colon in the path */
  2741. chr = *tt++;
  2742. } while (!IsTerminator(chr) && chr != ':');
  2743. if (chr == ':') { /* Is there a DOS/Windows style volume ID? */
  2744. i = FF_VOLUMES;
  2745. if (IsDigit(*tp) && tp + 2 == tt) { /* Is it a numeric volume ID + colon? */
  2746. i = (int)*tp - '0'; /* Get the logical drive number */
  2747. }
  2748. #if FF_STR_VOLUME_ID == 1 /* Arbitrary string volume ID is enabled */
  2749. else {
  2750. i = 0; /* Find volume ID string in the preconfigured table */
  2751. do {
  2752. vsp = VolumeStr[i]; tp = *path; /* Preconfigured string and path name to test */
  2753. do { /* Compare the volume ID with path name in case-insensitive */
  2754. vchr = *vsp++; chr = *tp++;
  2755. if (IsLower(vchr)) vchr -= 0x20;
  2756. if (IsLower(chr)) chr -= 0x20;
  2757. } while (vchr && (TCHAR)vchr == chr);
  2758. } while ((vchr || tp != tt) && ++i < FF_VOLUMES); /* Repeat for each id until pattern match */
  2759. }
  2760. #endif
  2761. if (i >= FF_VOLUMES) return -1; /* Not found or invalid volume ID */
  2762. *path = tt; /* Snip the drive prefix off */
  2763. return i; /* Return the found drive number */
  2764. }
  2765. #if FF_STR_VOLUME_ID == 2 /* Unix style volume ID is enabled */
  2766. if (*tp == '/') { /* Is there a volume ID? */
  2767. while (*(tp + 1) == '/') tp++; /* Skip duplicated separator */
  2768. i = 0;
  2769. do {
  2770. vsp = VolumeStr[i]; tt = tp; /* Preconfigured string and path name to test */
  2771. do { /* Compare the volume ID with path name in case-insensitive */
  2772. vchr = *vsp++; chr = *(++tt);
  2773. if (IsLower(vchr)) vchr -= 0x20;
  2774. if (IsLower(chr)) chr -= 0x20;
  2775. } while (vchr && (TCHAR)vchr == chr);
  2776. } while ((vchr || (chr != '/' && !IsTerminator(chr))) && ++i < FF_VOLUMES); /* Repeat for each ID until pattern match */
  2777. if (i >= FF_VOLUMES) return -1; /* Not found (invalid volume ID) */
  2778. *path = tt; /* Snip the node name off */
  2779. return i; /* Return the found drive number */
  2780. }
  2781. #endif
  2782. /* No drive prefix */
  2783. #if FF_FS_RPATH
  2784. return (int)CurrVol; /* Default drive is current drive */
  2785. #else
  2786. return 0; /* Default drive is 0 */
  2787. #endif
  2788. }
  2789. /*-----------------------------------------------------------------------*/
  2790. /* GPT support functions */
  2791. /*-----------------------------------------------------------------------*/
  2792. #if FF_LBA64
  2793. /* Calculate CRC32 in byte-by-byte */
  2794. static DWORD crc32 ( /* Returns next CRC value */
  2795. DWORD crc, /* Current CRC value */
  2796. BYTE d /* A byte to be processed */
  2797. )
  2798. {
  2799. BYTE b;
  2800. for (b = 1; b; b <<= 1) {
  2801. crc ^= (d & b) ? 1 : 0;
  2802. crc = (crc & 1) ? crc >> 1 ^ 0xEDB88320 : crc >> 1;
  2803. }
  2804. return crc;
  2805. }
  2806. /* Check validity of GPT header */
  2807. static int test_gpt_header ( /* 0:Invalid, 1:Valid */
  2808. const BYTE* gpth /* Pointer to the GPT header */
  2809. )
  2810. {
  2811. UINT i;
  2812. DWORD bcc, hlen;
  2813. if (memcmp(gpth + GPTH_Sign, "EFI PART" "\0\0\1", 12)) return 0; /* Check signature and version (1.0) */
  2814. hlen = ld_32(gpth + GPTH_Size); /* Check header size */
  2815. if (hlen < 92 || hlen > FF_MIN_SS) return 0;
  2816. for (i = 0, bcc = 0xFFFFFFFF; i < hlen; i++) { /* Check header BCC */
  2817. bcc = crc32(bcc, i - GPTH_Bcc < 4 ? 0 : gpth[i]);
  2818. }
  2819. if (~bcc != ld_32(gpth + GPTH_Bcc)) return 0;
  2820. if (ld_32(gpth + GPTH_PteSize) != SZ_GPTE) return 0; /* Table entry size (must be SZ_GPTE bytes) */
  2821. if (ld_32(gpth + GPTH_PtNum) > 128) return 0; /* Table size (must be 128 entries or less) */
  2822. return 1;
  2823. }
  2824. #if !FF_FS_READONLY && FF_USE_MKFS
  2825. /* Generate a random value */
  2826. static DWORD make_rand ( /* Returns a seed value for next */
  2827. DWORD seed, /* Seed value */
  2828. BYTE *buff, /* Output buffer */
  2829. UINT n /* Data length */
  2830. )
  2831. {
  2832. UINT r;
  2833. if (seed == 0) seed = 1;
  2834. do {
  2835. for (r = 0; r < 8; r++) seed = seed & 1 ? seed >> 1 ^ 0xA3000000 : seed >> 1; /* Shift 8 bits the 32-bit LFSR */
  2836. *buff++ = (BYTE)seed;
  2837. } while (--n);
  2838. return seed;
  2839. }
  2840. #endif
  2841. #endif
  2842. /*-----------------------------------------------------------------------*/
  2843. /* Load a sector and check if it is an FAT VBR */
  2844. /*-----------------------------------------------------------------------*/
  2845. /* Check what the sector is */
  2846. static UINT check_fs ( /* 0:FAT/FAT32 VBR, 1:exFAT VBR, 2:Not FAT and valid BS, 3:Not FAT and invalid BS, 4:Disk error */
  2847. FATFS* fs, /* Filesystem object */
  2848. LBA_t sect /* Sector to load and check if it is an FAT-VBR or not */
  2849. )
  2850. {
  2851. WORD w, sign;
  2852. BYTE b;
  2853. fs->wflag = 0; fs->winsect = (LBA_t)0 - 1; /* Invaidate window */
  2854. if (move_window(fs, sect) != FR_OK) return 4; /* Load the boot sector */
  2855. sign = ld_16(fs->win + BS_55AA);
  2856. #if FF_FS_EXFAT
  2857. if (sign == 0xAA55 && !memcmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1; /* It is an exFAT VBR */
  2858. #endif
  2859. b = fs->win[BS_JmpBoot];
  2860. if (b == 0xEB || b == 0xE9 || b == 0xE8) { /* Valid JumpBoot code? (short jump, near jump or near call) */
  2861. if (sign == 0xAA55 && !memcmp(fs->win + BS_FilSysType32, "FAT32 ", 8)) {
  2862. return 0; /* It is an FAT32 VBR */
  2863. }
  2864. /* FAT volumes created in the early MS-DOS era lack BS_55AA and BS_FilSysType, so FAT VBR needs to be identified without them. */
  2865. w = ld_16(fs->win + BPB_BytsPerSec);
  2866. b = fs->win[BPB_SecPerClus];
  2867. if ((w & (w - 1)) == 0 && w >= FF_MIN_SS && w <= FF_MAX_SS /* Properness of sector size (512-4096 and 2^n) */
  2868. && b != 0 && (b & (b - 1)) == 0 /* Properness of cluster size (2^n) */
  2869. && ld_16(fs->win + BPB_RsvdSecCnt) != 0 /* Properness of number of reserved sectors (MNBZ) */
  2870. && (UINT)fs->win[BPB_NumFATs] - 1 <= 1 /* Properness of number of FATs (1 or 2) */
  2871. && ld_16(fs->win + BPB_RootEntCnt) != 0 /* Properness of root dir size (MNBZ) */
  2872. && (ld_16(fs->win + BPB_TotSec16) >= MIN_VOLUME || ld_32(fs->win + BPB_TotSec32) >= 0x10000) /* Properness of volume size (>=128) */
  2873. && ld_16(fs->win + BPB_FATSz16) != 0) { /* Properness of FAT size (MNBZ) */
  2874. return 0; /* It can be presumed an FAT VBR */
  2875. }
  2876. }
  2877. return sign == 0xAA55 ? 2 : 3; /* Not an FAT VBR (with valid or invalid BS) */
  2878. }
  2879. /* Find an FAT volume */
  2880. /* (It supports only generic partitioning rules, MBR, GPT and SFD) */
  2881. static UINT find_volume ( /* Returns BS status found in the hosting drive */
  2882. FATFS* fs, /* Filesystem object */
  2883. UINT part /* Partition to fined = 0:find as SFD and partitions, >0:forced partition number */
  2884. )
  2885. {
  2886. UINT fmt, i;
  2887. DWORD mbr_pt[4];
  2888. fmt = check_fs(fs, 0); /* Load sector 0 and check if it is an FAT VBR as SFD format */
  2889. if (fmt != 2 && (fmt >= 3 || part == 0)) return fmt; /* Returns if it is an FAT VBR as auto scan, not a BS or disk error */
  2890. /* Sector 0 is not an FAT VBR or forced partition number wants a partitioned drive */
  2891. #if FF_LBA64
  2892. if (fs->win[MBR_Table + PTE_System] == 0xEE) { /* GPT protective MBR? */
  2893. DWORD n_ent, v_ent, ofs;
  2894. QWORD pt_lba;
  2895. if (move_window(fs, 1) != FR_OK) return 4; /* Load GPT header sector (next to MBR) */
  2896. if (!test_gpt_header(fs->win)) return 3; /* Check if GPT header is valid */
  2897. n_ent = ld_32(fs->win + GPTH_PtNum); /* Number of entries */
  2898. pt_lba = ld_64(fs->win + GPTH_PtOfs); /* Table location */
  2899. for (v_ent = i = 0; i < n_ent; i++) { /* Find FAT partition */
  2900. if (move_window(fs, pt_lba + i * SZ_GPTE / SS(fs)) != FR_OK) return 4; /* PT sector */
  2901. ofs = i * SZ_GPTE % SS(fs); /* Offset in the sector */
  2902. if (!memcmp(fs->win + ofs + GPTE_PtGuid, GUID_MS_Basic, 16)) { /* MS basic data partition? */
  2903. v_ent++; /* Order of MS BDP */
  2904. fmt = check_fs(fs, ld_64(fs->win + ofs + GPTE_FstLba)); /* Load VBR and check status */
  2905. if (part == 0 && fmt <= 1) return fmt; /* Auto search (valid FAT volume found first) */
  2906. if (part != 0 && v_ent == part) return fmt; /* Forced partition order (regardless of it is valid or not) */
  2907. }
  2908. }
  2909. return 3; /* Not found */
  2910. }
  2911. #endif
  2912. if (FF_MULTI_PARTITION && part > 4) return 3; /* MBR has four primary partitions max (FatFs does not support logical partition) */
  2913. for (i = 0; i < 4; i++) { /* Load partition offset in the MBR */
  2914. mbr_pt[i] = ld_32(fs->win + MBR_Table + i * SZ_PTE + PTE_StLba);
  2915. }
  2916. i = part ? part - 1 : 0; /* Table index to find first */
  2917. do { /* Find an FAT volume */
  2918. fmt = mbr_pt[i] ? check_fs(fs, mbr_pt[i]) : 3; /* Check if the partition is FAT */
  2919. } while (part == 0 && fmt >= 2 && ++i < 4);
  2920. return fmt;
  2921. }
  2922. /*-----------------------------------------------------------------------*/
  2923. /* Determine logical drive number and mount the volume if needed */
  2924. /*-----------------------------------------------------------------------*/
  2925. static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */
  2926. const TCHAR** path, /* Pointer to pointer to the path name (drive number) */
  2927. FATFS** rfs, /* Pointer to pointer to the found filesystem object */
  2928. BYTE mode /* Desiered access mode to check write protection */
  2929. )
  2930. {
  2931. int vol;
  2932. FATFS *fs;
  2933. DSTATUS stat;
  2934. LBA_t bsect;
  2935. UINT fmt;
  2936. /* Get logical drive number */
  2937. *rfs = 0;
  2938. vol = get_ldnumber(path);
  2939. if (vol < 0) return FR_INVALID_DRIVE;
  2940. /* Check if the filesystem object is valid or not */
  2941. fs = FatFs[vol]; /* Get pointer to the filesystem object */
  2942. if (!fs) return FR_NOT_ENABLED; /* Is the filesystem object available? */
  2943. #if FF_FS_REENTRANT
  2944. if (!lock_volume(fs, 1)) return FR_TIMEOUT; /* Lock the volume, and system if needed */
  2945. #endif
  2946. *rfs = fs; /* Return pointer to the filesystem object */
  2947. mode &= (BYTE)~FA_READ; /* Desired access mode, write access or not */
  2948. if (fs->fs_type != 0) { /* If the volume has been mounted */
  2949. stat = disk_status(fs->pdrv);
  2950. if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */
  2951. if (!FF_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check write protection if needed */
  2952. return FR_WRITE_PROTECTED;
  2953. }
  2954. return FR_OK; /* The filesystem object is already valid */
  2955. }
  2956. }
  2957. /* The filesystem object is not valid. */
  2958. /* Following code attempts to mount the volume. (find an FAT volume, analyze the BPB and initialize the filesystem object) */
  2959. fs->fs_type = 0; /* Invalidate the filesystem object */
  2960. stat = disk_initialize(fs->pdrv); /* Initialize the volume hosting physical drive */
  2961. if (stat & STA_NOINIT) { /* Check if the initialization succeeded */
  2962. return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
  2963. }
  2964. if (!FF_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check disk write protection if needed */
  2965. return FR_WRITE_PROTECTED;
  2966. }
  2967. #if FF_MAX_SS != FF_MIN_SS /* Get sector size (multiple sector size cfg only) */
  2968. if (disk_ioctl(fs->pdrv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK) return FR_DISK_ERR;
  2969. if (SS(fs) > FF_MAX_SS || SS(fs) < FF_MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;
  2970. #endif
  2971. /* Find an FAT volume on the hosting drive */
  2972. fmt = find_volume(fs, LD2PT(vol));
  2973. if (fmt == 4) return FR_DISK_ERR; /* An error occurred in the disk I/O layer */
  2974. if (fmt >= 2) return FR_NO_FILESYSTEM; /* No FAT volume is found */
  2975. bsect = fs->winsect; /* Volume offset in the hosting physical drive */
  2976. /* An FAT volume is found (bsect). Following code initializes the filesystem object */
  2977. #if FF_FS_EXFAT
  2978. if (fmt == 1) {
  2979. QWORD maxlba;
  2980. DWORD so, cv, bcl, ncl, i;
  2981. for (i = BPB_ZeroedEx; i < BPB_ZeroedEx + 53 && fs->win[i] == 0; i++) ; /* Check zero filler */
  2982. if (i < BPB_ZeroedEx + 53) return FR_NO_FILESYSTEM;
  2983. if (ld_16(fs->win + BPB_FSVerEx) != 0x100) return FR_NO_FILESYSTEM; /* Check exFAT version (must be version 1.0) */
  2984. if (1 << fs->win[BPB_BytsPerSecEx] != SS(fs)) { /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
  2985. return FR_NO_FILESYSTEM;
  2986. }
  2987. maxlba = ld_64(fs->win + BPB_TotSecEx) + bsect; /* Last LBA of the volume + 1 */
  2988. if (!FF_LBA64 && maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be accessed in 32-bit LBA) */
  2989. fs->fsize = ld_32(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */
  2990. fs->n_fats = fs->win[BPB_NumFATsEx]; /* Number of FATs */
  2991. if (fs->n_fats != 1) return FR_NO_FILESYSTEM; /* (Supports only 1 FAT) */
  2992. fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */
  2993. if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768 sectors) */
  2994. ncl = ld_32(fs->win + BPB_NumClusEx); /* Number of clusters */
  2995. if (ncl > MAX_EXFAT) return FR_NO_FILESYSTEM; /* (Too many clusters) */
  2996. fs->n_fatent = ncl + 2;
  2997. /* Boundaries and Limits */
  2998. fs->volbase = bsect;
  2999. fs->database = bsect + ld_32(fs->win + BPB_DataOfsEx);
  3000. fs->fatbase = bsect + ld_32(fs->win + BPB_FatOfsEx);
  3001. if (maxlba < (QWORD)fs->database + ncl * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size required) */
  3002. fs->dirbase = ld_32(fs->win + BPB_RootClusEx);
  3003. /* Get bitmap location and check if it is contiguous (implementation assumption) */
  3004. so = i = 0;
  3005. for (;;) { /* Find the bitmap entry in the root directory (in only first cluster) */
  3006. if (i == 0) {
  3007. if (so >= fs->csize) return FR_NO_FILESYSTEM; /* Not found? */
  3008. if (move_window(fs, clst2sect(fs, (DWORD)fs->dirbase) + so) != FR_OK) return FR_DISK_ERR;
  3009. so++;
  3010. }
  3011. if (fs->win[i] == ET_BITMAP) break; /* Is it a bitmap entry? */
  3012. i = (i + SZDIRE) % SS(fs); /* Next entry */
  3013. }
  3014. bcl = ld_32(fs->win + i + 20); /* Bitmap cluster */
  3015. if (bcl < 2 || bcl >= fs->n_fatent) return FR_NO_FILESYSTEM; /* (Wrong cluster#) */
  3016. fs->bitbase = fs->database + fs->csize * (bcl - 2); /* Bitmap sector */
  3017. for (;;) { /* Check if bitmap is contiguous */
  3018. if (move_window(fs, fs->fatbase + bcl / (SS(fs) / 4)) != FR_OK) return FR_DISK_ERR;
  3019. cv = ld_32(fs->win + bcl % (SS(fs) / 4) * 4);
  3020. if (cv == 0xFFFFFFFF) break; /* Last link? */
  3021. if (cv != ++bcl) return FR_NO_FILESYSTEM; /* Fragmented bitmap? */
  3022. }
  3023. #if !FF_FS_READONLY
  3024. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Invalidate cluster allocation information */
  3025. fs->fsi_flag = 0; /* Enable to sync PercInUse value in VBR */
  3026. #endif
  3027. fmt = FS_EXFAT; /* FAT sub-type */
  3028. } else
  3029. #endif /* FF_FS_EXFAT */
  3030. {
  3031. DWORD tsect, sysect, fasize, nclst, szbfat;
  3032. WORD nrsv;
  3033. if (ld_16(fs->win + BPB_BytsPerSec) != SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_BytsPerSec must be equal to the physical sector size) */
  3034. fasize = ld_16(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
  3035. if (fasize == 0) fasize = ld_32(fs->win + BPB_FATSz32);
  3036. fs->fsize = fasize;
  3037. fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FATs */
  3038. if (fs->n_fats != 1 && fs->n_fats != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
  3039. fasize *= fs->n_fats; /* Number of sectors for FAT area */
  3040. fs->csize = fs->win[BPB_SecPerClus]; /* Cluster size */
  3041. if (fs->csize == 0 || (fs->csize & (fs->csize - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
  3042. fs->n_rootdir = ld_16(fs->win + BPB_RootEntCnt); /* Number of root directory entries */
  3043. if (fs->n_rootdir % (SS(fs) / SZDIRE)) return FR_NO_FILESYSTEM; /* (Must be sector aligned) */
  3044. tsect = ld_16(fs->win + BPB_TotSec16); /* Number of sectors on the volume */
  3045. if (tsect == 0) tsect = ld_32(fs->win + BPB_TotSec32);
  3046. nrsv = ld_16(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
  3047. if (nrsv == 0) return FR_NO_FILESYSTEM; /* (Must not be 0) */
  3048. /* Determine the FAT sub type */
  3049. sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZDIRE); /* RSV + FAT + DIR */
  3050. if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  3051. nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
  3052. if (nclst == 0) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  3053. fmt = 0;
  3054. if (nclst <= MAX_FAT32) fmt = FS_FAT32;
  3055. if (nclst <= MAX_FAT16) fmt = FS_FAT16;
  3056. if (nclst <= MAX_FAT12) fmt = FS_FAT12;
  3057. if (nclst <= MIN_FAT12) fmt = 0;
  3058. if (fmt == 0) return FR_NO_FILESYSTEM;
  3059. /* Boundaries and Limits */
  3060. fs->n_fatent = nclst + 2; /* Number of FAT entries */
  3061. fs->volbase = bsect; /* Volume start sector */
  3062. fs->fatbase = bsect + nrsv; /* FAT start sector */
  3063. fs->database = bsect + sysect; /* Data start sector */
  3064. if (fmt == FS_FAT32) {
  3065. if (ld_16(fs->win + BPB_FSVer32) != 0) return FR_NO_FILESYSTEM; /* (Must be FAT32 revision 0.0) */
  3066. if (fs->n_rootdir != 0) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
  3067. fs->dirbase = ld_32(fs->win + BPB_RootClus32); /* Root directory start cluster */
  3068. szbfat = fs->n_fatent * 4; /* (Needed FAT size) */
  3069. } else {
  3070. if (fs->n_rootdir == 0) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must not be 0) */
  3071. fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
  3072. szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */
  3073. fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  3074. }
  3075. if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_FATSz must not be less than the size needed) */
  3076. #if !FF_FS_READONLY
  3077. /* Get FSInfo if available */
  3078. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Invalidate cluster allocation information */
  3079. fs->fsi_flag = 0x80; /* Disable FSInfo by default */
  3080. if (fmt == FS_FAT32
  3081. && ld_16(fs->win + BPB_FSInfo32) == 1 /* FAT32: Enable FSInfo feature only if FSInfo sector is next to VBR */
  3082. && move_window(fs, bsect + 1) == FR_OK)
  3083. {
  3084. fs->fsi_flag = 0;
  3085. if ( ld_32(fs->win + FSI_LeadSig) == 0x41615252 /* Load FSInfo data if available */
  3086. && ld_32(fs->win + FSI_StrucSig) == 0x61417272
  3087. && ld_32(fs->win + FSI_TrailSig) == 0xAA550000)
  3088. {
  3089. #if (FF_FS_NOFSINFO & 1) == 0 /* Get free cluster count if trust it */
  3090. fs->free_clst = ld_32(fs->win + FSI_Free_Count);
  3091. #endif
  3092. #if (FF_FS_NOFSINFO & 2) == 0 /* Get next free cluster if rtust it */
  3093. fs->last_clst = ld_32(fs->win + FSI_Nxt_Free);
  3094. #endif
  3095. }
  3096. }
  3097. #endif /* !FF_FS_READONLY */
  3098. }
  3099. fs->fs_type = (BYTE)fmt;/* FAT sub-type (the filesystem object gets valid) */
  3100. fs->id = ++Fsid; /* Volume mount ID */
  3101. #if FF_USE_LFN == 1 /* Initilize pointers to the static working buffers */
  3102. fs->lfnbuf = LfnBuf; /* LFN working buffer */
  3103. #if FF_FS_EXFAT
  3104. fs->dirbuf = DirBuf; /* Directory block scratchpad buuffer */
  3105. #endif
  3106. #endif
  3107. #if FF_FS_RPATH /* Set the current directory top layer (root) */
  3108. fs->cdir = 0;
  3109. #if FF_FS_EXFAT
  3110. memset(&fs->xcwds, 0, sizeof fs->xcwds);
  3111. #endif
  3112. #endif
  3113. #if FF_FS_LOCK /* Clear file lock semaphores */
  3114. clear_share(fs);
  3115. #endif
  3116. return FR_OK;
  3117. }
  3118. /*-----------------------------------------------------------------------*/
  3119. /* Check if the file/directory object is valid or not */
  3120. /*-----------------------------------------------------------------------*/
  3121. static FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */
  3122. FFOBJID* obj, /* Pointer to the FFOBJID, the 1st member in the FIL/DIR structure, to check validity */
  3123. FATFS** rfs /* Pointer to pointer to the owner filesystem object to return */
  3124. )
  3125. {
  3126. FRESULT res = FR_INVALID_OBJECT;
  3127. if (obj && obj->fs && obj->fs->fs_type && obj->id == obj->fs->id) { /* Test if the object is valid */
  3128. #if FF_FS_REENTRANT
  3129. if (lock_volume(obj->fs, 0)) { /* Take a grant to access the volume */
  3130. if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the hosting physical drive is kept initialized */
  3131. res = FR_OK;
  3132. } else {
  3133. unlock_volume(obj->fs, FR_OK); /* Invalidated volume, abort to access */
  3134. }
  3135. } else { /* Could not take */
  3136. res = FR_TIMEOUT;
  3137. }
  3138. #else
  3139. if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the hosting physical drive is kept initialized */
  3140. res = FR_OK;
  3141. }
  3142. #endif
  3143. }
  3144. *rfs = (res == FR_OK) ? obj->fs : 0; /* Return corresponding filesystem object if it is valid */
  3145. return res;
  3146. }
  3147. /*---------------------------------------------------------------------------
  3148. Public Functions (FatFs API)
  3149. ----------------------------------------------------------------------------*/
  3150. /*-----------------------------------------------------------------------*/
  3151. /* API: Mount/Unmount a Logical Drive */
  3152. /*-----------------------------------------------------------------------*/
  3153. FRESULT f_mount (
  3154. FATFS* fs, /* Pointer to the filesystem object to be registered (NULL:unmount)*/
  3155. const TCHAR* path, /* Logical drive number to be mounted/unmounted */
  3156. BYTE opt /* Mount option: 0=Do not mount (delayed mount), 1=Mount immediately */
  3157. )
  3158. {
  3159. FATFS *cfs;
  3160. int vol;
  3161. FRESULT res;
  3162. const TCHAR *rp = path;
  3163. /* Get volume ID (logical drive number) */
  3164. vol = get_ldnumber(&rp);
  3165. if (vol < 0) return FR_INVALID_DRIVE;
  3166. cfs = FatFs[vol]; /* Pointer to the filesystem object of the volume */
  3167. if (cfs) { /* Unregister current filesystem object */
  3168. FatFs[vol] = 0;
  3169. #if FF_FS_LOCK /* Clear file lock semaphores correspond to this volume */
  3170. clear_share(cfs);
  3171. #endif
  3172. #if FF_FS_REENTRANT /* Discard mutex of the current volume */
  3173. ff_mutex_delete(vol);
  3174. #endif
  3175. cfs->fs_type = 0; /* Invalidate the filesystem object to be unregistered */
  3176. }
  3177. if (fs) { /* Register new filesystem object */
  3178. fs->pdrv = LD2PD(vol); /* Volume hosting physical drive */
  3179. #if FF_FS_REENTRANT /* Create a volume mutex */
  3180. fs->ldrv = (BYTE)vol; /* Owner volume ID */
  3181. if (!ff_mutex_create(vol)) return FR_INT_ERR;
  3182. #if FF_FS_LOCK
  3183. if (SysLock == 0) { /* Create a system mutex if needed */
  3184. if (!ff_mutex_create(FF_VOLUMES)) {
  3185. ff_mutex_delete(vol);
  3186. return FR_INT_ERR;
  3187. }
  3188. SysLock = 1; /* System mutex is ready */
  3189. }
  3190. #endif
  3191. #endif
  3192. fs->fs_type = 0; /* Invalidate the new filesystem object */
  3193. FatFs[vol] = fs; /* Register it */
  3194. }
  3195. if (opt == 0) return FR_OK; /* Do not mount now, it will be mounted in subsequent file functions */
  3196. res = mount_volume(&path, &fs, 0); /* Force mounted the volume in this function */
  3197. LEAVE_FF(fs, res);
  3198. }
  3199. /*-----------------------------------------------------------------------*/
  3200. /* API: Open or Create a File */
  3201. /*-----------------------------------------------------------------------*/
  3202. FRESULT f_open (
  3203. FIL* fp, /* Pointer to the blank file object */
  3204. const TCHAR* path, /* Pointer to the file name */
  3205. BYTE mode /* Access mode and open mode flags */
  3206. )
  3207. {
  3208. FRESULT res;
  3209. DIR dj;
  3210. FATFS *fs;
  3211. DEF_NAMEBUFF
  3212. if (!fp) return FR_INVALID_OBJECT; /* Reject null pointer */
  3213. /* Get logical drive number and mount the volume if needed */
  3214. mode &= FF_FS_READONLY ? FA_READ : FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_CREATE_NEW | FA_OPEN_ALWAYS | FA_OPEN_APPEND;
  3215. res = mount_volume(&path, &fs, mode);
  3216. if (res == FR_OK) {
  3217. fp->obj.fs = fs;
  3218. dj.obj.fs = fs;
  3219. INIT_NAMEBUFF(fs);
  3220. res = follow_path(&dj, path); /* Follow the file path */
  3221. #if !FF_FS_READONLY /* Read/Write configuration */
  3222. if (res == FR_OK) {
  3223. if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
  3224. res = FR_INVALID_NAME;
  3225. }
  3226. #if FF_FS_LOCK
  3227. else {
  3228. res = chk_share(&dj, (mode & ~FA_READ) ? 1 : 0); /* Check if the file can be used */
  3229. }
  3230. #endif
  3231. }
  3232. /* Create or Open a file */
  3233. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  3234. if (res != FR_OK) { /* No file, create new */
  3235. if (res == FR_NO_FILE) { /* There is no file to open, create a new entry */
  3236. #if FF_FS_LOCK
  3237. res = enq_share() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
  3238. #else
  3239. res = dir_register(&dj);
  3240. #endif
  3241. }
  3242. mode |= FA_CREATE_ALWAYS; /* File is created */
  3243. }
  3244. else { /* An object with the same name is already existing */
  3245. if (mode & FA_CREATE_NEW) {
  3246. res = FR_EXIST; /* Cannot create as new file */
  3247. } else {
  3248. if (dj.obj.attr & (AM_RDO | AM_DIR)) res = FR_DENIED; /* Cannot overwrite it (R/O or DIR) */
  3249. }
  3250. }
  3251. if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate the file if overwrite mode */
  3252. DWORD tm = GET_FATTIME();
  3253. #if FF_FS_EXFAT
  3254. if (fs->fs_type == FS_EXFAT) {
  3255. /* Get current allocation info */
  3256. init_alloc_info(&fp->obj, 0);
  3257. /* Set exFAT directory entry block initial state */
  3258. memset(fs->dirbuf + 2, 0, 30); /* Clear 85 entry except for NumSec */
  3259. memset(fs->dirbuf + 38, 0, 26); /* Clear C0 entry except for NumName and NameHash */
  3260. fs->dirbuf[XDIR_Attr] = AM_ARC;
  3261. st_32(fs->dirbuf + XDIR_CrtTime, tm); /* Set created time */
  3262. st_32(fs->dirbuf + XDIR_ModTime, tm); /* Set modified time (tmp setting) */
  3263. fs->dirbuf[XDIR_GenFlags] = 1;
  3264. res = store_xdir(&dj);
  3265. if (res == FR_OK && fp->obj.sclust != 0) { /* Remove the cluster chain if exist */
  3266. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  3267. fs->last_clst = fp->obj.sclust - 1; /* Reuse the cluster hole */
  3268. }
  3269. } else
  3270. #endif
  3271. {
  3272. DWORD cl;
  3273. /* Set FAT directory entry initial state */
  3274. st_32(dj.dir + DIR_CrtTime, tm); /* Set created time */
  3275. st_32(dj.dir + DIR_ModTime, tm); /* Set modified time (tmp setting) */
  3276. cl = ld_clust(fs, dj.dir); /* Get current cluster chain */
  3277. dj.dir[DIR_Attr] = AM_ARC; /* Reset attribute */
  3278. st_clust(fs, dj.dir, 0); /* Reset file allocation info */
  3279. st_32(dj.dir + DIR_FileSize, 0);
  3280. fs->wflag = 1;
  3281. if (cl != 0) { /* Remove the cluster chain if exist */
  3282. LBA_t sc = fs->winsect;
  3283. res = remove_chain(&dj.obj, cl, 0);
  3284. if (res == FR_OK) {
  3285. res = move_window(fs, sc);
  3286. fs->last_clst = cl - 1; /* Reuse the cluster hole */
  3287. }
  3288. }
  3289. }
  3290. }
  3291. }
  3292. else { /* Open an existing file */
  3293. if (res == FR_OK) { /* Is the object exsiting? */
  3294. if (dj.obj.attr & AM_DIR) { /* File open against a directory */
  3295. res = FR_NO_FILE;
  3296. } else {
  3297. if ((mode & FA_WRITE) && (dj.obj.attr & AM_RDO)) { /* Write mode open against R/O file */
  3298. res = FR_DENIED;
  3299. }
  3300. }
  3301. }
  3302. }
  3303. if (res == FR_OK) {
  3304. if (mode & FA_CREATE_ALWAYS) mode |= FA_MODIFIED; /* Set file change flag if created or overwritten */
  3305. fp->dir_sect = fs->winsect; /* Pointer to the directory entry */
  3306. fp->dir_ptr = dj.dir;
  3307. #if FF_FS_LOCK
  3308. fp->obj.lockid = inc_share(&dj, (mode & ~FA_READ) ? 1 : 0); /* Lock the file for this session */
  3309. if (fp->obj.lockid == 0) res = FR_INT_ERR;
  3310. #endif
  3311. }
  3312. #else /* R/O configuration */
  3313. if (res == FR_OK) {
  3314. if (dj.fn[NSFLAG] & NS_NONAME) { /* Is it origin directory itself? */
  3315. res = FR_INVALID_NAME;
  3316. } else {
  3317. if (dj.obj.attr & AM_DIR) { /* Is it a directory? */
  3318. res = FR_NO_FILE;
  3319. }
  3320. }
  3321. }
  3322. #endif
  3323. if (res == FR_OK) {
  3324. #if FF_FS_EXFAT
  3325. if (fs->fs_type == FS_EXFAT) {
  3326. init_alloc_info(&fp->obj, &dj);
  3327. } else
  3328. #endif
  3329. {
  3330. fp->obj.sclust = ld_clust(fs, dj.dir); /* Get object allocation info */
  3331. fp->obj.objsize = ld_32(dj.dir + DIR_FileSize);
  3332. }
  3333. #if FF_USE_FASTSEEK
  3334. fp->cltbl = 0; /* Disable fast seek mode */
  3335. #endif
  3336. fp->obj.id = fs->id; /* Set current volume mount ID */
  3337. fp->flag = mode; /* Set file access mode */
  3338. fp->err = 0; /* Clear error flag */
  3339. fp->sect = 0; /* Invalidate current data sector */
  3340. fp->fptr = 0; /* Set file pointer top of the file */
  3341. #if !FF_FS_READONLY
  3342. #if !FF_FS_TINY
  3343. memset(fp->buf, 0, sizeof fp->buf); /* Clear sector buffer */
  3344. #endif
  3345. if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
  3346. DWORD bcs, clst;
  3347. FSIZE_t ofs;
  3348. fp->fptr = fp->obj.objsize; /* Offset to seek */
  3349. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size in byte */
  3350. clst = fp->obj.sclust; /* Follow the cluster chain */
  3351. for (ofs = fp->obj.objsize; res == FR_OK && ofs > bcs; ofs -= bcs) {
  3352. clst = get_fat(&fp->obj, clst);
  3353. if (clst <= 1) res = FR_INT_ERR;
  3354. if (clst == 0xFFFFFFFF) res = FR_DISK_ERR;
  3355. }
  3356. fp->clust = clst;
  3357. if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */
  3358. LBA_t sec = clst2sect(fs, clst);
  3359. if (sec == 0) {
  3360. res = FR_INT_ERR;
  3361. } else {
  3362. fp->sect = sec + (DWORD)(ofs / SS(fs));
  3363. #if !FF_FS_TINY
  3364. if (disk_read(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) res = FR_DISK_ERR;
  3365. #endif
  3366. }
  3367. }
  3368. #if FF_FS_LOCK
  3369. if (res != FR_OK) dec_share(fp->obj.lockid); /* Decrement file open counter if seek failed */
  3370. #endif
  3371. }
  3372. #endif
  3373. }
  3374. FREE_NAMEBUFF();
  3375. }
  3376. if (res != FR_OK) fp->obj.fs = 0; /* Invalidate file object on error */
  3377. LEAVE_FF(fs, res);
  3378. }
  3379. /*-----------------------------------------------------------------------*/
  3380. /* API: Read File */
  3381. /*-----------------------------------------------------------------------*/
  3382. FRESULT f_read (
  3383. FIL* fp, /* Open file to be read */
  3384. void* buff, /* Data buffer to store the read data */
  3385. UINT btr, /* Number of bytes to read */
  3386. UINT* br /* Number of bytes read */
  3387. )
  3388. {
  3389. FRESULT res;
  3390. FATFS *fs;
  3391. LBA_t sect;
  3392. FSIZE_t remain;
  3393. UINT rcnt, cc, csect;
  3394. BYTE *rbuff = (BYTE*)buff;
  3395. *br = 0; /* Clear read byte counter */
  3396. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3397. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  3398. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3399. remain = fp->obj.objsize - fp->fptr;
  3400. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  3401. for ( ; btr > 0; btr -= rcnt, *br += rcnt, rbuff += rcnt, fp->fptr += rcnt) { /* Repeat until btr bytes read */
  3402. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  3403. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  3404. if (csect == 0) { /* On the cluster boundary? */
  3405. DWORD clst;
  3406. if (fp->fptr == 0) { /* On the top of the file? */
  3407. clst = fp->obj.sclust; /* Follow cluster chain from the origin */
  3408. } else { /* Middle or end of the file */
  3409. #if FF_USE_FASTSEEK
  3410. if (fp->cltbl) {
  3411. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  3412. } else
  3413. #endif
  3414. {
  3415. clst = get_fat(&fp->obj, fp->clust); /* Follow cluster chain on the FAT */
  3416. }
  3417. }
  3418. if (clst < 2) ABORT(fs, FR_INT_ERR);
  3419. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3420. fp->clust = clst; /* Update current cluster */
  3421. }
  3422. sect = clst2sect(fs, fp->clust); /* Get current sector */
  3423. if (sect == 0) ABORT(fs, FR_INT_ERR);
  3424. sect += csect;
  3425. cc = btr / SS(fs); /* When remaining bytes >= sector size, */
  3426. if (cc > 0) { /* Read maximum contiguous sectors directly */
  3427. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  3428. cc = fs->csize - csect;
  3429. }
  3430. if (disk_read(fs->pdrv, rbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3431. #if !FF_FS_READONLY && FF_FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
  3432. #if FF_FS_TINY
  3433. if (fs->wflag && fs->winsect - sect < cc) {
  3434. memcpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));
  3435. }
  3436. #else
  3437. if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {
  3438. memcpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));
  3439. }
  3440. #endif
  3441. #endif
  3442. rcnt = SS(fs) * cc; /* Number of bytes transferred */
  3443. continue;
  3444. }
  3445. #if !FF_FS_TINY
  3446. if (fp->sect != sect) { /* Load data sector if not in cache */
  3447. #if !FF_FS_READONLY
  3448. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3449. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3450. fp->flag &= (BYTE)~FA_DIRTY;
  3451. }
  3452. #endif
  3453. if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  3454. }
  3455. #endif
  3456. fp->sect = sect;
  3457. }
  3458. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
  3459. if (rcnt > btr) rcnt = btr; /* Clip it by btr if needed */
  3460. #if FF_FS_TINY
  3461. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  3462. memcpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  3463. #else
  3464. memcpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  3465. #endif
  3466. }
  3467. LEAVE_FF(fs, FR_OK);
  3468. }
  3469. #if !FF_FS_READONLY
  3470. /*-----------------------------------------------------------------------*/
  3471. /* API: Write File */
  3472. /*-----------------------------------------------------------------------*/
  3473. FRESULT f_write (
  3474. FIL* fp, /* Open file to be written */
  3475. const void* buff, /* Data to be written */
  3476. UINT btw, /* Number of bytes to write */
  3477. UINT* bw /* Number of bytes written */
  3478. )
  3479. {
  3480. FRESULT res;
  3481. FATFS *fs;
  3482. DWORD clst;
  3483. LBA_t sect;
  3484. UINT wcnt, cc, csect;
  3485. const BYTE *wbuff = (const BYTE*)buff;
  3486. *bw = 0; /* Clear write byte counter */
  3487. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3488. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  3489. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3490. /* Check fptr wrap-around (file size cannot reach 4 GiB at FAT volume) */
  3491. if ((!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) && (DWORD)(fp->fptr + btw) < (DWORD)fp->fptr) {
  3492. btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr);
  3493. }
  3494. for ( ; btw > 0; btw -= wcnt, *bw += wcnt, wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize) { /* Repeat until all data written */
  3495. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  3496. csect = (UINT)(fp->fptr / SS(fs)) & (fs->csize - 1); /* Sector offset in the cluster */
  3497. if (csect == 0) { /* On the cluster boundary? */
  3498. if (fp->fptr == 0) { /* On the top of the file? */
  3499. clst = fp->obj.sclust; /* Follow from the origin */
  3500. if (clst == 0) { /* If no cluster is allocated, */
  3501. clst = create_chain(&fp->obj, 0); /* create a new cluster chain */
  3502. }
  3503. } else { /* On the middle or end of the file */
  3504. #if FF_USE_FASTSEEK
  3505. if (fp->cltbl) {
  3506. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  3507. } else
  3508. #endif
  3509. {
  3510. clst = create_chain(&fp->obj, fp->clust); /* Follow or stretch cluster chain on the FAT */
  3511. }
  3512. }
  3513. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  3514. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3515. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3516. fp->clust = clst; /* Update current cluster */
  3517. if (fp->obj.sclust == 0) fp->obj.sclust = clst; /* Set start cluster if the first write */
  3518. }
  3519. #if FF_FS_TINY
  3520. if (fs->winsect == fp->sect && sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Write-back sector cache */
  3521. #else
  3522. if (fp->flag & FA_DIRTY) { /* Write-back sector cache */
  3523. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3524. fp->flag &= (BYTE)~FA_DIRTY;
  3525. }
  3526. #endif
  3527. sect = clst2sect(fs, fp->clust); /* Get current sector */
  3528. if (sect == 0) ABORT(fs, FR_INT_ERR);
  3529. sect += csect;
  3530. cc = btw / SS(fs); /* When remaining bytes >= sector size, */
  3531. if (cc > 0) { /* Write maximum contiguous sectors directly */
  3532. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  3533. cc = fs->csize - csect;
  3534. }
  3535. if (disk_write(fs->pdrv, wbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3536. #if FF_FS_MINIMIZE <= 2
  3537. #if FF_FS_TINY
  3538. if (fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  3539. memcpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));
  3540. fs->wflag = 0;
  3541. }
  3542. #else
  3543. if (fp->sect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  3544. memcpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));
  3545. fp->flag &= (BYTE)~FA_DIRTY;
  3546. }
  3547. #endif
  3548. #endif
  3549. wcnt = SS(fs) * cc; /* Number of bytes transferred */
  3550. continue;
  3551. }
  3552. #if FF_FS_TINY
  3553. if (fp->fptr >= fp->obj.objsize) { /* Avoid silly cache filling on the growing edge */
  3554. if (sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR);
  3555. fs->winsect = sect;
  3556. }
  3557. #else
  3558. if (fp->sect != sect && /* Fill sector cache with file data */
  3559. fp->fptr < fp->obj.objsize &&
  3560. disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) {
  3561. ABORT(fs, FR_DISK_ERR);
  3562. }
  3563. #endif
  3564. fp->sect = sect;
  3565. }
  3566. wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
  3567. if (wcnt > btw) wcnt = btw; /* Clip it by btw if needed */
  3568. #if FF_FS_TINY
  3569. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  3570. memcpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3571. fs->wflag = 1;
  3572. #else
  3573. memcpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3574. fp->flag |= FA_DIRTY;
  3575. #endif
  3576. }
  3577. fp->flag |= FA_MODIFIED; /* Set file change flag */
  3578. LEAVE_FF(fs, FR_OK);
  3579. }
  3580. /*-----------------------------------------------------------------------*/
  3581. /* API: Synchronize the File */
  3582. /*-----------------------------------------------------------------------*/
  3583. FRESULT f_sync (
  3584. FIL* fp /* Open file to be synced */
  3585. )
  3586. {
  3587. FRESULT res;
  3588. FATFS *fs;
  3589. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3590. if (res == FR_OK) {
  3591. if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
  3592. #if !FF_FS_TINY
  3593. if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
  3594. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
  3595. fp->flag &= (BYTE)~FA_DIRTY;
  3596. }
  3597. #endif
  3598. /* Update the directory entry */
  3599. #if FF_FS_EXFAT
  3600. if (fs->fs_type == FS_EXFAT) {
  3601. res = fill_first_frag(&fp->obj); /* Fill first fragment on the FAT if needed */
  3602. if (res == FR_OK) {
  3603. res = fill_last_frag(&fp->obj, fp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
  3604. }
  3605. if (res == FR_OK) {
  3606. DIR dj;
  3607. DEF_NAMEBUFF
  3608. INIT_NAMEBUFF(fs);
  3609. res = load_obj_xdir(&dj, &fp->obj); /* Load directory entry block */
  3610. if (res == FR_OK) {
  3611. fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive attribute to indicate that the file has been changed */
  3612. fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation information */
  3613. st_32(fs->dirbuf + XDIR_FstClus, fp->obj.sclust); /* Update start cluster */
  3614. st_64(fs->dirbuf + XDIR_FileSize, fp->obj.objsize); /* Update file size */
  3615. st_64(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize); /* (FatFs does not support Valid File Size feature) */
  3616. st_32(fs->dirbuf + XDIR_ModTime, GET_FATTIME()); /* Update modified time */
  3617. fs->dirbuf[XDIR_ModTime10] = 0;
  3618. fs->dirbuf[XDIR_ModTZ] = 0;
  3619. st_32(fs->dirbuf + XDIR_AccTime, 0); /* Invalidate last access time */
  3620. fs->dirbuf[XDIR_AccTZ] = 0;
  3621. res = store_xdir(&dj); /* Restore it to the directory */
  3622. if (res == FR_OK) {
  3623. res = sync_fs(fs);
  3624. fp->flag &= (BYTE)~FA_MODIFIED;
  3625. }
  3626. }
  3627. FREE_NAMEBUFF();
  3628. }
  3629. } else
  3630. #endif
  3631. {
  3632. res = move_window(fs, fp->dir_sect);
  3633. if (res == FR_OK) {
  3634. BYTE *dir = fp->dir_ptr;
  3635. dir[DIR_Attr] |= AM_ARC; /* Set archive attribute to indicate that the file has been changed */
  3636. st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation information */
  3637. st_32(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
  3638. st_32(dir + DIR_ModTime, GET_FATTIME()); /* Update modified time */
  3639. st_16(dir + DIR_LstAccDate, 0); /* Invalidate last access date */
  3640. fs->wflag = 1;
  3641. res = sync_fs(fs); /* Restore it to the directory */
  3642. fp->flag &= (BYTE)~FA_MODIFIED;
  3643. }
  3644. }
  3645. }
  3646. }
  3647. LEAVE_FF(fs, res);
  3648. }
  3649. #endif /* !FF_FS_READONLY */
  3650. /*-----------------------------------------------------------------------*/
  3651. /* API: Close File */
  3652. /*-----------------------------------------------------------------------*/
  3653. FRESULT f_close (
  3654. FIL* fp /* Open file to be closed */
  3655. )
  3656. {
  3657. FRESULT res;
  3658. FATFS *fs;
  3659. #if !FF_FS_READONLY
  3660. res = f_sync(fp); /* Flush cached data */
  3661. if (res == FR_OK)
  3662. #endif
  3663. {
  3664. res = validate(&fp->obj, &fs); /* Lock volume */
  3665. if (res == FR_OK) {
  3666. #if FF_FS_LOCK
  3667. res = dec_share(fp->obj.lockid); /* Decrement file open counter */
  3668. if (res == FR_OK) fp->obj.fs = 0; /* Invalidate file object */
  3669. #else
  3670. fp->obj.fs = 0; /* Invalidate file object */
  3671. #endif
  3672. #if FF_FS_REENTRANT
  3673. unlock_volume(fs, FR_OK); /* Unlock volume */
  3674. #endif
  3675. }
  3676. }
  3677. return res;
  3678. }
  3679. #if FF_FS_RPATH >= 1
  3680. /*-----------------------------------------------------------------------*/
  3681. /* API: Change Current Drive */
  3682. /*-----------------------------------------------------------------------*/
  3683. FRESULT f_chdrive (
  3684. const TCHAR* path /* Drive number to set */
  3685. )
  3686. {
  3687. int vol;
  3688. /* Get logical drive number */
  3689. vol = get_ldnumber(&path);
  3690. if (vol < 0) return FR_INVALID_DRIVE;
  3691. CurrVol = (BYTE)vol; /* Set it as current volume */
  3692. return FR_OK;
  3693. }
  3694. /*-----------------------------------------------------------------------*/
  3695. /* API: Change Current Directory */
  3696. /*-----------------------------------------------------------------------*/
  3697. FRESULT f_chdir (
  3698. const TCHAR* path /* Pointer to the directory path */
  3699. )
  3700. {
  3701. FRESULT res;
  3702. DIR dj;
  3703. FATFS *fs;
  3704. DEF_NAMEBUFF
  3705. res = mount_volume(&path, &fs, 0); /* Get logical drive and mount the volume if needed */
  3706. if (res == FR_OK) {
  3707. dj.obj.fs = fs;
  3708. INIT_NAMEBUFF(fs);
  3709. res = follow_path(&dj, path); /* Follow the path */
  3710. if (res == FR_OK) { /* Follow completed */
  3711. if (dj.fn[NSFLAG] & NS_NONAME) { /* Is it the start directory itself? */
  3712. #if FF_FS_EXFAT
  3713. if (fs->fs_type == FS_EXFAT) {
  3714. memcpy(&fs->xcwds, &fs->xcwds2, sizeof fs->xcwds);
  3715. }
  3716. #endif
  3717. fs->cdir = dj.obj.sclust;
  3718. } else {
  3719. if (dj.obj.attr & AM_DIR) { /* It is a sub-directory */
  3720. #if FF_FS_EXFAT
  3721. if (fs->fs_type == FS_EXFAT) {
  3722. memcpy(&fs->xcwds, &fs->xcwds2, sizeof fs->xcwds);
  3723. fs->cdir = fs->xcwds.tbl[fs->xcwds.depth].d_scl; /* Sub-directory cluster */
  3724. } else
  3725. #endif
  3726. {
  3727. fs->cdir = ld_clust(fs, dj.dir); /* Sub-directory cluster */
  3728. }
  3729. } else {
  3730. res = FR_NO_PATH; /* Reached but a file */
  3731. }
  3732. }
  3733. }
  3734. FREE_NAMEBUFF();
  3735. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3736. #if FF_STR_VOLUME_ID == 2 /* Also current drive is changed if in Unix style volume ID */
  3737. if (res == FR_OK) {
  3738. UINT i;
  3739. for (i = FF_VOLUMES - 1; i && fs != FatFs[i]; i--) ; /* Set current drive */
  3740. CurrVol = (BYTE)i;
  3741. }
  3742. #endif
  3743. }
  3744. LEAVE_FF(fs, res);
  3745. }
  3746. #if FF_FS_RPATH >= 2
  3747. /*-----------------------------------------------------------------------*/
  3748. /* API: Get Curent Directory */
  3749. /*-----------------------------------------------------------------------*/
  3750. FRESULT f_getcwd (
  3751. TCHAR* buff, /* Pointer to the buffer to store the current direcotry path */
  3752. UINT len /* Size of buff in unit of TCHAR */
  3753. )
  3754. {
  3755. FRESULT res;
  3756. DIR dj;
  3757. FATFS *fs;
  3758. #if FF_VOLUMES >= 2
  3759. UINT vl;
  3760. #if FF_STR_VOLUME_ID
  3761. const char *vid;
  3762. #endif
  3763. #endif
  3764. FILINFO fno;
  3765. DEF_NAMEBUFF
  3766. buff[0] = 0; /* A null str to get current drive */
  3767. res = mount_volume((const TCHAR**)&buff, &fs, 0);
  3768. if (res == FR_OK) {
  3769. dj.obj.fs = fs;
  3770. INIT_NAMEBUFF(fs);
  3771. #if FF_FS_EXFAT
  3772. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  3773. UINT wi = 0;
  3774. UINT di, ni;
  3775. #if FF_VOLUMES >= 2 /* Add drive prefix if needed */
  3776. #if FF_STR_VOLUME_ID == 0 /* Numeric volume ID */
  3777. if (wi < len) buff[wi++] = '0' + CurrVol;
  3778. #else /* String volume ID */
  3779. if (FF_STR_VOLUME_ID == 2 && wi < len) buff[wi++] = '/';
  3780. for (vid = (const char*)VolumeStr[CurrVol]; *vid && wi < len; buff[wi++] = *vid++) ;
  3781. #endif
  3782. if (FF_STR_VOLUME_ID <= 1 && wi < len) buff[wi++] = ':';
  3783. #endif
  3784. if (wi < len) buff[wi++] = '/';
  3785. for (di = 0; wi < len && di < fs->xcwds.depth; di++) { /* Follow current directory path with cwd structure */
  3786. dj.obj.sclust = fs->xcwds.tbl[di].d_scl; /* Open this directory */
  3787. dj.obj.stat = (BYTE)fs->xcwds.tbl[di].d_size;
  3788. dj.obj.objsize = fs->xcwds.tbl[di].d_size & 0xFFFFFF00;
  3789. res = dir_sdi(&dj, fs->xcwds.tbl[di].nxt_ofs); /* Find next directory */
  3790. if (res != FR_OK) break;
  3791. res = DIR_READ_FILE(&dj); /* Get the directory name */
  3792. if (res != FR_OK) break;
  3793. get_fileinfo(&dj, &fno);
  3794. if (di > 0 && wi < len) buff[wi++] = '/'; /* Add the directory name with a directory separator */
  3795. for (ni = 0; fno.fname[ni] && wi < len; buff[wi++] = fno.fname[ni++]) ;
  3796. }
  3797. if (wi == len) { /* Buffer overflow? */
  3798. res = FR_NOT_ENOUGH_CORE;
  3799. } else {
  3800. buff[wi] = 0; /* Terminate the string */
  3801. }
  3802. }
  3803. else
  3804. #endif
  3805. { /* On the FAT/FAT32 volume */
  3806. TCHAR *tp = buff;
  3807. UINT i, nl;
  3808. DWORD ccl;
  3809. /* Follow parent directories toward the root directory and create the cwd path */
  3810. i = len; /* Bottom of buffer (directory stack base) */
  3811. dj.obj.sclust = fs->cdir; /* Start to follow upper directory from current directory */
  3812. while ((ccl = dj.obj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
  3813. res = dir_sdi(&dj, 1 * SZDIRE); /* Get parent directory */
  3814. if (res != FR_OK) break;
  3815. res = move_window(fs, dj.sect);
  3816. if (res != FR_OK) break;
  3817. dj.obj.sclust = ld_clust(fs, dj.dir); /* Go to parent directory */
  3818. res = dir_sdi(&dj, 0);
  3819. if (res != FR_OK) break;
  3820. do { /* Find the entry links to this sub-directory */
  3821. res = DIR_READ_FILE(&dj);
  3822. if (res != FR_OK) break;
  3823. if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */
  3824. res = dir_next(&dj, 0);
  3825. } while (res == FR_OK);
  3826. if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be 'not found'. */
  3827. if (res != FR_OK) break;
  3828. get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
  3829. for (nl = 0; fno.fname[nl]; nl++) ; /* Name length */
  3830. if (i < nl + 1) { /* Insufficient space to store the path name? */
  3831. res = FR_NOT_ENOUGH_CORE; break;
  3832. }
  3833. while (nl) buff[--i] = fno.fname[--nl]; /* Stack the name */
  3834. buff[--i] = '/';
  3835. }
  3836. if (res == FR_OK) {
  3837. if (i == len) buff[--i] = '/'; /* Is it the root-directory? */
  3838. #if FF_VOLUMES >= 2 /* Put drive prefix */
  3839. vl = 0;
  3840. #if FF_STR_VOLUME_ID >= 1 /* String volume ID */
  3841. for (nl = 0, vid = (const char*)VolumeStr[CurrVol]; vid[nl]; nl++) ; /* Volume ID length */
  3842. if (i >= nl + 2) {
  3843. if (FF_STR_VOLUME_ID == 2) *tp++ = '/'; /* Unix style */
  3844. for (vl = 0; vl < nl; *tp++ = vid[vl], vl++) ;
  3845. if (FF_STR_VOLUME_ID == 1) *tp++ = ':'; /* DOS/Windows style */
  3846. vl++;
  3847. }
  3848. #else /* Numeric volume ID */
  3849. if (i >= 3) {
  3850. *tp++ = '0' + CurrVol;
  3851. *tp++ = ':';
  3852. vl = 2;
  3853. }
  3854. #endif
  3855. if (vl == 0) res = FR_NOT_ENOUGH_CORE;
  3856. #endif
  3857. /* Add current directory path */
  3858. if (res == FR_OK) {
  3859. do { /* Copy stacked path string */
  3860. *tp++ = buff[i++];
  3861. } while (i < len);
  3862. }
  3863. }
  3864. *tp = 0;
  3865. }
  3866. FREE_NAMEBUFF();
  3867. }
  3868. LEAVE_FF(fs, res);
  3869. }
  3870. #endif /* FF_FS_RPATH >= 2 */
  3871. #endif /* FF_FS_RPATH >= 1 */
  3872. #if FF_FS_MINIMIZE <= 2
  3873. /*-----------------------------------------------------------------------*/
  3874. /* API: Seek File Read/Write Pointer */
  3875. /*-----------------------------------------------------------------------*/
  3876. FRESULT f_lseek (
  3877. FIL* fp, /* Pointer to the file object */
  3878. FSIZE_t ofs /* File pointer from top of file */
  3879. )
  3880. {
  3881. FRESULT res;
  3882. FATFS *fs;
  3883. DWORD clst, bcs;
  3884. LBA_t nsect;
  3885. FSIZE_t ifptr;
  3886. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3887. if (res == FR_OK) res = (FRESULT)fp->err;
  3888. #if FF_FS_EXFAT && !FF_FS_READONLY
  3889. if (res == FR_OK && fs->fs_type == FS_EXFAT) {
  3890. res = fill_last_frag(&fp->obj, fp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
  3891. }
  3892. #endif
  3893. if (res != FR_OK) LEAVE_FF(fs, res);
  3894. #if FF_USE_FASTSEEK
  3895. if (fp->cltbl) { /* Fast seek */
  3896. DWORD cl, pcl, ncl, tcl, tlen, ulen;
  3897. DWORD *tbl;
  3898. LBA_t dsc;
  3899. if (ofs == CREATE_LINKMAP) { /* Create CLMT */
  3900. tbl = fp->cltbl;
  3901. tlen = *tbl++; ulen = 2; /* Given table size and required table size */
  3902. cl = fp->obj.sclust; /* Origin of the chain */
  3903. if (cl != 0) {
  3904. do {
  3905. /* Get a fragment */
  3906. tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
  3907. do {
  3908. pcl = cl; ncl++;
  3909. cl = get_fat(&fp->obj, cl);
  3910. if (cl <= 1) ABORT(fs, FR_INT_ERR);
  3911. if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3912. } while (cl == pcl + 1);
  3913. if (ulen <= tlen) { /* Store the length and top of the fragment */
  3914. *tbl++ = ncl; *tbl++ = tcl;
  3915. }
  3916. } while (cl < fs->n_fatent); /* Repeat until end of chain */
  3917. }
  3918. *fp->cltbl = ulen; /* Number of items used */
  3919. if (ulen <= tlen) {
  3920. *tbl = 0; /* Terminate table */
  3921. } else {
  3922. res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
  3923. }
  3924. } else { /* Fast seek */
  3925. if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
  3926. fp->fptr = ofs; /* Set file pointer */
  3927. if (ofs > 0) {
  3928. fp->clust = clmt_clust(fp, ofs - 1);
  3929. dsc = clst2sect(fs, fp->clust);
  3930. if (dsc == 0) ABORT(fs, FR_INT_ERR);
  3931. dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
  3932. if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
  3933. #if !FF_FS_TINY
  3934. #if !FF_FS_READONLY
  3935. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3936. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3937. fp->flag &= (BYTE)~FA_DIRTY;
  3938. }
  3939. #endif
  3940. if (disk_read(fs->pdrv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
  3941. #endif
  3942. fp->sect = dsc;
  3943. }
  3944. }
  3945. }
  3946. } else
  3947. #endif
  3948. /* Normal Seek */
  3949. {
  3950. #if FF_FS_EXFAT
  3951. if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4 GiB - 1 if at FATxx */
  3952. #endif
  3953. if (ofs > fp->obj.objsize && (FF_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
  3954. ofs = fp->obj.objsize;
  3955. }
  3956. ifptr = fp->fptr;
  3957. fp->fptr = nsect = 0;
  3958. if (ofs > 0) {
  3959. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
  3960. if (ifptr > 0 &&
  3961. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  3962. fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
  3963. ofs -= fp->fptr;
  3964. clst = fp->clust;
  3965. } else { /* When seek to back cluster, */
  3966. clst = fp->obj.sclust; /* start from the first cluster */
  3967. #if !FF_FS_READONLY
  3968. if (clst == 0) { /* If no cluster chain, create a new chain */
  3969. clst = create_chain(&fp->obj, 0);
  3970. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3971. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3972. fp->obj.sclust = clst;
  3973. }
  3974. #endif
  3975. fp->clust = clst;
  3976. }
  3977. if (clst != 0) {
  3978. while (ofs > bcs) { /* Cluster following loop */
  3979. ofs -= bcs; fp->fptr += bcs;
  3980. #if !FF_FS_READONLY
  3981. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  3982. if (FF_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
  3983. fp->obj.objsize = fp->fptr;
  3984. fp->flag |= FA_MODIFIED;
  3985. }
  3986. clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
  3987. if (clst == 0) { /* Clip file size in case of disk full */
  3988. ofs = 0; break;
  3989. }
  3990. } else
  3991. #endif
  3992. {
  3993. clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
  3994. }
  3995. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3996. if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
  3997. fp->clust = clst;
  3998. }
  3999. fp->fptr += ofs;
  4000. if (ofs % SS(fs)) {
  4001. nsect = clst2sect(fs, clst); /* Current sector */
  4002. if (nsect == 0) ABORT(fs, FR_INT_ERR);
  4003. nsect += (DWORD)(ofs / SS(fs));
  4004. }
  4005. }
  4006. }
  4007. if (!FF_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
  4008. fp->obj.objsize = fp->fptr;
  4009. fp->flag |= FA_MODIFIED;
  4010. }
  4011. if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
  4012. #if !FF_FS_TINY
  4013. #if !FF_FS_READONLY
  4014. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  4015. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4016. fp->flag &= (BYTE)~FA_DIRTY;
  4017. }
  4018. #endif
  4019. if (disk_read(fs->pdrv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  4020. #endif
  4021. fp->sect = nsect;
  4022. }
  4023. }
  4024. LEAVE_FF(fs, res);
  4025. }
  4026. #if FF_FS_MINIMIZE <= 1
  4027. /*-----------------------------------------------------------------------*/
  4028. /* API: Create a Directory Object */
  4029. /*-----------------------------------------------------------------------*/
  4030. FRESULT f_opendir (
  4031. DIR* dp, /* Pointer to directory object to create */
  4032. const TCHAR* path /* Pointer to the directory path */
  4033. )
  4034. {
  4035. FRESULT res;
  4036. FATFS *fs;
  4037. DEF_NAMEBUFF
  4038. if (!dp) return FR_INVALID_OBJECT; /* Reject null pointer */
  4039. res = mount_volume(&path, &fs, 0); /* Get logical drive and mount the volume if needed */
  4040. if (res == FR_OK) {
  4041. dp->obj.fs = fs;
  4042. INIT_NAMEBUFF(fs);
  4043. res = follow_path(dp, path); /* Follow the path to the directory */
  4044. if (res == FR_OK) { /* Follow completed */
  4045. if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is neither the origin directory itself nor dot name in exFAT */
  4046. if (dp->obj.attr & AM_DIR) { /* This object is a sub-directory */
  4047. #if FF_FS_EXFAT
  4048. if (fs->fs_type == FS_EXFAT) {
  4049. init_alloc_info(&dp->obj, dp); /* Get object allocation info */
  4050. } else
  4051. #endif
  4052. {
  4053. dp->obj.sclust = ld_clust(fs, dp->dir); /* Get object allocation info */
  4054. }
  4055. } else { /* This object is a file */
  4056. res = FR_NO_PATH;
  4057. }
  4058. }
  4059. if (res == FR_OK) {
  4060. dp->obj.id = fs->id; /* Set current volume mount ID */
  4061. res = dir_sdi(dp, 0); /* Rewind directory */
  4062. #if FF_FS_LOCK
  4063. if (res == FR_OK) {
  4064. if (dp->obj.sclust) { /* Is this a sub-directory? */
  4065. dp->obj.lockid = inc_share(dp, 0); /* Lock the sub-directory */
  4066. if (!dp->obj.lockid) res = FR_TOO_MANY_OPEN_FILES;
  4067. } else {
  4068. dp->obj.lockid = 0; /* Root directory does not need to be locked */
  4069. }
  4070. }
  4071. #endif
  4072. }
  4073. }
  4074. FREE_NAMEBUFF();
  4075. if (res == FR_NO_FILE) res = FR_NO_PATH;
  4076. }
  4077. if (res != FR_OK) dp->obj.fs = 0; /* Invalidate the directory object if function failed */
  4078. LEAVE_FF(fs, res);
  4079. }
  4080. /*-----------------------------------------------------------------------*/
  4081. /* API: Close Directory */
  4082. /*-----------------------------------------------------------------------*/
  4083. FRESULT f_closedir (
  4084. DIR *dp /* Pointer to the directory object to be closed */
  4085. )
  4086. {
  4087. FRESULT res;
  4088. FATFS *fs;
  4089. res = validate(&dp->obj, &fs); /* Check validity of the file object */
  4090. if (res == FR_OK) {
  4091. #if FF_FS_LOCK
  4092. if (dp->obj.lockid) res = dec_share(dp->obj.lockid); /* Decrement sub-directory open counter */
  4093. if (res == FR_OK) dp->obj.fs = 0; /* Invalidate directory object */
  4094. #else
  4095. dp->obj.fs = 0; /* Invalidate directory object */
  4096. #endif
  4097. #if FF_FS_REENTRANT
  4098. unlock_volume(fs, FR_OK); /* Unlock volume */
  4099. #endif
  4100. }
  4101. return res;
  4102. }
  4103. /*-----------------------------------------------------------------------*/
  4104. /* API: Read Directory Entries in Sequence */
  4105. /*-----------------------------------------------------------------------*/
  4106. FRESULT f_readdir (
  4107. DIR* dp, /* Pointer to the open directory object */
  4108. FILINFO* fno /* Pointer to file information to return */
  4109. )
  4110. {
  4111. FRESULT res;
  4112. FATFS *fs;
  4113. DEF_NAMEBUFF
  4114. res = validate(&dp->obj, &fs); /* Check validity of the directory object */
  4115. if (res == FR_OK) {
  4116. if (!fno) {
  4117. res = dir_sdi(dp, 0); /* Rewind the directory object */
  4118. } else {
  4119. INIT_NAMEBUFF(fs);
  4120. fno->fname[0] = 0; /* Clear file information */
  4121. res = DIR_READ_FILE(dp); /* Read an item */
  4122. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
  4123. if (res == FR_OK) { /* A valid entry is found */
  4124. get_fileinfo(dp, fno); /* Get the object information */
  4125. res = dir_next(dp, 0); /* Increment index for next */
  4126. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
  4127. }
  4128. FREE_NAMEBUFF();
  4129. }
  4130. }
  4131. if (fno && res != FR_OK) fno->fname[0] = 0; /* Clear the file information if any error occured */
  4132. LEAVE_FF(fs, res);
  4133. }
  4134. #if FF_USE_FIND
  4135. /*-----------------------------------------------------------------------*/
  4136. /* API: Find Next File */
  4137. /*-----------------------------------------------------------------------*/
  4138. FRESULT f_findnext (
  4139. DIR* dp, /* Pointer to the open directory object */
  4140. FILINFO* fno /* Pointer to the file information structure */
  4141. )
  4142. {
  4143. FRESULT res;
  4144. for (;;) {
  4145. res = f_readdir(dp, fno); /* Get a directory item */
  4146. if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
  4147. if (pattern_match(dp->pat, fno->fname, 0, FIND_RECURS)) break; /* Test for the file name */
  4148. #if FF_USE_LFN && FF_USE_FIND == 2
  4149. if (pattern_match(dp->pat, fno->altname, 0, FIND_RECURS)) break; /* Test for alternative name if exist */
  4150. #endif
  4151. }
  4152. return res;
  4153. }
  4154. /*-----------------------------------------------------------------------*/
  4155. /* API: Find First File */
  4156. /*-----------------------------------------------------------------------*/
  4157. FRESULT f_findfirst (
  4158. DIR* dp, /* Pointer to the blank directory object */
  4159. FILINFO* fno, /* Pointer to the file information structure */
  4160. const TCHAR* path, /* Pointer to the directory to open */
  4161. const TCHAR* pattern /* Pointer to the matching pattern */
  4162. )
  4163. {
  4164. FRESULT res;
  4165. dp->pat = pattern; /* Save pointer to pattern string */
  4166. res = f_opendir(dp, path); /* Open the target directory */
  4167. if (res == FR_OK) {
  4168. res = f_findnext(dp, fno); /* Find the first item */
  4169. }
  4170. return res;
  4171. }
  4172. #endif /* FF_USE_FIND */
  4173. #if FF_FS_MINIMIZE == 0
  4174. /*-----------------------------------------------------------------------*/
  4175. /* API: Get File Status */
  4176. /*-----------------------------------------------------------------------*/
  4177. FRESULT f_stat (
  4178. const TCHAR* path, /* Pointer to the file path */
  4179. FILINFO* fno /* Pointer to file information to return */
  4180. )
  4181. {
  4182. FRESULT res;
  4183. DIR dj;
  4184. DEF_NAMEBUFF
  4185. /* Get logical drive and mount the volume if needed */
  4186. res = mount_volume(&path, &dj.obj.fs, 0);
  4187. if (res == FR_OK) {
  4188. INIT_NAMEBUFF(dj.obj.fs);
  4189. res = follow_path(&dj, path); /* Follow the file path */
  4190. if (res == FR_OK) { /* Follow completed */
  4191. if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
  4192. res = FR_INVALID_NAME;
  4193. } else { /* Found an object */
  4194. if (fno) get_fileinfo(&dj, fno);
  4195. }
  4196. }
  4197. FREE_NAMEBUFF();
  4198. }
  4199. if (fno && res != FR_OK) fno->fname[0] = 0; /* Invalidate the file information if an error occured */
  4200. LEAVE_FF(dj.obj.fs, res);
  4201. }
  4202. #if !FF_FS_READONLY
  4203. /*-----------------------------------------------------------------------*/
  4204. /* API: Get Number of Free Clusters */
  4205. /*-----------------------------------------------------------------------*/
  4206. FRESULT f_getfree (
  4207. const TCHAR* path, /* Logical drive number */
  4208. DWORD* nclst, /* Pointer to a variable to return number of free clusters */
  4209. FATFS** fatfs /* Pointer to a pointer to return corresponding filesystem object */
  4210. )
  4211. {
  4212. FRESULT res;
  4213. FATFS *fs;
  4214. DWORD nfree, clst, stat;
  4215. LBA_t sect;
  4216. UINT i;
  4217. FFOBJID obj;
  4218. /* Get logical drive and mount the volume if needed */
  4219. res = mount_volume(&path, &fs, 0);
  4220. if (res == FR_OK) {
  4221. *fatfs = fs; /* Return ptr to the fs object */
  4222. /* If free_clst is valid, return it without full FAT scan */
  4223. if (fs->free_clst <= fs->n_fatent - 2) {
  4224. *nclst = fs->free_clst;
  4225. } else {
  4226. /* Scan FAT to obtain the correct free cluster count */
  4227. nfree = 0;
  4228. if (fs->fs_type == FS_FAT12) { /* FAT12: Scan bit field FAT entries */
  4229. clst = 2; obj.fs = fs;
  4230. do {
  4231. stat = get_fat(&obj, clst);
  4232. if (stat == 0xFFFFFFFF) {
  4233. res = FR_DISK_ERR; break;
  4234. }
  4235. if (stat == 1) {
  4236. res = FR_INT_ERR; break;
  4237. }
  4238. if (stat == 0) nfree++;
  4239. } while (++clst < fs->n_fatent);
  4240. } else {
  4241. #if FF_FS_EXFAT
  4242. if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan allocation bitmap */
  4243. BYTE bm;
  4244. UINT b;
  4245. clst = fs->n_fatent - 2; /* Number of clusters */
  4246. sect = fs->bitbase; /* Bitmap sector */
  4247. i = 0; /* Offset in the sector */
  4248. do { /* Counts numbuer of clear bits (free clusters) in the bitmap */
  4249. if (i == 0) { /* New sector? */
  4250. res = move_window(fs, sect++);
  4251. if (res != FR_OK) break;
  4252. }
  4253. for (b = 8, bm = ~fs->win[i]; b && clst; b--, clst--) { /* Count clear bits in a byte */
  4254. nfree += bm & 1;
  4255. bm >>= 1;
  4256. }
  4257. i = (i + 1) % SS(fs); /* Next byte */
  4258. } while (clst);
  4259. } else
  4260. #endif
  4261. { /* FAT16/32: Scan WORD/DWORD FAT entries */
  4262. clst = fs->n_fatent; /* Number of entries */
  4263. sect = fs->fatbase; /* Top of the FAT */
  4264. i = 0; /* Offset in the sector */
  4265. do { /* Counts numbuer of entries with zero in the FAT */
  4266. if (i == 0) { /* New sector? */
  4267. res = move_window(fs, sect++);
  4268. if (res != FR_OK) break;
  4269. }
  4270. if (fs->fs_type == FS_FAT16) {
  4271. if (ld_16(fs->win + i) == 0) nfree++; /* FAT16: Is this cluster free? */
  4272. i += 2; /* Next entry */
  4273. } else {
  4274. if ((ld_32(fs->win + i) & 0x0FFFFFFF) == 0) nfree++; /* FAT32: Is this cluster free? */
  4275. i += 4; /* Next entry */
  4276. }
  4277. i %= SS(fs);
  4278. } while (--clst);
  4279. }
  4280. }
  4281. if (res == FR_OK) { /* Update parameters if succeeded */
  4282. *nclst = nfree; /* Return the free clusters */
  4283. fs->free_clst = nfree; /* Now free cluster count is valid */
  4284. fs->fsi_flag |= 1; /* FAT32/exfAT : Allocation information is to be updated */
  4285. }
  4286. }
  4287. }
  4288. LEAVE_FF(fs, res);
  4289. }
  4290. /*-----------------------------------------------------------------------*/
  4291. /* API: Truncate File */
  4292. /*-----------------------------------------------------------------------*/
  4293. FRESULT f_truncate (
  4294. FIL* fp /* Pointer to the file object */
  4295. )
  4296. {
  4297. FRESULT res;
  4298. FATFS *fs;
  4299. DWORD ncl;
  4300. /* Check validity of the file object */
  4301. res = validate(&fp->obj, &fs);
  4302. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4303. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  4304. if (fp->fptr < fp->obj.objsize) { /* Process when fptr is not on the eof */
  4305. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  4306. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  4307. fp->obj.sclust = 0;
  4308. } else { /* When truncate a part of the file, remove remaining clusters */
  4309. ncl = get_fat(&fp->obj, fp->clust);
  4310. res = FR_OK;
  4311. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  4312. if (ncl == 1) res = FR_INT_ERR;
  4313. if (res == FR_OK && ncl < fs->n_fatent) {
  4314. res = remove_chain(&fp->obj, ncl, fp->clust);
  4315. }
  4316. }
  4317. fp->obj.objsize = fp->fptr; /* Set file size to current read/write point */
  4318. fp->flag |= FA_MODIFIED;
  4319. #if !FF_FS_TINY
  4320. if (res == FR_OK && (fp->flag & FA_DIRTY)) {
  4321. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) {
  4322. res = FR_DISK_ERR;
  4323. } else {
  4324. fp->flag &= (BYTE)~FA_DIRTY;
  4325. }
  4326. }
  4327. #endif
  4328. if (res != FR_OK) ABORT(fs, res);
  4329. }
  4330. LEAVE_FF(fs, res);
  4331. }
  4332. /*-----------------------------------------------------------------------*/
  4333. /* API: Delete a File/Directory */
  4334. /*-----------------------------------------------------------------------*/
  4335. FRESULT f_unlink (
  4336. const TCHAR* path /* Pointer to the file or directory path */
  4337. )
  4338. {
  4339. FRESULT res = 0;
  4340. FATFS *fs = NULL;
  4341. DIR dj = {0}, sdj = {0};
  4342. DWORD dclst = 0;
  4343. #if FF_FS_EXFAT
  4344. FFOBJID obj = {0};
  4345. #endif
  4346. DEF_NAMEBUFF
  4347. /* Get logical drive and mount the volume if needed */
  4348. res = mount_volume(&path, &fs, FA_WRITE);
  4349. if (res == FR_OK) {
  4350. dj.obj.fs = fs;
  4351. INIT_NAMEBUFF(fs);
  4352. res = follow_path(&dj, path); /* Follow the path to the object */
  4353. if (res == FR_OK) {
  4354. if (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME)) {
  4355. res = FR_INVALID_NAME; /* It must be a real object */
  4356. } else if (dj.obj.attr & AM_RDO) {
  4357. res = FR_DENIED; /* The object must not be read-only */
  4358. #if FF_FS_LOCK
  4359. } else {
  4360. res = chk_share(&dj, 2); /* Check if the object is in use */
  4361. #endif
  4362. }
  4363. }
  4364. if (res == FR_OK) { /* The object is accessible */
  4365. #if FF_FS_EXFAT
  4366. obj.fs = fs;
  4367. if (fs->fs_type == FS_EXFAT) {
  4368. init_alloc_info(&obj, 0);
  4369. dclst = obj.sclust;
  4370. } else
  4371. #endif
  4372. {
  4373. dclst = ld_clust(fs, dj.dir);
  4374. }
  4375. if (dj.obj.attr & AM_DIR) { /* Is the object a sub-directory? */
  4376. #if FF_FS_RPATH
  4377. if (dclst == fs->cdir) {
  4378. res = FR_DENIED; /* Current directory cannot be removed */
  4379. } else
  4380. #endif
  4381. {
  4382. sdj.obj.fs = fs; /* Open the sub-directory */
  4383. sdj.obj.sclust = dclst;
  4384. #if FF_FS_EXFAT
  4385. if (fs->fs_type == FS_EXFAT) {
  4386. sdj.obj.objsize = obj.objsize;
  4387. sdj.obj.stat = obj.stat;
  4388. }
  4389. #endif
  4390. res = dir_sdi(&sdj, 0);
  4391. if (res == FR_OK) {
  4392. res = DIR_READ_FILE(&sdj); /* Check if the sub-directory is empty */
  4393. if (res == FR_OK) res = FR_DENIED; /* Not empty? */
  4394. if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
  4395. }
  4396. }
  4397. }
  4398. }
  4399. if (res == FR_OK) { /* It is ready to remove the object */
  4400. res = dir_remove(&dj); /* Remove the directory entry */
  4401. if (res == FR_OK && dclst != 0) { /* Remove the cluster chain if exist */
  4402. #if FF_FS_EXFAT
  4403. res = remove_chain(&obj, dclst, 0);
  4404. #else
  4405. res = remove_chain(&dj.obj, dclst, 0);
  4406. #endif
  4407. }
  4408. if (res == FR_OK) res = sync_fs(fs);
  4409. }
  4410. FREE_NAMEBUFF();
  4411. }
  4412. LEAVE_FF(fs, res);
  4413. }
  4414. /*-----------------------------------------------------------------------*/
  4415. /* API: Create a Directory */
  4416. /*-----------------------------------------------------------------------*/
  4417. FRESULT f_mkdir (
  4418. const TCHAR* path /* Pointer to the directory path */
  4419. )
  4420. {
  4421. FRESULT res;
  4422. FATFS *fs;
  4423. DIR dj;
  4424. FFOBJID sobj;
  4425. DWORD dcl, pcl, tm;
  4426. DEF_NAMEBUFF
  4427. res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive and mount the volume if needed */
  4428. if (res == FR_OK) {
  4429. dj.obj.fs = fs;
  4430. INIT_NAMEBUFF(fs);
  4431. res = follow_path(&dj, path); /* Follow the file path */
  4432. if (res == FR_OK) { /* Invalid name or name collision */
  4433. res = (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME)) ? FR_INVALID_NAME : FR_EXIST;
  4434. }
  4435. if (res == FR_NO_FILE) { /* It is clear to create a new directory */
  4436. sobj.fs = fs; /* New object ID to create a new chain */
  4437. dcl = create_chain(&sobj, 0); /* Allocate a cluster for the new directory */
  4438. res = FR_OK;
  4439. if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster? */
  4440. if (dcl == 1) res = FR_INT_ERR; /* Any insanity? */
  4441. if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR; /* Disk error? */
  4442. tm = GET_FATTIME();
  4443. if (res == FR_OK) {
  4444. res = dir_clear(fs, dcl); /* Clear the allocated cluster as new direcotry table */
  4445. if (res == FR_OK) {
  4446. if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* Create dot entries (FAT only) */
  4447. memset(fs->win + DIR_Name, ' ', 11); /* Create "." entry */
  4448. fs->win[DIR_Name] = '.';
  4449. fs->win[DIR_Attr] = AM_DIR;
  4450. st_32(fs->win + DIR_ModTime, tm);
  4451. st_clust(fs, fs->win, dcl);
  4452. memcpy(fs->win + SZDIRE, fs->win, SZDIRE); /* Create ".." entry */
  4453. fs->win[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
  4454. st_clust(fs, fs->win + SZDIRE, pcl);
  4455. fs->wflag = 1;
  4456. }
  4457. res = dir_register(&dj); /* Register the object to the parent directory */
  4458. }
  4459. }
  4460. if (res == FR_OK) {
  4461. #if FF_FS_EXFAT
  4462. if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
  4463. st_32(fs->dirbuf + XDIR_CrtTime, tm); /* Created time */
  4464. st_32(fs->dirbuf + XDIR_ModTime, tm);
  4465. st_32(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
  4466. st_32(fs->dirbuf + XDIR_FileSize, (DWORD)fs->csize * SS(fs)); /* Directory size needs to be valid */
  4467. st_32(fs->dirbuf + XDIR_ValidFileSize, (DWORD)fs->csize * SS(fs));
  4468. fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag */
  4469. fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
  4470. res = store_xdir(&dj);
  4471. } else
  4472. #endif
  4473. {
  4474. st_32(dj.dir + DIR_CrtTime, tm); /* Created time */
  4475. st_32(dj.dir + DIR_ModTime, tm);
  4476. st_clust(fs, dj.dir, dcl); /* Table start cluster */
  4477. dj.dir[DIR_Attr] = AM_DIR; /* Attribute */
  4478. fs->wflag = 1;
  4479. }
  4480. if (res == FR_OK) {
  4481. res = sync_fs(fs);
  4482. }
  4483. } else {
  4484. remove_chain(&sobj, dcl, 0); /* Could not register, remove the allocated cluster */
  4485. }
  4486. }
  4487. FREE_NAMEBUFF();
  4488. }
  4489. LEAVE_FF(fs, res);
  4490. }
  4491. /*-----------------------------------------------------------------------*/
  4492. /* API: Rename a File/Directory */
  4493. /*-----------------------------------------------------------------------*/
  4494. FRESULT f_rename (
  4495. const TCHAR* path_old, /* Pointer to the object name to be renamed */
  4496. const TCHAR* path_new /* Pointer to the new name */
  4497. )
  4498. {
  4499. FRESULT res;
  4500. FATFS *fs;
  4501. DIR djo, djn;
  4502. BYTE buf[FF_FS_EXFAT ? SZDIRE * 2 : SZDIRE], *dir;
  4503. DEF_NAMEBUFF
  4504. get_ldnumber(&path_new); /* Snip the drive number of new name off */
  4505. res = mount_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */
  4506. if (res == FR_OK) {
  4507. djo.obj.fs = fs;
  4508. INIT_NAMEBUFF(fs);
  4509. res = follow_path(&djo, path_old); /* Check old object */
  4510. if (res == FR_OK) {
  4511. if (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME)) {
  4512. res = FR_INVALID_NAME; /* Object must not be a dot name or blank name */
  4513. #if FF_FS_LOCK
  4514. } else {
  4515. res = chk_share(&djo, 2); /* Check if the object is in use */
  4516. #endif
  4517. }
  4518. }
  4519. if (res == FR_OK) { /* It is ready to rename the object */
  4520. #if FF_FS_EXFAT
  4521. if (fs->fs_type == FS_EXFAT) { /* At exFAT volume */
  4522. #if FF_FS_RPATH
  4523. UINT i;
  4524. DWORD dscl = ld_32(fs->dirbuf + XDIR_FstClus);
  4525. for (i = 1; i <= fs->xcwds.depth && dscl != fs->xcwds.tbl[i].d_scl; i++) ; /* Check if the object is a sub-dir in the current dir path */
  4526. if (i <= fs->xcwds.depth) {
  4527. res = FR_DENIED; /* Reject to rename a sub-dir in the current dir path */
  4528. } else
  4529. #endif
  4530. {
  4531. memcpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
  4532. memcpy(&djn, &djo, sizeof djn);
  4533. res = follow_path(&djn, path_new); /* Check if new object name collides with an existing one */
  4534. }
  4535. if (res == FR_OK) { /* Is new name already in use by another object? */
  4536. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  4537. }
  4538. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  4539. res = dir_register(&djn); /* Register the new entry */
  4540. if (res == FR_OK) {
  4541. BYTE nf, nn;
  4542. WORD nh;
  4543. nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName]; /* Save name length and hash */
  4544. nh = ld_16(fs->dirbuf + XDIR_NameHash);
  4545. memcpy(fs->dirbuf, buf, SZDIRE * 2); /* Restore 85+C0 entry */
  4546. fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn; /* Restore name length and hash */
  4547. st_16(fs->dirbuf + XDIR_NameHash, nh);
  4548. if (!(fs->dirbuf[XDIR_Attr] & AM_DIR)) fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive attribute if it is a file */
  4549. /* Start of critical section where an interruption can cause a cross-link */
  4550. res = store_xdir(&djn);
  4551. }
  4552. }
  4553. } else
  4554. #endif
  4555. { /* At FAT/FAT32 volume */
  4556. memcpy(buf, djo.dir, SZDIRE); /* Save directory entry of the object */
  4557. memcpy(&djn, &djo, sizeof djn); /* Duplicate the directory object */
  4558. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  4559. if (res == FR_OK) { /* Is new name already in use by another object? */
  4560. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  4561. }
  4562. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  4563. res = dir_register(&djn); /* Register the new entry */
  4564. if (res == FR_OK) {
  4565. dir = djn.dir; /* Copy directory entry of the object except name */
  4566. memcpy(dir + 13, buf + 13, SZDIRE - 13);
  4567. dir[DIR_Attr] = buf[DIR_Attr];
  4568. if (!(dir[DIR_Attr] & AM_DIR)) dir[DIR_Attr] |= AM_ARC; /* Set archive attribute if it is a file */
  4569. fs->wflag = 1;
  4570. if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory being moved if needed */
  4571. LBA_t sect = clst2sect(fs, ld_clust(fs, dir));
  4572. if (sect == 0) {
  4573. res = FR_INT_ERR;
  4574. } else {
  4575. /* Start of critical section where an interruption can cause a cross-link */
  4576. res = move_window(fs, sect);
  4577. dir = fs->win + SZDIRE * 1; /* Pointer to .. entry */
  4578. if (res == FR_OK && dir[1] == '.') {
  4579. st_clust(fs, dir, djn.obj.sclust);
  4580. fs->wflag = 1;
  4581. }
  4582. }
  4583. }
  4584. }
  4585. }
  4586. }
  4587. if (res == FR_OK) { /* New entry has been created */
  4588. res = dir_remove(&djo); /* Remove old entry */
  4589. if (res == FR_OK) {
  4590. res = sync_fs(fs);
  4591. }
  4592. }
  4593. /* End of the critical section */
  4594. }
  4595. FREE_NAMEBUFF();
  4596. }
  4597. LEAVE_FF(fs, res);
  4598. }
  4599. #endif /* !FF_FS_READONLY */
  4600. #endif /* FF_FS_MINIMIZE == 0 */
  4601. #endif /* FF_FS_MINIMIZE <= 1 */
  4602. #endif /* FF_FS_MINIMIZE <= 2 */
  4603. #if FF_USE_CHMOD && !FF_FS_READONLY
  4604. /*-----------------------------------------------------------------------*/
  4605. /* API: Change Attribute */
  4606. /*-----------------------------------------------------------------------*/
  4607. FRESULT f_chmod (
  4608. const TCHAR* path, /* Pointer to the file path */
  4609. BYTE attr, /* Attribute bits to set/clear */
  4610. BYTE mask /* Attribute mask to change */
  4611. )
  4612. {
  4613. FRESULT res;
  4614. FATFS *fs;
  4615. DIR dj;
  4616. DEF_NAMEBUFF
  4617. /* Get logical drive and mount the volume if needed */
  4618. res = mount_volume(&path, &fs, FA_WRITE);
  4619. if (res == FR_OK) {
  4620. dj.obj.fs = fs;
  4621. INIT_NAMEBUFF(fs);
  4622. res = follow_path(&dj, path); /* Follow the file path */
  4623. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  4624. if (res == FR_OK) {
  4625. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  4626. #if FF_FS_EXFAT
  4627. if (fs->fs_type == FS_EXFAT) {
  4628. fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  4629. res = store_xdir(&dj);
  4630. } else
  4631. #endif
  4632. {
  4633. dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  4634. fs->wflag = 1;
  4635. }
  4636. if (res == FR_OK) {
  4637. res = sync_fs(fs);
  4638. }
  4639. }
  4640. FREE_NAMEBUFF();
  4641. }
  4642. LEAVE_FF(fs, res);
  4643. }
  4644. /*-----------------------------------------------------------------------*/
  4645. /* API: Change Timestamp */
  4646. /*-----------------------------------------------------------------------*/
  4647. FRESULT f_utime (
  4648. const TCHAR* path, /* Pointer to the file/directory name */
  4649. const FILINFO* fno /* Timestamp to be set */
  4650. )
  4651. {
  4652. FRESULT res;
  4653. FATFS *fs;
  4654. DIR dj;
  4655. DEF_NAMEBUFF
  4656. /* Get logical drive and mount the volume if needed */
  4657. res = mount_volume(&path, &fs, FA_WRITE);
  4658. if (res == FR_OK) {
  4659. dj.obj.fs = fs;
  4660. INIT_NAMEBUFF(fs);
  4661. res = follow_path(&dj, path); /* Follow the file path */
  4662. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  4663. if (res == FR_OK) {
  4664. #if FF_FS_EXFAT
  4665. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  4666. if (fno->fdate) { /* Change last modified time if needed */
  4667. st_32(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4668. fs->dirbuf[XDIR_ModTime10] = 0;
  4669. fs->dirbuf[XDIR_ModTZ] = 0;
  4670. }
  4671. #if FF_FS_CRTIME
  4672. if (fno->crdate) { /* Change created time if needed */
  4673. st_32(fs->dirbuf + XDIR_CrtTime, (DWORD)fno->crdate << 16 | fno->crtime);
  4674. fs->dirbuf[XDIR_CrtTime10] = 0;
  4675. fs->dirbuf[XDIR_CrtTZ] = 0;
  4676. }
  4677. #endif
  4678. res = store_xdir(&dj);
  4679. } else
  4680. #endif
  4681. { /* On the FAT volume */
  4682. if (fno->fdate) { /* Change last modified time if needed */
  4683. st_32(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4684. }
  4685. #if FF_FS_CRTIME
  4686. if (fno->crdate) { /* Change created time if needed */
  4687. st_32(dj.dir + DIR_CrtTime, (DWORD)fno->crdate << 16 | fno->crtime);
  4688. dj.dir[DIR_CrtTime10] = 0;
  4689. }
  4690. #endif
  4691. fs->wflag = 1;
  4692. }
  4693. if (res == FR_OK) {
  4694. res = sync_fs(fs);
  4695. }
  4696. }
  4697. FREE_NAMEBUFF();
  4698. }
  4699. LEAVE_FF(fs, res);
  4700. }
  4701. #endif /* FF_USE_CHMOD && !FF_FS_READONLY */
  4702. #if FF_USE_LABEL
  4703. /*-----------------------------------------------------------------------*/
  4704. /* API: Get Volume Label */
  4705. /*-----------------------------------------------------------------------*/
  4706. FRESULT f_getlabel (
  4707. const TCHAR* path, /* Logical drive number */
  4708. TCHAR* label, /* Buffer to store the volume label */
  4709. DWORD* vsn /* Variable to store the volume serial number */
  4710. )
  4711. {
  4712. FRESULT res;
  4713. FATFS *fs;
  4714. DIR dj;
  4715. UINT si, di;
  4716. WCHAR wc;
  4717. res = mount_volume(&path, &fs, 0); /* Get logical drive and mount the volume if needed */
  4718. /* Get volume label */
  4719. if (res == FR_OK && label) {
  4720. dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
  4721. res = dir_sdi(&dj, 0);
  4722. if (res == FR_OK) {
  4723. res = DIR_READ_LABEL(&dj); /* Find a volume label entry */
  4724. if (res == FR_OK) {
  4725. #if FF_FS_EXFAT
  4726. if (fs->fs_type == FS_EXFAT) {
  4727. WCHAR hs;
  4728. UINT nw;
  4729. for (si = di = hs = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
  4730. wc = ld_16(dj.dir + XDIR_Label + si * 2);
  4731. if (hs == 0 && IsSurrogate(wc)) { /* Is the code a surrogate? */
  4732. hs = wc; continue;
  4733. }
  4734. nw = put_utf((DWORD)hs << 16 | wc, &label[di], 4); /* Store it in API encoding */
  4735. if (nw == 0) { /* Encode error? */
  4736. di = 0; break;
  4737. }
  4738. di += nw;
  4739. hs = 0;
  4740. }
  4741. if (hs != 0) di = 0; /* Broken surrogate pair? */
  4742. label[di] = 0;
  4743. } else
  4744. #endif
  4745. {
  4746. si = di = 0; /* Extract volume label from AM_VOL entry */
  4747. while (si < 11) {
  4748. wc = dj.dir[si++];
  4749. #if FF_USE_LFN && FF_LFN_UNICODE >= 1 /* Unicode output */
  4750. if (dbc_1st((BYTE)wc) && si < 11) wc = wc << 8 | dj.dir[si++]; /* Is it a DBC? */
  4751. wc = ff_oem2uni(wc, CODEPAGE); /* Convert it into Unicode */
  4752. if (wc == 0) { /* Invalid char in current code page? */
  4753. di = 0; break;
  4754. }
  4755. di += put_utf(wc, &label[di], 4); /* Store it in Unicode */
  4756. #else /* ANSI/OEM output */
  4757. label[di++] = (TCHAR)wc;
  4758. #endif
  4759. }
  4760. do { /* Truncate trailing spaces */
  4761. label[di] = 0;
  4762. if (di == 0) break;
  4763. } while (label[--di] == ' ');
  4764. }
  4765. }
  4766. }
  4767. if (res == FR_NO_FILE) { /* No label entry and return nul string */
  4768. label[0] = 0;
  4769. res = FR_OK;
  4770. }
  4771. }
  4772. /* Get volume serial number */
  4773. if (res == FR_OK && vsn) {
  4774. res = move_window(fs, fs->volbase); /* Load VBR */
  4775. if (res == FR_OK) {
  4776. switch (fs->fs_type) {
  4777. case FS_EXFAT:
  4778. di = BPB_VolIDEx;
  4779. break;
  4780. case FS_FAT32:
  4781. di = BS_VolID32;
  4782. break;
  4783. default: /* FAT12/16 */
  4784. di = fs->win[BS_BootSig] == 0x29 ? BS_VolID : 0;
  4785. }
  4786. *vsn = di ? ld_32(fs->win + di) : 0; /* Get VSN in the VBR */
  4787. }
  4788. }
  4789. LEAVE_FF(fs, res);
  4790. }
  4791. #if !FF_FS_READONLY
  4792. /*-----------------------------------------------------------------------*/
  4793. /* API: Set Volume Label */
  4794. /*-----------------------------------------------------------------------*/
  4795. FRESULT f_setlabel (
  4796. const TCHAR* label /* Volume label to set with heading logical drive number */
  4797. )
  4798. {
  4799. FRESULT res;
  4800. FATFS *fs;
  4801. DIR dj;
  4802. BYTE dirvn[22];
  4803. UINT di;
  4804. WCHAR wc;
  4805. static const char badchr[18] = "+.,;=[]" "/*:<>|\\\"\?\x7F"; /* [0..16] for FAT, [7..16] for exFAT */
  4806. #if FF_USE_LFN
  4807. DWORD dc;
  4808. #endif
  4809. /* Get logical drive and mount the volume if needed */
  4810. res = mount_volume(&label, &fs, FA_WRITE);
  4811. if (res != FR_OK) LEAVE_FF(fs, res);
  4812. #if FF_STR_VOLUME_ID == 2
  4813. for ( ; *label == '/'; label++) ; /* Snip the separators off */
  4814. #endif
  4815. #if FF_FS_EXFAT
  4816. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  4817. memset(dirvn, 0, 22);
  4818. di = 0;
  4819. while ((UINT)*label >= ' ') { /* Create volume label */
  4820. dc = tchar2uni(&label); /* Get a Unicode character */
  4821. if (dc >= 0x10000) {
  4822. if (dc == 0xFFFFFFFF || di >= 10) { /* Wrong surrogate or buffer overflow */
  4823. dc = 0;
  4824. } else {
  4825. st_16(dirvn + di * 2, (WCHAR)(dc >> 16)); di++;
  4826. }
  4827. }
  4828. if (dc == 0 || strchr(&badchr[7], (int)dc) || di >= 11) { /* Check validity of the volume label */
  4829. LEAVE_FF(fs, FR_INVALID_NAME);
  4830. }
  4831. st_16(dirvn + di * 2, (WCHAR)dc); di++;
  4832. }
  4833. } else
  4834. #endif
  4835. { /* On the FAT/FAT32 volume */
  4836. memset(dirvn, ' ', 11);
  4837. di = 0;
  4838. while ((UINT)*label >= ' ') { /* Create volume label */
  4839. #if FF_USE_LFN
  4840. dc = tchar2uni(&label);
  4841. wc = (dc < 0x10000) ? ff_uni2oem(ff_wtoupper(dc), CODEPAGE) : 0;
  4842. #else /* ANSI/OEM input */
  4843. wc = (BYTE)*label++;
  4844. if (dbc_1st((BYTE)wc)) wc = dbc_2nd((BYTE)*label) ? wc << 8 | (BYTE)*label++ : 0;
  4845. if (IsLower(wc)) wc -= 0x20; /* To upper ASCII characters */
  4846. #if FF_CODE_PAGE == 0
  4847. if (ExCvt && wc >= 0x80) wc = ExCvt[wc - 0x80]; /* To upper extended characters (SBCS cfg) */
  4848. #elif FF_CODE_PAGE < 900
  4849. if (wc >= 0x80) wc = ExCvt[wc - 0x80]; /* To upper extended characters (SBCS cfg) */
  4850. #endif
  4851. #endif
  4852. if (wc == 0 || strchr(&badchr[0], (int)wc) || di >= (UINT)((wc >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
  4853. LEAVE_FF(fs, FR_INVALID_NAME);
  4854. }
  4855. if (wc >= 0x100) dirvn[di++] = (BYTE)(wc >> 8);
  4856. dirvn[di++] = (BYTE)wc;
  4857. }
  4858. if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
  4859. while (di && dirvn[di - 1] == ' ') di--; /* Snip trailing spaces */
  4860. }
  4861. /* Set volume label */
  4862. dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
  4863. res = dir_sdi(&dj, 0);
  4864. if (res == FR_OK) {
  4865. res = DIR_READ_LABEL(&dj); /* Get volume label entry */
  4866. if (res == FR_OK) {
  4867. if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4868. dj.dir[XDIR_NumLabel] = (BYTE)di; /* Change the volume label */
  4869. memcpy(dj.dir + XDIR_Label, dirvn, 22);
  4870. } else {
  4871. if (di != 0) {
  4872. memcpy(dj.dir, dirvn, 11); /* Change the volume label */
  4873. } else {
  4874. dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
  4875. }
  4876. }
  4877. fs->wflag = 1;
  4878. res = sync_fs(fs);
  4879. } else { /* No volume label entry or an error */
  4880. if (res == FR_NO_FILE) {
  4881. res = FR_OK;
  4882. if (di != 0) { /* Create a volume label entry */
  4883. res = dir_alloc(&dj, 1); /* Allocate an entry */
  4884. if (res == FR_OK) {
  4885. memset(dj.dir, 0, SZDIRE); /* Clean the entry */
  4886. if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4887. dj.dir[XDIR_Type] = ET_VLABEL; /* Create volume label entry */
  4888. dj.dir[XDIR_NumLabel] = (BYTE)di;
  4889. memcpy(dj.dir + XDIR_Label, dirvn, 22);
  4890. } else {
  4891. dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
  4892. memcpy(dj.dir, dirvn, 11);
  4893. }
  4894. fs->wflag = 1;
  4895. res = sync_fs(fs);
  4896. }
  4897. }
  4898. }
  4899. }
  4900. }
  4901. LEAVE_FF(fs, res);
  4902. }
  4903. #endif /* !FF_FS_READONLY */
  4904. #endif /* FF_USE_LABEL */
  4905. #if FF_USE_EXPAND && !FF_FS_READONLY
  4906. /*-----------------------------------------------------------------------*/
  4907. /* API: Allocate a Contiguous Blocks to the File */
  4908. /*-----------------------------------------------------------------------*/
  4909. FRESULT f_expand (
  4910. FIL* fp, /* Pointer to the file object */
  4911. FSIZE_t fsz, /* File size to be expanded to */
  4912. BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
  4913. )
  4914. {
  4915. FRESULT res;
  4916. FATFS *fs;
  4917. DWORD n, clst, stcl, scl, ncl, tcl, lclst;
  4918. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4919. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4920. if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
  4921. #if FF_FS_EXFAT
  4922. if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
  4923. #endif
  4924. n = (DWORD)fs->csize * SS(fs); /* Cluster size */
  4925. tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
  4926. stcl = fs->last_clst; lclst = 0;
  4927. if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
  4928. #if FF_FS_EXFAT
  4929. if (fs->fs_type == FS_EXFAT) {
  4930. scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
  4931. if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
  4932. if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
  4933. if (res == FR_OK) { /* A contiguous free area is found */
  4934. if (opt) { /* Allocate it now */
  4935. res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
  4936. lclst = scl + tcl - 1;
  4937. } else { /* Set it as suggested point for next allocation */
  4938. lclst = scl - 1;
  4939. }
  4940. }
  4941. } else
  4942. #endif
  4943. {
  4944. scl = clst = stcl; ncl = 0;
  4945. for (;;) { /* Find a contiguous cluster block */
  4946. n = get_fat(&fp->obj, clst);
  4947. if (++clst >= fs->n_fatent) clst = 2;
  4948. if (n == 1) {
  4949. res = FR_INT_ERR; break;
  4950. }
  4951. if (n == 0xFFFFFFFF) {
  4952. res = FR_DISK_ERR; break;
  4953. }
  4954. if (n == 0) { /* Is it a free cluster? */
  4955. if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
  4956. } else {
  4957. scl = clst; ncl = 0; /* Not a free cluster */
  4958. }
  4959. if (clst == stcl) { /* No contiguous cluster? */
  4960. res = FR_DENIED; break;
  4961. }
  4962. }
  4963. if (res == FR_OK) { /* A contiguous free area is found */
  4964. if (opt) { /* Allocate it now */
  4965. for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
  4966. res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
  4967. if (res != FR_OK) break;
  4968. lclst = clst;
  4969. }
  4970. } else { /* Set it as suggested point for next allocation */
  4971. lclst = scl - 1;
  4972. }
  4973. }
  4974. }
  4975. if (res == FR_OK) {
  4976. fs->last_clst = lclst; /* Set suggested start cluster to start next */
  4977. if (opt) { /* Is it allocated now? */
  4978. fp->obj.sclust = scl; /* Update object allocation information */
  4979. fp->obj.objsize = fsz;
  4980. if (FF_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
  4981. fp->flag |= FA_MODIFIED;
  4982. if (fs->free_clst <= fs->n_fatent - 2) { /* Update FSINFO */
  4983. fs->free_clst -= tcl;
  4984. fs->fsi_flag |= 1;
  4985. }
  4986. }
  4987. }
  4988. LEAVE_FF(fs, res);
  4989. }
  4990. #endif /* FF_USE_EXPAND && !FF_FS_READONLY */
  4991. #if FF_USE_FORWARD
  4992. /*-----------------------------------------------------------------------*/
  4993. /* API: Forward Data to the Stream Directly */
  4994. /*-----------------------------------------------------------------------*/
  4995. FRESULT f_forward (
  4996. FIL* fp, /* Pointer to the file object */
  4997. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  4998. UINT btf, /* Number of bytes to forward */
  4999. UINT* bf /* Pointer to number of bytes forwarded */
  5000. )
  5001. {
  5002. FRESULT res;
  5003. FATFS *fs;
  5004. DWORD clst;
  5005. LBA_t sect;
  5006. FSIZE_t remain;
  5007. UINT rcnt, csect;
  5008. BYTE *dbuf;
  5009. *bf = 0; /* Clear transfer byte counter */
  5010. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  5011. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  5012. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  5013. remain = fp->obj.objsize - fp->fptr;
  5014. if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
  5015. for ( ; btf > 0 && (*func)(0, 0); fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) { /* Repeat until all data transferred or stream goes busy */
  5016. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  5017. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  5018. if (csect == 0) { /* On the cluster boundary? */
  5019. clst = (fp->fptr == 0) ? /* On the top of the file? */
  5020. fp->obj.sclust : get_fat(&fp->obj, fp->clust);
  5021. if (clst <= 1) ABORT(fs, FR_INT_ERR);
  5022. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  5023. fp->clust = clst; /* Update current cluster */
  5024. }
  5025. }
  5026. sect = clst2sect(fs, fp->clust); /* Get current data sector */
  5027. if (sect == 0) ABORT(fs, FR_INT_ERR);
  5028. sect += csect;
  5029. #if FF_FS_TINY
  5030. if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
  5031. dbuf = fs->win;
  5032. #else
  5033. if (fp->sect != sect) { /* Fill sector cache with file data */
  5034. #if !FF_FS_READONLY
  5035. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  5036. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  5037. fp->flag &= (BYTE)~FA_DIRTY;
  5038. }
  5039. #endif
  5040. if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  5041. }
  5042. dbuf = fp->buf;
  5043. #endif
  5044. fp->sect = sect;
  5045. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
  5046. if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
  5047. rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
  5048. if (rcnt == 0) ABORT(fs, FR_INT_ERR);
  5049. }
  5050. LEAVE_FF(fs, FR_OK);
  5051. }
  5052. #endif /* FF_USE_FORWARD */
  5053. #if !FF_FS_READONLY && FF_USE_MKFS
  5054. /*-----------------------------------------------------------------------*/
  5055. /* API: Create FAT/exFAT volume (with a sub-function) */
  5056. /*-----------------------------------------------------------------------*/
  5057. #define N_SEC_TRACK 63 /* Sectors per track for determination of drive CHS */
  5058. #define GPT_ALIGN 0x100000 /* Alignment of partitions in GPT [byte] (>=128KB) */
  5059. #define GPT_ITEMS 128 /* Number of GPT table items (>=128, sector aligned) */
  5060. /* Create partitions on the physical drive in format of MBR or GPT */
  5061. static FRESULT create_partition (
  5062. BYTE drv, /* Physical drive number */
  5063. const LBA_t plst[], /* Partition list */
  5064. BYTE sys, /* System ID for each partition (for only MBR) */
  5065. BYTE *buf /* Working buffer for a sector */
  5066. )
  5067. {
  5068. UINT i, cy;
  5069. LBA_t sz_drv;
  5070. DWORD sz_drv32, nxt_alloc32, sz_part32;
  5071. BYTE *pte;
  5072. BYTE hd, n_hd, sc, n_sc;
  5073. /* Get physical drive size */
  5074. if (disk_ioctl(drv, GET_SECTOR_COUNT, &sz_drv) != RES_OK) return FR_DISK_ERR;
  5075. #if FF_LBA64
  5076. if (sz_drv >= FF_MIN_GPT) { /* Create partitions in GPT format */
  5077. WORD ss;
  5078. UINT sz_ptbl, pi, si, ofs;
  5079. DWORD bcc, rnd, align;
  5080. QWORD nxt_alloc, sz_part, sz_pool, top_bpt;
  5081. static const BYTE gpt_mbr[16] = {0x00, 0x00, 0x02, 0x00, 0xEE, 0xFE, 0xFF, 0x00, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF};
  5082. #if FF_MAX_SS != FF_MIN_SS
  5083. if (disk_ioctl(drv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR; /* Get sector size */
  5084. if (ss > FF_MAX_SS || ss < FF_MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
  5085. #else
  5086. ss = FF_MAX_SS;
  5087. #endif
  5088. rnd = (DWORD)sz_drv + GET_FATTIME(); /* Random seed */
  5089. align = GPT_ALIGN / ss; /* Partition alignment for GPT [sector] */
  5090. sz_ptbl = GPT_ITEMS * SZ_GPTE / ss; /* Size of partition table [sector] */
  5091. top_bpt = sz_drv - sz_ptbl - 1; /* Backup partition table start LBA */
  5092. nxt_alloc = 2 + sz_ptbl; /* First allocatable LBA */
  5093. sz_pool = top_bpt - nxt_alloc; /* Size of allocatable area [sector] */
  5094. bcc = 0xFFFFFFFF; sz_part = 1;
  5095. pi = si = 0; /* partition table index, map index */
  5096. do {
  5097. if (pi * SZ_GPTE % ss == 0) memset(buf, 0, ss); /* Clean the buffer if needed */
  5098. if (sz_part != 0) { /* Is the size table not termintated? */
  5099. nxt_alloc = (nxt_alloc + align - 1) & ((QWORD)0 - align); /* Align partition start LBA */
  5100. sz_part = plst[si++]; /* Get a partition size */
  5101. if (sz_part <= 100) { /* Is the size in percentage? */
  5102. sz_part = sz_pool * sz_part / 100; /* Sectors in percentage */
  5103. sz_part = (sz_part + align - 1) & ((QWORD)0 - align); /* Align partition end LBA (only if in percentage) */
  5104. }
  5105. if (nxt_alloc + sz_part > top_bpt) { /* Clip the size at end of the pool */
  5106. sz_part = (nxt_alloc < top_bpt) ? top_bpt - nxt_alloc : 0;
  5107. }
  5108. }
  5109. if (sz_part != 0) { /* Add a partition? */
  5110. ofs = pi * SZ_GPTE % ss;
  5111. memcpy(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16); /* Set partition GUID (Microsoft Basic Data) */
  5112. rnd = make_rand(rnd, buf + ofs + GPTE_UpGuid, 16); /* Set unique partition GUID */
  5113. st_64(buf + ofs + GPTE_FstLba, nxt_alloc); /* Set partition start LBA */
  5114. st_64(buf + ofs + GPTE_LstLba, nxt_alloc + sz_part - 1); /* Set partition end LBA */
  5115. nxt_alloc += sz_part; /* Next allocatable LBA */
  5116. }
  5117. if ((pi + 1) * SZ_GPTE % ss == 0) { /* Write the sector buffer if it is filled up */
  5118. for (i = 0; i < ss; bcc = crc32(bcc, buf[i++])) ; /* Calculate table check sum */
  5119. if (disk_write(drv, buf, 2 + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Write to primary table */
  5120. if (disk_write(drv, buf, top_bpt + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Write to secondary table */
  5121. }
  5122. } while (++pi < GPT_ITEMS);
  5123. /* Create primary GPT header */
  5124. memset(buf, 0, ss);
  5125. memcpy(buf + GPTH_Sign, "EFI PART" "\0\0\1\0" "\x5C\0\0", 16); /* Signature, version (1.0) and size (92) */
  5126. st_32(buf + GPTH_PtBcc, ~bcc); /* Table check sum */
  5127. st_64(buf + GPTH_CurLba, 1); /* LBA of this header */
  5128. st_64(buf + GPTH_BakLba, sz_drv - 1); /* LBA of secondary header */
  5129. st_64(buf + GPTH_FstLba, 2 + sz_ptbl); /* LBA of first allocatable sector */
  5130. st_64(buf + GPTH_LstLba, top_bpt - 1); /* LBA of last allocatable sector */
  5131. st_32(buf + GPTH_PteSize, SZ_GPTE); /* Size of a table entry */
  5132. st_32(buf + GPTH_PtNum, GPT_ITEMS); /* Number of table entries */
  5133. st_32(buf + GPTH_PtOfs, 2); /* LBA of this table */
  5134. rnd = make_rand(rnd, buf + GPTH_DskGuid, 16); /* Disk GUID */
  5135. for (i = 0, bcc= 0xFFFFFFFF; i < 92; bcc = crc32(bcc, buf[i++])) ; /* Calculate header check sum */
  5136. st_32(buf + GPTH_Bcc, ~bcc); /* Header check sum */
  5137. if (disk_write(drv, buf, 1, 1) != RES_OK) return FR_DISK_ERR;
  5138. /* Create secondary GPT header */
  5139. st_64(buf + GPTH_CurLba, sz_drv - 1); /* LBA of this header */
  5140. st_64(buf + GPTH_BakLba, 1); /* LBA of primary header */
  5141. st_64(buf + GPTH_PtOfs, top_bpt); /* LBA of this table */
  5142. st_32(buf + GPTH_Bcc, 0);
  5143. for (i = 0, bcc= 0xFFFFFFFF; i < 92; bcc = crc32(bcc, buf[i++])) ; /* Calculate header check sum */
  5144. st_32(buf + GPTH_Bcc, ~bcc); /* Header check sum */
  5145. if (disk_write(drv, buf, sz_drv - 1, 1) != RES_OK) return FR_DISK_ERR;
  5146. /* Create protective MBR */
  5147. memset(buf, 0, ss);
  5148. memcpy(buf + MBR_Table, gpt_mbr, 16); /* Create a GPT partition */
  5149. st_16(buf + BS_55AA, 0xAA55);
  5150. if (disk_write(drv, buf, 0, 1) != RES_OK) return FR_DISK_ERR;
  5151. } else
  5152. #endif
  5153. { /* Create partitions in MBR format */
  5154. sz_drv32 = (DWORD)sz_drv;
  5155. n_sc = N_SEC_TRACK; /* Determine drive CHS without any consideration of the drive geometry */
  5156. for (n_hd = 8; n_hd != 0 && sz_drv32 / n_hd / n_sc > 1024; n_hd *= 2) ;
  5157. if (n_hd == 0) n_hd = 255; /* Number of heads needs to be <256 */
  5158. memset(buf, 0, FF_MAX_SS); /* Clear MBR */
  5159. pte = buf + MBR_Table; /* Partition table in the MBR */
  5160. for (i = 0, nxt_alloc32 = n_sc; i < 4 && nxt_alloc32 != 0 && nxt_alloc32 < sz_drv32; i++, nxt_alloc32 += sz_part32) {
  5161. sz_part32 = (DWORD)plst[i]; /* Get partition size */
  5162. if (sz_part32 <= 100) sz_part32 = (sz_part32 == 100) ? sz_drv32 : sz_drv32 / 100 * sz_part32; /* Size in percentage? */
  5163. if (nxt_alloc32 + sz_part32 > sz_drv32 || nxt_alloc32 + sz_part32 < nxt_alloc32) sz_part32 = sz_drv32 - nxt_alloc32; /* Clip at drive size */
  5164. if (sz_part32 == 0) break; /* End of table or no sector to allocate? */
  5165. st_32(pte + PTE_StLba, nxt_alloc32); /* Partition start LBA sector */
  5166. st_32(pte + PTE_SizLba, sz_part32); /* Size of partition [sector] */
  5167. pte[PTE_System] = sys; /* System type */
  5168. cy = (UINT)(nxt_alloc32 / n_sc / n_hd); /* Partitio start CHS cylinder */
  5169. hd = (BYTE)(nxt_alloc32 / n_sc % n_hd); /* Partition start CHS head */
  5170. sc = (BYTE)(nxt_alloc32 % n_sc + 1); /* Partition start CHS sector */
  5171. pte[PTE_StHead] = hd;
  5172. pte[PTE_StSec] = (BYTE)((cy >> 2 & 0xC0) | sc);
  5173. pte[PTE_StCyl] = (BYTE)cy;
  5174. cy = (UINT)((nxt_alloc32 + sz_part32 - 1) / n_sc / n_hd); /* Partition end CHS cylinder */
  5175. hd = (BYTE)((nxt_alloc32 + sz_part32 - 1) / n_sc % n_hd); /* Partition end CHS head */
  5176. sc = (BYTE)((nxt_alloc32 + sz_part32 - 1) % n_sc + 1); /* Partition end CHS sector */
  5177. pte[PTE_EdHead] = hd;
  5178. pte[PTE_EdSec] = (BYTE)((cy >> 2 & 0xC0) | sc);
  5179. pte[PTE_EdCyl] = (BYTE)cy;
  5180. pte += SZ_PTE; /* Next entry */
  5181. }
  5182. st_16(buf + BS_55AA, 0xAA55); /* MBR signature */
  5183. if (disk_write(drv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
  5184. }
  5185. return FR_OK;
  5186. }
  5187. FRESULT f_mkfs (
  5188. const TCHAR* path, /* Logical drive number */
  5189. const MKFS_PARM* opt, /* Format options */
  5190. void* work, /* Pointer to working buffer (null: use len bytes of heap memory) */
  5191. UINT len /* Size of working buffer [byte] */
  5192. )
  5193. {
  5194. static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT volume (4K sector unit) */
  5195. static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128K sector unit) */
  5196. static const MKFS_PARM defopt = {FM_ANY, 0, 0, 0, 0}; /* Default parameter */
  5197. BYTE fsopt, fsty, sys, pdrv, ipart;
  5198. BYTE *buf;
  5199. BYTE *pte;
  5200. WORD ss; /* Sector size */
  5201. DWORD sz_buf, sz_blk, n_clst, pau, nsect, n, vsn;
  5202. LBA_t sz_vol, b_vol, b_fat, b_data; /* Volume size, base LBA of volume, base LBA of FAT and base LBA of data */
  5203. LBA_t sect, lba[2];
  5204. DWORD sz_rsv, sz_fat, sz_dir, sz_au; /* Size of reserved area, FAT area, directry area, data area and cluster */
  5205. UINT n_fat, n_root, i; /* Number of FATs, number of roor directory entries and some index */
  5206. int vol;
  5207. DSTATUS ds;
  5208. FRESULT res;
  5209. /* Check mounted drive and clear work area */
  5210. vol = get_ldnumber(&path); /* Get logical drive number to be formatted */
  5211. if (vol < 0) return FR_INVALID_DRIVE;
  5212. if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear the fs object if mounted */
  5213. pdrv = LD2PD(vol); /* Hosting physical drive */
  5214. ipart = LD2PT(vol); /* Hosting partition (0:create as new, 1..:existing partition) */
  5215. /* Initialize the hosting physical drive */
  5216. ds = disk_initialize(pdrv);
  5217. if (ds & STA_NOINIT) return FR_NOT_READY;
  5218. if (ds & STA_PROTECT) return FR_WRITE_PROTECTED;
  5219. /* Get physical drive parameters (sz_drv, sz_blk and ss) */
  5220. if (!opt) opt = &defopt; /* Use default parameter if it is not given */
  5221. sz_blk = opt->align;
  5222. if (sz_blk == 0) disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk); /* Block size from the parameter or lower layer */
  5223. if (sz_blk == 0 || sz_blk > 0x8000 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Use default if the block size is invalid */
  5224. #if FF_MAX_SS != FF_MIN_SS
  5225. if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;
  5226. if (ss > FF_MAX_SS || ss < FF_MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
  5227. #else
  5228. ss = FF_MAX_SS;
  5229. #endif
  5230. /* Options for FAT sub-type and FAT parameters */
  5231. fsopt = opt->fmt & (FM_ANY | FM_SFD);
  5232. n_fat = (opt->n_fat >= 1 && opt->n_fat <= 2) ? opt->n_fat : 1;
  5233. n_root = (opt->n_root >= 1 && opt->n_root <= 32768 && (opt->n_root % (ss / SZDIRE)) == 0) ? opt->n_root : 512;
  5234. sz_au = (opt->au_size <= 0x1000000 && (opt->au_size & (opt->au_size - 1)) == 0) ? opt->au_size : 0;
  5235. sz_au /= ss; /* Byte --> Sector */
  5236. /* Get working buffer */
  5237. sz_buf = len / ss; /* Size of working buffer [sector] */
  5238. if (sz_buf == 0) return FR_NOT_ENOUGH_CORE;
  5239. buf = (BYTE*)work; /* Working buffer */
  5240. #if FF_USE_LFN == 3
  5241. if (!buf) buf = ff_memalloc(sz_buf * ss); /* Use heap memory for working buffer */
  5242. #endif
  5243. if (!buf) return FR_NOT_ENOUGH_CORE;
  5244. /* Determine where the volume to be located (b_vol, sz_vol) */
  5245. b_vol = sz_vol = 0;
  5246. if (FF_MULTI_PARTITION && ipart != 0) { /* Is the volume associated with any specific partition? */
  5247. /* Get partition location from the existing partition table */
  5248. if (disk_read(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Load MBR */
  5249. if (ld_16(buf + BS_55AA) != 0xAA55) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if MBR is valid */
  5250. #if FF_LBA64
  5251. if (buf[MBR_Table + PTE_System] == 0xEE) { /* GPT protective MBR? */
  5252. DWORD n_ent, ofs;
  5253. QWORD pt_lba;
  5254. /* Get the partition location from GPT */
  5255. if (disk_read(pdrv, buf, 1, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Load GPT header sector (next to MBR) */
  5256. if (!test_gpt_header(buf)) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if GPT header is valid */
  5257. n_ent = ld_32(buf + GPTH_PtNum); /* Number of entries */
  5258. pt_lba = ld_64(buf + GPTH_PtOfs); /* Table start sector */
  5259. ofs = i = 0;
  5260. while (n_ent) { /* Find MS Basic partition with order of ipart */
  5261. if (ofs == 0 && disk_read(pdrv, buf, pt_lba++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Get PT sector */
  5262. if (!memcmp(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16) && ++i == ipart) { /* MS basic data partition? */
  5263. b_vol = ld_64(buf + ofs + GPTE_FstLba);
  5264. sz_vol = ld_64(buf + ofs + GPTE_LstLba) - b_vol + 1;
  5265. break;
  5266. }
  5267. n_ent--; ofs = (ofs + SZ_GPTE) % ss; /* Next entry */
  5268. }
  5269. if (n_ent == 0) LEAVE_MKFS(FR_MKFS_ABORTED); /* Partition not found */
  5270. fsopt |= 0x80; /* Partitioning is in GPT */
  5271. } else
  5272. #endif
  5273. { /* Get the partition location from MBR partition table */
  5274. pte = buf + (MBR_Table + (ipart - 1) * SZ_PTE);
  5275. if (ipart > 4 || pte[PTE_System] == 0) LEAVE_MKFS(FR_MKFS_ABORTED); /* No partition? */
  5276. b_vol = ld_32(pte + PTE_StLba); /* Get volume start sector */
  5277. sz_vol = ld_32(pte + PTE_SizLba); /* Get volume size */
  5278. }
  5279. } else { /* The volume is associated with a physical drive */
  5280. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5281. if (!(fsopt & FM_SFD)) { /* To be partitioned? */
  5282. /* Create a single-partition on the drive in this function */
  5283. #if FF_LBA64
  5284. if (sz_vol >= FF_MIN_GPT) { /* Which partition type to create, MBR or GPT? */
  5285. fsopt |= 0x80; /* Partitioning is in GPT */
  5286. b_vol = GPT_ALIGN / ss; sz_vol -= b_vol + GPT_ITEMS * SZ_GPTE / ss + 1; /* Estimated partition offset and size */
  5287. } else
  5288. #endif
  5289. { /* Partitioning is in MBR */
  5290. if (sz_vol > N_SEC_TRACK) {
  5291. b_vol = N_SEC_TRACK; sz_vol -= b_vol; /* Estimated partition offset and size */
  5292. }
  5293. }
  5294. }
  5295. }
  5296. if (sz_vol < MIN_VOLUME) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if volume size is not too small */
  5297. /* Now start to create an FAT volume at b_vol and sz_vol */
  5298. do { /* Pre-determine the FAT type */
  5299. if (FF_FS_EXFAT && (fsopt & FM_EXFAT)) { /* exFAT possible? */
  5300. if ((fsopt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || sz_au > 128) { /* exFAT only, vol >= 64M sectors or sz_au > 128 sectors? */
  5301. fsty = FS_EXFAT; break;
  5302. }
  5303. }
  5304. #if FF_LBA64
  5305. if (sz_vol >= 0x100000000) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too large volume for FAT/FAT32 */
  5306. #endif
  5307. if (sz_au > 128) sz_au = 128; /* Invalid AU for FAT/FAT32? */
  5308. if (fsopt & FM_FAT32) { /* FAT32 possible? */
  5309. if (!(fsopt & FM_FAT)) { /* no-FAT? */
  5310. fsty = FS_FAT32; break;
  5311. }
  5312. }
  5313. if (!(fsopt & FM_FAT)) LEAVE_MKFS(FR_INVALID_PARAMETER); /* no-FAT? */
  5314. fsty = FS_FAT16;
  5315. } while (0);
  5316. vsn = (DWORD)sz_vol + GET_FATTIME(); /* VSN generated from current time and partition size */
  5317. #if FF_FS_EXFAT
  5318. if (fsty == FS_EXFAT) { /* Create an exFAT volume */
  5319. DWORD szb_bit, szb_case, sum, nbit, clu, clen[3];
  5320. WCHAR ch, si;
  5321. UINT j, st;
  5322. if (sz_vol < 0x1000) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume for exFAT? */
  5323. #if FF_USE_TRIM
  5324. lba[0] = b_vol; lba[1] = b_vol + sz_vol - 1; /* Inform storage device that the volume area may be erased */
  5325. disk_ioctl(pdrv, CTRL_TRIM, lba);
  5326. #endif
  5327. /* Determine FAT location, data location and number of clusters */
  5328. if (sz_au == 0) { /* AU auto-selection */
  5329. sz_au = 8;
  5330. if (sz_vol >= 0x80000) sz_au = 64; /* >= 512Ks */
  5331. if (sz_vol >= 0x4000000) sz_au = 256; /* >= 64Ms */
  5332. }
  5333. b_fat = b_vol + 32; /* FAT start at offset 32 */
  5334. sz_fat = (DWORD)((sz_vol / sz_au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */
  5335. b_data = (b_fat + sz_fat + sz_blk - 1) & ~((LBA_t)sz_blk - 1); /* Align data area to the erase block boundary */
  5336. if (b_data - b_vol >= sz_vol / 2) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume? */
  5337. n_clst = (DWORD)((sz_vol - (b_data - b_vol)) / sz_au); /* Number of clusters */
  5338. if (n_clst <16) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too few clusters? */
  5339. if (n_clst > MAX_EXFAT) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too many clusters? */
  5340. szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */
  5341. clen[0] = (szb_bit + sz_au * ss - 1) / (sz_au * ss); /* Number of allocation bitmap clusters */
  5342. /* Create a compressed up-case table */
  5343. sect = b_data + sz_au * clen[0]; /* Table start sector */
  5344. sum = 0; /* Table checksum to be stored in the 82 entry */
  5345. st = 0; si = 0; i = 0; j = 0; szb_case = 0;
  5346. do {
  5347. switch (st) {
  5348. case 0:
  5349. ch = (WCHAR)ff_wtoupper(si); /* Get an up-case char */
  5350. if (ch != si) {
  5351. si++; break; /* Store the up-case char if exist */
  5352. }
  5353. for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */
  5354. if (j >= 128) {
  5355. ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 chars */
  5356. }
  5357. st = 1; /* Do not compress short run */
  5358. /* FALLTHROUGH */
  5359. case 1:
  5360. ch = si++; /* Fill the short run */
  5361. if (--j == 0) st = 0;
  5362. break;
  5363. default:
  5364. ch = (WCHAR)j; si += (WCHAR)j; /* Number of chars to skip */
  5365. st = 0;
  5366. }
  5367. sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */
  5368. sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);
  5369. i += 2; szb_case += 2;
  5370. if (si == 0 || i == sz_buf * ss) { /* Write buffered data when buffer full or end of process */
  5371. n = (i + ss - 1) / ss;
  5372. if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5373. sect += n; i = 0;
  5374. }
  5375. } while (si);
  5376. clen[1] = (szb_case + sz_au * ss - 1) / (sz_au * ss); /* Number of up-case table clusters */
  5377. clen[2] = 1; /* Number of root directory clusters */
  5378. /* Initialize the allocation bitmap */
  5379. sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of bitmap sectors */
  5380. nbit = clen[0] + clen[1] + clen[2]; /* Number of clusters in-use by system (bitmap, up-case and root-dir) */
  5381. do {
  5382. memset(buf, 0, sz_buf * ss); /* Initialize bitmap buffer */
  5383. for (i = 0; nbit != 0 && i / 8 < sz_buf * ss; buf[i / 8] |= 1 << (i % 8), i++, nbit--) ; /* Mark used clusters */
  5384. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  5385. if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5386. sect += n; nsect -= n;
  5387. } while (nsect);
  5388. /* Initialize the FAT */
  5389. sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */
  5390. j = nbit = clu = 0;
  5391. do {
  5392. memset(buf, 0, sz_buf * ss); i = 0; /* Clear work area and reset write offset */
  5393. if (clu == 0) { /* Initialize FAT [0] and FAT[1] */
  5394. st_32(buf + i, 0xFFFFFFF8); i += 4; clu++;
  5395. st_32(buf + i, 0xFFFFFFFF); i += 4; clu++;
  5396. }
  5397. do { /* Create chains of bitmap, up-case and root directory */
  5398. while (nbit != 0 && i < sz_buf * ss) { /* Create a chain */
  5399. st_32(buf + i, (nbit > 1) ? clu + 1 : 0xFFFFFFFF);
  5400. i += 4; clu++; nbit--;
  5401. }
  5402. if (nbit == 0 && j < 3) nbit = clen[j++]; /* Get next chain length */
  5403. } while (nbit != 0 && i < sz_buf * ss);
  5404. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  5405. if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5406. sect += n; nsect -= n;
  5407. } while (nsect);
  5408. /* Initialize the root directory */
  5409. memset(buf, 0, sz_buf * ss);
  5410. buf[SZDIRE * 0 + 0] = ET_VLABEL; /* Volume label entry (no label) */
  5411. buf[SZDIRE * 1 + 0] = ET_BITMAP; /* Bitmap entry */
  5412. st_32(buf + SZDIRE * 1 + 20, 2); /* cluster */
  5413. st_32(buf + SZDIRE * 1 + 24, szb_bit); /* size */
  5414. buf[SZDIRE * 2 + 0] = ET_UPCASE; /* Up-case table entry */
  5415. st_32(buf + SZDIRE * 2 + 4, sum); /* sum */
  5416. st_32(buf + SZDIRE * 2 + 20, 2 + clen[0]); /* cluster */
  5417. st_32(buf + SZDIRE * 2 + 24, szb_case); /* size */
  5418. sect = b_data + sz_au * (clen[0] + clen[1]); nsect = sz_au; /* Start of the root directory and number of sectors */
  5419. do { /* Fill root directory sectors */
  5420. n = (nsect > sz_buf) ? sz_buf : nsect;
  5421. if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5422. memset(buf, 0, ss); /* Rest of entries are filled with zero */
  5423. sect += n; nsect -= n;
  5424. } while (nsect);
  5425. /* Create two set of the exFAT VBR blocks */
  5426. sect = b_vol;
  5427. for (n = 0; n < 2; n++) {
  5428. /* Main record (+0) */
  5429. memset(buf, 0, ss);
  5430. memcpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
  5431. st_64(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */
  5432. st_64(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */
  5433. st_32(buf + BPB_FatOfsEx, (DWORD)(b_fat - b_vol)); /* FAT offset [sector] */
  5434. st_32(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */
  5435. st_32(buf + BPB_DataOfsEx, (DWORD)(b_data - b_vol)); /* Data offset [sector] */
  5436. st_32(buf + BPB_NumClusEx, n_clst); /* Number of clusters */
  5437. st_32(buf + BPB_RootClusEx, 2 + clen[0] + clen[1]); /* Root directory cluster number */
  5438. st_32(buf + BPB_VolIDEx, vsn); /* VSN */
  5439. st_16(buf + BPB_FSVerEx, 0x100); /* Filesystem version (1.00) */
  5440. for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */
  5441. for (buf[BPB_SecPerClusEx] = 0, i = sz_au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */
  5442. buf[BPB_NumFATsEx] = 1; /* Number of FATs */
  5443. buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */
  5444. st_16(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */
  5445. st_16(buf + BS_55AA, 0xAA55); /* Signature (placed here regardless of sector size) */
  5446. for (i = sum = 0; i < ss; i++) { /* VBR checksum */
  5447. if (i != BPB_VolFlagEx && i != BPB_VolFlagEx + 1 && i != BPB_PercInUseEx) sum = xsum32(buf[i], sum);
  5448. }
  5449. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5450. /* Extended bootstrap record (+1..+8) */
  5451. memset(buf, 0, ss);
  5452. st_16(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */
  5453. for (j = 1; j < 9; j++) {
  5454. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  5455. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5456. }
  5457. /* OEM/Reserved record (+9..+10) */
  5458. memset(buf, 0, ss);
  5459. for ( ; j < 11; j++) {
  5460. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  5461. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5462. }
  5463. /* Sum record (+11) */
  5464. for (i = 0; i < ss; i += 4) st_32(buf + i, sum); /* Fill with checksum value */
  5465. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5466. }
  5467. } else
  5468. #endif /* FF_FS_EXFAT */
  5469. { /* Create an FAT/FAT32 volume */
  5470. do {
  5471. pau = sz_au;
  5472. /* Pre-determine number of clusters and FAT sub-type */
  5473. if (fsty == FS_FAT32) { /* FAT32 volume */
  5474. if (pau == 0) { /* AU auto-selection */
  5475. n = (DWORD)sz_vol / 0x20000; /* Volume size in unit of 128KS */
  5476. for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */
  5477. }
  5478. n_clst = (DWORD)sz_vol / pau; /* Number of clusters */
  5479. sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */
  5480. sz_rsv = 32; /* Number of reserved sectors */
  5481. sz_dir = 0; /* No static directory */
  5482. if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) LEAVE_MKFS(FR_MKFS_ABORTED);
  5483. } else { /* FAT volume */
  5484. if (pau == 0) { /* au auto-selection */
  5485. n = (DWORD)sz_vol / 0x1000; /* Volume size in unit of 4KS */
  5486. for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */
  5487. }
  5488. n_clst = (DWORD)sz_vol / pau;
  5489. if (n_clst > MAX_FAT12) {
  5490. n = n_clst * 2 + 4; /* FAT size [byte] */
  5491. } else {
  5492. fsty = FS_FAT12;
  5493. n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */
  5494. }
  5495. sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */
  5496. sz_rsv = 1; /* Number of reserved sectors */
  5497. sz_dir = (DWORD)n_root * SZDIRE / ss; /* Root directory size [sector] */
  5498. }
  5499. b_fat = b_vol + sz_rsv; /* FAT base */
  5500. b_data = b_fat + sz_fat * n_fat + sz_dir; /* Data base */
  5501. /* Align data area to erase block boundary (for flash memory media) */
  5502. n = (DWORD)(((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data); /* Sectors to next nearest from current data base */
  5503. if (fsty == FS_FAT32) { /* FAT32: Move FAT */
  5504. sz_rsv += n; b_fat += n;
  5505. } else { /* FAT: Expand FAT */
  5506. if (n % n_fat) { /* Adjust fractional error if needed */
  5507. n--; sz_rsv++; b_fat++;
  5508. }
  5509. sz_fat += n / n_fat;
  5510. }
  5511. /* Determine number of clusters and final check of validity of the FAT sub-type */
  5512. if (sz_vol < b_data + pau * MIN_FAT12 - b_vol) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume for this configuration? */
  5513. n_clst = ((DWORD)sz_vol - sz_rsv - sz_fat * n_fat - sz_dir) / pau;
  5514. if (fsty == FS_FAT32) {
  5515. if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32? */
  5516. if (sz_au == 0 && (sz_au = pau / 2) != 0) continue; /* Adjust cluster size and retry */
  5517. LEAVE_MKFS(FR_MKFS_ABORTED);
  5518. }
  5519. }
  5520. if (fsty == FS_FAT16) {
  5521. if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */
  5522. if (sz_au == 0 && (pau * 2) <= 64) {
  5523. sz_au = pau * 2; continue; /* Adjust cluster size and retry */
  5524. }
  5525. if ((fsopt & FM_FAT32)) {
  5526. fsty = FS_FAT32; continue; /* Switch type to FAT32 and retry */
  5527. }
  5528. if (sz_au == 0 && (sz_au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  5529. LEAVE_MKFS(FR_MKFS_ABORTED);
  5530. }
  5531. if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */
  5532. if (sz_au == 0 && (sz_au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  5533. LEAVE_MKFS(FR_MKFS_ABORTED);
  5534. }
  5535. }
  5536. if (fsty == FS_FAT12 && n_clst > MAX_FAT12) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too many clusters for FAT12 */
  5537. /* Ok, it is the valid cluster configuration */
  5538. break;
  5539. } while (1);
  5540. #if FF_USE_TRIM
  5541. lba[0] = b_vol; lba[1] = b_vol + sz_vol - 1; /* Inform storage device that the volume area may be erased */
  5542. disk_ioctl(pdrv, CTRL_TRIM, lba);
  5543. #endif
  5544. /* Create FAT VBR */
  5545. memset(buf, 0, ss);
  5546. memcpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11); /* Boot jump code (x86), OEM name */
  5547. st_16(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */
  5548. buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */
  5549. st_16(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */
  5550. buf[BPB_NumFATs] = (BYTE)n_fat; /* Number of FATs */
  5551. st_16(buf + BPB_RootEntCnt, (WORD)((fsty == FS_FAT32) ? 0 : n_root)); /* Number of root directory entries */
  5552. if (sz_vol < 0x10000) {
  5553. st_16(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */
  5554. } else {
  5555. st_32(buf + BPB_TotSec32, (DWORD)sz_vol); /* Volume size in 32-bit LBA */
  5556. }
  5557. buf[BPB_Media] = 0xF8; /* Media descriptor byte */
  5558. st_16(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */
  5559. st_16(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */
  5560. st_32(buf + BPB_HiddSec, (DWORD)b_vol); /* Volume offset in the physical drive [sector] */
  5561. if (fsty == FS_FAT32) {
  5562. st_32(buf + BS_VolID32, vsn); /* VSN */
  5563. st_32(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */
  5564. st_32(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */
  5565. st_16(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */
  5566. st_16(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */
  5567. buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */
  5568. buf[BS_BootSig32] = 0x29; /* Extended boot signature */
  5569. memcpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
  5570. } else {
  5571. st_32(buf + BS_VolID, vsn); /* VSN */
  5572. st_16(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */
  5573. buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */
  5574. buf[BS_BootSig] = 0x29; /* Extended boot signature */
  5575. memcpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
  5576. }
  5577. st_16(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
  5578. if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it to the VBR sector */
  5579. /* Create FSINFO record if needed */
  5580. if (fsty == FS_FAT32) {
  5581. disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */
  5582. memset(buf, 0, ss);
  5583. st_32(buf + FSI_LeadSig, 0x41615252);
  5584. st_32(buf + FSI_StrucSig, 0x61417272);
  5585. st_32(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
  5586. st_32(buf + FSI_Nxt_Free, 2); /* Last allocated cluster# */
  5587. st_16(buf + BS_55AA, 0xAA55);
  5588. disk_write(pdrv, buf, b_vol + 7, 1); /* Write backup FSINFO (VBR + 7) */
  5589. disk_write(pdrv, buf, b_vol + 1, 1); /* Write original FSINFO (VBR + 1) */
  5590. }
  5591. /* Initialize FAT area */
  5592. memset(buf, 0, sz_buf * ss);
  5593. sect = b_fat; /* FAT start sector */
  5594. for (i = 0; i < n_fat; i++) { /* Initialize FATs each */
  5595. if (fsty == FS_FAT32) {
  5596. st_32(buf + 0, 0xFFFFFFF8); /* FAT[0] */
  5597. st_32(buf + 4, 0xFFFFFFFF); /* FAT[1] */
  5598. st_32(buf + 8, 0x0FFFFFFF); /* FAT[2] (root directory at cluster# 2) */
  5599. } else {
  5600. st_32(buf + 0, (fsty == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* FAT[0] and FAT[1] */
  5601. }
  5602. nsect = sz_fat; /* Number of FAT sectors */
  5603. do { /* Fill FAT sectors */
  5604. n = (nsect > sz_buf) ? sz_buf : nsect;
  5605. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5606. memset(buf, 0, ss); /* Rest of FAT area is initially zero */
  5607. sect += n; nsect -= n;
  5608. } while (nsect);
  5609. }
  5610. /* Initialize root directory (fill with zero) */
  5611. nsect = (fsty == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */
  5612. do {
  5613. n = (nsect > sz_buf) ? sz_buf : nsect;
  5614. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5615. sect += n; nsect -= n;
  5616. } while (nsect);
  5617. }
  5618. /* A FAT volume has been created here */
  5619. /* Determine system ID in the MBR partition table */
  5620. if (FF_FS_EXFAT && fsty == FS_EXFAT) {
  5621. sys = 0x07; /* exFAT */
  5622. } else if (fsty == FS_FAT32) {
  5623. sys = 0x0C; /* FAT32X */
  5624. } else if (sz_vol >= 0x10000) {
  5625. sys = 0x06; /* FAT12/16 (large) */
  5626. } else if (fsty == FS_FAT16) {
  5627. sys = 0x04; /* FAT16 */
  5628. } else {
  5629. sys = 0x01; /* FAT12 */
  5630. }
  5631. /* Update partition information */
  5632. if (FF_MULTI_PARTITION && ipart != 0) { /* Volume is in the existing partition */
  5633. if (!FF_LBA64 || !(fsopt & 0x80)) { /* Is the partition in MBR? */
  5634. /* Update system ID in the partition table */
  5635. if (disk_read(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Read the MBR */
  5636. buf[MBR_Table + (ipart - 1) * SZ_PTE + PTE_System] = sys; /* Set system ID */
  5637. if (disk_write(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it back to the MBR */
  5638. }
  5639. } else { /* Volume as a new single partition */
  5640. if (!(fsopt & FM_SFD)) { /* Create partition table if not in SFD format */
  5641. lba[0] = sz_vol; lba[1] = 0;
  5642. res = create_partition(pdrv, lba, sys, buf);
  5643. if (res != FR_OK) LEAVE_MKFS(res);
  5644. }
  5645. }
  5646. if (disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5647. LEAVE_MKFS(FR_OK);
  5648. }
  5649. #if FF_MULTI_PARTITION
  5650. /*-----------------------------------------------------------------------*/
  5651. /* API: Create Partition Table on the Physical Drive */
  5652. /*-----------------------------------------------------------------------*/
  5653. FRESULT f_fdisk (
  5654. BYTE pdrv, /* Physical drive number */
  5655. const LBA_t ptbl[], /* Pointer to the size table for each partitions */
  5656. void* work /* Pointer to the working buffer (null: use heap memory) */
  5657. )
  5658. {
  5659. BYTE *buf = (BYTE*)work;
  5660. DSTATUS stat;
  5661. FRESULT res;
  5662. /* Initialize the physical drive */
  5663. stat = disk_initialize(pdrv);
  5664. if (stat & STA_NOINIT) return FR_NOT_READY;
  5665. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  5666. #if FF_USE_LFN == 3
  5667. if (!buf) buf = ff_memalloc(FF_MAX_SS); /* Use heap memory for working buffer */
  5668. #endif
  5669. if (!buf) return FR_NOT_ENOUGH_CORE;
  5670. res = create_partition(pdrv, ptbl, 0x07, buf); /* Create partitions (system ID is temporary setting and determined by f_mkfs) */
  5671. LEAVE_MKFS(res);
  5672. }
  5673. #endif /* FF_MULTI_PARTITION */
  5674. #endif /* !FF_FS_READONLY && FF_USE_MKFS */
  5675. #if FF_USE_STRFUNC
  5676. #if FF_USE_LFN && FF_LFN_UNICODE && (FF_STRF_ENCODE < 0 || FF_STRF_ENCODE > 3)
  5677. #error Wrong FF_STRF_ENCODE setting
  5678. #endif
  5679. /*-----------------------------------------------------------------------*/
  5680. /* API: Get a String from the File */
  5681. /*-----------------------------------------------------------------------*/
  5682. TCHAR* f_gets (
  5683. TCHAR* buff, /* Pointer to the buffer to store read string */
  5684. int len, /* Size of string buffer (items) */
  5685. FIL* fp /* Pointer to the file object */
  5686. )
  5687. {
  5688. int nc = 0;
  5689. TCHAR *p = buff;
  5690. BYTE s[4];
  5691. UINT rc;
  5692. DWORD dc;
  5693. #if FF_USE_LFN && FF_LFN_UNICODE && FF_STRF_ENCODE <= 2
  5694. WCHAR wc;
  5695. #endif
  5696. #if FF_USE_LFN && FF_LFN_UNICODE && FF_STRF_ENCODE == 3
  5697. UINT ct;
  5698. #endif
  5699. #if FF_USE_LFN && FF_LFN_UNICODE /* With code conversion (Unicode API) */
  5700. /* Make a room for the character and terminator */
  5701. if (FF_LFN_UNICODE == 1) len -= (FF_STRF_ENCODE == 0) ? 1 : 2;
  5702. if (FF_LFN_UNICODE == 2) len -= (FF_STRF_ENCODE == 0) ? 3 : 4;
  5703. if (FF_LFN_UNICODE == 3) len -= 1;
  5704. while (nc < len) {
  5705. #if FF_STRF_ENCODE == 0 /* Read a character in ANSI/OEM */
  5706. f_read(fp, s, 1, &rc); /* Get a code unit */
  5707. if (rc != 1) break; /* EOF? */
  5708. wc = s[0];
  5709. if (dbc_1st((BYTE)wc)) { /* DBC 1st byte? */
  5710. f_read(fp, s, 1, &rc); /* Get 2nd byte */
  5711. if (rc != 1 || !dbc_2nd(s[0])) continue; /* Wrong code? */
  5712. wc = wc << 8 | s[0];
  5713. }
  5714. dc = ff_oem2uni(wc, CODEPAGE); /* Convert ANSI/OEM into Unicode */
  5715. if (dc == 0) continue; /* Conversion error? */
  5716. #elif FF_STRF_ENCODE == 1 || FF_STRF_ENCODE == 2 /* Read a character in UTF-16LE/BE */
  5717. f_read(fp, s, 2, &rc); /* Get a code unit */
  5718. if (rc != 2) break; /* EOF? */
  5719. dc = (FF_STRF_ENCODE == 1) ? ld_16(s) : s[0] << 8 | s[1];
  5720. if (IsSurrogateL(dc)) continue; /* Broken surrogate pair? */
  5721. if (IsSurrogateH(dc)) { /* High surrogate? */
  5722. f_read(fp, s, 2, &rc); /* Get low surrogate */
  5723. if (rc != 2) break; /* EOF? */
  5724. wc = (FF_STRF_ENCODE == 1) ? ld_16(s) : s[0] << 8 | s[1];
  5725. if (!IsSurrogateL(wc)) continue; /* Broken surrogate pair? */
  5726. dc = ((dc & 0x3FF) + 0x40) << 10 | (wc & 0x3FF); /* Merge surrogate pair */
  5727. }
  5728. #else /* Read a character in UTF-8 */
  5729. f_read(fp, s, 1, &rc); /* Get a code unit */
  5730. if (rc != 1) break; /* EOF? */
  5731. dc = s[0];
  5732. if (dc >= 0x80) { /* Multi-byte sequence? */
  5733. ct = 0;
  5734. if ((dc & 0xE0) == 0xC0) { /* 2-byte sequence? */
  5735. dc &= 0x1F; ct = 1;
  5736. }
  5737. if ((dc & 0xF0) == 0xE0) { /* 3-byte sequence? */
  5738. dc &= 0x0F; ct = 2;
  5739. }
  5740. if ((dc & 0xF8) == 0xF0) { /* 4-byte sequence? */
  5741. dc &= 0x07; ct = 3;
  5742. }
  5743. if (ct == 0) continue;
  5744. f_read(fp, s, ct, &rc); /* Get trailing bytes */
  5745. if (rc != ct) break;
  5746. rc = 0;
  5747. do { /* Merge the byte sequence */
  5748. if ((s[rc] & 0xC0) != 0x80) break;
  5749. dc = dc << 6 | (s[rc] & 0x3F);
  5750. } while (++rc < ct);
  5751. if (rc != ct || dc < 0x80 || IsSurrogate(dc) || dc >= 0x110000) continue; /* Wrong encoding? */
  5752. }
  5753. #endif
  5754. /* A code point is available in dc to be output */
  5755. if (FF_USE_STRFUNC == 2 && dc == '\r') continue; /* Strip \r off if needed */
  5756. #if FF_LFN_UNICODE == 1 || FF_LFN_UNICODE == 3 /* Output it in UTF-16/32 encoding */
  5757. if (FF_LFN_UNICODE == 1 && dc >= 0x10000) { /* Out of BMP at UTF-16? */
  5758. *p++ = (TCHAR)(0xD800 | ((dc >> 10) - 0x40)); nc++; /* Make and output high surrogate */
  5759. dc = 0xDC00 | (dc & 0x3FF); /* Make low surrogate */
  5760. }
  5761. *p++ = (TCHAR)dc; nc++;
  5762. if (dc == '\n') break; /* End of line? */
  5763. #elif FF_LFN_UNICODE == 2 /* Output it in UTF-8 encoding */
  5764. if (dc < 0x80) { /* Single byte? */
  5765. *p++ = (TCHAR)dc;
  5766. nc++;
  5767. if (dc == '\n') break; /* End of line? */
  5768. } else if (dc < 0x800) { /* 2-byte sequence? */
  5769. *p++ = (TCHAR)(0xC0 | (dc >> 6 & 0x1F));
  5770. *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));
  5771. nc += 2;
  5772. } else if (dc < 0x10000) { /* 3-byte sequence? */
  5773. *p++ = (TCHAR)(0xE0 | (dc >> 12 & 0x0F));
  5774. *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F));
  5775. *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));
  5776. nc += 3;
  5777. } else { /* 4-byte sequence */
  5778. *p++ = (TCHAR)(0xF0 | (dc >> 18 & 0x07));
  5779. *p++ = (TCHAR)(0x80 | (dc >> 12 & 0x3F));
  5780. *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F));
  5781. *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));
  5782. nc += 4;
  5783. }
  5784. #endif
  5785. }
  5786. #else /* Byte-by-byte read without any conversion (ANSI/OEM API) */
  5787. len -= 1; /* Make a room for the terminator */
  5788. while (nc < len) {
  5789. f_read(fp, s, 1, &rc); /* Get a byte */
  5790. if (rc != 1) break; /* EOF? */
  5791. dc = s[0];
  5792. if (FF_USE_STRFUNC == 2 && dc == '\r') continue;
  5793. *p++ = (TCHAR)dc; nc++;
  5794. if (dc == '\n') break;
  5795. }
  5796. #endif
  5797. *p = 0; /* Terminate the string */
  5798. return nc ? buff : 0; /* When no data read due to EOF or error, return with error. */
  5799. }
  5800. #if !FF_FS_READONLY
  5801. #include <stdarg.h>
  5802. #define SZ_PUTC_BUF 64
  5803. #define SZ_NUM_BUF 32
  5804. /*-----------------------------------------------------------------------*/
  5805. /* API: Put a Character to the File (with sub-functions) */
  5806. /*-----------------------------------------------------------------------*/
  5807. /* Output buffer and work area */
  5808. typedef struct {
  5809. FIL *fp; /* Pointer to the writing file */
  5810. int idx, nchr; /* Write index of buf[] (-1:error), number of written encoding units */
  5811. #if FF_USE_LFN && FF_LFN_UNICODE == 1
  5812. WCHAR hs;
  5813. #elif FF_USE_LFN && FF_LFN_UNICODE == 2
  5814. BYTE bs[4];
  5815. UINT wi, ct;
  5816. #endif
  5817. BYTE buf[SZ_PUTC_BUF]; /* Write buffer */
  5818. } putbuff;
  5819. /* Buffered file write with code conversion */
  5820. static void putc_bfd (putbuff* pb, TCHAR c)
  5821. {
  5822. UINT n;
  5823. int i, nc;
  5824. #if FF_USE_LFN && FF_LFN_UNICODE
  5825. WCHAR hs, wc;
  5826. #if FF_LFN_UNICODE == 2
  5827. DWORD dc;
  5828. const TCHAR* tp;
  5829. #endif
  5830. #endif
  5831. if (FF_USE_STRFUNC == 2 && c == '\n') { /* LF -> CRLF conversion */
  5832. putc_bfd(pb, '\r');
  5833. }
  5834. i = pb->idx; /* Write index of pb->buf[] */
  5835. if (i < 0) return; /* In write error? */
  5836. nc = pb->nchr; /* Write unit counter */
  5837. #if FF_USE_LFN && FF_LFN_UNICODE
  5838. #if FF_LFN_UNICODE == 1 /* UTF-16 input */
  5839. if (IsSurrogateH(c)) { /* Is this a high-surrogate? */
  5840. pb->hs = c; return; /* Save it for next */
  5841. }
  5842. hs = pb->hs; pb->hs = 0;
  5843. if (hs != 0) { /* Is there a leading high-surrogate? */
  5844. if (!IsSurrogateL(c)) hs = 0; /* Discard high-surrogate if a stray high-surrogate */
  5845. } else {
  5846. if (IsSurrogateL(c)) return; /* Discard stray low-surrogate */
  5847. }
  5848. wc = c;
  5849. #elif FF_LFN_UNICODE == 2 /* UTF-8 input */
  5850. for (;;) {
  5851. if (pb->ct == 0) { /* Not in the multi-byte sequence? */
  5852. pb->bs[pb->wi = 0] = (BYTE)c; /* Save 1st byte */
  5853. if ((BYTE)c < 0x80) break; /* Single byte code? */
  5854. if (((BYTE)c & 0xE0) == 0xC0) pb->ct = 1; /* 2-byte sequence? */
  5855. if (((BYTE)c & 0xF0) == 0xE0) pb->ct = 2; /* 3-byte sequence? */
  5856. if (((BYTE)c & 0xF8) == 0xF0) pb->ct = 3; /* 4-byte sequence? */
  5857. return; /* Invalid leading byte (discard it) */
  5858. } else { /* In the multi-byte sequence */
  5859. if (((BYTE)c & 0xC0) != 0x80) { /* Broken sequence? */
  5860. pb->ct = 0; continue; /* Discard the sequence */
  5861. }
  5862. pb->bs[++pb->wi] = (BYTE)c; /* Save the trailing byte */
  5863. if (--pb->ct == 0) break; /* End of the sequence? */
  5864. return;
  5865. }
  5866. }
  5867. tp = (const TCHAR*)pb->bs;
  5868. dc = tchar2uni(&tp); /* UTF-8 ==> UTF-16 */
  5869. if (dc == 0xFFFFFFFF) return; /* Wrong code? */
  5870. hs = (WCHAR)(dc >> 16);
  5871. wc = (WCHAR)dc;
  5872. #elif FF_LFN_UNICODE == 3 /* UTF-32 input */
  5873. if (IsSurrogate(c) || c >= 0x110000) return; /* Discard invalid code */
  5874. if (c >= 0x10000) { /* Out of BMP? */
  5875. hs = (WCHAR)(0xD800 | ((c >> 10) - 0x40)); /* Make high surrogate */
  5876. wc = 0xDC00 | (c & 0x3FF); /* Make low surrogate */
  5877. } else {
  5878. hs = 0;
  5879. wc = (WCHAR)c;
  5880. }
  5881. #endif
  5882. /* A code point in UTF-16 is available in hs and wc */
  5883. #if FF_STRF_ENCODE == 1 /* Write a code point in UTF-16LE */
  5884. if (hs != 0) { /* Surrogate pair? */
  5885. st_16(&pb->buf[i], hs);
  5886. i += 2;
  5887. nc++;
  5888. }
  5889. st_16(&pb->buf[i], wc);
  5890. i += 2;
  5891. #elif FF_STRF_ENCODE == 2 /* Write a code point in UTF-16BE */
  5892. if (hs != 0) { /* Surrogate pair? */
  5893. pb->buf[i++] = (BYTE)(hs >> 8);
  5894. pb->buf[i++] = (BYTE)hs;
  5895. nc++;
  5896. }
  5897. pb->buf[i++] = (BYTE)(wc >> 8);
  5898. pb->buf[i++] = (BYTE)wc;
  5899. #elif FF_STRF_ENCODE == 3 /* Write a code point in UTF-8 */
  5900. if (hs != 0) { /* 4-byte sequence? */
  5901. nc += 3;
  5902. hs = (hs & 0x3FF) + 0x40;
  5903. pb->buf[i++] = (BYTE)(0xF0 | hs >> 8);
  5904. pb->buf[i++] = (BYTE)(0x80 | (hs >> 2 & 0x3F));
  5905. pb->buf[i++] = (BYTE)(0x80 | (hs & 3) << 4 | (wc >> 6 & 0x0F));
  5906. pb->buf[i++] = (BYTE)(0x80 | (wc & 0x3F));
  5907. } else {
  5908. if (wc < 0x80) { /* Single byte? */
  5909. pb->buf[i++] = (BYTE)wc;
  5910. } else {
  5911. if (wc < 0x800) { /* 2-byte sequence? */
  5912. nc += 1;
  5913. pb->buf[i++] = (BYTE)(0xC0 | wc >> 6);
  5914. } else { /* 3-byte sequence */
  5915. nc += 2;
  5916. pb->buf[i++] = (BYTE)(0xE0 | wc >> 12);
  5917. pb->buf[i++] = (BYTE)(0x80 | (wc >> 6 & 0x3F));
  5918. }
  5919. pb->buf[i++] = (BYTE)(0x80 | (wc & 0x3F));
  5920. }
  5921. }
  5922. #else /* Write a code point in ANSI/OEM */
  5923. if (hs != 0) return;
  5924. wc = ff_uni2oem(wc, CODEPAGE); /* UTF-16 ==> ANSI/OEM */
  5925. if (wc == 0) return;
  5926. if (wc >= 0x100) {
  5927. pb->buf[i++] = (BYTE)(wc >> 8); nc++;
  5928. }
  5929. pb->buf[i++] = (BYTE)wc;
  5930. #endif
  5931. #else /* ANSI/OEM input (without re-encoding) */
  5932. pb->buf[i++] = (BYTE)c;
  5933. #endif
  5934. if (i >= (int)(sizeof pb->buf) - 4) { /* Write buffered characters to the file */
  5935. f_write(pb->fp, pb->buf, (UINT)i, &n);
  5936. i = (n == (UINT)i) ? 0 : -1;
  5937. }
  5938. pb->idx = i;
  5939. pb->nchr = nc + 1;
  5940. }
  5941. /* Flush characters left in the buffer and return number of characters written */
  5942. static int putc_flush (putbuff* pb)
  5943. {
  5944. UINT nw;
  5945. if ( pb->idx >= 0 /* Flush buffered characters to the file */
  5946. && f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK
  5947. && (UINT)pb->idx == nw) {
  5948. return pb->nchr;
  5949. }
  5950. return -1;
  5951. }
  5952. /* Initialize write buffer */
  5953. static void putc_init (putbuff* pb, FIL* fp)
  5954. {
  5955. memset(pb, 0, sizeof (putbuff));
  5956. pb->fp = fp;
  5957. }
  5958. int f_putc (
  5959. TCHAR c, /* A character to be output */
  5960. FIL* fp /* Pointer to the file object */
  5961. )
  5962. {
  5963. putbuff pb;
  5964. putc_init(&pb, fp);
  5965. putc_bfd(&pb, c); /* Put the character */
  5966. return putc_flush(&pb);
  5967. }
  5968. /*-----------------------------------------------------------------------*/
  5969. /* API: Put a String to the File */
  5970. /*-----------------------------------------------------------------------*/
  5971. int f_puts (
  5972. const TCHAR* str, /* Pointer to the string to be output */
  5973. FIL* fp /* Pointer to the file object */
  5974. )
  5975. {
  5976. putbuff pb;
  5977. putc_init(&pb, fp);
  5978. while (*str) putc_bfd(&pb, *str++); /* Put the string */
  5979. return putc_flush(&pb);
  5980. }
  5981. /*-----------------------------------------------------------------------*/
  5982. /* API: Put a Formatted String to the File (with sub-functions) */
  5983. /*-----------------------------------------------------------------------*/
  5984. #if FF_PRINT_FLOAT && FF_INTDEF == 2
  5985. #include <math.h>
  5986. static int ilog10 (double n) /* Calculate log10(n) in integer output */
  5987. {
  5988. int rv = 0;
  5989. while (n >= 10) { /* Decimate digit in right shift */
  5990. if (n >= 100000) {
  5991. n /= 100000; rv += 5;
  5992. } else {
  5993. n /= 10; rv++;
  5994. }
  5995. }
  5996. while (n < 1) { /* Decimate digit in left shift */
  5997. if (n < 0.00001) {
  5998. n *= 100000; rv -= 5;
  5999. } else {
  6000. n *= 10; rv--;
  6001. }
  6002. }
  6003. return rv;
  6004. }
  6005. static double i10x (int n) /* Calculate 10^n in integer input */
  6006. {
  6007. double rv = 1;
  6008. while (n > 0) { /* Left shift */
  6009. if (n >= 5) {
  6010. rv *= 100000; n -= 5;
  6011. } else {
  6012. rv *= 10; n--;
  6013. }
  6014. }
  6015. while (n < 0) { /* Right shift */
  6016. if (n <= -5) {
  6017. rv /= 100000; n += 5;
  6018. } else {
  6019. rv /= 10; n++;
  6020. }
  6021. }
  6022. return rv;
  6023. }
  6024. static void ftoa (
  6025. char* buf, /* Buffer to output the floating point string */
  6026. double val, /* Value to output */
  6027. int prec, /* Number of fractional digits */
  6028. TCHAR fmt /* Notation */
  6029. )
  6030. {
  6031. int digit;
  6032. int exp = 0, mag = 0;
  6033. char sign = 0;
  6034. double w;
  6035. const char *er = 0;
  6036. const char ds = FF_PRINT_FLOAT == 2 ? ',' : '.';
  6037. if (isnan(val)) { /* Not a number? */
  6038. er = "NaN";
  6039. } else {
  6040. if (prec < 0) prec = 6; /* Default precision? (6 fractional digits) */
  6041. if (val < 0) { /* Negative? */
  6042. val = 0 - val; sign = '-';
  6043. } else {
  6044. sign = '+';
  6045. }
  6046. if (isinf(val)) { /* Infinite? */
  6047. er = "INF";
  6048. } else {
  6049. if (fmt == 'f') { /* Decimal notation? */
  6050. val += i10x(0 - prec) / 2; /* Round (nearest) */
  6051. mag = ilog10(val);
  6052. if (mag < 0) mag = 0;
  6053. if (mag + prec + 3 >= SZ_NUM_BUF) er = "OV"; /* Buffer overflow? */
  6054. } else { /* E notation */
  6055. if (val != 0) { /* Not a true zero? */
  6056. val += i10x(ilog10(val) - prec) / 2; /* Round (nearest) */
  6057. exp = ilog10(val);
  6058. if (exp > 99 || prec + 7 >= SZ_NUM_BUF) { /* Buffer overflow or E > +99? */
  6059. er = "OV";
  6060. } else {
  6061. if (exp < -99) exp = -99;
  6062. val /= i10x(exp); /* Normalize */
  6063. }
  6064. }
  6065. }
  6066. }
  6067. if (!er) { /* Not error condition */
  6068. if (sign == '-') *buf++ = sign; /* Add a - if negative value */
  6069. do { /* Put decimal number */
  6070. if (mag == -1) *buf++ = ds; /* Insert a decimal separator when get into fractional part */
  6071. w = i10x(mag); /* Snip the highest digit d */
  6072. digit = (int)(val / w); val -= digit * w;
  6073. *buf++ = (char)('0' + digit); /* Put the digit */
  6074. } while (--mag >= -prec); /* Output all digits specified by prec */
  6075. if (fmt != 'f') { /* Put exponent if needed */
  6076. *buf++ = (char)fmt;
  6077. if (exp < 0) {
  6078. exp = 0 - exp; *buf++ = '-';
  6079. } else {
  6080. *buf++ = '+';
  6081. }
  6082. *buf++ = (char)('0' + exp / 10);
  6083. *buf++ = (char)('0' + exp % 10);
  6084. }
  6085. }
  6086. }
  6087. if (er) { /* Error condition */
  6088. if (sign) *buf++ = sign; /* Add sign if needed */
  6089. do { /* Put error symbol */
  6090. *buf++ = *er++;
  6091. } while (*er);
  6092. }
  6093. *buf = 0; /* Term */
  6094. }
  6095. #endif /* FF_PRINT_FLOAT && FF_INTDEF == 2 */
  6096. int f_printf (
  6097. FIL* fp, /* Pointer to the file object */
  6098. const TCHAR* fmt, /* Pointer to the format string */
  6099. ... /* Optional arguments... */
  6100. )
  6101. {
  6102. va_list arp;
  6103. putbuff pb;
  6104. UINT i, j, width, flag, radix;
  6105. int prec;
  6106. #if FF_PRINT_LLI && FF_INTDEF == 2
  6107. QWORD val;
  6108. #else
  6109. DWORD val;
  6110. #endif
  6111. TCHAR *tp;
  6112. TCHAR chr, pad;
  6113. TCHAR nul = 0;
  6114. char digit, str[SZ_NUM_BUF];
  6115. putc_init(&pb, fp);
  6116. va_start(arp, fmt);
  6117. for (;;) {
  6118. chr = *fmt++;
  6119. if (chr == 0) break; /* End of format string */
  6120. if (chr != '%') { /* Not an escape character (pass-through) */
  6121. putc_bfd(&pb, chr);
  6122. continue;
  6123. }
  6124. flag = width = 0; pad = ' '; prec = -1; /* Initialize the parameters */
  6125. chr = *fmt++;
  6126. if (chr == '0') { /* Flag: '0' padded */
  6127. pad = '0'; chr = *fmt++;
  6128. } else if (chr == '-') { /* Flag: Left aligned */
  6129. flag = 2; chr = *fmt++;
  6130. }
  6131. if (chr == '*') { /* Minimum width from an argument */
  6132. width = (UINT)va_arg(arp, int);
  6133. chr = *fmt++;
  6134. } else {
  6135. while (IsDigit(chr)) { /* Minimum width */
  6136. width = width * 10 + chr - '0';
  6137. chr = *fmt++;
  6138. }
  6139. }
  6140. if (chr == '.') { /* Precision */
  6141. chr = *fmt++;
  6142. if (chr == '*') { /* Precision from an argument */
  6143. prec = va_arg(arp, int);
  6144. chr = *fmt++;
  6145. } else {
  6146. prec = 0;
  6147. while (IsDigit(chr)) { /* Precision */
  6148. prec = prec * 10 + chr - '0';
  6149. chr = *fmt++;
  6150. }
  6151. }
  6152. }
  6153. if (chr == 'l') { /* Size: long int */
  6154. flag |= 4; chr = *fmt++;
  6155. #if FF_PRINT_LLI && FF_INTDEF == 2
  6156. if (chr == 'l') { /* Size: long long int */
  6157. flag |= 8; chr = *fmt++;
  6158. }
  6159. #endif
  6160. }
  6161. if (chr == 0) break; /* End of format string */
  6162. switch (chr) { /* Atgument type is... */
  6163. case 'b': /* Unsigned binary */
  6164. radix = 2; break;
  6165. case 'o': /* Unsigned octal */
  6166. radix = 8; break;
  6167. case 'd': /* Signed decimal */
  6168. case 'u': /* Unsigned decimal */
  6169. radix = 10; break;
  6170. case 'x': /* Unsigned hexadecimal (lower case) */
  6171. case 'X': /* Unsigned hexadecimal (upper case) */
  6172. radix = 16; break;
  6173. case 'c': /* Character */
  6174. putc_bfd(&pb, (TCHAR)va_arg(arp, int));
  6175. continue;
  6176. case 's': /* String */
  6177. tp = va_arg(arp, TCHAR*); /* Get a pointer argument */
  6178. if (!tp) tp = &nul; /* Null pointer generates a null string */
  6179. for (j = 0; tp[j]; j++) ; /* j = tcslen(tp) */
  6180. if (prec >= 0 && j > (UINT)prec) j = (UINT)prec; /* Limited length of string body */
  6181. for ( ; !(flag & 2) && j < width; j++) putc_bfd(&pb, pad); /* Left padding */
  6182. while (*tp && prec--) putc_bfd(&pb, *tp++); /* Body */
  6183. while (j++ < width) putc_bfd(&pb, ' '); /* Right padding */
  6184. continue;
  6185. #if FF_PRINT_FLOAT && FF_INTDEF == 2
  6186. case 'f': /* Floating point (decimal) */
  6187. case 'e': /* Floating point (e) */
  6188. case 'E': /* Floating point (E) */
  6189. ftoa(str, va_arg(arp, double), prec, chr); /* Make a floating point string */
  6190. for (j = strlen(str); !(flag & 2) && j < width; j++) putc_bfd(&pb, pad); /* Leading pads */
  6191. for (i = 0; str[i]; putc_bfd(&pb, str[i++])) ; /* Body */
  6192. while (j++ < width) putc_bfd(&pb, ' '); /* Trailing pads */
  6193. continue;
  6194. #endif
  6195. default: /* Unknown type (pass-through) */
  6196. putc_bfd(&pb, chr);
  6197. continue;
  6198. }
  6199. /* Get an integer argument and put it in numeral */
  6200. #if FF_PRINT_LLI && FF_INTDEF == 2
  6201. if (flag & 8) { /* long long argument? */
  6202. val = (QWORD)va_arg(arp, long long);
  6203. } else if (flag & 4) { /* long argument? */
  6204. val = (chr == 'd') ? (QWORD)(long long)va_arg(arp, long) : (QWORD)va_arg(arp, unsigned long);
  6205. } else { /* int/short/char argument */
  6206. val = (chr == 'd') ? (QWORD)(long long)va_arg(arp, int) : (QWORD)va_arg(arp, unsigned int);
  6207. }
  6208. if (chr == 'd' && (val & 0x8000000000000000)) { /* Negative value? */
  6209. val = 0 - val; flag |= 1;
  6210. }
  6211. #else
  6212. if (flag & 4) { /* long argument? */
  6213. val = (DWORD)va_arg(arp, long);
  6214. } else { /* int/short/char argument */
  6215. val = (chr == 'd') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int);
  6216. }
  6217. if (chr == 'd' && (val & 0x80000000)) { /* Negative value? */
  6218. val = 0 - val; flag |= 1;
  6219. }
  6220. #endif
  6221. i = 0;
  6222. do { /* Make an integer number string */
  6223. digit = (char)(val % radix) + '0'; val /= radix;
  6224. if (digit > '9') digit += (chr == 'x') ? 0x27 : 0x07;
  6225. str[i++] = digit;
  6226. } while (val && i < SZ_NUM_BUF);
  6227. if (flag & 1) str[i++] = '-'; /* Sign */
  6228. /* Write it */
  6229. for (j = i; !(flag & 2) && j < width; j++) { /* Leading pads */
  6230. putc_bfd(&pb, pad);
  6231. }
  6232. do { /* Body */
  6233. putc_bfd(&pb, (TCHAR)str[--i]);
  6234. } while (i);
  6235. while (j++ < width) { /* Trailing pads */
  6236. putc_bfd(&pb, ' ');
  6237. }
  6238. }
  6239. va_end(arp);
  6240. return putc_flush(&pb);
  6241. }
  6242. #endif /* !FF_FS_READONLY */
  6243. #endif /* FF_USE_STRFUNC */
  6244. #if FF_CODE_PAGE == 0
  6245. /*-----------------------------------------------------------------------*/
  6246. /* API: Set Active Codepage for the Path Name */
  6247. /*-----------------------------------------------------------------------*/
  6248. FRESULT f_setcp (
  6249. WORD cp /* Value to be set as active code page */
  6250. )
  6251. {
  6252. static const WORD validcp[22] = { 437, 720, 737, 771, 775, 850, 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, 869, 932, 936, 949, 950, 0};
  6253. static const BYTE *const tables[22] = {Ct437, Ct720, Ct737, Ct771, Ct775, Ct850, Ct852, Ct855, Ct857, Ct860, Ct861, Ct862, Ct863, Ct864, Ct865, Ct866, Ct869, Dc932, Dc936, Dc949, Dc950, 0};
  6254. UINT i;
  6255. for (i = 0; validcp[i] != 0 && validcp[i] != cp; i++) ; /* Find the code page */
  6256. if (validcp[i] != cp) return FR_INVALID_PARAMETER; /* Not found? */
  6257. CodePage = cp;
  6258. if (cp >= 900) { /* DBCS */
  6259. ExCvt = 0;
  6260. DbcTbl = tables[i];
  6261. } else { /* SBCS */
  6262. ExCvt = tables[i];
  6263. DbcTbl = 0;
  6264. }
  6265. return FR_OK;
  6266. }
  6267. #endif /* FF_CODE_PAGE == 0 */