inode.c 170 KB

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