inode.c 155 KB

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