inode.c 174 KB

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