inode.c 171 KB

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