inode.c 174 KB

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