inode.c 174 KB

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