inode.c 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191
  1. /*
  2. * linux/fs/ext4/inode.c
  3. *
  4. * Copyright (C) 1992, 1993, 1994, 1995
  5. * Remy Card (card@masi.ibp.fr)
  6. * Laboratoire MASI - Institut Blaise Pascal
  7. * Universite Pierre et Marie Curie (Paris VI)
  8. *
  9. * from
  10. *
  11. * linux/fs/minix/inode.c
  12. *
  13. * Copyright (C) 1991, 1992 Linus Torvalds
  14. *
  15. * 64-bit file support on 64-bit platforms by Jakub Jelinek
  16. * (jj@sunsite.ms.mff.cuni.cz)
  17. *
  18. * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
  19. */
  20. #include <linux/fs.h>
  21. #include <linux/time.h>
  22. #include <linux/highuid.h>
  23. #include <linux/pagemap.h>
  24. #include <linux/dax.h>
  25. #include <linux/quotaops.h>
  26. #include <linux/string.h>
  27. #include <linux/buffer_head.h>
  28. #include <linux/writeback.h>
  29. #include <linux/pagevec.h>
  30. #include <linux/mpage.h>
  31. #include <linux/namei.h>
  32. #include <linux/uio.h>
  33. #include <linux/bio.h>
  34. #include <linux/workqueue.h>
  35. #include <linux/kernel.h>
  36. #include <linux/printk.h>
  37. #include <linux/slab.h>
  38. #include <linux/bitops.h>
  39. #include <linux/iomap.h>
  40. #include "ext4_jbd2.h"
  41. #include "xattr.h"
  42. #include "acl.h"
  43. #include "truncate.h"
  44. #include <trace/events/ext4.h>
  45. #define MPAGE_DA_EXTENT_TAIL 0x01
  46. static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
  47. struct ext4_inode_info *ei)
  48. {
  49. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  50. __u32 csum;
  51. __u16 dummy_csum = 0;
  52. int offset = offsetof(struct ext4_inode, i_checksum_lo);
  53. unsigned int csum_size = sizeof(dummy_csum);
  54. csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
  55. csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
  56. offset += csum_size;
  57. csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
  58. EXT4_GOOD_OLD_INODE_SIZE - offset);
  59. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  60. offset = offsetof(struct ext4_inode, i_checksum_hi);
  61. csum = ext4_chksum(sbi, csum, (__u8 *)raw +
  62. EXT4_GOOD_OLD_INODE_SIZE,
  63. offset - EXT4_GOOD_OLD_INODE_SIZE);
  64. if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
  65. csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
  66. csum_size);
  67. offset += csum_size;
  68. }
  69. csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
  70. EXT4_INODE_SIZE(inode->i_sb) - offset);
  71. }
  72. return csum;
  73. }
  74. static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
  75. struct ext4_inode_info *ei)
  76. {
  77. __u32 provided, calculated;
  78. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  79. cpu_to_le32(EXT4_OS_LINUX) ||
  80. !ext4_has_metadata_csum(inode->i_sb))
  81. return 1;
  82. provided = le16_to_cpu(raw->i_checksum_lo);
  83. calculated = ext4_inode_csum(inode, raw, ei);
  84. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
  85. EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
  86. provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
  87. else
  88. calculated &= 0xFFFF;
  89. return provided == calculated;
  90. }
  91. static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
  92. struct ext4_inode_info *ei)
  93. {
  94. __u32 csum;
  95. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  96. cpu_to_le32(EXT4_OS_LINUX) ||
  97. !ext4_has_metadata_csum(inode->i_sb))
  98. return;
  99. csum = ext4_inode_csum(inode, raw, ei);
  100. raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
  101. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
  102. EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
  103. raw->i_checksum_hi = cpu_to_le16(csum >> 16);
  104. }
  105. static inline int ext4_begin_ordered_truncate(struct inode *inode,
  106. loff_t new_size)
  107. {
  108. trace_ext4_begin_ordered_truncate(inode, new_size);
  109. /*
  110. * If jinode is zero, then we never opened the file for
  111. * writing, so there's no need to call
  112. * jbd2_journal_begin_ordered_truncate() since there's no
  113. * outstanding writes we need to flush.
  114. */
  115. if (!EXT4_I(inode)->jinode)
  116. return 0;
  117. return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
  118. EXT4_I(inode)->jinode,
  119. new_size);
  120. }
  121. static void ext4_invalidatepage(struct page *page, unsigned int offset,
  122. unsigned int length);
  123. static int __ext4_journalled_writepage(struct page *page, unsigned int len);
  124. static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
  125. static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
  126. int pextents);
  127. /*
  128. * Test whether an inode is a fast symlink.
  129. * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
  130. */
  131. int ext4_inode_is_fast_symlink(struct inode *inode)
  132. {
  133. return S_ISLNK(inode->i_mode) && inode->i_size &&
  134. (inode->i_size < EXT4_N_BLOCKS * 4);
  135. }
  136. /*
  137. * Restart the transaction associated with *handle. This does a commit,
  138. * so before we call here everything must be consistently dirtied against
  139. * this transaction.
  140. */
  141. int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
  142. int nblocks)
  143. {
  144. int ret;
  145. /*
  146. * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
  147. * moment, get_block can be called only for blocks inside i_size since
  148. * page cache has been already dropped and writes are blocked by
  149. * i_mutex. So we can safely drop the i_data_sem here.
  150. */
  151. BUG_ON(EXT4_JOURNAL(inode) == NULL);
  152. jbd_debug(2, "restarting handle %p\n", handle);
  153. up_write(&EXT4_I(inode)->i_data_sem);
  154. ret = ext4_journal_restart(handle, nblocks);
  155. down_write(&EXT4_I(inode)->i_data_sem);
  156. ext4_discard_preallocations(inode);
  157. return ret;
  158. }
  159. /*
  160. * Called at the last iput() if i_nlink is zero.
  161. */
  162. void ext4_evict_inode(struct inode *inode)
  163. {
  164. handle_t *handle;
  165. int err;
  166. int extra_credits = 3;
  167. struct ext4_xattr_inode_array *ea_inode_array = NULL;
  168. trace_ext4_evict_inode(inode);
  169. if (inode->i_nlink) {
  170. /*
  171. * When journalling data dirty buffers are tracked only in the
  172. * journal. So although mm thinks everything is clean and
  173. * ready for reaping the inode might still have some pages to
  174. * write in the running transaction or waiting to be
  175. * checkpointed. Thus calling jbd2_journal_invalidatepage()
  176. * (via truncate_inode_pages()) to discard these buffers can
  177. * cause data loss. Also even if we did not discard these
  178. * buffers, we would have no way to find them after the inode
  179. * is reaped and thus user could see stale data if he tries to
  180. * read them before the transaction is checkpointed. So be
  181. * careful and force everything to disk here... We use
  182. * ei->i_datasync_tid to store the newest transaction
  183. * containing inode's data.
  184. *
  185. * Note that directories do not have this problem because they
  186. * don't use page cache.
  187. */
  188. if (inode->i_ino != EXT4_JOURNAL_INO &&
  189. ext4_should_journal_data(inode) &&
  190. (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
  191. inode->i_data.nrpages) {
  192. journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
  193. tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
  194. jbd2_complete_transaction(journal, commit_tid);
  195. filemap_write_and_wait(&inode->i_data);
  196. }
  197. truncate_inode_pages_final(&inode->i_data);
  198. goto no_delete;
  199. }
  200. if (is_bad_inode(inode))
  201. goto no_delete;
  202. dquot_initialize(inode);
  203. if (ext4_should_order_data(inode))
  204. ext4_begin_ordered_truncate(inode, 0);
  205. truncate_inode_pages_final(&inode->i_data);
  206. /*
  207. * Protect us against freezing - iput() caller didn't have to have any
  208. * protection against it
  209. */
  210. sb_start_intwrite(inode->i_sb);
  211. if (!IS_NOQUOTA(inode))
  212. extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
  213. handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
  214. ext4_blocks_for_truncate(inode)+extra_credits);
  215. if (IS_ERR(handle)) {
  216. ext4_std_error(inode->i_sb, PTR_ERR(handle));
  217. /*
  218. * If we're going to skip the normal cleanup, we still need to
  219. * make sure that the in-core orphan linked list is properly
  220. * cleaned up.
  221. */
  222. ext4_orphan_del(NULL, inode);
  223. sb_end_intwrite(inode->i_sb);
  224. goto no_delete;
  225. }
  226. if (IS_SYNC(inode))
  227. ext4_handle_sync(handle);
  228. /*
  229. * Set inode->i_size to 0 before calling ext4_truncate(). We need
  230. * special handling of symlinks here because i_size is used to
  231. * determine whether ext4_inode_info->i_data contains symlink data or
  232. * block mappings. Setting i_size to 0 will remove its fast symlink
  233. * status. Erase i_data so that it becomes a valid empty block map.
  234. */
  235. if (ext4_inode_is_fast_symlink(inode))
  236. memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
  237. inode->i_size = 0;
  238. err = ext4_mark_inode_dirty(handle, inode);
  239. if (err) {
  240. ext4_warning(inode->i_sb,
  241. "couldn't mark inode dirty (err %d)", err);
  242. goto stop_handle;
  243. }
  244. if (inode->i_blocks) {
  245. err = ext4_truncate(inode);
  246. if (err) {
  247. ext4_error(inode->i_sb,
  248. "couldn't truncate inode %lu (err %d)",
  249. inode->i_ino, err);
  250. goto stop_handle;
  251. }
  252. }
  253. /* Remove xattr references. */
  254. err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
  255. extra_credits);
  256. if (err) {
  257. ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
  258. stop_handle:
  259. ext4_journal_stop(handle);
  260. ext4_orphan_del(NULL, inode);
  261. sb_end_intwrite(inode->i_sb);
  262. ext4_xattr_inode_array_free(ea_inode_array);
  263. goto no_delete;
  264. }
  265. /*
  266. * Kill off the orphan record which ext4_truncate created.
  267. * AKPM: I think this can be inside the above `if'.
  268. * Note that ext4_orphan_del() has to be able to cope with the
  269. * deletion of a non-existent orphan - this is because we don't
  270. * know if ext4_truncate() actually created an orphan record.
  271. * (Well, we could do this if we need to, but heck - it works)
  272. */
  273. ext4_orphan_del(handle, inode);
  274. EXT4_I(inode)->i_dtime = get_seconds();
  275. /*
  276. * One subtle ordering requirement: if anything has gone wrong
  277. * (transaction abort, IO errors, whatever), then we can still
  278. * do these next steps (the fs will already have been marked as
  279. * having errors), but we can't free the inode if the mark_dirty
  280. * fails.
  281. */
  282. if (ext4_mark_inode_dirty(handle, inode))
  283. /* If that failed, just do the required in-core inode clear. */
  284. ext4_clear_inode(inode);
  285. else
  286. ext4_free_inode(handle, inode);
  287. ext4_journal_stop(handle);
  288. sb_end_intwrite(inode->i_sb);
  289. ext4_xattr_inode_array_free(ea_inode_array);
  290. return;
  291. no_delete:
  292. ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
  293. }
  294. #ifdef CONFIG_QUOTA
  295. qsize_t *ext4_get_reserved_space(struct inode *inode)
  296. {
  297. return &EXT4_I(inode)->i_reserved_quota;
  298. }
  299. #endif
  300. /*
  301. * Called with i_data_sem down, which is important since we can call
  302. * ext4_discard_preallocations() from here.
  303. */
  304. void ext4_da_update_reserve_space(struct inode *inode,
  305. int used, int quota_claim)
  306. {
  307. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  308. struct ext4_inode_info *ei = EXT4_I(inode);
  309. spin_lock(&ei->i_block_reservation_lock);
  310. trace_ext4_da_update_reserve_space(inode, used, quota_claim);
  311. if (unlikely(used > ei->i_reserved_data_blocks)) {
  312. ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
  313. "with only %d reserved data blocks",
  314. __func__, inode->i_ino, used,
  315. ei->i_reserved_data_blocks);
  316. WARN_ON(1);
  317. used = ei->i_reserved_data_blocks;
  318. }
  319. /* Update per-inode reservations */
  320. ei->i_reserved_data_blocks -= used;
  321. percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
  322. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  323. /* Update quota subsystem for data blocks */
  324. if (quota_claim)
  325. dquot_claim_block(inode, EXT4_C2B(sbi, used));
  326. else {
  327. /*
  328. * We did fallocate with an offset that is already delayed
  329. * allocated. So on delayed allocated writeback we should
  330. * not re-claim the quota for fallocated blocks.
  331. */
  332. dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
  333. }
  334. /*
  335. * If we have done all the pending block allocations and if
  336. * there aren't any writers on the inode, we can discard the
  337. * inode's preallocations.
  338. */
  339. if ((ei->i_reserved_data_blocks == 0) &&
  340. (atomic_read(&inode->i_writecount) == 0))
  341. ext4_discard_preallocations(inode);
  342. }
  343. static int __check_block_validity(struct inode *inode, const char *func,
  344. unsigned int line,
  345. struct ext4_map_blocks *map)
  346. {
  347. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
  348. map->m_len)) {
  349. ext4_error_inode(inode, func, line, map->m_pblk,
  350. "lblock %lu mapped to illegal pblock "
  351. "(length %d)", (unsigned long) map->m_lblk,
  352. map->m_len);
  353. return -EFSCORRUPTED;
  354. }
  355. return 0;
  356. }
  357. int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
  358. ext4_lblk_t len)
  359. {
  360. int ret;
  361. if (ext4_encrypted_inode(inode))
  362. return fscrypt_zeroout_range(inode, lblk, pblk, len);
  363. ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
  364. if (ret > 0)
  365. ret = 0;
  366. return ret;
  367. }
  368. #define check_block_validity(inode, map) \
  369. __check_block_validity((inode), __func__, __LINE__, (map))
  370. #ifdef ES_AGGRESSIVE_TEST
  371. static void ext4_map_blocks_es_recheck(handle_t *handle,
  372. struct inode *inode,
  373. struct ext4_map_blocks *es_map,
  374. struct ext4_map_blocks *map,
  375. int flags)
  376. {
  377. int retval;
  378. map->m_flags = 0;
  379. /*
  380. * There is a race window that the result is not the same.
  381. * e.g. xfstests #223 when dioread_nolock enables. The reason
  382. * is that we lookup a block mapping in extent status tree with
  383. * out taking i_data_sem. So at the time the unwritten extent
  384. * could be converted.
  385. */
  386. down_read(&EXT4_I(inode)->i_data_sem);
  387. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  388. retval = ext4_ext_map_blocks(handle, inode, map, flags &
  389. EXT4_GET_BLOCKS_KEEP_SIZE);
  390. } else {
  391. retval = ext4_ind_map_blocks(handle, inode, map, flags &
  392. EXT4_GET_BLOCKS_KEEP_SIZE);
  393. }
  394. up_read((&EXT4_I(inode)->i_data_sem));
  395. /*
  396. * We don't check m_len because extent will be collpased in status
  397. * tree. So the m_len might not equal.
  398. */
  399. if (es_map->m_lblk != map->m_lblk ||
  400. es_map->m_flags != map->m_flags ||
  401. es_map->m_pblk != map->m_pblk) {
  402. printk("ES cache assertion failed for inode: %lu "
  403. "es_cached ex [%d/%d/%llu/%x] != "
  404. "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
  405. inode->i_ino, es_map->m_lblk, es_map->m_len,
  406. es_map->m_pblk, es_map->m_flags, map->m_lblk,
  407. map->m_len, map->m_pblk, map->m_flags,
  408. retval, flags);
  409. }
  410. }
  411. #endif /* ES_AGGRESSIVE_TEST */
  412. /*
  413. * The ext4_map_blocks() function tries to look up the requested blocks,
  414. * and returns if the blocks are already mapped.
  415. *
  416. * Otherwise it takes the write lock of the i_data_sem and allocate blocks
  417. * and store the allocated blocks in the result buffer head and mark it
  418. * mapped.
  419. *
  420. * If file type is extents based, it will call ext4_ext_map_blocks(),
  421. * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
  422. * based files
  423. *
  424. * On success, it returns the number of blocks being mapped or allocated. if
  425. * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
  426. * is marked as unwritten. If the create == 1, it will mark @map as mapped.
  427. *
  428. * It returns 0 if plain look up failed (blocks have not been allocated), in
  429. * that case, @map is returned as unmapped but we still do fill map->m_len to
  430. * indicate the length of a hole starting at map->m_lblk.
  431. *
  432. * It returns the error in case of allocation failure.
  433. */
  434. int ext4_map_blocks(handle_t *handle, struct inode *inode,
  435. struct ext4_map_blocks *map, int flags)
  436. {
  437. struct extent_status es;
  438. int retval;
  439. int ret = 0;
  440. #ifdef ES_AGGRESSIVE_TEST
  441. struct ext4_map_blocks orig_map;
  442. memcpy(&orig_map, map, sizeof(*map));
  443. #endif
  444. map->m_flags = 0;
  445. ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
  446. "logical block %lu\n", inode->i_ino, flags, map->m_len,
  447. (unsigned long) map->m_lblk);
  448. /*
  449. * ext4_map_blocks returns an int, and m_len is an unsigned int
  450. */
  451. if (unlikely(map->m_len > INT_MAX))
  452. map->m_len = INT_MAX;
  453. /* We can handle the block number less than EXT_MAX_BLOCKS */
  454. if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
  455. return -EFSCORRUPTED;
  456. /* Lookup extent status tree firstly */
  457. if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
  458. if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
  459. map->m_pblk = ext4_es_pblock(&es) +
  460. map->m_lblk - es.es_lblk;
  461. map->m_flags |= ext4_es_is_written(&es) ?
  462. EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
  463. retval = es.es_len - (map->m_lblk - es.es_lblk);
  464. if (retval > map->m_len)
  465. retval = map->m_len;
  466. map->m_len = retval;
  467. } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
  468. map->m_pblk = 0;
  469. retval = es.es_len - (map->m_lblk - es.es_lblk);
  470. if (retval > map->m_len)
  471. retval = map->m_len;
  472. map->m_len = retval;
  473. retval = 0;
  474. } else {
  475. BUG_ON(1);
  476. }
  477. #ifdef ES_AGGRESSIVE_TEST
  478. ext4_map_blocks_es_recheck(handle, inode, map,
  479. &orig_map, flags);
  480. #endif
  481. goto found;
  482. }
  483. /*
  484. * Try to see if we can get the block without requesting a new
  485. * file system block.
  486. */
  487. down_read(&EXT4_I(inode)->i_data_sem);
  488. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  489. retval = ext4_ext_map_blocks(handle, inode, map, flags &
  490. EXT4_GET_BLOCKS_KEEP_SIZE);
  491. } else {
  492. retval = ext4_ind_map_blocks(handle, inode, map, flags &
  493. EXT4_GET_BLOCKS_KEEP_SIZE);
  494. }
  495. if (retval > 0) {
  496. unsigned int status;
  497. if (unlikely(retval != map->m_len)) {
  498. ext4_warning(inode->i_sb,
  499. "ES len assertion failed for inode "
  500. "%lu: retval %d != map->m_len %d",
  501. inode->i_ino, retval, map->m_len);
  502. WARN_ON(1);
  503. }
  504. status = map->m_flags & EXT4_MAP_UNWRITTEN ?
  505. EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
  506. if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
  507. !(status & EXTENT_STATUS_WRITTEN) &&
  508. ext4_find_delalloc_range(inode, map->m_lblk,
  509. map->m_lblk + map->m_len - 1))
  510. status |= EXTENT_STATUS_DELAYED;
  511. ret = ext4_es_insert_extent(inode, map->m_lblk,
  512. map->m_len, map->m_pblk, status);
  513. if (ret < 0)
  514. retval = ret;
  515. }
  516. up_read((&EXT4_I(inode)->i_data_sem));
  517. found:
  518. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
  519. ret = check_block_validity(inode, map);
  520. if (ret != 0)
  521. return ret;
  522. }
  523. /* If it is only a block(s) look up */
  524. if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
  525. return retval;
  526. /*
  527. * Returns if the blocks have already allocated
  528. *
  529. * Note that if blocks have been preallocated
  530. * ext4_ext_get_block() returns the create = 0
  531. * with buffer head unmapped.
  532. */
  533. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
  534. /*
  535. * If we need to convert extent to unwritten
  536. * we continue and do the actual work in
  537. * ext4_ext_map_blocks()
  538. */
  539. if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
  540. return retval;
  541. /*
  542. * Here we clear m_flags because after allocating an new extent,
  543. * it will be set again.
  544. */
  545. map->m_flags &= ~EXT4_MAP_FLAGS;
  546. /*
  547. * New blocks allocate and/or writing to unwritten extent
  548. * will possibly result in updating i_data, so we take
  549. * the write lock of i_data_sem, and call get_block()
  550. * with create == 1 flag.
  551. */
  552. down_write(&EXT4_I(inode)->i_data_sem);
  553. /*
  554. * We need to check for EXT4 here because migrate
  555. * could have changed the inode type in between
  556. */
  557. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  558. retval = ext4_ext_map_blocks(handle, inode, map, flags);
  559. } else {
  560. retval = ext4_ind_map_blocks(handle, inode, map, flags);
  561. if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
  562. /*
  563. * We allocated new blocks which will result in
  564. * i_data's format changing. Force the migrate
  565. * to fail by clearing migrate flags
  566. */
  567. ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
  568. }
  569. /*
  570. * Update reserved blocks/metadata blocks after successful
  571. * block allocation which had been deferred till now. We don't
  572. * support fallocate for non extent files. So we can update
  573. * reserve space here.
  574. */
  575. if ((retval > 0) &&
  576. (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
  577. ext4_da_update_reserve_space(inode, retval, 1);
  578. }
  579. if (retval > 0) {
  580. unsigned int status;
  581. if (unlikely(retval != map->m_len)) {
  582. ext4_warning(inode->i_sb,
  583. "ES len assertion failed for inode "
  584. "%lu: retval %d != map->m_len %d",
  585. inode->i_ino, retval, map->m_len);
  586. WARN_ON(1);
  587. }
  588. /*
  589. * We have to zeroout blocks before inserting them into extent
  590. * status tree. Otherwise someone could look them up there and
  591. * use them before they are really zeroed. We also have to
  592. * unmap metadata before zeroing as otherwise writeback can
  593. * overwrite zeros with stale data from block device.
  594. */
  595. if (flags & EXT4_GET_BLOCKS_ZERO &&
  596. map->m_flags & EXT4_MAP_MAPPED &&
  597. map->m_flags & EXT4_MAP_NEW) {
  598. clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
  599. map->m_len);
  600. ret = ext4_issue_zeroout(inode, map->m_lblk,
  601. map->m_pblk, map->m_len);
  602. if (ret) {
  603. retval = ret;
  604. goto out_sem;
  605. }
  606. }
  607. /*
  608. * If the extent has been zeroed out, we don't need to update
  609. * extent status tree.
  610. */
  611. if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
  612. ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
  613. if (ext4_es_is_written(&es))
  614. goto out_sem;
  615. }
  616. status = map->m_flags & EXT4_MAP_UNWRITTEN ?
  617. EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
  618. if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
  619. !(status & EXTENT_STATUS_WRITTEN) &&
  620. ext4_find_delalloc_range(inode, map->m_lblk,
  621. map->m_lblk + map->m_len - 1))
  622. status |= EXTENT_STATUS_DELAYED;
  623. ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
  624. map->m_pblk, status);
  625. if (ret < 0) {
  626. retval = ret;
  627. goto out_sem;
  628. }
  629. }
  630. out_sem:
  631. up_write((&EXT4_I(inode)->i_data_sem));
  632. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
  633. ret = check_block_validity(inode, map);
  634. if (ret != 0)
  635. return ret;
  636. /*
  637. * Inodes with freshly allocated blocks where contents will be
  638. * visible after transaction commit must be on transaction's
  639. * ordered data list.
  640. */
  641. if (map->m_flags & EXT4_MAP_NEW &&
  642. !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
  643. !(flags & EXT4_GET_BLOCKS_ZERO) &&
  644. !ext4_is_quota_file(inode) &&
  645. ext4_should_order_data(inode)) {
  646. if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
  647. ret = ext4_jbd2_inode_add_wait(handle, inode);
  648. else
  649. ret = ext4_jbd2_inode_add_write(handle, inode);
  650. if (ret)
  651. return ret;
  652. }
  653. }
  654. return retval;
  655. }
  656. /*
  657. * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
  658. * we have to be careful as someone else may be manipulating b_state as well.
  659. */
  660. static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
  661. {
  662. unsigned long old_state;
  663. unsigned long new_state;
  664. flags &= EXT4_MAP_FLAGS;
  665. /* Dummy buffer_head? Set non-atomically. */
  666. if (!bh->b_page) {
  667. bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
  668. return;
  669. }
  670. /*
  671. * Someone else may be modifying b_state. Be careful! This is ugly but
  672. * once we get rid of using bh as a container for mapping information
  673. * to pass to / from get_block functions, this can go away.
  674. */
  675. do {
  676. old_state = READ_ONCE(bh->b_state);
  677. new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
  678. } while (unlikely(
  679. cmpxchg(&bh->b_state, old_state, new_state) != old_state));
  680. }
  681. static int _ext4_get_block(struct inode *inode, sector_t iblock,
  682. struct buffer_head *bh, int flags)
  683. {
  684. struct ext4_map_blocks map;
  685. int ret = 0;
  686. if (ext4_has_inline_data(inode))
  687. return -ERANGE;
  688. map.m_lblk = iblock;
  689. map.m_len = bh->b_size >> inode->i_blkbits;
  690. ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
  691. flags);
  692. if (ret > 0) {
  693. map_bh(bh, inode->i_sb, map.m_pblk);
  694. ext4_update_bh_state(bh, map.m_flags);
  695. bh->b_size = inode->i_sb->s_blocksize * map.m_len;
  696. ret = 0;
  697. } else if (ret == 0) {
  698. /* hole case, need to fill in bh->b_size */
  699. bh->b_size = inode->i_sb->s_blocksize * map.m_len;
  700. }
  701. return ret;
  702. }
  703. int ext4_get_block(struct inode *inode, sector_t iblock,
  704. struct buffer_head *bh, int create)
  705. {
  706. return _ext4_get_block(inode, iblock, bh,
  707. create ? EXT4_GET_BLOCKS_CREATE : 0);
  708. }
  709. /*
  710. * Get block function used when preparing for buffered write if we require
  711. * creating an unwritten extent if blocks haven't been allocated. The extent
  712. * will be converted to written after the IO is complete.
  713. */
  714. int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
  715. struct buffer_head *bh_result, int create)
  716. {
  717. ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
  718. inode->i_ino, create);
  719. return _ext4_get_block(inode, iblock, bh_result,
  720. EXT4_GET_BLOCKS_IO_CREATE_EXT);
  721. }
  722. /* Maximum number of blocks we map for direct IO at once. */
  723. #define DIO_MAX_BLOCKS 4096
  724. /*
  725. * Get blocks function for the cases that need to start a transaction -
  726. * generally difference cases of direct IO and DAX IO. It also handles retries
  727. * in case of ENOSPC.
  728. */
  729. static int ext4_get_block_trans(struct inode *inode, sector_t iblock,
  730. struct buffer_head *bh_result, int flags)
  731. {
  732. int dio_credits;
  733. handle_t *handle;
  734. int retries = 0;
  735. int ret;
  736. /* Trim mapping request to maximum we can map at once for DIO */
  737. if (bh_result->b_size >> inode->i_blkbits > DIO_MAX_BLOCKS)
  738. bh_result->b_size = DIO_MAX_BLOCKS << inode->i_blkbits;
  739. dio_credits = ext4_chunk_trans_blocks(inode,
  740. bh_result->b_size >> inode->i_blkbits);
  741. retry:
  742. handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
  743. if (IS_ERR(handle))
  744. return PTR_ERR(handle);
  745. ret = _ext4_get_block(inode, iblock, bh_result, flags);
  746. ext4_journal_stop(handle);
  747. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  748. goto retry;
  749. return ret;
  750. }
  751. /* Get block function for DIO reads and writes to inodes without extents */
  752. int ext4_dio_get_block(struct inode *inode, sector_t iblock,
  753. struct buffer_head *bh, int create)
  754. {
  755. /* We don't expect handle for direct IO */
  756. WARN_ON_ONCE(ext4_journal_current_handle());
  757. if (!create)
  758. return _ext4_get_block(inode, iblock, bh, 0);
  759. return ext4_get_block_trans(inode, iblock, bh, EXT4_GET_BLOCKS_CREATE);
  760. }
  761. /*
  762. * Get block function for AIO DIO writes when we create unwritten extent if
  763. * blocks are not allocated yet. The extent will be converted to written
  764. * after IO is complete.
  765. */
  766. static int ext4_dio_get_block_unwritten_async(struct inode *inode,
  767. sector_t iblock, struct buffer_head *bh_result, int create)
  768. {
  769. int ret;
  770. /* We don't expect handle for direct IO */
  771. WARN_ON_ONCE(ext4_journal_current_handle());
  772. ret = ext4_get_block_trans(inode, iblock, bh_result,
  773. EXT4_GET_BLOCKS_IO_CREATE_EXT);
  774. /*
  775. * When doing DIO using unwritten extents, we need io_end to convert
  776. * unwritten extents to written on IO completion. We allocate io_end
  777. * once we spot unwritten extent and store it in b_private. Generic
  778. * DIO code keeps b_private set and furthermore passes the value to
  779. * our completion callback in 'private' argument.
  780. */
  781. if (!ret && buffer_unwritten(bh_result)) {
  782. if (!bh_result->b_private) {
  783. ext4_io_end_t *io_end;
  784. io_end = ext4_init_io_end(inode, GFP_KERNEL);
  785. if (!io_end)
  786. return -ENOMEM;
  787. bh_result->b_private = io_end;
  788. ext4_set_io_unwritten_flag(inode, io_end);
  789. }
  790. set_buffer_defer_completion(bh_result);
  791. }
  792. return ret;
  793. }
  794. /*
  795. * Get block function for non-AIO DIO writes when we create unwritten extent if
  796. * blocks are not allocated yet. The extent will be converted to written
  797. * after IO is complete by ext4_direct_IO_write().
  798. */
  799. static int ext4_dio_get_block_unwritten_sync(struct inode *inode,
  800. sector_t iblock, struct buffer_head *bh_result, int create)
  801. {
  802. int ret;
  803. /* We don't expect handle for direct IO */
  804. WARN_ON_ONCE(ext4_journal_current_handle());
  805. ret = ext4_get_block_trans(inode, iblock, bh_result,
  806. EXT4_GET_BLOCKS_IO_CREATE_EXT);
  807. /*
  808. * Mark inode as having pending DIO writes to unwritten extents.
  809. * ext4_direct_IO_write() checks this flag and converts extents to
  810. * written.
  811. */
  812. if (!ret && buffer_unwritten(bh_result))
  813. ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
  814. return ret;
  815. }
  816. static int ext4_dio_get_block_overwrite(struct inode *inode, sector_t iblock,
  817. struct buffer_head *bh_result, int create)
  818. {
  819. int ret;
  820. ext4_debug("ext4_dio_get_block_overwrite: inode %lu, create flag %d\n",
  821. inode->i_ino, create);
  822. /* We don't expect handle for direct IO */
  823. WARN_ON_ONCE(ext4_journal_current_handle());
  824. ret = _ext4_get_block(inode, iblock, bh_result, 0);
  825. /*
  826. * Blocks should have been preallocated! ext4_file_write_iter() checks
  827. * that.
  828. */
  829. WARN_ON_ONCE(!buffer_mapped(bh_result) || buffer_unwritten(bh_result));
  830. return ret;
  831. }
  832. /*
  833. * `handle' can be NULL if create is zero
  834. */
  835. struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
  836. ext4_lblk_t block, int map_flags)
  837. {
  838. struct ext4_map_blocks map;
  839. struct buffer_head *bh;
  840. int create = map_flags & EXT4_GET_BLOCKS_CREATE;
  841. int err;
  842. J_ASSERT(handle != NULL || create == 0);
  843. map.m_lblk = block;
  844. map.m_len = 1;
  845. err = ext4_map_blocks(handle, inode, &map, map_flags);
  846. if (err == 0)
  847. return create ? ERR_PTR(-ENOSPC) : NULL;
  848. if (err < 0)
  849. return ERR_PTR(err);
  850. bh = sb_getblk(inode->i_sb, map.m_pblk);
  851. if (unlikely(!bh))
  852. return ERR_PTR(-ENOMEM);
  853. if (map.m_flags & EXT4_MAP_NEW) {
  854. J_ASSERT(create != 0);
  855. J_ASSERT(handle != NULL);
  856. /*
  857. * Now that we do not always journal data, we should
  858. * keep in mind whether this should always journal the
  859. * new buffer as metadata. For now, regular file
  860. * writes use ext4_get_block instead, so it's not a
  861. * problem.
  862. */
  863. lock_buffer(bh);
  864. BUFFER_TRACE(bh, "call get_create_access");
  865. err = ext4_journal_get_create_access(handle, bh);
  866. if (unlikely(err)) {
  867. unlock_buffer(bh);
  868. goto errout;
  869. }
  870. if (!buffer_uptodate(bh)) {
  871. memset(bh->b_data, 0, inode->i_sb->s_blocksize);
  872. set_buffer_uptodate(bh);
  873. }
  874. unlock_buffer(bh);
  875. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  876. err = ext4_handle_dirty_metadata(handle, inode, bh);
  877. if (unlikely(err))
  878. goto errout;
  879. } else
  880. BUFFER_TRACE(bh, "not a new buffer");
  881. return bh;
  882. errout:
  883. brelse(bh);
  884. return ERR_PTR(err);
  885. }
  886. struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
  887. ext4_lblk_t block, int map_flags)
  888. {
  889. struct buffer_head *bh;
  890. bh = ext4_getblk(handle, inode, block, map_flags);
  891. if (IS_ERR(bh))
  892. return bh;
  893. if (!bh || buffer_uptodate(bh))
  894. return bh;
  895. ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &bh);
  896. wait_on_buffer(bh);
  897. if (buffer_uptodate(bh))
  898. return bh;
  899. put_bh(bh);
  900. return ERR_PTR(-EIO);
  901. }
  902. /* Read a contiguous batch of blocks. */
  903. int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
  904. bool wait, struct buffer_head **bhs)
  905. {
  906. int i, err;
  907. for (i = 0; i < bh_count; i++) {
  908. bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
  909. if (IS_ERR(bhs[i])) {
  910. err = PTR_ERR(bhs[i]);
  911. bh_count = i;
  912. goto out_brelse;
  913. }
  914. }
  915. for (i = 0; i < bh_count; i++)
  916. /* Note that NULL bhs[i] is valid because of holes. */
  917. if (bhs[i] && !buffer_uptodate(bhs[i]))
  918. ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1,
  919. &bhs[i]);
  920. if (!wait)
  921. return 0;
  922. for (i = 0; i < bh_count; i++)
  923. if (bhs[i])
  924. wait_on_buffer(bhs[i]);
  925. for (i = 0; i < bh_count; i++) {
  926. if (bhs[i] && !buffer_uptodate(bhs[i])) {
  927. err = -EIO;
  928. goto out_brelse;
  929. }
  930. }
  931. return 0;
  932. out_brelse:
  933. for (i = 0; i < bh_count; i++) {
  934. brelse(bhs[i]);
  935. bhs[i] = NULL;
  936. }
  937. return err;
  938. }
  939. int ext4_walk_page_buffers(handle_t *handle,
  940. struct buffer_head *head,
  941. unsigned from,
  942. unsigned to,
  943. int *partial,
  944. int (*fn)(handle_t *handle,
  945. struct buffer_head *bh))
  946. {
  947. struct buffer_head *bh;
  948. unsigned block_start, block_end;
  949. unsigned blocksize = head->b_size;
  950. int err, ret = 0;
  951. struct buffer_head *next;
  952. for (bh = head, block_start = 0;
  953. ret == 0 && (bh != head || !block_start);
  954. block_start = block_end, bh = next) {
  955. next = bh->b_this_page;
  956. block_end = block_start + blocksize;
  957. if (block_end <= from || block_start >= to) {
  958. if (partial && !buffer_uptodate(bh))
  959. *partial = 1;
  960. continue;
  961. }
  962. err = (*fn)(handle, bh);
  963. if (!ret)
  964. ret = err;
  965. }
  966. return ret;
  967. }
  968. /*
  969. * To preserve ordering, it is essential that the hole instantiation and
  970. * the data write be encapsulated in a single transaction. We cannot
  971. * close off a transaction and start a new one between the ext4_get_block()
  972. * and the commit_write(). So doing the jbd2_journal_start at the start of
  973. * prepare_write() is the right place.
  974. *
  975. * Also, this function can nest inside ext4_writepage(). In that case, we
  976. * *know* that ext4_writepage() has generated enough buffer credits to do the
  977. * whole page. So we won't block on the journal in that case, which is good,
  978. * because the caller may be PF_MEMALLOC.
  979. *
  980. * By accident, ext4 can be reentered when a transaction is open via
  981. * quota file writes. If we were to commit the transaction while thus
  982. * reentered, there can be a deadlock - we would be holding a quota
  983. * lock, and the commit would never complete if another thread had a
  984. * transaction open and was blocking on the quota lock - a ranking
  985. * violation.
  986. *
  987. * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
  988. * will _not_ run commit under these circumstances because handle->h_ref
  989. * is elevated. We'll still have enough credits for the tiny quotafile
  990. * write.
  991. */
  992. int do_journal_get_write_access(handle_t *handle,
  993. struct buffer_head *bh)
  994. {
  995. int dirty = buffer_dirty(bh);
  996. int ret;
  997. if (!buffer_mapped(bh) || buffer_freed(bh))
  998. return 0;
  999. /*
  1000. * __block_write_begin() could have dirtied some buffers. Clean
  1001. * the dirty bit as jbd2_journal_get_write_access() could complain
  1002. * otherwise about fs integrity issues. Setting of the dirty bit
  1003. * by __block_write_begin() isn't a real problem here as we clear
  1004. * the bit before releasing a page lock and thus writeback cannot
  1005. * ever write the buffer.
  1006. */
  1007. if (dirty)
  1008. clear_buffer_dirty(bh);
  1009. BUFFER_TRACE(bh, "get write access");
  1010. ret = ext4_journal_get_write_access(handle, bh);
  1011. if (!ret && dirty)
  1012. ret = ext4_handle_dirty_metadata(handle, NULL, bh);
  1013. return ret;
  1014. }
  1015. #ifdef CONFIG_EXT4_FS_ENCRYPTION
  1016. static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
  1017. get_block_t *get_block)
  1018. {
  1019. unsigned from = pos & (PAGE_SIZE - 1);
  1020. unsigned to = from + len;
  1021. struct inode *inode = page->mapping->host;
  1022. unsigned block_start, block_end;
  1023. sector_t block;
  1024. int err = 0;
  1025. unsigned blocksize = inode->i_sb->s_blocksize;
  1026. unsigned bbits;
  1027. struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
  1028. bool decrypt = false;
  1029. BUG_ON(!PageLocked(page));
  1030. BUG_ON(from > PAGE_SIZE);
  1031. BUG_ON(to > PAGE_SIZE);
  1032. BUG_ON(from > to);
  1033. if (!page_has_buffers(page))
  1034. create_empty_buffers(page, blocksize, 0);
  1035. head = page_buffers(page);
  1036. bbits = ilog2(blocksize);
  1037. block = (sector_t)page->index << (PAGE_SHIFT - bbits);
  1038. for (bh = head, block_start = 0; bh != head || !block_start;
  1039. block++, block_start = block_end, bh = bh->b_this_page) {
  1040. block_end = block_start + blocksize;
  1041. if (block_end <= from || block_start >= to) {
  1042. if (PageUptodate(page)) {
  1043. if (!buffer_uptodate(bh))
  1044. set_buffer_uptodate(bh);
  1045. }
  1046. continue;
  1047. }
  1048. if (buffer_new(bh))
  1049. clear_buffer_new(bh);
  1050. if (!buffer_mapped(bh)) {
  1051. WARN_ON(bh->b_size != blocksize);
  1052. err = get_block(inode, block, bh, 1);
  1053. if (err)
  1054. break;
  1055. if (buffer_new(bh)) {
  1056. clean_bdev_bh_alias(bh);
  1057. if (PageUptodate(page)) {
  1058. clear_buffer_new(bh);
  1059. set_buffer_uptodate(bh);
  1060. mark_buffer_dirty(bh);
  1061. continue;
  1062. }
  1063. if (block_end > to || block_start < from)
  1064. zero_user_segments(page, to, block_end,
  1065. block_start, from);
  1066. continue;
  1067. }
  1068. }
  1069. if (PageUptodate(page)) {
  1070. if (!buffer_uptodate(bh))
  1071. set_buffer_uptodate(bh);
  1072. continue;
  1073. }
  1074. if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
  1075. !buffer_unwritten(bh) &&
  1076. (block_start < from || block_end > to)) {
  1077. ll_rw_block(REQ_OP_READ, 0, 1, &bh);
  1078. *wait_bh++ = bh;
  1079. decrypt = ext4_encrypted_inode(inode) &&
  1080. S_ISREG(inode->i_mode);
  1081. }
  1082. }
  1083. /*
  1084. * If we issued read requests, let them complete.
  1085. */
  1086. while (wait_bh > wait) {
  1087. wait_on_buffer(*--wait_bh);
  1088. if (!buffer_uptodate(*wait_bh))
  1089. err = -EIO;
  1090. }
  1091. if (unlikely(err))
  1092. page_zero_new_buffers(page, from, to);
  1093. else if (decrypt)
  1094. err = fscrypt_decrypt_page(page->mapping->host, page,
  1095. PAGE_SIZE, 0, page->index);
  1096. return err;
  1097. }
  1098. #endif
  1099. static int ext4_write_begin(struct file *file, struct address_space *mapping,
  1100. loff_t pos, unsigned len, unsigned flags,
  1101. struct page **pagep, void **fsdata)
  1102. {
  1103. struct inode *inode = mapping->host;
  1104. int ret, needed_blocks;
  1105. handle_t *handle;
  1106. int retries = 0;
  1107. struct page *page;
  1108. pgoff_t index;
  1109. unsigned from, to;
  1110. if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
  1111. return -EIO;
  1112. trace_ext4_write_begin(inode, pos, len, flags);
  1113. /*
  1114. * Reserve one block more for addition to orphan list in case
  1115. * we allocate blocks but write fails for some reason
  1116. */
  1117. needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
  1118. index = pos >> PAGE_SHIFT;
  1119. from = pos & (PAGE_SIZE - 1);
  1120. to = from + len;
  1121. if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
  1122. ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
  1123. flags, pagep);
  1124. if (ret < 0)
  1125. return ret;
  1126. if (ret == 1)
  1127. return 0;
  1128. }
  1129. /*
  1130. * grab_cache_page_write_begin() can take a long time if the
  1131. * system is thrashing due to memory pressure, or if the page
  1132. * is being written back. So grab it first before we start
  1133. * the transaction handle. This also allows us to allocate
  1134. * the page (if needed) without using GFP_NOFS.
  1135. */
  1136. retry_grab:
  1137. page = grab_cache_page_write_begin(mapping, index, flags);
  1138. if (!page)
  1139. return -ENOMEM;
  1140. unlock_page(page);
  1141. retry_journal:
  1142. handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
  1143. if (IS_ERR(handle)) {
  1144. put_page(page);
  1145. return PTR_ERR(handle);
  1146. }
  1147. lock_page(page);
  1148. if (page->mapping != mapping) {
  1149. /* The page got truncated from under us */
  1150. unlock_page(page);
  1151. put_page(page);
  1152. ext4_journal_stop(handle);
  1153. goto retry_grab;
  1154. }
  1155. /* In case writeback began while the page was unlocked */
  1156. wait_for_stable_page(page);
  1157. #ifdef CONFIG_EXT4_FS_ENCRYPTION
  1158. if (ext4_should_dioread_nolock(inode))
  1159. ret = ext4_block_write_begin(page, pos, len,
  1160. ext4_get_block_unwritten);
  1161. else
  1162. ret = ext4_block_write_begin(page, pos, len,
  1163. ext4_get_block);
  1164. #else
  1165. if (ext4_should_dioread_nolock(inode))
  1166. ret = __block_write_begin(page, pos, len,
  1167. ext4_get_block_unwritten);
  1168. else
  1169. ret = __block_write_begin(page, pos, len, ext4_get_block);
  1170. #endif
  1171. if (!ret && ext4_should_journal_data(inode)) {
  1172. ret = ext4_walk_page_buffers(handle, page_buffers(page),
  1173. from, to, NULL,
  1174. do_journal_get_write_access);
  1175. }
  1176. if (ret) {
  1177. unlock_page(page);
  1178. /*
  1179. * __block_write_begin may have instantiated a few blocks
  1180. * outside i_size. Trim these off again. Don't need
  1181. * i_size_read because we hold i_mutex.
  1182. *
  1183. * Add inode to orphan list in case we crash before
  1184. * truncate finishes
  1185. */
  1186. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  1187. ext4_orphan_add(handle, inode);
  1188. ext4_journal_stop(handle);
  1189. if (pos + len > inode->i_size) {
  1190. ext4_truncate_failed_write(inode);
  1191. /*
  1192. * If truncate failed early the inode might
  1193. * still be on the orphan list; we need to
  1194. * make sure the inode is removed from the
  1195. * orphan list in that case.
  1196. */
  1197. if (inode->i_nlink)
  1198. ext4_orphan_del(NULL, inode);
  1199. }
  1200. if (ret == -ENOSPC &&
  1201. ext4_should_retry_alloc(inode->i_sb, &retries))
  1202. goto retry_journal;
  1203. put_page(page);
  1204. return ret;
  1205. }
  1206. *pagep = page;
  1207. return ret;
  1208. }
  1209. /* For write_end() in data=journal mode */
  1210. static int write_end_fn(handle_t *handle, struct buffer_head *bh)
  1211. {
  1212. int ret;
  1213. if (!buffer_mapped(bh) || buffer_freed(bh))
  1214. return 0;
  1215. set_buffer_uptodate(bh);
  1216. ret = ext4_handle_dirty_metadata(handle, NULL, bh);
  1217. clear_buffer_meta(bh);
  1218. clear_buffer_prio(bh);
  1219. return ret;
  1220. }
  1221. /*
  1222. * We need to pick up the new inode size which generic_commit_write gave us
  1223. * `file' can be NULL - eg, when called from page_symlink().
  1224. *
  1225. * ext4 never places buffers on inode->i_mapping->private_list. metadata
  1226. * buffers are managed internally.
  1227. */
  1228. static int ext4_write_end(struct file *file,
  1229. struct address_space *mapping,
  1230. loff_t pos, unsigned len, unsigned copied,
  1231. struct page *page, void *fsdata)
  1232. {
  1233. handle_t *handle = ext4_journal_current_handle();
  1234. struct inode *inode = mapping->host;
  1235. loff_t old_size = inode->i_size;
  1236. int ret = 0, ret2;
  1237. int i_size_changed = 0;
  1238. trace_ext4_write_end(inode, pos, len, copied);
  1239. if (ext4_has_inline_data(inode)) {
  1240. ret = ext4_write_inline_data_end(inode, pos, len,
  1241. copied, page);
  1242. if (ret < 0) {
  1243. unlock_page(page);
  1244. put_page(page);
  1245. goto errout;
  1246. }
  1247. copied = ret;
  1248. } else
  1249. copied = block_write_end(file, mapping, pos,
  1250. len, copied, page, fsdata);
  1251. /*
  1252. * it's important to update i_size while still holding page lock:
  1253. * page writeout could otherwise come in and zero beyond i_size.
  1254. */
  1255. i_size_changed = ext4_update_inode_size(inode, pos + copied);
  1256. unlock_page(page);
  1257. put_page(page);
  1258. if (old_size < pos)
  1259. pagecache_isize_extended(inode, old_size, pos);
  1260. /*
  1261. * Don't mark the inode dirty under page lock. First, it unnecessarily
  1262. * makes the holding time of page lock longer. Second, it forces lock
  1263. * ordering of page lock and transaction start for journaling
  1264. * filesystems.
  1265. */
  1266. if (i_size_changed)
  1267. ext4_mark_inode_dirty(handle, inode);
  1268. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  1269. /* if we have allocated more blocks and copied
  1270. * less. We will have blocks allocated outside
  1271. * inode->i_size. So truncate them
  1272. */
  1273. ext4_orphan_add(handle, inode);
  1274. errout:
  1275. ret2 = ext4_journal_stop(handle);
  1276. if (!ret)
  1277. ret = ret2;
  1278. if (pos + len > inode->i_size) {
  1279. ext4_truncate_failed_write(inode);
  1280. /*
  1281. * If truncate failed early the inode might still be
  1282. * on the orphan list; we need to make sure the inode
  1283. * is removed from the orphan list in that case.
  1284. */
  1285. if (inode->i_nlink)
  1286. ext4_orphan_del(NULL, inode);
  1287. }
  1288. return ret ? ret : copied;
  1289. }
  1290. /*
  1291. * This is a private version of page_zero_new_buffers() which doesn't
  1292. * set the buffer to be dirty, since in data=journalled mode we need
  1293. * to call ext4_handle_dirty_metadata() instead.
  1294. */
  1295. static void ext4_journalled_zero_new_buffers(handle_t *handle,
  1296. struct page *page,
  1297. unsigned from, unsigned to)
  1298. {
  1299. unsigned int block_start = 0, block_end;
  1300. struct buffer_head *head, *bh;
  1301. bh = head = page_buffers(page);
  1302. do {
  1303. block_end = block_start + bh->b_size;
  1304. if (buffer_new(bh)) {
  1305. if (block_end > from && block_start < to) {
  1306. if (!PageUptodate(page)) {
  1307. unsigned start, size;
  1308. start = max(from, block_start);
  1309. size = min(to, block_end) - start;
  1310. zero_user(page, start, size);
  1311. write_end_fn(handle, bh);
  1312. }
  1313. clear_buffer_new(bh);
  1314. }
  1315. }
  1316. block_start = block_end;
  1317. bh = bh->b_this_page;
  1318. } while (bh != head);
  1319. }
  1320. static int ext4_journalled_write_end(struct file *file,
  1321. struct address_space *mapping,
  1322. loff_t pos, unsigned len, unsigned copied,
  1323. struct page *page, void *fsdata)
  1324. {
  1325. handle_t *handle = ext4_journal_current_handle();
  1326. struct inode *inode = mapping->host;
  1327. loff_t old_size = inode->i_size;
  1328. int ret = 0, ret2;
  1329. int partial = 0;
  1330. unsigned from, to;
  1331. int size_changed = 0;
  1332. trace_ext4_journalled_write_end(inode, pos, len, copied);
  1333. from = pos & (PAGE_SIZE - 1);
  1334. to = from + len;
  1335. BUG_ON(!ext4_handle_valid(handle));
  1336. if (ext4_has_inline_data(inode)) {
  1337. ret = ext4_write_inline_data_end(inode, pos, len,
  1338. copied, page);
  1339. if (ret < 0) {
  1340. unlock_page(page);
  1341. put_page(page);
  1342. goto errout;
  1343. }
  1344. copied = ret;
  1345. } else if (unlikely(copied < len) && !PageUptodate(page)) {
  1346. copied = 0;
  1347. ext4_journalled_zero_new_buffers(handle, page, from, to);
  1348. } else {
  1349. if (unlikely(copied < len))
  1350. ext4_journalled_zero_new_buffers(handle, page,
  1351. from + copied, to);
  1352. ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
  1353. from + copied, &partial,
  1354. write_end_fn);
  1355. if (!partial)
  1356. SetPageUptodate(page);
  1357. }
  1358. size_changed = ext4_update_inode_size(inode, pos + copied);
  1359. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  1360. EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
  1361. unlock_page(page);
  1362. put_page(page);
  1363. if (old_size < pos)
  1364. pagecache_isize_extended(inode, old_size, pos);
  1365. if (size_changed) {
  1366. ret2 = ext4_mark_inode_dirty(handle, inode);
  1367. if (!ret)
  1368. ret = ret2;
  1369. }
  1370. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  1371. /* if we have allocated more blocks and copied
  1372. * less. We will have blocks allocated outside
  1373. * inode->i_size. So truncate them
  1374. */
  1375. ext4_orphan_add(handle, inode);
  1376. errout:
  1377. ret2 = ext4_journal_stop(handle);
  1378. if (!ret)
  1379. ret = ret2;
  1380. if (pos + len > inode->i_size) {
  1381. ext4_truncate_failed_write(inode);
  1382. /*
  1383. * If truncate failed early the inode might still be
  1384. * on the orphan list; we need to make sure the inode
  1385. * is removed from the orphan list in that case.
  1386. */
  1387. if (inode->i_nlink)
  1388. ext4_orphan_del(NULL, inode);
  1389. }
  1390. return ret ? ret : copied;
  1391. }
  1392. /*
  1393. * Reserve space for a single cluster
  1394. */
  1395. static int ext4_da_reserve_space(struct inode *inode)
  1396. {
  1397. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1398. struct ext4_inode_info *ei = EXT4_I(inode);
  1399. int ret;
  1400. /*
  1401. * We will charge metadata quota at writeout time; this saves
  1402. * us from metadata over-estimation, though we may go over by
  1403. * a small amount in the end. Here we just reserve for data.
  1404. */
  1405. ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
  1406. if (ret)
  1407. return ret;
  1408. spin_lock(&ei->i_block_reservation_lock);
  1409. if (ext4_claim_free_clusters(sbi, 1, 0)) {
  1410. spin_unlock(&ei->i_block_reservation_lock);
  1411. dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
  1412. return -ENOSPC;
  1413. }
  1414. ei->i_reserved_data_blocks++;
  1415. trace_ext4_da_reserve_space(inode);
  1416. spin_unlock(&ei->i_block_reservation_lock);
  1417. return 0; /* success */
  1418. }
  1419. static void ext4_da_release_space(struct inode *inode, int to_free)
  1420. {
  1421. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1422. struct ext4_inode_info *ei = EXT4_I(inode);
  1423. if (!to_free)
  1424. return; /* Nothing to release, exit */
  1425. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  1426. trace_ext4_da_release_space(inode, to_free);
  1427. if (unlikely(to_free > ei->i_reserved_data_blocks)) {
  1428. /*
  1429. * if there aren't enough reserved blocks, then the
  1430. * counter is messed up somewhere. Since this
  1431. * function is called from invalidate page, it's
  1432. * harmless to return without any action.
  1433. */
  1434. ext4_warning(inode->i_sb, "ext4_da_release_space: "
  1435. "ino %lu, to_free %d with only %d reserved "
  1436. "data blocks", inode->i_ino, to_free,
  1437. ei->i_reserved_data_blocks);
  1438. WARN_ON(1);
  1439. to_free = ei->i_reserved_data_blocks;
  1440. }
  1441. ei->i_reserved_data_blocks -= to_free;
  1442. /* update fs dirty data blocks counter */
  1443. percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
  1444. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  1445. dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
  1446. }
  1447. static void ext4_da_page_release_reservation(struct page *page,
  1448. unsigned int offset,
  1449. unsigned int length)
  1450. {
  1451. int to_release = 0, contiguous_blks = 0;
  1452. struct buffer_head *head, *bh;
  1453. unsigned int curr_off = 0;
  1454. struct inode *inode = page->mapping->host;
  1455. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1456. unsigned int stop = offset + length;
  1457. int num_clusters;
  1458. ext4_fsblk_t lblk;
  1459. BUG_ON(stop > PAGE_SIZE || stop < length);
  1460. head = page_buffers(page);
  1461. bh = head;
  1462. do {
  1463. unsigned int next_off = curr_off + bh->b_size;
  1464. if (next_off > stop)
  1465. break;
  1466. if ((offset <= curr_off) && (buffer_delay(bh))) {
  1467. to_release++;
  1468. contiguous_blks++;
  1469. clear_buffer_delay(bh);
  1470. } else if (contiguous_blks) {
  1471. lblk = page->index <<
  1472. (PAGE_SHIFT - inode->i_blkbits);
  1473. lblk += (curr_off >> inode->i_blkbits) -
  1474. contiguous_blks;
  1475. ext4_es_remove_extent(inode, lblk, contiguous_blks);
  1476. contiguous_blks = 0;
  1477. }
  1478. curr_off = next_off;
  1479. } while ((bh = bh->b_this_page) != head);
  1480. if (contiguous_blks) {
  1481. lblk = page->index << (PAGE_SHIFT - inode->i_blkbits);
  1482. lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
  1483. ext4_es_remove_extent(inode, lblk, contiguous_blks);
  1484. }
  1485. /* If we have released all the blocks belonging to a cluster, then we
  1486. * need to release the reserved space for that cluster. */
  1487. num_clusters = EXT4_NUM_B2C(sbi, to_release);
  1488. while (num_clusters > 0) {
  1489. lblk = (page->index << (PAGE_SHIFT - inode->i_blkbits)) +
  1490. ((num_clusters - 1) << sbi->s_cluster_bits);
  1491. if (sbi->s_cluster_ratio == 1 ||
  1492. !ext4_find_delalloc_cluster(inode, lblk))
  1493. ext4_da_release_space(inode, 1);
  1494. num_clusters--;
  1495. }
  1496. }
  1497. /*
  1498. * Delayed allocation stuff
  1499. */
  1500. struct mpage_da_data {
  1501. struct inode *inode;
  1502. struct writeback_control *wbc;
  1503. pgoff_t first_page; /* The first page to write */
  1504. pgoff_t next_page; /* Current page to examine */
  1505. pgoff_t last_page; /* Last page to examine */
  1506. /*
  1507. * Extent to map - this can be after first_page because that can be
  1508. * fully mapped. We somewhat abuse m_flags to store whether the extent
  1509. * is delalloc or unwritten.
  1510. */
  1511. struct ext4_map_blocks map;
  1512. struct ext4_io_submit io_submit; /* IO submission data */
  1513. unsigned int do_map:1;
  1514. };
  1515. static void mpage_release_unused_pages(struct mpage_da_data *mpd,
  1516. bool invalidate)
  1517. {
  1518. int nr_pages, i;
  1519. pgoff_t index, end;
  1520. struct pagevec pvec;
  1521. struct inode *inode = mpd->inode;
  1522. struct address_space *mapping = inode->i_mapping;
  1523. /* This is necessary when next_page == 0. */
  1524. if (mpd->first_page >= mpd->next_page)
  1525. return;
  1526. index = mpd->first_page;
  1527. end = mpd->next_page - 1;
  1528. if (invalidate) {
  1529. ext4_lblk_t start, last;
  1530. start = index << (PAGE_SHIFT - inode->i_blkbits);
  1531. last = end << (PAGE_SHIFT - inode->i_blkbits);
  1532. ext4_es_remove_extent(inode, start, last - start + 1);
  1533. }
  1534. pagevec_init(&pvec, 0);
  1535. while (index <= end) {
  1536. nr_pages = pagevec_lookup(&pvec, mapping, &index, PAGEVEC_SIZE);
  1537. if (nr_pages == 0)
  1538. break;
  1539. for (i = 0; i < nr_pages; i++) {
  1540. struct page *page = pvec.pages[i];
  1541. if (page->index > end)
  1542. break;
  1543. BUG_ON(!PageLocked(page));
  1544. BUG_ON(PageWriteback(page));
  1545. if (invalidate) {
  1546. if (page_mapped(page))
  1547. clear_page_dirty_for_io(page);
  1548. block_invalidatepage(page, 0, PAGE_SIZE);
  1549. ClearPageUptodate(page);
  1550. }
  1551. unlock_page(page);
  1552. }
  1553. pagevec_release(&pvec);
  1554. }
  1555. }
  1556. static void ext4_print_free_blocks(struct inode *inode)
  1557. {
  1558. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1559. struct super_block *sb = inode->i_sb;
  1560. struct ext4_inode_info *ei = EXT4_I(inode);
  1561. ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
  1562. EXT4_C2B(EXT4_SB(inode->i_sb),
  1563. ext4_count_free_clusters(sb)));
  1564. ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
  1565. ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
  1566. (long long) EXT4_C2B(EXT4_SB(sb),
  1567. percpu_counter_sum(&sbi->s_freeclusters_counter)));
  1568. ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
  1569. (long long) EXT4_C2B(EXT4_SB(sb),
  1570. percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
  1571. ext4_msg(sb, KERN_CRIT, "Block reservation details");
  1572. ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
  1573. ei->i_reserved_data_blocks);
  1574. return;
  1575. }
  1576. static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
  1577. {
  1578. return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
  1579. }
  1580. /*
  1581. * This function is grabs code from the very beginning of
  1582. * ext4_map_blocks, but assumes that the caller is from delayed write
  1583. * time. This function looks up the requested blocks and sets the
  1584. * buffer delay bit under the protection of i_data_sem.
  1585. */
  1586. static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
  1587. struct ext4_map_blocks *map,
  1588. struct buffer_head *bh)
  1589. {
  1590. struct extent_status es;
  1591. int retval;
  1592. sector_t invalid_block = ~((sector_t) 0xffff);
  1593. #ifdef ES_AGGRESSIVE_TEST
  1594. struct ext4_map_blocks orig_map;
  1595. memcpy(&orig_map, map, sizeof(*map));
  1596. #endif
  1597. if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
  1598. invalid_block = ~0;
  1599. map->m_flags = 0;
  1600. ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
  1601. "logical block %lu\n", inode->i_ino, map->m_len,
  1602. (unsigned long) map->m_lblk);
  1603. /* Lookup extent status tree firstly */
  1604. if (ext4_es_lookup_extent(inode, iblock, &es)) {
  1605. if (ext4_es_is_hole(&es)) {
  1606. retval = 0;
  1607. down_read(&EXT4_I(inode)->i_data_sem);
  1608. goto add_delayed;
  1609. }
  1610. /*
  1611. * Delayed extent could be allocated by fallocate.
  1612. * So we need to check it.
  1613. */
  1614. if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
  1615. map_bh(bh, inode->i_sb, invalid_block);
  1616. set_buffer_new(bh);
  1617. set_buffer_delay(bh);
  1618. return 0;
  1619. }
  1620. map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
  1621. retval = es.es_len - (iblock - es.es_lblk);
  1622. if (retval > map->m_len)
  1623. retval = map->m_len;
  1624. map->m_len = retval;
  1625. if (ext4_es_is_written(&es))
  1626. map->m_flags |= EXT4_MAP_MAPPED;
  1627. else if (ext4_es_is_unwritten(&es))
  1628. map->m_flags |= EXT4_MAP_UNWRITTEN;
  1629. else
  1630. BUG_ON(1);
  1631. #ifdef ES_AGGRESSIVE_TEST
  1632. ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
  1633. #endif
  1634. return retval;
  1635. }
  1636. /*
  1637. * Try to see if we can get the block without requesting a new
  1638. * file system block.
  1639. */
  1640. down_read(&EXT4_I(inode)->i_data_sem);
  1641. if (ext4_has_inline_data(inode))
  1642. retval = 0;
  1643. else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  1644. retval = ext4_ext_map_blocks(NULL, inode, map, 0);
  1645. else
  1646. retval = ext4_ind_map_blocks(NULL, inode, map, 0);
  1647. add_delayed:
  1648. if (retval == 0) {
  1649. int ret;
  1650. /*
  1651. * XXX: __block_prepare_write() unmaps passed block,
  1652. * is it OK?
  1653. */
  1654. /*
  1655. * If the block was allocated from previously allocated cluster,
  1656. * then we don't need to reserve it again. However we still need
  1657. * to reserve metadata for every block we're going to write.
  1658. */
  1659. if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
  1660. !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
  1661. ret = ext4_da_reserve_space(inode);
  1662. if (ret) {
  1663. /* not enough space to reserve */
  1664. retval = ret;
  1665. goto out_unlock;
  1666. }
  1667. }
  1668. ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
  1669. ~0, EXTENT_STATUS_DELAYED);
  1670. if (ret) {
  1671. retval = ret;
  1672. goto out_unlock;
  1673. }
  1674. map_bh(bh, inode->i_sb, invalid_block);
  1675. set_buffer_new(bh);
  1676. set_buffer_delay(bh);
  1677. } else if (retval > 0) {
  1678. int ret;
  1679. unsigned int status;
  1680. if (unlikely(retval != map->m_len)) {
  1681. ext4_warning(inode->i_sb,
  1682. "ES len assertion failed for inode "
  1683. "%lu: retval %d != map->m_len %d",
  1684. inode->i_ino, retval, map->m_len);
  1685. WARN_ON(1);
  1686. }
  1687. status = map->m_flags & EXT4_MAP_UNWRITTEN ?
  1688. EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
  1689. ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
  1690. map->m_pblk, status);
  1691. if (ret != 0)
  1692. retval = ret;
  1693. }
  1694. out_unlock:
  1695. up_read((&EXT4_I(inode)->i_data_sem));
  1696. return retval;
  1697. }
  1698. /*
  1699. * This is a special get_block_t callback which is used by
  1700. * ext4_da_write_begin(). It will either return mapped block or
  1701. * reserve space for a single block.
  1702. *
  1703. * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
  1704. * We also have b_blocknr = -1 and b_bdev initialized properly
  1705. *
  1706. * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
  1707. * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
  1708. * initialized properly.
  1709. */
  1710. int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
  1711. struct buffer_head *bh, int create)
  1712. {
  1713. struct ext4_map_blocks map;
  1714. int ret = 0;
  1715. BUG_ON(create == 0);
  1716. BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
  1717. map.m_lblk = iblock;
  1718. map.m_len = 1;
  1719. /*
  1720. * first, we need to know whether the block is allocated already
  1721. * preallocated blocks are unmapped but should treated
  1722. * the same as allocated blocks.
  1723. */
  1724. ret = ext4_da_map_blocks(inode, iblock, &map, bh);
  1725. if (ret <= 0)
  1726. return ret;
  1727. map_bh(bh, inode->i_sb, map.m_pblk);
  1728. ext4_update_bh_state(bh, map.m_flags);
  1729. if (buffer_unwritten(bh)) {
  1730. /* A delayed write to unwritten bh should be marked
  1731. * new and mapped. Mapped ensures that we don't do
  1732. * get_block multiple times when we write to the same
  1733. * offset and new ensures that we do proper zero out
  1734. * for partial write.
  1735. */
  1736. set_buffer_new(bh);
  1737. set_buffer_mapped(bh);
  1738. }
  1739. return 0;
  1740. }
  1741. static int bget_one(handle_t *handle, struct buffer_head *bh)
  1742. {
  1743. get_bh(bh);
  1744. return 0;
  1745. }
  1746. static int bput_one(handle_t *handle, struct buffer_head *bh)
  1747. {
  1748. put_bh(bh);
  1749. return 0;
  1750. }
  1751. static int __ext4_journalled_writepage(struct page *page,
  1752. unsigned int len)
  1753. {
  1754. struct address_space *mapping = page->mapping;
  1755. struct inode *inode = mapping->host;
  1756. struct buffer_head *page_bufs = NULL;
  1757. handle_t *handle = NULL;
  1758. int ret = 0, err = 0;
  1759. int inline_data = ext4_has_inline_data(inode);
  1760. struct buffer_head *inode_bh = NULL;
  1761. ClearPageChecked(page);
  1762. if (inline_data) {
  1763. BUG_ON(page->index != 0);
  1764. BUG_ON(len > ext4_get_max_inline_size(inode));
  1765. inode_bh = ext4_journalled_write_inline_data(inode, len, page);
  1766. if (inode_bh == NULL)
  1767. goto out;
  1768. } else {
  1769. page_bufs = page_buffers(page);
  1770. if (!page_bufs) {
  1771. BUG();
  1772. goto out;
  1773. }
  1774. ext4_walk_page_buffers(handle, page_bufs, 0, len,
  1775. NULL, bget_one);
  1776. }
  1777. /*
  1778. * We need to release the page lock before we start the
  1779. * journal, so grab a reference so the page won't disappear
  1780. * out from under us.
  1781. */
  1782. get_page(page);
  1783. unlock_page(page);
  1784. handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
  1785. ext4_writepage_trans_blocks(inode));
  1786. if (IS_ERR(handle)) {
  1787. ret = PTR_ERR(handle);
  1788. put_page(page);
  1789. goto out_no_pagelock;
  1790. }
  1791. BUG_ON(!ext4_handle_valid(handle));
  1792. lock_page(page);
  1793. put_page(page);
  1794. if (page->mapping != mapping) {
  1795. /* The page got truncated from under us */
  1796. ext4_journal_stop(handle);
  1797. ret = 0;
  1798. goto out;
  1799. }
  1800. if (inline_data) {
  1801. BUFFER_TRACE(inode_bh, "get write access");
  1802. ret = ext4_journal_get_write_access(handle, inode_bh);
  1803. err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
  1804. } else {
  1805. ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
  1806. do_journal_get_write_access);
  1807. err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
  1808. write_end_fn);
  1809. }
  1810. if (ret == 0)
  1811. ret = err;
  1812. EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
  1813. err = ext4_journal_stop(handle);
  1814. if (!ret)
  1815. ret = err;
  1816. if (!ext4_has_inline_data(inode))
  1817. ext4_walk_page_buffers(NULL, page_bufs, 0, len,
  1818. NULL, bput_one);
  1819. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  1820. out:
  1821. unlock_page(page);
  1822. out_no_pagelock:
  1823. brelse(inode_bh);
  1824. return ret;
  1825. }
  1826. /*
  1827. * Note that we don't need to start a transaction unless we're journaling data
  1828. * because we should have holes filled from ext4_page_mkwrite(). We even don't
  1829. * need to file the inode to the transaction's list in ordered mode because if
  1830. * we are writing back data added by write(), the inode is already there and if
  1831. * we are writing back data modified via mmap(), no one guarantees in which
  1832. * transaction the data will hit the disk. In case we are journaling data, we
  1833. * cannot start transaction directly because transaction start ranks above page
  1834. * lock so we have to do some magic.
  1835. *
  1836. * This function can get called via...
  1837. * - ext4_writepages after taking page lock (have journal handle)
  1838. * - journal_submit_inode_data_buffers (no journal handle)
  1839. * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
  1840. * - grab_page_cache when doing write_begin (have journal handle)
  1841. *
  1842. * We don't do any block allocation in this function. If we have page with
  1843. * multiple blocks we need to write those buffer_heads that are mapped. This
  1844. * is important for mmaped based write. So if we do with blocksize 1K
  1845. * truncate(f, 1024);
  1846. * a = mmap(f, 0, 4096);
  1847. * a[0] = 'a';
  1848. * truncate(f, 4096);
  1849. * we have in the page first buffer_head mapped via page_mkwrite call back
  1850. * but other buffer_heads would be unmapped but dirty (dirty done via the
  1851. * do_wp_page). So writepage should write the first block. If we modify
  1852. * the mmap area beyond 1024 we will again get a page_fault and the
  1853. * page_mkwrite callback will do the block allocation and mark the
  1854. * buffer_heads mapped.
  1855. *
  1856. * We redirty the page if we have any buffer_heads that is either delay or
  1857. * unwritten in the page.
  1858. *
  1859. * We can get recursively called as show below.
  1860. *
  1861. * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
  1862. * ext4_writepage()
  1863. *
  1864. * But since we don't do any block allocation we should not deadlock.
  1865. * Page also have the dirty flag cleared so we don't get recurive page_lock.
  1866. */
  1867. static int ext4_writepage(struct page *page,
  1868. struct writeback_control *wbc)
  1869. {
  1870. int ret = 0;
  1871. loff_t size;
  1872. unsigned int len;
  1873. struct buffer_head *page_bufs = NULL;
  1874. struct inode *inode = page->mapping->host;
  1875. struct ext4_io_submit io_submit;
  1876. bool keep_towrite = false;
  1877. if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
  1878. ext4_invalidatepage(page, 0, PAGE_SIZE);
  1879. unlock_page(page);
  1880. return -EIO;
  1881. }
  1882. trace_ext4_writepage(page);
  1883. size = i_size_read(inode);
  1884. if (page->index == size >> PAGE_SHIFT)
  1885. len = size & ~PAGE_MASK;
  1886. else
  1887. len = PAGE_SIZE;
  1888. page_bufs = page_buffers(page);
  1889. /*
  1890. * We cannot do block allocation or other extent handling in this
  1891. * function. If there are buffers needing that, we have to redirty
  1892. * the page. But we may reach here when we do a journal commit via
  1893. * journal_submit_inode_data_buffers() and in that case we must write
  1894. * allocated buffers to achieve data=ordered mode guarantees.
  1895. *
  1896. * Also, if there is only one buffer per page (the fs block
  1897. * size == the page size), if one buffer needs block
  1898. * allocation or needs to modify the extent tree to clear the
  1899. * unwritten flag, we know that the page can't be written at
  1900. * all, so we might as well refuse the write immediately.
  1901. * Unfortunately if the block size != page size, we can't as
  1902. * easily detect this case using ext4_walk_page_buffers(), but
  1903. * for the extremely common case, this is an optimization that
  1904. * skips a useless round trip through ext4_bio_write_page().
  1905. */
  1906. if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  1907. ext4_bh_delay_or_unwritten)) {
  1908. redirty_page_for_writepage(wbc, page);
  1909. if ((current->flags & PF_MEMALLOC) ||
  1910. (inode->i_sb->s_blocksize == PAGE_SIZE)) {
  1911. /*
  1912. * For memory cleaning there's no point in writing only
  1913. * some buffers. So just bail out. Warn if we came here
  1914. * from direct reclaim.
  1915. */
  1916. WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
  1917. == PF_MEMALLOC);
  1918. unlock_page(page);
  1919. return 0;
  1920. }
  1921. keep_towrite = true;
  1922. }
  1923. if (PageChecked(page) && ext4_should_journal_data(inode))
  1924. /*
  1925. * It's mmapped pagecache. Add buffers and journal it. There
  1926. * doesn't seem much point in redirtying the page here.
  1927. */
  1928. return __ext4_journalled_writepage(page, len);
  1929. ext4_io_submit_init(&io_submit, wbc);
  1930. io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
  1931. if (!io_submit.io_end) {
  1932. redirty_page_for_writepage(wbc, page);
  1933. unlock_page(page);
  1934. return -ENOMEM;
  1935. }
  1936. ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
  1937. ext4_io_submit(&io_submit);
  1938. /* Drop io_end reference we got from init */
  1939. ext4_put_io_end_defer(io_submit.io_end);
  1940. return ret;
  1941. }
  1942. static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
  1943. {
  1944. int len;
  1945. loff_t size;
  1946. int err;
  1947. BUG_ON(page->index != mpd->first_page);
  1948. clear_page_dirty_for_io(page);
  1949. /*
  1950. * We have to be very careful here! Nothing protects writeback path
  1951. * against i_size changes and the page can be writeably mapped into
  1952. * page tables. So an application can be growing i_size and writing
  1953. * data through mmap while writeback runs. clear_page_dirty_for_io()
  1954. * write-protects our page in page tables and the page cannot get
  1955. * written to again until we release page lock. So only after
  1956. * clear_page_dirty_for_io() we are safe to sample i_size for
  1957. * ext4_bio_write_page() to zero-out tail of the written page. We rely
  1958. * on the barrier provided by TestClearPageDirty in
  1959. * clear_page_dirty_for_io() to make sure i_size is really sampled only
  1960. * after page tables are updated.
  1961. */
  1962. size = i_size_read(mpd->inode);
  1963. if (page->index == size >> PAGE_SHIFT)
  1964. len = size & ~PAGE_MASK;
  1965. else
  1966. len = PAGE_SIZE;
  1967. err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
  1968. if (!err)
  1969. mpd->wbc->nr_to_write--;
  1970. mpd->first_page++;
  1971. return err;
  1972. }
  1973. #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
  1974. /*
  1975. * mballoc gives us at most this number of blocks...
  1976. * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
  1977. * The rest of mballoc seems to handle chunks up to full group size.
  1978. */
  1979. #define MAX_WRITEPAGES_EXTENT_LEN 2048
  1980. /*
  1981. * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
  1982. *
  1983. * @mpd - extent of blocks
  1984. * @lblk - logical number of the block in the file
  1985. * @bh - buffer head we want to add to the extent
  1986. *
  1987. * The function is used to collect contig. blocks in the same state. If the
  1988. * buffer doesn't require mapping for writeback and we haven't started the
  1989. * extent of buffers to map yet, the function returns 'true' immediately - the
  1990. * caller can write the buffer right away. Otherwise the function returns true
  1991. * if the block has been added to the extent, false if the block couldn't be
  1992. * added.
  1993. */
  1994. static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
  1995. struct buffer_head *bh)
  1996. {
  1997. struct ext4_map_blocks *map = &mpd->map;
  1998. /* Buffer that doesn't need mapping for writeback? */
  1999. if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
  2000. (!buffer_delay(bh) && !buffer_unwritten(bh))) {
  2001. /* So far no extent to map => we write the buffer right away */
  2002. if (map->m_len == 0)
  2003. return true;
  2004. return false;
  2005. }
  2006. /* First block in the extent? */
  2007. if (map->m_len == 0) {
  2008. /* We cannot map unless handle is started... */
  2009. if (!mpd->do_map)
  2010. return false;
  2011. map->m_lblk = lblk;
  2012. map->m_len = 1;
  2013. map->m_flags = bh->b_state & BH_FLAGS;
  2014. return true;
  2015. }
  2016. /* Don't go larger than mballoc is willing to allocate */
  2017. if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
  2018. return false;
  2019. /* Can we merge the block to our big extent? */
  2020. if (lblk == map->m_lblk + map->m_len &&
  2021. (bh->b_state & BH_FLAGS) == map->m_flags) {
  2022. map->m_len++;
  2023. return true;
  2024. }
  2025. return false;
  2026. }
  2027. /*
  2028. * mpage_process_page_bufs - submit page buffers for IO or add them to extent
  2029. *
  2030. * @mpd - extent of blocks for mapping
  2031. * @head - the first buffer in the page
  2032. * @bh - buffer we should start processing from
  2033. * @lblk - logical number of the block in the file corresponding to @bh
  2034. *
  2035. * Walk through page buffers from @bh upto @head (exclusive) and either submit
  2036. * the page for IO if all buffers in this page were mapped and there's no
  2037. * accumulated extent of buffers to map or add buffers in the page to the
  2038. * extent of buffers to map. The function returns 1 if the caller can continue
  2039. * by processing the next page, 0 if it should stop adding buffers to the
  2040. * extent to map because we cannot extend it anymore. It can also return value
  2041. * < 0 in case of error during IO submission.
  2042. */
  2043. static int mpage_process_page_bufs(struct mpage_da_data *mpd,
  2044. struct buffer_head *head,
  2045. struct buffer_head *bh,
  2046. ext4_lblk_t lblk)
  2047. {
  2048. struct inode *inode = mpd->inode;
  2049. int err;
  2050. ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
  2051. >> inode->i_blkbits;
  2052. do {
  2053. BUG_ON(buffer_locked(bh));
  2054. if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
  2055. /* Found extent to map? */
  2056. if (mpd->map.m_len)
  2057. return 0;
  2058. /* Buffer needs mapping and handle is not started? */
  2059. if (!mpd->do_map)
  2060. return 0;
  2061. /* Everything mapped so far and we hit EOF */
  2062. break;
  2063. }
  2064. } while (lblk++, (bh = bh->b_this_page) != head);
  2065. /* So far everything mapped? Submit the page for IO. */
  2066. if (mpd->map.m_len == 0) {
  2067. err = mpage_submit_page(mpd, head->b_page);
  2068. if (err < 0)
  2069. return err;
  2070. }
  2071. return lblk < blocks;
  2072. }
  2073. /*
  2074. * mpage_map_buffers - update buffers corresponding to changed extent and
  2075. * submit fully mapped pages for IO
  2076. *
  2077. * @mpd - description of extent to map, on return next extent to map
  2078. *
  2079. * Scan buffers corresponding to changed extent (we expect corresponding pages
  2080. * to be already locked) and update buffer state according to new extent state.
  2081. * We map delalloc buffers to their physical location, clear unwritten bits,
  2082. * and mark buffers as uninit when we perform writes to unwritten extents
  2083. * and do extent conversion after IO is finished. If the last page is not fully
  2084. * mapped, we update @map to the next extent in the last page that needs
  2085. * mapping. Otherwise we submit the page for IO.
  2086. */
  2087. static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
  2088. {
  2089. struct pagevec pvec;
  2090. int nr_pages, i;
  2091. struct inode *inode = mpd->inode;
  2092. struct buffer_head *head, *bh;
  2093. int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
  2094. pgoff_t start, end;
  2095. ext4_lblk_t lblk;
  2096. sector_t pblock;
  2097. int err;
  2098. start = mpd->map.m_lblk >> bpp_bits;
  2099. end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
  2100. lblk = start << bpp_bits;
  2101. pblock = mpd->map.m_pblk;
  2102. pagevec_init(&pvec, 0);
  2103. while (start <= end) {
  2104. nr_pages = pagevec_lookup(&pvec, inode->i_mapping, &start,
  2105. PAGEVEC_SIZE);
  2106. if (nr_pages == 0)
  2107. break;
  2108. for (i = 0; i < nr_pages; i++) {
  2109. struct page *page = pvec.pages[i];
  2110. if (page->index > end)
  2111. break;
  2112. bh = head = page_buffers(page);
  2113. do {
  2114. if (lblk < mpd->map.m_lblk)
  2115. continue;
  2116. if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
  2117. /*
  2118. * Buffer after end of mapped extent.
  2119. * Find next buffer in the page to map.
  2120. */
  2121. mpd->map.m_len = 0;
  2122. mpd->map.m_flags = 0;
  2123. /*
  2124. * FIXME: If dioread_nolock supports
  2125. * blocksize < pagesize, we need to make
  2126. * sure we add size mapped so far to
  2127. * io_end->size as the following call
  2128. * can submit the page for IO.
  2129. */
  2130. err = mpage_process_page_bufs(mpd, head,
  2131. bh, lblk);
  2132. pagevec_release(&pvec);
  2133. if (err > 0)
  2134. err = 0;
  2135. return err;
  2136. }
  2137. if (buffer_delay(bh)) {
  2138. clear_buffer_delay(bh);
  2139. bh->b_blocknr = pblock++;
  2140. }
  2141. clear_buffer_unwritten(bh);
  2142. } while (lblk++, (bh = bh->b_this_page) != head);
  2143. /*
  2144. * FIXME: This is going to break if dioread_nolock
  2145. * supports blocksize < pagesize as we will try to
  2146. * convert potentially unmapped parts of inode.
  2147. */
  2148. mpd->io_submit.io_end->size += PAGE_SIZE;
  2149. /* Page fully mapped - let IO run! */
  2150. err = mpage_submit_page(mpd, page);
  2151. if (err < 0) {
  2152. pagevec_release(&pvec);
  2153. return err;
  2154. }
  2155. }
  2156. pagevec_release(&pvec);
  2157. }
  2158. /* Extent fully mapped and matches with page boundary. We are done. */
  2159. mpd->map.m_len = 0;
  2160. mpd->map.m_flags = 0;
  2161. return 0;
  2162. }
  2163. static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
  2164. {
  2165. struct inode *inode = mpd->inode;
  2166. struct ext4_map_blocks *map = &mpd->map;
  2167. int get_blocks_flags;
  2168. int err, dioread_nolock;
  2169. trace_ext4_da_write_pages_extent(inode, map);
  2170. /*
  2171. * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
  2172. * to convert an unwritten extent to be initialized (in the case
  2173. * where we have written into one or more preallocated blocks). It is
  2174. * possible that we're going to need more metadata blocks than
  2175. * previously reserved. However we must not fail because we're in
  2176. * writeback and there is nothing we can do about it so it might result
  2177. * in data loss. So use reserved blocks to allocate metadata if
  2178. * possible.
  2179. *
  2180. * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
  2181. * the blocks in question are delalloc blocks. This indicates
  2182. * that the blocks and quotas has already been checked when
  2183. * the data was copied into the page cache.
  2184. */
  2185. get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
  2186. EXT4_GET_BLOCKS_METADATA_NOFAIL |
  2187. EXT4_GET_BLOCKS_IO_SUBMIT;
  2188. dioread_nolock = ext4_should_dioread_nolock(inode);
  2189. if (dioread_nolock)
  2190. get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
  2191. if (map->m_flags & (1 << BH_Delay))
  2192. get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
  2193. err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
  2194. if (err < 0)
  2195. return err;
  2196. if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
  2197. if (!mpd->io_submit.io_end->handle &&
  2198. ext4_handle_valid(handle)) {
  2199. mpd->io_submit.io_end->handle = handle->h_rsv_handle;
  2200. handle->h_rsv_handle = NULL;
  2201. }
  2202. ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
  2203. }
  2204. BUG_ON(map->m_len == 0);
  2205. if (map->m_flags & EXT4_MAP_NEW) {
  2206. clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
  2207. map->m_len);
  2208. }
  2209. return 0;
  2210. }
  2211. /*
  2212. * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
  2213. * mpd->len and submit pages underlying it for IO
  2214. *
  2215. * @handle - handle for journal operations
  2216. * @mpd - extent to map
  2217. * @give_up_on_write - we set this to true iff there is a fatal error and there
  2218. * is no hope of writing the data. The caller should discard
  2219. * dirty pages to avoid infinite loops.
  2220. *
  2221. * The function maps extent starting at mpd->lblk of length mpd->len. If it is
  2222. * delayed, blocks are allocated, if it is unwritten, we may need to convert
  2223. * them to initialized or split the described range from larger unwritten
  2224. * extent. Note that we need not map all the described range since allocation
  2225. * can return less blocks or the range is covered by more unwritten extents. We
  2226. * cannot map more because we are limited by reserved transaction credits. On
  2227. * the other hand we always make sure that the last touched page is fully
  2228. * mapped so that it can be written out (and thus forward progress is
  2229. * guaranteed). After mapping we submit all mapped pages for IO.
  2230. */
  2231. static int mpage_map_and_submit_extent(handle_t *handle,
  2232. struct mpage_da_data *mpd,
  2233. bool *give_up_on_write)
  2234. {
  2235. struct inode *inode = mpd->inode;
  2236. struct ext4_map_blocks *map = &mpd->map;
  2237. int err;
  2238. loff_t disksize;
  2239. int progress = 0;
  2240. mpd->io_submit.io_end->offset =
  2241. ((loff_t)map->m_lblk) << inode->i_blkbits;
  2242. do {
  2243. err = mpage_map_one_extent(handle, mpd);
  2244. if (err < 0) {
  2245. struct super_block *sb = inode->i_sb;
  2246. if (ext4_forced_shutdown(EXT4_SB(sb)) ||
  2247. EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
  2248. goto invalidate_dirty_pages;
  2249. /*
  2250. * Let the uper layers retry transient errors.
  2251. * In the case of ENOSPC, if ext4_count_free_blocks()
  2252. * is non-zero, a commit should free up blocks.
  2253. */
  2254. if ((err == -ENOMEM) ||
  2255. (err == -ENOSPC && ext4_count_free_clusters(sb))) {
  2256. if (progress)
  2257. goto update_disksize;
  2258. return err;
  2259. }
  2260. ext4_msg(sb, KERN_CRIT,
  2261. "Delayed block allocation failed for "
  2262. "inode %lu at logical offset %llu with"
  2263. " max blocks %u with error %d",
  2264. inode->i_ino,
  2265. (unsigned long long)map->m_lblk,
  2266. (unsigned)map->m_len, -err);
  2267. ext4_msg(sb, KERN_CRIT,
  2268. "This should not happen!! Data will "
  2269. "be lost\n");
  2270. if (err == -ENOSPC)
  2271. ext4_print_free_blocks(inode);
  2272. invalidate_dirty_pages:
  2273. *give_up_on_write = true;
  2274. return err;
  2275. }
  2276. progress = 1;
  2277. /*
  2278. * Update buffer state, submit mapped pages, and get us new
  2279. * extent to map
  2280. */
  2281. err = mpage_map_and_submit_buffers(mpd);
  2282. if (err < 0)
  2283. goto update_disksize;
  2284. } while (map->m_len);
  2285. update_disksize:
  2286. /*
  2287. * Update on-disk size after IO is submitted. Races with
  2288. * truncate are avoided by checking i_size under i_data_sem.
  2289. */
  2290. disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
  2291. if (disksize > EXT4_I(inode)->i_disksize) {
  2292. int err2;
  2293. loff_t i_size;
  2294. down_write(&EXT4_I(inode)->i_data_sem);
  2295. i_size = i_size_read(inode);
  2296. if (disksize > i_size)
  2297. disksize = i_size;
  2298. if (disksize > EXT4_I(inode)->i_disksize)
  2299. EXT4_I(inode)->i_disksize = disksize;
  2300. up_write(&EXT4_I(inode)->i_data_sem);
  2301. err2 = ext4_mark_inode_dirty(handle, inode);
  2302. if (err2)
  2303. ext4_error(inode->i_sb,
  2304. "Failed to mark inode %lu dirty",
  2305. inode->i_ino);
  2306. if (!err)
  2307. err = err2;
  2308. }
  2309. return err;
  2310. }
  2311. /*
  2312. * Calculate the total number of credits to reserve for one writepages
  2313. * iteration. This is called from ext4_writepages(). We map an extent of
  2314. * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
  2315. * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
  2316. * bpp - 1 blocks in bpp different extents.
  2317. */
  2318. static int ext4_da_writepages_trans_blocks(struct inode *inode)
  2319. {
  2320. int bpp = ext4_journal_blocks_per_page(inode);
  2321. return ext4_meta_trans_blocks(inode,
  2322. MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
  2323. }
  2324. /*
  2325. * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
  2326. * and underlying extent to map
  2327. *
  2328. * @mpd - where to look for pages
  2329. *
  2330. * Walk dirty pages in the mapping. If they are fully mapped, submit them for
  2331. * IO immediately. When we find a page which isn't mapped we start accumulating
  2332. * extent of buffers underlying these pages that needs mapping (formed by
  2333. * either delayed or unwritten buffers). We also lock the pages containing
  2334. * these buffers. The extent found is returned in @mpd structure (starting at
  2335. * mpd->lblk with length mpd->len blocks).
  2336. *
  2337. * Note that this function can attach bios to one io_end structure which are
  2338. * neither logically nor physically contiguous. Although it may seem as an
  2339. * unnecessary complication, it is actually inevitable in blocksize < pagesize
  2340. * case as we need to track IO to all buffers underlying a page in one io_end.
  2341. */
  2342. static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
  2343. {
  2344. struct address_space *mapping = mpd->inode->i_mapping;
  2345. struct pagevec pvec;
  2346. unsigned int nr_pages;
  2347. long left = mpd->wbc->nr_to_write;
  2348. pgoff_t index = mpd->first_page;
  2349. pgoff_t end = mpd->last_page;
  2350. int tag;
  2351. int i, err = 0;
  2352. int blkbits = mpd->inode->i_blkbits;
  2353. ext4_lblk_t lblk;
  2354. struct buffer_head *head;
  2355. if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
  2356. tag = PAGECACHE_TAG_TOWRITE;
  2357. else
  2358. tag = PAGECACHE_TAG_DIRTY;
  2359. pagevec_init(&pvec, 0);
  2360. mpd->map.m_len = 0;
  2361. mpd->next_page = index;
  2362. while (index <= end) {
  2363. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
  2364. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
  2365. if (nr_pages == 0)
  2366. goto out;
  2367. for (i = 0; i < nr_pages; i++) {
  2368. struct page *page = pvec.pages[i];
  2369. /*
  2370. * At this point, the page may be truncated or
  2371. * invalidated (changing page->mapping to NULL), or
  2372. * even swizzled back from swapper_space to tmpfs file
  2373. * mapping. However, page->index will not change
  2374. * because we have a reference on the page.
  2375. */
  2376. if (page->index > end)
  2377. goto out;
  2378. /*
  2379. * Accumulated enough dirty pages? This doesn't apply
  2380. * to WB_SYNC_ALL mode. For integrity sync we have to
  2381. * keep going because someone may be concurrently
  2382. * dirtying pages, and we might have synced a lot of
  2383. * newly appeared dirty pages, but have not synced all
  2384. * of the old dirty pages.
  2385. */
  2386. if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
  2387. goto out;
  2388. /* If we can't merge this page, we are done. */
  2389. if (mpd->map.m_len > 0 && mpd->next_page != page->index)
  2390. goto out;
  2391. lock_page(page);
  2392. /*
  2393. * If the page is no longer dirty, or its mapping no
  2394. * longer corresponds to inode we are writing (which
  2395. * means it has been truncated or invalidated), or the
  2396. * page is already under writeback and we are not doing
  2397. * a data integrity writeback, skip the page
  2398. */
  2399. if (!PageDirty(page) ||
  2400. (PageWriteback(page) &&
  2401. (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
  2402. unlikely(page->mapping != mapping)) {
  2403. unlock_page(page);
  2404. continue;
  2405. }
  2406. wait_on_page_writeback(page);
  2407. BUG_ON(PageWriteback(page));
  2408. if (mpd->map.m_len == 0)
  2409. mpd->first_page = page->index;
  2410. mpd->next_page = page->index + 1;
  2411. /* Add all dirty buffers to mpd */
  2412. lblk = ((ext4_lblk_t)page->index) <<
  2413. (PAGE_SHIFT - blkbits);
  2414. head = page_buffers(page);
  2415. err = mpage_process_page_bufs(mpd, head, head, lblk);
  2416. if (err <= 0)
  2417. goto out;
  2418. err = 0;
  2419. left--;
  2420. }
  2421. pagevec_release(&pvec);
  2422. cond_resched();
  2423. }
  2424. return 0;
  2425. out:
  2426. pagevec_release(&pvec);
  2427. return err;
  2428. }
  2429. static int __writepage(struct page *page, struct writeback_control *wbc,
  2430. void *data)
  2431. {
  2432. struct address_space *mapping = data;
  2433. int ret = ext4_writepage(page, wbc);
  2434. mapping_set_error(mapping, ret);
  2435. return ret;
  2436. }
  2437. static int ext4_writepages(struct address_space *mapping,
  2438. struct writeback_control *wbc)
  2439. {
  2440. pgoff_t writeback_index = 0;
  2441. long nr_to_write = wbc->nr_to_write;
  2442. int range_whole = 0;
  2443. int cycled = 1;
  2444. handle_t *handle = NULL;
  2445. struct mpage_da_data mpd;
  2446. struct inode *inode = mapping->host;
  2447. int needed_blocks, rsv_blocks = 0, ret = 0;
  2448. struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
  2449. bool done;
  2450. struct blk_plug plug;
  2451. bool give_up_on_write = false;
  2452. if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
  2453. return -EIO;
  2454. percpu_down_read(&sbi->s_journal_flag_rwsem);
  2455. trace_ext4_writepages(inode, wbc);
  2456. if (dax_mapping(mapping)) {
  2457. ret = dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev,
  2458. wbc);
  2459. goto out_writepages;
  2460. }
  2461. /*
  2462. * No pages to write? This is mainly a kludge to avoid starting
  2463. * a transaction for special inodes like journal inode on last iput()
  2464. * because that could violate lock ordering on umount
  2465. */
  2466. if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
  2467. goto out_writepages;
  2468. if (ext4_should_journal_data(inode)) {
  2469. struct blk_plug plug;
  2470. blk_start_plug(&plug);
  2471. ret = write_cache_pages(mapping, wbc, __writepage, mapping);
  2472. blk_finish_plug(&plug);
  2473. goto out_writepages;
  2474. }
  2475. /*
  2476. * If the filesystem has aborted, it is read-only, so return
  2477. * right away instead of dumping stack traces later on that
  2478. * will obscure the real source of the problem. We test
  2479. * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
  2480. * the latter could be true if the filesystem is mounted
  2481. * read-only, and in that case, ext4_writepages should
  2482. * *never* be called, so if that ever happens, we would want
  2483. * the stack trace.
  2484. */
  2485. if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
  2486. sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
  2487. ret = -EROFS;
  2488. goto out_writepages;
  2489. }
  2490. if (ext4_should_dioread_nolock(inode)) {
  2491. /*
  2492. * We may need to convert up to one extent per block in
  2493. * the page and we may dirty the inode.
  2494. */
  2495. rsv_blocks = 1 + (PAGE_SIZE >> inode->i_blkbits);
  2496. }
  2497. /*
  2498. * If we have inline data and arrive here, it means that
  2499. * we will soon create the block for the 1st page, so
  2500. * we'd better clear the inline data here.
  2501. */
  2502. if (ext4_has_inline_data(inode)) {
  2503. /* Just inode will be modified... */
  2504. handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
  2505. if (IS_ERR(handle)) {
  2506. ret = PTR_ERR(handle);
  2507. goto out_writepages;
  2508. }
  2509. BUG_ON(ext4_test_inode_state(inode,
  2510. EXT4_STATE_MAY_INLINE_DATA));
  2511. ext4_destroy_inline_data(handle, inode);
  2512. ext4_journal_stop(handle);
  2513. }
  2514. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  2515. range_whole = 1;
  2516. if (wbc->range_cyclic) {
  2517. writeback_index = mapping->writeback_index;
  2518. if (writeback_index)
  2519. cycled = 0;
  2520. mpd.first_page = writeback_index;
  2521. mpd.last_page = -1;
  2522. } else {
  2523. mpd.first_page = wbc->range_start >> PAGE_SHIFT;
  2524. mpd.last_page = wbc->range_end >> PAGE_SHIFT;
  2525. }
  2526. mpd.inode = inode;
  2527. mpd.wbc = wbc;
  2528. ext4_io_submit_init(&mpd.io_submit, wbc);
  2529. retry:
  2530. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  2531. tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
  2532. done = false;
  2533. blk_start_plug(&plug);
  2534. /*
  2535. * First writeback pages that don't need mapping - we can avoid
  2536. * starting a transaction unnecessarily and also avoid being blocked
  2537. * in the block layer on device congestion while having transaction
  2538. * started.
  2539. */
  2540. mpd.do_map = 0;
  2541. mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
  2542. if (!mpd.io_submit.io_end) {
  2543. ret = -ENOMEM;
  2544. goto unplug;
  2545. }
  2546. ret = mpage_prepare_extent_to_map(&mpd);
  2547. /* Submit prepared bio */
  2548. ext4_io_submit(&mpd.io_submit);
  2549. ext4_put_io_end_defer(mpd.io_submit.io_end);
  2550. mpd.io_submit.io_end = NULL;
  2551. /* Unlock pages we didn't use */
  2552. mpage_release_unused_pages(&mpd, false);
  2553. if (ret < 0)
  2554. goto unplug;
  2555. while (!done && mpd.first_page <= mpd.last_page) {
  2556. /* For each extent of pages we use new io_end */
  2557. mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
  2558. if (!mpd.io_submit.io_end) {
  2559. ret = -ENOMEM;
  2560. break;
  2561. }
  2562. /*
  2563. * We have two constraints: We find one extent to map and we
  2564. * must always write out whole page (makes a difference when
  2565. * blocksize < pagesize) so that we don't block on IO when we
  2566. * try to write out the rest of the page. Journalled mode is
  2567. * not supported by delalloc.
  2568. */
  2569. BUG_ON(ext4_should_journal_data(inode));
  2570. needed_blocks = ext4_da_writepages_trans_blocks(inode);
  2571. /* start a new transaction */
  2572. handle = ext4_journal_start_with_reserve(inode,
  2573. EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
  2574. if (IS_ERR(handle)) {
  2575. ret = PTR_ERR(handle);
  2576. ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
  2577. "%ld pages, ino %lu; err %d", __func__,
  2578. wbc->nr_to_write, inode->i_ino, ret);
  2579. /* Release allocated io_end */
  2580. ext4_put_io_end(mpd.io_submit.io_end);
  2581. mpd.io_submit.io_end = NULL;
  2582. break;
  2583. }
  2584. mpd.do_map = 1;
  2585. trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
  2586. ret = mpage_prepare_extent_to_map(&mpd);
  2587. if (!ret) {
  2588. if (mpd.map.m_len)
  2589. ret = mpage_map_and_submit_extent(handle, &mpd,
  2590. &give_up_on_write);
  2591. else {
  2592. /*
  2593. * We scanned the whole range (or exhausted
  2594. * nr_to_write), submitted what was mapped and
  2595. * didn't find anything needing mapping. We are
  2596. * done.
  2597. */
  2598. done = true;
  2599. }
  2600. }
  2601. /*
  2602. * Caution: If the handle is synchronous,
  2603. * ext4_journal_stop() can wait for transaction commit
  2604. * to finish which may depend on writeback of pages to
  2605. * complete or on page lock to be released. In that
  2606. * case, we have to wait until after after we have
  2607. * submitted all the IO, released page locks we hold,
  2608. * and dropped io_end reference (for extent conversion
  2609. * to be able to complete) before stopping the handle.
  2610. */
  2611. if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
  2612. ext4_journal_stop(handle);
  2613. handle = NULL;
  2614. mpd.do_map = 0;
  2615. }
  2616. /* Submit prepared bio */
  2617. ext4_io_submit(&mpd.io_submit);
  2618. /* Unlock pages we didn't use */
  2619. mpage_release_unused_pages(&mpd, give_up_on_write);
  2620. /*
  2621. * Drop our io_end reference we got from init. We have
  2622. * to be careful and use deferred io_end finishing if
  2623. * we are still holding the transaction as we can
  2624. * release the last reference to io_end which may end
  2625. * up doing unwritten extent conversion.
  2626. */
  2627. if (handle) {
  2628. ext4_put_io_end_defer(mpd.io_submit.io_end);
  2629. ext4_journal_stop(handle);
  2630. } else
  2631. ext4_put_io_end(mpd.io_submit.io_end);
  2632. mpd.io_submit.io_end = NULL;
  2633. if (ret == -ENOSPC && sbi->s_journal) {
  2634. /*
  2635. * Commit the transaction which would
  2636. * free blocks released in the transaction
  2637. * and try again
  2638. */
  2639. jbd2_journal_force_commit_nested(sbi->s_journal);
  2640. ret = 0;
  2641. continue;
  2642. }
  2643. /* Fatal error - ENOMEM, EIO... */
  2644. if (ret)
  2645. break;
  2646. }
  2647. unplug:
  2648. blk_finish_plug(&plug);
  2649. if (!ret && !cycled && wbc->nr_to_write > 0) {
  2650. cycled = 1;
  2651. mpd.last_page = writeback_index - 1;
  2652. mpd.first_page = 0;
  2653. goto retry;
  2654. }
  2655. /* Update index */
  2656. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  2657. /*
  2658. * Set the writeback_index so that range_cyclic
  2659. * mode will write it back later
  2660. */
  2661. mapping->writeback_index = mpd.first_page;
  2662. out_writepages:
  2663. trace_ext4_writepages_result(inode, wbc, ret,
  2664. nr_to_write - wbc->nr_to_write);
  2665. percpu_up_read(&sbi->s_journal_flag_rwsem);
  2666. return ret;
  2667. }
  2668. static int ext4_nonda_switch(struct super_block *sb)
  2669. {
  2670. s64 free_clusters, dirty_clusters;
  2671. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2672. /*
  2673. * switch to non delalloc mode if we are running low
  2674. * on free block. The free block accounting via percpu
  2675. * counters can get slightly wrong with percpu_counter_batch getting
  2676. * accumulated on each CPU without updating global counters
  2677. * Delalloc need an accurate free block accounting. So switch
  2678. * to non delalloc when we are near to error range.
  2679. */
  2680. free_clusters =
  2681. percpu_counter_read_positive(&sbi->s_freeclusters_counter);
  2682. dirty_clusters =
  2683. percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
  2684. /*
  2685. * Start pushing delalloc when 1/2 of free blocks are dirty.
  2686. */
  2687. if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
  2688. try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
  2689. if (2 * free_clusters < 3 * dirty_clusters ||
  2690. free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
  2691. /*
  2692. * free block count is less than 150% of dirty blocks
  2693. * or free blocks is less than watermark
  2694. */
  2695. return 1;
  2696. }
  2697. return 0;
  2698. }
  2699. /* We always reserve for an inode update; the superblock could be there too */
  2700. static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
  2701. {
  2702. if (likely(ext4_has_feature_large_file(inode->i_sb)))
  2703. return 1;
  2704. if (pos + len <= 0x7fffffffULL)
  2705. return 1;
  2706. /* We might need to update the superblock to set LARGE_FILE */
  2707. return 2;
  2708. }
  2709. static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
  2710. loff_t pos, unsigned len, unsigned flags,
  2711. struct page **pagep, void **fsdata)
  2712. {
  2713. int ret, retries = 0;
  2714. struct page *page;
  2715. pgoff_t index;
  2716. struct inode *inode = mapping->host;
  2717. handle_t *handle;
  2718. if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
  2719. return -EIO;
  2720. index = pos >> PAGE_SHIFT;
  2721. if (ext4_nonda_switch(inode->i_sb) ||
  2722. S_ISLNK(inode->i_mode)) {
  2723. *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
  2724. return ext4_write_begin(file, mapping, pos,
  2725. len, flags, pagep, fsdata);
  2726. }
  2727. *fsdata = (void *)0;
  2728. trace_ext4_da_write_begin(inode, pos, len, flags);
  2729. if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
  2730. ret = ext4_da_write_inline_data_begin(mapping, inode,
  2731. pos, len, flags,
  2732. pagep, fsdata);
  2733. if (ret < 0)
  2734. return ret;
  2735. if (ret == 1)
  2736. return 0;
  2737. }
  2738. /*
  2739. * grab_cache_page_write_begin() can take a long time if the
  2740. * system is thrashing due to memory pressure, or if the page
  2741. * is being written back. So grab it first before we start
  2742. * the transaction handle. This also allows us to allocate
  2743. * the page (if needed) without using GFP_NOFS.
  2744. */
  2745. retry_grab:
  2746. page = grab_cache_page_write_begin(mapping, index, flags);
  2747. if (!page)
  2748. return -ENOMEM;
  2749. unlock_page(page);
  2750. /*
  2751. * With delayed allocation, we don't log the i_disksize update
  2752. * if there is delayed block allocation. But we still need
  2753. * to journalling the i_disksize update if writes to the end
  2754. * of file which has an already mapped buffer.
  2755. */
  2756. retry_journal:
  2757. handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
  2758. ext4_da_write_credits(inode, pos, len));
  2759. if (IS_ERR(handle)) {
  2760. put_page(page);
  2761. return PTR_ERR(handle);
  2762. }
  2763. lock_page(page);
  2764. if (page->mapping != mapping) {
  2765. /* The page got truncated from under us */
  2766. unlock_page(page);
  2767. put_page(page);
  2768. ext4_journal_stop(handle);
  2769. goto retry_grab;
  2770. }
  2771. /* In case writeback began while the page was unlocked */
  2772. wait_for_stable_page(page);
  2773. #ifdef CONFIG_EXT4_FS_ENCRYPTION
  2774. ret = ext4_block_write_begin(page, pos, len,
  2775. ext4_da_get_block_prep);
  2776. #else
  2777. ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
  2778. #endif
  2779. if (ret < 0) {
  2780. unlock_page(page);
  2781. ext4_journal_stop(handle);
  2782. /*
  2783. * block_write_begin may have instantiated a few blocks
  2784. * outside i_size. Trim these off again. Don't need
  2785. * i_size_read because we hold i_mutex.
  2786. */
  2787. if (pos + len > inode->i_size)
  2788. ext4_truncate_failed_write(inode);
  2789. if (ret == -ENOSPC &&
  2790. ext4_should_retry_alloc(inode->i_sb, &retries))
  2791. goto retry_journal;
  2792. put_page(page);
  2793. return ret;
  2794. }
  2795. *pagep = page;
  2796. return ret;
  2797. }
  2798. /*
  2799. * Check if we should update i_disksize
  2800. * when write to the end of file but not require block allocation
  2801. */
  2802. static int ext4_da_should_update_i_disksize(struct page *page,
  2803. unsigned long offset)
  2804. {
  2805. struct buffer_head *bh;
  2806. struct inode *inode = page->mapping->host;
  2807. unsigned int idx;
  2808. int i;
  2809. bh = page_buffers(page);
  2810. idx = offset >> inode->i_blkbits;
  2811. for (i = 0; i < idx; i++)
  2812. bh = bh->b_this_page;
  2813. if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
  2814. return 0;
  2815. return 1;
  2816. }
  2817. static int ext4_da_write_end(struct file *file,
  2818. struct address_space *mapping,
  2819. loff_t pos, unsigned len, unsigned copied,
  2820. struct page *page, void *fsdata)
  2821. {
  2822. struct inode *inode = mapping->host;
  2823. int ret = 0, ret2;
  2824. handle_t *handle = ext4_journal_current_handle();
  2825. loff_t new_i_size;
  2826. unsigned long start, end;
  2827. int write_mode = (int)(unsigned long)fsdata;
  2828. if (write_mode == FALL_BACK_TO_NONDELALLOC)
  2829. return ext4_write_end(file, mapping, pos,
  2830. len, copied, page, fsdata);
  2831. trace_ext4_da_write_end(inode, pos, len, copied);
  2832. start = pos & (PAGE_SIZE - 1);
  2833. end = start + copied - 1;
  2834. /*
  2835. * generic_write_end() will run mark_inode_dirty() if i_size
  2836. * changes. So let's piggyback the i_disksize mark_inode_dirty
  2837. * into that.
  2838. */
  2839. new_i_size = pos + copied;
  2840. if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
  2841. if (ext4_has_inline_data(inode) ||
  2842. ext4_da_should_update_i_disksize(page, end)) {
  2843. ext4_update_i_disksize(inode, new_i_size);
  2844. /* We need to mark inode dirty even if
  2845. * new_i_size is less that inode->i_size
  2846. * bu greater than i_disksize.(hint delalloc)
  2847. */
  2848. ext4_mark_inode_dirty(handle, inode);
  2849. }
  2850. }
  2851. if (write_mode != CONVERT_INLINE_DATA &&
  2852. ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
  2853. ext4_has_inline_data(inode))
  2854. ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
  2855. page);
  2856. else
  2857. ret2 = generic_write_end(file, mapping, pos, len, copied,
  2858. page, fsdata);
  2859. copied = ret2;
  2860. if (ret2 < 0)
  2861. ret = ret2;
  2862. ret2 = ext4_journal_stop(handle);
  2863. if (!ret)
  2864. ret = ret2;
  2865. return ret ? ret : copied;
  2866. }
  2867. static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
  2868. unsigned int length)
  2869. {
  2870. /*
  2871. * Drop reserved blocks
  2872. */
  2873. BUG_ON(!PageLocked(page));
  2874. if (!page_has_buffers(page))
  2875. goto out;
  2876. ext4_da_page_release_reservation(page, offset, length);
  2877. out:
  2878. ext4_invalidatepage(page, offset, length);
  2879. return;
  2880. }
  2881. /*
  2882. * Force all delayed allocation blocks to be allocated for a given inode.
  2883. */
  2884. int ext4_alloc_da_blocks(struct inode *inode)
  2885. {
  2886. trace_ext4_alloc_da_blocks(inode);
  2887. if (!EXT4_I(inode)->i_reserved_data_blocks)
  2888. return 0;
  2889. /*
  2890. * We do something simple for now. The filemap_flush() will
  2891. * also start triggering a write of the data blocks, which is
  2892. * not strictly speaking necessary (and for users of
  2893. * laptop_mode, not even desirable). However, to do otherwise
  2894. * would require replicating code paths in:
  2895. *
  2896. * ext4_writepages() ->
  2897. * write_cache_pages() ---> (via passed in callback function)
  2898. * __mpage_da_writepage() -->
  2899. * mpage_add_bh_to_extent()
  2900. * mpage_da_map_blocks()
  2901. *
  2902. * The problem is that write_cache_pages(), located in
  2903. * mm/page-writeback.c, marks pages clean in preparation for
  2904. * doing I/O, which is not desirable if we're not planning on
  2905. * doing I/O at all.
  2906. *
  2907. * We could call write_cache_pages(), and then redirty all of
  2908. * the pages by calling redirty_page_for_writepage() but that
  2909. * would be ugly in the extreme. So instead we would need to
  2910. * replicate parts of the code in the above functions,
  2911. * simplifying them because we wouldn't actually intend to
  2912. * write out the pages, but rather only collect contiguous
  2913. * logical block extents, call the multi-block allocator, and
  2914. * then update the buffer heads with the block allocations.
  2915. *
  2916. * For now, though, we'll cheat by calling filemap_flush(),
  2917. * which will map the blocks, and start the I/O, but not
  2918. * actually wait for the I/O to complete.
  2919. */
  2920. return filemap_flush(inode->i_mapping);
  2921. }
  2922. /*
  2923. * bmap() is special. It gets used by applications such as lilo and by
  2924. * the swapper to find the on-disk block of a specific piece of data.
  2925. *
  2926. * Naturally, this is dangerous if the block concerned is still in the
  2927. * journal. If somebody makes a swapfile on an ext4 data-journaling
  2928. * filesystem and enables swap, then they may get a nasty shock when the
  2929. * data getting swapped to that swapfile suddenly gets overwritten by
  2930. * the original zero's written out previously to the journal and
  2931. * awaiting writeback in the kernel's buffer cache.
  2932. *
  2933. * So, if we see any bmap calls here on a modified, data-journaled file,
  2934. * take extra steps to flush any blocks which might be in the cache.
  2935. */
  2936. static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
  2937. {
  2938. struct inode *inode = mapping->host;
  2939. journal_t *journal;
  2940. int err;
  2941. /*
  2942. * We can get here for an inline file via the FIBMAP ioctl
  2943. */
  2944. if (ext4_has_inline_data(inode))
  2945. return 0;
  2946. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
  2947. test_opt(inode->i_sb, DELALLOC)) {
  2948. /*
  2949. * With delalloc we want to sync the file
  2950. * so that we can make sure we allocate
  2951. * blocks for file
  2952. */
  2953. filemap_write_and_wait(mapping);
  2954. }
  2955. if (EXT4_JOURNAL(inode) &&
  2956. ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
  2957. /*
  2958. * This is a REALLY heavyweight approach, but the use of
  2959. * bmap on dirty files is expected to be extremely rare:
  2960. * only if we run lilo or swapon on a freshly made file
  2961. * do we expect this to happen.
  2962. *
  2963. * (bmap requires CAP_SYS_RAWIO so this does not
  2964. * represent an unprivileged user DOS attack --- we'd be
  2965. * in trouble if mortal users could trigger this path at
  2966. * will.)
  2967. *
  2968. * NB. EXT4_STATE_JDATA is not set on files other than
  2969. * regular files. If somebody wants to bmap a directory
  2970. * or symlink and gets confused because the buffer
  2971. * hasn't yet been flushed to disk, they deserve
  2972. * everything they get.
  2973. */
  2974. ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
  2975. journal = EXT4_JOURNAL(inode);
  2976. jbd2_journal_lock_updates(journal);
  2977. err = jbd2_journal_flush(journal);
  2978. jbd2_journal_unlock_updates(journal);
  2979. if (err)
  2980. return 0;
  2981. }
  2982. return generic_block_bmap(mapping, block, ext4_get_block);
  2983. }
  2984. static int ext4_readpage(struct file *file, struct page *page)
  2985. {
  2986. int ret = -EAGAIN;
  2987. struct inode *inode = page->mapping->host;
  2988. trace_ext4_readpage(page);
  2989. if (ext4_has_inline_data(inode))
  2990. ret = ext4_readpage_inline(inode, page);
  2991. if (ret == -EAGAIN)
  2992. return ext4_mpage_readpages(page->mapping, NULL, page, 1);
  2993. return ret;
  2994. }
  2995. static int
  2996. ext4_readpages(struct file *file, struct address_space *mapping,
  2997. struct list_head *pages, unsigned nr_pages)
  2998. {
  2999. struct inode *inode = mapping->host;
  3000. /* If the file has inline data, no need to do readpages. */
  3001. if (ext4_has_inline_data(inode))
  3002. return 0;
  3003. return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
  3004. }
  3005. static void ext4_invalidatepage(struct page *page, unsigned int offset,
  3006. unsigned int length)
  3007. {
  3008. trace_ext4_invalidatepage(page, offset, length);
  3009. /* No journalling happens on data buffers when this function is used */
  3010. WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
  3011. block_invalidatepage(page, offset, length);
  3012. }
  3013. static int __ext4_journalled_invalidatepage(struct page *page,
  3014. unsigned int offset,
  3015. unsigned int length)
  3016. {
  3017. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  3018. trace_ext4_journalled_invalidatepage(page, offset, length);
  3019. /*
  3020. * If it's a full truncate we just forget about the pending dirtying
  3021. */
  3022. if (offset == 0 && length == PAGE_SIZE)
  3023. ClearPageChecked(page);
  3024. return jbd2_journal_invalidatepage(journal, page, offset, length);
  3025. }
  3026. /* Wrapper for aops... */
  3027. static void ext4_journalled_invalidatepage(struct page *page,
  3028. unsigned int offset,
  3029. unsigned int length)
  3030. {
  3031. WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
  3032. }
  3033. static int ext4_releasepage(struct page *page, gfp_t wait)
  3034. {
  3035. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  3036. trace_ext4_releasepage(page);
  3037. /* Page has dirty journalled data -> cannot release */
  3038. if (PageChecked(page))
  3039. return 0;
  3040. if (journal)
  3041. return jbd2_journal_try_to_free_buffers(journal, page, wait);
  3042. else
  3043. return try_to_free_buffers(page);
  3044. }
  3045. #ifdef CONFIG_FS_DAX
  3046. static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
  3047. unsigned flags, struct iomap *iomap)
  3048. {
  3049. struct block_device *bdev;
  3050. unsigned int blkbits = inode->i_blkbits;
  3051. unsigned long first_block = offset >> blkbits;
  3052. unsigned long last_block = (offset + length - 1) >> blkbits;
  3053. struct ext4_map_blocks map;
  3054. int ret;
  3055. if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
  3056. return -ERANGE;
  3057. map.m_lblk = first_block;
  3058. map.m_len = last_block - first_block + 1;
  3059. if (!(flags & IOMAP_WRITE)) {
  3060. ret = ext4_map_blocks(NULL, inode, &map, 0);
  3061. } else {
  3062. int dio_credits;
  3063. handle_t *handle;
  3064. int retries = 0;
  3065. /* Trim mapping request to maximum we can map at once for DIO */
  3066. if (map.m_len > DIO_MAX_BLOCKS)
  3067. map.m_len = DIO_MAX_BLOCKS;
  3068. dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
  3069. retry:
  3070. /*
  3071. * Either we allocate blocks and then we don't get unwritten
  3072. * extent so we have reserved enough credits, or the blocks
  3073. * are already allocated and unwritten and in that case
  3074. * extent conversion fits in the credits as well.
  3075. */
  3076. handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
  3077. dio_credits);
  3078. if (IS_ERR(handle))
  3079. return PTR_ERR(handle);
  3080. ret = ext4_map_blocks(handle, inode, &map,
  3081. EXT4_GET_BLOCKS_CREATE_ZERO);
  3082. if (ret < 0) {
  3083. ext4_journal_stop(handle);
  3084. if (ret == -ENOSPC &&
  3085. ext4_should_retry_alloc(inode->i_sb, &retries))
  3086. goto retry;
  3087. return ret;
  3088. }
  3089. /*
  3090. * If we added blocks beyond i_size, we need to make sure they
  3091. * will get truncated if we crash before updating i_size in
  3092. * ext4_iomap_end(). For faults we don't need to do that (and
  3093. * even cannot because for orphan list operations inode_lock is
  3094. * required) - if we happen to instantiate block beyond i_size,
  3095. * it is because we race with truncate which has already added
  3096. * the inode to the orphan list.
  3097. */
  3098. if (!(flags & IOMAP_FAULT) && first_block + map.m_len >
  3099. (i_size_read(inode) + (1 << blkbits) - 1) >> blkbits) {
  3100. int err;
  3101. err = ext4_orphan_add(handle, inode);
  3102. if (err < 0) {
  3103. ext4_journal_stop(handle);
  3104. return err;
  3105. }
  3106. }
  3107. ext4_journal_stop(handle);
  3108. }
  3109. iomap->flags = 0;
  3110. bdev = inode->i_sb->s_bdev;
  3111. iomap->bdev = bdev;
  3112. if (blk_queue_dax(bdev->bd_queue))
  3113. iomap->dax_dev = fs_dax_get_by_host(bdev->bd_disk->disk_name);
  3114. else
  3115. iomap->dax_dev = NULL;
  3116. iomap->offset = first_block << blkbits;
  3117. if (ret == 0) {
  3118. iomap->type = IOMAP_HOLE;
  3119. iomap->blkno = IOMAP_NULL_BLOCK;
  3120. iomap->length = (u64)map.m_len << blkbits;
  3121. } else {
  3122. if (map.m_flags & EXT4_MAP_MAPPED) {
  3123. iomap->type = IOMAP_MAPPED;
  3124. } else if (map.m_flags & EXT4_MAP_UNWRITTEN) {
  3125. iomap->type = IOMAP_UNWRITTEN;
  3126. } else {
  3127. WARN_ON_ONCE(1);
  3128. return -EIO;
  3129. }
  3130. iomap->blkno = (sector_t)map.m_pblk << (blkbits - 9);
  3131. iomap->length = (u64)map.m_len << blkbits;
  3132. }
  3133. if (map.m_flags & EXT4_MAP_NEW)
  3134. iomap->flags |= IOMAP_F_NEW;
  3135. return 0;
  3136. }
  3137. static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
  3138. ssize_t written, unsigned flags, struct iomap *iomap)
  3139. {
  3140. int ret = 0;
  3141. handle_t *handle;
  3142. int blkbits = inode->i_blkbits;
  3143. bool truncate = false;
  3144. fs_put_dax(iomap->dax_dev);
  3145. if (!(flags & IOMAP_WRITE) || (flags & IOMAP_FAULT))
  3146. return 0;
  3147. handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
  3148. if (IS_ERR(handle)) {
  3149. ret = PTR_ERR(handle);
  3150. goto orphan_del;
  3151. }
  3152. if (ext4_update_inode_size(inode, offset + written))
  3153. ext4_mark_inode_dirty(handle, inode);
  3154. /*
  3155. * We may need to truncate allocated but not written blocks beyond EOF.
  3156. */
  3157. if (iomap->offset + iomap->length >
  3158. ALIGN(inode->i_size, 1 << blkbits)) {
  3159. ext4_lblk_t written_blk, end_blk;
  3160. written_blk = (offset + written) >> blkbits;
  3161. end_blk = (offset + length) >> blkbits;
  3162. if (written_blk < end_blk && ext4_can_truncate(inode))
  3163. truncate = true;
  3164. }
  3165. /*
  3166. * Remove inode from orphan list if we were extending a inode and
  3167. * everything went fine.
  3168. */
  3169. if (!truncate && inode->i_nlink &&
  3170. !list_empty(&EXT4_I(inode)->i_orphan))
  3171. ext4_orphan_del(handle, inode);
  3172. ext4_journal_stop(handle);
  3173. if (truncate) {
  3174. ext4_truncate_failed_write(inode);
  3175. orphan_del:
  3176. /*
  3177. * If truncate failed early the inode might still be on the
  3178. * orphan list; we need to make sure the inode is removed from
  3179. * the orphan list in that case.
  3180. */
  3181. if (inode->i_nlink)
  3182. ext4_orphan_del(NULL, inode);
  3183. }
  3184. return ret;
  3185. }
  3186. const struct iomap_ops ext4_iomap_ops = {
  3187. .iomap_begin = ext4_iomap_begin,
  3188. .iomap_end = ext4_iomap_end,
  3189. };
  3190. #endif
  3191. static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
  3192. ssize_t size, void *private)
  3193. {
  3194. ext4_io_end_t *io_end = private;
  3195. /* if not async direct IO just return */
  3196. if (!io_end)
  3197. return 0;
  3198. ext_debug("ext4_end_io_dio(): io_end 0x%p "
  3199. "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
  3200. io_end, io_end->inode->i_ino, iocb, offset, size);
  3201. /*
  3202. * Error during AIO DIO. We cannot convert unwritten extents as the
  3203. * data was not written. Just clear the unwritten flag and drop io_end.
  3204. */
  3205. if (size <= 0) {
  3206. ext4_clear_io_unwritten_flag(io_end);
  3207. size = 0;
  3208. }
  3209. io_end->offset = offset;
  3210. io_end->size = size;
  3211. ext4_put_io_end(io_end);
  3212. return 0;
  3213. }
  3214. /*
  3215. * Handling of direct IO writes.
  3216. *
  3217. * For ext4 extent files, ext4 will do direct-io write even to holes,
  3218. * preallocated extents, and those write extend the file, no need to
  3219. * fall back to buffered IO.
  3220. *
  3221. * For holes, we fallocate those blocks, mark them as unwritten
  3222. * If those blocks were preallocated, we mark sure they are split, but
  3223. * still keep the range to write as unwritten.
  3224. *
  3225. * The unwritten extents will be converted to written when DIO is completed.
  3226. * For async direct IO, since the IO may still pending when return, we
  3227. * set up an end_io call back function, which will do the conversion
  3228. * when async direct IO completed.
  3229. *
  3230. * If the O_DIRECT write will extend the file then add this inode to the
  3231. * orphan list. So recovery will truncate it back to the original size
  3232. * if the machine crashes during the write.
  3233. *
  3234. */
  3235. static ssize_t ext4_direct_IO_write(struct kiocb *iocb, struct iov_iter *iter)
  3236. {
  3237. struct file *file = iocb->ki_filp;
  3238. struct inode *inode = file->f_mapping->host;
  3239. struct ext4_inode_info *ei = EXT4_I(inode);
  3240. ssize_t ret;
  3241. loff_t offset = iocb->ki_pos;
  3242. size_t count = iov_iter_count(iter);
  3243. int overwrite = 0;
  3244. get_block_t *get_block_func = NULL;
  3245. int dio_flags = 0;
  3246. loff_t final_size = offset + count;
  3247. int orphan = 0;
  3248. handle_t *handle;
  3249. if (final_size > inode->i_size) {
  3250. /* Credits for sb + inode write */
  3251. handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
  3252. if (IS_ERR(handle)) {
  3253. ret = PTR_ERR(handle);
  3254. goto out;
  3255. }
  3256. ret = ext4_orphan_add(handle, inode);
  3257. if (ret) {
  3258. ext4_journal_stop(handle);
  3259. goto out;
  3260. }
  3261. orphan = 1;
  3262. ei->i_disksize = inode->i_size;
  3263. ext4_journal_stop(handle);
  3264. }
  3265. BUG_ON(iocb->private == NULL);
  3266. /*
  3267. * Make all waiters for direct IO properly wait also for extent
  3268. * conversion. This also disallows race between truncate() and
  3269. * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
  3270. */
  3271. inode_dio_begin(inode);
  3272. /* If we do a overwrite dio, i_mutex locking can be released */
  3273. overwrite = *((int *)iocb->private);
  3274. if (overwrite)
  3275. inode_unlock(inode);
  3276. /*
  3277. * For extent mapped files we could direct write to holes and fallocate.
  3278. *
  3279. * Allocated blocks to fill the hole are marked as unwritten to prevent
  3280. * parallel buffered read to expose the stale data before DIO complete
  3281. * the data IO.
  3282. *
  3283. * As to previously fallocated extents, ext4 get_block will just simply
  3284. * mark the buffer mapped but still keep the extents unwritten.
  3285. *
  3286. * For non AIO case, we will convert those unwritten extents to written
  3287. * after return back from blockdev_direct_IO. That way we save us from
  3288. * allocating io_end structure and also the overhead of offloading
  3289. * the extent convertion to a workqueue.
  3290. *
  3291. * For async DIO, the conversion needs to be deferred when the
  3292. * IO is completed. The ext4 end_io callback function will be
  3293. * called to take care of the conversion work. Here for async
  3294. * case, we allocate an io_end structure to hook to the iocb.
  3295. */
  3296. iocb->private = NULL;
  3297. if (overwrite)
  3298. get_block_func = ext4_dio_get_block_overwrite;
  3299. else if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS) ||
  3300. round_down(offset, i_blocksize(inode)) >= inode->i_size) {
  3301. get_block_func = ext4_dio_get_block;
  3302. dio_flags = DIO_LOCKING | DIO_SKIP_HOLES;
  3303. } else if (is_sync_kiocb(iocb)) {
  3304. get_block_func = ext4_dio_get_block_unwritten_sync;
  3305. dio_flags = DIO_LOCKING;
  3306. } else {
  3307. get_block_func = ext4_dio_get_block_unwritten_async;
  3308. dio_flags = DIO_LOCKING;
  3309. }
  3310. ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter,
  3311. get_block_func, ext4_end_io_dio, NULL,
  3312. dio_flags);
  3313. if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
  3314. EXT4_STATE_DIO_UNWRITTEN)) {
  3315. int err;
  3316. /*
  3317. * for non AIO case, since the IO is already
  3318. * completed, we could do the conversion right here
  3319. */
  3320. err = ext4_convert_unwritten_extents(NULL, inode,
  3321. offset, ret);
  3322. if (err < 0)
  3323. ret = err;
  3324. ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
  3325. }
  3326. inode_dio_end(inode);
  3327. /* take i_mutex locking again if we do a ovewrite dio */
  3328. if (overwrite)
  3329. inode_lock(inode);
  3330. if (ret < 0 && final_size > inode->i_size)
  3331. ext4_truncate_failed_write(inode);
  3332. /* Handle extending of i_size after direct IO write */
  3333. if (orphan) {
  3334. int err;
  3335. /* Credits for sb + inode write */
  3336. handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
  3337. if (IS_ERR(handle)) {
  3338. /* This is really bad luck. We've written the data
  3339. * but cannot extend i_size. Bail out and pretend
  3340. * the write failed... */
  3341. ret = PTR_ERR(handle);
  3342. if (inode->i_nlink)
  3343. ext4_orphan_del(NULL, inode);
  3344. goto out;
  3345. }
  3346. if (inode->i_nlink)
  3347. ext4_orphan_del(handle, inode);
  3348. if (ret > 0) {
  3349. loff_t end = offset + ret;
  3350. if (end > inode->i_size) {
  3351. ei->i_disksize = end;
  3352. i_size_write(inode, end);
  3353. /*
  3354. * We're going to return a positive `ret'
  3355. * here due to non-zero-length I/O, so there's
  3356. * no way of reporting error returns from
  3357. * ext4_mark_inode_dirty() to userspace. So
  3358. * ignore it.
  3359. */
  3360. ext4_mark_inode_dirty(handle, inode);
  3361. }
  3362. }
  3363. err = ext4_journal_stop(handle);
  3364. if (ret == 0)
  3365. ret = err;
  3366. }
  3367. out:
  3368. return ret;
  3369. }
  3370. static ssize_t ext4_direct_IO_read(struct kiocb *iocb, struct iov_iter *iter)
  3371. {
  3372. struct address_space *mapping = iocb->ki_filp->f_mapping;
  3373. struct inode *inode = mapping->host;
  3374. size_t count = iov_iter_count(iter);
  3375. ssize_t ret;
  3376. /*
  3377. * Shared inode_lock is enough for us - it protects against concurrent
  3378. * writes & truncates and since we take care of writing back page cache,
  3379. * we are protected against page writeback as well.
  3380. */
  3381. inode_lock_shared(inode);
  3382. ret = filemap_write_and_wait_range(mapping, iocb->ki_pos,
  3383. iocb->ki_pos + count - 1);
  3384. if (ret)
  3385. goto out_unlock;
  3386. ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
  3387. iter, ext4_dio_get_block, NULL, NULL, 0);
  3388. out_unlock:
  3389. inode_unlock_shared(inode);
  3390. return ret;
  3391. }
  3392. static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
  3393. {
  3394. struct file *file = iocb->ki_filp;
  3395. struct inode *inode = file->f_mapping->host;
  3396. size_t count = iov_iter_count(iter);
  3397. loff_t offset = iocb->ki_pos;
  3398. ssize_t ret;
  3399. #ifdef CONFIG_EXT4_FS_ENCRYPTION
  3400. if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode))
  3401. return 0;
  3402. #endif
  3403. /*
  3404. * If we are doing data journalling we don't support O_DIRECT
  3405. */
  3406. if (ext4_should_journal_data(inode))
  3407. return 0;
  3408. /* Let buffer I/O handle the inline data case. */
  3409. if (ext4_has_inline_data(inode))
  3410. return 0;
  3411. /* DAX uses iomap path now */
  3412. if (WARN_ON_ONCE(IS_DAX(inode)))
  3413. return 0;
  3414. trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter));
  3415. if (iov_iter_rw(iter) == READ)
  3416. ret = ext4_direct_IO_read(iocb, iter);
  3417. else
  3418. ret = ext4_direct_IO_write(iocb, iter);
  3419. trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret);
  3420. return ret;
  3421. }
  3422. /*
  3423. * Pages can be marked dirty completely asynchronously from ext4's journalling
  3424. * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
  3425. * much here because ->set_page_dirty is called under VFS locks. The page is
  3426. * not necessarily locked.
  3427. *
  3428. * We cannot just dirty the page and leave attached buffers clean, because the
  3429. * buffers' dirty state is "definitive". We cannot just set the buffers dirty
  3430. * or jbddirty because all the journalling code will explode.
  3431. *
  3432. * So what we do is to mark the page "pending dirty" and next time writepage
  3433. * is called, propagate that into the buffers appropriately.
  3434. */
  3435. static int ext4_journalled_set_page_dirty(struct page *page)
  3436. {
  3437. SetPageChecked(page);
  3438. return __set_page_dirty_nobuffers(page);
  3439. }
  3440. static int ext4_set_page_dirty(struct page *page)
  3441. {
  3442. WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
  3443. WARN_ON_ONCE(!page_has_buffers(page));
  3444. return __set_page_dirty_buffers(page);
  3445. }
  3446. static const struct address_space_operations ext4_aops = {
  3447. .readpage = ext4_readpage,
  3448. .readpages = ext4_readpages,
  3449. .writepage = ext4_writepage,
  3450. .writepages = ext4_writepages,
  3451. .write_begin = ext4_write_begin,
  3452. .write_end = ext4_write_end,
  3453. .set_page_dirty = ext4_set_page_dirty,
  3454. .bmap = ext4_bmap,
  3455. .invalidatepage = ext4_invalidatepage,
  3456. .releasepage = ext4_releasepage,
  3457. .direct_IO = ext4_direct_IO,
  3458. .migratepage = buffer_migrate_page,
  3459. .is_partially_uptodate = block_is_partially_uptodate,
  3460. .error_remove_page = generic_error_remove_page,
  3461. };
  3462. static const struct address_space_operations ext4_journalled_aops = {
  3463. .readpage = ext4_readpage,
  3464. .readpages = ext4_readpages,
  3465. .writepage = ext4_writepage,
  3466. .writepages = ext4_writepages,
  3467. .write_begin = ext4_write_begin,
  3468. .write_end = ext4_journalled_write_end,
  3469. .set_page_dirty = ext4_journalled_set_page_dirty,
  3470. .bmap = ext4_bmap,
  3471. .invalidatepage = ext4_journalled_invalidatepage,
  3472. .releasepage = ext4_releasepage,
  3473. .direct_IO = ext4_direct_IO,
  3474. .is_partially_uptodate = block_is_partially_uptodate,
  3475. .error_remove_page = generic_error_remove_page,
  3476. };
  3477. static const struct address_space_operations ext4_da_aops = {
  3478. .readpage = ext4_readpage,
  3479. .readpages = ext4_readpages,
  3480. .writepage = ext4_writepage,
  3481. .writepages = ext4_writepages,
  3482. .write_begin = ext4_da_write_begin,
  3483. .write_end = ext4_da_write_end,
  3484. .set_page_dirty = ext4_set_page_dirty,
  3485. .bmap = ext4_bmap,
  3486. .invalidatepage = ext4_da_invalidatepage,
  3487. .releasepage = ext4_releasepage,
  3488. .direct_IO = ext4_direct_IO,
  3489. .migratepage = buffer_migrate_page,
  3490. .is_partially_uptodate = block_is_partially_uptodate,
  3491. .error_remove_page = generic_error_remove_page,
  3492. };
  3493. void ext4_set_aops(struct inode *inode)
  3494. {
  3495. switch (ext4_inode_journal_mode(inode)) {
  3496. case EXT4_INODE_ORDERED_DATA_MODE:
  3497. case EXT4_INODE_WRITEBACK_DATA_MODE:
  3498. break;
  3499. case EXT4_INODE_JOURNAL_DATA_MODE:
  3500. inode->i_mapping->a_ops = &ext4_journalled_aops;
  3501. return;
  3502. default:
  3503. BUG();
  3504. }
  3505. if (test_opt(inode->i_sb, DELALLOC))
  3506. inode->i_mapping->a_ops = &ext4_da_aops;
  3507. else
  3508. inode->i_mapping->a_ops = &ext4_aops;
  3509. }
  3510. static int __ext4_block_zero_page_range(handle_t *handle,
  3511. struct address_space *mapping, loff_t from, loff_t length)
  3512. {
  3513. ext4_fsblk_t index = from >> PAGE_SHIFT;
  3514. unsigned offset = from & (PAGE_SIZE-1);
  3515. unsigned blocksize, pos;
  3516. ext4_lblk_t iblock;
  3517. struct inode *inode = mapping->host;
  3518. struct buffer_head *bh;
  3519. struct page *page;
  3520. int err = 0;
  3521. page = find_or_create_page(mapping, from >> PAGE_SHIFT,
  3522. mapping_gfp_constraint(mapping, ~__GFP_FS));
  3523. if (!page)
  3524. return -ENOMEM;
  3525. blocksize = inode->i_sb->s_blocksize;
  3526. iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
  3527. if (!page_has_buffers(page))
  3528. create_empty_buffers(page, blocksize, 0);
  3529. /* Find the buffer that contains "offset" */
  3530. bh = page_buffers(page);
  3531. pos = blocksize;
  3532. while (offset >= pos) {
  3533. bh = bh->b_this_page;
  3534. iblock++;
  3535. pos += blocksize;
  3536. }
  3537. if (buffer_freed(bh)) {
  3538. BUFFER_TRACE(bh, "freed: skip");
  3539. goto unlock;
  3540. }
  3541. if (!buffer_mapped(bh)) {
  3542. BUFFER_TRACE(bh, "unmapped");
  3543. ext4_get_block(inode, iblock, bh, 0);
  3544. /* unmapped? It's a hole - nothing to do */
  3545. if (!buffer_mapped(bh)) {
  3546. BUFFER_TRACE(bh, "still unmapped");
  3547. goto unlock;
  3548. }
  3549. }
  3550. /* Ok, it's mapped. Make sure it's up-to-date */
  3551. if (PageUptodate(page))
  3552. set_buffer_uptodate(bh);
  3553. if (!buffer_uptodate(bh)) {
  3554. err = -EIO;
  3555. ll_rw_block(REQ_OP_READ, 0, 1, &bh);
  3556. wait_on_buffer(bh);
  3557. /* Uhhuh. Read error. Complain and punt. */
  3558. if (!buffer_uptodate(bh))
  3559. goto unlock;
  3560. if (S_ISREG(inode->i_mode) &&
  3561. ext4_encrypted_inode(inode)) {
  3562. /* We expect the key to be set. */
  3563. BUG_ON(!fscrypt_has_encryption_key(inode));
  3564. BUG_ON(blocksize != PAGE_SIZE);
  3565. WARN_ON_ONCE(fscrypt_decrypt_page(page->mapping->host,
  3566. page, PAGE_SIZE, 0, page->index));
  3567. }
  3568. }
  3569. if (ext4_should_journal_data(inode)) {
  3570. BUFFER_TRACE(bh, "get write access");
  3571. err = ext4_journal_get_write_access(handle, bh);
  3572. if (err)
  3573. goto unlock;
  3574. }
  3575. zero_user(page, offset, length);
  3576. BUFFER_TRACE(bh, "zeroed end of block");
  3577. if (ext4_should_journal_data(inode)) {
  3578. err = ext4_handle_dirty_metadata(handle, inode, bh);
  3579. } else {
  3580. err = 0;
  3581. mark_buffer_dirty(bh);
  3582. if (ext4_should_order_data(inode))
  3583. err = ext4_jbd2_inode_add_write(handle, inode);
  3584. }
  3585. unlock:
  3586. unlock_page(page);
  3587. put_page(page);
  3588. return err;
  3589. }
  3590. /*
  3591. * ext4_block_zero_page_range() zeros out a mapping of length 'length'
  3592. * starting from file offset 'from'. The range to be zero'd must
  3593. * be contained with in one block. If the specified range exceeds
  3594. * the end of the block it will be shortened to end of the block
  3595. * that cooresponds to 'from'
  3596. */
  3597. static int ext4_block_zero_page_range(handle_t *handle,
  3598. struct address_space *mapping, loff_t from, loff_t length)
  3599. {
  3600. struct inode *inode = mapping->host;
  3601. unsigned offset = from & (PAGE_SIZE-1);
  3602. unsigned blocksize = inode->i_sb->s_blocksize;
  3603. unsigned max = blocksize - (offset & (blocksize - 1));
  3604. /*
  3605. * correct length if it does not fall between
  3606. * 'from' and the end of the block
  3607. */
  3608. if (length > max || length < 0)
  3609. length = max;
  3610. if (IS_DAX(inode)) {
  3611. return iomap_zero_range(inode, from, length, NULL,
  3612. &ext4_iomap_ops);
  3613. }
  3614. return __ext4_block_zero_page_range(handle, mapping, from, length);
  3615. }
  3616. /*
  3617. * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
  3618. * up to the end of the block which corresponds to `from'.
  3619. * This required during truncate. We need to physically zero the tail end
  3620. * of that block so it doesn't yield old data if the file is later grown.
  3621. */
  3622. static int ext4_block_truncate_page(handle_t *handle,
  3623. struct address_space *mapping, loff_t from)
  3624. {
  3625. unsigned offset = from & (PAGE_SIZE-1);
  3626. unsigned length;
  3627. unsigned blocksize;
  3628. struct inode *inode = mapping->host;
  3629. /* If we are processing an encrypted inode during orphan list handling */
  3630. if (ext4_encrypted_inode(inode) && !fscrypt_has_encryption_key(inode))
  3631. return 0;
  3632. blocksize = inode->i_sb->s_blocksize;
  3633. length = blocksize - (offset & (blocksize - 1));
  3634. return ext4_block_zero_page_range(handle, mapping, from, length);
  3635. }
  3636. int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
  3637. loff_t lstart, loff_t length)
  3638. {
  3639. struct super_block *sb = inode->i_sb;
  3640. struct address_space *mapping = inode->i_mapping;
  3641. unsigned partial_start, partial_end;
  3642. ext4_fsblk_t start, end;
  3643. loff_t byte_end = (lstart + length - 1);
  3644. int err = 0;
  3645. partial_start = lstart & (sb->s_blocksize - 1);
  3646. partial_end = byte_end & (sb->s_blocksize - 1);
  3647. start = lstart >> sb->s_blocksize_bits;
  3648. end = byte_end >> sb->s_blocksize_bits;
  3649. /* Handle partial zero within the single block */
  3650. if (start == end &&
  3651. (partial_start || (partial_end != sb->s_blocksize - 1))) {
  3652. err = ext4_block_zero_page_range(handle, mapping,
  3653. lstart, length);
  3654. return err;
  3655. }
  3656. /* Handle partial zero out on the start of the range */
  3657. if (partial_start) {
  3658. err = ext4_block_zero_page_range(handle, mapping,
  3659. lstart, sb->s_blocksize);
  3660. if (err)
  3661. return err;
  3662. }
  3663. /* Handle partial zero out on the end of the range */
  3664. if (partial_end != sb->s_blocksize - 1)
  3665. err = ext4_block_zero_page_range(handle, mapping,
  3666. byte_end - partial_end,
  3667. partial_end + 1);
  3668. return err;
  3669. }
  3670. int ext4_can_truncate(struct inode *inode)
  3671. {
  3672. if (S_ISREG(inode->i_mode))
  3673. return 1;
  3674. if (S_ISDIR(inode->i_mode))
  3675. return 1;
  3676. if (S_ISLNK(inode->i_mode))
  3677. return !ext4_inode_is_fast_symlink(inode);
  3678. return 0;
  3679. }
  3680. /*
  3681. * We have to make sure i_disksize gets properly updated before we truncate
  3682. * page cache due to hole punching or zero range. Otherwise i_disksize update
  3683. * can get lost as it may have been postponed to submission of writeback but
  3684. * that will never happen after we truncate page cache.
  3685. */
  3686. int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
  3687. loff_t len)
  3688. {
  3689. handle_t *handle;
  3690. loff_t size = i_size_read(inode);
  3691. WARN_ON(!inode_is_locked(inode));
  3692. if (offset > size || offset + len < size)
  3693. return 0;
  3694. if (EXT4_I(inode)->i_disksize >= size)
  3695. return 0;
  3696. handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
  3697. if (IS_ERR(handle))
  3698. return PTR_ERR(handle);
  3699. ext4_update_i_disksize(inode, size);
  3700. ext4_mark_inode_dirty(handle, inode);
  3701. ext4_journal_stop(handle);
  3702. return 0;
  3703. }
  3704. /*
  3705. * ext4_punch_hole: punches a hole in a file by releasing the blocks
  3706. * associated with the given offset and length
  3707. *
  3708. * @inode: File inode
  3709. * @offset: The offset where the hole will begin
  3710. * @len: The length of the hole
  3711. *
  3712. * Returns: 0 on success or negative on failure
  3713. */
  3714. int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
  3715. {
  3716. struct super_block *sb = inode->i_sb;
  3717. ext4_lblk_t first_block, stop_block;
  3718. struct address_space *mapping = inode->i_mapping;
  3719. loff_t first_block_offset, last_block_offset;
  3720. handle_t *handle;
  3721. unsigned int credits;
  3722. int ret = 0;
  3723. if (!S_ISREG(inode->i_mode))
  3724. return -EOPNOTSUPP;
  3725. trace_ext4_punch_hole(inode, offset, length, 0);
  3726. /*
  3727. * Write out all dirty pages to avoid race conditions
  3728. * Then release them.
  3729. */
  3730. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
  3731. ret = filemap_write_and_wait_range(mapping, offset,
  3732. offset + length - 1);
  3733. if (ret)
  3734. return ret;
  3735. }
  3736. inode_lock(inode);
  3737. /* No need to punch hole beyond i_size */
  3738. if (offset >= inode->i_size)
  3739. goto out_mutex;
  3740. /*
  3741. * If the hole extends beyond i_size, set the hole
  3742. * to end after the page that contains i_size
  3743. */
  3744. if (offset + length > inode->i_size) {
  3745. length = inode->i_size +
  3746. PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
  3747. offset;
  3748. }
  3749. if (offset & (sb->s_blocksize - 1) ||
  3750. (offset + length) & (sb->s_blocksize - 1)) {
  3751. /*
  3752. * Attach jinode to inode for jbd2 if we do any zeroing of
  3753. * partial block
  3754. */
  3755. ret = ext4_inode_attach_jinode(inode);
  3756. if (ret < 0)
  3757. goto out_mutex;
  3758. }
  3759. /* Wait all existing dio workers, newcomers will block on i_mutex */
  3760. ext4_inode_block_unlocked_dio(inode);
  3761. inode_dio_wait(inode);
  3762. /*
  3763. * Prevent page faults from reinstantiating pages we have released from
  3764. * page cache.
  3765. */
  3766. down_write(&EXT4_I(inode)->i_mmap_sem);
  3767. first_block_offset = round_up(offset, sb->s_blocksize);
  3768. last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
  3769. /* Now release the pages and zero block aligned part of pages*/
  3770. if (last_block_offset > first_block_offset) {
  3771. ret = ext4_update_disksize_before_punch(inode, offset, length);
  3772. if (ret)
  3773. goto out_dio;
  3774. truncate_pagecache_range(inode, first_block_offset,
  3775. last_block_offset);
  3776. }
  3777. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  3778. credits = ext4_writepage_trans_blocks(inode);
  3779. else
  3780. credits = ext4_blocks_for_truncate(inode);
  3781. handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
  3782. if (IS_ERR(handle)) {
  3783. ret = PTR_ERR(handle);
  3784. ext4_std_error(sb, ret);
  3785. goto out_dio;
  3786. }
  3787. ret = ext4_zero_partial_blocks(handle, inode, offset,
  3788. length);
  3789. if (ret)
  3790. goto out_stop;
  3791. first_block = (offset + sb->s_blocksize - 1) >>
  3792. EXT4_BLOCK_SIZE_BITS(sb);
  3793. stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
  3794. /* If there are no blocks to remove, return now */
  3795. if (first_block >= stop_block)
  3796. goto out_stop;
  3797. down_write(&EXT4_I(inode)->i_data_sem);
  3798. ext4_discard_preallocations(inode);
  3799. ret = ext4_es_remove_extent(inode, first_block,
  3800. stop_block - first_block);
  3801. if (ret) {
  3802. up_write(&EXT4_I(inode)->i_data_sem);
  3803. goto out_stop;
  3804. }
  3805. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  3806. ret = ext4_ext_remove_space(inode, first_block,
  3807. stop_block - 1);
  3808. else
  3809. ret = ext4_ind_remove_space(handle, inode, first_block,
  3810. stop_block);
  3811. up_write(&EXT4_I(inode)->i_data_sem);
  3812. if (IS_SYNC(inode))
  3813. ext4_handle_sync(handle);
  3814. inode->i_mtime = inode->i_ctime = current_time(inode);
  3815. ext4_mark_inode_dirty(handle, inode);
  3816. if (ret >= 0)
  3817. ext4_update_inode_fsync_trans(handle, inode, 1);
  3818. out_stop:
  3819. ext4_journal_stop(handle);
  3820. out_dio:
  3821. up_write(&EXT4_I(inode)->i_mmap_sem);
  3822. ext4_inode_resume_unlocked_dio(inode);
  3823. out_mutex:
  3824. inode_unlock(inode);
  3825. return ret;
  3826. }
  3827. int ext4_inode_attach_jinode(struct inode *inode)
  3828. {
  3829. struct ext4_inode_info *ei = EXT4_I(inode);
  3830. struct jbd2_inode *jinode;
  3831. if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
  3832. return 0;
  3833. jinode = jbd2_alloc_inode(GFP_KERNEL);
  3834. spin_lock(&inode->i_lock);
  3835. if (!ei->jinode) {
  3836. if (!jinode) {
  3837. spin_unlock(&inode->i_lock);
  3838. return -ENOMEM;
  3839. }
  3840. ei->jinode = jinode;
  3841. jbd2_journal_init_jbd_inode(ei->jinode, inode);
  3842. jinode = NULL;
  3843. }
  3844. spin_unlock(&inode->i_lock);
  3845. if (unlikely(jinode != NULL))
  3846. jbd2_free_inode(jinode);
  3847. return 0;
  3848. }
  3849. /*
  3850. * ext4_truncate()
  3851. *
  3852. * We block out ext4_get_block() block instantiations across the entire
  3853. * transaction, and VFS/VM ensures that ext4_truncate() cannot run
  3854. * simultaneously on behalf of the same inode.
  3855. *
  3856. * As we work through the truncate and commit bits of it to the journal there
  3857. * is one core, guiding principle: the file's tree must always be consistent on
  3858. * disk. We must be able to restart the truncate after a crash.
  3859. *
  3860. * The file's tree may be transiently inconsistent in memory (although it
  3861. * probably isn't), but whenever we close off and commit a journal transaction,
  3862. * the contents of (the filesystem + the journal) must be consistent and
  3863. * restartable. It's pretty simple, really: bottom up, right to left (although
  3864. * left-to-right works OK too).
  3865. *
  3866. * Note that at recovery time, journal replay occurs *before* the restart of
  3867. * truncate against the orphan inode list.
  3868. *
  3869. * The committed inode has the new, desired i_size (which is the same as
  3870. * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
  3871. * that this inode's truncate did not complete and it will again call
  3872. * ext4_truncate() to have another go. So there will be instantiated blocks
  3873. * to the right of the truncation point in a crashed ext4 filesystem. But
  3874. * that's fine - as long as they are linked from the inode, the post-crash
  3875. * ext4_truncate() run will find them and release them.
  3876. */
  3877. int ext4_truncate(struct inode *inode)
  3878. {
  3879. struct ext4_inode_info *ei = EXT4_I(inode);
  3880. unsigned int credits;
  3881. int err = 0;
  3882. handle_t *handle;
  3883. struct address_space *mapping = inode->i_mapping;
  3884. /*
  3885. * There is a possibility that we're either freeing the inode
  3886. * or it's a completely new inode. In those cases we might not
  3887. * have i_mutex locked because it's not necessary.
  3888. */
  3889. if (!(inode->i_state & (I_NEW|I_FREEING)))
  3890. WARN_ON(!inode_is_locked(inode));
  3891. trace_ext4_truncate_enter(inode);
  3892. if (!ext4_can_truncate(inode))
  3893. return 0;
  3894. ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
  3895. if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
  3896. ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
  3897. if (ext4_has_inline_data(inode)) {
  3898. int has_inline = 1;
  3899. err = ext4_inline_data_truncate(inode, &has_inline);
  3900. if (err)
  3901. return err;
  3902. if (has_inline)
  3903. return 0;
  3904. }
  3905. /* If we zero-out tail of the page, we have to create jinode for jbd2 */
  3906. if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
  3907. if (ext4_inode_attach_jinode(inode) < 0)
  3908. return 0;
  3909. }
  3910. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  3911. credits = ext4_writepage_trans_blocks(inode);
  3912. else
  3913. credits = ext4_blocks_for_truncate(inode);
  3914. handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
  3915. if (IS_ERR(handle))
  3916. return PTR_ERR(handle);
  3917. if (inode->i_size & (inode->i_sb->s_blocksize - 1))
  3918. ext4_block_truncate_page(handle, mapping, inode->i_size);
  3919. /*
  3920. * We add the inode to the orphan list, so that if this
  3921. * truncate spans multiple transactions, and we crash, we will
  3922. * resume the truncate when the filesystem recovers. It also
  3923. * marks the inode dirty, to catch the new size.
  3924. *
  3925. * Implication: the file must always be in a sane, consistent
  3926. * truncatable state while each transaction commits.
  3927. */
  3928. err = ext4_orphan_add(handle, inode);
  3929. if (err)
  3930. goto out_stop;
  3931. down_write(&EXT4_I(inode)->i_data_sem);
  3932. ext4_discard_preallocations(inode);
  3933. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  3934. err = ext4_ext_truncate(handle, inode);
  3935. else
  3936. ext4_ind_truncate(handle, inode);
  3937. up_write(&ei->i_data_sem);
  3938. if (err)
  3939. goto out_stop;
  3940. if (IS_SYNC(inode))
  3941. ext4_handle_sync(handle);
  3942. out_stop:
  3943. /*
  3944. * If this was a simple ftruncate() and the file will remain alive,
  3945. * then we need to clear up the orphan record which we created above.
  3946. * However, if this was a real unlink then we were called by
  3947. * ext4_evict_inode(), and we allow that function to clean up the
  3948. * orphan info for us.
  3949. */
  3950. if (inode->i_nlink)
  3951. ext4_orphan_del(handle, inode);
  3952. inode->i_mtime = inode->i_ctime = current_time(inode);
  3953. ext4_mark_inode_dirty(handle, inode);
  3954. ext4_journal_stop(handle);
  3955. trace_ext4_truncate_exit(inode);
  3956. return err;
  3957. }
  3958. /*
  3959. * ext4_get_inode_loc returns with an extra refcount against the inode's
  3960. * underlying buffer_head on success. If 'in_mem' is true, we have all
  3961. * data in memory that is needed to recreate the on-disk version of this
  3962. * inode.
  3963. */
  3964. static int __ext4_get_inode_loc(struct inode *inode,
  3965. struct ext4_iloc *iloc, int in_mem)
  3966. {
  3967. struct ext4_group_desc *gdp;
  3968. struct buffer_head *bh;
  3969. struct super_block *sb = inode->i_sb;
  3970. ext4_fsblk_t block;
  3971. int inodes_per_block, inode_offset;
  3972. iloc->bh = NULL;
  3973. if (!ext4_valid_inum(sb, inode->i_ino))
  3974. return -EFSCORRUPTED;
  3975. iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
  3976. gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
  3977. if (!gdp)
  3978. return -EIO;
  3979. /*
  3980. * Figure out the offset within the block group inode table
  3981. */
  3982. inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
  3983. inode_offset = ((inode->i_ino - 1) %
  3984. EXT4_INODES_PER_GROUP(sb));
  3985. block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
  3986. iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
  3987. bh = sb_getblk(sb, block);
  3988. if (unlikely(!bh))
  3989. return -ENOMEM;
  3990. if (!buffer_uptodate(bh)) {
  3991. lock_buffer(bh);
  3992. /*
  3993. * If the buffer has the write error flag, we have failed
  3994. * to write out another inode in the same block. In this
  3995. * case, we don't have to read the block because we may
  3996. * read the old inode data successfully.
  3997. */
  3998. if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
  3999. set_buffer_uptodate(bh);
  4000. if (buffer_uptodate(bh)) {
  4001. /* someone brought it uptodate while we waited */
  4002. unlock_buffer(bh);
  4003. goto has_buffer;
  4004. }
  4005. /*
  4006. * If we have all information of the inode in memory and this
  4007. * is the only valid inode in the block, we need not read the
  4008. * block.
  4009. */
  4010. if (in_mem) {
  4011. struct buffer_head *bitmap_bh;
  4012. int i, start;
  4013. start = inode_offset & ~(inodes_per_block - 1);
  4014. /* Is the inode bitmap in cache? */
  4015. bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
  4016. if (unlikely(!bitmap_bh))
  4017. goto make_io;
  4018. /*
  4019. * If the inode bitmap isn't in cache then the
  4020. * optimisation may end up performing two reads instead
  4021. * of one, so skip it.
  4022. */
  4023. if (!buffer_uptodate(bitmap_bh)) {
  4024. brelse(bitmap_bh);
  4025. goto make_io;
  4026. }
  4027. for (i = start; i < start + inodes_per_block; i++) {
  4028. if (i == inode_offset)
  4029. continue;
  4030. if (ext4_test_bit(i, bitmap_bh->b_data))
  4031. break;
  4032. }
  4033. brelse(bitmap_bh);
  4034. if (i == start + inodes_per_block) {
  4035. /* all other inodes are free, so skip I/O */
  4036. memset(bh->b_data, 0, bh->b_size);
  4037. set_buffer_uptodate(bh);
  4038. unlock_buffer(bh);
  4039. goto has_buffer;
  4040. }
  4041. }
  4042. make_io:
  4043. /*
  4044. * If we need to do any I/O, try to pre-readahead extra
  4045. * blocks from the inode table.
  4046. */
  4047. if (EXT4_SB(sb)->s_inode_readahead_blks) {
  4048. ext4_fsblk_t b, end, table;
  4049. unsigned num;
  4050. __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
  4051. table = ext4_inode_table(sb, gdp);
  4052. /* s_inode_readahead_blks is always a power of 2 */
  4053. b = block & ~((ext4_fsblk_t) ra_blks - 1);
  4054. if (table > b)
  4055. b = table;
  4056. end = b + ra_blks;
  4057. num = EXT4_INODES_PER_GROUP(sb);
  4058. if (ext4_has_group_desc_csum(sb))
  4059. num -= ext4_itable_unused_count(sb, gdp);
  4060. table += num / inodes_per_block;
  4061. if (end > table)
  4062. end = table;
  4063. while (b <= end)
  4064. sb_breadahead(sb, b++);
  4065. }
  4066. /*
  4067. * There are other valid inodes in the buffer, this inode
  4068. * has in-inode xattrs, or we don't have this inode in memory.
  4069. * Read the block from disk.
  4070. */
  4071. trace_ext4_load_inode(inode);
  4072. get_bh(bh);
  4073. bh->b_end_io = end_buffer_read_sync;
  4074. submit_bh(REQ_OP_READ, REQ_META | REQ_PRIO, bh);
  4075. wait_on_buffer(bh);
  4076. if (!buffer_uptodate(bh)) {
  4077. EXT4_ERROR_INODE_BLOCK(inode, block,
  4078. "unable to read itable block");
  4079. brelse(bh);
  4080. return -EIO;
  4081. }
  4082. }
  4083. has_buffer:
  4084. iloc->bh = bh;
  4085. return 0;
  4086. }
  4087. int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
  4088. {
  4089. /* We have all inode data except xattrs in memory here. */
  4090. return __ext4_get_inode_loc(inode, iloc,
  4091. !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
  4092. }
  4093. void ext4_set_inode_flags(struct inode *inode)
  4094. {
  4095. unsigned int flags = EXT4_I(inode)->i_flags;
  4096. unsigned int new_fl = 0;
  4097. if (flags & EXT4_SYNC_FL)
  4098. new_fl |= S_SYNC;
  4099. if (flags & EXT4_APPEND_FL)
  4100. new_fl |= S_APPEND;
  4101. if (flags & EXT4_IMMUTABLE_FL)
  4102. new_fl |= S_IMMUTABLE;
  4103. if (flags & EXT4_NOATIME_FL)
  4104. new_fl |= S_NOATIME;
  4105. if (flags & EXT4_DIRSYNC_FL)
  4106. new_fl |= S_DIRSYNC;
  4107. if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode) &&
  4108. !ext4_should_journal_data(inode) && !ext4_has_inline_data(inode) &&
  4109. !ext4_encrypted_inode(inode))
  4110. new_fl |= S_DAX;
  4111. inode_set_flags(inode, new_fl,
  4112. S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
  4113. }
  4114. static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
  4115. struct ext4_inode_info *ei)
  4116. {
  4117. blkcnt_t i_blocks ;
  4118. struct inode *inode = &(ei->vfs_inode);
  4119. struct super_block *sb = inode->i_sb;
  4120. if (ext4_has_feature_huge_file(sb)) {
  4121. /* we are using combined 48 bit field */
  4122. i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
  4123. le32_to_cpu(raw_inode->i_blocks_lo);
  4124. if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
  4125. /* i_blocks represent file system block size */
  4126. return i_blocks << (inode->i_blkbits - 9);
  4127. } else {
  4128. return i_blocks;
  4129. }
  4130. } else {
  4131. return le32_to_cpu(raw_inode->i_blocks_lo);
  4132. }
  4133. }
  4134. static inline void ext4_iget_extra_inode(struct inode *inode,
  4135. struct ext4_inode *raw_inode,
  4136. struct ext4_inode_info *ei)
  4137. {
  4138. __le32 *magic = (void *)raw_inode +
  4139. EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
  4140. if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
  4141. EXT4_INODE_SIZE(inode->i_sb) &&
  4142. *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
  4143. ext4_set_inode_state(inode, EXT4_STATE_XATTR);
  4144. ext4_find_inline_data_nolock(inode);
  4145. } else
  4146. EXT4_I(inode)->i_inline_off = 0;
  4147. }
  4148. int ext4_get_projid(struct inode *inode, kprojid_t *projid)
  4149. {
  4150. if (!ext4_has_feature_project(inode->i_sb))
  4151. return -EOPNOTSUPP;
  4152. *projid = EXT4_I(inode)->i_projid;
  4153. return 0;
  4154. }
  4155. struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
  4156. {
  4157. struct ext4_iloc iloc;
  4158. struct ext4_inode *raw_inode;
  4159. struct ext4_inode_info *ei;
  4160. struct inode *inode;
  4161. journal_t *journal = EXT4_SB(sb)->s_journal;
  4162. long ret;
  4163. loff_t size;
  4164. int block;
  4165. uid_t i_uid;
  4166. gid_t i_gid;
  4167. projid_t i_projid;
  4168. inode = iget_locked(sb, ino);
  4169. if (!inode)
  4170. return ERR_PTR(-ENOMEM);
  4171. if (!(inode->i_state & I_NEW))
  4172. return inode;
  4173. ei = EXT4_I(inode);
  4174. iloc.bh = NULL;
  4175. ret = __ext4_get_inode_loc(inode, &iloc, 0);
  4176. if (ret < 0)
  4177. goto bad_inode;
  4178. raw_inode = ext4_raw_inode(&iloc);
  4179. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  4180. ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
  4181. if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
  4182. EXT4_INODE_SIZE(inode->i_sb) ||
  4183. (ei->i_extra_isize & 3)) {
  4184. EXT4_ERROR_INODE(inode,
  4185. "bad extra_isize %u (inode size %u)",
  4186. ei->i_extra_isize,
  4187. EXT4_INODE_SIZE(inode->i_sb));
  4188. ret = -EFSCORRUPTED;
  4189. goto bad_inode;
  4190. }
  4191. } else
  4192. ei->i_extra_isize = 0;
  4193. /* Precompute checksum seed for inode metadata */
  4194. if (ext4_has_metadata_csum(sb)) {
  4195. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  4196. __u32 csum;
  4197. __le32 inum = cpu_to_le32(inode->i_ino);
  4198. __le32 gen = raw_inode->i_generation;
  4199. csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
  4200. sizeof(inum));
  4201. ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
  4202. sizeof(gen));
  4203. }
  4204. if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
  4205. EXT4_ERROR_INODE(inode, "checksum invalid");
  4206. ret = -EFSBADCRC;
  4207. goto bad_inode;
  4208. }
  4209. inode->i_mode = le16_to_cpu(raw_inode->i_mode);
  4210. i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
  4211. i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
  4212. if (ext4_has_feature_project(sb) &&
  4213. EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
  4214. EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
  4215. i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
  4216. else
  4217. i_projid = EXT4_DEF_PROJID;
  4218. if (!(test_opt(inode->i_sb, NO_UID32))) {
  4219. i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
  4220. i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
  4221. }
  4222. i_uid_write(inode, i_uid);
  4223. i_gid_write(inode, i_gid);
  4224. ei->i_projid = make_kprojid(&init_user_ns, i_projid);
  4225. set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
  4226. ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
  4227. ei->i_inline_off = 0;
  4228. ei->i_dir_start_lookup = 0;
  4229. ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
  4230. /* We now have enough fields to check if the inode was active or not.
  4231. * This is needed because nfsd might try to access dead inodes
  4232. * the test is that same one that e2fsck uses
  4233. * NeilBrown 1999oct15
  4234. */
  4235. if (inode->i_nlink == 0) {
  4236. if ((inode->i_mode == 0 ||
  4237. !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
  4238. ino != EXT4_BOOT_LOADER_INO) {
  4239. /* this inode is deleted */
  4240. ret = -ESTALE;
  4241. goto bad_inode;
  4242. }
  4243. /* The only unlinked inodes we let through here have
  4244. * valid i_mode and are being read by the orphan
  4245. * recovery code: that's fine, we're about to complete
  4246. * the process of deleting those.
  4247. * OR it is the EXT4_BOOT_LOADER_INO which is
  4248. * not initialized on a new filesystem. */
  4249. }
  4250. ei->i_flags = le32_to_cpu(raw_inode->i_flags);
  4251. inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
  4252. ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
  4253. if (ext4_has_feature_64bit(sb))
  4254. ei->i_file_acl |=
  4255. ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
  4256. inode->i_size = ext4_isize(sb, raw_inode);
  4257. if ((size = i_size_read(inode)) < 0) {
  4258. EXT4_ERROR_INODE(inode, "bad i_size value: %lld", size);
  4259. ret = -EFSCORRUPTED;
  4260. goto bad_inode;
  4261. }
  4262. ei->i_disksize = inode->i_size;
  4263. #ifdef CONFIG_QUOTA
  4264. ei->i_reserved_quota = 0;
  4265. #endif
  4266. inode->i_generation = le32_to_cpu(raw_inode->i_generation);
  4267. ei->i_block_group = iloc.block_group;
  4268. ei->i_last_alloc_group = ~0;
  4269. /*
  4270. * NOTE! The in-memory inode i_data array is in little-endian order
  4271. * even on big-endian machines: we do NOT byteswap the block numbers!
  4272. */
  4273. for (block = 0; block < EXT4_N_BLOCKS; block++)
  4274. ei->i_data[block] = raw_inode->i_block[block];
  4275. INIT_LIST_HEAD(&ei->i_orphan);
  4276. /*
  4277. * Set transaction id's of transactions that have to be committed
  4278. * to finish f[data]sync. We set them to currently running transaction
  4279. * as we cannot be sure that the inode or some of its metadata isn't
  4280. * part of the transaction - the inode could have been reclaimed and
  4281. * now it is reread from disk.
  4282. */
  4283. if (journal) {
  4284. transaction_t *transaction;
  4285. tid_t tid;
  4286. read_lock(&journal->j_state_lock);
  4287. if (journal->j_running_transaction)
  4288. transaction = journal->j_running_transaction;
  4289. else
  4290. transaction = journal->j_committing_transaction;
  4291. if (transaction)
  4292. tid = transaction->t_tid;
  4293. else
  4294. tid = journal->j_commit_sequence;
  4295. read_unlock(&journal->j_state_lock);
  4296. ei->i_sync_tid = tid;
  4297. ei->i_datasync_tid = tid;
  4298. }
  4299. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  4300. if (ei->i_extra_isize == 0) {
  4301. /* The extra space is currently unused. Use it. */
  4302. BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
  4303. ei->i_extra_isize = sizeof(struct ext4_inode) -
  4304. EXT4_GOOD_OLD_INODE_SIZE;
  4305. } else {
  4306. ext4_iget_extra_inode(inode, raw_inode, ei);
  4307. }
  4308. }
  4309. EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
  4310. EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
  4311. EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
  4312. EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
  4313. if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
  4314. inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
  4315. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  4316. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  4317. inode->i_version |=
  4318. (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
  4319. }
  4320. }
  4321. ret = 0;
  4322. if (ei->i_file_acl &&
  4323. !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
  4324. EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
  4325. ei->i_file_acl);
  4326. ret = -EFSCORRUPTED;
  4327. goto bad_inode;
  4328. } else if (!ext4_has_inline_data(inode)) {
  4329. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  4330. if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
  4331. (S_ISLNK(inode->i_mode) &&
  4332. !ext4_inode_is_fast_symlink(inode))))
  4333. /* Validate extent which is part of inode */
  4334. ret = ext4_ext_check_inode(inode);
  4335. } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
  4336. (S_ISLNK(inode->i_mode) &&
  4337. !ext4_inode_is_fast_symlink(inode))) {
  4338. /* Validate block references which are part of inode */
  4339. ret = ext4_ind_check_inode(inode);
  4340. }
  4341. }
  4342. if (ret)
  4343. goto bad_inode;
  4344. if (S_ISREG(inode->i_mode)) {
  4345. inode->i_op = &ext4_file_inode_operations;
  4346. inode->i_fop = &ext4_file_operations;
  4347. ext4_set_aops(inode);
  4348. } else if (S_ISDIR(inode->i_mode)) {
  4349. inode->i_op = &ext4_dir_inode_operations;
  4350. inode->i_fop = &ext4_dir_operations;
  4351. } else if (S_ISLNK(inode->i_mode)) {
  4352. if (ext4_encrypted_inode(inode)) {
  4353. inode->i_op = &ext4_encrypted_symlink_inode_operations;
  4354. ext4_set_aops(inode);
  4355. } else if (ext4_inode_is_fast_symlink(inode)) {
  4356. inode->i_link = (char *)ei->i_data;
  4357. inode->i_op = &ext4_fast_symlink_inode_operations;
  4358. nd_terminate_link(ei->i_data, inode->i_size,
  4359. sizeof(ei->i_data) - 1);
  4360. } else {
  4361. inode->i_op = &ext4_symlink_inode_operations;
  4362. ext4_set_aops(inode);
  4363. }
  4364. inode_nohighmem(inode);
  4365. } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
  4366. S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
  4367. inode->i_op = &ext4_special_inode_operations;
  4368. if (raw_inode->i_block[0])
  4369. init_special_inode(inode, inode->i_mode,
  4370. old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
  4371. else
  4372. init_special_inode(inode, inode->i_mode,
  4373. new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
  4374. } else if (ino == EXT4_BOOT_LOADER_INO) {
  4375. make_bad_inode(inode);
  4376. } else {
  4377. ret = -EFSCORRUPTED;
  4378. EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
  4379. goto bad_inode;
  4380. }
  4381. brelse(iloc.bh);
  4382. ext4_set_inode_flags(inode);
  4383. if (ei->i_flags & EXT4_EA_INODE_FL) {
  4384. ext4_xattr_inode_set_class(inode);
  4385. inode_lock(inode);
  4386. inode->i_flags |= S_NOQUOTA;
  4387. inode_unlock(inode);
  4388. }
  4389. unlock_new_inode(inode);
  4390. return inode;
  4391. bad_inode:
  4392. brelse(iloc.bh);
  4393. iget_failed(inode);
  4394. return ERR_PTR(ret);
  4395. }
  4396. struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
  4397. {
  4398. if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
  4399. return ERR_PTR(-EFSCORRUPTED);
  4400. return ext4_iget(sb, ino);
  4401. }
  4402. static int ext4_inode_blocks_set(handle_t *handle,
  4403. struct ext4_inode *raw_inode,
  4404. struct ext4_inode_info *ei)
  4405. {
  4406. struct inode *inode = &(ei->vfs_inode);
  4407. u64 i_blocks = inode->i_blocks;
  4408. struct super_block *sb = inode->i_sb;
  4409. if (i_blocks <= ~0U) {
  4410. /*
  4411. * i_blocks can be represented in a 32 bit variable
  4412. * as multiple of 512 bytes
  4413. */
  4414. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  4415. raw_inode->i_blocks_high = 0;
  4416. ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  4417. return 0;
  4418. }
  4419. if (!ext4_has_feature_huge_file(sb))
  4420. return -EFBIG;
  4421. if (i_blocks <= 0xffffffffffffULL) {
  4422. /*
  4423. * i_blocks can be represented in a 48 bit variable
  4424. * as multiple of 512 bytes
  4425. */
  4426. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  4427. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  4428. ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  4429. } else {
  4430. ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  4431. /* i_block is stored in file system block size */
  4432. i_blocks = i_blocks >> (inode->i_blkbits - 9);
  4433. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  4434. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  4435. }
  4436. return 0;
  4437. }
  4438. struct other_inode {
  4439. unsigned long orig_ino;
  4440. struct ext4_inode *raw_inode;
  4441. };
  4442. static int other_inode_match(struct inode * inode, unsigned long ino,
  4443. void *data)
  4444. {
  4445. struct other_inode *oi = (struct other_inode *) data;
  4446. if ((inode->i_ino != ino) ||
  4447. (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
  4448. I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
  4449. ((inode->i_state & I_DIRTY_TIME) == 0))
  4450. return 0;
  4451. spin_lock(&inode->i_lock);
  4452. if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
  4453. I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
  4454. (inode->i_state & I_DIRTY_TIME)) {
  4455. struct ext4_inode_info *ei = EXT4_I(inode);
  4456. inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
  4457. spin_unlock(&inode->i_lock);
  4458. spin_lock(&ei->i_raw_lock);
  4459. EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
  4460. EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
  4461. EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
  4462. ext4_inode_csum_set(inode, oi->raw_inode, ei);
  4463. spin_unlock(&ei->i_raw_lock);
  4464. trace_ext4_other_inode_update_time(inode, oi->orig_ino);
  4465. return -1;
  4466. }
  4467. spin_unlock(&inode->i_lock);
  4468. return -1;
  4469. }
  4470. /*
  4471. * Opportunistically update the other time fields for other inodes in
  4472. * the same inode table block.
  4473. */
  4474. static void ext4_update_other_inodes_time(struct super_block *sb,
  4475. unsigned long orig_ino, char *buf)
  4476. {
  4477. struct other_inode oi;
  4478. unsigned long ino;
  4479. int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
  4480. int inode_size = EXT4_INODE_SIZE(sb);
  4481. oi.orig_ino = orig_ino;
  4482. /*
  4483. * Calculate the first inode in the inode table block. Inode
  4484. * numbers are one-based. That is, the first inode in a block
  4485. * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
  4486. */
  4487. ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
  4488. for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
  4489. if (ino == orig_ino)
  4490. continue;
  4491. oi.raw_inode = (struct ext4_inode *) buf;
  4492. (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
  4493. }
  4494. }
  4495. /*
  4496. * Post the struct inode info into an on-disk inode location in the
  4497. * buffer-cache. This gobbles the caller's reference to the
  4498. * buffer_head in the inode location struct.
  4499. *
  4500. * The caller must have write access to iloc->bh.
  4501. */
  4502. static int ext4_do_update_inode(handle_t *handle,
  4503. struct inode *inode,
  4504. struct ext4_iloc *iloc)
  4505. {
  4506. struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
  4507. struct ext4_inode_info *ei = EXT4_I(inode);
  4508. struct buffer_head *bh = iloc->bh;
  4509. struct super_block *sb = inode->i_sb;
  4510. int err = 0, rc, block;
  4511. int need_datasync = 0, set_large_file = 0;
  4512. uid_t i_uid;
  4513. gid_t i_gid;
  4514. projid_t i_projid;
  4515. spin_lock(&ei->i_raw_lock);
  4516. /* For fields not tracked in the in-memory inode,
  4517. * initialise them to zero for new inodes. */
  4518. if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
  4519. memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
  4520. raw_inode->i_mode = cpu_to_le16(inode->i_mode);
  4521. i_uid = i_uid_read(inode);
  4522. i_gid = i_gid_read(inode);
  4523. i_projid = from_kprojid(&init_user_ns, ei->i_projid);
  4524. if (!(test_opt(inode->i_sb, NO_UID32))) {
  4525. raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
  4526. raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
  4527. /*
  4528. * Fix up interoperability with old kernels. Otherwise, old inodes get
  4529. * re-used with the upper 16 bits of the uid/gid intact
  4530. */
  4531. if (ei->i_dtime && list_empty(&ei->i_orphan)) {
  4532. raw_inode->i_uid_high = 0;
  4533. raw_inode->i_gid_high = 0;
  4534. } else {
  4535. raw_inode->i_uid_high =
  4536. cpu_to_le16(high_16_bits(i_uid));
  4537. raw_inode->i_gid_high =
  4538. cpu_to_le16(high_16_bits(i_gid));
  4539. }
  4540. } else {
  4541. raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
  4542. raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
  4543. raw_inode->i_uid_high = 0;
  4544. raw_inode->i_gid_high = 0;
  4545. }
  4546. raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
  4547. EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
  4548. EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
  4549. EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
  4550. EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
  4551. err = ext4_inode_blocks_set(handle, raw_inode, ei);
  4552. if (err) {
  4553. spin_unlock(&ei->i_raw_lock);
  4554. goto out_brelse;
  4555. }
  4556. raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
  4557. raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
  4558. if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
  4559. raw_inode->i_file_acl_high =
  4560. cpu_to_le16(ei->i_file_acl >> 32);
  4561. raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
  4562. if (ei->i_disksize != ext4_isize(inode->i_sb, raw_inode)) {
  4563. ext4_isize_set(raw_inode, ei->i_disksize);
  4564. need_datasync = 1;
  4565. }
  4566. if (ei->i_disksize > 0x7fffffffULL) {
  4567. if (!ext4_has_feature_large_file(sb) ||
  4568. EXT4_SB(sb)->s_es->s_rev_level ==
  4569. cpu_to_le32(EXT4_GOOD_OLD_REV))
  4570. set_large_file = 1;
  4571. }
  4572. raw_inode->i_generation = cpu_to_le32(inode->i_generation);
  4573. if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
  4574. if (old_valid_dev(inode->i_rdev)) {
  4575. raw_inode->i_block[0] =
  4576. cpu_to_le32(old_encode_dev(inode->i_rdev));
  4577. raw_inode->i_block[1] = 0;
  4578. } else {
  4579. raw_inode->i_block[0] = 0;
  4580. raw_inode->i_block[1] =
  4581. cpu_to_le32(new_encode_dev(inode->i_rdev));
  4582. raw_inode->i_block[2] = 0;
  4583. }
  4584. } else if (!ext4_has_inline_data(inode)) {
  4585. for (block = 0; block < EXT4_N_BLOCKS; block++)
  4586. raw_inode->i_block[block] = ei->i_data[block];
  4587. }
  4588. if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
  4589. raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
  4590. if (ei->i_extra_isize) {
  4591. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  4592. raw_inode->i_version_hi =
  4593. cpu_to_le32(inode->i_version >> 32);
  4594. raw_inode->i_extra_isize =
  4595. cpu_to_le16(ei->i_extra_isize);
  4596. }
  4597. }
  4598. BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
  4599. i_projid != EXT4_DEF_PROJID);
  4600. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
  4601. EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
  4602. raw_inode->i_projid = cpu_to_le32(i_projid);
  4603. ext4_inode_csum_set(inode, raw_inode, ei);
  4604. spin_unlock(&ei->i_raw_lock);
  4605. if (inode->i_sb->s_flags & MS_LAZYTIME)
  4606. ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
  4607. bh->b_data);
  4608. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  4609. rc = ext4_handle_dirty_metadata(handle, NULL, bh);
  4610. if (!err)
  4611. err = rc;
  4612. ext4_clear_inode_state(inode, EXT4_STATE_NEW);
  4613. if (set_large_file) {
  4614. BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
  4615. err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
  4616. if (err)
  4617. goto out_brelse;
  4618. ext4_update_dynamic_rev(sb);
  4619. ext4_set_feature_large_file(sb);
  4620. ext4_handle_sync(handle);
  4621. err = ext4_handle_dirty_super(handle, sb);
  4622. }
  4623. ext4_update_inode_fsync_trans(handle, inode, need_datasync);
  4624. out_brelse:
  4625. brelse(bh);
  4626. ext4_std_error(inode->i_sb, err);
  4627. return err;
  4628. }
  4629. /*
  4630. * ext4_write_inode()
  4631. *
  4632. * We are called from a few places:
  4633. *
  4634. * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
  4635. * Here, there will be no transaction running. We wait for any running
  4636. * transaction to commit.
  4637. *
  4638. * - Within flush work (sys_sync(), kupdate and such).
  4639. * We wait on commit, if told to.
  4640. *
  4641. * - Within iput_final() -> write_inode_now()
  4642. * We wait on commit, if told to.
  4643. *
  4644. * In all cases it is actually safe for us to return without doing anything,
  4645. * because the inode has been copied into a raw inode buffer in
  4646. * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
  4647. * writeback.
  4648. *
  4649. * Note that we are absolutely dependent upon all inode dirtiers doing the
  4650. * right thing: they *must* call mark_inode_dirty() after dirtying info in
  4651. * which we are interested.
  4652. *
  4653. * It would be a bug for them to not do this. The code:
  4654. *
  4655. * mark_inode_dirty(inode)
  4656. * stuff();
  4657. * inode->i_size = expr;
  4658. *
  4659. * is in error because write_inode() could occur while `stuff()' is running,
  4660. * and the new i_size will be lost. Plus the inode will no longer be on the
  4661. * superblock's dirty inode list.
  4662. */
  4663. int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
  4664. {
  4665. int err;
  4666. if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
  4667. return 0;
  4668. if (EXT4_SB(inode->i_sb)->s_journal) {
  4669. if (ext4_journal_current_handle()) {
  4670. jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
  4671. dump_stack();
  4672. return -EIO;
  4673. }
  4674. /*
  4675. * No need to force transaction in WB_SYNC_NONE mode. Also
  4676. * ext4_sync_fs() will force the commit after everything is
  4677. * written.
  4678. */
  4679. if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
  4680. return 0;
  4681. err = ext4_force_commit(inode->i_sb);
  4682. } else {
  4683. struct ext4_iloc iloc;
  4684. err = __ext4_get_inode_loc(inode, &iloc, 0);
  4685. if (err)
  4686. return err;
  4687. /*
  4688. * sync(2) will flush the whole buffer cache. No need to do
  4689. * it here separately for each inode.
  4690. */
  4691. if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
  4692. sync_dirty_buffer(iloc.bh);
  4693. if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
  4694. EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
  4695. "IO error syncing inode");
  4696. err = -EIO;
  4697. }
  4698. brelse(iloc.bh);
  4699. }
  4700. return err;
  4701. }
  4702. /*
  4703. * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
  4704. * buffers that are attached to a page stradding i_size and are undergoing
  4705. * commit. In that case we have to wait for commit to finish and try again.
  4706. */
  4707. static void ext4_wait_for_tail_page_commit(struct inode *inode)
  4708. {
  4709. struct page *page;
  4710. unsigned offset;
  4711. journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
  4712. tid_t commit_tid = 0;
  4713. int ret;
  4714. offset = inode->i_size & (PAGE_SIZE - 1);
  4715. /*
  4716. * All buffers in the last page remain valid? Then there's nothing to
  4717. * do. We do the check mainly to optimize the common PAGE_SIZE ==
  4718. * blocksize case
  4719. */
  4720. if (offset > PAGE_SIZE - i_blocksize(inode))
  4721. return;
  4722. while (1) {
  4723. page = find_lock_page(inode->i_mapping,
  4724. inode->i_size >> PAGE_SHIFT);
  4725. if (!page)
  4726. return;
  4727. ret = __ext4_journalled_invalidatepage(page, offset,
  4728. PAGE_SIZE - offset);
  4729. unlock_page(page);
  4730. put_page(page);
  4731. if (ret != -EBUSY)
  4732. return;
  4733. commit_tid = 0;
  4734. read_lock(&journal->j_state_lock);
  4735. if (journal->j_committing_transaction)
  4736. commit_tid = journal->j_committing_transaction->t_tid;
  4737. read_unlock(&journal->j_state_lock);
  4738. if (commit_tid)
  4739. jbd2_log_wait_commit(journal, commit_tid);
  4740. }
  4741. }
  4742. /*
  4743. * ext4_setattr()
  4744. *
  4745. * Called from notify_change.
  4746. *
  4747. * We want to trap VFS attempts to truncate the file as soon as
  4748. * possible. In particular, we want to make sure that when the VFS
  4749. * shrinks i_size, we put the inode on the orphan list and modify
  4750. * i_disksize immediately, so that during the subsequent flushing of
  4751. * dirty pages and freeing of disk blocks, we can guarantee that any
  4752. * commit will leave the blocks being flushed in an unused state on
  4753. * disk. (On recovery, the inode will get truncated and the blocks will
  4754. * be freed, so we have a strong guarantee that no future commit will
  4755. * leave these blocks visible to the user.)
  4756. *
  4757. * Another thing we have to assure is that if we are in ordered mode
  4758. * and inode is still attached to the committing transaction, we must
  4759. * we start writeout of all the dirty pages which are being truncated.
  4760. * This way we are sure that all the data written in the previous
  4761. * transaction are already on disk (truncate waits for pages under
  4762. * writeback).
  4763. *
  4764. * Called with inode->i_mutex down.
  4765. */
  4766. int ext4_setattr(struct dentry *dentry, struct iattr *attr)
  4767. {
  4768. struct inode *inode = d_inode(dentry);
  4769. int error, rc = 0;
  4770. int orphan = 0;
  4771. const unsigned int ia_valid = attr->ia_valid;
  4772. if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
  4773. return -EIO;
  4774. error = setattr_prepare(dentry, attr);
  4775. if (error)
  4776. return error;
  4777. if (is_quota_modification(inode, attr)) {
  4778. error = dquot_initialize(inode);
  4779. if (error)
  4780. return error;
  4781. }
  4782. if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
  4783. (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
  4784. handle_t *handle;
  4785. /* (user+group)*(old+new) structure, inode write (sb,
  4786. * inode block, ? - but truncate inode update has it) */
  4787. handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
  4788. (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
  4789. EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
  4790. if (IS_ERR(handle)) {
  4791. error = PTR_ERR(handle);
  4792. goto err_out;
  4793. }
  4794. /* dquot_transfer() calls back ext4_get_inode_usage() which
  4795. * counts xattr inode references.
  4796. */
  4797. down_read(&EXT4_I(inode)->xattr_sem);
  4798. error = dquot_transfer(inode, attr);
  4799. up_read(&EXT4_I(inode)->xattr_sem);
  4800. if (error) {
  4801. ext4_journal_stop(handle);
  4802. return error;
  4803. }
  4804. /* Update corresponding info in inode so that everything is in
  4805. * one transaction */
  4806. if (attr->ia_valid & ATTR_UID)
  4807. inode->i_uid = attr->ia_uid;
  4808. if (attr->ia_valid & ATTR_GID)
  4809. inode->i_gid = attr->ia_gid;
  4810. error = ext4_mark_inode_dirty(handle, inode);
  4811. ext4_journal_stop(handle);
  4812. }
  4813. if (attr->ia_valid & ATTR_SIZE) {
  4814. handle_t *handle;
  4815. loff_t oldsize = inode->i_size;
  4816. int shrink = (attr->ia_size <= inode->i_size);
  4817. if (ext4_encrypted_inode(inode)) {
  4818. error = fscrypt_get_encryption_info(inode);
  4819. if (error)
  4820. return error;
  4821. if (!fscrypt_has_encryption_key(inode))
  4822. return -ENOKEY;
  4823. }
  4824. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
  4825. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  4826. if (attr->ia_size > sbi->s_bitmap_maxbytes)
  4827. return -EFBIG;
  4828. }
  4829. if (!S_ISREG(inode->i_mode))
  4830. return -EINVAL;
  4831. if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
  4832. inode_inc_iversion(inode);
  4833. if (ext4_should_order_data(inode) &&
  4834. (attr->ia_size < inode->i_size)) {
  4835. error = ext4_begin_ordered_truncate(inode,
  4836. attr->ia_size);
  4837. if (error)
  4838. goto err_out;
  4839. }
  4840. if (attr->ia_size != inode->i_size) {
  4841. handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
  4842. if (IS_ERR(handle)) {
  4843. error = PTR_ERR(handle);
  4844. goto err_out;
  4845. }
  4846. if (ext4_handle_valid(handle) && shrink) {
  4847. error = ext4_orphan_add(handle, inode);
  4848. orphan = 1;
  4849. }
  4850. /*
  4851. * Update c/mtime on truncate up, ext4_truncate() will
  4852. * update c/mtime in shrink case below
  4853. */
  4854. if (!shrink) {
  4855. inode->i_mtime = current_time(inode);
  4856. inode->i_ctime = inode->i_mtime;
  4857. }
  4858. down_write(&EXT4_I(inode)->i_data_sem);
  4859. EXT4_I(inode)->i_disksize = attr->ia_size;
  4860. rc = ext4_mark_inode_dirty(handle, inode);
  4861. if (!error)
  4862. error = rc;
  4863. /*
  4864. * We have to update i_size under i_data_sem together
  4865. * with i_disksize to avoid races with writeback code
  4866. * running ext4_wb_update_i_disksize().
  4867. */
  4868. if (!error)
  4869. i_size_write(inode, attr->ia_size);
  4870. up_write(&EXT4_I(inode)->i_data_sem);
  4871. ext4_journal_stop(handle);
  4872. if (error) {
  4873. if (orphan)
  4874. ext4_orphan_del(NULL, inode);
  4875. goto err_out;
  4876. }
  4877. }
  4878. if (!shrink)
  4879. pagecache_isize_extended(inode, oldsize, inode->i_size);
  4880. /*
  4881. * Blocks are going to be removed from the inode. Wait
  4882. * for dio in flight. Temporarily disable
  4883. * dioread_nolock to prevent livelock.
  4884. */
  4885. if (orphan) {
  4886. if (!ext4_should_journal_data(inode)) {
  4887. ext4_inode_block_unlocked_dio(inode);
  4888. inode_dio_wait(inode);
  4889. ext4_inode_resume_unlocked_dio(inode);
  4890. } else
  4891. ext4_wait_for_tail_page_commit(inode);
  4892. }
  4893. down_write(&EXT4_I(inode)->i_mmap_sem);
  4894. /*
  4895. * Truncate pagecache after we've waited for commit
  4896. * in data=journal mode to make pages freeable.
  4897. */
  4898. truncate_pagecache(inode, inode->i_size);
  4899. if (shrink) {
  4900. rc = ext4_truncate(inode);
  4901. if (rc)
  4902. error = rc;
  4903. }
  4904. up_write(&EXT4_I(inode)->i_mmap_sem);
  4905. }
  4906. if (!error) {
  4907. setattr_copy(inode, attr);
  4908. mark_inode_dirty(inode);
  4909. }
  4910. /*
  4911. * If the call to ext4_truncate failed to get a transaction handle at
  4912. * all, we need to clean up the in-core orphan list manually.
  4913. */
  4914. if (orphan && inode->i_nlink)
  4915. ext4_orphan_del(NULL, inode);
  4916. if (!error && (ia_valid & ATTR_MODE))
  4917. rc = posix_acl_chmod(inode, inode->i_mode);
  4918. err_out:
  4919. ext4_std_error(inode->i_sb, error);
  4920. if (!error)
  4921. error = rc;
  4922. return error;
  4923. }
  4924. int ext4_getattr(const struct path *path, struct kstat *stat,
  4925. u32 request_mask, unsigned int query_flags)
  4926. {
  4927. struct inode *inode = d_inode(path->dentry);
  4928. struct ext4_inode *raw_inode;
  4929. struct ext4_inode_info *ei = EXT4_I(inode);
  4930. unsigned int flags;
  4931. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
  4932. stat->result_mask |= STATX_BTIME;
  4933. stat->btime.tv_sec = ei->i_crtime.tv_sec;
  4934. stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
  4935. }
  4936. flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
  4937. if (flags & EXT4_APPEND_FL)
  4938. stat->attributes |= STATX_ATTR_APPEND;
  4939. if (flags & EXT4_COMPR_FL)
  4940. stat->attributes |= STATX_ATTR_COMPRESSED;
  4941. if (flags & EXT4_ENCRYPT_FL)
  4942. stat->attributes |= STATX_ATTR_ENCRYPTED;
  4943. if (flags & EXT4_IMMUTABLE_FL)
  4944. stat->attributes |= STATX_ATTR_IMMUTABLE;
  4945. if (flags & EXT4_NODUMP_FL)
  4946. stat->attributes |= STATX_ATTR_NODUMP;
  4947. stat->attributes_mask |= (STATX_ATTR_APPEND |
  4948. STATX_ATTR_COMPRESSED |
  4949. STATX_ATTR_ENCRYPTED |
  4950. STATX_ATTR_IMMUTABLE |
  4951. STATX_ATTR_NODUMP);
  4952. generic_fillattr(inode, stat);
  4953. return 0;
  4954. }
  4955. int ext4_file_getattr(const struct path *path, struct kstat *stat,
  4956. u32 request_mask, unsigned int query_flags)
  4957. {
  4958. struct inode *inode = d_inode(path->dentry);
  4959. u64 delalloc_blocks;
  4960. ext4_getattr(path, stat, request_mask, query_flags);
  4961. /*
  4962. * If there is inline data in the inode, the inode will normally not
  4963. * have data blocks allocated (it may have an external xattr block).
  4964. * Report at least one sector for such files, so tools like tar, rsync,
  4965. * others don't incorrectly think the file is completely sparse.
  4966. */
  4967. if (unlikely(ext4_has_inline_data(inode)))
  4968. stat->blocks += (stat->size + 511) >> 9;
  4969. /*
  4970. * We can't update i_blocks if the block allocation is delayed
  4971. * otherwise in the case of system crash before the real block
  4972. * allocation is done, we will have i_blocks inconsistent with
  4973. * on-disk file blocks.
  4974. * We always keep i_blocks updated together with real
  4975. * allocation. But to not confuse with user, stat
  4976. * will return the blocks that include the delayed allocation
  4977. * blocks for this file.
  4978. */
  4979. delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
  4980. EXT4_I(inode)->i_reserved_data_blocks);
  4981. stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
  4982. return 0;
  4983. }
  4984. static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
  4985. int pextents)
  4986. {
  4987. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
  4988. return ext4_ind_trans_blocks(inode, lblocks);
  4989. return ext4_ext_index_trans_blocks(inode, pextents);
  4990. }
  4991. /*
  4992. * Account for index blocks, block groups bitmaps and block group
  4993. * descriptor blocks if modify datablocks and index blocks
  4994. * worse case, the indexs blocks spread over different block groups
  4995. *
  4996. * If datablocks are discontiguous, they are possible to spread over
  4997. * different block groups too. If they are contiguous, with flexbg,
  4998. * they could still across block group boundary.
  4999. *
  5000. * Also account for superblock, inode, quota and xattr blocks
  5001. */
  5002. static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
  5003. int pextents)
  5004. {
  5005. ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
  5006. int gdpblocks;
  5007. int idxblocks;
  5008. int ret = 0;
  5009. /*
  5010. * How many index blocks need to touch to map @lblocks logical blocks
  5011. * to @pextents physical extents?
  5012. */
  5013. idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
  5014. ret = idxblocks;
  5015. /*
  5016. * Now let's see how many group bitmaps and group descriptors need
  5017. * to account
  5018. */
  5019. groups = idxblocks + pextents;
  5020. gdpblocks = groups;
  5021. if (groups > ngroups)
  5022. groups = ngroups;
  5023. if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
  5024. gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
  5025. /* bitmaps and block group descriptor blocks */
  5026. ret += groups + gdpblocks;
  5027. /* Blocks for super block, inode, quota and xattr blocks */
  5028. ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
  5029. return ret;
  5030. }
  5031. /*
  5032. * Calculate the total number of credits to reserve to fit
  5033. * the modification of a single pages into a single transaction,
  5034. * which may include multiple chunks of block allocations.
  5035. *
  5036. * This could be called via ext4_write_begin()
  5037. *
  5038. * We need to consider the worse case, when
  5039. * one new block per extent.
  5040. */
  5041. int ext4_writepage_trans_blocks(struct inode *inode)
  5042. {
  5043. int bpp = ext4_journal_blocks_per_page(inode);
  5044. int ret;
  5045. ret = ext4_meta_trans_blocks(inode, bpp, bpp);
  5046. /* Account for data blocks for journalled mode */
  5047. if (ext4_should_journal_data(inode))
  5048. ret += bpp;
  5049. return ret;
  5050. }
  5051. /*
  5052. * Calculate the journal credits for a chunk of data modification.
  5053. *
  5054. * This is called from DIO, fallocate or whoever calling
  5055. * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
  5056. *
  5057. * journal buffers for data blocks are not included here, as DIO
  5058. * and fallocate do no need to journal data buffers.
  5059. */
  5060. int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
  5061. {
  5062. return ext4_meta_trans_blocks(inode, nrblocks, 1);
  5063. }
  5064. /*
  5065. * The caller must have previously called ext4_reserve_inode_write().
  5066. * Give this, we know that the caller already has write access to iloc->bh.
  5067. */
  5068. int ext4_mark_iloc_dirty(handle_t *handle,
  5069. struct inode *inode, struct ext4_iloc *iloc)
  5070. {
  5071. int err = 0;
  5072. if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
  5073. return -EIO;
  5074. if (IS_I_VERSION(inode))
  5075. inode_inc_iversion(inode);
  5076. /* the do_update_inode consumes one bh->b_count */
  5077. get_bh(iloc->bh);
  5078. /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
  5079. err = ext4_do_update_inode(handle, inode, iloc);
  5080. put_bh(iloc->bh);
  5081. return err;
  5082. }
  5083. /*
  5084. * On success, We end up with an outstanding reference count against
  5085. * iloc->bh. This _must_ be cleaned up later.
  5086. */
  5087. int
  5088. ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
  5089. struct ext4_iloc *iloc)
  5090. {
  5091. int err;
  5092. if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
  5093. return -EIO;
  5094. err = ext4_get_inode_loc(inode, iloc);
  5095. if (!err) {
  5096. BUFFER_TRACE(iloc->bh, "get_write_access");
  5097. err = ext4_journal_get_write_access(handle, iloc->bh);
  5098. if (err) {
  5099. brelse(iloc->bh);
  5100. iloc->bh = NULL;
  5101. }
  5102. }
  5103. ext4_std_error(inode->i_sb, err);
  5104. return err;
  5105. }
  5106. static int __ext4_expand_extra_isize(struct inode *inode,
  5107. unsigned int new_extra_isize,
  5108. struct ext4_iloc *iloc,
  5109. handle_t *handle, int *no_expand)
  5110. {
  5111. struct ext4_inode *raw_inode;
  5112. struct ext4_xattr_ibody_header *header;
  5113. int error;
  5114. raw_inode = ext4_raw_inode(iloc);
  5115. header = IHDR(inode, raw_inode);
  5116. /* No extended attributes present */
  5117. if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
  5118. header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
  5119. memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
  5120. EXT4_I(inode)->i_extra_isize, 0,
  5121. new_extra_isize - EXT4_I(inode)->i_extra_isize);
  5122. EXT4_I(inode)->i_extra_isize = new_extra_isize;
  5123. return 0;
  5124. }
  5125. /* try to expand with EAs present */
  5126. error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
  5127. raw_inode, handle);
  5128. if (error) {
  5129. /*
  5130. * Inode size expansion failed; don't try again
  5131. */
  5132. *no_expand = 1;
  5133. }
  5134. return error;
  5135. }
  5136. /*
  5137. * Expand an inode by new_extra_isize bytes.
  5138. * Returns 0 on success or negative error number on failure.
  5139. */
  5140. static int ext4_try_to_expand_extra_isize(struct inode *inode,
  5141. unsigned int new_extra_isize,
  5142. struct ext4_iloc iloc,
  5143. handle_t *handle)
  5144. {
  5145. int no_expand;
  5146. int error;
  5147. if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
  5148. return -EOVERFLOW;
  5149. /*
  5150. * In nojournal mode, we can immediately attempt to expand
  5151. * the inode. When journaled, we first need to obtain extra
  5152. * buffer credits since we may write into the EA block
  5153. * with this same handle. If journal_extend fails, then it will
  5154. * only result in a minor loss of functionality for that inode.
  5155. * If this is felt to be critical, then e2fsck should be run to
  5156. * force a large enough s_min_extra_isize.
  5157. */
  5158. if (ext4_handle_valid(handle) &&
  5159. jbd2_journal_extend(handle,
  5160. EXT4_DATA_TRANS_BLOCKS(inode->i_sb)) != 0)
  5161. return -ENOSPC;
  5162. if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
  5163. return -EBUSY;
  5164. error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
  5165. handle, &no_expand);
  5166. ext4_write_unlock_xattr(inode, &no_expand);
  5167. return error;
  5168. }
  5169. int ext4_expand_extra_isize(struct inode *inode,
  5170. unsigned int new_extra_isize,
  5171. struct ext4_iloc *iloc)
  5172. {
  5173. handle_t *handle;
  5174. int no_expand;
  5175. int error, rc;
  5176. if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
  5177. brelse(iloc->bh);
  5178. return -EOVERFLOW;
  5179. }
  5180. handle = ext4_journal_start(inode, EXT4_HT_INODE,
  5181. EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
  5182. if (IS_ERR(handle)) {
  5183. error = PTR_ERR(handle);
  5184. brelse(iloc->bh);
  5185. return error;
  5186. }
  5187. ext4_write_lock_xattr(inode, &no_expand);
  5188. BUFFER_TRACE(iloc.bh, "get_write_access");
  5189. error = ext4_journal_get_write_access(handle, iloc->bh);
  5190. if (error) {
  5191. brelse(iloc->bh);
  5192. goto out_stop;
  5193. }
  5194. error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
  5195. handle, &no_expand);
  5196. rc = ext4_mark_iloc_dirty(handle, inode, iloc);
  5197. if (!error)
  5198. error = rc;
  5199. ext4_write_unlock_xattr(inode, &no_expand);
  5200. out_stop:
  5201. ext4_journal_stop(handle);
  5202. return error;
  5203. }
  5204. /*
  5205. * What we do here is to mark the in-core inode as clean with respect to inode
  5206. * dirtiness (it may still be data-dirty).
  5207. * This means that the in-core inode may be reaped by prune_icache
  5208. * without having to perform any I/O. This is a very good thing,
  5209. * because *any* task may call prune_icache - even ones which
  5210. * have a transaction open against a different journal.
  5211. *
  5212. * Is this cheating? Not really. Sure, we haven't written the
  5213. * inode out, but prune_icache isn't a user-visible syncing function.
  5214. * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
  5215. * we start and wait on commits.
  5216. */
  5217. int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
  5218. {
  5219. struct ext4_iloc iloc;
  5220. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  5221. int err;
  5222. might_sleep();
  5223. trace_ext4_mark_inode_dirty(inode, _RET_IP_);
  5224. err = ext4_reserve_inode_write(handle, inode, &iloc);
  5225. if (err)
  5226. return err;
  5227. if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
  5228. ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
  5229. iloc, handle);
  5230. return ext4_mark_iloc_dirty(handle, inode, &iloc);
  5231. }
  5232. /*
  5233. * ext4_dirty_inode() is called from __mark_inode_dirty()
  5234. *
  5235. * We're really interested in the case where a file is being extended.
  5236. * i_size has been changed by generic_commit_write() and we thus need
  5237. * to include the updated inode in the current transaction.
  5238. *
  5239. * Also, dquot_alloc_block() will always dirty the inode when blocks
  5240. * are allocated to the file.
  5241. *
  5242. * If the inode is marked synchronous, we don't honour that here - doing
  5243. * so would cause a commit on atime updates, which we don't bother doing.
  5244. * We handle synchronous inodes at the highest possible level.
  5245. *
  5246. * If only the I_DIRTY_TIME flag is set, we can skip everything. If
  5247. * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
  5248. * to copy into the on-disk inode structure are the timestamp files.
  5249. */
  5250. void ext4_dirty_inode(struct inode *inode, int flags)
  5251. {
  5252. handle_t *handle;
  5253. if (flags == I_DIRTY_TIME)
  5254. return;
  5255. handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
  5256. if (IS_ERR(handle))
  5257. goto out;
  5258. ext4_mark_inode_dirty(handle, inode);
  5259. ext4_journal_stop(handle);
  5260. out:
  5261. return;
  5262. }
  5263. #if 0
  5264. /*
  5265. * Bind an inode's backing buffer_head into this transaction, to prevent
  5266. * it from being flushed to disk early. Unlike
  5267. * ext4_reserve_inode_write, this leaves behind no bh reference and
  5268. * returns no iloc structure, so the caller needs to repeat the iloc
  5269. * lookup to mark the inode dirty later.
  5270. */
  5271. static int ext4_pin_inode(handle_t *handle, struct inode *inode)
  5272. {
  5273. struct ext4_iloc iloc;
  5274. int err = 0;
  5275. if (handle) {
  5276. err = ext4_get_inode_loc(inode, &iloc);
  5277. if (!err) {
  5278. BUFFER_TRACE(iloc.bh, "get_write_access");
  5279. err = jbd2_journal_get_write_access(handle, iloc.bh);
  5280. if (!err)
  5281. err = ext4_handle_dirty_metadata(handle,
  5282. NULL,
  5283. iloc.bh);
  5284. brelse(iloc.bh);
  5285. }
  5286. }
  5287. ext4_std_error(inode->i_sb, err);
  5288. return err;
  5289. }
  5290. #endif
  5291. int ext4_change_inode_journal_flag(struct inode *inode, int val)
  5292. {
  5293. journal_t *journal;
  5294. handle_t *handle;
  5295. int err;
  5296. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  5297. /*
  5298. * We have to be very careful here: changing a data block's
  5299. * journaling status dynamically is dangerous. If we write a
  5300. * data block to the journal, change the status and then delete
  5301. * that block, we risk forgetting to revoke the old log record
  5302. * from the journal and so a subsequent replay can corrupt data.
  5303. * So, first we make sure that the journal is empty and that
  5304. * nobody is changing anything.
  5305. */
  5306. journal = EXT4_JOURNAL(inode);
  5307. if (!journal)
  5308. return 0;
  5309. if (is_journal_aborted(journal))
  5310. return -EROFS;
  5311. /* Wait for all existing dio workers */
  5312. ext4_inode_block_unlocked_dio(inode);
  5313. inode_dio_wait(inode);
  5314. /*
  5315. * Before flushing the journal and switching inode's aops, we have
  5316. * to flush all dirty data the inode has. There can be outstanding
  5317. * delayed allocations, there can be unwritten extents created by
  5318. * fallocate or buffered writes in dioread_nolock mode covered by
  5319. * dirty data which can be converted only after flushing the dirty
  5320. * data (and journalled aops don't know how to handle these cases).
  5321. */
  5322. if (val) {
  5323. down_write(&EXT4_I(inode)->i_mmap_sem);
  5324. err = filemap_write_and_wait(inode->i_mapping);
  5325. if (err < 0) {
  5326. up_write(&EXT4_I(inode)->i_mmap_sem);
  5327. ext4_inode_resume_unlocked_dio(inode);
  5328. return err;
  5329. }
  5330. }
  5331. percpu_down_write(&sbi->s_journal_flag_rwsem);
  5332. jbd2_journal_lock_updates(journal);
  5333. /*
  5334. * OK, there are no updates running now, and all cached data is
  5335. * synced to disk. We are now in a completely consistent state
  5336. * which doesn't have anything in the journal, and we know that
  5337. * no filesystem updates are running, so it is safe to modify
  5338. * the inode's in-core data-journaling state flag now.
  5339. */
  5340. if (val)
  5341. ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  5342. else {
  5343. err = jbd2_journal_flush(journal);
  5344. if (err < 0) {
  5345. jbd2_journal_unlock_updates(journal);
  5346. percpu_up_write(&sbi->s_journal_flag_rwsem);
  5347. ext4_inode_resume_unlocked_dio(inode);
  5348. return err;
  5349. }
  5350. ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  5351. }
  5352. ext4_set_aops(inode);
  5353. /*
  5354. * Update inode->i_flags after EXT4_INODE_JOURNAL_DATA was updated.
  5355. * E.g. S_DAX may get cleared / set.
  5356. */
  5357. ext4_set_inode_flags(inode);
  5358. jbd2_journal_unlock_updates(journal);
  5359. percpu_up_write(&sbi->s_journal_flag_rwsem);
  5360. if (val)
  5361. up_write(&EXT4_I(inode)->i_mmap_sem);
  5362. ext4_inode_resume_unlocked_dio(inode);
  5363. /* Finally we can mark the inode as dirty. */
  5364. handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
  5365. if (IS_ERR(handle))
  5366. return PTR_ERR(handle);
  5367. err = ext4_mark_inode_dirty(handle, inode);
  5368. ext4_handle_sync(handle);
  5369. ext4_journal_stop(handle);
  5370. ext4_std_error(inode->i_sb, err);
  5371. return err;
  5372. }
  5373. static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
  5374. {
  5375. return !buffer_mapped(bh);
  5376. }
  5377. int ext4_page_mkwrite(struct vm_fault *vmf)
  5378. {
  5379. struct vm_area_struct *vma = vmf->vma;
  5380. struct page *page = vmf->page;
  5381. loff_t size;
  5382. unsigned long len;
  5383. int ret;
  5384. struct file *file = vma->vm_file;
  5385. struct inode *inode = file_inode(file);
  5386. struct address_space *mapping = inode->i_mapping;
  5387. handle_t *handle;
  5388. get_block_t *get_block;
  5389. int retries = 0;
  5390. sb_start_pagefault(inode->i_sb);
  5391. file_update_time(vma->vm_file);
  5392. down_read(&EXT4_I(inode)->i_mmap_sem);
  5393. ret = ext4_convert_inline_data(inode);
  5394. if (ret)
  5395. goto out_ret;
  5396. /* Delalloc case is easy... */
  5397. if (test_opt(inode->i_sb, DELALLOC) &&
  5398. !ext4_should_journal_data(inode) &&
  5399. !ext4_nonda_switch(inode->i_sb)) {
  5400. do {
  5401. ret = block_page_mkwrite(vma, vmf,
  5402. ext4_da_get_block_prep);
  5403. } while (ret == -ENOSPC &&
  5404. ext4_should_retry_alloc(inode->i_sb, &retries));
  5405. goto out_ret;
  5406. }
  5407. lock_page(page);
  5408. size = i_size_read(inode);
  5409. /* Page got truncated from under us? */
  5410. if (page->mapping != mapping || page_offset(page) > size) {
  5411. unlock_page(page);
  5412. ret = VM_FAULT_NOPAGE;
  5413. goto out;
  5414. }
  5415. if (page->index == size >> PAGE_SHIFT)
  5416. len = size & ~PAGE_MASK;
  5417. else
  5418. len = PAGE_SIZE;
  5419. /*
  5420. * Return if we have all the buffers mapped. This avoids the need to do
  5421. * journal_start/journal_stop which can block and take a long time
  5422. */
  5423. if (page_has_buffers(page)) {
  5424. if (!ext4_walk_page_buffers(NULL, page_buffers(page),
  5425. 0, len, NULL,
  5426. ext4_bh_unmapped)) {
  5427. /* Wait so that we don't change page under IO */
  5428. wait_for_stable_page(page);
  5429. ret = VM_FAULT_LOCKED;
  5430. goto out;
  5431. }
  5432. }
  5433. unlock_page(page);
  5434. /* OK, we need to fill the hole... */
  5435. if (ext4_should_dioread_nolock(inode))
  5436. get_block = ext4_get_block_unwritten;
  5437. else
  5438. get_block = ext4_get_block;
  5439. retry_alloc:
  5440. handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
  5441. ext4_writepage_trans_blocks(inode));
  5442. if (IS_ERR(handle)) {
  5443. ret = VM_FAULT_SIGBUS;
  5444. goto out;
  5445. }
  5446. ret = block_page_mkwrite(vma, vmf, get_block);
  5447. if (!ret && ext4_should_journal_data(inode)) {
  5448. if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
  5449. PAGE_SIZE, NULL, do_journal_get_write_access)) {
  5450. unlock_page(page);
  5451. ret = VM_FAULT_SIGBUS;
  5452. ext4_journal_stop(handle);
  5453. goto out;
  5454. }
  5455. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  5456. }
  5457. ext4_journal_stop(handle);
  5458. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  5459. goto retry_alloc;
  5460. out_ret:
  5461. ret = block_page_mkwrite_return(ret);
  5462. out:
  5463. up_read(&EXT4_I(inode)->i_mmap_sem);
  5464. sb_end_pagefault(inode->i_sb);
  5465. return ret;
  5466. }
  5467. int ext4_filemap_fault(struct vm_fault *vmf)
  5468. {
  5469. struct inode *inode = file_inode(vmf->vma->vm_file);
  5470. int err;
  5471. down_read(&EXT4_I(inode)->i_mmap_sem);
  5472. err = filemap_fault(vmf);
  5473. up_read(&EXT4_I(inode)->i_mmap_sem);
  5474. return err;
  5475. }
  5476. /*
  5477. * Find the first extent at or after @lblk in an inode that is not a hole.
  5478. * Search for @map_len blocks at most. The extent is returned in @result.
  5479. *
  5480. * The function returns 1 if we found an extent. The function returns 0 in
  5481. * case there is no extent at or after @lblk and in that case also sets
  5482. * @result->es_len to 0. In case of error, the error code is returned.
  5483. */
  5484. int ext4_get_next_extent(struct inode *inode, ext4_lblk_t lblk,
  5485. unsigned int map_len, struct extent_status *result)
  5486. {
  5487. struct ext4_map_blocks map;
  5488. struct extent_status es = {};
  5489. int ret;
  5490. map.m_lblk = lblk;
  5491. map.m_len = map_len;
  5492. /*
  5493. * For non-extent based files this loop may iterate several times since
  5494. * we do not determine full hole size.
  5495. */
  5496. while (map.m_len > 0) {
  5497. ret = ext4_map_blocks(NULL, inode, &map, 0);
  5498. if (ret < 0)
  5499. return ret;
  5500. /* There's extent covering m_lblk? Just return it. */
  5501. if (ret > 0) {
  5502. int status;
  5503. ext4_es_store_pblock(result, map.m_pblk);
  5504. result->es_lblk = map.m_lblk;
  5505. result->es_len = map.m_len;
  5506. if (map.m_flags & EXT4_MAP_UNWRITTEN)
  5507. status = EXTENT_STATUS_UNWRITTEN;
  5508. else
  5509. status = EXTENT_STATUS_WRITTEN;
  5510. ext4_es_store_status(result, status);
  5511. return 1;
  5512. }
  5513. ext4_es_find_delayed_extent_range(inode, map.m_lblk,
  5514. map.m_lblk + map.m_len - 1,
  5515. &es);
  5516. /* Is delalloc data before next block in extent tree? */
  5517. if (es.es_len && es.es_lblk < map.m_lblk + map.m_len) {
  5518. ext4_lblk_t offset = 0;
  5519. if (es.es_lblk < lblk)
  5520. offset = lblk - es.es_lblk;
  5521. result->es_lblk = es.es_lblk + offset;
  5522. ext4_es_store_pblock(result,
  5523. ext4_es_pblock(&es) + offset);
  5524. result->es_len = es.es_len - offset;
  5525. ext4_es_store_status(result, ext4_es_status(&es));
  5526. return 1;
  5527. }
  5528. /* There's a hole at m_lblk, advance us after it */
  5529. map.m_lblk += map.m_len;
  5530. map_len -= map.m_len;
  5531. map.m_len = map_len;
  5532. cond_resched();
  5533. }
  5534. result->es_len = 0;
  5535. return 0;
  5536. }