inode.c 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924
  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, nblocks);
  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, goal,
  583. 0, &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, NULL, 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, NULL, 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, NULL, 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, NULL, new_blocks[i], 1, 0);
  767. ext4_free_blocks(handle, inode, NULL, 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, NULL, 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. trace_ext4_ind_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
  895. J_ASSERT(!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)));
  896. J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
  897. depth = ext4_block_to_path(inode, map->m_lblk, offsets,
  898. &blocks_to_boundary);
  899. if (depth == 0)
  900. goto out;
  901. partial = ext4_get_branch(inode, depth, offsets, chain, &err);
  902. /* Simplest case - block found, no allocation needed */
  903. if (!partial) {
  904. first_block = le32_to_cpu(chain[depth - 1].key);
  905. count++;
  906. /*map more blocks*/
  907. while (count < map->m_len && count <= blocks_to_boundary) {
  908. ext4_fsblk_t blk;
  909. blk = le32_to_cpu(*(chain[depth-1].p + count));
  910. if (blk == first_block + count)
  911. count++;
  912. else
  913. break;
  914. }
  915. goto got_it;
  916. }
  917. /* Next simple case - plain lookup or failed read of indirect block */
  918. if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
  919. goto cleanup;
  920. /*
  921. * Okay, we need to do block allocation.
  922. */
  923. goal = ext4_find_goal(inode, map->m_lblk, partial);
  924. /* the number of blocks need to allocate for [d,t]indirect blocks */
  925. indirect_blks = (chain + depth) - partial - 1;
  926. /*
  927. * Next look up the indirect map to count the totoal number of
  928. * direct blocks to allocate for this branch.
  929. */
  930. count = ext4_blks_to_allocate(partial, indirect_blks,
  931. map->m_len, blocks_to_boundary);
  932. /*
  933. * Block out ext4_truncate while we alter the tree
  934. */
  935. err = ext4_alloc_branch(handle, inode, map->m_lblk, indirect_blks,
  936. &count, goal,
  937. offsets + (partial - chain), partial);
  938. /*
  939. * The ext4_splice_branch call will free and forget any buffers
  940. * on the new chain if there is a failure, but that risks using
  941. * up transaction credits, especially for bitmaps where the
  942. * credits cannot be returned. Can we handle this somehow? We
  943. * may need to return -EAGAIN upwards in the worst case. --sct
  944. */
  945. if (!err)
  946. err = ext4_splice_branch(handle, inode, map->m_lblk,
  947. partial, indirect_blks, count);
  948. if (err)
  949. goto cleanup;
  950. map->m_flags |= EXT4_MAP_NEW;
  951. ext4_update_inode_fsync_trans(handle, inode, 1);
  952. got_it:
  953. map->m_flags |= EXT4_MAP_MAPPED;
  954. map->m_pblk = le32_to_cpu(chain[depth-1].key);
  955. map->m_len = count;
  956. if (count > blocks_to_boundary)
  957. map->m_flags |= EXT4_MAP_BOUNDARY;
  958. err = count;
  959. /* Clean up and exit */
  960. partial = chain + depth - 1; /* the whole chain */
  961. cleanup:
  962. while (partial > chain) {
  963. BUFFER_TRACE(partial->bh, "call brelse");
  964. brelse(partial->bh);
  965. partial--;
  966. }
  967. out:
  968. trace_ext4_ind_map_blocks_exit(inode, map->m_lblk,
  969. map->m_pblk, map->m_len, err);
  970. return err;
  971. }
  972. #ifdef CONFIG_QUOTA
  973. qsize_t *ext4_get_reserved_space(struct inode *inode)
  974. {
  975. return &EXT4_I(inode)->i_reserved_quota;
  976. }
  977. #endif
  978. /*
  979. * Calculate the number of metadata blocks need to reserve
  980. * to allocate a new block at @lblocks for non extent file based file
  981. */
  982. static int ext4_ind_calc_metadata_amount(struct inode *inode, sector_t lblock)
  983. {
  984. struct ext4_inode_info *ei = EXT4_I(inode);
  985. sector_t dind_mask = ~((sector_t)EXT4_ADDR_PER_BLOCK(inode->i_sb) - 1);
  986. int blk_bits;
  987. if (lblock < EXT4_NDIR_BLOCKS)
  988. return 0;
  989. lblock -= EXT4_NDIR_BLOCKS;
  990. if (ei->i_da_metadata_calc_len &&
  991. (lblock & dind_mask) == ei->i_da_metadata_calc_last_lblock) {
  992. ei->i_da_metadata_calc_len++;
  993. return 0;
  994. }
  995. ei->i_da_metadata_calc_last_lblock = lblock & dind_mask;
  996. ei->i_da_metadata_calc_len = 1;
  997. blk_bits = order_base_2(lblock);
  998. return (blk_bits / EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb)) + 1;
  999. }
  1000. /*
  1001. * Calculate the number of metadata blocks need to reserve
  1002. * to allocate a block located at @lblock
  1003. */
  1004. static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
  1005. {
  1006. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  1007. return ext4_ext_calc_metadata_amount(inode, lblock);
  1008. return ext4_ind_calc_metadata_amount(inode, lblock);
  1009. }
  1010. /*
  1011. * Called with i_data_sem down, which is important since we can call
  1012. * ext4_discard_preallocations() from here.
  1013. */
  1014. void ext4_da_update_reserve_space(struct inode *inode,
  1015. int used, int quota_claim)
  1016. {
  1017. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1018. struct ext4_inode_info *ei = EXT4_I(inode);
  1019. spin_lock(&ei->i_block_reservation_lock);
  1020. trace_ext4_da_update_reserve_space(inode, used);
  1021. if (unlikely(used > ei->i_reserved_data_blocks)) {
  1022. ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
  1023. "with only %d reserved data blocks\n",
  1024. __func__, inode->i_ino, used,
  1025. ei->i_reserved_data_blocks);
  1026. WARN_ON(1);
  1027. used = ei->i_reserved_data_blocks;
  1028. }
  1029. /* Update per-inode reservations */
  1030. ei->i_reserved_data_blocks -= used;
  1031. ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
  1032. percpu_counter_sub(&sbi->s_dirtyblocks_counter,
  1033. used + ei->i_allocated_meta_blocks);
  1034. ei->i_allocated_meta_blocks = 0;
  1035. if (ei->i_reserved_data_blocks == 0) {
  1036. /*
  1037. * We can release all of the reserved metadata blocks
  1038. * only when we have written all of the delayed
  1039. * allocation blocks.
  1040. */
  1041. percpu_counter_sub(&sbi->s_dirtyblocks_counter,
  1042. ei->i_reserved_meta_blocks);
  1043. ei->i_reserved_meta_blocks = 0;
  1044. ei->i_da_metadata_calc_len = 0;
  1045. }
  1046. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  1047. /* Update quota subsystem for data blocks */
  1048. if (quota_claim)
  1049. dquot_claim_block(inode, used);
  1050. else {
  1051. /*
  1052. * We did fallocate with an offset that is already delayed
  1053. * allocated. So on delayed allocated writeback we should
  1054. * not re-claim the quota for fallocated blocks.
  1055. */
  1056. dquot_release_reservation_block(inode, used);
  1057. }
  1058. /*
  1059. * If we have done all the pending block allocations and if
  1060. * there aren't any writers on the inode, we can discard the
  1061. * inode's preallocations.
  1062. */
  1063. if ((ei->i_reserved_data_blocks == 0) &&
  1064. (atomic_read(&inode->i_writecount) == 0))
  1065. ext4_discard_preallocations(inode);
  1066. }
  1067. static int __check_block_validity(struct inode *inode, const char *func,
  1068. unsigned int line,
  1069. struct ext4_map_blocks *map)
  1070. {
  1071. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
  1072. map->m_len)) {
  1073. ext4_error_inode(inode, func, line, map->m_pblk,
  1074. "lblock %lu mapped to illegal pblock "
  1075. "(length %d)", (unsigned long) map->m_lblk,
  1076. map->m_len);
  1077. return -EIO;
  1078. }
  1079. return 0;
  1080. }
  1081. #define check_block_validity(inode, map) \
  1082. __check_block_validity((inode), __func__, __LINE__, (map))
  1083. /*
  1084. * Return the number of contiguous dirty pages in a given inode
  1085. * starting at page frame idx.
  1086. */
  1087. static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
  1088. unsigned int max_pages)
  1089. {
  1090. struct address_space *mapping = inode->i_mapping;
  1091. pgoff_t index;
  1092. struct pagevec pvec;
  1093. pgoff_t num = 0;
  1094. int i, nr_pages, done = 0;
  1095. if (max_pages == 0)
  1096. return 0;
  1097. pagevec_init(&pvec, 0);
  1098. while (!done) {
  1099. index = idx;
  1100. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
  1101. PAGECACHE_TAG_DIRTY,
  1102. (pgoff_t)PAGEVEC_SIZE);
  1103. if (nr_pages == 0)
  1104. break;
  1105. for (i = 0; i < nr_pages; i++) {
  1106. struct page *page = pvec.pages[i];
  1107. struct buffer_head *bh, *head;
  1108. lock_page(page);
  1109. if (unlikely(page->mapping != mapping) ||
  1110. !PageDirty(page) ||
  1111. PageWriteback(page) ||
  1112. page->index != idx) {
  1113. done = 1;
  1114. unlock_page(page);
  1115. break;
  1116. }
  1117. if (page_has_buffers(page)) {
  1118. bh = head = page_buffers(page);
  1119. do {
  1120. if (!buffer_delay(bh) &&
  1121. !buffer_unwritten(bh))
  1122. done = 1;
  1123. bh = bh->b_this_page;
  1124. } while (!done && (bh != head));
  1125. }
  1126. unlock_page(page);
  1127. if (done)
  1128. break;
  1129. idx++;
  1130. num++;
  1131. if (num >= max_pages) {
  1132. done = 1;
  1133. break;
  1134. }
  1135. }
  1136. pagevec_release(&pvec);
  1137. }
  1138. return num;
  1139. }
  1140. /*
  1141. * The ext4_map_blocks() function tries to look up the requested blocks,
  1142. * and returns if the blocks are already mapped.
  1143. *
  1144. * Otherwise it takes the write lock of the i_data_sem and allocate blocks
  1145. * and store the allocated blocks in the result buffer head and mark it
  1146. * mapped.
  1147. *
  1148. * If file type is extents based, it will call ext4_ext_map_blocks(),
  1149. * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
  1150. * based files
  1151. *
  1152. * On success, it returns the number of blocks being mapped or allocate.
  1153. * if create==0 and the blocks are pre-allocated and uninitialized block,
  1154. * the result buffer head is unmapped. If the create ==1, it will make sure
  1155. * the buffer head is mapped.
  1156. *
  1157. * It returns 0 if plain look up failed (blocks have not been allocated), in
  1158. * that casem, buffer head is unmapped
  1159. *
  1160. * It returns the error in case of allocation failure.
  1161. */
  1162. int ext4_map_blocks(handle_t *handle, struct inode *inode,
  1163. struct ext4_map_blocks *map, int flags)
  1164. {
  1165. int retval;
  1166. map->m_flags = 0;
  1167. ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
  1168. "logical block %lu\n", inode->i_ino, flags, map->m_len,
  1169. (unsigned long) map->m_lblk);
  1170. /*
  1171. * Try to see if we can get the block without requesting a new
  1172. * file system block.
  1173. */
  1174. down_read((&EXT4_I(inode)->i_data_sem));
  1175. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  1176. retval = ext4_ext_map_blocks(handle, inode, map, 0);
  1177. } else {
  1178. retval = ext4_ind_map_blocks(handle, inode, map, 0);
  1179. }
  1180. up_read((&EXT4_I(inode)->i_data_sem));
  1181. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
  1182. int ret = check_block_validity(inode, map);
  1183. if (ret != 0)
  1184. return ret;
  1185. }
  1186. /* If it is only a block(s) look up */
  1187. if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
  1188. return retval;
  1189. /*
  1190. * Returns if the blocks have already allocated
  1191. *
  1192. * Note that if blocks have been preallocated
  1193. * ext4_ext_get_block() returns th create = 0
  1194. * with buffer head unmapped.
  1195. */
  1196. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
  1197. return retval;
  1198. /*
  1199. * When we call get_blocks without the create flag, the
  1200. * BH_Unwritten flag could have gotten set if the blocks
  1201. * requested were part of a uninitialized extent. We need to
  1202. * clear this flag now that we are committed to convert all or
  1203. * part of the uninitialized extent to be an initialized
  1204. * extent. This is because we need to avoid the combination
  1205. * of BH_Unwritten and BH_Mapped flags being simultaneously
  1206. * set on the buffer_head.
  1207. */
  1208. map->m_flags &= ~EXT4_MAP_UNWRITTEN;
  1209. /*
  1210. * New blocks allocate and/or writing to uninitialized extent
  1211. * will possibly result in updating i_data, so we take
  1212. * the write lock of i_data_sem, and call get_blocks()
  1213. * with create == 1 flag.
  1214. */
  1215. down_write((&EXT4_I(inode)->i_data_sem));
  1216. /*
  1217. * if the caller is from delayed allocation writeout path
  1218. * we have already reserved fs blocks for allocation
  1219. * let the underlying get_block() function know to
  1220. * avoid double accounting
  1221. */
  1222. if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
  1223. ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
  1224. /*
  1225. * We need to check for EXT4 here because migrate
  1226. * could have changed the inode type in between
  1227. */
  1228. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  1229. retval = ext4_ext_map_blocks(handle, inode, map, flags);
  1230. } else {
  1231. retval = ext4_ind_map_blocks(handle, inode, map, flags);
  1232. if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
  1233. /*
  1234. * We allocated new blocks which will result in
  1235. * i_data's format changing. Force the migrate
  1236. * to fail by clearing migrate flags
  1237. */
  1238. ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
  1239. }
  1240. /*
  1241. * Update reserved blocks/metadata blocks after successful
  1242. * block allocation which had been deferred till now. We don't
  1243. * support fallocate for non extent files. So we can update
  1244. * reserve space here.
  1245. */
  1246. if ((retval > 0) &&
  1247. (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
  1248. ext4_da_update_reserve_space(inode, retval, 1);
  1249. }
  1250. if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
  1251. ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
  1252. up_write((&EXT4_I(inode)->i_data_sem));
  1253. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
  1254. int ret = check_block_validity(inode, map);
  1255. if (ret != 0)
  1256. return ret;
  1257. }
  1258. return retval;
  1259. }
  1260. /* Maximum number of blocks we map for direct IO at once. */
  1261. #define DIO_MAX_BLOCKS 4096
  1262. static int _ext4_get_block(struct inode *inode, sector_t iblock,
  1263. struct buffer_head *bh, int flags)
  1264. {
  1265. handle_t *handle = ext4_journal_current_handle();
  1266. struct ext4_map_blocks map;
  1267. int ret = 0, started = 0;
  1268. int dio_credits;
  1269. map.m_lblk = iblock;
  1270. map.m_len = bh->b_size >> inode->i_blkbits;
  1271. if (flags && !handle) {
  1272. /* Direct IO write... */
  1273. if (map.m_len > DIO_MAX_BLOCKS)
  1274. map.m_len = DIO_MAX_BLOCKS;
  1275. dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
  1276. handle = ext4_journal_start(inode, dio_credits);
  1277. if (IS_ERR(handle)) {
  1278. ret = PTR_ERR(handle);
  1279. return ret;
  1280. }
  1281. started = 1;
  1282. }
  1283. ret = ext4_map_blocks(handle, inode, &map, flags);
  1284. if (ret > 0) {
  1285. map_bh(bh, inode->i_sb, map.m_pblk);
  1286. bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
  1287. bh->b_size = inode->i_sb->s_blocksize * map.m_len;
  1288. ret = 0;
  1289. }
  1290. if (started)
  1291. ext4_journal_stop(handle);
  1292. return ret;
  1293. }
  1294. int ext4_get_block(struct inode *inode, sector_t iblock,
  1295. struct buffer_head *bh, int create)
  1296. {
  1297. return _ext4_get_block(inode, iblock, bh,
  1298. create ? EXT4_GET_BLOCKS_CREATE : 0);
  1299. }
  1300. /*
  1301. * `handle' can be NULL if create is zero
  1302. */
  1303. struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
  1304. ext4_lblk_t block, int create, int *errp)
  1305. {
  1306. struct ext4_map_blocks map;
  1307. struct buffer_head *bh;
  1308. int fatal = 0, err;
  1309. J_ASSERT(handle != NULL || create == 0);
  1310. map.m_lblk = block;
  1311. map.m_len = 1;
  1312. err = ext4_map_blocks(handle, inode, &map,
  1313. create ? EXT4_GET_BLOCKS_CREATE : 0);
  1314. if (err < 0)
  1315. *errp = err;
  1316. if (err <= 0)
  1317. return NULL;
  1318. *errp = 0;
  1319. bh = sb_getblk(inode->i_sb, map.m_pblk);
  1320. if (!bh) {
  1321. *errp = -EIO;
  1322. return NULL;
  1323. }
  1324. if (map.m_flags & EXT4_MAP_NEW) {
  1325. J_ASSERT(create != 0);
  1326. J_ASSERT(handle != NULL);
  1327. /*
  1328. * Now that we do not always journal data, we should
  1329. * keep in mind whether this should always journal the
  1330. * new buffer as metadata. For now, regular file
  1331. * writes use ext4_get_block instead, so it's not a
  1332. * problem.
  1333. */
  1334. lock_buffer(bh);
  1335. BUFFER_TRACE(bh, "call get_create_access");
  1336. fatal = ext4_journal_get_create_access(handle, bh);
  1337. if (!fatal && !buffer_uptodate(bh)) {
  1338. memset(bh->b_data, 0, inode->i_sb->s_blocksize);
  1339. set_buffer_uptodate(bh);
  1340. }
  1341. unlock_buffer(bh);
  1342. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  1343. err = ext4_handle_dirty_metadata(handle, inode, bh);
  1344. if (!fatal)
  1345. fatal = err;
  1346. } else {
  1347. BUFFER_TRACE(bh, "not a new buffer");
  1348. }
  1349. if (fatal) {
  1350. *errp = fatal;
  1351. brelse(bh);
  1352. bh = NULL;
  1353. }
  1354. return bh;
  1355. }
  1356. struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
  1357. ext4_lblk_t block, int create, int *err)
  1358. {
  1359. struct buffer_head *bh;
  1360. bh = ext4_getblk(handle, inode, block, create, err);
  1361. if (!bh)
  1362. return bh;
  1363. if (buffer_uptodate(bh))
  1364. return bh;
  1365. ll_rw_block(READ_META, 1, &bh);
  1366. wait_on_buffer(bh);
  1367. if (buffer_uptodate(bh))
  1368. return bh;
  1369. put_bh(bh);
  1370. *err = -EIO;
  1371. return NULL;
  1372. }
  1373. static int walk_page_buffers(handle_t *handle,
  1374. struct buffer_head *head,
  1375. unsigned from,
  1376. unsigned to,
  1377. int *partial,
  1378. int (*fn)(handle_t *handle,
  1379. struct buffer_head *bh))
  1380. {
  1381. struct buffer_head *bh;
  1382. unsigned block_start, block_end;
  1383. unsigned blocksize = head->b_size;
  1384. int err, ret = 0;
  1385. struct buffer_head *next;
  1386. for (bh = head, block_start = 0;
  1387. ret == 0 && (bh != head || !block_start);
  1388. block_start = block_end, bh = next) {
  1389. next = bh->b_this_page;
  1390. block_end = block_start + blocksize;
  1391. if (block_end <= from || block_start >= to) {
  1392. if (partial && !buffer_uptodate(bh))
  1393. *partial = 1;
  1394. continue;
  1395. }
  1396. err = (*fn)(handle, bh);
  1397. if (!ret)
  1398. ret = err;
  1399. }
  1400. return ret;
  1401. }
  1402. /*
  1403. * To preserve ordering, it is essential that the hole instantiation and
  1404. * the data write be encapsulated in a single transaction. We cannot
  1405. * close off a transaction and start a new one between the ext4_get_block()
  1406. * and the commit_write(). So doing the jbd2_journal_start at the start of
  1407. * prepare_write() is the right place.
  1408. *
  1409. * Also, this function can nest inside ext4_writepage() ->
  1410. * block_write_full_page(). In that case, we *know* that ext4_writepage()
  1411. * has generated enough buffer credits to do the whole page. So we won't
  1412. * block on the journal in that case, which is good, because the caller may
  1413. * be PF_MEMALLOC.
  1414. *
  1415. * By accident, ext4 can be reentered when a transaction is open via
  1416. * quota file writes. If we were to commit the transaction while thus
  1417. * reentered, there can be a deadlock - we would be holding a quota
  1418. * lock, and the commit would never complete if another thread had a
  1419. * transaction open and was blocking on the quota lock - a ranking
  1420. * violation.
  1421. *
  1422. * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
  1423. * will _not_ run commit under these circumstances because handle->h_ref
  1424. * is elevated. We'll still have enough credits for the tiny quotafile
  1425. * write.
  1426. */
  1427. static int do_journal_get_write_access(handle_t *handle,
  1428. struct buffer_head *bh)
  1429. {
  1430. int dirty = buffer_dirty(bh);
  1431. int ret;
  1432. if (!buffer_mapped(bh) || buffer_freed(bh))
  1433. return 0;
  1434. /*
  1435. * __block_write_begin() could have dirtied some buffers. Clean
  1436. * the dirty bit as jbd2_journal_get_write_access() could complain
  1437. * otherwise about fs integrity issues. Setting of the dirty bit
  1438. * by __block_write_begin() isn't a real problem here as we clear
  1439. * the bit before releasing a page lock and thus writeback cannot
  1440. * ever write the buffer.
  1441. */
  1442. if (dirty)
  1443. clear_buffer_dirty(bh);
  1444. ret = ext4_journal_get_write_access(handle, bh);
  1445. if (!ret && dirty)
  1446. ret = ext4_handle_dirty_metadata(handle, NULL, bh);
  1447. return ret;
  1448. }
  1449. /*
  1450. * Truncate blocks that were not used by write. We have to truncate the
  1451. * pagecache as well so that corresponding buffers get properly unmapped.
  1452. */
  1453. static void ext4_truncate_failed_write(struct inode *inode)
  1454. {
  1455. truncate_inode_pages(inode->i_mapping, inode->i_size);
  1456. ext4_truncate(inode);
  1457. }
  1458. static int ext4_get_block_write(struct inode *inode, sector_t iblock,
  1459. struct buffer_head *bh_result, int create);
  1460. static int ext4_write_begin(struct file *file, struct address_space *mapping,
  1461. loff_t pos, unsigned len, unsigned flags,
  1462. struct page **pagep, void **fsdata)
  1463. {
  1464. struct inode *inode = mapping->host;
  1465. int ret, needed_blocks;
  1466. handle_t *handle;
  1467. int retries = 0;
  1468. struct page *page;
  1469. pgoff_t index;
  1470. unsigned from, to;
  1471. trace_ext4_write_begin(inode, pos, len, flags);
  1472. /*
  1473. * Reserve one block more for addition to orphan list in case
  1474. * we allocate blocks but write fails for some reason
  1475. */
  1476. needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
  1477. index = pos >> PAGE_CACHE_SHIFT;
  1478. from = pos & (PAGE_CACHE_SIZE - 1);
  1479. to = from + len;
  1480. retry:
  1481. handle = ext4_journal_start(inode, needed_blocks);
  1482. if (IS_ERR(handle)) {
  1483. ret = PTR_ERR(handle);
  1484. goto out;
  1485. }
  1486. /* We cannot recurse into the filesystem as the transaction is already
  1487. * started */
  1488. flags |= AOP_FLAG_NOFS;
  1489. page = grab_cache_page_write_begin(mapping, index, flags);
  1490. if (!page) {
  1491. ext4_journal_stop(handle);
  1492. ret = -ENOMEM;
  1493. goto out;
  1494. }
  1495. *pagep = page;
  1496. if (ext4_should_dioread_nolock(inode))
  1497. ret = __block_write_begin(page, pos, len, ext4_get_block_write);
  1498. else
  1499. ret = __block_write_begin(page, pos, len, ext4_get_block);
  1500. if (!ret && ext4_should_journal_data(inode)) {
  1501. ret = walk_page_buffers(handle, page_buffers(page),
  1502. from, to, NULL, do_journal_get_write_access);
  1503. }
  1504. if (ret) {
  1505. unlock_page(page);
  1506. page_cache_release(page);
  1507. /*
  1508. * __block_write_begin may have instantiated a few blocks
  1509. * outside i_size. Trim these off again. Don't need
  1510. * i_size_read because we hold i_mutex.
  1511. *
  1512. * Add inode to orphan list in case we crash before
  1513. * truncate finishes
  1514. */
  1515. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  1516. ext4_orphan_add(handle, inode);
  1517. ext4_journal_stop(handle);
  1518. if (pos + len > inode->i_size) {
  1519. ext4_truncate_failed_write(inode);
  1520. /*
  1521. * If truncate failed early the inode might
  1522. * still be on the orphan list; we need to
  1523. * make sure the inode is removed from the
  1524. * orphan list in that case.
  1525. */
  1526. if (inode->i_nlink)
  1527. ext4_orphan_del(NULL, inode);
  1528. }
  1529. }
  1530. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  1531. goto retry;
  1532. out:
  1533. return ret;
  1534. }
  1535. /* For write_end() in data=journal mode */
  1536. static int write_end_fn(handle_t *handle, struct buffer_head *bh)
  1537. {
  1538. if (!buffer_mapped(bh) || buffer_freed(bh))
  1539. return 0;
  1540. set_buffer_uptodate(bh);
  1541. return ext4_handle_dirty_metadata(handle, NULL, bh);
  1542. }
  1543. static int ext4_generic_write_end(struct file *file,
  1544. struct address_space *mapping,
  1545. loff_t pos, unsigned len, unsigned copied,
  1546. struct page *page, void *fsdata)
  1547. {
  1548. int i_size_changed = 0;
  1549. struct inode *inode = mapping->host;
  1550. handle_t *handle = ext4_journal_current_handle();
  1551. copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
  1552. /*
  1553. * No need to use i_size_read() here, the i_size
  1554. * cannot change under us because we hold i_mutex.
  1555. *
  1556. * But it's important to update i_size while still holding page lock:
  1557. * page writeout could otherwise come in and zero beyond i_size.
  1558. */
  1559. if (pos + copied > inode->i_size) {
  1560. i_size_write(inode, pos + copied);
  1561. i_size_changed = 1;
  1562. }
  1563. if (pos + copied > EXT4_I(inode)->i_disksize) {
  1564. /* We need to mark inode dirty even if
  1565. * new_i_size is less that inode->i_size
  1566. * bu greater than i_disksize.(hint delalloc)
  1567. */
  1568. ext4_update_i_disksize(inode, (pos + copied));
  1569. i_size_changed = 1;
  1570. }
  1571. unlock_page(page);
  1572. page_cache_release(page);
  1573. /*
  1574. * Don't mark the inode dirty under page lock. First, it unnecessarily
  1575. * makes the holding time of page lock longer. Second, it forces lock
  1576. * ordering of page lock and transaction start for journaling
  1577. * filesystems.
  1578. */
  1579. if (i_size_changed)
  1580. ext4_mark_inode_dirty(handle, inode);
  1581. return copied;
  1582. }
  1583. /*
  1584. * We need to pick up the new inode size which generic_commit_write gave us
  1585. * `file' can be NULL - eg, when called from page_symlink().
  1586. *
  1587. * ext4 never places buffers on inode->i_mapping->private_list. metadata
  1588. * buffers are managed internally.
  1589. */
  1590. static int ext4_ordered_write_end(struct file *file,
  1591. struct address_space *mapping,
  1592. loff_t pos, unsigned len, unsigned copied,
  1593. struct page *page, void *fsdata)
  1594. {
  1595. handle_t *handle = ext4_journal_current_handle();
  1596. struct inode *inode = mapping->host;
  1597. int ret = 0, ret2;
  1598. trace_ext4_ordered_write_end(inode, pos, len, copied);
  1599. ret = ext4_jbd2_file_inode(handle, inode);
  1600. if (ret == 0) {
  1601. ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
  1602. page, fsdata);
  1603. copied = ret2;
  1604. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  1605. /* if we have allocated more blocks and copied
  1606. * less. We will have blocks allocated outside
  1607. * inode->i_size. So truncate them
  1608. */
  1609. ext4_orphan_add(handle, inode);
  1610. if (ret2 < 0)
  1611. ret = ret2;
  1612. }
  1613. ret2 = ext4_journal_stop(handle);
  1614. if (!ret)
  1615. ret = ret2;
  1616. if (pos + len > inode->i_size) {
  1617. ext4_truncate_failed_write(inode);
  1618. /*
  1619. * If truncate failed early the inode might still be
  1620. * on the orphan list; we need to make sure the inode
  1621. * is removed from the orphan list in that case.
  1622. */
  1623. if (inode->i_nlink)
  1624. ext4_orphan_del(NULL, inode);
  1625. }
  1626. return ret ? ret : copied;
  1627. }
  1628. static int ext4_writeback_write_end(struct file *file,
  1629. struct address_space *mapping,
  1630. loff_t pos, unsigned len, unsigned copied,
  1631. struct page *page, void *fsdata)
  1632. {
  1633. handle_t *handle = ext4_journal_current_handle();
  1634. struct inode *inode = mapping->host;
  1635. int ret = 0, ret2;
  1636. trace_ext4_writeback_write_end(inode, pos, len, copied);
  1637. ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
  1638. page, fsdata);
  1639. copied = ret2;
  1640. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  1641. /* if we have allocated more blocks and copied
  1642. * less. We will have blocks allocated outside
  1643. * inode->i_size. So truncate them
  1644. */
  1645. ext4_orphan_add(handle, inode);
  1646. if (ret2 < 0)
  1647. ret = ret2;
  1648. ret2 = ext4_journal_stop(handle);
  1649. if (!ret)
  1650. ret = ret2;
  1651. if (pos + len > inode->i_size) {
  1652. ext4_truncate_failed_write(inode);
  1653. /*
  1654. * If truncate failed early the inode might still be
  1655. * on the orphan list; we need to make sure the inode
  1656. * is removed from the orphan list in that case.
  1657. */
  1658. if (inode->i_nlink)
  1659. ext4_orphan_del(NULL, inode);
  1660. }
  1661. return ret ? ret : copied;
  1662. }
  1663. static int ext4_journalled_write_end(struct file *file,
  1664. struct address_space *mapping,
  1665. loff_t pos, unsigned len, unsigned copied,
  1666. struct page *page, void *fsdata)
  1667. {
  1668. handle_t *handle = ext4_journal_current_handle();
  1669. struct inode *inode = mapping->host;
  1670. int ret = 0, ret2;
  1671. int partial = 0;
  1672. unsigned from, to;
  1673. loff_t new_i_size;
  1674. trace_ext4_journalled_write_end(inode, pos, len, copied);
  1675. from = pos & (PAGE_CACHE_SIZE - 1);
  1676. to = from + len;
  1677. if (copied < len) {
  1678. if (!PageUptodate(page))
  1679. copied = 0;
  1680. page_zero_new_buffers(page, from+copied, to);
  1681. }
  1682. ret = walk_page_buffers(handle, page_buffers(page), from,
  1683. to, &partial, write_end_fn);
  1684. if (!partial)
  1685. SetPageUptodate(page);
  1686. new_i_size = pos + copied;
  1687. if (new_i_size > inode->i_size)
  1688. i_size_write(inode, pos+copied);
  1689. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  1690. if (new_i_size > EXT4_I(inode)->i_disksize) {
  1691. ext4_update_i_disksize(inode, new_i_size);
  1692. ret2 = ext4_mark_inode_dirty(handle, inode);
  1693. if (!ret)
  1694. ret = ret2;
  1695. }
  1696. unlock_page(page);
  1697. page_cache_release(page);
  1698. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  1699. /* if we have allocated more blocks and copied
  1700. * less. We will have blocks allocated outside
  1701. * inode->i_size. So truncate them
  1702. */
  1703. ext4_orphan_add(handle, inode);
  1704. ret2 = ext4_journal_stop(handle);
  1705. if (!ret)
  1706. ret = ret2;
  1707. if (pos + len > inode->i_size) {
  1708. ext4_truncate_failed_write(inode);
  1709. /*
  1710. * If truncate failed early the inode might still be
  1711. * on the orphan list; we need to make sure the inode
  1712. * is removed from the orphan list in that case.
  1713. */
  1714. if (inode->i_nlink)
  1715. ext4_orphan_del(NULL, inode);
  1716. }
  1717. return ret ? ret : copied;
  1718. }
  1719. /*
  1720. * Reserve a single block located at lblock
  1721. */
  1722. static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
  1723. {
  1724. int retries = 0;
  1725. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1726. struct ext4_inode_info *ei = EXT4_I(inode);
  1727. unsigned long md_needed;
  1728. int ret;
  1729. /*
  1730. * recalculate the amount of metadata blocks to reserve
  1731. * in order to allocate nrblocks
  1732. * worse case is one extent per block
  1733. */
  1734. repeat:
  1735. spin_lock(&ei->i_block_reservation_lock);
  1736. md_needed = ext4_calc_metadata_amount(inode, lblock);
  1737. trace_ext4_da_reserve_space(inode, md_needed);
  1738. spin_unlock(&ei->i_block_reservation_lock);
  1739. /*
  1740. * We will charge metadata quota at writeout time; this saves
  1741. * us from metadata over-estimation, though we may go over by
  1742. * a small amount in the end. Here we just reserve for data.
  1743. */
  1744. ret = dquot_reserve_block(inode, 1);
  1745. if (ret)
  1746. return ret;
  1747. /*
  1748. * We do still charge estimated metadata to the sb though;
  1749. * we cannot afford to run out of free blocks.
  1750. */
  1751. if (ext4_claim_free_blocks(sbi, md_needed + 1, 0)) {
  1752. dquot_release_reservation_block(inode, 1);
  1753. if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
  1754. yield();
  1755. goto repeat;
  1756. }
  1757. return -ENOSPC;
  1758. }
  1759. spin_lock(&ei->i_block_reservation_lock);
  1760. ei->i_reserved_data_blocks++;
  1761. ei->i_reserved_meta_blocks += md_needed;
  1762. spin_unlock(&ei->i_block_reservation_lock);
  1763. return 0; /* success */
  1764. }
  1765. static void ext4_da_release_space(struct inode *inode, int to_free)
  1766. {
  1767. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1768. struct ext4_inode_info *ei = EXT4_I(inode);
  1769. if (!to_free)
  1770. return; /* Nothing to release, exit */
  1771. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  1772. trace_ext4_da_release_space(inode, to_free);
  1773. if (unlikely(to_free > ei->i_reserved_data_blocks)) {
  1774. /*
  1775. * if there aren't enough reserved blocks, then the
  1776. * counter is messed up somewhere. Since this
  1777. * function is called from invalidate page, it's
  1778. * harmless to return without any action.
  1779. */
  1780. ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
  1781. "ino %lu, to_free %d with only %d reserved "
  1782. "data blocks\n", inode->i_ino, to_free,
  1783. ei->i_reserved_data_blocks);
  1784. WARN_ON(1);
  1785. to_free = ei->i_reserved_data_blocks;
  1786. }
  1787. ei->i_reserved_data_blocks -= to_free;
  1788. if (ei->i_reserved_data_blocks == 0) {
  1789. /*
  1790. * We can release all of the reserved metadata blocks
  1791. * only when we have written all of the delayed
  1792. * allocation blocks.
  1793. */
  1794. percpu_counter_sub(&sbi->s_dirtyblocks_counter,
  1795. ei->i_reserved_meta_blocks);
  1796. ei->i_reserved_meta_blocks = 0;
  1797. ei->i_da_metadata_calc_len = 0;
  1798. }
  1799. /* update fs dirty data blocks counter */
  1800. percpu_counter_sub(&sbi->s_dirtyblocks_counter, to_free);
  1801. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  1802. dquot_release_reservation_block(inode, to_free);
  1803. }
  1804. static void ext4_da_page_release_reservation(struct page *page,
  1805. unsigned long offset)
  1806. {
  1807. int to_release = 0;
  1808. struct buffer_head *head, *bh;
  1809. unsigned int curr_off = 0;
  1810. head = page_buffers(page);
  1811. bh = head;
  1812. do {
  1813. unsigned int next_off = curr_off + bh->b_size;
  1814. if ((offset <= curr_off) && (buffer_delay(bh))) {
  1815. to_release++;
  1816. clear_buffer_delay(bh);
  1817. }
  1818. curr_off = next_off;
  1819. } while ((bh = bh->b_this_page) != head);
  1820. ext4_da_release_space(page->mapping->host, to_release);
  1821. }
  1822. /*
  1823. * Delayed allocation stuff
  1824. */
  1825. /*
  1826. * mpage_da_submit_io - walks through extent of pages and try to write
  1827. * them with writepage() call back
  1828. *
  1829. * @mpd->inode: inode
  1830. * @mpd->first_page: first page of the extent
  1831. * @mpd->next_page: page after the last page of the extent
  1832. *
  1833. * By the time mpage_da_submit_io() is called we expect all blocks
  1834. * to be allocated. this may be wrong if allocation failed.
  1835. *
  1836. * As pages are already locked by write_cache_pages(), we can't use it
  1837. */
  1838. static int mpage_da_submit_io(struct mpage_da_data *mpd,
  1839. struct ext4_map_blocks *map)
  1840. {
  1841. struct pagevec pvec;
  1842. unsigned long index, end;
  1843. int ret = 0, err, nr_pages, i;
  1844. struct inode *inode = mpd->inode;
  1845. struct address_space *mapping = inode->i_mapping;
  1846. loff_t size = i_size_read(inode);
  1847. unsigned int len, block_start;
  1848. struct buffer_head *bh, *page_bufs = NULL;
  1849. int journal_data = ext4_should_journal_data(inode);
  1850. sector_t pblock = 0, cur_logical = 0;
  1851. struct ext4_io_submit io_submit;
  1852. BUG_ON(mpd->next_page <= mpd->first_page);
  1853. memset(&io_submit, 0, sizeof(io_submit));
  1854. /*
  1855. * We need to start from the first_page to the next_page - 1
  1856. * to make sure we also write the mapped dirty buffer_heads.
  1857. * If we look at mpd->b_blocknr we would only be looking
  1858. * at the currently mapped buffer_heads.
  1859. */
  1860. index = mpd->first_page;
  1861. end = mpd->next_page - 1;
  1862. pagevec_init(&pvec, 0);
  1863. while (index <= end) {
  1864. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1865. if (nr_pages == 0)
  1866. break;
  1867. for (i = 0; i < nr_pages; i++) {
  1868. int commit_write = 0, skip_page = 0;
  1869. struct page *page = pvec.pages[i];
  1870. index = page->index;
  1871. if (index > end)
  1872. break;
  1873. if (index == size >> PAGE_CACHE_SHIFT)
  1874. len = size & ~PAGE_CACHE_MASK;
  1875. else
  1876. len = PAGE_CACHE_SIZE;
  1877. if (map) {
  1878. cur_logical = index << (PAGE_CACHE_SHIFT -
  1879. inode->i_blkbits);
  1880. pblock = map->m_pblk + (cur_logical -
  1881. map->m_lblk);
  1882. }
  1883. index++;
  1884. BUG_ON(!PageLocked(page));
  1885. BUG_ON(PageWriteback(page));
  1886. /*
  1887. * If the page does not have buffers (for
  1888. * whatever reason), try to create them using
  1889. * __block_write_begin. If this fails,
  1890. * skip the page and move on.
  1891. */
  1892. if (!page_has_buffers(page)) {
  1893. if (__block_write_begin(page, 0, len,
  1894. noalloc_get_block_write)) {
  1895. skip_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 skip_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. /* skip page if block allocation undone */
  1921. if (buffer_delay(bh) || buffer_unwritten(bh))
  1922. skip_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 (skip_page)
  1929. goto skip_page;
  1930. if (commit_write)
  1931. /* mark the buffer_heads as dirty & uptodate */
  1932. block_commit_write(page, 0, len);
  1933. clear_page_dirty_for_io(page);
  1934. /*
  1935. * Delalloc doesn't support data journalling,
  1936. * but eventually maybe we'll lift this
  1937. * restriction.
  1938. */
  1939. if (unlikely(journal_data && PageChecked(page)))
  1940. err = __ext4_journalled_writepage(page, len);
  1941. else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
  1942. err = ext4_bio_write_page(&io_submit, page,
  1943. len, mpd->wbc);
  1944. else
  1945. err = block_write_full_page(page,
  1946. noalloc_get_block_write, mpd->wbc);
  1947. if (!err)
  1948. mpd->pages_written++;
  1949. /*
  1950. * In error case, we have to continue because
  1951. * remaining pages are still locked
  1952. */
  1953. if (ret == 0)
  1954. ret = err;
  1955. }
  1956. pagevec_release(&pvec);
  1957. }
  1958. ext4_io_submit(&io_submit);
  1959. return ret;
  1960. }
  1961. static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
  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 = mpd->first_page;
  1969. end = mpd->next_page - 1;
  1970. while (index <= end) {
  1971. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1972. if (nr_pages == 0)
  1973. break;
  1974. for (i = 0; i < nr_pages; i++) {
  1975. struct page *page = pvec.pages[i];
  1976. if (page->index > end)
  1977. break;
  1978. BUG_ON(!PageLocked(page));
  1979. BUG_ON(PageWriteback(page));
  1980. block_invalidatepage(page, 0);
  1981. ClearPageUptodate(page);
  1982. unlock_page(page);
  1983. }
  1984. index = pvec.pages[nr_pages - 1]->index + 1;
  1985. pagevec_release(&pvec);
  1986. }
  1987. return;
  1988. }
  1989. static void ext4_print_free_blocks(struct inode *inode)
  1990. {
  1991. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1992. printk(KERN_CRIT "Total free blocks count %lld\n",
  1993. ext4_count_free_blocks(inode->i_sb));
  1994. printk(KERN_CRIT "Free/Dirty block details\n");
  1995. printk(KERN_CRIT "free_blocks=%lld\n",
  1996. (long long) percpu_counter_sum(&sbi->s_freeblocks_counter));
  1997. printk(KERN_CRIT "dirty_blocks=%lld\n",
  1998. (long long) percpu_counter_sum(&sbi->s_dirtyblocks_counter));
  1999. printk(KERN_CRIT "Block reservation details\n");
  2000. printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
  2001. EXT4_I(inode)->i_reserved_data_blocks);
  2002. printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
  2003. EXT4_I(inode)->i_reserved_meta_blocks);
  2004. return;
  2005. }
  2006. /*
  2007. * mpage_da_map_and_submit - go through given space, map them
  2008. * if necessary, and then submit them for I/O
  2009. *
  2010. * @mpd - bh describing space
  2011. *
  2012. * The function skips space we know is already mapped to disk blocks.
  2013. *
  2014. */
  2015. static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
  2016. {
  2017. int err, blks, get_blocks_flags;
  2018. struct ext4_map_blocks map, *mapp = NULL;
  2019. sector_t next = mpd->b_blocknr;
  2020. unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
  2021. loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
  2022. handle_t *handle = NULL;
  2023. /*
  2024. * If the blocks are mapped already, or we couldn't accumulate
  2025. * any blocks, then proceed immediately to the submission stage.
  2026. */
  2027. if ((mpd->b_size == 0) ||
  2028. ((mpd->b_state & (1 << BH_Mapped)) &&
  2029. !(mpd->b_state & (1 << BH_Delay)) &&
  2030. !(mpd->b_state & (1 << BH_Unwritten))))
  2031. goto submit_io;
  2032. handle = ext4_journal_current_handle();
  2033. BUG_ON(!handle);
  2034. /*
  2035. * Call ext4_map_blocks() to allocate any delayed allocation
  2036. * blocks, or to convert an uninitialized extent to be
  2037. * initialized (in the case where we have written into
  2038. * one or more preallocated blocks).
  2039. *
  2040. * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
  2041. * indicate that we are on the delayed allocation path. This
  2042. * affects functions in many different parts of the allocation
  2043. * call path. This flag exists primarily because we don't
  2044. * want to change *many* call functions, so ext4_map_blocks()
  2045. * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
  2046. * inode's allocation semaphore is taken.
  2047. *
  2048. * If the blocks in questions were delalloc blocks, set
  2049. * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
  2050. * variables are updated after the blocks have been allocated.
  2051. */
  2052. map.m_lblk = next;
  2053. map.m_len = max_blocks;
  2054. get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
  2055. if (ext4_should_dioread_nolock(mpd->inode))
  2056. get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
  2057. if (mpd->b_state & (1 << BH_Delay))
  2058. get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
  2059. blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
  2060. if (blks < 0) {
  2061. struct super_block *sb = mpd->inode->i_sb;
  2062. err = blks;
  2063. /*
  2064. * If get block returns EAGAIN or ENOSPC and there
  2065. * appears to be free blocks we will just let
  2066. * mpage_da_submit_io() unlock all of the pages.
  2067. */
  2068. if (err == -EAGAIN)
  2069. goto submit_io;
  2070. if (err == -ENOSPC &&
  2071. ext4_count_free_blocks(sb)) {
  2072. mpd->retval = err;
  2073. goto submit_io;
  2074. }
  2075. /*
  2076. * get block failure will cause us to loop in
  2077. * writepages, because a_ops->writepage won't be able
  2078. * to make progress. The page will be redirtied by
  2079. * writepage and writepages will again try to write
  2080. * the same.
  2081. */
  2082. if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
  2083. ext4_msg(sb, KERN_CRIT,
  2084. "delayed block allocation failed for inode %lu "
  2085. "at logical offset %llu with max blocks %zd "
  2086. "with error %d", mpd->inode->i_ino,
  2087. (unsigned long long) next,
  2088. mpd->b_size >> mpd->inode->i_blkbits, err);
  2089. ext4_msg(sb, KERN_CRIT,
  2090. "This should not happen!! Data will be lost\n");
  2091. if (err == -ENOSPC)
  2092. ext4_print_free_blocks(mpd->inode);
  2093. }
  2094. /* invalidate all the pages */
  2095. ext4_da_block_invalidatepages(mpd);
  2096. /* Mark this page range as having been completed */
  2097. mpd->io_done = 1;
  2098. return;
  2099. }
  2100. BUG_ON(blks == 0);
  2101. mapp = &map;
  2102. if (map.m_flags & EXT4_MAP_NEW) {
  2103. struct block_device *bdev = mpd->inode->i_sb->s_bdev;
  2104. int i;
  2105. for (i = 0; i < map.m_len; i++)
  2106. unmap_underlying_metadata(bdev, map.m_pblk + i);
  2107. }
  2108. if (ext4_should_order_data(mpd->inode)) {
  2109. err = ext4_jbd2_file_inode(handle, mpd->inode);
  2110. if (err)
  2111. /* This only happens if the journal is aborted */
  2112. return;
  2113. }
  2114. /*
  2115. * Update on-disk size along with block allocation.
  2116. */
  2117. disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
  2118. if (disksize > i_size_read(mpd->inode))
  2119. disksize = i_size_read(mpd->inode);
  2120. if (disksize > EXT4_I(mpd->inode)->i_disksize) {
  2121. ext4_update_i_disksize(mpd->inode, disksize);
  2122. err = ext4_mark_inode_dirty(handle, mpd->inode);
  2123. if (err)
  2124. ext4_error(mpd->inode->i_sb,
  2125. "Failed to mark inode %lu dirty",
  2126. mpd->inode->i_ino);
  2127. }
  2128. submit_io:
  2129. mpage_da_submit_io(mpd, mapp);
  2130. mpd->io_done = 1;
  2131. }
  2132. #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
  2133. (1 << BH_Delay) | (1 << BH_Unwritten))
  2134. /*
  2135. * mpage_add_bh_to_extent - try to add one more block to extent of blocks
  2136. *
  2137. * @mpd->lbh - extent of blocks
  2138. * @logical - logical number of the block in the file
  2139. * @bh - bh of the block (used to access block's state)
  2140. *
  2141. * the function is used to collect contig. blocks in same state
  2142. */
  2143. static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
  2144. sector_t logical, size_t b_size,
  2145. unsigned long b_state)
  2146. {
  2147. sector_t next;
  2148. int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
  2149. /*
  2150. * XXX Don't go larger than mballoc is willing to allocate
  2151. * This is a stopgap solution. We eventually need to fold
  2152. * mpage_da_submit_io() into this function and then call
  2153. * ext4_map_blocks() multiple times in a loop
  2154. */
  2155. if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
  2156. goto flush_it;
  2157. /* check if thereserved journal credits might overflow */
  2158. if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
  2159. if (nrblocks >= EXT4_MAX_TRANS_DATA) {
  2160. /*
  2161. * With non-extent format we are limited by the journal
  2162. * credit available. Total credit needed to insert
  2163. * nrblocks contiguous blocks is dependent on the
  2164. * nrblocks. So limit nrblocks.
  2165. */
  2166. goto flush_it;
  2167. } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
  2168. EXT4_MAX_TRANS_DATA) {
  2169. /*
  2170. * Adding the new buffer_head would make it cross the
  2171. * allowed limit for which we have journal credit
  2172. * reserved. So limit the new bh->b_size
  2173. */
  2174. b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
  2175. mpd->inode->i_blkbits;
  2176. /* we will do mpage_da_submit_io in the next loop */
  2177. }
  2178. }
  2179. /*
  2180. * First block in the extent
  2181. */
  2182. if (mpd->b_size == 0) {
  2183. mpd->b_blocknr = logical;
  2184. mpd->b_size = b_size;
  2185. mpd->b_state = b_state & BH_FLAGS;
  2186. return;
  2187. }
  2188. next = mpd->b_blocknr + nrblocks;
  2189. /*
  2190. * Can we merge the block to our big extent?
  2191. */
  2192. if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
  2193. mpd->b_size += b_size;
  2194. return;
  2195. }
  2196. flush_it:
  2197. /*
  2198. * We couldn't merge the block to our extent, so we
  2199. * need to flush current extent and start new one
  2200. */
  2201. mpage_da_map_and_submit(mpd);
  2202. return;
  2203. }
  2204. static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
  2205. {
  2206. return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
  2207. }
  2208. /*
  2209. * This is a special get_blocks_t callback which is used by
  2210. * ext4_da_write_begin(). It will either return mapped block or
  2211. * reserve space for a single block.
  2212. *
  2213. * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
  2214. * We also have b_blocknr = -1 and b_bdev initialized properly
  2215. *
  2216. * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
  2217. * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
  2218. * initialized properly.
  2219. */
  2220. static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
  2221. struct buffer_head *bh, int create)
  2222. {
  2223. struct ext4_map_blocks map;
  2224. int ret = 0;
  2225. sector_t invalid_block = ~((sector_t) 0xffff);
  2226. if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
  2227. invalid_block = ~0;
  2228. BUG_ON(create == 0);
  2229. BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
  2230. map.m_lblk = iblock;
  2231. map.m_len = 1;
  2232. /*
  2233. * first, we need to know whether the block is allocated already
  2234. * preallocated blocks are unmapped but should treated
  2235. * the same as allocated blocks.
  2236. */
  2237. ret = ext4_map_blocks(NULL, inode, &map, 0);
  2238. if (ret < 0)
  2239. return ret;
  2240. if (ret == 0) {
  2241. if (buffer_delay(bh))
  2242. return 0; /* Not sure this could or should happen */
  2243. /*
  2244. * XXX: __block_write_begin() unmaps passed block, is it OK?
  2245. */
  2246. ret = ext4_da_reserve_space(inode, iblock);
  2247. if (ret)
  2248. /* not enough space to reserve */
  2249. return ret;
  2250. map_bh(bh, inode->i_sb, invalid_block);
  2251. set_buffer_new(bh);
  2252. set_buffer_delay(bh);
  2253. return 0;
  2254. }
  2255. map_bh(bh, inode->i_sb, map.m_pblk);
  2256. bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
  2257. if (buffer_unwritten(bh)) {
  2258. /* A delayed write to unwritten bh should be marked
  2259. * new and mapped. Mapped ensures that we don't do
  2260. * get_block multiple times when we write to the same
  2261. * offset and new ensures that we do proper zero out
  2262. * for partial write.
  2263. */
  2264. set_buffer_new(bh);
  2265. set_buffer_mapped(bh);
  2266. }
  2267. return 0;
  2268. }
  2269. /*
  2270. * This function is used as a standard get_block_t calback function
  2271. * when there is no desire to allocate any blocks. It is used as a
  2272. * callback function for block_write_begin() and block_write_full_page().
  2273. * These functions should only try to map a single block at a time.
  2274. *
  2275. * Since this function doesn't do block allocations even if the caller
  2276. * requests it by passing in create=1, it is critically important that
  2277. * any caller checks to make sure that any buffer heads are returned
  2278. * by this function are either all already mapped or marked for
  2279. * delayed allocation before calling block_write_full_page(). Otherwise,
  2280. * b_blocknr could be left unitialized, and the page write functions will
  2281. * be taken by surprise.
  2282. */
  2283. static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
  2284. struct buffer_head *bh_result, int create)
  2285. {
  2286. BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
  2287. return _ext4_get_block(inode, iblock, bh_result, 0);
  2288. }
  2289. static int bget_one(handle_t *handle, struct buffer_head *bh)
  2290. {
  2291. get_bh(bh);
  2292. return 0;
  2293. }
  2294. static int bput_one(handle_t *handle, struct buffer_head *bh)
  2295. {
  2296. put_bh(bh);
  2297. return 0;
  2298. }
  2299. static int __ext4_journalled_writepage(struct page *page,
  2300. unsigned int len)
  2301. {
  2302. struct address_space *mapping = page->mapping;
  2303. struct inode *inode = mapping->host;
  2304. struct buffer_head *page_bufs;
  2305. handle_t *handle = NULL;
  2306. int ret = 0;
  2307. int err;
  2308. ClearPageChecked(page);
  2309. page_bufs = page_buffers(page);
  2310. BUG_ON(!page_bufs);
  2311. walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
  2312. /* As soon as we unlock the page, it can go away, but we have
  2313. * references to buffers so we are safe */
  2314. unlock_page(page);
  2315. handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
  2316. if (IS_ERR(handle)) {
  2317. ret = PTR_ERR(handle);
  2318. goto out;
  2319. }
  2320. ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
  2321. do_journal_get_write_access);
  2322. err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
  2323. write_end_fn);
  2324. if (ret == 0)
  2325. ret = err;
  2326. err = ext4_journal_stop(handle);
  2327. if (!ret)
  2328. ret = err;
  2329. walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
  2330. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  2331. out:
  2332. return ret;
  2333. }
  2334. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
  2335. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
  2336. /*
  2337. * Note that we don't need to start a transaction unless we're journaling data
  2338. * because we should have holes filled from ext4_page_mkwrite(). We even don't
  2339. * need to file the inode to the transaction's list in ordered mode because if
  2340. * we are writing back data added by write(), the inode is already there and if
  2341. * we are writing back data modified via mmap(), no one guarantees in which
  2342. * transaction the data will hit the disk. In case we are journaling data, we
  2343. * cannot start transaction directly because transaction start ranks above page
  2344. * lock so we have to do some magic.
  2345. *
  2346. * This function can get called via...
  2347. * - ext4_da_writepages after taking page lock (have journal handle)
  2348. * - journal_submit_inode_data_buffers (no journal handle)
  2349. * - shrink_page_list via pdflush (no journal handle)
  2350. * - grab_page_cache when doing write_begin (have journal handle)
  2351. *
  2352. * We don't do any block allocation in this function. If we have page with
  2353. * multiple blocks we need to write those buffer_heads that are mapped. This
  2354. * is important for mmaped based write. So if we do with blocksize 1K
  2355. * truncate(f, 1024);
  2356. * a = mmap(f, 0, 4096);
  2357. * a[0] = 'a';
  2358. * truncate(f, 4096);
  2359. * we have in the page first buffer_head mapped via page_mkwrite call back
  2360. * but other bufer_heads would be unmapped but dirty(dirty done via the
  2361. * do_wp_page). So writepage should write the first block. If we modify
  2362. * the mmap area beyond 1024 we will again get a page_fault and the
  2363. * page_mkwrite callback will do the block allocation and mark the
  2364. * buffer_heads mapped.
  2365. *
  2366. * We redirty the page if we have any buffer_heads that is either delay or
  2367. * unwritten in the page.
  2368. *
  2369. * We can get recursively called as show below.
  2370. *
  2371. * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
  2372. * ext4_writepage()
  2373. *
  2374. * But since we don't do any block allocation we should not deadlock.
  2375. * Page also have the dirty flag cleared so we don't get recurive page_lock.
  2376. */
  2377. static int ext4_writepage(struct page *page,
  2378. struct writeback_control *wbc)
  2379. {
  2380. int ret = 0, commit_write = 0;
  2381. loff_t size;
  2382. unsigned int len;
  2383. struct buffer_head *page_bufs = NULL;
  2384. struct inode *inode = page->mapping->host;
  2385. trace_ext4_writepage(page);
  2386. size = i_size_read(inode);
  2387. if (page->index == size >> PAGE_CACHE_SHIFT)
  2388. len = size & ~PAGE_CACHE_MASK;
  2389. else
  2390. len = PAGE_CACHE_SIZE;
  2391. /*
  2392. * If the page does not have buffers (for whatever reason),
  2393. * try to create them using __block_write_begin. If this
  2394. * fails, redirty the page and move on.
  2395. */
  2396. if (!page_has_buffers(page)) {
  2397. if (__block_write_begin(page, 0, len,
  2398. noalloc_get_block_write)) {
  2399. redirty_page:
  2400. redirty_page_for_writepage(wbc, page);
  2401. unlock_page(page);
  2402. return 0;
  2403. }
  2404. commit_write = 1;
  2405. }
  2406. page_bufs = page_buffers(page);
  2407. if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  2408. ext4_bh_delay_or_unwritten)) {
  2409. /*
  2410. * We don't want to do block allocation, so redirty
  2411. * the page and return. We may reach here when we do
  2412. * a journal commit via journal_submit_inode_data_buffers.
  2413. * We can also reach here via shrink_page_list
  2414. */
  2415. goto redirty_page;
  2416. }
  2417. if (commit_write)
  2418. /* now mark the buffer_heads as dirty and uptodate */
  2419. block_commit_write(page, 0, len);
  2420. if (PageChecked(page) && ext4_should_journal_data(inode))
  2421. /*
  2422. * It's mmapped pagecache. Add buffers and journal it. There
  2423. * doesn't seem much point in redirtying the page here.
  2424. */
  2425. return __ext4_journalled_writepage(page, len);
  2426. if (buffer_uninit(page_bufs)) {
  2427. ext4_set_bh_endio(page_bufs, inode);
  2428. ret = block_write_full_page_endio(page, noalloc_get_block_write,
  2429. wbc, ext4_end_io_buffer_write);
  2430. } else
  2431. ret = block_write_full_page(page, noalloc_get_block_write,
  2432. wbc);
  2433. return ret;
  2434. }
  2435. /*
  2436. * This is called via ext4_da_writepages() to
  2437. * calculate the total number of credits to reserve to fit
  2438. * a single extent allocation into a single transaction,
  2439. * ext4_da_writpeages() will loop calling this before
  2440. * the block allocation.
  2441. */
  2442. static int ext4_da_writepages_trans_blocks(struct inode *inode)
  2443. {
  2444. int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  2445. /*
  2446. * With non-extent format the journal credit needed to
  2447. * insert nrblocks contiguous block is dependent on
  2448. * number of contiguous block. So we will limit
  2449. * number of contiguous block to a sane value
  2450. */
  2451. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
  2452. (max_blocks > EXT4_MAX_TRANS_DATA))
  2453. max_blocks = EXT4_MAX_TRANS_DATA;
  2454. return ext4_chunk_trans_blocks(inode, max_blocks);
  2455. }
  2456. /*
  2457. * write_cache_pages_da - walk the list of dirty pages of the given
  2458. * address space and accumulate pages that need writing, and call
  2459. * mpage_da_map_and_submit to map a single contiguous memory region
  2460. * and then write them.
  2461. */
  2462. static int write_cache_pages_da(struct address_space *mapping,
  2463. struct writeback_control *wbc,
  2464. struct mpage_da_data *mpd,
  2465. pgoff_t *done_index)
  2466. {
  2467. struct buffer_head *bh, *head;
  2468. struct inode *inode = mapping->host;
  2469. struct pagevec pvec;
  2470. unsigned int nr_pages;
  2471. sector_t logical;
  2472. pgoff_t index, end;
  2473. long nr_to_write = wbc->nr_to_write;
  2474. int i, tag, ret = 0;
  2475. memset(mpd, 0, sizeof(struct mpage_da_data));
  2476. mpd->wbc = wbc;
  2477. mpd->inode = inode;
  2478. pagevec_init(&pvec, 0);
  2479. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  2480. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  2481. if (wbc->sync_mode == WB_SYNC_ALL)
  2482. tag = PAGECACHE_TAG_TOWRITE;
  2483. else
  2484. tag = PAGECACHE_TAG_DIRTY;
  2485. *done_index = index;
  2486. while (index <= end) {
  2487. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
  2488. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
  2489. if (nr_pages == 0)
  2490. return 0;
  2491. for (i = 0; i < nr_pages; i++) {
  2492. struct page *page = pvec.pages[i];
  2493. /*
  2494. * At this point, the page may be truncated or
  2495. * invalidated (changing page->mapping to NULL), or
  2496. * even swizzled back from swapper_space to tmpfs file
  2497. * mapping. However, page->index will not change
  2498. * because we have a reference on the page.
  2499. */
  2500. if (page->index > end)
  2501. goto out;
  2502. *done_index = page->index + 1;
  2503. /*
  2504. * If we can't merge this page, and we have
  2505. * accumulated an contiguous region, write it
  2506. */
  2507. if ((mpd->next_page != page->index) &&
  2508. (mpd->next_page != mpd->first_page)) {
  2509. mpage_da_map_and_submit(mpd);
  2510. goto ret_extent_tail;
  2511. }
  2512. lock_page(page);
  2513. /*
  2514. * If the page is no longer dirty, or its
  2515. * mapping no longer corresponds to inode we
  2516. * are writing (which means it has been
  2517. * truncated or invalidated), or the page is
  2518. * already under writeback and we are not
  2519. * doing a data integrity writeback, skip the page
  2520. */
  2521. if (!PageDirty(page) ||
  2522. (PageWriteback(page) &&
  2523. (wbc->sync_mode == WB_SYNC_NONE)) ||
  2524. unlikely(page->mapping != mapping)) {
  2525. unlock_page(page);
  2526. continue;
  2527. }
  2528. wait_on_page_writeback(page);
  2529. BUG_ON(PageWriteback(page));
  2530. if (mpd->next_page != page->index)
  2531. mpd->first_page = page->index;
  2532. mpd->next_page = page->index + 1;
  2533. logical = (sector_t) page->index <<
  2534. (PAGE_CACHE_SHIFT - inode->i_blkbits);
  2535. if (!page_has_buffers(page)) {
  2536. mpage_add_bh_to_extent(mpd, logical,
  2537. PAGE_CACHE_SIZE,
  2538. (1 << BH_Dirty) | (1 << BH_Uptodate));
  2539. if (mpd->io_done)
  2540. goto ret_extent_tail;
  2541. } else {
  2542. /*
  2543. * Page with regular buffer heads,
  2544. * just add all dirty ones
  2545. */
  2546. head = page_buffers(page);
  2547. bh = head;
  2548. do {
  2549. BUG_ON(buffer_locked(bh));
  2550. /*
  2551. * We need to try to allocate
  2552. * unmapped blocks in the same page.
  2553. * Otherwise we won't make progress
  2554. * with the page in ext4_writepage
  2555. */
  2556. if (ext4_bh_delay_or_unwritten(NULL, bh)) {
  2557. mpage_add_bh_to_extent(mpd, logical,
  2558. bh->b_size,
  2559. bh->b_state);
  2560. if (mpd->io_done)
  2561. goto ret_extent_tail;
  2562. } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
  2563. /*
  2564. * mapped dirty buffer. We need
  2565. * to update the b_state
  2566. * because we look at b_state
  2567. * in mpage_da_map_blocks. We
  2568. * don't update b_size because
  2569. * if we find an unmapped
  2570. * buffer_head later we need to
  2571. * use the b_state flag of that
  2572. * buffer_head.
  2573. */
  2574. if (mpd->b_size == 0)
  2575. mpd->b_state = bh->b_state & BH_FLAGS;
  2576. }
  2577. logical++;
  2578. } while ((bh = bh->b_this_page) != head);
  2579. }
  2580. if (nr_to_write > 0) {
  2581. nr_to_write--;
  2582. if (nr_to_write == 0 &&
  2583. wbc->sync_mode == WB_SYNC_NONE)
  2584. /*
  2585. * We stop writing back only if we are
  2586. * not doing integrity sync. In case of
  2587. * integrity sync we have to keep going
  2588. * because someone may be concurrently
  2589. * dirtying pages, and we might have
  2590. * synced a lot of newly appeared dirty
  2591. * pages, but have not synced all of the
  2592. * old dirty pages.
  2593. */
  2594. goto out;
  2595. }
  2596. }
  2597. pagevec_release(&pvec);
  2598. cond_resched();
  2599. }
  2600. return 0;
  2601. ret_extent_tail:
  2602. ret = MPAGE_DA_EXTENT_TAIL;
  2603. out:
  2604. pagevec_release(&pvec);
  2605. cond_resched();
  2606. return ret;
  2607. }
  2608. static int ext4_da_writepages(struct address_space *mapping,
  2609. struct writeback_control *wbc)
  2610. {
  2611. pgoff_t index;
  2612. int range_whole = 0;
  2613. handle_t *handle = NULL;
  2614. struct mpage_da_data mpd;
  2615. struct inode *inode = mapping->host;
  2616. int pages_written = 0;
  2617. unsigned int max_pages;
  2618. int range_cyclic, cycled = 1, io_done = 0;
  2619. int needed_blocks, ret = 0;
  2620. long desired_nr_to_write, nr_to_writebump = 0;
  2621. loff_t range_start = wbc->range_start;
  2622. struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
  2623. pgoff_t done_index = 0;
  2624. pgoff_t end;
  2625. trace_ext4_da_writepages(inode, wbc);
  2626. /*
  2627. * No pages to write? This is mainly a kludge to avoid starting
  2628. * a transaction for special inodes like journal inode on last iput()
  2629. * because that could violate lock ordering on umount
  2630. */
  2631. if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
  2632. return 0;
  2633. /*
  2634. * If the filesystem has aborted, it is read-only, so return
  2635. * right away instead of dumping stack traces later on that
  2636. * will obscure the real source of the problem. We test
  2637. * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
  2638. * the latter could be true if the filesystem is mounted
  2639. * read-only, and in that case, ext4_da_writepages should
  2640. * *never* be called, so if that ever happens, we would want
  2641. * the stack trace.
  2642. */
  2643. if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
  2644. return -EROFS;
  2645. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  2646. range_whole = 1;
  2647. range_cyclic = wbc->range_cyclic;
  2648. if (wbc->range_cyclic) {
  2649. index = mapping->writeback_index;
  2650. if (index)
  2651. cycled = 0;
  2652. wbc->range_start = index << PAGE_CACHE_SHIFT;
  2653. wbc->range_end = LLONG_MAX;
  2654. wbc->range_cyclic = 0;
  2655. end = -1;
  2656. } else {
  2657. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  2658. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  2659. }
  2660. /*
  2661. * This works around two forms of stupidity. The first is in
  2662. * the writeback code, which caps the maximum number of pages
  2663. * written to be 1024 pages. This is wrong on multiple
  2664. * levels; different architectues have a different page size,
  2665. * which changes the maximum amount of data which gets
  2666. * written. Secondly, 4 megabytes is way too small. XFS
  2667. * forces this value to be 16 megabytes by multiplying
  2668. * nr_to_write parameter by four, and then relies on its
  2669. * allocator to allocate larger extents to make them
  2670. * contiguous. Unfortunately this brings us to the second
  2671. * stupidity, which is that ext4's mballoc code only allocates
  2672. * at most 2048 blocks. So we force contiguous writes up to
  2673. * the number of dirty blocks in the inode, or
  2674. * sbi->max_writeback_mb_bump whichever is smaller.
  2675. */
  2676. max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
  2677. if (!range_cyclic && range_whole) {
  2678. if (wbc->nr_to_write == LONG_MAX)
  2679. desired_nr_to_write = wbc->nr_to_write;
  2680. else
  2681. desired_nr_to_write = wbc->nr_to_write * 8;
  2682. } else
  2683. desired_nr_to_write = ext4_num_dirty_pages(inode, index,
  2684. max_pages);
  2685. if (desired_nr_to_write > max_pages)
  2686. desired_nr_to_write = max_pages;
  2687. if (wbc->nr_to_write < desired_nr_to_write) {
  2688. nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
  2689. wbc->nr_to_write = desired_nr_to_write;
  2690. }
  2691. retry:
  2692. if (wbc->sync_mode == WB_SYNC_ALL)
  2693. tag_pages_for_writeback(mapping, index, end);
  2694. while (!ret && wbc->nr_to_write > 0) {
  2695. /*
  2696. * we insert one extent at a time. So we need
  2697. * credit needed for single extent allocation.
  2698. * journalled mode is currently not supported
  2699. * by delalloc
  2700. */
  2701. BUG_ON(ext4_should_journal_data(inode));
  2702. needed_blocks = ext4_da_writepages_trans_blocks(inode);
  2703. /* start a new transaction*/
  2704. handle = ext4_journal_start(inode, needed_blocks);
  2705. if (IS_ERR(handle)) {
  2706. ret = PTR_ERR(handle);
  2707. ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
  2708. "%ld pages, ino %lu; err %d", __func__,
  2709. wbc->nr_to_write, inode->i_ino, ret);
  2710. goto out_writepages;
  2711. }
  2712. /*
  2713. * Now call write_cache_pages_da() to find the next
  2714. * contiguous region of logical blocks that need
  2715. * blocks to be allocated by ext4 and submit them.
  2716. */
  2717. ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
  2718. /*
  2719. * If we have a contiguous extent of pages and we
  2720. * haven't done the I/O yet, map the blocks and submit
  2721. * them for I/O.
  2722. */
  2723. if (!mpd.io_done && mpd.next_page != mpd.first_page) {
  2724. mpage_da_map_and_submit(&mpd);
  2725. ret = MPAGE_DA_EXTENT_TAIL;
  2726. }
  2727. trace_ext4_da_write_pages(inode, &mpd);
  2728. wbc->nr_to_write -= mpd.pages_written;
  2729. ext4_journal_stop(handle);
  2730. if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
  2731. /* commit the transaction which would
  2732. * free blocks released in the transaction
  2733. * and try again
  2734. */
  2735. jbd2_journal_force_commit_nested(sbi->s_journal);
  2736. ret = 0;
  2737. } else if (ret == MPAGE_DA_EXTENT_TAIL) {
  2738. /*
  2739. * got one extent now try with
  2740. * rest of the pages
  2741. */
  2742. pages_written += mpd.pages_written;
  2743. ret = 0;
  2744. io_done = 1;
  2745. } else if (wbc->nr_to_write)
  2746. /*
  2747. * There is no more writeout needed
  2748. * or we requested for a noblocking writeout
  2749. * and we found the device congested
  2750. */
  2751. break;
  2752. }
  2753. if (!io_done && !cycled) {
  2754. cycled = 1;
  2755. index = 0;
  2756. wbc->range_start = index << PAGE_CACHE_SHIFT;
  2757. wbc->range_end = mapping->writeback_index - 1;
  2758. goto retry;
  2759. }
  2760. /* Update index */
  2761. wbc->range_cyclic = range_cyclic;
  2762. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  2763. /*
  2764. * set the writeback_index so that range_cyclic
  2765. * mode will write it back later
  2766. */
  2767. mapping->writeback_index = done_index;
  2768. out_writepages:
  2769. wbc->nr_to_write -= nr_to_writebump;
  2770. wbc->range_start = range_start;
  2771. trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
  2772. return ret;
  2773. }
  2774. #define FALL_BACK_TO_NONDELALLOC 1
  2775. static int ext4_nonda_switch(struct super_block *sb)
  2776. {
  2777. s64 free_blocks, dirty_blocks;
  2778. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2779. /*
  2780. * switch to non delalloc mode if we are running low
  2781. * on free block. The free block accounting via percpu
  2782. * counters can get slightly wrong with percpu_counter_batch getting
  2783. * accumulated on each CPU without updating global counters
  2784. * Delalloc need an accurate free block accounting. So switch
  2785. * to non delalloc when we are near to error range.
  2786. */
  2787. free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
  2788. dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
  2789. if (2 * free_blocks < 3 * dirty_blocks ||
  2790. free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
  2791. /*
  2792. * free block count is less than 150% of dirty blocks
  2793. * or free blocks is less than watermark
  2794. */
  2795. return 1;
  2796. }
  2797. /*
  2798. * Even if we don't switch but are nearing capacity,
  2799. * start pushing delalloc when 1/2 of free blocks are dirty.
  2800. */
  2801. if (free_blocks < 2 * dirty_blocks)
  2802. writeback_inodes_sb_if_idle(sb);
  2803. return 0;
  2804. }
  2805. static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
  2806. loff_t pos, unsigned len, unsigned flags,
  2807. struct page **pagep, void **fsdata)
  2808. {
  2809. int ret, retries = 0;
  2810. struct page *page;
  2811. pgoff_t index;
  2812. struct inode *inode = mapping->host;
  2813. handle_t *handle;
  2814. index = pos >> PAGE_CACHE_SHIFT;
  2815. if (ext4_nonda_switch(inode->i_sb)) {
  2816. *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
  2817. return ext4_write_begin(file, mapping, pos,
  2818. len, flags, pagep, fsdata);
  2819. }
  2820. *fsdata = (void *)0;
  2821. trace_ext4_da_write_begin(inode, pos, len, flags);
  2822. retry:
  2823. /*
  2824. * With delayed allocation, we don't log the i_disksize update
  2825. * if there is delayed block allocation. But we still need
  2826. * to journalling the i_disksize update if writes to the end
  2827. * of file which has an already mapped buffer.
  2828. */
  2829. handle = ext4_journal_start(inode, 1);
  2830. if (IS_ERR(handle)) {
  2831. ret = PTR_ERR(handle);
  2832. goto out;
  2833. }
  2834. /* We cannot recurse into the filesystem as the transaction is already
  2835. * started */
  2836. flags |= AOP_FLAG_NOFS;
  2837. page = grab_cache_page_write_begin(mapping, index, flags);
  2838. if (!page) {
  2839. ext4_journal_stop(handle);
  2840. ret = -ENOMEM;
  2841. goto out;
  2842. }
  2843. *pagep = page;
  2844. ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
  2845. if (ret < 0) {
  2846. unlock_page(page);
  2847. ext4_journal_stop(handle);
  2848. page_cache_release(page);
  2849. /*
  2850. * block_write_begin may have instantiated a few blocks
  2851. * outside i_size. Trim these off again. Don't need
  2852. * i_size_read because we hold i_mutex.
  2853. */
  2854. if (pos + len > inode->i_size)
  2855. ext4_truncate_failed_write(inode);
  2856. }
  2857. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  2858. goto retry;
  2859. out:
  2860. return ret;
  2861. }
  2862. /*
  2863. * Check if we should update i_disksize
  2864. * when write to the end of file but not require block allocation
  2865. */
  2866. static int ext4_da_should_update_i_disksize(struct page *page,
  2867. unsigned long offset)
  2868. {
  2869. struct buffer_head *bh;
  2870. struct inode *inode = page->mapping->host;
  2871. unsigned int idx;
  2872. int i;
  2873. bh = page_buffers(page);
  2874. idx = offset >> inode->i_blkbits;
  2875. for (i = 0; i < idx; i++)
  2876. bh = bh->b_this_page;
  2877. if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
  2878. return 0;
  2879. return 1;
  2880. }
  2881. static int ext4_da_write_end(struct file *file,
  2882. struct address_space *mapping,
  2883. loff_t pos, unsigned len, unsigned copied,
  2884. struct page *page, void *fsdata)
  2885. {
  2886. struct inode *inode = mapping->host;
  2887. int ret = 0, ret2;
  2888. handle_t *handle = ext4_journal_current_handle();
  2889. loff_t new_i_size;
  2890. unsigned long start, end;
  2891. int write_mode = (int)(unsigned long)fsdata;
  2892. if (write_mode == FALL_BACK_TO_NONDELALLOC) {
  2893. if (ext4_should_order_data(inode)) {
  2894. return ext4_ordered_write_end(file, mapping, pos,
  2895. len, copied, page, fsdata);
  2896. } else if (ext4_should_writeback_data(inode)) {
  2897. return ext4_writeback_write_end(file, mapping, pos,
  2898. len, copied, page, fsdata);
  2899. } else {
  2900. BUG();
  2901. }
  2902. }
  2903. trace_ext4_da_write_end(inode, pos, len, copied);
  2904. start = pos & (PAGE_CACHE_SIZE - 1);
  2905. end = start + copied - 1;
  2906. /*
  2907. * generic_write_end() will run mark_inode_dirty() if i_size
  2908. * changes. So let's piggyback the i_disksize mark_inode_dirty
  2909. * into that.
  2910. */
  2911. new_i_size = pos + copied;
  2912. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2913. if (ext4_da_should_update_i_disksize(page, end)) {
  2914. down_write(&EXT4_I(inode)->i_data_sem);
  2915. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2916. /*
  2917. * Updating i_disksize when extending file
  2918. * without needing block allocation
  2919. */
  2920. if (ext4_should_order_data(inode))
  2921. ret = ext4_jbd2_file_inode(handle,
  2922. inode);
  2923. EXT4_I(inode)->i_disksize = new_i_size;
  2924. }
  2925. up_write(&EXT4_I(inode)->i_data_sem);
  2926. /* We need to mark inode dirty even if
  2927. * new_i_size is less that inode->i_size
  2928. * bu greater than i_disksize.(hint delalloc)
  2929. */
  2930. ext4_mark_inode_dirty(handle, inode);
  2931. }
  2932. }
  2933. ret2 = generic_write_end(file, mapping, pos, len, copied,
  2934. page, fsdata);
  2935. copied = ret2;
  2936. if (ret2 < 0)
  2937. ret = ret2;
  2938. ret2 = ext4_journal_stop(handle);
  2939. if (!ret)
  2940. ret = ret2;
  2941. return ret ? ret : copied;
  2942. }
  2943. static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
  2944. {
  2945. /*
  2946. * Drop reserved blocks
  2947. */
  2948. BUG_ON(!PageLocked(page));
  2949. if (!page_has_buffers(page))
  2950. goto out;
  2951. ext4_da_page_release_reservation(page, offset);
  2952. out:
  2953. ext4_invalidatepage(page, offset);
  2954. return;
  2955. }
  2956. /*
  2957. * Force all delayed allocation blocks to be allocated for a given inode.
  2958. */
  2959. int ext4_alloc_da_blocks(struct inode *inode)
  2960. {
  2961. trace_ext4_alloc_da_blocks(inode);
  2962. if (!EXT4_I(inode)->i_reserved_data_blocks &&
  2963. !EXT4_I(inode)->i_reserved_meta_blocks)
  2964. return 0;
  2965. /*
  2966. * We do something simple for now. The filemap_flush() will
  2967. * also start triggering a write of the data blocks, which is
  2968. * not strictly speaking necessary (and for users of
  2969. * laptop_mode, not even desirable). However, to do otherwise
  2970. * would require replicating code paths in:
  2971. *
  2972. * ext4_da_writepages() ->
  2973. * write_cache_pages() ---> (via passed in callback function)
  2974. * __mpage_da_writepage() -->
  2975. * mpage_add_bh_to_extent()
  2976. * mpage_da_map_blocks()
  2977. *
  2978. * The problem is that write_cache_pages(), located in
  2979. * mm/page-writeback.c, marks pages clean in preparation for
  2980. * doing I/O, which is not desirable if we're not planning on
  2981. * doing I/O at all.
  2982. *
  2983. * We could call write_cache_pages(), and then redirty all of
  2984. * the pages by calling redirty_page_for_writepage() but that
  2985. * would be ugly in the extreme. So instead we would need to
  2986. * replicate parts of the code in the above functions,
  2987. * simplifying them because we wouldn't actually intend to
  2988. * write out the pages, but rather only collect contiguous
  2989. * logical block extents, call the multi-block allocator, and
  2990. * then update the buffer heads with the block allocations.
  2991. *
  2992. * For now, though, we'll cheat by calling filemap_flush(),
  2993. * which will map the blocks, and start the I/O, but not
  2994. * actually wait for the I/O to complete.
  2995. */
  2996. return filemap_flush(inode->i_mapping);
  2997. }
  2998. /*
  2999. * bmap() is special. It gets used by applications such as lilo and by
  3000. * the swapper to find the on-disk block of a specific piece of data.
  3001. *
  3002. * Naturally, this is dangerous if the block concerned is still in the
  3003. * journal. If somebody makes a swapfile on an ext4 data-journaling
  3004. * filesystem and enables swap, then they may get a nasty shock when the
  3005. * data getting swapped to that swapfile suddenly gets overwritten by
  3006. * the original zero's written out previously to the journal and
  3007. * awaiting writeback in the kernel's buffer cache.
  3008. *
  3009. * So, if we see any bmap calls here on a modified, data-journaled file,
  3010. * take extra steps to flush any blocks which might be in the cache.
  3011. */
  3012. static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
  3013. {
  3014. struct inode *inode = mapping->host;
  3015. journal_t *journal;
  3016. int err;
  3017. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
  3018. test_opt(inode->i_sb, DELALLOC)) {
  3019. /*
  3020. * With delalloc we want to sync the file
  3021. * so that we can make sure we allocate
  3022. * blocks for file
  3023. */
  3024. filemap_write_and_wait(mapping);
  3025. }
  3026. if (EXT4_JOURNAL(inode) &&
  3027. ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
  3028. /*
  3029. * This is a REALLY heavyweight approach, but the use of
  3030. * bmap on dirty files is expected to be extremely rare:
  3031. * only if we run lilo or swapon on a freshly made file
  3032. * do we expect this to happen.
  3033. *
  3034. * (bmap requires CAP_SYS_RAWIO so this does not
  3035. * represent an unprivileged user DOS attack --- we'd be
  3036. * in trouble if mortal users could trigger this path at
  3037. * will.)
  3038. *
  3039. * NB. EXT4_STATE_JDATA is not set on files other than
  3040. * regular files. If somebody wants to bmap a directory
  3041. * or symlink and gets confused because the buffer
  3042. * hasn't yet been flushed to disk, they deserve
  3043. * everything they get.
  3044. */
  3045. ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
  3046. journal = EXT4_JOURNAL(inode);
  3047. jbd2_journal_lock_updates(journal);
  3048. err = jbd2_journal_flush(journal);
  3049. jbd2_journal_unlock_updates(journal);
  3050. if (err)
  3051. return 0;
  3052. }
  3053. return generic_block_bmap(mapping, block, ext4_get_block);
  3054. }
  3055. static int ext4_readpage(struct file *file, struct page *page)
  3056. {
  3057. trace_ext4_readpage(page);
  3058. return mpage_readpage(page, ext4_get_block);
  3059. }
  3060. static int
  3061. ext4_readpages(struct file *file, struct address_space *mapping,
  3062. struct list_head *pages, unsigned nr_pages)
  3063. {
  3064. return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
  3065. }
  3066. static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
  3067. {
  3068. struct buffer_head *head, *bh;
  3069. unsigned int curr_off = 0;
  3070. if (!page_has_buffers(page))
  3071. return;
  3072. head = bh = page_buffers(page);
  3073. do {
  3074. if (offset <= curr_off && test_clear_buffer_uninit(bh)
  3075. && bh->b_private) {
  3076. ext4_free_io_end(bh->b_private);
  3077. bh->b_private = NULL;
  3078. bh->b_end_io = NULL;
  3079. }
  3080. curr_off = curr_off + bh->b_size;
  3081. bh = bh->b_this_page;
  3082. } while (bh != head);
  3083. }
  3084. static void ext4_invalidatepage(struct page *page, unsigned long offset)
  3085. {
  3086. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  3087. trace_ext4_invalidatepage(page, offset);
  3088. /*
  3089. * free any io_end structure allocated for buffers to be discarded
  3090. */
  3091. if (ext4_should_dioread_nolock(page->mapping->host))
  3092. ext4_invalidatepage_free_endio(page, offset);
  3093. /*
  3094. * If it's a full truncate we just forget about the pending dirtying
  3095. */
  3096. if (offset == 0)
  3097. ClearPageChecked(page);
  3098. if (journal)
  3099. jbd2_journal_invalidatepage(journal, page, offset);
  3100. else
  3101. block_invalidatepage(page, offset);
  3102. }
  3103. static int ext4_releasepage(struct page *page, gfp_t wait)
  3104. {
  3105. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  3106. trace_ext4_releasepage(page);
  3107. WARN_ON(PageChecked(page));
  3108. if (!page_has_buffers(page))
  3109. return 0;
  3110. if (journal)
  3111. return jbd2_journal_try_to_free_buffers(journal, page, wait);
  3112. else
  3113. return try_to_free_buffers(page);
  3114. }
  3115. /*
  3116. * O_DIRECT for ext3 (or indirect map) based files
  3117. *
  3118. * If the O_DIRECT write will extend the file then add this inode to the
  3119. * orphan list. So recovery will truncate it back to the original size
  3120. * if the machine crashes during the write.
  3121. *
  3122. * If the O_DIRECT write is intantiating holes inside i_size and the machine
  3123. * crashes then stale disk data _may_ be exposed inside the file. But current
  3124. * VFS code falls back into buffered path in that case so we are safe.
  3125. */
  3126. static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
  3127. const struct iovec *iov, loff_t offset,
  3128. unsigned long nr_segs)
  3129. {
  3130. struct file *file = iocb->ki_filp;
  3131. struct inode *inode = file->f_mapping->host;
  3132. struct ext4_inode_info *ei = EXT4_I(inode);
  3133. handle_t *handle;
  3134. ssize_t ret;
  3135. int orphan = 0;
  3136. size_t count = iov_length(iov, nr_segs);
  3137. int retries = 0;
  3138. if (rw == WRITE) {
  3139. loff_t final_size = offset + count;
  3140. if (final_size > inode->i_size) {
  3141. /* Credits for sb + inode write */
  3142. handle = ext4_journal_start(inode, 2);
  3143. if (IS_ERR(handle)) {
  3144. ret = PTR_ERR(handle);
  3145. goto out;
  3146. }
  3147. ret = ext4_orphan_add(handle, inode);
  3148. if (ret) {
  3149. ext4_journal_stop(handle);
  3150. goto out;
  3151. }
  3152. orphan = 1;
  3153. ei->i_disksize = inode->i_size;
  3154. ext4_journal_stop(handle);
  3155. }
  3156. }
  3157. retry:
  3158. if (rw == READ && ext4_should_dioread_nolock(inode))
  3159. ret = __blockdev_direct_IO(rw, iocb, inode,
  3160. inode->i_sb->s_bdev, iov,
  3161. offset, nr_segs,
  3162. ext4_get_block, NULL, NULL, 0);
  3163. else {
  3164. ret = blockdev_direct_IO(rw, iocb, inode,
  3165. inode->i_sb->s_bdev, iov,
  3166. offset, nr_segs,
  3167. ext4_get_block, NULL);
  3168. if (unlikely((rw & WRITE) && ret < 0)) {
  3169. loff_t isize = i_size_read(inode);
  3170. loff_t end = offset + iov_length(iov, nr_segs);
  3171. if (end > isize)
  3172. ext4_truncate_failed_write(inode);
  3173. }
  3174. }
  3175. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  3176. goto retry;
  3177. if (orphan) {
  3178. int err;
  3179. /* Credits for sb + inode write */
  3180. handle = ext4_journal_start(inode, 2);
  3181. if (IS_ERR(handle)) {
  3182. /* This is really bad luck. We've written the data
  3183. * but cannot extend i_size. Bail out and pretend
  3184. * the write failed... */
  3185. ret = PTR_ERR(handle);
  3186. if (inode->i_nlink)
  3187. ext4_orphan_del(NULL, inode);
  3188. goto out;
  3189. }
  3190. if (inode->i_nlink)
  3191. ext4_orphan_del(handle, inode);
  3192. if (ret > 0) {
  3193. loff_t end = offset + ret;
  3194. if (end > inode->i_size) {
  3195. ei->i_disksize = end;
  3196. i_size_write(inode, end);
  3197. /*
  3198. * We're going to return a positive `ret'
  3199. * here due to non-zero-length I/O, so there's
  3200. * no way of reporting error returns from
  3201. * ext4_mark_inode_dirty() to userspace. So
  3202. * ignore it.
  3203. */
  3204. ext4_mark_inode_dirty(handle, inode);
  3205. }
  3206. }
  3207. err = ext4_journal_stop(handle);
  3208. if (ret == 0)
  3209. ret = err;
  3210. }
  3211. out:
  3212. return ret;
  3213. }
  3214. /*
  3215. * ext4_get_block used when preparing for a DIO write or buffer write.
  3216. * We allocate an uinitialized extent if blocks haven't been allocated.
  3217. * The extent will be converted to initialized after the IO is complete.
  3218. */
  3219. static int ext4_get_block_write(struct inode *inode, sector_t iblock,
  3220. struct buffer_head *bh_result, int create)
  3221. {
  3222. ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
  3223. inode->i_ino, create);
  3224. return _ext4_get_block(inode, iblock, bh_result,
  3225. EXT4_GET_BLOCKS_IO_CREATE_EXT);
  3226. }
  3227. static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
  3228. ssize_t size, void *private, int ret,
  3229. bool is_async)
  3230. {
  3231. ext4_io_end_t *io_end = iocb->private;
  3232. struct workqueue_struct *wq;
  3233. unsigned long flags;
  3234. struct ext4_inode_info *ei;
  3235. /* if not async direct IO or dio with 0 bytes write, just return */
  3236. if (!io_end || !size)
  3237. goto out;
  3238. ext_debug("ext4_end_io_dio(): io_end 0x%p"
  3239. "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
  3240. iocb->private, io_end->inode->i_ino, iocb, offset,
  3241. size);
  3242. /* if not aio dio with unwritten extents, just free io and return */
  3243. if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
  3244. ext4_free_io_end(io_end);
  3245. iocb->private = NULL;
  3246. out:
  3247. if (is_async)
  3248. aio_complete(iocb, ret, 0);
  3249. return;
  3250. }
  3251. io_end->offset = offset;
  3252. io_end->size = size;
  3253. if (is_async) {
  3254. io_end->iocb = iocb;
  3255. io_end->result = ret;
  3256. }
  3257. wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
  3258. /* Add the io_end to per-inode completed aio dio list*/
  3259. ei = EXT4_I(io_end->inode);
  3260. spin_lock_irqsave(&ei->i_completed_io_lock, flags);
  3261. list_add_tail(&io_end->list, &ei->i_completed_io_list);
  3262. spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
  3263. /* queue the work to convert unwritten extents to written */
  3264. queue_work(wq, &io_end->work);
  3265. iocb->private = NULL;
  3266. }
  3267. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
  3268. {
  3269. ext4_io_end_t *io_end = bh->b_private;
  3270. struct workqueue_struct *wq;
  3271. struct inode *inode;
  3272. unsigned long flags;
  3273. if (!test_clear_buffer_uninit(bh) || !io_end)
  3274. goto out;
  3275. if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
  3276. printk("sb umounted, discard end_io request for inode %lu\n",
  3277. io_end->inode->i_ino);
  3278. ext4_free_io_end(io_end);
  3279. goto out;
  3280. }
  3281. io_end->flag = EXT4_IO_END_UNWRITTEN;
  3282. inode = io_end->inode;
  3283. /* Add the io_end to per-inode completed io list*/
  3284. spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
  3285. list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
  3286. spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
  3287. wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
  3288. /* queue the work to convert unwritten extents to written */
  3289. queue_work(wq, &io_end->work);
  3290. out:
  3291. bh->b_private = NULL;
  3292. bh->b_end_io = NULL;
  3293. clear_buffer_uninit(bh);
  3294. end_buffer_async_write(bh, uptodate);
  3295. }
  3296. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
  3297. {
  3298. ext4_io_end_t *io_end;
  3299. struct page *page = bh->b_page;
  3300. loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
  3301. size_t size = bh->b_size;
  3302. retry:
  3303. io_end = ext4_init_io_end(inode, GFP_ATOMIC);
  3304. if (!io_end) {
  3305. pr_warn_ratelimited("%s: allocation fail\n", __func__);
  3306. schedule();
  3307. goto retry;
  3308. }
  3309. io_end->offset = offset;
  3310. io_end->size = size;
  3311. /*
  3312. * We need to hold a reference to the page to make sure it
  3313. * doesn't get evicted before ext4_end_io_work() has a chance
  3314. * to convert the extent from written to unwritten.
  3315. */
  3316. io_end->page = page;
  3317. get_page(io_end->page);
  3318. bh->b_private = io_end;
  3319. bh->b_end_io = ext4_end_io_buffer_write;
  3320. return 0;
  3321. }
  3322. /*
  3323. * For ext4 extent files, ext4 will do direct-io write to holes,
  3324. * preallocated extents, and those write extend the file, no need to
  3325. * fall back to buffered IO.
  3326. *
  3327. * For holes, we fallocate those blocks, mark them as uninitialized
  3328. * If those blocks were preallocated, we mark sure they are splited, but
  3329. * still keep the range to write as uninitialized.
  3330. *
  3331. * The unwrritten extents will be converted to written when DIO is completed.
  3332. * For async direct IO, since the IO may still pending when return, we
  3333. * set up an end_io call back function, which will do the conversion
  3334. * when async direct IO completed.
  3335. *
  3336. * If the O_DIRECT write will extend the file then add this inode to the
  3337. * orphan list. So recovery will truncate it back to the original size
  3338. * if the machine crashes during the write.
  3339. *
  3340. */
  3341. static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
  3342. const struct iovec *iov, loff_t offset,
  3343. unsigned long nr_segs)
  3344. {
  3345. struct file *file = iocb->ki_filp;
  3346. struct inode *inode = file->f_mapping->host;
  3347. ssize_t ret;
  3348. size_t count = iov_length(iov, nr_segs);
  3349. loff_t final_size = offset + count;
  3350. if (rw == WRITE && final_size <= inode->i_size) {
  3351. /*
  3352. * We could direct write to holes and fallocate.
  3353. *
  3354. * Allocated blocks to fill the hole are marked as uninitialized
  3355. * to prevent parallel buffered read to expose the stale data
  3356. * before DIO complete the data IO.
  3357. *
  3358. * As to previously fallocated extents, ext4 get_block
  3359. * will just simply mark the buffer mapped but still
  3360. * keep the extents uninitialized.
  3361. *
  3362. * for non AIO case, we will convert those unwritten extents
  3363. * to written after return back from blockdev_direct_IO.
  3364. *
  3365. * for async DIO, the conversion needs to be defered when
  3366. * the IO is completed. The ext4 end_io callback function
  3367. * will be called to take care of the conversion work.
  3368. * Here for async case, we allocate an io_end structure to
  3369. * hook to the iocb.
  3370. */
  3371. iocb->private = NULL;
  3372. EXT4_I(inode)->cur_aio_dio = NULL;
  3373. if (!is_sync_kiocb(iocb)) {
  3374. iocb->private = ext4_init_io_end(inode, GFP_NOFS);
  3375. if (!iocb->private)
  3376. return -ENOMEM;
  3377. /*
  3378. * we save the io structure for current async
  3379. * direct IO, so that later ext4_map_blocks()
  3380. * could flag the io structure whether there
  3381. * is a unwritten extents needs to be converted
  3382. * when IO is completed.
  3383. */
  3384. EXT4_I(inode)->cur_aio_dio = iocb->private;
  3385. }
  3386. ret = blockdev_direct_IO(rw, iocb, inode,
  3387. inode->i_sb->s_bdev, iov,
  3388. offset, nr_segs,
  3389. ext4_get_block_write,
  3390. ext4_end_io_dio);
  3391. if (iocb->private)
  3392. EXT4_I(inode)->cur_aio_dio = NULL;
  3393. /*
  3394. * The io_end structure takes a reference to the inode,
  3395. * that structure needs to be destroyed and the
  3396. * reference to the inode need to be dropped, when IO is
  3397. * complete, even with 0 byte write, or failed.
  3398. *
  3399. * In the successful AIO DIO case, the io_end structure will be
  3400. * desctroyed and the reference to the inode will be dropped
  3401. * after the end_io call back function is called.
  3402. *
  3403. * In the case there is 0 byte write, or error case, since
  3404. * VFS direct IO won't invoke the end_io call back function,
  3405. * we need to free the end_io structure here.
  3406. */
  3407. if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
  3408. ext4_free_io_end(iocb->private);
  3409. iocb->private = NULL;
  3410. } else if (ret > 0 && ext4_test_inode_state(inode,
  3411. EXT4_STATE_DIO_UNWRITTEN)) {
  3412. int err;
  3413. /*
  3414. * for non AIO case, since the IO is already
  3415. * completed, we could do the conversion right here
  3416. */
  3417. err = ext4_convert_unwritten_extents(inode,
  3418. offset, ret);
  3419. if (err < 0)
  3420. ret = err;
  3421. ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
  3422. }
  3423. return ret;
  3424. }
  3425. /* for write the the end of file case, we fall back to old way */
  3426. return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
  3427. }
  3428. static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
  3429. const struct iovec *iov, loff_t offset,
  3430. unsigned long nr_segs)
  3431. {
  3432. struct file *file = iocb->ki_filp;
  3433. struct inode *inode = file->f_mapping->host;
  3434. ssize_t ret;
  3435. trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
  3436. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  3437. ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
  3438. else
  3439. ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
  3440. trace_ext4_direct_IO_exit(inode, offset,
  3441. iov_length(iov, nr_segs), rw, ret);
  3442. return ret;
  3443. }
  3444. /*
  3445. * Pages can be marked dirty completely asynchronously from ext4's journalling
  3446. * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
  3447. * much here because ->set_page_dirty is called under VFS locks. The page is
  3448. * not necessarily locked.
  3449. *
  3450. * We cannot just dirty the page and leave attached buffers clean, because the
  3451. * buffers' dirty state is "definitive". We cannot just set the buffers dirty
  3452. * or jbddirty because all the journalling code will explode.
  3453. *
  3454. * So what we do is to mark the page "pending dirty" and next time writepage
  3455. * is called, propagate that into the buffers appropriately.
  3456. */
  3457. static int ext4_journalled_set_page_dirty(struct page *page)
  3458. {
  3459. SetPageChecked(page);
  3460. return __set_page_dirty_nobuffers(page);
  3461. }
  3462. static const struct address_space_operations ext4_ordered_aops = {
  3463. .readpage = ext4_readpage,
  3464. .readpages = ext4_readpages,
  3465. .writepage = ext4_writepage,
  3466. .write_begin = ext4_write_begin,
  3467. .write_end = ext4_ordered_write_end,
  3468. .bmap = ext4_bmap,
  3469. .invalidatepage = ext4_invalidatepage,
  3470. .releasepage = ext4_releasepage,
  3471. .direct_IO = ext4_direct_IO,
  3472. .migratepage = buffer_migrate_page,
  3473. .is_partially_uptodate = block_is_partially_uptodate,
  3474. .error_remove_page = generic_error_remove_page,
  3475. };
  3476. static const struct address_space_operations ext4_writeback_aops = {
  3477. .readpage = ext4_readpage,
  3478. .readpages = ext4_readpages,
  3479. .writepage = ext4_writepage,
  3480. .write_begin = ext4_write_begin,
  3481. .write_end = ext4_writeback_write_end,
  3482. .bmap = ext4_bmap,
  3483. .invalidatepage = ext4_invalidatepage,
  3484. .releasepage = ext4_releasepage,
  3485. .direct_IO = ext4_direct_IO,
  3486. .migratepage = buffer_migrate_page,
  3487. .is_partially_uptodate = block_is_partially_uptodate,
  3488. .error_remove_page = generic_error_remove_page,
  3489. };
  3490. static const struct address_space_operations ext4_journalled_aops = {
  3491. .readpage = ext4_readpage,
  3492. .readpages = ext4_readpages,
  3493. .writepage = ext4_writepage,
  3494. .write_begin = ext4_write_begin,
  3495. .write_end = ext4_journalled_write_end,
  3496. .set_page_dirty = ext4_journalled_set_page_dirty,
  3497. .bmap = ext4_bmap,
  3498. .invalidatepage = ext4_invalidatepage,
  3499. .releasepage = ext4_releasepage,
  3500. .is_partially_uptodate = block_is_partially_uptodate,
  3501. .error_remove_page = generic_error_remove_page,
  3502. };
  3503. static const struct address_space_operations ext4_da_aops = {
  3504. .readpage = ext4_readpage,
  3505. .readpages = ext4_readpages,
  3506. .writepage = ext4_writepage,
  3507. .writepages = ext4_da_writepages,
  3508. .write_begin = ext4_da_write_begin,
  3509. .write_end = ext4_da_write_end,
  3510. .bmap = ext4_bmap,
  3511. .invalidatepage = ext4_da_invalidatepage,
  3512. .releasepage = ext4_releasepage,
  3513. .direct_IO = ext4_direct_IO,
  3514. .migratepage = buffer_migrate_page,
  3515. .is_partially_uptodate = block_is_partially_uptodate,
  3516. .error_remove_page = generic_error_remove_page,
  3517. };
  3518. void ext4_set_aops(struct inode *inode)
  3519. {
  3520. if (ext4_should_order_data(inode) &&
  3521. test_opt(inode->i_sb, DELALLOC))
  3522. inode->i_mapping->a_ops = &ext4_da_aops;
  3523. else if (ext4_should_order_data(inode))
  3524. inode->i_mapping->a_ops = &ext4_ordered_aops;
  3525. else if (ext4_should_writeback_data(inode) &&
  3526. test_opt(inode->i_sb, DELALLOC))
  3527. inode->i_mapping->a_ops = &ext4_da_aops;
  3528. else if (ext4_should_writeback_data(inode))
  3529. inode->i_mapping->a_ops = &ext4_writeback_aops;
  3530. else
  3531. inode->i_mapping->a_ops = &ext4_journalled_aops;
  3532. }
  3533. /*
  3534. * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
  3535. * up to the end of the block which corresponds to `from'.
  3536. * This required during truncate. We need to physically zero the tail end
  3537. * of that block so it doesn't yield old data if the file is later grown.
  3538. */
  3539. int ext4_block_truncate_page(handle_t *handle,
  3540. struct address_space *mapping, loff_t from)
  3541. {
  3542. unsigned offset = from & (PAGE_CACHE_SIZE-1);
  3543. unsigned length;
  3544. unsigned blocksize;
  3545. struct inode *inode = mapping->host;
  3546. blocksize = inode->i_sb->s_blocksize;
  3547. length = blocksize - (offset & (blocksize - 1));
  3548. return ext4_block_zero_page_range(handle, mapping, from, length);
  3549. }
  3550. /*
  3551. * ext4_block_zero_page_range() zeros out a mapping of length 'length'
  3552. * starting from file offset 'from'. The range to be zero'd must
  3553. * be contained with in one block. If the specified range exceeds
  3554. * the end of the block it will be shortened to end of the block
  3555. * that cooresponds to 'from'
  3556. */
  3557. int ext4_block_zero_page_range(handle_t *handle,
  3558. struct address_space *mapping, loff_t from, loff_t length)
  3559. {
  3560. ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
  3561. unsigned offset = from & (PAGE_CACHE_SIZE-1);
  3562. unsigned blocksize, max, pos;
  3563. ext4_lblk_t iblock;
  3564. struct inode *inode = mapping->host;
  3565. struct buffer_head *bh;
  3566. struct page *page;
  3567. int err = 0;
  3568. page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
  3569. mapping_gfp_mask(mapping) & ~__GFP_FS);
  3570. if (!page)
  3571. return -EINVAL;
  3572. blocksize = inode->i_sb->s_blocksize;
  3573. max = blocksize - (offset & (blocksize - 1));
  3574. /*
  3575. * correct length if it does not fall between
  3576. * 'from' and the end of the block
  3577. */
  3578. if (length > max || length < 0)
  3579. length = max;
  3580. iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
  3581. if (!page_has_buffers(page))
  3582. create_empty_buffers(page, blocksize, 0);
  3583. /* Find the buffer that contains "offset" */
  3584. bh = page_buffers(page);
  3585. pos = blocksize;
  3586. while (offset >= pos) {
  3587. bh = bh->b_this_page;
  3588. iblock++;
  3589. pos += blocksize;
  3590. }
  3591. err = 0;
  3592. if (buffer_freed(bh)) {
  3593. BUFFER_TRACE(bh, "freed: skip");
  3594. goto unlock;
  3595. }
  3596. if (!buffer_mapped(bh)) {
  3597. BUFFER_TRACE(bh, "unmapped");
  3598. ext4_get_block(inode, iblock, bh, 0);
  3599. /* unmapped? It's a hole - nothing to do */
  3600. if (!buffer_mapped(bh)) {
  3601. BUFFER_TRACE(bh, "still unmapped");
  3602. goto unlock;
  3603. }
  3604. }
  3605. /* Ok, it's mapped. Make sure it's up-to-date */
  3606. if (PageUptodate(page))
  3607. set_buffer_uptodate(bh);
  3608. if (!buffer_uptodate(bh)) {
  3609. err = -EIO;
  3610. ll_rw_block(READ, 1, &bh);
  3611. wait_on_buffer(bh);
  3612. /* Uhhuh. Read error. Complain and punt. */
  3613. if (!buffer_uptodate(bh))
  3614. goto unlock;
  3615. }
  3616. if (ext4_should_journal_data(inode)) {
  3617. BUFFER_TRACE(bh, "get write access");
  3618. err = ext4_journal_get_write_access(handle, bh);
  3619. if (err)
  3620. goto unlock;
  3621. }
  3622. zero_user(page, offset, length);
  3623. BUFFER_TRACE(bh, "zeroed end of block");
  3624. err = 0;
  3625. if (ext4_should_journal_data(inode)) {
  3626. err = ext4_handle_dirty_metadata(handle, inode, bh);
  3627. } else {
  3628. if (ext4_should_order_data(inode) && EXT4_I(inode)->jinode)
  3629. err = ext4_jbd2_file_inode(handle, inode);
  3630. mark_buffer_dirty(bh);
  3631. }
  3632. unlock:
  3633. unlock_page(page);
  3634. page_cache_release(page);
  3635. return err;
  3636. }
  3637. /*
  3638. * Probably it should be a library function... search for first non-zero word
  3639. * or memcmp with zero_page, whatever is better for particular architecture.
  3640. * Linus?
  3641. */
  3642. static inline int all_zeroes(__le32 *p, __le32 *q)
  3643. {
  3644. while (p < q)
  3645. if (*p++)
  3646. return 0;
  3647. return 1;
  3648. }
  3649. /**
  3650. * ext4_find_shared - find the indirect blocks for partial truncation.
  3651. * @inode: inode in question
  3652. * @depth: depth of the affected branch
  3653. * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
  3654. * @chain: place to store the pointers to partial indirect blocks
  3655. * @top: place to the (detached) top of branch
  3656. *
  3657. * This is a helper function used by ext4_truncate().
  3658. *
  3659. * When we do truncate() we may have to clean the ends of several
  3660. * indirect blocks but leave the blocks themselves alive. Block is
  3661. * partially truncated if some data below the new i_size is referred
  3662. * from it (and it is on the path to the first completely truncated
  3663. * data block, indeed). We have to free the top of that path along
  3664. * with everything to the right of the path. Since no allocation
  3665. * past the truncation point is possible until ext4_truncate()
  3666. * finishes, we may safely do the latter, but top of branch may
  3667. * require special attention - pageout below the truncation point
  3668. * might try to populate it.
  3669. *
  3670. * We atomically detach the top of branch from the tree, store the
  3671. * block number of its root in *@top, pointers to buffer_heads of
  3672. * partially truncated blocks - in @chain[].bh and pointers to
  3673. * their last elements that should not be removed - in
  3674. * @chain[].p. Return value is the pointer to last filled element
  3675. * of @chain.
  3676. *
  3677. * The work left to caller to do the actual freeing of subtrees:
  3678. * a) free the subtree starting from *@top
  3679. * b) free the subtrees whose roots are stored in
  3680. * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
  3681. * c) free the subtrees growing from the inode past the @chain[0].
  3682. * (no partially truncated stuff there). */
  3683. static Indirect *ext4_find_shared(struct inode *inode, int depth,
  3684. ext4_lblk_t offsets[4], Indirect chain[4],
  3685. __le32 *top)
  3686. {
  3687. Indirect *partial, *p;
  3688. int k, err;
  3689. *top = 0;
  3690. /* Make k index the deepest non-null offset + 1 */
  3691. for (k = depth; k > 1 && !offsets[k-1]; k--)
  3692. ;
  3693. partial = ext4_get_branch(inode, k, offsets, chain, &err);
  3694. /* Writer: pointers */
  3695. if (!partial)
  3696. partial = chain + k-1;
  3697. /*
  3698. * If the branch acquired continuation since we've looked at it -
  3699. * fine, it should all survive and (new) top doesn't belong to us.
  3700. */
  3701. if (!partial->key && *partial->p)
  3702. /* Writer: end */
  3703. goto no_top;
  3704. for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
  3705. ;
  3706. /*
  3707. * OK, we've found the last block that must survive. The rest of our
  3708. * branch should be detached before unlocking. However, if that rest
  3709. * of branch is all ours and does not grow immediately from the inode
  3710. * it's easier to cheat and just decrement partial->p.
  3711. */
  3712. if (p == chain + k - 1 && p > chain) {
  3713. p->p--;
  3714. } else {
  3715. *top = *p->p;
  3716. /* Nope, don't do this in ext4. Must leave the tree intact */
  3717. #if 0
  3718. *p->p = 0;
  3719. #endif
  3720. }
  3721. /* Writer: end */
  3722. while (partial > p) {
  3723. brelse(partial->bh);
  3724. partial--;
  3725. }
  3726. no_top:
  3727. return partial;
  3728. }
  3729. /*
  3730. * Zero a number of block pointers in either an inode or an indirect block.
  3731. * If we restart the transaction we must again get write access to the
  3732. * indirect block for further modification.
  3733. *
  3734. * We release `count' blocks on disk, but (last - first) may be greater
  3735. * than `count' because there can be holes in there.
  3736. *
  3737. * Return 0 on success, 1 on invalid block range
  3738. * and < 0 on fatal error.
  3739. */
  3740. static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
  3741. struct buffer_head *bh,
  3742. ext4_fsblk_t block_to_free,
  3743. unsigned long count, __le32 *first,
  3744. __le32 *last)
  3745. {
  3746. __le32 *p;
  3747. int flags = EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_VALIDATED;
  3748. int err;
  3749. if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
  3750. flags |= EXT4_FREE_BLOCKS_METADATA;
  3751. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free,
  3752. count)) {
  3753. EXT4_ERROR_INODE(inode, "attempt to clear invalid "
  3754. "blocks %llu len %lu",
  3755. (unsigned long long) block_to_free, count);
  3756. return 1;
  3757. }
  3758. if (try_to_extend_transaction(handle, inode)) {
  3759. if (bh) {
  3760. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  3761. err = ext4_handle_dirty_metadata(handle, inode, bh);
  3762. if (unlikely(err))
  3763. goto out_err;
  3764. }
  3765. err = ext4_mark_inode_dirty(handle, inode);
  3766. if (unlikely(err))
  3767. goto out_err;
  3768. err = ext4_truncate_restart_trans(handle, inode,
  3769. blocks_for_truncate(inode));
  3770. if (unlikely(err))
  3771. goto out_err;
  3772. if (bh) {
  3773. BUFFER_TRACE(bh, "retaking write access");
  3774. err = ext4_journal_get_write_access(handle, bh);
  3775. if (unlikely(err))
  3776. goto out_err;
  3777. }
  3778. }
  3779. for (p = first; p < last; p++)
  3780. *p = 0;
  3781. ext4_free_blocks(handle, inode, NULL, block_to_free, count, flags);
  3782. return 0;
  3783. out_err:
  3784. ext4_std_error(inode->i_sb, err);
  3785. return err;
  3786. }
  3787. /**
  3788. * ext4_free_data - free a list of data blocks
  3789. * @handle: handle for this transaction
  3790. * @inode: inode we are dealing with
  3791. * @this_bh: indirect buffer_head which contains *@first and *@last
  3792. * @first: array of block numbers
  3793. * @last: points immediately past the end of array
  3794. *
  3795. * We are freeing all blocks referred from that array (numbers are stored as
  3796. * little-endian 32-bit) and updating @inode->i_blocks appropriately.
  3797. *
  3798. * We accumulate contiguous runs of blocks to free. Conveniently, if these
  3799. * blocks are contiguous then releasing them at one time will only affect one
  3800. * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
  3801. * actually use a lot of journal space.
  3802. *
  3803. * @this_bh will be %NULL if @first and @last point into the inode's direct
  3804. * block pointers.
  3805. */
  3806. static void ext4_free_data(handle_t *handle, struct inode *inode,
  3807. struct buffer_head *this_bh,
  3808. __le32 *first, __le32 *last)
  3809. {
  3810. ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
  3811. unsigned long count = 0; /* Number of blocks in the run */
  3812. __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
  3813. corresponding to
  3814. block_to_free */
  3815. ext4_fsblk_t nr; /* Current block # */
  3816. __le32 *p; /* Pointer into inode/ind
  3817. for current block */
  3818. int err = 0;
  3819. if (this_bh) { /* For indirect block */
  3820. BUFFER_TRACE(this_bh, "get_write_access");
  3821. err = ext4_journal_get_write_access(handle, this_bh);
  3822. /* Important: if we can't update the indirect pointers
  3823. * to the blocks, we can't free them. */
  3824. if (err)
  3825. return;
  3826. }
  3827. for (p = first; p < last; p++) {
  3828. nr = le32_to_cpu(*p);
  3829. if (nr) {
  3830. /* accumulate blocks to free if they're contiguous */
  3831. if (count == 0) {
  3832. block_to_free = nr;
  3833. block_to_free_p = p;
  3834. count = 1;
  3835. } else if (nr == block_to_free + count) {
  3836. count++;
  3837. } else {
  3838. err = ext4_clear_blocks(handle, inode, this_bh,
  3839. block_to_free, count,
  3840. block_to_free_p, p);
  3841. if (err)
  3842. break;
  3843. block_to_free = nr;
  3844. block_to_free_p = p;
  3845. count = 1;
  3846. }
  3847. }
  3848. }
  3849. if (!err && count > 0)
  3850. err = ext4_clear_blocks(handle, inode, this_bh, block_to_free,
  3851. count, block_to_free_p, p);
  3852. if (err < 0)
  3853. /* fatal error */
  3854. return;
  3855. if (this_bh) {
  3856. BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
  3857. /*
  3858. * The buffer head should have an attached journal head at this
  3859. * point. However, if the data is corrupted and an indirect
  3860. * block pointed to itself, it would have been detached when
  3861. * the block was cleared. Check for this instead of OOPSing.
  3862. */
  3863. if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
  3864. ext4_handle_dirty_metadata(handle, inode, this_bh);
  3865. else
  3866. EXT4_ERROR_INODE(inode,
  3867. "circular indirect block detected at "
  3868. "block %llu",
  3869. (unsigned long long) this_bh->b_blocknr);
  3870. }
  3871. }
  3872. /**
  3873. * ext4_free_branches - free an array of branches
  3874. * @handle: JBD handle for this transaction
  3875. * @inode: inode we are dealing with
  3876. * @parent_bh: the buffer_head which contains *@first and *@last
  3877. * @first: array of block numbers
  3878. * @last: pointer immediately past the end of array
  3879. * @depth: depth of the branches to free
  3880. *
  3881. * We are freeing all blocks referred from these branches (numbers are
  3882. * stored as little-endian 32-bit) and updating @inode->i_blocks
  3883. * appropriately.
  3884. */
  3885. static void ext4_free_branches(handle_t *handle, struct inode *inode,
  3886. struct buffer_head *parent_bh,
  3887. __le32 *first, __le32 *last, int depth)
  3888. {
  3889. ext4_fsblk_t nr;
  3890. __le32 *p;
  3891. if (ext4_handle_is_aborted(handle))
  3892. return;
  3893. if (depth--) {
  3894. struct buffer_head *bh;
  3895. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  3896. p = last;
  3897. while (--p >= first) {
  3898. nr = le32_to_cpu(*p);
  3899. if (!nr)
  3900. continue; /* A hole */
  3901. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
  3902. nr, 1)) {
  3903. EXT4_ERROR_INODE(inode,
  3904. "invalid indirect mapped "
  3905. "block %lu (level %d)",
  3906. (unsigned long) nr, depth);
  3907. break;
  3908. }
  3909. /* Go read the buffer for the next level down */
  3910. bh = sb_bread(inode->i_sb, nr);
  3911. /*
  3912. * A read failure? Report error and clear slot
  3913. * (should be rare).
  3914. */
  3915. if (!bh) {
  3916. EXT4_ERROR_INODE_BLOCK(inode, nr,
  3917. "Read failure");
  3918. continue;
  3919. }
  3920. /* This zaps the entire block. Bottom up. */
  3921. BUFFER_TRACE(bh, "free child branches");
  3922. ext4_free_branches(handle, inode, bh,
  3923. (__le32 *) bh->b_data,
  3924. (__le32 *) bh->b_data + addr_per_block,
  3925. depth);
  3926. brelse(bh);
  3927. /*
  3928. * Everything below this this pointer has been
  3929. * released. Now let this top-of-subtree go.
  3930. *
  3931. * We want the freeing of this indirect block to be
  3932. * atomic in the journal with the updating of the
  3933. * bitmap block which owns it. So make some room in
  3934. * the journal.
  3935. *
  3936. * We zero the parent pointer *after* freeing its
  3937. * pointee in the bitmaps, so if extend_transaction()
  3938. * for some reason fails to put the bitmap changes and
  3939. * the release into the same transaction, recovery
  3940. * will merely complain about releasing a free block,
  3941. * rather than leaking blocks.
  3942. */
  3943. if (ext4_handle_is_aborted(handle))
  3944. return;
  3945. if (try_to_extend_transaction(handle, inode)) {
  3946. ext4_mark_inode_dirty(handle, inode);
  3947. ext4_truncate_restart_trans(handle, inode,
  3948. blocks_for_truncate(inode));
  3949. }
  3950. /*
  3951. * The forget flag here is critical because if
  3952. * we are journaling (and not doing data
  3953. * journaling), we have to make sure a revoke
  3954. * record is written to prevent the journal
  3955. * replay from overwriting the (former)
  3956. * indirect block if it gets reallocated as a
  3957. * data block. This must happen in the same
  3958. * transaction where the data blocks are
  3959. * actually freed.
  3960. */
  3961. ext4_free_blocks(handle, inode, NULL, nr, 1,
  3962. EXT4_FREE_BLOCKS_METADATA|
  3963. EXT4_FREE_BLOCKS_FORGET);
  3964. if (parent_bh) {
  3965. /*
  3966. * The block which we have just freed is
  3967. * pointed to by an indirect block: journal it
  3968. */
  3969. BUFFER_TRACE(parent_bh, "get_write_access");
  3970. if (!ext4_journal_get_write_access(handle,
  3971. parent_bh)){
  3972. *p = 0;
  3973. BUFFER_TRACE(parent_bh,
  3974. "call ext4_handle_dirty_metadata");
  3975. ext4_handle_dirty_metadata(handle,
  3976. inode,
  3977. parent_bh);
  3978. }
  3979. }
  3980. }
  3981. } else {
  3982. /* We have reached the bottom of the tree. */
  3983. BUFFER_TRACE(parent_bh, "free data blocks");
  3984. ext4_free_data(handle, inode, parent_bh, first, last);
  3985. }
  3986. }
  3987. int ext4_can_truncate(struct inode *inode)
  3988. {
  3989. if (S_ISREG(inode->i_mode))
  3990. return 1;
  3991. if (S_ISDIR(inode->i_mode))
  3992. return 1;
  3993. if (S_ISLNK(inode->i_mode))
  3994. return !ext4_inode_is_fast_symlink(inode);
  3995. return 0;
  3996. }
  3997. /*
  3998. * ext4_punch_hole: punches a hole in a file by releaseing the blocks
  3999. * associated with the given offset and length
  4000. *
  4001. * @inode: File inode
  4002. * @offset: The offset where the hole will begin
  4003. * @len: The length of the hole
  4004. *
  4005. * Returns: 0 on sucess or negative on failure
  4006. */
  4007. int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
  4008. {
  4009. struct inode *inode = file->f_path.dentry->d_inode;
  4010. if (!S_ISREG(inode->i_mode))
  4011. return -ENOTSUPP;
  4012. if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  4013. /* TODO: Add support for non extent hole punching */
  4014. return -ENOTSUPP;
  4015. }
  4016. return ext4_ext_punch_hole(file, offset, length);
  4017. }
  4018. /*
  4019. * ext4_truncate()
  4020. *
  4021. * We block out ext4_get_block() block instantiations across the entire
  4022. * transaction, and VFS/VM ensures that ext4_truncate() cannot run
  4023. * simultaneously on behalf of the same inode.
  4024. *
  4025. * As we work through the truncate and commmit bits of it to the journal there
  4026. * is one core, guiding principle: the file's tree must always be consistent on
  4027. * disk. We must be able to restart the truncate after a crash.
  4028. *
  4029. * The file's tree may be transiently inconsistent in memory (although it
  4030. * probably isn't), but whenever we close off and commit a journal transaction,
  4031. * the contents of (the filesystem + the journal) must be consistent and
  4032. * restartable. It's pretty simple, really: bottom up, right to left (although
  4033. * left-to-right works OK too).
  4034. *
  4035. * Note that at recovery time, journal replay occurs *before* the restart of
  4036. * truncate against the orphan inode list.
  4037. *
  4038. * The committed inode has the new, desired i_size (which is the same as
  4039. * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
  4040. * that this inode's truncate did not complete and it will again call
  4041. * ext4_truncate() to have another go. So there will be instantiated blocks
  4042. * to the right of the truncation point in a crashed ext4 filesystem. But
  4043. * that's fine - as long as they are linked from the inode, the post-crash
  4044. * ext4_truncate() run will find them and release them.
  4045. */
  4046. void ext4_truncate(struct inode *inode)
  4047. {
  4048. trace_ext4_truncate_enter(inode);
  4049. if (!ext4_can_truncate(inode))
  4050. return;
  4051. ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
  4052. if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
  4053. ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
  4054. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  4055. ext4_ext_truncate(inode);
  4056. else
  4057. ext4_ind_truncate(inode);
  4058. trace_ext4_truncate_exit(inode);
  4059. }
  4060. void ext4_ind_truncate(struct inode *inode)
  4061. {
  4062. handle_t *handle;
  4063. struct ext4_inode_info *ei = EXT4_I(inode);
  4064. __le32 *i_data = ei->i_data;
  4065. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  4066. struct address_space *mapping = inode->i_mapping;
  4067. ext4_lblk_t offsets[4];
  4068. Indirect chain[4];
  4069. Indirect *partial;
  4070. __le32 nr = 0;
  4071. int n = 0;
  4072. ext4_lblk_t last_block, max_block;
  4073. unsigned blocksize = inode->i_sb->s_blocksize;
  4074. handle = start_transaction(inode);
  4075. if (IS_ERR(handle))
  4076. return; /* AKPM: return what? */
  4077. last_block = (inode->i_size + blocksize-1)
  4078. >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
  4079. max_block = (EXT4_SB(inode->i_sb)->s_bitmap_maxbytes + blocksize-1)
  4080. >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
  4081. if (inode->i_size & (blocksize - 1))
  4082. if (ext4_block_truncate_page(handle, mapping, inode->i_size))
  4083. goto out_stop;
  4084. if (last_block != max_block) {
  4085. n = ext4_block_to_path(inode, last_block, offsets, NULL);
  4086. if (n == 0)
  4087. goto out_stop; /* error */
  4088. }
  4089. /*
  4090. * OK. This truncate is going to happen. We add the inode to the
  4091. * orphan list, so that if this truncate spans multiple transactions,
  4092. * and we crash, we will resume the truncate when the filesystem
  4093. * recovers. It also marks the inode dirty, to catch the new size.
  4094. *
  4095. * Implication: the file must always be in a sane, consistent
  4096. * truncatable state while each transaction commits.
  4097. */
  4098. if (ext4_orphan_add(handle, inode))
  4099. goto out_stop;
  4100. /*
  4101. * From here we block out all ext4_get_block() callers who want to
  4102. * modify the block allocation tree.
  4103. */
  4104. down_write(&ei->i_data_sem);
  4105. ext4_discard_preallocations(inode);
  4106. /*
  4107. * The orphan list entry will now protect us from any crash which
  4108. * occurs before the truncate completes, so it is now safe to propagate
  4109. * the new, shorter inode size (held for now in i_size) into the
  4110. * on-disk inode. We do this via i_disksize, which is the value which
  4111. * ext4 *really* writes onto the disk inode.
  4112. */
  4113. ei->i_disksize = inode->i_size;
  4114. if (last_block == max_block) {
  4115. /*
  4116. * It is unnecessary to free any data blocks if last_block is
  4117. * equal to the indirect block limit.
  4118. */
  4119. goto out_unlock;
  4120. } else if (n == 1) { /* direct blocks */
  4121. ext4_free_data(handle, inode, NULL, i_data+offsets[0],
  4122. i_data + EXT4_NDIR_BLOCKS);
  4123. goto do_indirects;
  4124. }
  4125. partial = ext4_find_shared(inode, n, offsets, chain, &nr);
  4126. /* Kill the top of shared branch (not detached) */
  4127. if (nr) {
  4128. if (partial == chain) {
  4129. /* Shared branch grows from the inode */
  4130. ext4_free_branches(handle, inode, NULL,
  4131. &nr, &nr+1, (chain+n-1) - partial);
  4132. *partial->p = 0;
  4133. /*
  4134. * We mark the inode dirty prior to restart,
  4135. * and prior to stop. No need for it here.
  4136. */
  4137. } else {
  4138. /* Shared branch grows from an indirect block */
  4139. BUFFER_TRACE(partial->bh, "get_write_access");
  4140. ext4_free_branches(handle, inode, partial->bh,
  4141. partial->p,
  4142. partial->p+1, (chain+n-1) - partial);
  4143. }
  4144. }
  4145. /* Clear the ends of indirect blocks on the shared branch */
  4146. while (partial > chain) {
  4147. ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
  4148. (__le32*)partial->bh->b_data+addr_per_block,
  4149. (chain+n-1) - partial);
  4150. BUFFER_TRACE(partial->bh, "call brelse");
  4151. brelse(partial->bh);
  4152. partial--;
  4153. }
  4154. do_indirects:
  4155. /* Kill the remaining (whole) subtrees */
  4156. switch (offsets[0]) {
  4157. default:
  4158. nr = i_data[EXT4_IND_BLOCK];
  4159. if (nr) {
  4160. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
  4161. i_data[EXT4_IND_BLOCK] = 0;
  4162. }
  4163. case EXT4_IND_BLOCK:
  4164. nr = i_data[EXT4_DIND_BLOCK];
  4165. if (nr) {
  4166. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
  4167. i_data[EXT4_DIND_BLOCK] = 0;
  4168. }
  4169. case EXT4_DIND_BLOCK:
  4170. nr = i_data[EXT4_TIND_BLOCK];
  4171. if (nr) {
  4172. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
  4173. i_data[EXT4_TIND_BLOCK] = 0;
  4174. }
  4175. case EXT4_TIND_BLOCK:
  4176. ;
  4177. }
  4178. out_unlock:
  4179. up_write(&ei->i_data_sem);
  4180. inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
  4181. ext4_mark_inode_dirty(handle, inode);
  4182. /*
  4183. * In a multi-transaction truncate, we only make the final transaction
  4184. * synchronous
  4185. */
  4186. if (IS_SYNC(inode))
  4187. ext4_handle_sync(handle);
  4188. out_stop:
  4189. /*
  4190. * If this was a simple ftruncate(), and the file will remain alive
  4191. * then we need to clear up the orphan record which we created above.
  4192. * However, if this was a real unlink then we were called by
  4193. * ext4_delete_inode(), and we allow that function to clean up the
  4194. * orphan info for us.
  4195. */
  4196. if (inode->i_nlink)
  4197. ext4_orphan_del(handle, inode);
  4198. ext4_journal_stop(handle);
  4199. trace_ext4_truncate_exit(inode);
  4200. }
  4201. /*
  4202. * ext4_get_inode_loc returns with an extra refcount against the inode's
  4203. * underlying buffer_head on success. If 'in_mem' is true, we have all
  4204. * data in memory that is needed to recreate the on-disk version of this
  4205. * inode.
  4206. */
  4207. static int __ext4_get_inode_loc(struct inode *inode,
  4208. struct ext4_iloc *iloc, int in_mem)
  4209. {
  4210. struct ext4_group_desc *gdp;
  4211. struct buffer_head *bh;
  4212. struct super_block *sb = inode->i_sb;
  4213. ext4_fsblk_t block;
  4214. int inodes_per_block, inode_offset;
  4215. iloc->bh = NULL;
  4216. if (!ext4_valid_inum(sb, inode->i_ino))
  4217. return -EIO;
  4218. iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
  4219. gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
  4220. if (!gdp)
  4221. return -EIO;
  4222. /*
  4223. * Figure out the offset within the block group inode table
  4224. */
  4225. inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
  4226. inode_offset = ((inode->i_ino - 1) %
  4227. EXT4_INODES_PER_GROUP(sb));
  4228. block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
  4229. iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
  4230. bh = sb_getblk(sb, block);
  4231. if (!bh) {
  4232. EXT4_ERROR_INODE_BLOCK(inode, block,
  4233. "unable to read itable block");
  4234. return -EIO;
  4235. }
  4236. if (!buffer_uptodate(bh)) {
  4237. lock_buffer(bh);
  4238. /*
  4239. * If the buffer has the write error flag, we have failed
  4240. * to write out another inode in the same block. In this
  4241. * case, we don't have to read the block because we may
  4242. * read the old inode data successfully.
  4243. */
  4244. if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
  4245. set_buffer_uptodate(bh);
  4246. if (buffer_uptodate(bh)) {
  4247. /* someone brought it uptodate while we waited */
  4248. unlock_buffer(bh);
  4249. goto has_buffer;
  4250. }
  4251. /*
  4252. * If we have all information of the inode in memory and this
  4253. * is the only valid inode in the block, we need not read the
  4254. * block.
  4255. */
  4256. if (in_mem) {
  4257. struct buffer_head *bitmap_bh;
  4258. int i, start;
  4259. start = inode_offset & ~(inodes_per_block - 1);
  4260. /* Is the inode bitmap in cache? */
  4261. bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
  4262. if (!bitmap_bh)
  4263. goto make_io;
  4264. /*
  4265. * If the inode bitmap isn't in cache then the
  4266. * optimisation may end up performing two reads instead
  4267. * of one, so skip it.
  4268. */
  4269. if (!buffer_uptodate(bitmap_bh)) {
  4270. brelse(bitmap_bh);
  4271. goto make_io;
  4272. }
  4273. for (i = start; i < start + inodes_per_block; i++) {
  4274. if (i == inode_offset)
  4275. continue;
  4276. if (ext4_test_bit(i, bitmap_bh->b_data))
  4277. break;
  4278. }
  4279. brelse(bitmap_bh);
  4280. if (i == start + inodes_per_block) {
  4281. /* all other inodes are free, so skip I/O */
  4282. memset(bh->b_data, 0, bh->b_size);
  4283. set_buffer_uptodate(bh);
  4284. unlock_buffer(bh);
  4285. goto has_buffer;
  4286. }
  4287. }
  4288. make_io:
  4289. /*
  4290. * If we need to do any I/O, try to pre-readahead extra
  4291. * blocks from the inode table.
  4292. */
  4293. if (EXT4_SB(sb)->s_inode_readahead_blks) {
  4294. ext4_fsblk_t b, end, table;
  4295. unsigned num;
  4296. table = ext4_inode_table(sb, gdp);
  4297. /* s_inode_readahead_blks is always a power of 2 */
  4298. b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
  4299. if (table > b)
  4300. b = table;
  4301. end = b + EXT4_SB(sb)->s_inode_readahead_blks;
  4302. num = EXT4_INODES_PER_GROUP(sb);
  4303. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  4304. EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
  4305. num -= ext4_itable_unused_count(sb, gdp);
  4306. table += num / inodes_per_block;
  4307. if (end > table)
  4308. end = table;
  4309. while (b <= end)
  4310. sb_breadahead(sb, b++);
  4311. }
  4312. /*
  4313. * There are other valid inodes in the buffer, this inode
  4314. * has in-inode xattrs, or we don't have this inode in memory.
  4315. * Read the block from disk.
  4316. */
  4317. trace_ext4_load_inode(inode);
  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 = NULL;
  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. handle_t *handle;
  4867. handle = ext4_journal_start(inode, 3);
  4868. if (IS_ERR(handle)) {
  4869. error = PTR_ERR(handle);
  4870. goto err_out;
  4871. }
  4872. if (ext4_handle_valid(handle)) {
  4873. error = ext4_orphan_add(handle, inode);
  4874. orphan = 1;
  4875. }
  4876. EXT4_I(inode)->i_disksize = attr->ia_size;
  4877. rc = ext4_mark_inode_dirty(handle, inode);
  4878. if (!error)
  4879. error = rc;
  4880. ext4_journal_stop(handle);
  4881. if (ext4_should_order_data(inode)) {
  4882. error = ext4_begin_ordered_truncate(inode,
  4883. attr->ia_size);
  4884. if (error) {
  4885. /* Do as much error cleanup as possible */
  4886. handle = ext4_journal_start(inode, 3);
  4887. if (IS_ERR(handle)) {
  4888. ext4_orphan_del(NULL, inode);
  4889. goto err_out;
  4890. }
  4891. ext4_orphan_del(handle, inode);
  4892. orphan = 0;
  4893. ext4_journal_stop(handle);
  4894. goto err_out;
  4895. }
  4896. }
  4897. }
  4898. if (attr->ia_valid & ATTR_SIZE) {
  4899. if (attr->ia_size != i_size_read(inode)) {
  4900. truncate_setsize(inode, attr->ia_size);
  4901. ext4_truncate(inode);
  4902. } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
  4903. ext4_truncate(inode);
  4904. }
  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_ind_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  4945. {
  4946. int indirects;
  4947. /* if nrblocks are contiguous */
  4948. if (chunk) {
  4949. /*
  4950. * With N contiguous data blocks, we need at most
  4951. * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) + 1 indirect blocks,
  4952. * 2 dindirect blocks, and 1 tindirect block
  4953. */
  4954. return DIV_ROUND_UP(nrblocks,
  4955. EXT4_ADDR_PER_BLOCK(inode->i_sb)) + 4;
  4956. }
  4957. /*
  4958. * if nrblocks are not contiguous, worse case, each block touch
  4959. * a indirect block, and each indirect block touch a double indirect
  4960. * block, plus a triple indirect block
  4961. */
  4962. indirects = nrblocks * 2 + 1;
  4963. return indirects;
  4964. }
  4965. static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  4966. {
  4967. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
  4968. return ext4_ind_trans_blocks(inode, nrblocks, chunk);
  4969. return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
  4970. }
  4971. /*
  4972. * Account for index blocks, block groups bitmaps and block group
  4973. * descriptor blocks if modify datablocks and index blocks
  4974. * worse case, the indexs blocks spread over different block groups
  4975. *
  4976. * If datablocks are discontiguous, they are possible to spread over
  4977. * different block groups too. If they are contiuguous, with flexbg,
  4978. * they could still across block group boundary.
  4979. *
  4980. * Also account for superblock, inode, quota and xattr blocks
  4981. */
  4982. static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  4983. {
  4984. ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
  4985. int gdpblocks;
  4986. int idxblocks;
  4987. int ret = 0;
  4988. /*
  4989. * How many index blocks need to touch to modify nrblocks?
  4990. * The "Chunk" flag indicating whether the nrblocks is
  4991. * physically contiguous on disk
  4992. *
  4993. * For Direct IO and fallocate, they calls get_block to allocate
  4994. * one single extent at a time, so they could set the "Chunk" flag
  4995. */
  4996. idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
  4997. ret = idxblocks;
  4998. /*
  4999. * Now let's see how many group bitmaps and group descriptors need
  5000. * to account
  5001. */
  5002. groups = idxblocks;
  5003. if (chunk)
  5004. groups += 1;
  5005. else
  5006. groups += nrblocks;
  5007. gdpblocks = groups;
  5008. if (groups > ngroups)
  5009. groups = ngroups;
  5010. if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
  5011. gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
  5012. /* bitmaps and block group descriptor blocks */
  5013. ret += groups + gdpblocks;
  5014. /* Blocks for super block, inode, quota and xattr blocks */
  5015. ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
  5016. return ret;
  5017. }
  5018. /*
  5019. * Calculate the total number of credits to reserve to fit
  5020. * the modification of a single pages into a single transaction,
  5021. * which may include multiple chunks of block allocations.
  5022. *
  5023. * This could be called via ext4_write_begin()
  5024. *
  5025. * We need to consider the worse case, when
  5026. * one new block per extent.
  5027. */
  5028. int ext4_writepage_trans_blocks(struct inode *inode)
  5029. {
  5030. int bpp = ext4_journal_blocks_per_page(inode);
  5031. int ret;
  5032. ret = ext4_meta_trans_blocks(inode, bpp, 0);
  5033. /* Account for data blocks for journalled mode */
  5034. if (ext4_should_journal_data(inode))
  5035. ret += bpp;
  5036. return ret;
  5037. }
  5038. /*
  5039. * Calculate the journal credits for a chunk of data modification.
  5040. *
  5041. * This is called from DIO, fallocate or whoever calling
  5042. * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
  5043. *
  5044. * journal buffers for data blocks are not included here, as DIO
  5045. * and fallocate do no need to journal data buffers.
  5046. */
  5047. int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
  5048. {
  5049. return ext4_meta_trans_blocks(inode, nrblocks, 1);
  5050. }
  5051. /*
  5052. * The caller must have previously called ext4_reserve_inode_write().
  5053. * Give this, we know that the caller already has write access to iloc->bh.
  5054. */
  5055. int ext4_mark_iloc_dirty(handle_t *handle,
  5056. struct inode *inode, struct ext4_iloc *iloc)
  5057. {
  5058. int err = 0;
  5059. if (test_opt(inode->i_sb, I_VERSION))
  5060. inode_inc_iversion(inode);
  5061. /* the do_update_inode consumes one bh->b_count */
  5062. get_bh(iloc->bh);
  5063. /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
  5064. err = ext4_do_update_inode(handle, inode, iloc);
  5065. put_bh(iloc->bh);
  5066. return err;
  5067. }
  5068. /*
  5069. * On success, We end up with an outstanding reference count against
  5070. * iloc->bh. This _must_ be cleaned up later.
  5071. */
  5072. int
  5073. ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
  5074. struct ext4_iloc *iloc)
  5075. {
  5076. int err;
  5077. err = ext4_get_inode_loc(inode, iloc);
  5078. if (!err) {
  5079. BUFFER_TRACE(iloc->bh, "get_write_access");
  5080. err = ext4_journal_get_write_access(handle, iloc->bh);
  5081. if (err) {
  5082. brelse(iloc->bh);
  5083. iloc->bh = NULL;
  5084. }
  5085. }
  5086. ext4_std_error(inode->i_sb, err);
  5087. return err;
  5088. }
  5089. /*
  5090. * Expand an inode by new_extra_isize bytes.
  5091. * Returns 0 on success or negative error number on failure.
  5092. */
  5093. static int ext4_expand_extra_isize(struct inode *inode,
  5094. unsigned int new_extra_isize,
  5095. struct ext4_iloc iloc,
  5096. handle_t *handle)
  5097. {
  5098. struct ext4_inode *raw_inode;
  5099. struct ext4_xattr_ibody_header *header;
  5100. if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
  5101. return 0;
  5102. raw_inode = ext4_raw_inode(&iloc);
  5103. header = IHDR(inode, raw_inode);
  5104. /* No extended attributes present */
  5105. if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
  5106. header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
  5107. memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
  5108. new_extra_isize);
  5109. EXT4_I(inode)->i_extra_isize = new_extra_isize;
  5110. return 0;
  5111. }
  5112. /* try to expand with EAs present */
  5113. return ext4_expand_extra_isize_ea(inode, new_extra_isize,
  5114. raw_inode, handle);
  5115. }
  5116. /*
  5117. * What we do here is to mark the in-core inode as clean with respect to inode
  5118. * dirtiness (it may still be data-dirty).
  5119. * This means that the in-core inode may be reaped by prune_icache
  5120. * without having to perform any I/O. This is a very good thing,
  5121. * because *any* task may call prune_icache - even ones which
  5122. * have a transaction open against a different journal.
  5123. *
  5124. * Is this cheating? Not really. Sure, we haven't written the
  5125. * inode out, but prune_icache isn't a user-visible syncing function.
  5126. * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
  5127. * we start and wait on commits.
  5128. *
  5129. * Is this efficient/effective? Well, we're being nice to the system
  5130. * by cleaning up our inodes proactively so they can be reaped
  5131. * without I/O. But we are potentially leaving up to five seconds'
  5132. * worth of inodes floating about which prune_icache wants us to
  5133. * write out. One way to fix that would be to get prune_icache()
  5134. * to do a write_super() to free up some memory. It has the desired
  5135. * effect.
  5136. */
  5137. int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
  5138. {
  5139. struct ext4_iloc iloc;
  5140. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  5141. static unsigned int mnt_count;
  5142. int err, ret;
  5143. might_sleep();
  5144. trace_ext4_mark_inode_dirty(inode, _RET_IP_);
  5145. err = ext4_reserve_inode_write(handle, inode, &iloc);
  5146. if (ext4_handle_valid(handle) &&
  5147. EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
  5148. !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
  5149. /*
  5150. * We need extra buffer credits since we may write into EA block
  5151. * with this same handle. If journal_extend fails, then it will
  5152. * only result in a minor loss of functionality for that inode.
  5153. * If this is felt to be critical, then e2fsck should be run to
  5154. * force a large enough s_min_extra_isize.
  5155. */
  5156. if ((jbd2_journal_extend(handle,
  5157. EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
  5158. ret = ext4_expand_extra_isize(inode,
  5159. sbi->s_want_extra_isize,
  5160. iloc, handle);
  5161. if (ret) {
  5162. ext4_set_inode_state(inode,
  5163. EXT4_STATE_NO_EXPAND);
  5164. if (mnt_count !=
  5165. le16_to_cpu(sbi->s_es->s_mnt_count)) {
  5166. ext4_warning(inode->i_sb,
  5167. "Unable to expand inode %lu. Delete"
  5168. " some EAs or run e2fsck.",
  5169. inode->i_ino);
  5170. mnt_count =
  5171. le16_to_cpu(sbi->s_es->s_mnt_count);
  5172. }
  5173. }
  5174. }
  5175. }
  5176. if (!err)
  5177. err = ext4_mark_iloc_dirty(handle, inode, &iloc);
  5178. return err;
  5179. }
  5180. /*
  5181. * ext4_dirty_inode() is called from __mark_inode_dirty()
  5182. *
  5183. * We're really interested in the case where a file is being extended.
  5184. * i_size has been changed by generic_commit_write() and we thus need
  5185. * to include the updated inode in the current transaction.
  5186. *
  5187. * Also, dquot_alloc_block() will always dirty the inode when blocks
  5188. * are allocated to the file.
  5189. *
  5190. * If the inode is marked synchronous, we don't honour that here - doing
  5191. * so would cause a commit on atime updates, which we don't bother doing.
  5192. * We handle synchronous inodes at the highest possible level.
  5193. */
  5194. void ext4_dirty_inode(struct inode *inode, int flags)
  5195. {
  5196. handle_t *handle;
  5197. handle = ext4_journal_start(inode, 2);
  5198. if (IS_ERR(handle))
  5199. goto out;
  5200. ext4_mark_inode_dirty(handle, inode);
  5201. ext4_journal_stop(handle);
  5202. out:
  5203. return;
  5204. }
  5205. #if 0
  5206. /*
  5207. * Bind an inode's backing buffer_head into this transaction, to prevent
  5208. * it from being flushed to disk early. Unlike
  5209. * ext4_reserve_inode_write, this leaves behind no bh reference and
  5210. * returns no iloc structure, so the caller needs to repeat the iloc
  5211. * lookup to mark the inode dirty later.
  5212. */
  5213. static int ext4_pin_inode(handle_t *handle, struct inode *inode)
  5214. {
  5215. struct ext4_iloc iloc;
  5216. int err = 0;
  5217. if (handle) {
  5218. err = ext4_get_inode_loc(inode, &iloc);
  5219. if (!err) {
  5220. BUFFER_TRACE(iloc.bh, "get_write_access");
  5221. err = jbd2_journal_get_write_access(handle, iloc.bh);
  5222. if (!err)
  5223. err = ext4_handle_dirty_metadata(handle,
  5224. NULL,
  5225. iloc.bh);
  5226. brelse(iloc.bh);
  5227. }
  5228. }
  5229. ext4_std_error(inode->i_sb, err);
  5230. return err;
  5231. }
  5232. #endif
  5233. int ext4_change_inode_journal_flag(struct inode *inode, int val)
  5234. {
  5235. journal_t *journal;
  5236. handle_t *handle;
  5237. int err;
  5238. /*
  5239. * We have to be very careful here: changing a data block's
  5240. * journaling status dynamically is dangerous. If we write a
  5241. * data block to the journal, change the status and then delete
  5242. * that block, we risk forgetting to revoke the old log record
  5243. * from the journal and so a subsequent replay can corrupt data.
  5244. * So, first we make sure that the journal is empty and that
  5245. * nobody is changing anything.
  5246. */
  5247. journal = EXT4_JOURNAL(inode);
  5248. if (!journal)
  5249. return 0;
  5250. if (is_journal_aborted(journal))
  5251. return -EROFS;
  5252. jbd2_journal_lock_updates(journal);
  5253. jbd2_journal_flush(journal);
  5254. /*
  5255. * OK, there are no updates running now, and all cached data is
  5256. * synced to disk. We are now in a completely consistent state
  5257. * which doesn't have anything in the journal, and we know that
  5258. * no filesystem updates are running, so it is safe to modify
  5259. * the inode's in-core data-journaling state flag now.
  5260. */
  5261. if (val)
  5262. ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  5263. else
  5264. ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  5265. ext4_set_aops(inode);
  5266. jbd2_journal_unlock_updates(journal);
  5267. /* Finally we can mark the inode as dirty. */
  5268. handle = ext4_journal_start(inode, 1);
  5269. if (IS_ERR(handle))
  5270. return PTR_ERR(handle);
  5271. err = ext4_mark_inode_dirty(handle, inode);
  5272. ext4_handle_sync(handle);
  5273. ext4_journal_stop(handle);
  5274. ext4_std_error(inode->i_sb, err);
  5275. return err;
  5276. }
  5277. static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
  5278. {
  5279. return !buffer_mapped(bh);
  5280. }
  5281. int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
  5282. {
  5283. struct page *page = vmf->page;
  5284. loff_t size;
  5285. unsigned long len;
  5286. int ret = -EINVAL;
  5287. void *fsdata;
  5288. struct file *file = vma->vm_file;
  5289. struct inode *inode = file->f_path.dentry->d_inode;
  5290. struct address_space *mapping = inode->i_mapping;
  5291. /*
  5292. * Get i_alloc_sem to stop truncates messing with the inode. We cannot
  5293. * get i_mutex because we are already holding mmap_sem.
  5294. */
  5295. down_read(&inode->i_alloc_sem);
  5296. size = i_size_read(inode);
  5297. if (page->mapping != mapping || size <= page_offset(page)
  5298. || !PageUptodate(page)) {
  5299. /* page got truncated from under us? */
  5300. goto out_unlock;
  5301. }
  5302. ret = 0;
  5303. lock_page(page);
  5304. wait_on_page_writeback(page);
  5305. if (PageMappedToDisk(page)) {
  5306. up_read(&inode->i_alloc_sem);
  5307. return VM_FAULT_LOCKED;
  5308. }
  5309. if (page->index == size >> PAGE_CACHE_SHIFT)
  5310. len = size & ~PAGE_CACHE_MASK;
  5311. else
  5312. len = PAGE_CACHE_SIZE;
  5313. /*
  5314. * return if we have all the buffers mapped. This avoid
  5315. * the need to call write_begin/write_end which does a
  5316. * journal_start/journal_stop which can block and take
  5317. * long time
  5318. */
  5319. if (page_has_buffers(page)) {
  5320. if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  5321. ext4_bh_unmapped)) {
  5322. up_read(&inode->i_alloc_sem);
  5323. return VM_FAULT_LOCKED;
  5324. }
  5325. }
  5326. unlock_page(page);
  5327. /*
  5328. * OK, we need to fill the hole... Do write_begin write_end
  5329. * to do block allocation/reservation.We are not holding
  5330. * inode.i__mutex here. That allow * parallel write_begin,
  5331. * write_end call. lock_page prevent this from happening
  5332. * on the same page though
  5333. */
  5334. ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
  5335. len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
  5336. if (ret < 0)
  5337. goto out_unlock;
  5338. ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
  5339. len, len, page, fsdata);
  5340. if (ret < 0)
  5341. goto out_unlock;
  5342. ret = 0;
  5343. /*
  5344. * write_begin/end might have created a dirty page and someone
  5345. * could wander in and start the IO. Make sure that hasn't
  5346. * happened.
  5347. */
  5348. lock_page(page);
  5349. wait_on_page_writeback(page);
  5350. up_read(&inode->i_alloc_sem);
  5351. return VM_FAULT_LOCKED;
  5352. out_unlock:
  5353. if (ret)
  5354. ret = VM_FAULT_SIGBUS;
  5355. up_read(&inode->i_alloc_sem);
  5356. return ret;
  5357. }