inode.c 132 KB

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