inode.c 142 KB

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