inode.c 168 KB

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