inode.c 170 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873
  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_prepare_write() 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_prepare_write() 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_prepare_write. If this fails,
  1868. * redirty the page and move on.
  1869. */
  1870. if (!page_has_buffers(page)) {
  1871. if (block_prepare_write(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_prepare_write() unmaps passed block,
  2312. * is it OK?
  2313. */
  2314. ret = ext4_da_reserve_space(inode, iblock);
  2315. if (ret)
  2316. /* not enough space to reserve */
  2317. return ret;
  2318. map_bh(bh, inode->i_sb, invalid_block);
  2319. set_buffer_new(bh);
  2320. set_buffer_delay(bh);
  2321. return 0;
  2322. }
  2323. map_bh(bh, inode->i_sb, map.m_pblk);
  2324. bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
  2325. if (buffer_unwritten(bh)) {
  2326. /* A delayed write to unwritten bh should be marked
  2327. * new and mapped. Mapped ensures that we don't do
  2328. * get_block multiple times when we write to the same
  2329. * offset and new ensures that we do proper zero out
  2330. * for partial write.
  2331. */
  2332. set_buffer_new(bh);
  2333. set_buffer_mapped(bh);
  2334. }
  2335. return 0;
  2336. }
  2337. /*
  2338. * This function is used as a standard get_block_t calback function
  2339. * when there is no desire to allocate any blocks. It is used as a
  2340. * callback function for block_prepare_write() and block_write_full_page().
  2341. * These functions should only try to map a single block at a time.
  2342. *
  2343. * Since this function doesn't do block allocations even if the caller
  2344. * requests it by passing in create=1, it is critically important that
  2345. * any caller checks to make sure that any buffer heads are returned
  2346. * by this function are either all already mapped or marked for
  2347. * delayed allocation before calling block_write_full_page(). Otherwise,
  2348. * b_blocknr could be left unitialized, and the page write functions will
  2349. * be taken by surprise.
  2350. */
  2351. static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
  2352. struct buffer_head *bh_result, int create)
  2353. {
  2354. BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
  2355. return _ext4_get_block(inode, iblock, bh_result, 0);
  2356. }
  2357. static int bget_one(handle_t *handle, struct buffer_head *bh)
  2358. {
  2359. get_bh(bh);
  2360. return 0;
  2361. }
  2362. static int bput_one(handle_t *handle, struct buffer_head *bh)
  2363. {
  2364. put_bh(bh);
  2365. return 0;
  2366. }
  2367. static int __ext4_journalled_writepage(struct page *page,
  2368. unsigned int len)
  2369. {
  2370. struct address_space *mapping = page->mapping;
  2371. struct inode *inode = mapping->host;
  2372. struct buffer_head *page_bufs;
  2373. handle_t *handle = NULL;
  2374. int ret = 0;
  2375. int err;
  2376. ClearPageChecked(page);
  2377. page_bufs = page_buffers(page);
  2378. BUG_ON(!page_bufs);
  2379. walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
  2380. /* As soon as we unlock the page, it can go away, but we have
  2381. * references to buffers so we are safe */
  2382. unlock_page(page);
  2383. handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
  2384. if (IS_ERR(handle)) {
  2385. ret = PTR_ERR(handle);
  2386. goto out;
  2387. }
  2388. ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
  2389. do_journal_get_write_access);
  2390. err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
  2391. write_end_fn);
  2392. if (ret == 0)
  2393. ret = err;
  2394. err = ext4_journal_stop(handle);
  2395. if (!ret)
  2396. ret = err;
  2397. walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
  2398. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  2399. out:
  2400. return ret;
  2401. }
  2402. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
  2403. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
  2404. /*
  2405. * Note that we don't need to start a transaction unless we're journaling data
  2406. * because we should have holes filled from ext4_page_mkwrite(). We even don't
  2407. * need to file the inode to the transaction's list in ordered mode because if
  2408. * we are writing back data added by write(), the inode is already there and if
  2409. * we are writing back data modified via mmap(), noone guarantees in which
  2410. * transaction the data will hit the disk. In case we are journaling data, we
  2411. * cannot start transaction directly because transaction start ranks above page
  2412. * lock so we have to do some magic.
  2413. *
  2414. * This function can get called via...
  2415. * - ext4_da_writepages after taking page lock (have journal handle)
  2416. * - journal_submit_inode_data_buffers (no journal handle)
  2417. * - shrink_page_list via pdflush (no journal handle)
  2418. * - grab_page_cache when doing write_begin (have journal handle)
  2419. *
  2420. * We don't do any block allocation in this function. If we have page with
  2421. * multiple blocks we need to write those buffer_heads that are mapped. This
  2422. * is important for mmaped based write. So if we do with blocksize 1K
  2423. * truncate(f, 1024);
  2424. * a = mmap(f, 0, 4096);
  2425. * a[0] = 'a';
  2426. * truncate(f, 4096);
  2427. * we have in the page first buffer_head mapped via page_mkwrite call back
  2428. * but other bufer_heads would be unmapped but dirty(dirty done via the
  2429. * do_wp_page). So writepage should write the first block. If we modify
  2430. * the mmap area beyond 1024 we will again get a page_fault and the
  2431. * page_mkwrite callback will do the block allocation and mark the
  2432. * buffer_heads mapped.
  2433. *
  2434. * We redirty the page if we have any buffer_heads that is either delay or
  2435. * unwritten in the page.
  2436. *
  2437. * We can get recursively called as show below.
  2438. *
  2439. * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
  2440. * ext4_writepage()
  2441. *
  2442. * But since we don't do any block allocation we should not deadlock.
  2443. * Page also have the dirty flag cleared so we don't get recurive page_lock.
  2444. */
  2445. static int ext4_writepage(struct page *page,
  2446. struct writeback_control *wbc)
  2447. {
  2448. int ret = 0, commit_write = 0;
  2449. loff_t size;
  2450. unsigned int len;
  2451. struct buffer_head *page_bufs = NULL;
  2452. struct inode *inode = page->mapping->host;
  2453. trace_ext4_writepage(inode, page);
  2454. size = i_size_read(inode);
  2455. if (page->index == size >> PAGE_CACHE_SHIFT)
  2456. len = size & ~PAGE_CACHE_MASK;
  2457. else
  2458. len = PAGE_CACHE_SIZE;
  2459. /*
  2460. * If the page does not have buffers (for whatever reason),
  2461. * try to create them using block_prepare_write. If this
  2462. * fails, redirty the page and move on.
  2463. */
  2464. if (!page_buffers(page)) {
  2465. if (block_prepare_write(page, 0, len,
  2466. noalloc_get_block_write)) {
  2467. redirty_page:
  2468. redirty_page_for_writepage(wbc, page);
  2469. unlock_page(page);
  2470. return 0;
  2471. }
  2472. commit_write = 1;
  2473. }
  2474. page_bufs = page_buffers(page);
  2475. if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  2476. ext4_bh_delay_or_unwritten)) {
  2477. /*
  2478. * We don't want to do block allocation So redirty the
  2479. * page and return We may reach here when we do a
  2480. * journal commit via
  2481. * journal_submit_inode_data_buffers. If we don't
  2482. * have mapping block we just ignore them. We can also
  2483. * reach here via shrink_page_list
  2484. */
  2485. goto redirty_page;
  2486. }
  2487. if (commit_write)
  2488. /* now mark the buffer_heads as dirty and uptodate */
  2489. block_commit_write(page, 0, len);
  2490. if (PageChecked(page) && ext4_should_journal_data(inode))
  2491. /*
  2492. * It's mmapped pagecache. Add buffers and journal it. There
  2493. * doesn't seem much point in redirtying the page here.
  2494. */
  2495. return __ext4_journalled_writepage(page, len);
  2496. if (buffer_uninit(page_bufs)) {
  2497. ext4_set_bh_endio(page_bufs, inode);
  2498. ret = block_write_full_page_endio(page, noalloc_get_block_write,
  2499. wbc, ext4_end_io_buffer_write);
  2500. } else
  2501. ret = block_write_full_page(page, noalloc_get_block_write,
  2502. wbc);
  2503. return ret;
  2504. }
  2505. /*
  2506. * This is called via ext4_da_writepages() to
  2507. * calulate the total number of credits to reserve to fit
  2508. * a single extent allocation into a single transaction,
  2509. * ext4_da_writpeages() will loop calling this before
  2510. * the block allocation.
  2511. */
  2512. static int ext4_da_writepages_trans_blocks(struct inode *inode)
  2513. {
  2514. int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  2515. /*
  2516. * With non-extent format the journal credit needed to
  2517. * insert nrblocks contiguous block is dependent on
  2518. * number of contiguous block. So we will limit
  2519. * number of contiguous block to a sane value
  2520. */
  2521. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
  2522. (max_blocks > EXT4_MAX_TRANS_DATA))
  2523. max_blocks = EXT4_MAX_TRANS_DATA;
  2524. return ext4_chunk_trans_blocks(inode, max_blocks);
  2525. }
  2526. /*
  2527. * write_cache_pages_da - walk the list of dirty pages of the given
  2528. * address space and call the callback function (which usually writes
  2529. * the pages).
  2530. *
  2531. * This is a forked version of write_cache_pages(). Differences:
  2532. * Range cyclic is ignored.
  2533. * no_nrwrite_index_update is always presumed true
  2534. */
  2535. static int write_cache_pages_da(struct address_space *mapping,
  2536. struct writeback_control *wbc,
  2537. struct mpage_da_data *mpd,
  2538. pgoff_t *done_index)
  2539. {
  2540. int ret = 0;
  2541. int done = 0;
  2542. struct pagevec pvec;
  2543. unsigned nr_pages;
  2544. pgoff_t index;
  2545. pgoff_t end; /* Inclusive */
  2546. long nr_to_write = wbc->nr_to_write;
  2547. int tag;
  2548. pagevec_init(&pvec, 0);
  2549. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  2550. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  2551. if (wbc->sync_mode == WB_SYNC_ALL)
  2552. tag = PAGECACHE_TAG_TOWRITE;
  2553. else
  2554. tag = PAGECACHE_TAG_DIRTY;
  2555. *done_index = index;
  2556. while (!done && (index <= end)) {
  2557. int i;
  2558. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
  2559. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
  2560. if (nr_pages == 0)
  2561. break;
  2562. for (i = 0; i < nr_pages; i++) {
  2563. struct page *page = pvec.pages[i];
  2564. /*
  2565. * At this point, the page may be truncated or
  2566. * invalidated (changing page->mapping to NULL), or
  2567. * even swizzled back from swapper_space to tmpfs file
  2568. * mapping. However, page->index will not change
  2569. * because we have a reference on the page.
  2570. */
  2571. if (page->index > end) {
  2572. done = 1;
  2573. break;
  2574. }
  2575. *done_index = page->index + 1;
  2576. lock_page(page);
  2577. /*
  2578. * Page truncated or invalidated. We can freely skip it
  2579. * then, even for data integrity operations: the page
  2580. * has disappeared concurrently, so there could be no
  2581. * real expectation of this data interity operation
  2582. * even if there is now a new, dirty page at the same
  2583. * pagecache address.
  2584. */
  2585. if (unlikely(page->mapping != mapping)) {
  2586. continue_unlock:
  2587. unlock_page(page);
  2588. continue;
  2589. }
  2590. if (!PageDirty(page)) {
  2591. /* someone wrote it for us */
  2592. goto continue_unlock;
  2593. }
  2594. if (PageWriteback(page)) {
  2595. if (wbc->sync_mode != WB_SYNC_NONE)
  2596. wait_on_page_writeback(page);
  2597. else
  2598. goto continue_unlock;
  2599. }
  2600. BUG_ON(PageWriteback(page));
  2601. if (!clear_page_dirty_for_io(page))
  2602. goto continue_unlock;
  2603. ret = __mpage_da_writepage(page, wbc, mpd);
  2604. if (unlikely(ret)) {
  2605. if (ret == AOP_WRITEPAGE_ACTIVATE) {
  2606. unlock_page(page);
  2607. ret = 0;
  2608. } else {
  2609. done = 1;
  2610. break;
  2611. }
  2612. }
  2613. if (nr_to_write > 0) {
  2614. nr_to_write--;
  2615. if (nr_to_write == 0 &&
  2616. wbc->sync_mode == WB_SYNC_NONE) {
  2617. /*
  2618. * We stop writing back only if we are
  2619. * not doing integrity sync. In case of
  2620. * integrity sync we have to keep going
  2621. * because someone may be concurrently
  2622. * dirtying pages, and we might have
  2623. * synced a lot of newly appeared dirty
  2624. * pages, but have not synced all of the
  2625. * old dirty pages.
  2626. */
  2627. done = 1;
  2628. break;
  2629. }
  2630. }
  2631. }
  2632. pagevec_release(&pvec);
  2633. cond_resched();
  2634. }
  2635. return ret;
  2636. }
  2637. static int ext4_da_writepages(struct address_space *mapping,
  2638. struct writeback_control *wbc)
  2639. {
  2640. pgoff_t index;
  2641. int range_whole = 0;
  2642. handle_t *handle = NULL;
  2643. struct mpage_da_data mpd;
  2644. struct inode *inode = mapping->host;
  2645. int pages_written = 0;
  2646. long pages_skipped;
  2647. unsigned int max_pages;
  2648. int range_cyclic, cycled = 1, io_done = 0;
  2649. int needed_blocks, ret = 0;
  2650. long desired_nr_to_write, nr_to_writebump = 0;
  2651. loff_t range_start = wbc->range_start;
  2652. struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
  2653. pgoff_t done_index = 0;
  2654. pgoff_t end;
  2655. trace_ext4_da_writepages(inode, wbc);
  2656. /*
  2657. * No pages to write? This is mainly a kludge to avoid starting
  2658. * a transaction for special inodes like journal inode on last iput()
  2659. * because that could violate lock ordering on umount
  2660. */
  2661. if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
  2662. return 0;
  2663. /*
  2664. * If the filesystem has aborted, it is read-only, so return
  2665. * right away instead of dumping stack traces later on that
  2666. * will obscure the real source of the problem. We test
  2667. * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
  2668. * the latter could be true if the filesystem is mounted
  2669. * read-only, and in that case, ext4_da_writepages should
  2670. * *never* be called, so if that ever happens, we would want
  2671. * the stack trace.
  2672. */
  2673. if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
  2674. return -EROFS;
  2675. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  2676. range_whole = 1;
  2677. range_cyclic = wbc->range_cyclic;
  2678. if (wbc->range_cyclic) {
  2679. index = mapping->writeback_index;
  2680. if (index)
  2681. cycled = 0;
  2682. wbc->range_start = index << PAGE_CACHE_SHIFT;
  2683. wbc->range_end = LLONG_MAX;
  2684. wbc->range_cyclic = 0;
  2685. end = -1;
  2686. } else {
  2687. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  2688. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  2689. }
  2690. /*
  2691. * This works around two forms of stupidity. The first is in
  2692. * the writeback code, which caps the maximum number of pages
  2693. * written to be 1024 pages. This is wrong on multiple
  2694. * levels; different architectues have a different page size,
  2695. * which changes the maximum amount of data which gets
  2696. * written. Secondly, 4 megabytes is way too small. XFS
  2697. * forces this value to be 16 megabytes by multiplying
  2698. * nr_to_write parameter by four, and then relies on its
  2699. * allocator to allocate larger extents to make them
  2700. * contiguous. Unfortunately this brings us to the second
  2701. * stupidity, which is that ext4's mballoc code only allocates
  2702. * at most 2048 blocks. So we force contiguous writes up to
  2703. * the number of dirty blocks in the inode, or
  2704. * sbi->max_writeback_mb_bump whichever is smaller.
  2705. */
  2706. max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
  2707. if (!range_cyclic && range_whole) {
  2708. if (wbc->nr_to_write == LONG_MAX)
  2709. desired_nr_to_write = wbc->nr_to_write;
  2710. else
  2711. desired_nr_to_write = wbc->nr_to_write * 8;
  2712. } else
  2713. desired_nr_to_write = ext4_num_dirty_pages(inode, index,
  2714. max_pages);
  2715. if (desired_nr_to_write > max_pages)
  2716. desired_nr_to_write = max_pages;
  2717. if (wbc->nr_to_write < desired_nr_to_write) {
  2718. nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
  2719. wbc->nr_to_write = desired_nr_to_write;
  2720. }
  2721. mpd.wbc = wbc;
  2722. mpd.inode = mapping->host;
  2723. pages_skipped = wbc->pages_skipped;
  2724. retry:
  2725. if (wbc->sync_mode == WB_SYNC_ALL)
  2726. tag_pages_for_writeback(mapping, index, end);
  2727. while (!ret && wbc->nr_to_write > 0) {
  2728. /*
  2729. * we insert one extent at a time. So we need
  2730. * credit needed for single extent allocation.
  2731. * journalled mode is currently not supported
  2732. * by delalloc
  2733. */
  2734. BUG_ON(ext4_should_journal_data(inode));
  2735. needed_blocks = ext4_da_writepages_trans_blocks(inode);
  2736. /* start a new transaction*/
  2737. handle = ext4_journal_start(inode, needed_blocks);
  2738. if (IS_ERR(handle)) {
  2739. ret = PTR_ERR(handle);
  2740. ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
  2741. "%ld pages, ino %lu; err %d", __func__,
  2742. wbc->nr_to_write, inode->i_ino, ret);
  2743. goto out_writepages;
  2744. }
  2745. /*
  2746. * Now call __mpage_da_writepage to find the next
  2747. * contiguous region of logical blocks that need
  2748. * blocks to be allocated by ext4. We don't actually
  2749. * submit the blocks for I/O here, even though
  2750. * write_cache_pages thinks it will, and will set the
  2751. * pages as clean for write before calling
  2752. * __mpage_da_writepage().
  2753. */
  2754. mpd.b_size = 0;
  2755. mpd.b_state = 0;
  2756. mpd.b_blocknr = 0;
  2757. mpd.first_page = 0;
  2758. mpd.next_page = 0;
  2759. mpd.io_done = 0;
  2760. mpd.pages_written = 0;
  2761. mpd.retval = 0;
  2762. ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
  2763. /*
  2764. * If we have a contiguous extent of pages and we
  2765. * haven't done the I/O yet, map the blocks and submit
  2766. * them for I/O.
  2767. */
  2768. if (!mpd.io_done && mpd.next_page != mpd.first_page) {
  2769. mpage_da_map_and_submit(&mpd);
  2770. ret = MPAGE_DA_EXTENT_TAIL;
  2771. }
  2772. trace_ext4_da_write_pages(inode, &mpd);
  2773. wbc->nr_to_write -= mpd.pages_written;
  2774. ext4_journal_stop(handle);
  2775. if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
  2776. /* commit the transaction which would
  2777. * free blocks released in the transaction
  2778. * and try again
  2779. */
  2780. jbd2_journal_force_commit_nested(sbi->s_journal);
  2781. wbc->pages_skipped = pages_skipped;
  2782. ret = 0;
  2783. } else if (ret == MPAGE_DA_EXTENT_TAIL) {
  2784. /*
  2785. * got one extent now try with
  2786. * rest of the pages
  2787. */
  2788. pages_written += mpd.pages_written;
  2789. wbc->pages_skipped = pages_skipped;
  2790. ret = 0;
  2791. io_done = 1;
  2792. } else if (wbc->nr_to_write)
  2793. /*
  2794. * There is no more writeout needed
  2795. * or we requested for a noblocking writeout
  2796. * and we found the device congested
  2797. */
  2798. break;
  2799. }
  2800. if (!io_done && !cycled) {
  2801. cycled = 1;
  2802. index = 0;
  2803. wbc->range_start = index << PAGE_CACHE_SHIFT;
  2804. wbc->range_end = mapping->writeback_index - 1;
  2805. goto retry;
  2806. }
  2807. if (pages_skipped != wbc->pages_skipped)
  2808. ext4_msg(inode->i_sb, KERN_CRIT,
  2809. "This should not happen leaving %s "
  2810. "with nr_to_write = %ld ret = %d",
  2811. __func__, wbc->nr_to_write, ret);
  2812. /* Update index */
  2813. wbc->range_cyclic = range_cyclic;
  2814. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  2815. /*
  2816. * set the writeback_index so that range_cyclic
  2817. * mode will write it back later
  2818. */
  2819. mapping->writeback_index = done_index;
  2820. out_writepages:
  2821. wbc->nr_to_write -= nr_to_writebump;
  2822. wbc->range_start = range_start;
  2823. trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
  2824. return ret;
  2825. }
  2826. #define FALL_BACK_TO_NONDELALLOC 1
  2827. static int ext4_nonda_switch(struct super_block *sb)
  2828. {
  2829. s64 free_blocks, dirty_blocks;
  2830. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2831. /*
  2832. * switch to non delalloc mode if we are running low
  2833. * on free block. The free block accounting via percpu
  2834. * counters can get slightly wrong with percpu_counter_batch getting
  2835. * accumulated on each CPU without updating global counters
  2836. * Delalloc need an accurate free block accounting. So switch
  2837. * to non delalloc when we are near to error range.
  2838. */
  2839. free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
  2840. dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
  2841. if (2 * free_blocks < 3 * dirty_blocks ||
  2842. free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
  2843. /*
  2844. * free block count is less than 150% of dirty blocks
  2845. * or free blocks is less than watermark
  2846. */
  2847. return 1;
  2848. }
  2849. /*
  2850. * Even if we don't switch but are nearing capacity,
  2851. * start pushing delalloc when 1/2 of free blocks are dirty.
  2852. */
  2853. if (free_blocks < 2 * dirty_blocks)
  2854. writeback_inodes_sb_if_idle(sb);
  2855. return 0;
  2856. }
  2857. static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
  2858. loff_t pos, unsigned len, unsigned flags,
  2859. struct page **pagep, void **fsdata)
  2860. {
  2861. int ret, retries = 0;
  2862. struct page *page;
  2863. pgoff_t index;
  2864. struct inode *inode = mapping->host;
  2865. handle_t *handle;
  2866. index = pos >> PAGE_CACHE_SHIFT;
  2867. if (ext4_nonda_switch(inode->i_sb)) {
  2868. *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
  2869. return ext4_write_begin(file, mapping, pos,
  2870. len, flags, pagep, fsdata);
  2871. }
  2872. *fsdata = (void *)0;
  2873. trace_ext4_da_write_begin(inode, pos, len, flags);
  2874. retry:
  2875. /*
  2876. * With delayed allocation, we don't log the i_disksize update
  2877. * if there is delayed block allocation. But we still need
  2878. * to journalling the i_disksize update if writes to the end
  2879. * of file which has an already mapped buffer.
  2880. */
  2881. handle = ext4_journal_start(inode, 1);
  2882. if (IS_ERR(handle)) {
  2883. ret = PTR_ERR(handle);
  2884. goto out;
  2885. }
  2886. /* We cannot recurse into the filesystem as the transaction is already
  2887. * started */
  2888. flags |= AOP_FLAG_NOFS;
  2889. page = grab_cache_page_write_begin(mapping, index, flags);
  2890. if (!page) {
  2891. ext4_journal_stop(handle);
  2892. ret = -ENOMEM;
  2893. goto out;
  2894. }
  2895. *pagep = page;
  2896. ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
  2897. if (ret < 0) {
  2898. unlock_page(page);
  2899. ext4_journal_stop(handle);
  2900. page_cache_release(page);
  2901. /*
  2902. * block_write_begin may have instantiated a few blocks
  2903. * outside i_size. Trim these off again. Don't need
  2904. * i_size_read because we hold i_mutex.
  2905. */
  2906. if (pos + len > inode->i_size)
  2907. ext4_truncate_failed_write(inode);
  2908. }
  2909. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  2910. goto retry;
  2911. out:
  2912. return ret;
  2913. }
  2914. /*
  2915. * Check if we should update i_disksize
  2916. * when write to the end of file but not require block allocation
  2917. */
  2918. static int ext4_da_should_update_i_disksize(struct page *page,
  2919. unsigned long offset)
  2920. {
  2921. struct buffer_head *bh;
  2922. struct inode *inode = page->mapping->host;
  2923. unsigned int idx;
  2924. int i;
  2925. bh = page_buffers(page);
  2926. idx = offset >> inode->i_blkbits;
  2927. for (i = 0; i < idx; i++)
  2928. bh = bh->b_this_page;
  2929. if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
  2930. return 0;
  2931. return 1;
  2932. }
  2933. static int ext4_da_write_end(struct file *file,
  2934. struct address_space *mapping,
  2935. loff_t pos, unsigned len, unsigned copied,
  2936. struct page *page, void *fsdata)
  2937. {
  2938. struct inode *inode = mapping->host;
  2939. int ret = 0, ret2;
  2940. handle_t *handle = ext4_journal_current_handle();
  2941. loff_t new_i_size;
  2942. unsigned long start, end;
  2943. int write_mode = (int)(unsigned long)fsdata;
  2944. if (write_mode == FALL_BACK_TO_NONDELALLOC) {
  2945. if (ext4_should_order_data(inode)) {
  2946. return ext4_ordered_write_end(file, mapping, pos,
  2947. len, copied, page, fsdata);
  2948. } else if (ext4_should_writeback_data(inode)) {
  2949. return ext4_writeback_write_end(file, mapping, pos,
  2950. len, copied, page, fsdata);
  2951. } else {
  2952. BUG();
  2953. }
  2954. }
  2955. trace_ext4_da_write_end(inode, pos, len, copied);
  2956. start = pos & (PAGE_CACHE_SIZE - 1);
  2957. end = start + copied - 1;
  2958. /*
  2959. * generic_write_end() will run mark_inode_dirty() if i_size
  2960. * changes. So let's piggyback the i_disksize mark_inode_dirty
  2961. * into that.
  2962. */
  2963. new_i_size = pos + copied;
  2964. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2965. if (ext4_da_should_update_i_disksize(page, end)) {
  2966. down_write(&EXT4_I(inode)->i_data_sem);
  2967. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2968. /*
  2969. * Updating i_disksize when extending file
  2970. * without needing block allocation
  2971. */
  2972. if (ext4_should_order_data(inode))
  2973. ret = ext4_jbd2_file_inode(handle,
  2974. inode);
  2975. EXT4_I(inode)->i_disksize = new_i_size;
  2976. }
  2977. up_write(&EXT4_I(inode)->i_data_sem);
  2978. /* We need to mark inode dirty even if
  2979. * new_i_size is less that inode->i_size
  2980. * bu greater than i_disksize.(hint delalloc)
  2981. */
  2982. ext4_mark_inode_dirty(handle, inode);
  2983. }
  2984. }
  2985. ret2 = generic_write_end(file, mapping, pos, len, copied,
  2986. page, fsdata);
  2987. copied = ret2;
  2988. if (ret2 < 0)
  2989. ret = ret2;
  2990. ret2 = ext4_journal_stop(handle);
  2991. if (!ret)
  2992. ret = ret2;
  2993. return ret ? ret : copied;
  2994. }
  2995. static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
  2996. {
  2997. /*
  2998. * Drop reserved blocks
  2999. */
  3000. BUG_ON(!PageLocked(page));
  3001. if (!page_has_buffers(page))
  3002. goto out;
  3003. ext4_da_page_release_reservation(page, offset);
  3004. out:
  3005. ext4_invalidatepage(page, offset);
  3006. return;
  3007. }
  3008. /*
  3009. * Force all delayed allocation blocks to be allocated for a given inode.
  3010. */
  3011. int ext4_alloc_da_blocks(struct inode *inode)
  3012. {
  3013. trace_ext4_alloc_da_blocks(inode);
  3014. if (!EXT4_I(inode)->i_reserved_data_blocks &&
  3015. !EXT4_I(inode)->i_reserved_meta_blocks)
  3016. return 0;
  3017. /*
  3018. * We do something simple for now. The filemap_flush() will
  3019. * also start triggering a write of the data blocks, which is
  3020. * not strictly speaking necessary (and for users of
  3021. * laptop_mode, not even desirable). However, to do otherwise
  3022. * would require replicating code paths in:
  3023. *
  3024. * ext4_da_writepages() ->
  3025. * write_cache_pages() ---> (via passed in callback function)
  3026. * __mpage_da_writepage() -->
  3027. * mpage_add_bh_to_extent()
  3028. * mpage_da_map_blocks()
  3029. *
  3030. * The problem is that write_cache_pages(), located in
  3031. * mm/page-writeback.c, marks pages clean in preparation for
  3032. * doing I/O, which is not desirable if we're not planning on
  3033. * doing I/O at all.
  3034. *
  3035. * We could call write_cache_pages(), and then redirty all of
  3036. * the pages by calling redirty_page_for_writeback() but that
  3037. * would be ugly in the extreme. So instead we would need to
  3038. * replicate parts of the code in the above functions,
  3039. * simplifying them becuase we wouldn't actually intend to
  3040. * write out the pages, but rather only collect contiguous
  3041. * logical block extents, call the multi-block allocator, and
  3042. * then update the buffer heads with the block allocations.
  3043. *
  3044. * For now, though, we'll cheat by calling filemap_flush(),
  3045. * which will map the blocks, and start the I/O, but not
  3046. * actually wait for the I/O to complete.
  3047. */
  3048. return filemap_flush(inode->i_mapping);
  3049. }
  3050. /*
  3051. * bmap() is special. It gets used by applications such as lilo and by
  3052. * the swapper to find the on-disk block of a specific piece of data.
  3053. *
  3054. * Naturally, this is dangerous if the block concerned is still in the
  3055. * journal. If somebody makes a swapfile on an ext4 data-journaling
  3056. * filesystem and enables swap, then they may get a nasty shock when the
  3057. * data getting swapped to that swapfile suddenly gets overwritten by
  3058. * the original zero's written out previously to the journal and
  3059. * awaiting writeback in the kernel's buffer cache.
  3060. *
  3061. * So, if we see any bmap calls here on a modified, data-journaled file,
  3062. * take extra steps to flush any blocks which might be in the cache.
  3063. */
  3064. static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
  3065. {
  3066. struct inode *inode = mapping->host;
  3067. journal_t *journal;
  3068. int err;
  3069. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
  3070. test_opt(inode->i_sb, DELALLOC)) {
  3071. /*
  3072. * With delalloc we want to sync the file
  3073. * so that we can make sure we allocate
  3074. * blocks for file
  3075. */
  3076. filemap_write_and_wait(mapping);
  3077. }
  3078. if (EXT4_JOURNAL(inode) &&
  3079. ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
  3080. /*
  3081. * This is a REALLY heavyweight approach, but the use of
  3082. * bmap on dirty files is expected to be extremely rare:
  3083. * only if we run lilo or swapon on a freshly made file
  3084. * do we expect this to happen.
  3085. *
  3086. * (bmap requires CAP_SYS_RAWIO so this does not
  3087. * represent an unprivileged user DOS attack --- we'd be
  3088. * in trouble if mortal users could trigger this path at
  3089. * will.)
  3090. *
  3091. * NB. EXT4_STATE_JDATA is not set on files other than
  3092. * regular files. If somebody wants to bmap a directory
  3093. * or symlink and gets confused because the buffer
  3094. * hasn't yet been flushed to disk, they deserve
  3095. * everything they get.
  3096. */
  3097. ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
  3098. journal = EXT4_JOURNAL(inode);
  3099. jbd2_journal_lock_updates(journal);
  3100. err = jbd2_journal_flush(journal);
  3101. jbd2_journal_unlock_updates(journal);
  3102. if (err)
  3103. return 0;
  3104. }
  3105. return generic_block_bmap(mapping, block, ext4_get_block);
  3106. }
  3107. static int ext4_readpage(struct file *file, struct page *page)
  3108. {
  3109. return mpage_readpage(page, ext4_get_block);
  3110. }
  3111. static int
  3112. ext4_readpages(struct file *file, struct address_space *mapping,
  3113. struct list_head *pages, unsigned nr_pages)
  3114. {
  3115. return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
  3116. }
  3117. static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
  3118. {
  3119. struct buffer_head *head, *bh;
  3120. unsigned int curr_off = 0;
  3121. if (!page_has_buffers(page))
  3122. return;
  3123. head = bh = page_buffers(page);
  3124. do {
  3125. if (offset <= curr_off && test_clear_buffer_uninit(bh)
  3126. && bh->b_private) {
  3127. ext4_free_io_end(bh->b_private);
  3128. bh->b_private = NULL;
  3129. bh->b_end_io = NULL;
  3130. }
  3131. curr_off = curr_off + bh->b_size;
  3132. bh = bh->b_this_page;
  3133. } while (bh != head);
  3134. }
  3135. static void ext4_invalidatepage(struct page *page, unsigned long offset)
  3136. {
  3137. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  3138. /*
  3139. * free any io_end structure allocated for buffers to be discarded
  3140. */
  3141. if (ext4_should_dioread_nolock(page->mapping->host))
  3142. ext4_invalidatepage_free_endio(page, offset);
  3143. /*
  3144. * If it's a full truncate we just forget about the pending dirtying
  3145. */
  3146. if (offset == 0)
  3147. ClearPageChecked(page);
  3148. if (journal)
  3149. jbd2_journal_invalidatepage(journal, page, offset);
  3150. else
  3151. block_invalidatepage(page, offset);
  3152. }
  3153. static int ext4_releasepage(struct page *page, gfp_t wait)
  3154. {
  3155. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  3156. WARN_ON(PageChecked(page));
  3157. if (!page_has_buffers(page))
  3158. return 0;
  3159. if (journal)
  3160. return jbd2_journal_try_to_free_buffers(journal, page, wait);
  3161. else
  3162. return try_to_free_buffers(page);
  3163. }
  3164. /*
  3165. * O_DIRECT for ext3 (or indirect map) based files
  3166. *
  3167. * If the O_DIRECT write will extend the file then add this inode to the
  3168. * orphan list. So recovery will truncate it back to the original size
  3169. * if the machine crashes during the write.
  3170. *
  3171. * If the O_DIRECT write is intantiating holes inside i_size and the machine
  3172. * crashes then stale disk data _may_ be exposed inside the file. But current
  3173. * VFS code falls back into buffered path in that case so we are safe.
  3174. */
  3175. static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
  3176. const struct iovec *iov, loff_t offset,
  3177. unsigned long nr_segs)
  3178. {
  3179. struct file *file = iocb->ki_filp;
  3180. struct inode *inode = file->f_mapping->host;
  3181. struct ext4_inode_info *ei = EXT4_I(inode);
  3182. handle_t *handle;
  3183. ssize_t ret;
  3184. int orphan = 0;
  3185. size_t count = iov_length(iov, nr_segs);
  3186. int retries = 0;
  3187. if (rw == WRITE) {
  3188. loff_t final_size = offset + count;
  3189. if (final_size > inode->i_size) {
  3190. /* Credits for sb + inode write */
  3191. handle = ext4_journal_start(inode, 2);
  3192. if (IS_ERR(handle)) {
  3193. ret = PTR_ERR(handle);
  3194. goto out;
  3195. }
  3196. ret = ext4_orphan_add(handle, inode);
  3197. if (ret) {
  3198. ext4_journal_stop(handle);
  3199. goto out;
  3200. }
  3201. orphan = 1;
  3202. ei->i_disksize = inode->i_size;
  3203. ext4_journal_stop(handle);
  3204. }
  3205. }
  3206. retry:
  3207. if (rw == READ && ext4_should_dioread_nolock(inode))
  3208. ret = __blockdev_direct_IO(rw, iocb, inode,
  3209. inode->i_sb->s_bdev, iov,
  3210. offset, nr_segs,
  3211. ext4_get_block, NULL, NULL, 0);
  3212. else {
  3213. ret = blockdev_direct_IO(rw, iocb, inode,
  3214. inode->i_sb->s_bdev, iov,
  3215. offset, nr_segs,
  3216. ext4_get_block, NULL);
  3217. if (unlikely((rw & WRITE) && ret < 0)) {
  3218. loff_t isize = i_size_read(inode);
  3219. loff_t end = offset + iov_length(iov, nr_segs);
  3220. if (end > isize)
  3221. vmtruncate(inode, isize);
  3222. }
  3223. }
  3224. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  3225. goto retry;
  3226. if (orphan) {
  3227. int err;
  3228. /* Credits for sb + inode write */
  3229. handle = ext4_journal_start(inode, 2);
  3230. if (IS_ERR(handle)) {
  3231. /* This is really bad luck. We've written the data
  3232. * but cannot extend i_size. Bail out and pretend
  3233. * the write failed... */
  3234. ret = PTR_ERR(handle);
  3235. if (inode->i_nlink)
  3236. ext4_orphan_del(NULL, inode);
  3237. goto out;
  3238. }
  3239. if (inode->i_nlink)
  3240. ext4_orphan_del(handle, inode);
  3241. if (ret > 0) {
  3242. loff_t end = offset + ret;
  3243. if (end > inode->i_size) {
  3244. ei->i_disksize = end;
  3245. i_size_write(inode, end);
  3246. /*
  3247. * We're going to return a positive `ret'
  3248. * here due to non-zero-length I/O, so there's
  3249. * no way of reporting error returns from
  3250. * ext4_mark_inode_dirty() to userspace. So
  3251. * ignore it.
  3252. */
  3253. ext4_mark_inode_dirty(handle, inode);
  3254. }
  3255. }
  3256. err = ext4_journal_stop(handle);
  3257. if (ret == 0)
  3258. ret = err;
  3259. }
  3260. out:
  3261. return ret;
  3262. }
  3263. /*
  3264. * ext4_get_block used when preparing for a DIO write or buffer write.
  3265. * We allocate an uinitialized extent if blocks haven't been allocated.
  3266. * The extent will be converted to initialized after the IO is complete.
  3267. */
  3268. static int ext4_get_block_write(struct inode *inode, sector_t iblock,
  3269. struct buffer_head *bh_result, int create)
  3270. {
  3271. ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
  3272. inode->i_ino, create);
  3273. return _ext4_get_block(inode, iblock, bh_result,
  3274. EXT4_GET_BLOCKS_IO_CREATE_EXT);
  3275. }
  3276. static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
  3277. ssize_t size, void *private, int ret,
  3278. bool is_async)
  3279. {
  3280. ext4_io_end_t *io_end = iocb->private;
  3281. struct workqueue_struct *wq;
  3282. unsigned long flags;
  3283. struct ext4_inode_info *ei;
  3284. /* if not async direct IO or dio with 0 bytes write, just return */
  3285. if (!io_end || !size)
  3286. goto out;
  3287. ext_debug("ext4_end_io_dio(): io_end 0x%p"
  3288. "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
  3289. iocb->private, io_end->inode->i_ino, iocb, offset,
  3290. size);
  3291. /* if not aio dio with unwritten extents, just free io and return */
  3292. if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
  3293. ext4_free_io_end(io_end);
  3294. iocb->private = NULL;
  3295. out:
  3296. if (is_async)
  3297. aio_complete(iocb, ret, 0);
  3298. return;
  3299. }
  3300. io_end->offset = offset;
  3301. io_end->size = size;
  3302. if (is_async) {
  3303. io_end->iocb = iocb;
  3304. io_end->result = ret;
  3305. }
  3306. wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
  3307. /* Add the io_end to per-inode completed aio dio list*/
  3308. ei = EXT4_I(io_end->inode);
  3309. spin_lock_irqsave(&ei->i_completed_io_lock, flags);
  3310. list_add_tail(&io_end->list, &ei->i_completed_io_list);
  3311. spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
  3312. /* queue the work to convert unwritten extents to written */
  3313. queue_work(wq, &io_end->work);
  3314. iocb->private = NULL;
  3315. }
  3316. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
  3317. {
  3318. ext4_io_end_t *io_end = bh->b_private;
  3319. struct workqueue_struct *wq;
  3320. struct inode *inode;
  3321. unsigned long flags;
  3322. if (!test_clear_buffer_uninit(bh) || !io_end)
  3323. goto out;
  3324. if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
  3325. printk("sb umounted, discard end_io request for inode %lu\n",
  3326. io_end->inode->i_ino);
  3327. ext4_free_io_end(io_end);
  3328. goto out;
  3329. }
  3330. io_end->flag = EXT4_IO_END_UNWRITTEN;
  3331. inode = io_end->inode;
  3332. /* Add the io_end to per-inode completed io list*/
  3333. spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
  3334. list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
  3335. spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
  3336. wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
  3337. /* queue the work to convert unwritten extents to written */
  3338. queue_work(wq, &io_end->work);
  3339. out:
  3340. bh->b_private = NULL;
  3341. bh->b_end_io = NULL;
  3342. clear_buffer_uninit(bh);
  3343. end_buffer_async_write(bh, uptodate);
  3344. }
  3345. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
  3346. {
  3347. ext4_io_end_t *io_end;
  3348. struct page *page = bh->b_page;
  3349. loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
  3350. size_t size = bh->b_size;
  3351. retry:
  3352. io_end = ext4_init_io_end(inode, GFP_ATOMIC);
  3353. if (!io_end) {
  3354. if (printk_ratelimit())
  3355. printk(KERN_WARNING "%s: allocation fail\n", __func__);
  3356. schedule();
  3357. goto retry;
  3358. }
  3359. io_end->offset = offset;
  3360. io_end->size = size;
  3361. /*
  3362. * We need to hold a reference to the page to make sure it
  3363. * doesn't get evicted before ext4_end_io_work() has a chance
  3364. * to convert the extent from written to unwritten.
  3365. */
  3366. io_end->page = page;
  3367. get_page(io_end->page);
  3368. bh->b_private = io_end;
  3369. bh->b_end_io = ext4_end_io_buffer_write;
  3370. return 0;
  3371. }
  3372. /*
  3373. * For ext4 extent files, ext4 will do direct-io write to holes,
  3374. * preallocated extents, and those write extend the file, no need to
  3375. * fall back to buffered IO.
  3376. *
  3377. * For holes, we fallocate those blocks, mark them as unintialized
  3378. * If those blocks were preallocated, we mark sure they are splited, but
  3379. * still keep the range to write as unintialized.
  3380. *
  3381. * The unwrritten extents will be converted to written when DIO is completed.
  3382. * For async direct IO, since the IO may still pending when return, we
  3383. * set up an end_io call back function, which will do the convertion
  3384. * when async direct IO completed.
  3385. *
  3386. * If the O_DIRECT write will extend the file then add this inode to the
  3387. * orphan list. So recovery will truncate it back to the original size
  3388. * if the machine crashes during the write.
  3389. *
  3390. */
  3391. static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
  3392. const struct iovec *iov, loff_t offset,
  3393. unsigned long nr_segs)
  3394. {
  3395. struct file *file = iocb->ki_filp;
  3396. struct inode *inode = file->f_mapping->host;
  3397. ssize_t ret;
  3398. size_t count = iov_length(iov, nr_segs);
  3399. loff_t final_size = offset + count;
  3400. if (rw == WRITE && final_size <= inode->i_size) {
  3401. /*
  3402. * We could direct write to holes and fallocate.
  3403. *
  3404. * Allocated blocks to fill the hole are marked as uninitialized
  3405. * to prevent paralel buffered read to expose the stale data
  3406. * before DIO complete the data IO.
  3407. *
  3408. * As to previously fallocated extents, ext4 get_block
  3409. * will just simply mark the buffer mapped but still
  3410. * keep the extents uninitialized.
  3411. *
  3412. * for non AIO case, we will convert those unwritten extents
  3413. * to written after return back from blockdev_direct_IO.
  3414. *
  3415. * for async DIO, the conversion needs to be defered when
  3416. * the IO is completed. The ext4 end_io callback function
  3417. * will be called to take care of the conversion work.
  3418. * Here for async case, we allocate an io_end structure to
  3419. * hook to the iocb.
  3420. */
  3421. iocb->private = NULL;
  3422. EXT4_I(inode)->cur_aio_dio = NULL;
  3423. if (!is_sync_kiocb(iocb)) {
  3424. iocb->private = ext4_init_io_end(inode, GFP_NOFS);
  3425. if (!iocb->private)
  3426. return -ENOMEM;
  3427. /*
  3428. * we save the io structure for current async
  3429. * direct IO, so that later ext4_map_blocks()
  3430. * could flag the io structure whether there
  3431. * is a unwritten extents needs to be converted
  3432. * when IO is completed.
  3433. */
  3434. EXT4_I(inode)->cur_aio_dio = iocb->private;
  3435. }
  3436. ret = blockdev_direct_IO(rw, iocb, inode,
  3437. inode->i_sb->s_bdev, iov,
  3438. offset, nr_segs,
  3439. ext4_get_block_write,
  3440. ext4_end_io_dio);
  3441. if (iocb->private)
  3442. EXT4_I(inode)->cur_aio_dio = NULL;
  3443. /*
  3444. * The io_end structure takes a reference to the inode,
  3445. * that structure needs to be destroyed and the
  3446. * reference to the inode need to be dropped, when IO is
  3447. * complete, even with 0 byte write, or failed.
  3448. *
  3449. * In the successful AIO DIO case, the io_end structure will be
  3450. * desctroyed and the reference to the inode will be dropped
  3451. * after the end_io call back function is called.
  3452. *
  3453. * In the case there is 0 byte write, or error case, since
  3454. * VFS direct IO won't invoke the end_io call back function,
  3455. * we need to free the end_io structure here.
  3456. */
  3457. if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
  3458. ext4_free_io_end(iocb->private);
  3459. iocb->private = NULL;
  3460. } else if (ret > 0 && ext4_test_inode_state(inode,
  3461. EXT4_STATE_DIO_UNWRITTEN)) {
  3462. int err;
  3463. /*
  3464. * for non AIO case, since the IO is already
  3465. * completed, we could do the convertion right here
  3466. */
  3467. err = ext4_convert_unwritten_extents(inode,
  3468. offset, ret);
  3469. if (err < 0)
  3470. ret = err;
  3471. ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
  3472. }
  3473. return ret;
  3474. }
  3475. /* for write the the end of file case, we fall back to old way */
  3476. return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
  3477. }
  3478. static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
  3479. const struct iovec *iov, loff_t offset,
  3480. unsigned long nr_segs)
  3481. {
  3482. struct file *file = iocb->ki_filp;
  3483. struct inode *inode = file->f_mapping->host;
  3484. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  3485. return ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
  3486. return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
  3487. }
  3488. /*
  3489. * Pages can be marked dirty completely asynchronously from ext4's journalling
  3490. * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
  3491. * much here because ->set_page_dirty is called under VFS locks. The page is
  3492. * not necessarily locked.
  3493. *
  3494. * We cannot just dirty the page and leave attached buffers clean, because the
  3495. * buffers' dirty state is "definitive". We cannot just set the buffers dirty
  3496. * or jbddirty because all the journalling code will explode.
  3497. *
  3498. * So what we do is to mark the page "pending dirty" and next time writepage
  3499. * is called, propagate that into the buffers appropriately.
  3500. */
  3501. static int ext4_journalled_set_page_dirty(struct page *page)
  3502. {
  3503. SetPageChecked(page);
  3504. return __set_page_dirty_nobuffers(page);
  3505. }
  3506. static const struct address_space_operations ext4_ordered_aops = {
  3507. .readpage = ext4_readpage,
  3508. .readpages = ext4_readpages,
  3509. .writepage = ext4_writepage,
  3510. .sync_page = block_sync_page,
  3511. .write_begin = ext4_write_begin,
  3512. .write_end = ext4_ordered_write_end,
  3513. .bmap = ext4_bmap,
  3514. .invalidatepage = ext4_invalidatepage,
  3515. .releasepage = ext4_releasepage,
  3516. .direct_IO = ext4_direct_IO,
  3517. .migratepage = buffer_migrate_page,
  3518. .is_partially_uptodate = block_is_partially_uptodate,
  3519. .error_remove_page = generic_error_remove_page,
  3520. };
  3521. static const struct address_space_operations ext4_writeback_aops = {
  3522. .readpage = ext4_readpage,
  3523. .readpages = ext4_readpages,
  3524. .writepage = ext4_writepage,
  3525. .sync_page = block_sync_page,
  3526. .write_begin = ext4_write_begin,
  3527. .write_end = ext4_writeback_write_end,
  3528. .bmap = ext4_bmap,
  3529. .invalidatepage = ext4_invalidatepage,
  3530. .releasepage = ext4_releasepage,
  3531. .direct_IO = ext4_direct_IO,
  3532. .migratepage = buffer_migrate_page,
  3533. .is_partially_uptodate = block_is_partially_uptodate,
  3534. .error_remove_page = generic_error_remove_page,
  3535. };
  3536. static const struct address_space_operations ext4_journalled_aops = {
  3537. .readpage = ext4_readpage,
  3538. .readpages = ext4_readpages,
  3539. .writepage = ext4_writepage,
  3540. .sync_page = block_sync_page,
  3541. .write_begin = ext4_write_begin,
  3542. .write_end = ext4_journalled_write_end,
  3543. .set_page_dirty = ext4_journalled_set_page_dirty,
  3544. .bmap = ext4_bmap,
  3545. .invalidatepage = ext4_invalidatepage,
  3546. .releasepage = ext4_releasepage,
  3547. .is_partially_uptodate = block_is_partially_uptodate,
  3548. .error_remove_page = generic_error_remove_page,
  3549. };
  3550. static const struct address_space_operations ext4_da_aops = {
  3551. .readpage = ext4_readpage,
  3552. .readpages = ext4_readpages,
  3553. .writepage = ext4_writepage,
  3554. .writepages = ext4_da_writepages,
  3555. .sync_page = block_sync_page,
  3556. .write_begin = ext4_da_write_begin,
  3557. .write_end = ext4_da_write_end,
  3558. .bmap = ext4_bmap,
  3559. .invalidatepage = ext4_da_invalidatepage,
  3560. .releasepage = ext4_releasepage,
  3561. .direct_IO = ext4_direct_IO,
  3562. .migratepage = buffer_migrate_page,
  3563. .is_partially_uptodate = block_is_partially_uptodate,
  3564. .error_remove_page = generic_error_remove_page,
  3565. };
  3566. void ext4_set_aops(struct inode *inode)
  3567. {
  3568. if (ext4_should_order_data(inode) &&
  3569. test_opt(inode->i_sb, DELALLOC))
  3570. inode->i_mapping->a_ops = &ext4_da_aops;
  3571. else if (ext4_should_order_data(inode))
  3572. inode->i_mapping->a_ops = &ext4_ordered_aops;
  3573. else if (ext4_should_writeback_data(inode) &&
  3574. test_opt(inode->i_sb, DELALLOC))
  3575. inode->i_mapping->a_ops = &ext4_da_aops;
  3576. else if (ext4_should_writeback_data(inode))
  3577. inode->i_mapping->a_ops = &ext4_writeback_aops;
  3578. else
  3579. inode->i_mapping->a_ops = &ext4_journalled_aops;
  3580. }
  3581. /*
  3582. * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
  3583. * up to the end of the block which corresponds to `from'.
  3584. * This required during truncate. We need to physically zero the tail end
  3585. * of that block so it doesn't yield old data if the file is later grown.
  3586. */
  3587. int ext4_block_truncate_page(handle_t *handle,
  3588. struct address_space *mapping, loff_t from)
  3589. {
  3590. ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
  3591. unsigned offset = from & (PAGE_CACHE_SIZE-1);
  3592. unsigned blocksize, length, pos;
  3593. ext4_lblk_t iblock;
  3594. struct inode *inode = mapping->host;
  3595. struct buffer_head *bh;
  3596. struct page *page;
  3597. int err = 0;
  3598. page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
  3599. mapping_gfp_mask(mapping) & ~__GFP_FS);
  3600. if (!page)
  3601. return -EINVAL;
  3602. blocksize = inode->i_sb->s_blocksize;
  3603. length = blocksize - (offset & (blocksize - 1));
  3604. iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
  3605. if (!page_has_buffers(page))
  3606. create_empty_buffers(page, blocksize, 0);
  3607. /* Find the buffer that contains "offset" */
  3608. bh = page_buffers(page);
  3609. pos = blocksize;
  3610. while (offset >= pos) {
  3611. bh = bh->b_this_page;
  3612. iblock++;
  3613. pos += blocksize;
  3614. }
  3615. err = 0;
  3616. if (buffer_freed(bh)) {
  3617. BUFFER_TRACE(bh, "freed: skip");
  3618. goto unlock;
  3619. }
  3620. if (!buffer_mapped(bh)) {
  3621. BUFFER_TRACE(bh, "unmapped");
  3622. ext4_get_block(inode, iblock, bh, 0);
  3623. /* unmapped? It's a hole - nothing to do */
  3624. if (!buffer_mapped(bh)) {
  3625. BUFFER_TRACE(bh, "still unmapped");
  3626. goto unlock;
  3627. }
  3628. }
  3629. /* Ok, it's mapped. Make sure it's up-to-date */
  3630. if (PageUptodate(page))
  3631. set_buffer_uptodate(bh);
  3632. if (!buffer_uptodate(bh)) {
  3633. err = -EIO;
  3634. ll_rw_block(READ, 1, &bh);
  3635. wait_on_buffer(bh);
  3636. /* Uhhuh. Read error. Complain and punt. */
  3637. if (!buffer_uptodate(bh))
  3638. goto unlock;
  3639. }
  3640. if (ext4_should_journal_data(inode)) {
  3641. BUFFER_TRACE(bh, "get write access");
  3642. err = ext4_journal_get_write_access(handle, bh);
  3643. if (err)
  3644. goto unlock;
  3645. }
  3646. zero_user(page, offset, length);
  3647. BUFFER_TRACE(bh, "zeroed end of block");
  3648. err = 0;
  3649. if (ext4_should_journal_data(inode)) {
  3650. err = ext4_handle_dirty_metadata(handle, inode, bh);
  3651. } else {
  3652. if (ext4_should_order_data(inode))
  3653. err = ext4_jbd2_file_inode(handle, inode);
  3654. mark_buffer_dirty(bh);
  3655. }
  3656. unlock:
  3657. unlock_page(page);
  3658. page_cache_release(page);
  3659. return err;
  3660. }
  3661. /*
  3662. * Probably it should be a library function... search for first non-zero word
  3663. * or memcmp with zero_page, whatever is better for particular architecture.
  3664. * Linus?
  3665. */
  3666. static inline int all_zeroes(__le32 *p, __le32 *q)
  3667. {
  3668. while (p < q)
  3669. if (*p++)
  3670. return 0;
  3671. return 1;
  3672. }
  3673. /**
  3674. * ext4_find_shared - find the indirect blocks for partial truncation.
  3675. * @inode: inode in question
  3676. * @depth: depth of the affected branch
  3677. * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
  3678. * @chain: place to store the pointers to partial indirect blocks
  3679. * @top: place to the (detached) top of branch
  3680. *
  3681. * This is a helper function used by ext4_truncate().
  3682. *
  3683. * When we do truncate() we may have to clean the ends of several
  3684. * indirect blocks but leave the blocks themselves alive. Block is
  3685. * partially truncated if some data below the new i_size is refered
  3686. * from it (and it is on the path to the first completely truncated
  3687. * data block, indeed). We have to free the top of that path along
  3688. * with everything to the right of the path. Since no allocation
  3689. * past the truncation point is possible until ext4_truncate()
  3690. * finishes, we may safely do the latter, but top of branch may
  3691. * require special attention - pageout below the truncation point
  3692. * might try to populate it.
  3693. *
  3694. * We atomically detach the top of branch from the tree, store the
  3695. * block number of its root in *@top, pointers to buffer_heads of
  3696. * partially truncated blocks - in @chain[].bh and pointers to
  3697. * their last elements that should not be removed - in
  3698. * @chain[].p. Return value is the pointer to last filled element
  3699. * of @chain.
  3700. *
  3701. * The work left to caller to do the actual freeing of subtrees:
  3702. * a) free the subtree starting from *@top
  3703. * b) free the subtrees whose roots are stored in
  3704. * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
  3705. * c) free the subtrees growing from the inode past the @chain[0].
  3706. * (no partially truncated stuff there). */
  3707. static Indirect *ext4_find_shared(struct inode *inode, int depth,
  3708. ext4_lblk_t offsets[4], Indirect chain[4],
  3709. __le32 *top)
  3710. {
  3711. Indirect *partial, *p;
  3712. int k, err;
  3713. *top = 0;
  3714. /* Make k index the deepest non-null offset + 1 */
  3715. for (k = depth; k > 1 && !offsets[k-1]; k--)
  3716. ;
  3717. partial = ext4_get_branch(inode, k, offsets, chain, &err);
  3718. /* Writer: pointers */
  3719. if (!partial)
  3720. partial = chain + k-1;
  3721. /*
  3722. * If the branch acquired continuation since we've looked at it -
  3723. * fine, it should all survive and (new) top doesn't belong to us.
  3724. */
  3725. if (!partial->key && *partial->p)
  3726. /* Writer: end */
  3727. goto no_top;
  3728. for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
  3729. ;
  3730. /*
  3731. * OK, we've found the last block that must survive. The rest of our
  3732. * branch should be detached before unlocking. However, if that rest
  3733. * of branch is all ours and does not grow immediately from the inode
  3734. * it's easier to cheat and just decrement partial->p.
  3735. */
  3736. if (p == chain + k - 1 && p > chain) {
  3737. p->p--;
  3738. } else {
  3739. *top = *p->p;
  3740. /* Nope, don't do this in ext4. Must leave the tree intact */
  3741. #if 0
  3742. *p->p = 0;
  3743. #endif
  3744. }
  3745. /* Writer: end */
  3746. while (partial > p) {
  3747. brelse(partial->bh);
  3748. partial--;
  3749. }
  3750. no_top:
  3751. return partial;
  3752. }
  3753. /*
  3754. * Zero a number of block pointers in either an inode or an indirect block.
  3755. * If we restart the transaction we must again get write access to the
  3756. * indirect block for further modification.
  3757. *
  3758. * We release `count' blocks on disk, but (last - first) may be greater
  3759. * than `count' because there can be holes in there.
  3760. */
  3761. static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
  3762. struct buffer_head *bh,
  3763. ext4_fsblk_t block_to_free,
  3764. unsigned long count, __le32 *first,
  3765. __le32 *last)
  3766. {
  3767. __le32 *p;
  3768. int flags = EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_VALIDATED;
  3769. if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
  3770. flags |= EXT4_FREE_BLOCKS_METADATA;
  3771. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free,
  3772. count)) {
  3773. EXT4_ERROR_INODE(inode, "attempt to clear invalid "
  3774. "blocks %llu len %lu",
  3775. (unsigned long long) block_to_free, count);
  3776. return 1;
  3777. }
  3778. if (try_to_extend_transaction(handle, inode)) {
  3779. if (bh) {
  3780. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  3781. ext4_handle_dirty_metadata(handle, inode, bh);
  3782. }
  3783. ext4_mark_inode_dirty(handle, inode);
  3784. ext4_truncate_restart_trans(handle, inode,
  3785. blocks_for_truncate(inode));
  3786. if (bh) {
  3787. BUFFER_TRACE(bh, "retaking write access");
  3788. ext4_journal_get_write_access(handle, bh);
  3789. }
  3790. }
  3791. for (p = first; p < last; p++)
  3792. *p = 0;
  3793. ext4_free_blocks(handle, inode, 0, block_to_free, count, flags);
  3794. return 0;
  3795. }
  3796. /**
  3797. * ext4_free_data - free a list of data blocks
  3798. * @handle: handle for this transaction
  3799. * @inode: inode we are dealing with
  3800. * @this_bh: indirect buffer_head which contains *@first and *@last
  3801. * @first: array of block numbers
  3802. * @last: points immediately past the end of array
  3803. *
  3804. * We are freeing all blocks refered from that array (numbers are stored as
  3805. * little-endian 32-bit) and updating @inode->i_blocks appropriately.
  3806. *
  3807. * We accumulate contiguous runs of blocks to free. Conveniently, if these
  3808. * blocks are contiguous then releasing them at one time will only affect one
  3809. * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
  3810. * actually use a lot of journal space.
  3811. *
  3812. * @this_bh will be %NULL if @first and @last point into the inode's direct
  3813. * block pointers.
  3814. */
  3815. static void ext4_free_data(handle_t *handle, struct inode *inode,
  3816. struct buffer_head *this_bh,
  3817. __le32 *first, __le32 *last)
  3818. {
  3819. ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
  3820. unsigned long count = 0; /* Number of blocks in the run */
  3821. __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
  3822. corresponding to
  3823. block_to_free */
  3824. ext4_fsblk_t nr; /* Current block # */
  3825. __le32 *p; /* Pointer into inode/ind
  3826. for current block */
  3827. int err;
  3828. if (this_bh) { /* For indirect block */
  3829. BUFFER_TRACE(this_bh, "get_write_access");
  3830. err = ext4_journal_get_write_access(handle, this_bh);
  3831. /* Important: if we can't update the indirect pointers
  3832. * to the blocks, we can't free them. */
  3833. if (err)
  3834. return;
  3835. }
  3836. for (p = first; p < last; p++) {
  3837. nr = le32_to_cpu(*p);
  3838. if (nr) {
  3839. /* accumulate blocks to free if they're contiguous */
  3840. if (count == 0) {
  3841. block_to_free = nr;
  3842. block_to_free_p = p;
  3843. count = 1;
  3844. } else if (nr == block_to_free + count) {
  3845. count++;
  3846. } else {
  3847. if (ext4_clear_blocks(handle, inode, this_bh,
  3848. block_to_free, count,
  3849. block_to_free_p, p))
  3850. break;
  3851. block_to_free = nr;
  3852. block_to_free_p = p;
  3853. count = 1;
  3854. }
  3855. }
  3856. }
  3857. if (count > 0)
  3858. ext4_clear_blocks(handle, inode, this_bh, block_to_free,
  3859. count, block_to_free_p, p);
  3860. if (this_bh) {
  3861. BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
  3862. /*
  3863. * The buffer head should have an attached journal head at this
  3864. * point. However, if the data is corrupted and an indirect
  3865. * block pointed to itself, it would have been detached when
  3866. * the block was cleared. Check for this instead of OOPSing.
  3867. */
  3868. if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
  3869. ext4_handle_dirty_metadata(handle, inode, this_bh);
  3870. else
  3871. EXT4_ERROR_INODE(inode,
  3872. "circular indirect block detected at "
  3873. "block %llu",
  3874. (unsigned long long) this_bh->b_blocknr);
  3875. }
  3876. }
  3877. /**
  3878. * ext4_free_branches - free an array of branches
  3879. * @handle: JBD handle for this transaction
  3880. * @inode: inode we are dealing with
  3881. * @parent_bh: the buffer_head which contains *@first and *@last
  3882. * @first: array of block numbers
  3883. * @last: pointer immediately past the end of array
  3884. * @depth: depth of the branches to free
  3885. *
  3886. * We are freeing all blocks refered from these branches (numbers are
  3887. * stored as little-endian 32-bit) and updating @inode->i_blocks
  3888. * appropriately.
  3889. */
  3890. static void ext4_free_branches(handle_t *handle, struct inode *inode,
  3891. struct buffer_head *parent_bh,
  3892. __le32 *first, __le32 *last, int depth)
  3893. {
  3894. ext4_fsblk_t nr;
  3895. __le32 *p;
  3896. if (ext4_handle_is_aborted(handle))
  3897. return;
  3898. if (depth--) {
  3899. struct buffer_head *bh;
  3900. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  3901. p = last;
  3902. while (--p >= first) {
  3903. nr = le32_to_cpu(*p);
  3904. if (!nr)
  3905. continue; /* A hole */
  3906. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
  3907. nr, 1)) {
  3908. EXT4_ERROR_INODE(inode,
  3909. "invalid indirect mapped "
  3910. "block %lu (level %d)",
  3911. (unsigned long) nr, depth);
  3912. break;
  3913. }
  3914. /* Go read the buffer for the next level down */
  3915. bh = sb_bread(inode->i_sb, nr);
  3916. /*
  3917. * A read failure? Report error and clear slot
  3918. * (should be rare).
  3919. */
  3920. if (!bh) {
  3921. EXT4_ERROR_INODE_BLOCK(inode, nr,
  3922. "Read failure");
  3923. continue;
  3924. }
  3925. /* This zaps the entire block. Bottom up. */
  3926. BUFFER_TRACE(bh, "free child branches");
  3927. ext4_free_branches(handle, inode, bh,
  3928. (__le32 *) bh->b_data,
  3929. (__le32 *) bh->b_data + addr_per_block,
  3930. depth);
  3931. /*
  3932. * Everything below this this pointer has been
  3933. * released. Now let this top-of-subtree go.
  3934. *
  3935. * We want the freeing of this indirect block to be
  3936. * atomic in the journal with the updating of the
  3937. * bitmap block which owns it. So make some room in
  3938. * the journal.
  3939. *
  3940. * We zero the parent pointer *after* freeing its
  3941. * pointee in the bitmaps, so if extend_transaction()
  3942. * for some reason fails to put the bitmap changes and
  3943. * the release into the same transaction, recovery
  3944. * will merely complain about releasing a free block,
  3945. * rather than leaking blocks.
  3946. */
  3947. if (ext4_handle_is_aborted(handle))
  3948. return;
  3949. if (try_to_extend_transaction(handle, inode)) {
  3950. ext4_mark_inode_dirty(handle, inode);
  3951. ext4_truncate_restart_trans(handle, inode,
  3952. blocks_for_truncate(inode));
  3953. }
  3954. /*
  3955. * The forget flag here is critical because if
  3956. * we are journaling (and not doing data
  3957. * journaling), we have to make sure a revoke
  3958. * record is written to prevent the journal
  3959. * replay from overwriting the (former)
  3960. * indirect block if it gets reallocated as a
  3961. * data block. This must happen in the same
  3962. * transaction where the data blocks are
  3963. * actually freed.
  3964. */
  3965. ext4_free_blocks(handle, inode, 0, nr, 1,
  3966. EXT4_FREE_BLOCKS_METADATA|
  3967. EXT4_FREE_BLOCKS_FORGET);
  3968. if (parent_bh) {
  3969. /*
  3970. * The block which we have just freed is
  3971. * pointed to by an indirect block: journal it
  3972. */
  3973. BUFFER_TRACE(parent_bh, "get_write_access");
  3974. if (!ext4_journal_get_write_access(handle,
  3975. parent_bh)){
  3976. *p = 0;
  3977. BUFFER_TRACE(parent_bh,
  3978. "call ext4_handle_dirty_metadata");
  3979. ext4_handle_dirty_metadata(handle,
  3980. inode,
  3981. parent_bh);
  3982. }
  3983. }
  3984. }
  3985. } else {
  3986. /* We have reached the bottom of the tree. */
  3987. BUFFER_TRACE(parent_bh, "free data blocks");
  3988. ext4_free_data(handle, inode, parent_bh, first, last);
  3989. }
  3990. }
  3991. int ext4_can_truncate(struct inode *inode)
  3992. {
  3993. if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
  3994. return 0;
  3995. if (S_ISREG(inode->i_mode))
  3996. return 1;
  3997. if (S_ISDIR(inode->i_mode))
  3998. return 1;
  3999. if (S_ISLNK(inode->i_mode))
  4000. return !ext4_inode_is_fast_symlink(inode);
  4001. return 0;
  4002. }
  4003. /*
  4004. * ext4_truncate()
  4005. *
  4006. * We block out ext4_get_block() block instantiations across the entire
  4007. * transaction, and VFS/VM ensures that ext4_truncate() cannot run
  4008. * simultaneously on behalf of the same inode.
  4009. *
  4010. * As we work through the truncate and commmit bits of it to the journal there
  4011. * is one core, guiding principle: the file's tree must always be consistent on
  4012. * disk. We must be able to restart the truncate after a crash.
  4013. *
  4014. * The file's tree may be transiently inconsistent in memory (although it
  4015. * probably isn't), but whenever we close off and commit a journal transaction,
  4016. * the contents of (the filesystem + the journal) must be consistent and
  4017. * restartable. It's pretty simple, really: bottom up, right to left (although
  4018. * left-to-right works OK too).
  4019. *
  4020. * Note that at recovery time, journal replay occurs *before* the restart of
  4021. * truncate against the orphan inode list.
  4022. *
  4023. * The committed inode has the new, desired i_size (which is the same as
  4024. * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
  4025. * that this inode's truncate did not complete and it will again call
  4026. * ext4_truncate() to have another go. So there will be instantiated blocks
  4027. * to the right of the truncation point in a crashed ext4 filesystem. But
  4028. * that's fine - as long as they are linked from the inode, the post-crash
  4029. * ext4_truncate() run will find them and release them.
  4030. */
  4031. void ext4_truncate(struct inode *inode)
  4032. {
  4033. handle_t *handle;
  4034. struct ext4_inode_info *ei = EXT4_I(inode);
  4035. __le32 *i_data = ei->i_data;
  4036. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  4037. struct address_space *mapping = inode->i_mapping;
  4038. ext4_lblk_t offsets[4];
  4039. Indirect chain[4];
  4040. Indirect *partial;
  4041. __le32 nr = 0;
  4042. int n;
  4043. ext4_lblk_t last_block;
  4044. unsigned blocksize = inode->i_sb->s_blocksize;
  4045. if (!ext4_can_truncate(inode))
  4046. return;
  4047. ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
  4048. if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
  4049. ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
  4050. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  4051. ext4_ext_truncate(inode);
  4052. return;
  4053. }
  4054. handle = start_transaction(inode);
  4055. if (IS_ERR(handle))
  4056. return; /* AKPM: return what? */
  4057. last_block = (inode->i_size + blocksize-1)
  4058. >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
  4059. if (inode->i_size & (blocksize - 1))
  4060. if (ext4_block_truncate_page(handle, mapping, inode->i_size))
  4061. goto out_stop;
  4062. n = ext4_block_to_path(inode, last_block, offsets, NULL);
  4063. if (n == 0)
  4064. goto out_stop; /* error */
  4065. /*
  4066. * OK. This truncate is going to happen. We add the inode to the
  4067. * orphan list, so that if this truncate spans multiple transactions,
  4068. * and we crash, we will resume the truncate when the filesystem
  4069. * recovers. It also marks the inode dirty, to catch the new size.
  4070. *
  4071. * Implication: the file must always be in a sane, consistent
  4072. * truncatable state while each transaction commits.
  4073. */
  4074. if (ext4_orphan_add(handle, inode))
  4075. goto out_stop;
  4076. /*
  4077. * From here we block out all ext4_get_block() callers who want to
  4078. * modify the block allocation tree.
  4079. */
  4080. down_write(&ei->i_data_sem);
  4081. ext4_discard_preallocations(inode);
  4082. /*
  4083. * The orphan list entry will now protect us from any crash which
  4084. * occurs before the truncate completes, so it is now safe to propagate
  4085. * the new, shorter inode size (held for now in i_size) into the
  4086. * on-disk inode. We do this via i_disksize, which is the value which
  4087. * ext4 *really* writes onto the disk inode.
  4088. */
  4089. ei->i_disksize = inode->i_size;
  4090. if (n == 1) { /* direct blocks */
  4091. ext4_free_data(handle, inode, NULL, i_data+offsets[0],
  4092. i_data + EXT4_NDIR_BLOCKS);
  4093. goto do_indirects;
  4094. }
  4095. partial = ext4_find_shared(inode, n, offsets, chain, &nr);
  4096. /* Kill the top of shared branch (not detached) */
  4097. if (nr) {
  4098. if (partial == chain) {
  4099. /* Shared branch grows from the inode */
  4100. ext4_free_branches(handle, inode, NULL,
  4101. &nr, &nr+1, (chain+n-1) - partial);
  4102. *partial->p = 0;
  4103. /*
  4104. * We mark the inode dirty prior to restart,
  4105. * and prior to stop. No need for it here.
  4106. */
  4107. } else {
  4108. /* Shared branch grows from an indirect block */
  4109. BUFFER_TRACE(partial->bh, "get_write_access");
  4110. ext4_free_branches(handle, inode, partial->bh,
  4111. partial->p,
  4112. partial->p+1, (chain+n-1) - partial);
  4113. }
  4114. }
  4115. /* Clear the ends of indirect blocks on the shared branch */
  4116. while (partial > chain) {
  4117. ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
  4118. (__le32*)partial->bh->b_data+addr_per_block,
  4119. (chain+n-1) - partial);
  4120. BUFFER_TRACE(partial->bh, "call brelse");
  4121. brelse(partial->bh);
  4122. partial--;
  4123. }
  4124. do_indirects:
  4125. /* Kill the remaining (whole) subtrees */
  4126. switch (offsets[0]) {
  4127. default:
  4128. nr = i_data[EXT4_IND_BLOCK];
  4129. if (nr) {
  4130. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
  4131. i_data[EXT4_IND_BLOCK] = 0;
  4132. }
  4133. case EXT4_IND_BLOCK:
  4134. nr = i_data[EXT4_DIND_BLOCK];
  4135. if (nr) {
  4136. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
  4137. i_data[EXT4_DIND_BLOCK] = 0;
  4138. }
  4139. case EXT4_DIND_BLOCK:
  4140. nr = i_data[EXT4_TIND_BLOCK];
  4141. if (nr) {
  4142. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
  4143. i_data[EXT4_TIND_BLOCK] = 0;
  4144. }
  4145. case EXT4_TIND_BLOCK:
  4146. ;
  4147. }
  4148. up_write(&ei->i_data_sem);
  4149. inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
  4150. ext4_mark_inode_dirty(handle, inode);
  4151. /*
  4152. * In a multi-transaction truncate, we only make the final transaction
  4153. * synchronous
  4154. */
  4155. if (IS_SYNC(inode))
  4156. ext4_handle_sync(handle);
  4157. out_stop:
  4158. /*
  4159. * If this was a simple ftruncate(), and the file will remain alive
  4160. * then we need to clear up the orphan record which we created above.
  4161. * However, if this was a real unlink then we were called by
  4162. * ext4_delete_inode(), and we allow that function to clean up the
  4163. * orphan info for us.
  4164. */
  4165. if (inode->i_nlink)
  4166. ext4_orphan_del(handle, inode);
  4167. ext4_journal_stop(handle);
  4168. }
  4169. /*
  4170. * ext4_get_inode_loc returns with an extra refcount against the inode's
  4171. * underlying buffer_head on success. If 'in_mem' is true, we have all
  4172. * data in memory that is needed to recreate the on-disk version of this
  4173. * inode.
  4174. */
  4175. static int __ext4_get_inode_loc(struct inode *inode,
  4176. struct ext4_iloc *iloc, int in_mem)
  4177. {
  4178. struct ext4_group_desc *gdp;
  4179. struct buffer_head *bh;
  4180. struct super_block *sb = inode->i_sb;
  4181. ext4_fsblk_t block;
  4182. int inodes_per_block, inode_offset;
  4183. iloc->bh = NULL;
  4184. if (!ext4_valid_inum(sb, inode->i_ino))
  4185. return -EIO;
  4186. iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
  4187. gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
  4188. if (!gdp)
  4189. return -EIO;
  4190. /*
  4191. * Figure out the offset within the block group inode table
  4192. */
  4193. inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
  4194. inode_offset = ((inode->i_ino - 1) %
  4195. EXT4_INODES_PER_GROUP(sb));
  4196. block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
  4197. iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
  4198. bh = sb_getblk(sb, block);
  4199. if (!bh) {
  4200. EXT4_ERROR_INODE_BLOCK(inode, block,
  4201. "unable to read itable block");
  4202. return -EIO;
  4203. }
  4204. if (!buffer_uptodate(bh)) {
  4205. lock_buffer(bh);
  4206. /*
  4207. * If the buffer has the write error flag, we have failed
  4208. * to write out another inode in the same block. In this
  4209. * case, we don't have to read the block because we may
  4210. * read the old inode data successfully.
  4211. */
  4212. if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
  4213. set_buffer_uptodate(bh);
  4214. if (buffer_uptodate(bh)) {
  4215. /* someone brought it uptodate while we waited */
  4216. unlock_buffer(bh);
  4217. goto has_buffer;
  4218. }
  4219. /*
  4220. * If we have all information of the inode in memory and this
  4221. * is the only valid inode in the block, we need not read the
  4222. * block.
  4223. */
  4224. if (in_mem) {
  4225. struct buffer_head *bitmap_bh;
  4226. int i, start;
  4227. start = inode_offset & ~(inodes_per_block - 1);
  4228. /* Is the inode bitmap in cache? */
  4229. bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
  4230. if (!bitmap_bh)
  4231. goto make_io;
  4232. /*
  4233. * If the inode bitmap isn't in cache then the
  4234. * optimisation may end up performing two reads instead
  4235. * of one, so skip it.
  4236. */
  4237. if (!buffer_uptodate(bitmap_bh)) {
  4238. brelse(bitmap_bh);
  4239. goto make_io;
  4240. }
  4241. for (i = start; i < start + inodes_per_block; i++) {
  4242. if (i == inode_offset)
  4243. continue;
  4244. if (ext4_test_bit(i, bitmap_bh->b_data))
  4245. break;
  4246. }
  4247. brelse(bitmap_bh);
  4248. if (i == start + inodes_per_block) {
  4249. /* all other inodes are free, so skip I/O */
  4250. memset(bh->b_data, 0, bh->b_size);
  4251. set_buffer_uptodate(bh);
  4252. unlock_buffer(bh);
  4253. goto has_buffer;
  4254. }
  4255. }
  4256. make_io:
  4257. /*
  4258. * If we need to do any I/O, try to pre-readahead extra
  4259. * blocks from the inode table.
  4260. */
  4261. if (EXT4_SB(sb)->s_inode_readahead_blks) {
  4262. ext4_fsblk_t b, end, table;
  4263. unsigned num;
  4264. table = ext4_inode_table(sb, gdp);
  4265. /* s_inode_readahead_blks is always a power of 2 */
  4266. b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
  4267. if (table > b)
  4268. b = table;
  4269. end = b + EXT4_SB(sb)->s_inode_readahead_blks;
  4270. num = EXT4_INODES_PER_GROUP(sb);
  4271. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  4272. EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
  4273. num -= ext4_itable_unused_count(sb, gdp);
  4274. table += num / inodes_per_block;
  4275. if (end > table)
  4276. end = table;
  4277. while (b <= end)
  4278. sb_breadahead(sb, b++);
  4279. }
  4280. /*
  4281. * There are other valid inodes in the buffer, this inode
  4282. * has in-inode xattrs, or we don't have this inode in memory.
  4283. * Read the block from disk.
  4284. */
  4285. get_bh(bh);
  4286. bh->b_end_io = end_buffer_read_sync;
  4287. submit_bh(READ_META, bh);
  4288. wait_on_buffer(bh);
  4289. if (!buffer_uptodate(bh)) {
  4290. EXT4_ERROR_INODE_BLOCK(inode, block,
  4291. "unable to read itable block");
  4292. brelse(bh);
  4293. return -EIO;
  4294. }
  4295. }
  4296. has_buffer:
  4297. iloc->bh = bh;
  4298. return 0;
  4299. }
  4300. int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
  4301. {
  4302. /* We have all inode data except xattrs in memory here. */
  4303. return __ext4_get_inode_loc(inode, iloc,
  4304. !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
  4305. }
  4306. void ext4_set_inode_flags(struct inode *inode)
  4307. {
  4308. unsigned int flags = EXT4_I(inode)->i_flags;
  4309. inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
  4310. if (flags & EXT4_SYNC_FL)
  4311. inode->i_flags |= S_SYNC;
  4312. if (flags & EXT4_APPEND_FL)
  4313. inode->i_flags |= S_APPEND;
  4314. if (flags & EXT4_IMMUTABLE_FL)
  4315. inode->i_flags |= S_IMMUTABLE;
  4316. if (flags & EXT4_NOATIME_FL)
  4317. inode->i_flags |= S_NOATIME;
  4318. if (flags & EXT4_DIRSYNC_FL)
  4319. inode->i_flags |= S_DIRSYNC;
  4320. }
  4321. /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
  4322. void ext4_get_inode_flags(struct ext4_inode_info *ei)
  4323. {
  4324. unsigned int vfs_fl;
  4325. unsigned long old_fl, new_fl;
  4326. do {
  4327. vfs_fl = ei->vfs_inode.i_flags;
  4328. old_fl = ei->i_flags;
  4329. new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
  4330. EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
  4331. EXT4_DIRSYNC_FL);
  4332. if (vfs_fl & S_SYNC)
  4333. new_fl |= EXT4_SYNC_FL;
  4334. if (vfs_fl & S_APPEND)
  4335. new_fl |= EXT4_APPEND_FL;
  4336. if (vfs_fl & S_IMMUTABLE)
  4337. new_fl |= EXT4_IMMUTABLE_FL;
  4338. if (vfs_fl & S_NOATIME)
  4339. new_fl |= EXT4_NOATIME_FL;
  4340. if (vfs_fl & S_DIRSYNC)
  4341. new_fl |= EXT4_DIRSYNC_FL;
  4342. } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
  4343. }
  4344. static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
  4345. struct ext4_inode_info *ei)
  4346. {
  4347. blkcnt_t i_blocks ;
  4348. struct inode *inode = &(ei->vfs_inode);
  4349. struct super_block *sb = inode->i_sb;
  4350. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  4351. EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
  4352. /* we are using combined 48 bit field */
  4353. i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
  4354. le32_to_cpu(raw_inode->i_blocks_lo);
  4355. if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
  4356. /* i_blocks represent file system block size */
  4357. return i_blocks << (inode->i_blkbits - 9);
  4358. } else {
  4359. return i_blocks;
  4360. }
  4361. } else {
  4362. return le32_to_cpu(raw_inode->i_blocks_lo);
  4363. }
  4364. }
  4365. struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
  4366. {
  4367. struct ext4_iloc iloc;
  4368. struct ext4_inode *raw_inode;
  4369. struct ext4_inode_info *ei;
  4370. struct inode *inode;
  4371. journal_t *journal = EXT4_SB(sb)->s_journal;
  4372. long ret;
  4373. int block;
  4374. inode = iget_locked(sb, ino);
  4375. if (!inode)
  4376. return ERR_PTR(-ENOMEM);
  4377. if (!(inode->i_state & I_NEW))
  4378. return inode;
  4379. ei = EXT4_I(inode);
  4380. iloc.bh = 0;
  4381. ret = __ext4_get_inode_loc(inode, &iloc, 0);
  4382. if (ret < 0)
  4383. goto bad_inode;
  4384. raw_inode = ext4_raw_inode(&iloc);
  4385. inode->i_mode = le16_to_cpu(raw_inode->i_mode);
  4386. inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
  4387. inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
  4388. if (!(test_opt(inode->i_sb, NO_UID32))) {
  4389. inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
  4390. inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
  4391. }
  4392. inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
  4393. ei->i_state_flags = 0;
  4394. ei->i_dir_start_lookup = 0;
  4395. ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
  4396. /* We now have enough fields to check if the inode was active or not.
  4397. * This is needed because nfsd might try to access dead inodes
  4398. * the test is that same one that e2fsck uses
  4399. * NeilBrown 1999oct15
  4400. */
  4401. if (inode->i_nlink == 0) {
  4402. if (inode->i_mode == 0 ||
  4403. !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
  4404. /* this inode is deleted */
  4405. ret = -ESTALE;
  4406. goto bad_inode;
  4407. }
  4408. /* The only unlinked inodes we let through here have
  4409. * valid i_mode and are being read by the orphan
  4410. * recovery code: that's fine, we're about to complete
  4411. * the process of deleting those. */
  4412. }
  4413. ei->i_flags = le32_to_cpu(raw_inode->i_flags);
  4414. inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
  4415. ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
  4416. if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
  4417. ei->i_file_acl |=
  4418. ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
  4419. inode->i_size = ext4_isize(raw_inode);
  4420. ei->i_disksize = inode->i_size;
  4421. #ifdef CONFIG_QUOTA
  4422. ei->i_reserved_quota = 0;
  4423. #endif
  4424. inode->i_generation = le32_to_cpu(raw_inode->i_generation);
  4425. ei->i_block_group = iloc.block_group;
  4426. ei->i_last_alloc_group = ~0;
  4427. /*
  4428. * NOTE! The in-memory inode i_data array is in little-endian order
  4429. * even on big-endian machines: we do NOT byteswap the block numbers!
  4430. */
  4431. for (block = 0; block < EXT4_N_BLOCKS; block++)
  4432. ei->i_data[block] = raw_inode->i_block[block];
  4433. INIT_LIST_HEAD(&ei->i_orphan);
  4434. /*
  4435. * Set transaction id's of transactions that have to be committed
  4436. * to finish f[data]sync. We set them to currently running transaction
  4437. * as we cannot be sure that the inode or some of its metadata isn't
  4438. * part of the transaction - the inode could have been reclaimed and
  4439. * now it is reread from disk.
  4440. */
  4441. if (journal) {
  4442. transaction_t *transaction;
  4443. tid_t tid;
  4444. read_lock(&journal->j_state_lock);
  4445. if (journal->j_running_transaction)
  4446. transaction = journal->j_running_transaction;
  4447. else
  4448. transaction = journal->j_committing_transaction;
  4449. if (transaction)
  4450. tid = transaction->t_tid;
  4451. else
  4452. tid = journal->j_commit_sequence;
  4453. read_unlock(&journal->j_state_lock);
  4454. ei->i_sync_tid = tid;
  4455. ei->i_datasync_tid = tid;
  4456. }
  4457. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  4458. ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
  4459. if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
  4460. EXT4_INODE_SIZE(inode->i_sb)) {
  4461. ret = -EIO;
  4462. goto bad_inode;
  4463. }
  4464. if (ei->i_extra_isize == 0) {
  4465. /* The extra space is currently unused. Use it. */
  4466. ei->i_extra_isize = sizeof(struct ext4_inode) -
  4467. EXT4_GOOD_OLD_INODE_SIZE;
  4468. } else {
  4469. __le32 *magic = (void *)raw_inode +
  4470. EXT4_GOOD_OLD_INODE_SIZE +
  4471. ei->i_extra_isize;
  4472. if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
  4473. ext4_set_inode_state(inode, EXT4_STATE_XATTR);
  4474. }
  4475. } else
  4476. ei->i_extra_isize = 0;
  4477. EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
  4478. EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
  4479. EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
  4480. EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
  4481. inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
  4482. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  4483. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  4484. inode->i_version |=
  4485. (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
  4486. }
  4487. ret = 0;
  4488. if (ei->i_file_acl &&
  4489. !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
  4490. EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
  4491. ei->i_file_acl);
  4492. ret = -EIO;
  4493. goto bad_inode;
  4494. } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  4495. if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
  4496. (S_ISLNK(inode->i_mode) &&
  4497. !ext4_inode_is_fast_symlink(inode)))
  4498. /* Validate extent which is part of inode */
  4499. ret = ext4_ext_check_inode(inode);
  4500. } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
  4501. (S_ISLNK(inode->i_mode) &&
  4502. !ext4_inode_is_fast_symlink(inode))) {
  4503. /* Validate block references which are part of inode */
  4504. ret = ext4_check_inode_blockref(inode);
  4505. }
  4506. if (ret)
  4507. goto bad_inode;
  4508. if (S_ISREG(inode->i_mode)) {
  4509. inode->i_op = &ext4_file_inode_operations;
  4510. inode->i_fop = &ext4_file_operations;
  4511. ext4_set_aops(inode);
  4512. } else if (S_ISDIR(inode->i_mode)) {
  4513. inode->i_op = &ext4_dir_inode_operations;
  4514. inode->i_fop = &ext4_dir_operations;
  4515. } else if (S_ISLNK(inode->i_mode)) {
  4516. if (ext4_inode_is_fast_symlink(inode)) {
  4517. inode->i_op = &ext4_fast_symlink_inode_operations;
  4518. nd_terminate_link(ei->i_data, inode->i_size,
  4519. sizeof(ei->i_data) - 1);
  4520. } else {
  4521. inode->i_op = &ext4_symlink_inode_operations;
  4522. ext4_set_aops(inode);
  4523. }
  4524. } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
  4525. S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
  4526. inode->i_op = &ext4_special_inode_operations;
  4527. if (raw_inode->i_block[0])
  4528. init_special_inode(inode, inode->i_mode,
  4529. old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
  4530. else
  4531. init_special_inode(inode, inode->i_mode,
  4532. new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
  4533. } else {
  4534. ret = -EIO;
  4535. EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
  4536. goto bad_inode;
  4537. }
  4538. brelse(iloc.bh);
  4539. ext4_set_inode_flags(inode);
  4540. unlock_new_inode(inode);
  4541. return inode;
  4542. bad_inode:
  4543. brelse(iloc.bh);
  4544. iget_failed(inode);
  4545. return ERR_PTR(ret);
  4546. }
  4547. static int ext4_inode_blocks_set(handle_t *handle,
  4548. struct ext4_inode *raw_inode,
  4549. struct ext4_inode_info *ei)
  4550. {
  4551. struct inode *inode = &(ei->vfs_inode);
  4552. u64 i_blocks = inode->i_blocks;
  4553. struct super_block *sb = inode->i_sb;
  4554. if (i_blocks <= ~0U) {
  4555. /*
  4556. * i_blocks can be represnted in a 32 bit variable
  4557. * as multiple of 512 bytes
  4558. */
  4559. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  4560. raw_inode->i_blocks_high = 0;
  4561. ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  4562. return 0;
  4563. }
  4564. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
  4565. return -EFBIG;
  4566. if (i_blocks <= 0xffffffffffffULL) {
  4567. /*
  4568. * i_blocks can be represented in a 48 bit variable
  4569. * as multiple of 512 bytes
  4570. */
  4571. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  4572. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  4573. ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  4574. } else {
  4575. ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  4576. /* i_block is stored in file system block size */
  4577. i_blocks = i_blocks >> (inode->i_blkbits - 9);
  4578. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  4579. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  4580. }
  4581. return 0;
  4582. }
  4583. /*
  4584. * Post the struct inode info into an on-disk inode location in the
  4585. * buffer-cache. This gobbles the caller's reference to the
  4586. * buffer_head in the inode location struct.
  4587. *
  4588. * The caller must have write access to iloc->bh.
  4589. */
  4590. static int ext4_do_update_inode(handle_t *handle,
  4591. struct inode *inode,
  4592. struct ext4_iloc *iloc)
  4593. {
  4594. struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
  4595. struct ext4_inode_info *ei = EXT4_I(inode);
  4596. struct buffer_head *bh = iloc->bh;
  4597. int err = 0, rc, block;
  4598. /* For fields not not tracking in the in-memory inode,
  4599. * initialise them to zero for new inodes. */
  4600. if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
  4601. memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
  4602. ext4_get_inode_flags(ei);
  4603. raw_inode->i_mode = cpu_to_le16(inode->i_mode);
  4604. if (!(test_opt(inode->i_sb, NO_UID32))) {
  4605. raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
  4606. raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
  4607. /*
  4608. * Fix up interoperability with old kernels. Otherwise, old inodes get
  4609. * re-used with the upper 16 bits of the uid/gid intact
  4610. */
  4611. if (!ei->i_dtime) {
  4612. raw_inode->i_uid_high =
  4613. cpu_to_le16(high_16_bits(inode->i_uid));
  4614. raw_inode->i_gid_high =
  4615. cpu_to_le16(high_16_bits(inode->i_gid));
  4616. } else {
  4617. raw_inode->i_uid_high = 0;
  4618. raw_inode->i_gid_high = 0;
  4619. }
  4620. } else {
  4621. raw_inode->i_uid_low =
  4622. cpu_to_le16(fs_high2lowuid(inode->i_uid));
  4623. raw_inode->i_gid_low =
  4624. cpu_to_le16(fs_high2lowgid(inode->i_gid));
  4625. raw_inode->i_uid_high = 0;
  4626. raw_inode->i_gid_high = 0;
  4627. }
  4628. raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
  4629. EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
  4630. EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
  4631. EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
  4632. EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
  4633. if (ext4_inode_blocks_set(handle, raw_inode, ei))
  4634. goto out_brelse;
  4635. raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
  4636. raw_inode->i_flags = cpu_to_le32(ei->i_flags);
  4637. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  4638. cpu_to_le32(EXT4_OS_HURD))
  4639. raw_inode->i_file_acl_high =
  4640. cpu_to_le16(ei->i_file_acl >> 32);
  4641. raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
  4642. ext4_isize_set(raw_inode, ei->i_disksize);
  4643. if (ei->i_disksize > 0x7fffffffULL) {
  4644. struct super_block *sb = inode->i_sb;
  4645. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
  4646. EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
  4647. EXT4_SB(sb)->s_es->s_rev_level ==
  4648. cpu_to_le32(EXT4_GOOD_OLD_REV)) {
  4649. /* If this is the first large file
  4650. * created, add a flag to the superblock.
  4651. */
  4652. err = ext4_journal_get_write_access(handle,
  4653. EXT4_SB(sb)->s_sbh);
  4654. if (err)
  4655. goto out_brelse;
  4656. ext4_update_dynamic_rev(sb);
  4657. EXT4_SET_RO_COMPAT_FEATURE(sb,
  4658. EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
  4659. sb->s_dirt = 1;
  4660. ext4_handle_sync(handle);
  4661. err = ext4_handle_dirty_metadata(handle, NULL,
  4662. EXT4_SB(sb)->s_sbh);
  4663. }
  4664. }
  4665. raw_inode->i_generation = cpu_to_le32(inode->i_generation);
  4666. if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
  4667. if (old_valid_dev(inode->i_rdev)) {
  4668. raw_inode->i_block[0] =
  4669. cpu_to_le32(old_encode_dev(inode->i_rdev));
  4670. raw_inode->i_block[1] = 0;
  4671. } else {
  4672. raw_inode->i_block[0] = 0;
  4673. raw_inode->i_block[1] =
  4674. cpu_to_le32(new_encode_dev(inode->i_rdev));
  4675. raw_inode->i_block[2] = 0;
  4676. }
  4677. } else
  4678. for (block = 0; block < EXT4_N_BLOCKS; block++)
  4679. raw_inode->i_block[block] = ei->i_data[block];
  4680. raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
  4681. if (ei->i_extra_isize) {
  4682. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  4683. raw_inode->i_version_hi =
  4684. cpu_to_le32(inode->i_version >> 32);
  4685. raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
  4686. }
  4687. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  4688. rc = ext4_handle_dirty_metadata(handle, NULL, bh);
  4689. if (!err)
  4690. err = rc;
  4691. ext4_clear_inode_state(inode, EXT4_STATE_NEW);
  4692. ext4_update_inode_fsync_trans(handle, inode, 0);
  4693. out_brelse:
  4694. brelse(bh);
  4695. ext4_std_error(inode->i_sb, err);
  4696. return err;
  4697. }
  4698. /*
  4699. * ext4_write_inode()
  4700. *
  4701. * We are called from a few places:
  4702. *
  4703. * - Within generic_file_write() for O_SYNC files.
  4704. * Here, there will be no transaction running. We wait for any running
  4705. * trasnaction to commit.
  4706. *
  4707. * - Within sys_sync(), kupdate and such.
  4708. * We wait on commit, if tol to.
  4709. *
  4710. * - Within prune_icache() (PF_MEMALLOC == true)
  4711. * Here we simply return. We can't afford to block kswapd on the
  4712. * journal commit.
  4713. *
  4714. * In all cases it is actually safe for us to return without doing anything,
  4715. * because the inode has been copied into a raw inode buffer in
  4716. * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
  4717. * knfsd.
  4718. *
  4719. * Note that we are absolutely dependent upon all inode dirtiers doing the
  4720. * right thing: they *must* call mark_inode_dirty() after dirtying info in
  4721. * which we are interested.
  4722. *
  4723. * It would be a bug for them to not do this. The code:
  4724. *
  4725. * mark_inode_dirty(inode)
  4726. * stuff();
  4727. * inode->i_size = expr;
  4728. *
  4729. * is in error because a kswapd-driven write_inode() could occur while
  4730. * `stuff()' is running, and the new i_size will be lost. Plus the inode
  4731. * will no longer be on the superblock's dirty inode list.
  4732. */
  4733. int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
  4734. {
  4735. int err;
  4736. if (current->flags & PF_MEMALLOC)
  4737. return 0;
  4738. if (EXT4_SB(inode->i_sb)->s_journal) {
  4739. if (ext4_journal_current_handle()) {
  4740. jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
  4741. dump_stack();
  4742. return -EIO;
  4743. }
  4744. if (wbc->sync_mode != WB_SYNC_ALL)
  4745. return 0;
  4746. err = ext4_force_commit(inode->i_sb);
  4747. } else {
  4748. struct ext4_iloc iloc;
  4749. err = __ext4_get_inode_loc(inode, &iloc, 0);
  4750. if (err)
  4751. return err;
  4752. if (wbc->sync_mode == WB_SYNC_ALL)
  4753. sync_dirty_buffer(iloc.bh);
  4754. if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
  4755. EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
  4756. "IO error syncing inode");
  4757. err = -EIO;
  4758. }
  4759. brelse(iloc.bh);
  4760. }
  4761. return err;
  4762. }
  4763. /*
  4764. * ext4_setattr()
  4765. *
  4766. * Called from notify_change.
  4767. *
  4768. * We want to trap VFS attempts to truncate the file as soon as
  4769. * possible. In particular, we want to make sure that when the VFS
  4770. * shrinks i_size, we put the inode on the orphan list and modify
  4771. * i_disksize immediately, so that during the subsequent flushing of
  4772. * dirty pages and freeing of disk blocks, we can guarantee that any
  4773. * commit will leave the blocks being flushed in an unused state on
  4774. * disk. (On recovery, the inode will get truncated and the blocks will
  4775. * be freed, so we have a strong guarantee that no future commit will
  4776. * leave these blocks visible to the user.)
  4777. *
  4778. * Another thing we have to assure is that if we are in ordered mode
  4779. * and inode is still attached to the committing transaction, we must
  4780. * we start writeout of all the dirty pages which are being truncated.
  4781. * This way we are sure that all the data written in the previous
  4782. * transaction are already on disk (truncate waits for pages under
  4783. * writeback).
  4784. *
  4785. * Called with inode->i_mutex down.
  4786. */
  4787. int ext4_setattr(struct dentry *dentry, struct iattr *attr)
  4788. {
  4789. struct inode *inode = dentry->d_inode;
  4790. int error, rc = 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. error = ext4_orphan_add(handle, inode);
  4840. EXT4_I(inode)->i_disksize = attr->ia_size;
  4841. rc = ext4_mark_inode_dirty(handle, inode);
  4842. if (!error)
  4843. error = rc;
  4844. ext4_journal_stop(handle);
  4845. if (ext4_should_order_data(inode)) {
  4846. error = ext4_begin_ordered_truncate(inode,
  4847. attr->ia_size);
  4848. if (error) {
  4849. /* Do as much error cleanup as possible */
  4850. handle = ext4_journal_start(inode, 3);
  4851. if (IS_ERR(handle)) {
  4852. ext4_orphan_del(NULL, inode);
  4853. goto err_out;
  4854. }
  4855. ext4_orphan_del(handle, inode);
  4856. ext4_journal_stop(handle);
  4857. goto err_out;
  4858. }
  4859. }
  4860. /* ext4_truncate will clear the flag */
  4861. if ((ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS)))
  4862. ext4_truncate(inode);
  4863. }
  4864. if ((attr->ia_valid & ATTR_SIZE) &&
  4865. attr->ia_size != i_size_read(inode))
  4866. rc = vmtruncate(inode, attr->ia_size);
  4867. if (!rc) {
  4868. setattr_copy(inode, attr);
  4869. mark_inode_dirty(inode);
  4870. }
  4871. /*
  4872. * If the call to ext4_truncate failed to get a transaction handle at
  4873. * all, we need to clean up the in-core orphan list manually.
  4874. */
  4875. if (inode->i_nlink)
  4876. ext4_orphan_del(NULL, inode);
  4877. if (!rc && (ia_valid & ATTR_MODE))
  4878. rc = ext4_acl_chmod(inode);
  4879. err_out:
  4880. ext4_std_error(inode->i_sb, error);
  4881. if (!error)
  4882. error = rc;
  4883. return error;
  4884. }
  4885. int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
  4886. struct kstat *stat)
  4887. {
  4888. struct inode *inode;
  4889. unsigned long delalloc_blocks;
  4890. inode = dentry->d_inode;
  4891. generic_fillattr(inode, stat);
  4892. /*
  4893. * We can't update i_blocks if the block allocation is delayed
  4894. * otherwise in the case of system crash before the real block
  4895. * allocation is done, we will have i_blocks inconsistent with
  4896. * on-disk file blocks.
  4897. * We always keep i_blocks updated together with real
  4898. * allocation. But to not confuse with user, stat
  4899. * will return the blocks that include the delayed allocation
  4900. * blocks for this file.
  4901. */
  4902. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  4903. delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  4904. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  4905. stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
  4906. return 0;
  4907. }
  4908. static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
  4909. int chunk)
  4910. {
  4911. int indirects;
  4912. /* if nrblocks are contiguous */
  4913. if (chunk) {
  4914. /*
  4915. * With N contiguous data blocks, it need at most
  4916. * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
  4917. * 2 dindirect blocks
  4918. * 1 tindirect block
  4919. */
  4920. indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
  4921. return indirects + 3;
  4922. }
  4923. /*
  4924. * if nrblocks are not contiguous, worse case, each block touch
  4925. * a indirect block, and each indirect block touch a double indirect
  4926. * block, plus a triple indirect block
  4927. */
  4928. indirects = nrblocks * 2 + 1;
  4929. return indirects;
  4930. }
  4931. static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  4932. {
  4933. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
  4934. return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
  4935. return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
  4936. }
  4937. /*
  4938. * Account for index blocks, block groups bitmaps and block group
  4939. * descriptor blocks if modify datablocks and index blocks
  4940. * worse case, the indexs blocks spread over different block groups
  4941. *
  4942. * If datablocks are discontiguous, they are possible to spread over
  4943. * different block groups too. If they are contiuguous, with flexbg,
  4944. * they could still across block group boundary.
  4945. *
  4946. * Also account for superblock, inode, quota and xattr blocks
  4947. */
  4948. static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  4949. {
  4950. ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
  4951. int gdpblocks;
  4952. int idxblocks;
  4953. int ret = 0;
  4954. /*
  4955. * How many index blocks need to touch to modify nrblocks?
  4956. * The "Chunk" flag indicating whether the nrblocks is
  4957. * physically contiguous on disk
  4958. *
  4959. * For Direct IO and fallocate, they calls get_block to allocate
  4960. * one single extent at a time, so they could set the "Chunk" flag
  4961. */
  4962. idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
  4963. ret = idxblocks;
  4964. /*
  4965. * Now let's see how many group bitmaps and group descriptors need
  4966. * to account
  4967. */
  4968. groups = idxblocks;
  4969. if (chunk)
  4970. groups += 1;
  4971. else
  4972. groups += nrblocks;
  4973. gdpblocks = groups;
  4974. if (groups > ngroups)
  4975. groups = ngroups;
  4976. if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
  4977. gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
  4978. /* bitmaps and block group descriptor blocks */
  4979. ret += groups + gdpblocks;
  4980. /* Blocks for super block, inode, quota and xattr blocks */
  4981. ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
  4982. return ret;
  4983. }
  4984. /*
  4985. * Calulate the total number of credits to reserve to fit
  4986. * the modification of a single pages into a single transaction,
  4987. * which may include multiple chunks of block allocations.
  4988. *
  4989. * This could be called via ext4_write_begin()
  4990. *
  4991. * We need to consider the worse case, when
  4992. * one new block per extent.
  4993. */
  4994. int ext4_writepage_trans_blocks(struct inode *inode)
  4995. {
  4996. int bpp = ext4_journal_blocks_per_page(inode);
  4997. int ret;
  4998. ret = ext4_meta_trans_blocks(inode, bpp, 0);
  4999. /* Account for data blocks for journalled mode */
  5000. if (ext4_should_journal_data(inode))
  5001. ret += bpp;
  5002. return ret;
  5003. }
  5004. /*
  5005. * Calculate the journal credits for a chunk of data modification.
  5006. *
  5007. * This is called from DIO, fallocate or whoever calling
  5008. * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
  5009. *
  5010. * journal buffers for data blocks are not included here, as DIO
  5011. * and fallocate do no need to journal data buffers.
  5012. */
  5013. int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
  5014. {
  5015. return ext4_meta_trans_blocks(inode, nrblocks, 1);
  5016. }
  5017. /*
  5018. * The caller must have previously called ext4_reserve_inode_write().
  5019. * Give this, we know that the caller already has write access to iloc->bh.
  5020. */
  5021. int ext4_mark_iloc_dirty(handle_t *handle,
  5022. struct inode *inode, struct ext4_iloc *iloc)
  5023. {
  5024. int err = 0;
  5025. if (test_opt(inode->i_sb, I_VERSION))
  5026. inode_inc_iversion(inode);
  5027. /* the do_update_inode consumes one bh->b_count */
  5028. get_bh(iloc->bh);
  5029. /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
  5030. err = ext4_do_update_inode(handle, inode, iloc);
  5031. put_bh(iloc->bh);
  5032. return err;
  5033. }
  5034. /*
  5035. * On success, We end up with an outstanding reference count against
  5036. * iloc->bh. This _must_ be cleaned up later.
  5037. */
  5038. int
  5039. ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
  5040. struct ext4_iloc *iloc)
  5041. {
  5042. int err;
  5043. err = ext4_get_inode_loc(inode, iloc);
  5044. if (!err) {
  5045. BUFFER_TRACE(iloc->bh, "get_write_access");
  5046. err = ext4_journal_get_write_access(handle, iloc->bh);
  5047. if (err) {
  5048. brelse(iloc->bh);
  5049. iloc->bh = NULL;
  5050. }
  5051. }
  5052. ext4_std_error(inode->i_sb, err);
  5053. return err;
  5054. }
  5055. /*
  5056. * Expand an inode by new_extra_isize bytes.
  5057. * Returns 0 on success or negative error number on failure.
  5058. */
  5059. static int ext4_expand_extra_isize(struct inode *inode,
  5060. unsigned int new_extra_isize,
  5061. struct ext4_iloc iloc,
  5062. handle_t *handle)
  5063. {
  5064. struct ext4_inode *raw_inode;
  5065. struct ext4_xattr_ibody_header *header;
  5066. if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
  5067. return 0;
  5068. raw_inode = ext4_raw_inode(&iloc);
  5069. header = IHDR(inode, raw_inode);
  5070. /* No extended attributes present */
  5071. if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
  5072. header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
  5073. memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
  5074. new_extra_isize);
  5075. EXT4_I(inode)->i_extra_isize = new_extra_isize;
  5076. return 0;
  5077. }
  5078. /* try to expand with EAs present */
  5079. return ext4_expand_extra_isize_ea(inode, new_extra_isize,
  5080. raw_inode, handle);
  5081. }
  5082. /*
  5083. * What we do here is to mark the in-core inode as clean with respect to inode
  5084. * dirtiness (it may still be data-dirty).
  5085. * This means that the in-core inode may be reaped by prune_icache
  5086. * without having to perform any I/O. This is a very good thing,
  5087. * because *any* task may call prune_icache - even ones which
  5088. * have a transaction open against a different journal.
  5089. *
  5090. * Is this cheating? Not really. Sure, we haven't written the
  5091. * inode out, but prune_icache isn't a user-visible syncing function.
  5092. * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
  5093. * we start and wait on commits.
  5094. *
  5095. * Is this efficient/effective? Well, we're being nice to the system
  5096. * by cleaning up our inodes proactively so they can be reaped
  5097. * without I/O. But we are potentially leaving up to five seconds'
  5098. * worth of inodes floating about which prune_icache wants us to
  5099. * write out. One way to fix that would be to get prune_icache()
  5100. * to do a write_super() to free up some memory. It has the desired
  5101. * effect.
  5102. */
  5103. int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
  5104. {
  5105. struct ext4_iloc iloc;
  5106. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  5107. static unsigned int mnt_count;
  5108. int err, ret;
  5109. might_sleep();
  5110. err = ext4_reserve_inode_write(handle, inode, &iloc);
  5111. if (ext4_handle_valid(handle) &&
  5112. EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
  5113. !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
  5114. /*
  5115. * We need extra buffer credits since we may write into EA block
  5116. * with this same handle. If journal_extend fails, then it will
  5117. * only result in a minor loss of functionality for that inode.
  5118. * If this is felt to be critical, then e2fsck should be run to
  5119. * force a large enough s_min_extra_isize.
  5120. */
  5121. if ((jbd2_journal_extend(handle,
  5122. EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
  5123. ret = ext4_expand_extra_isize(inode,
  5124. sbi->s_want_extra_isize,
  5125. iloc, handle);
  5126. if (ret) {
  5127. ext4_set_inode_state(inode,
  5128. EXT4_STATE_NO_EXPAND);
  5129. if (mnt_count !=
  5130. le16_to_cpu(sbi->s_es->s_mnt_count)) {
  5131. ext4_warning(inode->i_sb,
  5132. "Unable to expand inode %lu. Delete"
  5133. " some EAs or run e2fsck.",
  5134. inode->i_ino);
  5135. mnt_count =
  5136. le16_to_cpu(sbi->s_es->s_mnt_count);
  5137. }
  5138. }
  5139. }
  5140. }
  5141. if (!err)
  5142. err = ext4_mark_iloc_dirty(handle, inode, &iloc);
  5143. return err;
  5144. }
  5145. /*
  5146. * ext4_dirty_inode() is called from __mark_inode_dirty()
  5147. *
  5148. * We're really interested in the case where a file is being extended.
  5149. * i_size has been changed by generic_commit_write() and we thus need
  5150. * to include the updated inode in the current transaction.
  5151. *
  5152. * Also, dquot_alloc_block() will always dirty the inode when blocks
  5153. * are allocated to the file.
  5154. *
  5155. * If the inode is marked synchronous, we don't honour that here - doing
  5156. * so would cause a commit on atime updates, which we don't bother doing.
  5157. * We handle synchronous inodes at the highest possible level.
  5158. */
  5159. void ext4_dirty_inode(struct inode *inode)
  5160. {
  5161. handle_t *handle;
  5162. handle = ext4_journal_start(inode, 2);
  5163. if (IS_ERR(handle))
  5164. goto out;
  5165. ext4_mark_inode_dirty(handle, inode);
  5166. ext4_journal_stop(handle);
  5167. out:
  5168. return;
  5169. }
  5170. #if 0
  5171. /*
  5172. * Bind an inode's backing buffer_head into this transaction, to prevent
  5173. * it from being flushed to disk early. Unlike
  5174. * ext4_reserve_inode_write, this leaves behind no bh reference and
  5175. * returns no iloc structure, so the caller needs to repeat the iloc
  5176. * lookup to mark the inode dirty later.
  5177. */
  5178. static int ext4_pin_inode(handle_t *handle, struct inode *inode)
  5179. {
  5180. struct ext4_iloc iloc;
  5181. int err = 0;
  5182. if (handle) {
  5183. err = ext4_get_inode_loc(inode, &iloc);
  5184. if (!err) {
  5185. BUFFER_TRACE(iloc.bh, "get_write_access");
  5186. err = jbd2_journal_get_write_access(handle, iloc.bh);
  5187. if (!err)
  5188. err = ext4_handle_dirty_metadata(handle,
  5189. NULL,
  5190. iloc.bh);
  5191. brelse(iloc.bh);
  5192. }
  5193. }
  5194. ext4_std_error(inode->i_sb, err);
  5195. return err;
  5196. }
  5197. #endif
  5198. int ext4_change_inode_journal_flag(struct inode *inode, int val)
  5199. {
  5200. journal_t *journal;
  5201. handle_t *handle;
  5202. int err;
  5203. /*
  5204. * We have to be very careful here: changing a data block's
  5205. * journaling status dynamically is dangerous. If we write a
  5206. * data block to the journal, change the status and then delete
  5207. * that block, we risk forgetting to revoke the old log record
  5208. * from the journal and so a subsequent replay can corrupt data.
  5209. * So, first we make sure that the journal is empty and that
  5210. * nobody is changing anything.
  5211. */
  5212. journal = EXT4_JOURNAL(inode);
  5213. if (!journal)
  5214. return 0;
  5215. if (is_journal_aborted(journal))
  5216. return -EROFS;
  5217. jbd2_journal_lock_updates(journal);
  5218. jbd2_journal_flush(journal);
  5219. /*
  5220. * OK, there are no updates running now, and all cached data is
  5221. * synced to disk. We are now in a completely consistent state
  5222. * which doesn't have anything in the journal, and we know that
  5223. * no filesystem updates are running, so it is safe to modify
  5224. * the inode's in-core data-journaling state flag now.
  5225. */
  5226. if (val)
  5227. ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  5228. else
  5229. ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  5230. ext4_set_aops(inode);
  5231. jbd2_journal_unlock_updates(journal);
  5232. /* Finally we can mark the inode as dirty. */
  5233. handle = ext4_journal_start(inode, 1);
  5234. if (IS_ERR(handle))
  5235. return PTR_ERR(handle);
  5236. err = ext4_mark_inode_dirty(handle, inode);
  5237. ext4_handle_sync(handle);
  5238. ext4_journal_stop(handle);
  5239. ext4_std_error(inode->i_sb, err);
  5240. return err;
  5241. }
  5242. static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
  5243. {
  5244. return !buffer_mapped(bh);
  5245. }
  5246. int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
  5247. {
  5248. struct page *page = vmf->page;
  5249. loff_t size;
  5250. unsigned long len;
  5251. int ret = -EINVAL;
  5252. void *fsdata;
  5253. struct file *file = vma->vm_file;
  5254. struct inode *inode = file->f_path.dentry->d_inode;
  5255. struct address_space *mapping = inode->i_mapping;
  5256. /*
  5257. * Get i_alloc_sem to stop truncates messing with the inode. We cannot
  5258. * get i_mutex because we are already holding mmap_sem.
  5259. */
  5260. down_read(&inode->i_alloc_sem);
  5261. size = i_size_read(inode);
  5262. if (page->mapping != mapping || size <= page_offset(page)
  5263. || !PageUptodate(page)) {
  5264. /* page got truncated from under us? */
  5265. goto out_unlock;
  5266. }
  5267. ret = 0;
  5268. if (PageMappedToDisk(page))
  5269. goto out_unlock;
  5270. if (page->index == size >> PAGE_CACHE_SHIFT)
  5271. len = size & ~PAGE_CACHE_MASK;
  5272. else
  5273. len = PAGE_CACHE_SIZE;
  5274. lock_page(page);
  5275. /*
  5276. * return if we have all the buffers mapped. This avoid
  5277. * the need to call write_begin/write_end which does a
  5278. * journal_start/journal_stop which can block and take
  5279. * long time
  5280. */
  5281. if (page_has_buffers(page)) {
  5282. if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  5283. ext4_bh_unmapped)) {
  5284. unlock_page(page);
  5285. goto out_unlock;
  5286. }
  5287. }
  5288. unlock_page(page);
  5289. /*
  5290. * OK, we need to fill the hole... Do write_begin write_end
  5291. * to do block allocation/reservation.We are not holding
  5292. * inode.i__mutex here. That allow * parallel write_begin,
  5293. * write_end call. lock_page prevent this from happening
  5294. * on the same page though
  5295. */
  5296. ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
  5297. len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
  5298. if (ret < 0)
  5299. goto out_unlock;
  5300. ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
  5301. len, len, page, fsdata);
  5302. if (ret < 0)
  5303. goto out_unlock;
  5304. ret = 0;
  5305. out_unlock:
  5306. if (ret)
  5307. ret = VM_FAULT_SIGBUS;
  5308. up_read(&inode->i_alloc_sem);
  5309. return ret;
  5310. }