inode.c 174 KB

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