inode.c 166 KB

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