inode.c 157 KB

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