inode.c 174 KB

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