inode.c 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003
  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. long pages_skipped;
  1483. BUG_ON(mpd->next_page <= mpd->first_page);
  1484. pagevec_init(&pvec, 0);
  1485. index = mpd->first_page;
  1486. end = mpd->next_page - 1;
  1487. while (index <= end) {
  1488. /*
  1489. * We can use PAGECACHE_TAG_DIRTY lookup here because
  1490. * even though we have cleared the dirty flag on the page
  1491. * We still keep the page in the radix tree with tag
  1492. * PAGECACHE_TAG_DIRTY. See clear_page_dirty_for_io.
  1493. * The PAGECACHE_TAG_DIRTY is cleared in set_page_writeback
  1494. * which is called via the below writepage callback.
  1495. */
  1496. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
  1497. PAGECACHE_TAG_DIRTY,
  1498. min(end - index,
  1499. (pgoff_t)PAGEVEC_SIZE-1) + 1);
  1500. if (nr_pages == 0)
  1501. break;
  1502. for (i = 0; i < nr_pages; i++) {
  1503. struct page *page = pvec.pages[i];
  1504. pages_skipped = mpd->wbc->pages_skipped;
  1505. err = mapping->a_ops->writepage(page, mpd->wbc);
  1506. if (!err && (pages_skipped == mpd->wbc->pages_skipped))
  1507. /*
  1508. * have successfully written the page
  1509. * without skipping the same
  1510. */
  1511. mpd->pages_written++;
  1512. /*
  1513. * In error case, we have to continue because
  1514. * remaining pages are still locked
  1515. * XXX: unlock and re-dirty them?
  1516. */
  1517. if (ret == 0)
  1518. ret = err;
  1519. }
  1520. pagevec_release(&pvec);
  1521. }
  1522. return ret;
  1523. }
  1524. /*
  1525. * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
  1526. *
  1527. * @mpd->inode - inode to walk through
  1528. * @exbh->b_blocknr - first block on a disk
  1529. * @exbh->b_size - amount of space in bytes
  1530. * @logical - first logical block to start assignment with
  1531. *
  1532. * the function goes through all passed space and put actual disk
  1533. * block numbers into buffer heads, dropping BH_Delay
  1534. */
  1535. static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
  1536. struct buffer_head *exbh)
  1537. {
  1538. struct inode *inode = mpd->inode;
  1539. struct address_space *mapping = inode->i_mapping;
  1540. int blocks = exbh->b_size >> inode->i_blkbits;
  1541. sector_t pblock = exbh->b_blocknr, cur_logical;
  1542. struct buffer_head *head, *bh;
  1543. pgoff_t index, end;
  1544. struct pagevec pvec;
  1545. int nr_pages, i;
  1546. index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1547. end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1548. cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1549. pagevec_init(&pvec, 0);
  1550. while (index <= end) {
  1551. /* XXX: optimize tail */
  1552. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1553. if (nr_pages == 0)
  1554. break;
  1555. for (i = 0; i < nr_pages; i++) {
  1556. struct page *page = pvec.pages[i];
  1557. index = page->index;
  1558. if (index > end)
  1559. break;
  1560. index++;
  1561. BUG_ON(!PageLocked(page));
  1562. BUG_ON(PageWriteback(page));
  1563. BUG_ON(!page_has_buffers(page));
  1564. bh = page_buffers(page);
  1565. head = bh;
  1566. /* skip blocks out of the range */
  1567. do {
  1568. if (cur_logical >= logical)
  1569. break;
  1570. cur_logical++;
  1571. } while ((bh = bh->b_this_page) != head);
  1572. do {
  1573. if (cur_logical >= logical + blocks)
  1574. break;
  1575. if (buffer_delay(bh)) {
  1576. bh->b_blocknr = pblock;
  1577. clear_buffer_delay(bh);
  1578. bh->b_bdev = inode->i_sb->s_bdev;
  1579. } else if (buffer_unwritten(bh)) {
  1580. bh->b_blocknr = pblock;
  1581. clear_buffer_unwritten(bh);
  1582. set_buffer_mapped(bh);
  1583. set_buffer_new(bh);
  1584. bh->b_bdev = inode->i_sb->s_bdev;
  1585. } else if (buffer_mapped(bh))
  1586. BUG_ON(bh->b_blocknr != pblock);
  1587. cur_logical++;
  1588. pblock++;
  1589. } while ((bh = bh->b_this_page) != head);
  1590. }
  1591. pagevec_release(&pvec);
  1592. }
  1593. }
  1594. /*
  1595. * __unmap_underlying_blocks - just a helper function to unmap
  1596. * set of blocks described by @bh
  1597. */
  1598. static inline void __unmap_underlying_blocks(struct inode *inode,
  1599. struct buffer_head *bh)
  1600. {
  1601. struct block_device *bdev = inode->i_sb->s_bdev;
  1602. int blocks, i;
  1603. blocks = bh->b_size >> inode->i_blkbits;
  1604. for (i = 0; i < blocks; i++)
  1605. unmap_underlying_metadata(bdev, bh->b_blocknr + i);
  1606. }
  1607. static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
  1608. sector_t logical, long blk_cnt)
  1609. {
  1610. int nr_pages, i;
  1611. pgoff_t index, end;
  1612. struct pagevec pvec;
  1613. struct inode *inode = mpd->inode;
  1614. struct address_space *mapping = inode->i_mapping;
  1615. index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1616. end = (logical + blk_cnt - 1) >>
  1617. (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1618. while (index <= end) {
  1619. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1620. if (nr_pages == 0)
  1621. break;
  1622. for (i = 0; i < nr_pages; i++) {
  1623. struct page *page = pvec.pages[i];
  1624. index = page->index;
  1625. if (index > end)
  1626. break;
  1627. index++;
  1628. BUG_ON(!PageLocked(page));
  1629. BUG_ON(PageWriteback(page));
  1630. block_invalidatepage(page, 0);
  1631. ClearPageUptodate(page);
  1632. unlock_page(page);
  1633. }
  1634. }
  1635. return;
  1636. }
  1637. static void ext4_print_free_blocks(struct inode *inode)
  1638. {
  1639. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1640. printk(KERN_EMERG "Total free blocks count %lld\n",
  1641. ext4_count_free_blocks(inode->i_sb));
  1642. printk(KERN_EMERG "Free/Dirty block details\n");
  1643. printk(KERN_EMERG "free_blocks=%lld\n",
  1644. percpu_counter_sum(&sbi->s_freeblocks_counter));
  1645. printk(KERN_EMERG "dirty_blocks=%lld\n",
  1646. percpu_counter_sum(&sbi->s_dirtyblocks_counter));
  1647. printk(KERN_EMERG "Block reservation details\n");
  1648. printk(KERN_EMERG "i_reserved_data_blocks=%lu\n",
  1649. EXT4_I(inode)->i_reserved_data_blocks);
  1650. printk(KERN_EMERG "i_reserved_meta_blocks=%lu\n",
  1651. EXT4_I(inode)->i_reserved_meta_blocks);
  1652. return;
  1653. }
  1654. /*
  1655. * mpage_da_map_blocks - go through given space
  1656. *
  1657. * @mpd->lbh - bh describing space
  1658. * @mpd->get_block - the filesystem's block mapper function
  1659. *
  1660. * The function skips space we know is already mapped to disk blocks.
  1661. *
  1662. */
  1663. static int mpage_da_map_blocks(struct mpage_da_data *mpd)
  1664. {
  1665. int err = 0;
  1666. struct buffer_head new;
  1667. struct buffer_head *lbh = &mpd->lbh;
  1668. sector_t next;
  1669. /*
  1670. * We consider only non-mapped and non-allocated blocks
  1671. */
  1672. if (buffer_mapped(lbh) && !buffer_delay(lbh))
  1673. return 0;
  1674. new.b_state = lbh->b_state;
  1675. new.b_blocknr = 0;
  1676. new.b_size = lbh->b_size;
  1677. next = lbh->b_blocknr;
  1678. /*
  1679. * If we didn't accumulate anything
  1680. * to write simply return
  1681. */
  1682. if (!new.b_size)
  1683. return 0;
  1684. err = mpd->get_block(mpd->inode, next, &new, 1);
  1685. if (err) {
  1686. /* If get block returns with error
  1687. * we simply return. Later writepage
  1688. * will redirty the page and writepages
  1689. * will find the dirty page again
  1690. */
  1691. if (err == -EAGAIN)
  1692. return 0;
  1693. if (err == -ENOSPC &&
  1694. ext4_count_free_blocks(mpd->inode->i_sb)) {
  1695. mpd->retval = err;
  1696. return 0;
  1697. }
  1698. /*
  1699. * get block failure will cause us
  1700. * to loop in writepages. Because
  1701. * a_ops->writepage won't be able to
  1702. * make progress. The page will be redirtied
  1703. * by writepage and writepages will again
  1704. * try to write the same.
  1705. */
  1706. printk(KERN_EMERG "%s block allocation failed for inode %lu "
  1707. "at logical offset %llu with max blocks "
  1708. "%zd with error %d\n",
  1709. __func__, mpd->inode->i_ino,
  1710. (unsigned long long)next,
  1711. lbh->b_size >> mpd->inode->i_blkbits, err);
  1712. printk(KERN_EMERG "This should not happen.!! "
  1713. "Data will be lost\n");
  1714. if (err == -ENOSPC) {
  1715. ext4_print_free_blocks(mpd->inode);
  1716. }
  1717. /* invlaidate all the pages */
  1718. ext4_da_block_invalidatepages(mpd, next,
  1719. lbh->b_size >> mpd->inode->i_blkbits);
  1720. return err;
  1721. }
  1722. BUG_ON(new.b_size == 0);
  1723. if (buffer_new(&new))
  1724. __unmap_underlying_blocks(mpd->inode, &new);
  1725. /*
  1726. * If blocks are delayed marked, we need to
  1727. * put actual blocknr and drop delayed bit
  1728. */
  1729. if (buffer_delay(lbh) || buffer_unwritten(lbh))
  1730. mpage_put_bnr_to_bhs(mpd, next, &new);
  1731. return 0;
  1732. }
  1733. #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
  1734. (1 << BH_Delay) | (1 << BH_Unwritten))
  1735. /*
  1736. * mpage_add_bh_to_extent - try to add one more block to extent of blocks
  1737. *
  1738. * @mpd->lbh - extent of blocks
  1739. * @logical - logical number of the block in the file
  1740. * @bh - bh of the block (used to access block's state)
  1741. *
  1742. * the function is used to collect contig. blocks in same state
  1743. */
  1744. static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
  1745. sector_t logical, struct buffer_head *bh)
  1746. {
  1747. sector_t next;
  1748. size_t b_size = bh->b_size;
  1749. struct buffer_head *lbh = &mpd->lbh;
  1750. int nrblocks = lbh->b_size >> mpd->inode->i_blkbits;
  1751. /* check if thereserved journal credits might overflow */
  1752. if (!(EXT4_I(mpd->inode)->i_flags & EXT4_EXTENTS_FL)) {
  1753. if (nrblocks >= EXT4_MAX_TRANS_DATA) {
  1754. /*
  1755. * With non-extent format we are limited by the journal
  1756. * credit available. Total credit needed to insert
  1757. * nrblocks contiguous blocks is dependent on the
  1758. * nrblocks. So limit nrblocks.
  1759. */
  1760. goto flush_it;
  1761. } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
  1762. EXT4_MAX_TRANS_DATA) {
  1763. /*
  1764. * Adding the new buffer_head would make it cross the
  1765. * allowed limit for which we have journal credit
  1766. * reserved. So limit the new bh->b_size
  1767. */
  1768. b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
  1769. mpd->inode->i_blkbits;
  1770. /* we will do mpage_da_submit_io in the next loop */
  1771. }
  1772. }
  1773. /*
  1774. * First block in the extent
  1775. */
  1776. if (lbh->b_size == 0) {
  1777. lbh->b_blocknr = logical;
  1778. lbh->b_size = b_size;
  1779. lbh->b_state = bh->b_state & BH_FLAGS;
  1780. return;
  1781. }
  1782. next = lbh->b_blocknr + nrblocks;
  1783. /*
  1784. * Can we merge the block to our big extent?
  1785. */
  1786. if (logical == next && (bh->b_state & BH_FLAGS) == lbh->b_state) {
  1787. lbh->b_size += b_size;
  1788. return;
  1789. }
  1790. flush_it:
  1791. /*
  1792. * We couldn't merge the block to our extent, so we
  1793. * need to flush current extent and start new one
  1794. */
  1795. if (mpage_da_map_blocks(mpd) == 0)
  1796. mpage_da_submit_io(mpd);
  1797. mpd->io_done = 1;
  1798. return;
  1799. }
  1800. /*
  1801. * __mpage_da_writepage - finds extent of pages and blocks
  1802. *
  1803. * @page: page to consider
  1804. * @wbc: not used, we just follow rules
  1805. * @data: context
  1806. *
  1807. * The function finds extents of pages and scan them for all blocks.
  1808. */
  1809. static int __mpage_da_writepage(struct page *page,
  1810. struct writeback_control *wbc, void *data)
  1811. {
  1812. struct mpage_da_data *mpd = data;
  1813. struct inode *inode = mpd->inode;
  1814. struct buffer_head *bh, *head, fake;
  1815. sector_t logical;
  1816. if (mpd->io_done) {
  1817. /*
  1818. * Rest of the page in the page_vec
  1819. * redirty then and skip then. We will
  1820. * try to to write them again after
  1821. * starting a new transaction
  1822. */
  1823. redirty_page_for_writepage(wbc, page);
  1824. unlock_page(page);
  1825. return MPAGE_DA_EXTENT_TAIL;
  1826. }
  1827. /*
  1828. * Can we merge this page to current extent?
  1829. */
  1830. if (mpd->next_page != page->index) {
  1831. /*
  1832. * Nope, we can't. So, we map non-allocated blocks
  1833. * and start IO on them using writepage()
  1834. */
  1835. if (mpd->next_page != mpd->first_page) {
  1836. if (mpage_da_map_blocks(mpd) == 0)
  1837. mpage_da_submit_io(mpd);
  1838. /*
  1839. * skip rest of the page in the page_vec
  1840. */
  1841. mpd->io_done = 1;
  1842. redirty_page_for_writepage(wbc, page);
  1843. unlock_page(page);
  1844. return MPAGE_DA_EXTENT_TAIL;
  1845. }
  1846. /*
  1847. * Start next extent of pages ...
  1848. */
  1849. mpd->first_page = page->index;
  1850. /*
  1851. * ... and blocks
  1852. */
  1853. mpd->lbh.b_size = 0;
  1854. mpd->lbh.b_state = 0;
  1855. mpd->lbh.b_blocknr = 0;
  1856. }
  1857. mpd->next_page = page->index + 1;
  1858. logical = (sector_t) page->index <<
  1859. (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1860. if (!page_has_buffers(page)) {
  1861. /*
  1862. * There is no attached buffer heads yet (mmap?)
  1863. * we treat the page asfull of dirty blocks
  1864. */
  1865. bh = &fake;
  1866. bh->b_size = PAGE_CACHE_SIZE;
  1867. bh->b_state = 0;
  1868. set_buffer_dirty(bh);
  1869. set_buffer_uptodate(bh);
  1870. mpage_add_bh_to_extent(mpd, logical, bh);
  1871. if (mpd->io_done)
  1872. return MPAGE_DA_EXTENT_TAIL;
  1873. } else {
  1874. /*
  1875. * Page with regular buffer heads, just add all dirty ones
  1876. */
  1877. head = page_buffers(page);
  1878. bh = head;
  1879. do {
  1880. BUG_ON(buffer_locked(bh));
  1881. if (buffer_dirty(bh) &&
  1882. (!buffer_mapped(bh) || buffer_delay(bh))) {
  1883. mpage_add_bh_to_extent(mpd, logical, bh);
  1884. if (mpd->io_done)
  1885. return MPAGE_DA_EXTENT_TAIL;
  1886. }
  1887. logical++;
  1888. } while ((bh = bh->b_this_page) != head);
  1889. }
  1890. return 0;
  1891. }
  1892. /*
  1893. * mpage_da_writepages - walk the list of dirty pages of the given
  1894. * address space, allocates non-allocated blocks, maps newly-allocated
  1895. * blocks to existing bhs and issue IO them
  1896. *
  1897. * @mapping: address space structure to write
  1898. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1899. * @get_block: the filesystem's block mapper function.
  1900. *
  1901. * This is a library function, which implements the writepages()
  1902. * address_space_operation.
  1903. */
  1904. static int mpage_da_writepages(struct address_space *mapping,
  1905. struct writeback_control *wbc,
  1906. struct mpage_da_data *mpd)
  1907. {
  1908. int ret;
  1909. if (!mpd->get_block)
  1910. return generic_writepages(mapping, wbc);
  1911. mpd->lbh.b_size = 0;
  1912. mpd->lbh.b_state = 0;
  1913. mpd->lbh.b_blocknr = 0;
  1914. mpd->first_page = 0;
  1915. mpd->next_page = 0;
  1916. mpd->io_done = 0;
  1917. mpd->pages_written = 0;
  1918. mpd->retval = 0;
  1919. ret = write_cache_pages(mapping, wbc, __mpage_da_writepage, mpd);
  1920. /*
  1921. * Handle last extent of pages
  1922. */
  1923. if (!mpd->io_done && mpd->next_page != mpd->first_page) {
  1924. if (mpage_da_map_blocks(mpd) == 0)
  1925. mpage_da_submit_io(mpd);
  1926. mpd->io_done = 1;
  1927. ret = MPAGE_DA_EXTENT_TAIL;
  1928. }
  1929. wbc->nr_to_write -= mpd->pages_written;
  1930. return ret;
  1931. }
  1932. /*
  1933. * this is a special callback for ->write_begin() only
  1934. * it's intention is to return mapped block or reserve space
  1935. */
  1936. static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
  1937. struct buffer_head *bh_result, int create)
  1938. {
  1939. int ret = 0;
  1940. BUG_ON(create == 0);
  1941. BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
  1942. /*
  1943. * first, we need to know whether the block is allocated already
  1944. * preallocated blocks are unmapped but should treated
  1945. * the same as allocated blocks.
  1946. */
  1947. ret = ext4_get_blocks_wrap(NULL, inode, iblock, 1, bh_result, 0, 0, 0);
  1948. if ((ret == 0) && !buffer_delay(bh_result)) {
  1949. /* the block isn't (pre)allocated yet, let's reserve space */
  1950. /*
  1951. * XXX: __block_prepare_write() unmaps passed block,
  1952. * is it OK?
  1953. */
  1954. ret = ext4_da_reserve_space(inode, 1);
  1955. if (ret)
  1956. /* not enough space to reserve */
  1957. return ret;
  1958. map_bh(bh_result, inode->i_sb, 0);
  1959. set_buffer_new(bh_result);
  1960. set_buffer_delay(bh_result);
  1961. } else if (ret > 0) {
  1962. bh_result->b_size = (ret << inode->i_blkbits);
  1963. ret = 0;
  1964. }
  1965. return ret;
  1966. }
  1967. #define EXT4_DELALLOC_RSVED 1
  1968. static int ext4_da_get_block_write(struct inode *inode, sector_t iblock,
  1969. struct buffer_head *bh_result, int create)
  1970. {
  1971. int ret;
  1972. unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
  1973. loff_t disksize = EXT4_I(inode)->i_disksize;
  1974. handle_t *handle = NULL;
  1975. handle = ext4_journal_current_handle();
  1976. BUG_ON(!handle);
  1977. ret = ext4_get_blocks_wrap(handle, inode, iblock, max_blocks,
  1978. bh_result, create, 0, EXT4_DELALLOC_RSVED);
  1979. if (ret > 0) {
  1980. bh_result->b_size = (ret << inode->i_blkbits);
  1981. if (ext4_should_order_data(inode)) {
  1982. int retval;
  1983. retval = ext4_jbd2_file_inode(handle, inode);
  1984. if (retval)
  1985. /*
  1986. * Failed to add inode for ordered
  1987. * mode. Don't update file size
  1988. */
  1989. return retval;
  1990. }
  1991. /*
  1992. * Update on-disk size along with block allocation
  1993. * we don't use 'extend_disksize' as size may change
  1994. * within already allocated block -bzzz
  1995. */
  1996. disksize = ((loff_t) iblock + ret) << inode->i_blkbits;
  1997. if (disksize > i_size_read(inode))
  1998. disksize = i_size_read(inode);
  1999. if (disksize > EXT4_I(inode)->i_disksize) {
  2000. ext4_update_i_disksize(inode, disksize);
  2001. ret = ext4_mark_inode_dirty(handle, inode);
  2002. return ret;
  2003. }
  2004. ret = 0;
  2005. }
  2006. return ret;
  2007. }
  2008. static int ext4_bh_unmapped_or_delay(handle_t *handle, struct buffer_head *bh)
  2009. {
  2010. /*
  2011. * unmapped buffer is possible for holes.
  2012. * delay buffer is possible with delayed allocation
  2013. */
  2014. return ((!buffer_mapped(bh) || buffer_delay(bh)) && buffer_dirty(bh));
  2015. }
  2016. static int ext4_normal_get_block_write(struct inode *inode, sector_t iblock,
  2017. struct buffer_head *bh_result, int create)
  2018. {
  2019. int ret = 0;
  2020. unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
  2021. /*
  2022. * we don't want to do block allocation in writepage
  2023. * so call get_block_wrap with create = 0
  2024. */
  2025. ret = ext4_get_blocks_wrap(NULL, inode, iblock, max_blocks,
  2026. bh_result, 0, 0, 0);
  2027. if (ret > 0) {
  2028. bh_result->b_size = (ret << inode->i_blkbits);
  2029. ret = 0;
  2030. }
  2031. return ret;
  2032. }
  2033. /*
  2034. * get called vi ext4_da_writepages after taking page lock (have journal handle)
  2035. * get called via journal_submit_inode_data_buffers (no journal handle)
  2036. * get called via shrink_page_list via pdflush (no journal handle)
  2037. * or grab_page_cache when doing write_begin (have journal handle)
  2038. */
  2039. static int ext4_da_writepage(struct page *page,
  2040. struct writeback_control *wbc)
  2041. {
  2042. int ret = 0;
  2043. loff_t size;
  2044. unsigned long len;
  2045. struct buffer_head *page_bufs;
  2046. struct inode *inode = page->mapping->host;
  2047. size = i_size_read(inode);
  2048. if (page->index == size >> PAGE_CACHE_SHIFT)
  2049. len = size & ~PAGE_CACHE_MASK;
  2050. else
  2051. len = PAGE_CACHE_SIZE;
  2052. if (page_has_buffers(page)) {
  2053. page_bufs = page_buffers(page);
  2054. if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  2055. ext4_bh_unmapped_or_delay)) {
  2056. /*
  2057. * We don't want to do block allocation
  2058. * So redirty the page and return
  2059. * We may reach here when we do a journal commit
  2060. * via journal_submit_inode_data_buffers.
  2061. * If we don't have mapping block we just ignore
  2062. * them. We can also reach here via shrink_page_list
  2063. */
  2064. redirty_page_for_writepage(wbc, page);
  2065. unlock_page(page);
  2066. return 0;
  2067. }
  2068. } else {
  2069. /*
  2070. * The test for page_has_buffers() is subtle:
  2071. * We know the page is dirty but it lost buffers. That means
  2072. * that at some moment in time after write_begin()/write_end()
  2073. * has been called all buffers have been clean and thus they
  2074. * must have been written at least once. So they are all
  2075. * mapped and we can happily proceed with mapping them
  2076. * and writing the page.
  2077. *
  2078. * Try to initialize the buffer_heads and check whether
  2079. * all are mapped and non delay. We don't want to
  2080. * do block allocation here.
  2081. */
  2082. ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
  2083. ext4_normal_get_block_write);
  2084. if (!ret) {
  2085. page_bufs = page_buffers(page);
  2086. /* check whether all are mapped and non delay */
  2087. if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  2088. ext4_bh_unmapped_or_delay)) {
  2089. redirty_page_for_writepage(wbc, page);
  2090. unlock_page(page);
  2091. return 0;
  2092. }
  2093. } else {
  2094. /*
  2095. * We can't do block allocation here
  2096. * so just redity the page and unlock
  2097. * and return
  2098. */
  2099. redirty_page_for_writepage(wbc, page);
  2100. unlock_page(page);
  2101. return 0;
  2102. }
  2103. /* now mark the buffer_heads as dirty and uptodate */
  2104. block_commit_write(page, 0, PAGE_CACHE_SIZE);
  2105. }
  2106. if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
  2107. ret = nobh_writepage(page, ext4_normal_get_block_write, wbc);
  2108. else
  2109. ret = block_write_full_page(page,
  2110. ext4_normal_get_block_write,
  2111. wbc);
  2112. return ret;
  2113. }
  2114. /*
  2115. * This is called via ext4_da_writepages() to
  2116. * calulate the total number of credits to reserve to fit
  2117. * a single extent allocation into a single transaction,
  2118. * ext4_da_writpeages() will loop calling this before
  2119. * the block allocation.
  2120. */
  2121. static int ext4_da_writepages_trans_blocks(struct inode *inode)
  2122. {
  2123. int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  2124. /*
  2125. * With non-extent format the journal credit needed to
  2126. * insert nrblocks contiguous block is dependent on
  2127. * number of contiguous block. So we will limit
  2128. * number of contiguous block to a sane value
  2129. */
  2130. if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
  2131. (max_blocks > EXT4_MAX_TRANS_DATA))
  2132. max_blocks = EXT4_MAX_TRANS_DATA;
  2133. return ext4_chunk_trans_blocks(inode, max_blocks);
  2134. }
  2135. static int ext4_da_writepages(struct address_space *mapping,
  2136. struct writeback_control *wbc)
  2137. {
  2138. pgoff_t index;
  2139. int range_whole = 0;
  2140. handle_t *handle = NULL;
  2141. struct mpage_da_data mpd;
  2142. struct inode *inode = mapping->host;
  2143. int no_nrwrite_index_update;
  2144. long pages_written = 0, pages_skipped;
  2145. int needed_blocks, ret = 0, nr_to_writebump = 0;
  2146. struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
  2147. /*
  2148. * No pages to write? This is mainly a kludge to avoid starting
  2149. * a transaction for special inodes like journal inode on last iput()
  2150. * because that could violate lock ordering on umount
  2151. */
  2152. if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
  2153. return 0;
  2154. /*
  2155. * Make sure nr_to_write is >= sbi->s_mb_stream_request
  2156. * This make sure small files blocks are allocated in
  2157. * single attempt. This ensure that small files
  2158. * get less fragmented.
  2159. */
  2160. if (wbc->nr_to_write < sbi->s_mb_stream_request) {
  2161. nr_to_writebump = sbi->s_mb_stream_request - wbc->nr_to_write;
  2162. wbc->nr_to_write = sbi->s_mb_stream_request;
  2163. }
  2164. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  2165. range_whole = 1;
  2166. if (wbc->range_cyclic)
  2167. index = mapping->writeback_index;
  2168. else
  2169. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  2170. mpd.wbc = wbc;
  2171. mpd.inode = mapping->host;
  2172. /*
  2173. * we don't want write_cache_pages to update
  2174. * nr_to_write and writeback_index
  2175. */
  2176. no_nrwrite_index_update = wbc->no_nrwrite_index_update;
  2177. wbc->no_nrwrite_index_update = 1;
  2178. pages_skipped = wbc->pages_skipped;
  2179. while (!ret && wbc->nr_to_write > 0) {
  2180. /*
  2181. * we insert one extent at a time. So we need
  2182. * credit needed for single extent allocation.
  2183. * journalled mode is currently not supported
  2184. * by delalloc
  2185. */
  2186. BUG_ON(ext4_should_journal_data(inode));
  2187. needed_blocks = ext4_da_writepages_trans_blocks(inode);
  2188. /* start a new transaction*/
  2189. handle = ext4_journal_start(inode, needed_blocks);
  2190. if (IS_ERR(handle)) {
  2191. ret = PTR_ERR(handle);
  2192. printk(KERN_EMERG "%s: jbd2_start: "
  2193. "%ld pages, ino %lu; err %d\n", __func__,
  2194. wbc->nr_to_write, inode->i_ino, ret);
  2195. dump_stack();
  2196. goto out_writepages;
  2197. }
  2198. mpd.get_block = ext4_da_get_block_write;
  2199. ret = mpage_da_writepages(mapping, wbc, &mpd);
  2200. ext4_journal_stop(handle);
  2201. if (mpd.retval == -ENOSPC) {
  2202. /* commit the transaction which would
  2203. * free blocks released in the transaction
  2204. * and try again
  2205. */
  2206. jbd2_journal_force_commit_nested(sbi->s_journal);
  2207. wbc->pages_skipped = pages_skipped;
  2208. ret = 0;
  2209. } else if (ret == MPAGE_DA_EXTENT_TAIL) {
  2210. /*
  2211. * got one extent now try with
  2212. * rest of the pages
  2213. */
  2214. pages_written += mpd.pages_written;
  2215. wbc->pages_skipped = pages_skipped;
  2216. ret = 0;
  2217. } else if (wbc->nr_to_write)
  2218. /*
  2219. * There is no more writeout needed
  2220. * or we requested for a noblocking writeout
  2221. * and we found the device congested
  2222. */
  2223. break;
  2224. }
  2225. if (pages_skipped != wbc->pages_skipped)
  2226. printk(KERN_EMERG "This should not happen leaving %s "
  2227. "with nr_to_write = %ld ret = %d\n",
  2228. __func__, wbc->nr_to_write, ret);
  2229. /* Update index */
  2230. index += pages_written;
  2231. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  2232. /*
  2233. * set the writeback_index so that range_cyclic
  2234. * mode will write it back later
  2235. */
  2236. mapping->writeback_index = index;
  2237. out_writepages:
  2238. if (!no_nrwrite_index_update)
  2239. wbc->no_nrwrite_index_update = 0;
  2240. wbc->nr_to_write -= nr_to_writebump;
  2241. return ret;
  2242. }
  2243. #define FALL_BACK_TO_NONDELALLOC 1
  2244. static int ext4_nonda_switch(struct super_block *sb)
  2245. {
  2246. s64 free_blocks, dirty_blocks;
  2247. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2248. /*
  2249. * switch to non delalloc mode if we are running low
  2250. * on free block. The free block accounting via percpu
  2251. * counters can get slightly wrong with FBC_BATCH getting
  2252. * accumulated on each CPU without updating global counters
  2253. * Delalloc need an accurate free block accounting. So switch
  2254. * to non delalloc when we are near to error range.
  2255. */
  2256. free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
  2257. dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
  2258. if (2 * free_blocks < 3 * dirty_blocks ||
  2259. free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
  2260. /*
  2261. * free block count is less that 150% of dirty blocks
  2262. * or free blocks is less that watermark
  2263. */
  2264. return 1;
  2265. }
  2266. return 0;
  2267. }
  2268. static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
  2269. loff_t pos, unsigned len, unsigned flags,
  2270. struct page **pagep, void **fsdata)
  2271. {
  2272. int ret, retries = 0;
  2273. struct page *page;
  2274. pgoff_t index;
  2275. unsigned from, to;
  2276. struct inode *inode = mapping->host;
  2277. handle_t *handle;
  2278. index = pos >> PAGE_CACHE_SHIFT;
  2279. from = pos & (PAGE_CACHE_SIZE - 1);
  2280. to = from + len;
  2281. if (ext4_nonda_switch(inode->i_sb)) {
  2282. *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
  2283. return ext4_write_begin(file, mapping, pos,
  2284. len, flags, pagep, fsdata);
  2285. }
  2286. *fsdata = (void *)0;
  2287. retry:
  2288. /*
  2289. * With delayed allocation, we don't log the i_disksize update
  2290. * if there is delayed block allocation. But we still need
  2291. * to journalling the i_disksize update if writes to the end
  2292. * of file which has an already mapped buffer.
  2293. */
  2294. handle = ext4_journal_start(inode, 1);
  2295. if (IS_ERR(handle)) {
  2296. ret = PTR_ERR(handle);
  2297. goto out;
  2298. }
  2299. page = __grab_cache_page(mapping, index);
  2300. if (!page) {
  2301. ext4_journal_stop(handle);
  2302. ret = -ENOMEM;
  2303. goto out;
  2304. }
  2305. *pagep = page;
  2306. ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
  2307. ext4_da_get_block_prep);
  2308. if (ret < 0) {
  2309. unlock_page(page);
  2310. ext4_journal_stop(handle);
  2311. page_cache_release(page);
  2312. /*
  2313. * block_write_begin may have instantiated a few blocks
  2314. * outside i_size. Trim these off again. Don't need
  2315. * i_size_read because we hold i_mutex.
  2316. */
  2317. if (pos + len > inode->i_size)
  2318. vmtruncate(inode, inode->i_size);
  2319. }
  2320. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  2321. goto retry;
  2322. out:
  2323. return ret;
  2324. }
  2325. /*
  2326. * Check if we should update i_disksize
  2327. * when write to the end of file but not require block allocation
  2328. */
  2329. static int ext4_da_should_update_i_disksize(struct page *page,
  2330. unsigned long offset)
  2331. {
  2332. struct buffer_head *bh;
  2333. struct inode *inode = page->mapping->host;
  2334. unsigned int idx;
  2335. int i;
  2336. bh = page_buffers(page);
  2337. idx = offset >> inode->i_blkbits;
  2338. for (i = 0; i < idx; i++)
  2339. bh = bh->b_this_page;
  2340. if (!buffer_mapped(bh) || (buffer_delay(bh)))
  2341. return 0;
  2342. return 1;
  2343. }
  2344. static int ext4_da_write_end(struct file *file,
  2345. struct address_space *mapping,
  2346. loff_t pos, unsigned len, unsigned copied,
  2347. struct page *page, void *fsdata)
  2348. {
  2349. struct inode *inode = mapping->host;
  2350. int ret = 0, ret2;
  2351. handle_t *handle = ext4_journal_current_handle();
  2352. loff_t new_i_size;
  2353. unsigned long start, end;
  2354. int write_mode = (int)(unsigned long)fsdata;
  2355. if (write_mode == FALL_BACK_TO_NONDELALLOC) {
  2356. if (ext4_should_order_data(inode)) {
  2357. return ext4_ordered_write_end(file, mapping, pos,
  2358. len, copied, page, fsdata);
  2359. } else if (ext4_should_writeback_data(inode)) {
  2360. return ext4_writeback_write_end(file, mapping, pos,
  2361. len, copied, page, fsdata);
  2362. } else {
  2363. BUG();
  2364. }
  2365. }
  2366. start = pos & (PAGE_CACHE_SIZE - 1);
  2367. end = start + copied - 1;
  2368. /*
  2369. * generic_write_end() will run mark_inode_dirty() if i_size
  2370. * changes. So let's piggyback the i_disksize mark_inode_dirty
  2371. * into that.
  2372. */
  2373. new_i_size = pos + copied;
  2374. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2375. if (ext4_da_should_update_i_disksize(page, end)) {
  2376. down_write(&EXT4_I(inode)->i_data_sem);
  2377. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2378. /*
  2379. * Updating i_disksize when extending file
  2380. * without needing block allocation
  2381. */
  2382. if (ext4_should_order_data(inode))
  2383. ret = ext4_jbd2_file_inode(handle,
  2384. inode);
  2385. EXT4_I(inode)->i_disksize = new_i_size;
  2386. }
  2387. up_write(&EXT4_I(inode)->i_data_sem);
  2388. /* We need to mark inode dirty even if
  2389. * new_i_size is less that inode->i_size
  2390. * bu greater than i_disksize.(hint delalloc)
  2391. */
  2392. ext4_mark_inode_dirty(handle, inode);
  2393. }
  2394. }
  2395. ret2 = generic_write_end(file, mapping, pos, len, copied,
  2396. page, fsdata);
  2397. copied = ret2;
  2398. if (ret2 < 0)
  2399. ret = ret2;
  2400. ret2 = ext4_journal_stop(handle);
  2401. if (!ret)
  2402. ret = ret2;
  2403. return ret ? ret : copied;
  2404. }
  2405. static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
  2406. {
  2407. /*
  2408. * Drop reserved blocks
  2409. */
  2410. BUG_ON(!PageLocked(page));
  2411. if (!page_has_buffers(page))
  2412. goto out;
  2413. ext4_da_page_release_reservation(page, offset);
  2414. out:
  2415. ext4_invalidatepage(page, offset);
  2416. return;
  2417. }
  2418. /*
  2419. * bmap() is special. It gets used by applications such as lilo and by
  2420. * the swapper to find the on-disk block of a specific piece of data.
  2421. *
  2422. * Naturally, this is dangerous if the block concerned is still in the
  2423. * journal. If somebody makes a swapfile on an ext4 data-journaling
  2424. * filesystem and enables swap, then they may get a nasty shock when the
  2425. * data getting swapped to that swapfile suddenly gets overwritten by
  2426. * the original zero's written out previously to the journal and
  2427. * awaiting writeback in the kernel's buffer cache.
  2428. *
  2429. * So, if we see any bmap calls here on a modified, data-journaled file,
  2430. * take extra steps to flush any blocks which might be in the cache.
  2431. */
  2432. static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
  2433. {
  2434. struct inode *inode = mapping->host;
  2435. journal_t *journal;
  2436. int err;
  2437. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
  2438. test_opt(inode->i_sb, DELALLOC)) {
  2439. /*
  2440. * With delalloc we want to sync the file
  2441. * so that we can make sure we allocate
  2442. * blocks for file
  2443. */
  2444. filemap_write_and_wait(mapping);
  2445. }
  2446. if (EXT4_I(inode)->i_state & EXT4_STATE_JDATA) {
  2447. /*
  2448. * This is a REALLY heavyweight approach, but the use of
  2449. * bmap on dirty files is expected to be extremely rare:
  2450. * only if we run lilo or swapon on a freshly made file
  2451. * do we expect this to happen.
  2452. *
  2453. * (bmap requires CAP_SYS_RAWIO so this does not
  2454. * represent an unprivileged user DOS attack --- we'd be
  2455. * in trouble if mortal users could trigger this path at
  2456. * will.)
  2457. *
  2458. * NB. EXT4_STATE_JDATA is not set on files other than
  2459. * regular files. If somebody wants to bmap a directory
  2460. * or symlink and gets confused because the buffer
  2461. * hasn't yet been flushed to disk, they deserve
  2462. * everything they get.
  2463. */
  2464. EXT4_I(inode)->i_state &= ~EXT4_STATE_JDATA;
  2465. journal = EXT4_JOURNAL(inode);
  2466. jbd2_journal_lock_updates(journal);
  2467. err = jbd2_journal_flush(journal);
  2468. jbd2_journal_unlock_updates(journal);
  2469. if (err)
  2470. return 0;
  2471. }
  2472. return generic_block_bmap(mapping, block, ext4_get_block);
  2473. }
  2474. static int bget_one(handle_t *handle, struct buffer_head *bh)
  2475. {
  2476. get_bh(bh);
  2477. return 0;
  2478. }
  2479. static int bput_one(handle_t *handle, struct buffer_head *bh)
  2480. {
  2481. put_bh(bh);
  2482. return 0;
  2483. }
  2484. /*
  2485. * Note that we don't need to start a transaction unless we're journaling data
  2486. * because we should have holes filled from ext4_page_mkwrite(). We even don't
  2487. * need to file the inode to the transaction's list in ordered mode because if
  2488. * we are writing back data added by write(), the inode is already there and if
  2489. * we are writing back data modified via mmap(), noone guarantees in which
  2490. * transaction the data will hit the disk. In case we are journaling data, we
  2491. * cannot start transaction directly because transaction start ranks above page
  2492. * lock so we have to do some magic.
  2493. *
  2494. * In all journaling modes block_write_full_page() will start the I/O.
  2495. *
  2496. * Problem:
  2497. *
  2498. * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
  2499. * ext4_writepage()
  2500. *
  2501. * Similar for:
  2502. *
  2503. * ext4_file_write() -> generic_file_write() -> __alloc_pages() -> ...
  2504. *
  2505. * Same applies to ext4_get_block(). We will deadlock on various things like
  2506. * lock_journal and i_data_sem
  2507. *
  2508. * Setting PF_MEMALLOC here doesn't work - too many internal memory
  2509. * allocations fail.
  2510. *
  2511. * 16May01: If we're reentered then journal_current_handle() will be
  2512. * non-zero. We simply *return*.
  2513. *
  2514. * 1 July 2001: @@@ FIXME:
  2515. * In journalled data mode, a data buffer may be metadata against the
  2516. * current transaction. But the same file is part of a shared mapping
  2517. * and someone does a writepage() on it.
  2518. *
  2519. * We will move the buffer onto the async_data list, but *after* it has
  2520. * been dirtied. So there's a small window where we have dirty data on
  2521. * BJ_Metadata.
  2522. *
  2523. * Note that this only applies to the last partial page in the file. The
  2524. * bit which block_write_full_page() uses prepare/commit for. (That's
  2525. * broken code anyway: it's wrong for msync()).
  2526. *
  2527. * It's a rare case: affects the final partial page, for journalled data
  2528. * where the file is subject to bith write() and writepage() in the same
  2529. * transction. To fix it we'll need a custom block_write_full_page().
  2530. * We'll probably need that anyway for journalling writepage() output.
  2531. *
  2532. * We don't honour synchronous mounts for writepage(). That would be
  2533. * disastrous. Any write() or metadata operation will sync the fs for
  2534. * us.
  2535. *
  2536. */
  2537. static int __ext4_normal_writepage(struct page *page,
  2538. struct writeback_control *wbc)
  2539. {
  2540. struct inode *inode = page->mapping->host;
  2541. if (test_opt(inode->i_sb, NOBH))
  2542. return nobh_writepage(page,
  2543. ext4_normal_get_block_write, wbc);
  2544. else
  2545. return block_write_full_page(page,
  2546. ext4_normal_get_block_write,
  2547. wbc);
  2548. }
  2549. static int ext4_normal_writepage(struct page *page,
  2550. struct writeback_control *wbc)
  2551. {
  2552. struct inode *inode = page->mapping->host;
  2553. loff_t size = i_size_read(inode);
  2554. loff_t len;
  2555. J_ASSERT(PageLocked(page));
  2556. if (page->index == size >> PAGE_CACHE_SHIFT)
  2557. len = size & ~PAGE_CACHE_MASK;
  2558. else
  2559. len = PAGE_CACHE_SIZE;
  2560. if (page_has_buffers(page)) {
  2561. /* if page has buffers it should all be mapped
  2562. * and allocated. If there are not buffers attached
  2563. * to the page we know the page is dirty but it lost
  2564. * buffers. That means that at some moment in time
  2565. * after write_begin() / write_end() has been called
  2566. * all buffers have been clean and thus they must have been
  2567. * written at least once. So they are all mapped and we can
  2568. * happily proceed with mapping them and writing the page.
  2569. */
  2570. BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  2571. ext4_bh_unmapped_or_delay));
  2572. }
  2573. if (!ext4_journal_current_handle())
  2574. return __ext4_normal_writepage(page, wbc);
  2575. redirty_page_for_writepage(wbc, page);
  2576. unlock_page(page);
  2577. return 0;
  2578. }
  2579. static int __ext4_journalled_writepage(struct page *page,
  2580. struct writeback_control *wbc)
  2581. {
  2582. struct address_space *mapping = page->mapping;
  2583. struct inode *inode = mapping->host;
  2584. struct buffer_head *page_bufs;
  2585. handle_t *handle = NULL;
  2586. int ret = 0;
  2587. int err;
  2588. ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
  2589. ext4_normal_get_block_write);
  2590. if (ret != 0)
  2591. goto out_unlock;
  2592. page_bufs = page_buffers(page);
  2593. walk_page_buffers(handle, page_bufs, 0, PAGE_CACHE_SIZE, NULL,
  2594. bget_one);
  2595. /* As soon as we unlock the page, it can go away, but we have
  2596. * references to buffers so we are safe */
  2597. unlock_page(page);
  2598. handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
  2599. if (IS_ERR(handle)) {
  2600. ret = PTR_ERR(handle);
  2601. goto out;
  2602. }
  2603. ret = walk_page_buffers(handle, page_bufs, 0,
  2604. PAGE_CACHE_SIZE, NULL, do_journal_get_write_access);
  2605. err = walk_page_buffers(handle, page_bufs, 0,
  2606. PAGE_CACHE_SIZE, NULL, write_end_fn);
  2607. if (ret == 0)
  2608. ret = err;
  2609. err = ext4_journal_stop(handle);
  2610. if (!ret)
  2611. ret = err;
  2612. walk_page_buffers(handle, page_bufs, 0,
  2613. PAGE_CACHE_SIZE, NULL, bput_one);
  2614. EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
  2615. goto out;
  2616. out_unlock:
  2617. unlock_page(page);
  2618. out:
  2619. return ret;
  2620. }
  2621. static int ext4_journalled_writepage(struct page *page,
  2622. struct writeback_control *wbc)
  2623. {
  2624. struct inode *inode = page->mapping->host;
  2625. loff_t size = i_size_read(inode);
  2626. loff_t len;
  2627. J_ASSERT(PageLocked(page));
  2628. if (page->index == size >> PAGE_CACHE_SHIFT)
  2629. len = size & ~PAGE_CACHE_MASK;
  2630. else
  2631. len = PAGE_CACHE_SIZE;
  2632. if (page_has_buffers(page)) {
  2633. /* if page has buffers it should all be mapped
  2634. * and allocated. If there are not buffers attached
  2635. * to the page we know the page is dirty but it lost
  2636. * buffers. That means that at some moment in time
  2637. * after write_begin() / write_end() has been called
  2638. * all buffers have been clean and thus they must have been
  2639. * written at least once. So they are all mapped and we can
  2640. * happily proceed with mapping them and writing the page.
  2641. */
  2642. BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  2643. ext4_bh_unmapped_or_delay));
  2644. }
  2645. if (ext4_journal_current_handle())
  2646. goto no_write;
  2647. if (PageChecked(page)) {
  2648. /*
  2649. * It's mmapped pagecache. Add buffers and journal it. There
  2650. * doesn't seem much point in redirtying the page here.
  2651. */
  2652. ClearPageChecked(page);
  2653. return __ext4_journalled_writepage(page, wbc);
  2654. } else {
  2655. /*
  2656. * It may be a page full of checkpoint-mode buffers. We don't
  2657. * really know unless we go poke around in the buffer_heads.
  2658. * But block_write_full_page will do the right thing.
  2659. */
  2660. return block_write_full_page(page,
  2661. ext4_normal_get_block_write,
  2662. wbc);
  2663. }
  2664. no_write:
  2665. redirty_page_for_writepage(wbc, page);
  2666. unlock_page(page);
  2667. return 0;
  2668. }
  2669. static int ext4_readpage(struct file *file, struct page *page)
  2670. {
  2671. return mpage_readpage(page, ext4_get_block);
  2672. }
  2673. static int
  2674. ext4_readpages(struct file *file, struct address_space *mapping,
  2675. struct list_head *pages, unsigned nr_pages)
  2676. {
  2677. return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
  2678. }
  2679. static void ext4_invalidatepage(struct page *page, unsigned long offset)
  2680. {
  2681. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  2682. /*
  2683. * If it's a full truncate we just forget about the pending dirtying
  2684. */
  2685. if (offset == 0)
  2686. ClearPageChecked(page);
  2687. jbd2_journal_invalidatepage(journal, page, offset);
  2688. }
  2689. static int ext4_releasepage(struct page *page, gfp_t wait)
  2690. {
  2691. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  2692. WARN_ON(PageChecked(page));
  2693. if (!page_has_buffers(page))
  2694. return 0;
  2695. return jbd2_journal_try_to_free_buffers(journal, page, wait);
  2696. }
  2697. /*
  2698. * If the O_DIRECT write will extend the file then add this inode to the
  2699. * orphan list. So recovery will truncate it back to the original size
  2700. * if the machine crashes during the write.
  2701. *
  2702. * If the O_DIRECT write is intantiating holes inside i_size and the machine
  2703. * crashes then stale disk data _may_ be exposed inside the file. But current
  2704. * VFS code falls back into buffered path in that case so we are safe.
  2705. */
  2706. static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
  2707. const struct iovec *iov, loff_t offset,
  2708. unsigned long nr_segs)
  2709. {
  2710. struct file *file = iocb->ki_filp;
  2711. struct inode *inode = file->f_mapping->host;
  2712. struct ext4_inode_info *ei = EXT4_I(inode);
  2713. handle_t *handle;
  2714. ssize_t ret;
  2715. int orphan = 0;
  2716. size_t count = iov_length(iov, nr_segs);
  2717. if (rw == WRITE) {
  2718. loff_t final_size = offset + count;
  2719. if (final_size > inode->i_size) {
  2720. /* Credits for sb + inode write */
  2721. handle = ext4_journal_start(inode, 2);
  2722. if (IS_ERR(handle)) {
  2723. ret = PTR_ERR(handle);
  2724. goto out;
  2725. }
  2726. ret = ext4_orphan_add(handle, inode);
  2727. if (ret) {
  2728. ext4_journal_stop(handle);
  2729. goto out;
  2730. }
  2731. orphan = 1;
  2732. ei->i_disksize = inode->i_size;
  2733. ext4_journal_stop(handle);
  2734. }
  2735. }
  2736. ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
  2737. offset, nr_segs,
  2738. ext4_get_block, NULL);
  2739. if (orphan) {
  2740. int err;
  2741. /* Credits for sb + inode write */
  2742. handle = ext4_journal_start(inode, 2);
  2743. if (IS_ERR(handle)) {
  2744. /* This is really bad luck. We've written the data
  2745. * but cannot extend i_size. Bail out and pretend
  2746. * the write failed... */
  2747. ret = PTR_ERR(handle);
  2748. goto out;
  2749. }
  2750. if (inode->i_nlink)
  2751. ext4_orphan_del(handle, inode);
  2752. if (ret > 0) {
  2753. loff_t end = offset + ret;
  2754. if (end > inode->i_size) {
  2755. ei->i_disksize = end;
  2756. i_size_write(inode, end);
  2757. /*
  2758. * We're going to return a positive `ret'
  2759. * here due to non-zero-length I/O, so there's
  2760. * no way of reporting error returns from
  2761. * ext4_mark_inode_dirty() to userspace. So
  2762. * ignore it.
  2763. */
  2764. ext4_mark_inode_dirty(handle, inode);
  2765. }
  2766. }
  2767. err = ext4_journal_stop(handle);
  2768. if (ret == 0)
  2769. ret = err;
  2770. }
  2771. out:
  2772. return ret;
  2773. }
  2774. /*
  2775. * Pages can be marked dirty completely asynchronously from ext4's journalling
  2776. * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
  2777. * much here because ->set_page_dirty is called under VFS locks. The page is
  2778. * not necessarily locked.
  2779. *
  2780. * We cannot just dirty the page and leave attached buffers clean, because the
  2781. * buffers' dirty state is "definitive". We cannot just set the buffers dirty
  2782. * or jbddirty because all the journalling code will explode.
  2783. *
  2784. * So what we do is to mark the page "pending dirty" and next time writepage
  2785. * is called, propagate that into the buffers appropriately.
  2786. */
  2787. static int ext4_journalled_set_page_dirty(struct page *page)
  2788. {
  2789. SetPageChecked(page);
  2790. return __set_page_dirty_nobuffers(page);
  2791. }
  2792. static const struct address_space_operations ext4_ordered_aops = {
  2793. .readpage = ext4_readpage,
  2794. .readpages = ext4_readpages,
  2795. .writepage = ext4_normal_writepage,
  2796. .sync_page = block_sync_page,
  2797. .write_begin = ext4_write_begin,
  2798. .write_end = ext4_ordered_write_end,
  2799. .bmap = ext4_bmap,
  2800. .invalidatepage = ext4_invalidatepage,
  2801. .releasepage = ext4_releasepage,
  2802. .direct_IO = ext4_direct_IO,
  2803. .migratepage = buffer_migrate_page,
  2804. .is_partially_uptodate = block_is_partially_uptodate,
  2805. };
  2806. static const struct address_space_operations ext4_writeback_aops = {
  2807. .readpage = ext4_readpage,
  2808. .readpages = ext4_readpages,
  2809. .writepage = ext4_normal_writepage,
  2810. .sync_page = block_sync_page,
  2811. .write_begin = ext4_write_begin,
  2812. .write_end = ext4_writeback_write_end,
  2813. .bmap = ext4_bmap,
  2814. .invalidatepage = ext4_invalidatepage,
  2815. .releasepage = ext4_releasepage,
  2816. .direct_IO = ext4_direct_IO,
  2817. .migratepage = buffer_migrate_page,
  2818. .is_partially_uptodate = block_is_partially_uptodate,
  2819. };
  2820. static const struct address_space_operations ext4_journalled_aops = {
  2821. .readpage = ext4_readpage,
  2822. .readpages = ext4_readpages,
  2823. .writepage = ext4_journalled_writepage,
  2824. .sync_page = block_sync_page,
  2825. .write_begin = ext4_write_begin,
  2826. .write_end = ext4_journalled_write_end,
  2827. .set_page_dirty = ext4_journalled_set_page_dirty,
  2828. .bmap = ext4_bmap,
  2829. .invalidatepage = ext4_invalidatepage,
  2830. .releasepage = ext4_releasepage,
  2831. .is_partially_uptodate = block_is_partially_uptodate,
  2832. };
  2833. static const struct address_space_operations ext4_da_aops = {
  2834. .readpage = ext4_readpage,
  2835. .readpages = ext4_readpages,
  2836. .writepage = ext4_da_writepage,
  2837. .writepages = ext4_da_writepages,
  2838. .sync_page = block_sync_page,
  2839. .write_begin = ext4_da_write_begin,
  2840. .write_end = ext4_da_write_end,
  2841. .bmap = ext4_bmap,
  2842. .invalidatepage = ext4_da_invalidatepage,
  2843. .releasepage = ext4_releasepage,
  2844. .direct_IO = ext4_direct_IO,
  2845. .migratepage = buffer_migrate_page,
  2846. .is_partially_uptodate = block_is_partially_uptodate,
  2847. };
  2848. void ext4_set_aops(struct inode *inode)
  2849. {
  2850. if (ext4_should_order_data(inode) &&
  2851. test_opt(inode->i_sb, DELALLOC))
  2852. inode->i_mapping->a_ops = &ext4_da_aops;
  2853. else if (ext4_should_order_data(inode))
  2854. inode->i_mapping->a_ops = &ext4_ordered_aops;
  2855. else if (ext4_should_writeback_data(inode) &&
  2856. test_opt(inode->i_sb, DELALLOC))
  2857. inode->i_mapping->a_ops = &ext4_da_aops;
  2858. else if (ext4_should_writeback_data(inode))
  2859. inode->i_mapping->a_ops = &ext4_writeback_aops;
  2860. else
  2861. inode->i_mapping->a_ops = &ext4_journalled_aops;
  2862. }
  2863. /*
  2864. * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
  2865. * up to the end of the block which corresponds to `from'.
  2866. * This required during truncate. We need to physically zero the tail end
  2867. * of that block so it doesn't yield old data if the file is later grown.
  2868. */
  2869. int ext4_block_truncate_page(handle_t *handle,
  2870. struct address_space *mapping, loff_t from)
  2871. {
  2872. ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
  2873. unsigned offset = from & (PAGE_CACHE_SIZE-1);
  2874. unsigned blocksize, length, pos;
  2875. ext4_lblk_t iblock;
  2876. struct inode *inode = mapping->host;
  2877. struct buffer_head *bh;
  2878. struct page *page;
  2879. int err = 0;
  2880. page = grab_cache_page(mapping, from >> PAGE_CACHE_SHIFT);
  2881. if (!page)
  2882. return -EINVAL;
  2883. blocksize = inode->i_sb->s_blocksize;
  2884. length = blocksize - (offset & (blocksize - 1));
  2885. iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
  2886. /*
  2887. * For "nobh" option, we can only work if we don't need to
  2888. * read-in the page - otherwise we create buffers to do the IO.
  2889. */
  2890. if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
  2891. ext4_should_writeback_data(inode) && PageUptodate(page)) {
  2892. zero_user(page, offset, length);
  2893. set_page_dirty(page);
  2894. goto unlock;
  2895. }
  2896. if (!page_has_buffers(page))
  2897. create_empty_buffers(page, blocksize, 0);
  2898. /* Find the buffer that contains "offset" */
  2899. bh = page_buffers(page);
  2900. pos = blocksize;
  2901. while (offset >= pos) {
  2902. bh = bh->b_this_page;
  2903. iblock++;
  2904. pos += blocksize;
  2905. }
  2906. err = 0;
  2907. if (buffer_freed(bh)) {
  2908. BUFFER_TRACE(bh, "freed: skip");
  2909. goto unlock;
  2910. }
  2911. if (!buffer_mapped(bh)) {
  2912. BUFFER_TRACE(bh, "unmapped");
  2913. ext4_get_block(inode, iblock, bh, 0);
  2914. /* unmapped? It's a hole - nothing to do */
  2915. if (!buffer_mapped(bh)) {
  2916. BUFFER_TRACE(bh, "still unmapped");
  2917. goto unlock;
  2918. }
  2919. }
  2920. /* Ok, it's mapped. Make sure it's up-to-date */
  2921. if (PageUptodate(page))
  2922. set_buffer_uptodate(bh);
  2923. if (!buffer_uptodate(bh)) {
  2924. err = -EIO;
  2925. ll_rw_block(READ, 1, &bh);
  2926. wait_on_buffer(bh);
  2927. /* Uhhuh. Read error. Complain and punt. */
  2928. if (!buffer_uptodate(bh))
  2929. goto unlock;
  2930. }
  2931. if (ext4_should_journal_data(inode)) {
  2932. BUFFER_TRACE(bh, "get write access");
  2933. err = ext4_journal_get_write_access(handle, bh);
  2934. if (err)
  2935. goto unlock;
  2936. }
  2937. zero_user(page, offset, length);
  2938. BUFFER_TRACE(bh, "zeroed end of block");
  2939. err = 0;
  2940. if (ext4_should_journal_data(inode)) {
  2941. err = ext4_journal_dirty_metadata(handle, bh);
  2942. } else {
  2943. if (ext4_should_order_data(inode))
  2944. err = ext4_jbd2_file_inode(handle, inode);
  2945. mark_buffer_dirty(bh);
  2946. }
  2947. unlock:
  2948. unlock_page(page);
  2949. page_cache_release(page);
  2950. return err;
  2951. }
  2952. /*
  2953. * Probably it should be a library function... search for first non-zero word
  2954. * or memcmp with zero_page, whatever is better for particular architecture.
  2955. * Linus?
  2956. */
  2957. static inline int all_zeroes(__le32 *p, __le32 *q)
  2958. {
  2959. while (p < q)
  2960. if (*p++)
  2961. return 0;
  2962. return 1;
  2963. }
  2964. /**
  2965. * ext4_find_shared - find the indirect blocks for partial truncation.
  2966. * @inode: inode in question
  2967. * @depth: depth of the affected branch
  2968. * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
  2969. * @chain: place to store the pointers to partial indirect blocks
  2970. * @top: place to the (detached) top of branch
  2971. *
  2972. * This is a helper function used by ext4_truncate().
  2973. *
  2974. * When we do truncate() we may have to clean the ends of several
  2975. * indirect blocks but leave the blocks themselves alive. Block is
  2976. * partially truncated if some data below the new i_size is refered
  2977. * from it (and it is on the path to the first completely truncated
  2978. * data block, indeed). We have to free the top of that path along
  2979. * with everything to the right of the path. Since no allocation
  2980. * past the truncation point is possible until ext4_truncate()
  2981. * finishes, we may safely do the latter, but top of branch may
  2982. * require special attention - pageout below the truncation point
  2983. * might try to populate it.
  2984. *
  2985. * We atomically detach the top of branch from the tree, store the
  2986. * block number of its root in *@top, pointers to buffer_heads of
  2987. * partially truncated blocks - in @chain[].bh and pointers to
  2988. * their last elements that should not be removed - in
  2989. * @chain[].p. Return value is the pointer to last filled element
  2990. * of @chain.
  2991. *
  2992. * The work left to caller to do the actual freeing of subtrees:
  2993. * a) free the subtree starting from *@top
  2994. * b) free the subtrees whose roots are stored in
  2995. * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
  2996. * c) free the subtrees growing from the inode past the @chain[0].
  2997. * (no partially truncated stuff there). */
  2998. static Indirect *ext4_find_shared(struct inode *inode, int depth,
  2999. ext4_lblk_t offsets[4], Indirect chain[4], __le32 *top)
  3000. {
  3001. Indirect *partial, *p;
  3002. int k, err;
  3003. *top = 0;
  3004. /* Make k index the deepest non-null offest + 1 */
  3005. for (k = depth; k > 1 && !offsets[k-1]; k--)
  3006. ;
  3007. partial = ext4_get_branch(inode, k, offsets, chain, &err);
  3008. /* Writer: pointers */
  3009. if (!partial)
  3010. partial = chain + k-1;
  3011. /*
  3012. * If the branch acquired continuation since we've looked at it -
  3013. * fine, it should all survive and (new) top doesn't belong to us.
  3014. */
  3015. if (!partial->key && *partial->p)
  3016. /* Writer: end */
  3017. goto no_top;
  3018. for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
  3019. ;
  3020. /*
  3021. * OK, we've found the last block that must survive. The rest of our
  3022. * branch should be detached before unlocking. However, if that rest
  3023. * of branch is all ours and does not grow immediately from the inode
  3024. * it's easier to cheat and just decrement partial->p.
  3025. */
  3026. if (p == chain + k - 1 && p > chain) {
  3027. p->p--;
  3028. } else {
  3029. *top = *p->p;
  3030. /* Nope, don't do this in ext4. Must leave the tree intact */
  3031. #if 0
  3032. *p->p = 0;
  3033. #endif
  3034. }
  3035. /* Writer: end */
  3036. while (partial > p) {
  3037. brelse(partial->bh);
  3038. partial--;
  3039. }
  3040. no_top:
  3041. return partial;
  3042. }
  3043. /*
  3044. * Zero a number of block pointers in either an inode or an indirect block.
  3045. * If we restart the transaction we must again get write access to the
  3046. * indirect block for further modification.
  3047. *
  3048. * We release `count' blocks on disk, but (last - first) may be greater
  3049. * than `count' because there can be holes in there.
  3050. */
  3051. static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
  3052. struct buffer_head *bh, ext4_fsblk_t block_to_free,
  3053. unsigned long count, __le32 *first, __le32 *last)
  3054. {
  3055. __le32 *p;
  3056. if (try_to_extend_transaction(handle, inode)) {
  3057. if (bh) {
  3058. BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
  3059. ext4_journal_dirty_metadata(handle, bh);
  3060. }
  3061. ext4_mark_inode_dirty(handle, inode);
  3062. ext4_journal_test_restart(handle, inode);
  3063. if (bh) {
  3064. BUFFER_TRACE(bh, "retaking write access");
  3065. ext4_journal_get_write_access(handle, bh);
  3066. }
  3067. }
  3068. /*
  3069. * Any buffers which are on the journal will be in memory. We find
  3070. * them on the hash table so jbd2_journal_revoke() will run jbd2_journal_forget()
  3071. * on them. We've already detached each block from the file, so
  3072. * bforget() in jbd2_journal_forget() should be safe.
  3073. *
  3074. * AKPM: turn on bforget in jbd2_journal_forget()!!!
  3075. */
  3076. for (p = first; p < last; p++) {
  3077. u32 nr = le32_to_cpu(*p);
  3078. if (nr) {
  3079. struct buffer_head *tbh;
  3080. *p = 0;
  3081. tbh = sb_find_get_block(inode->i_sb, nr);
  3082. ext4_forget(handle, 0, inode, tbh, nr);
  3083. }
  3084. }
  3085. ext4_free_blocks(handle, inode, block_to_free, count, 0);
  3086. }
  3087. /**
  3088. * ext4_free_data - free a list of data blocks
  3089. * @handle: handle for this transaction
  3090. * @inode: inode we are dealing with
  3091. * @this_bh: indirect buffer_head which contains *@first and *@last
  3092. * @first: array of block numbers
  3093. * @last: points immediately past the end of array
  3094. *
  3095. * We are freeing all blocks refered from that array (numbers are stored as
  3096. * little-endian 32-bit) and updating @inode->i_blocks appropriately.
  3097. *
  3098. * We accumulate contiguous runs of blocks to free. Conveniently, if these
  3099. * blocks are contiguous then releasing them at one time will only affect one
  3100. * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
  3101. * actually use a lot of journal space.
  3102. *
  3103. * @this_bh will be %NULL if @first and @last point into the inode's direct
  3104. * block pointers.
  3105. */
  3106. static void ext4_free_data(handle_t *handle, struct inode *inode,
  3107. struct buffer_head *this_bh,
  3108. __le32 *first, __le32 *last)
  3109. {
  3110. ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
  3111. unsigned long count = 0; /* Number of blocks in the run */
  3112. __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
  3113. corresponding to
  3114. block_to_free */
  3115. ext4_fsblk_t nr; /* Current block # */
  3116. __le32 *p; /* Pointer into inode/ind
  3117. for current block */
  3118. int err;
  3119. if (this_bh) { /* For indirect block */
  3120. BUFFER_TRACE(this_bh, "get_write_access");
  3121. err = ext4_journal_get_write_access(handle, this_bh);
  3122. /* Important: if we can't update the indirect pointers
  3123. * to the blocks, we can't free them. */
  3124. if (err)
  3125. return;
  3126. }
  3127. for (p = first; p < last; p++) {
  3128. nr = le32_to_cpu(*p);
  3129. if (nr) {
  3130. /* accumulate blocks to free if they're contiguous */
  3131. if (count == 0) {
  3132. block_to_free = nr;
  3133. block_to_free_p = p;
  3134. count = 1;
  3135. } else if (nr == block_to_free + count) {
  3136. count++;
  3137. } else {
  3138. ext4_clear_blocks(handle, inode, this_bh,
  3139. block_to_free,
  3140. count, block_to_free_p, p);
  3141. block_to_free = nr;
  3142. block_to_free_p = p;
  3143. count = 1;
  3144. }
  3145. }
  3146. }
  3147. if (count > 0)
  3148. ext4_clear_blocks(handle, inode, this_bh, block_to_free,
  3149. count, block_to_free_p, p);
  3150. if (this_bh) {
  3151. BUFFER_TRACE(this_bh, "call ext4_journal_dirty_metadata");
  3152. /*
  3153. * The buffer head should have an attached journal head at this
  3154. * point. However, if the data is corrupted and an indirect
  3155. * block pointed to itself, it would have been detached when
  3156. * the block was cleared. Check for this instead of OOPSing.
  3157. */
  3158. if (bh2jh(this_bh))
  3159. ext4_journal_dirty_metadata(handle, this_bh);
  3160. else
  3161. ext4_error(inode->i_sb, __func__,
  3162. "circular indirect block detected, "
  3163. "inode=%lu, block=%llu",
  3164. inode->i_ino,
  3165. (unsigned long long) this_bh->b_blocknr);
  3166. }
  3167. }
  3168. /**
  3169. * ext4_free_branches - free an array of branches
  3170. * @handle: JBD handle for this transaction
  3171. * @inode: inode we are dealing with
  3172. * @parent_bh: the buffer_head which contains *@first and *@last
  3173. * @first: array of block numbers
  3174. * @last: pointer immediately past the end of array
  3175. * @depth: depth of the branches to free
  3176. *
  3177. * We are freeing all blocks refered from these branches (numbers are
  3178. * stored as little-endian 32-bit) and updating @inode->i_blocks
  3179. * appropriately.
  3180. */
  3181. static void ext4_free_branches(handle_t *handle, struct inode *inode,
  3182. struct buffer_head *parent_bh,
  3183. __le32 *first, __le32 *last, int depth)
  3184. {
  3185. ext4_fsblk_t nr;
  3186. __le32 *p;
  3187. if (is_handle_aborted(handle))
  3188. return;
  3189. if (depth--) {
  3190. struct buffer_head *bh;
  3191. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  3192. p = last;
  3193. while (--p >= first) {
  3194. nr = le32_to_cpu(*p);
  3195. if (!nr)
  3196. continue; /* A hole */
  3197. /* Go read the buffer for the next level down */
  3198. bh = sb_bread(inode->i_sb, nr);
  3199. /*
  3200. * A read failure? Report error and clear slot
  3201. * (should be rare).
  3202. */
  3203. if (!bh) {
  3204. ext4_error(inode->i_sb, "ext4_free_branches",
  3205. "Read failure, inode=%lu, block=%llu",
  3206. inode->i_ino, nr);
  3207. continue;
  3208. }
  3209. /* This zaps the entire block. Bottom up. */
  3210. BUFFER_TRACE(bh, "free child branches");
  3211. ext4_free_branches(handle, inode, bh,
  3212. (__le32 *) bh->b_data,
  3213. (__le32 *) bh->b_data + addr_per_block,
  3214. depth);
  3215. /*
  3216. * We've probably journalled the indirect block several
  3217. * times during the truncate. But it's no longer
  3218. * needed and we now drop it from the transaction via
  3219. * jbd2_journal_revoke().
  3220. *
  3221. * That's easy if it's exclusively part of this
  3222. * transaction. But if it's part of the committing
  3223. * transaction then jbd2_journal_forget() will simply
  3224. * brelse() it. That means that if the underlying
  3225. * block is reallocated in ext4_get_block(),
  3226. * unmap_underlying_metadata() will find this block
  3227. * and will try to get rid of it. damn, damn.
  3228. *
  3229. * If this block has already been committed to the
  3230. * journal, a revoke record will be written. And
  3231. * revoke records must be emitted *before* clearing
  3232. * this block's bit in the bitmaps.
  3233. */
  3234. ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
  3235. /*
  3236. * Everything below this this pointer has been
  3237. * released. Now let this top-of-subtree go.
  3238. *
  3239. * We want the freeing of this indirect block to be
  3240. * atomic in the journal with the updating of the
  3241. * bitmap block which owns it. So make some room in
  3242. * the journal.
  3243. *
  3244. * We zero the parent pointer *after* freeing its
  3245. * pointee in the bitmaps, so if extend_transaction()
  3246. * for some reason fails to put the bitmap changes and
  3247. * the release into the same transaction, recovery
  3248. * will merely complain about releasing a free block,
  3249. * rather than leaking blocks.
  3250. */
  3251. if (is_handle_aborted(handle))
  3252. return;
  3253. if (try_to_extend_transaction(handle, inode)) {
  3254. ext4_mark_inode_dirty(handle, inode);
  3255. ext4_journal_test_restart(handle, inode);
  3256. }
  3257. ext4_free_blocks(handle, inode, nr, 1, 1);
  3258. if (parent_bh) {
  3259. /*
  3260. * The block which we have just freed is
  3261. * pointed to by an indirect block: journal it
  3262. */
  3263. BUFFER_TRACE(parent_bh, "get_write_access");
  3264. if (!ext4_journal_get_write_access(handle,
  3265. parent_bh)){
  3266. *p = 0;
  3267. BUFFER_TRACE(parent_bh,
  3268. "call ext4_journal_dirty_metadata");
  3269. ext4_journal_dirty_metadata(handle,
  3270. parent_bh);
  3271. }
  3272. }
  3273. }
  3274. } else {
  3275. /* We have reached the bottom of the tree. */
  3276. BUFFER_TRACE(parent_bh, "free data blocks");
  3277. ext4_free_data(handle, inode, parent_bh, first, last);
  3278. }
  3279. }
  3280. int ext4_can_truncate(struct inode *inode)
  3281. {
  3282. if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
  3283. return 0;
  3284. if (S_ISREG(inode->i_mode))
  3285. return 1;
  3286. if (S_ISDIR(inode->i_mode))
  3287. return 1;
  3288. if (S_ISLNK(inode->i_mode))
  3289. return !ext4_inode_is_fast_symlink(inode);
  3290. return 0;
  3291. }
  3292. /*
  3293. * ext4_truncate()
  3294. *
  3295. * We block out ext4_get_block() block instantiations across the entire
  3296. * transaction, and VFS/VM ensures that ext4_truncate() cannot run
  3297. * simultaneously on behalf of the same inode.
  3298. *
  3299. * As we work through the truncate and commmit bits of it to the journal there
  3300. * is one core, guiding principle: the file's tree must always be consistent on
  3301. * disk. We must be able to restart the truncate after a crash.
  3302. *
  3303. * The file's tree may be transiently inconsistent in memory (although it
  3304. * probably isn't), but whenever we close off and commit a journal transaction,
  3305. * the contents of (the filesystem + the journal) must be consistent and
  3306. * restartable. It's pretty simple, really: bottom up, right to left (although
  3307. * left-to-right works OK too).
  3308. *
  3309. * Note that at recovery time, journal replay occurs *before* the restart of
  3310. * truncate against the orphan inode list.
  3311. *
  3312. * The committed inode has the new, desired i_size (which is the same as
  3313. * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
  3314. * that this inode's truncate did not complete and it will again call
  3315. * ext4_truncate() to have another go. So there will be instantiated blocks
  3316. * to the right of the truncation point in a crashed ext4 filesystem. But
  3317. * that's fine - as long as they are linked from the inode, the post-crash
  3318. * ext4_truncate() run will find them and release them.
  3319. */
  3320. void ext4_truncate(struct inode *inode)
  3321. {
  3322. handle_t *handle;
  3323. struct ext4_inode_info *ei = EXT4_I(inode);
  3324. __le32 *i_data = ei->i_data;
  3325. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  3326. struct address_space *mapping = inode->i_mapping;
  3327. ext4_lblk_t offsets[4];
  3328. Indirect chain[4];
  3329. Indirect *partial;
  3330. __le32 nr = 0;
  3331. int n;
  3332. ext4_lblk_t last_block;
  3333. unsigned blocksize = inode->i_sb->s_blocksize;
  3334. if (!ext4_can_truncate(inode))
  3335. return;
  3336. if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
  3337. ext4_ext_truncate(inode);
  3338. return;
  3339. }
  3340. handle = start_transaction(inode);
  3341. if (IS_ERR(handle))
  3342. return; /* AKPM: return what? */
  3343. last_block = (inode->i_size + blocksize-1)
  3344. >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
  3345. if (inode->i_size & (blocksize - 1))
  3346. if (ext4_block_truncate_page(handle, mapping, inode->i_size))
  3347. goto out_stop;
  3348. n = ext4_block_to_path(inode, last_block, offsets, NULL);
  3349. if (n == 0)
  3350. goto out_stop; /* error */
  3351. /*
  3352. * OK. This truncate is going to happen. We add the inode to the
  3353. * orphan list, so that if this truncate spans multiple transactions,
  3354. * and we crash, we will resume the truncate when the filesystem
  3355. * recovers. It also marks the inode dirty, to catch the new size.
  3356. *
  3357. * Implication: the file must always be in a sane, consistent
  3358. * truncatable state while each transaction commits.
  3359. */
  3360. if (ext4_orphan_add(handle, inode))
  3361. goto out_stop;
  3362. /*
  3363. * From here we block out all ext4_get_block() callers who want to
  3364. * modify the block allocation tree.
  3365. */
  3366. down_write(&ei->i_data_sem);
  3367. ext4_discard_preallocations(inode);
  3368. /*
  3369. * The orphan list entry will now protect us from any crash which
  3370. * occurs before the truncate completes, so it is now safe to propagate
  3371. * the new, shorter inode size (held for now in i_size) into the
  3372. * on-disk inode. We do this via i_disksize, which is the value which
  3373. * ext4 *really* writes onto the disk inode.
  3374. */
  3375. ei->i_disksize = inode->i_size;
  3376. if (n == 1) { /* direct blocks */
  3377. ext4_free_data(handle, inode, NULL, i_data+offsets[0],
  3378. i_data + EXT4_NDIR_BLOCKS);
  3379. goto do_indirects;
  3380. }
  3381. partial = ext4_find_shared(inode, n, offsets, chain, &nr);
  3382. /* Kill the top of shared branch (not detached) */
  3383. if (nr) {
  3384. if (partial == chain) {
  3385. /* Shared branch grows from the inode */
  3386. ext4_free_branches(handle, inode, NULL,
  3387. &nr, &nr+1, (chain+n-1) - partial);
  3388. *partial->p = 0;
  3389. /*
  3390. * We mark the inode dirty prior to restart,
  3391. * and prior to stop. No need for it here.
  3392. */
  3393. } else {
  3394. /* Shared branch grows from an indirect block */
  3395. BUFFER_TRACE(partial->bh, "get_write_access");
  3396. ext4_free_branches(handle, inode, partial->bh,
  3397. partial->p,
  3398. partial->p+1, (chain+n-1) - partial);
  3399. }
  3400. }
  3401. /* Clear the ends of indirect blocks on the shared branch */
  3402. while (partial > chain) {
  3403. ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
  3404. (__le32*)partial->bh->b_data+addr_per_block,
  3405. (chain+n-1) - partial);
  3406. BUFFER_TRACE(partial->bh, "call brelse");
  3407. brelse (partial->bh);
  3408. partial--;
  3409. }
  3410. do_indirects:
  3411. /* Kill the remaining (whole) subtrees */
  3412. switch (offsets[0]) {
  3413. default:
  3414. nr = i_data[EXT4_IND_BLOCK];
  3415. if (nr) {
  3416. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
  3417. i_data[EXT4_IND_BLOCK] = 0;
  3418. }
  3419. case EXT4_IND_BLOCK:
  3420. nr = i_data[EXT4_DIND_BLOCK];
  3421. if (nr) {
  3422. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
  3423. i_data[EXT4_DIND_BLOCK] = 0;
  3424. }
  3425. case EXT4_DIND_BLOCK:
  3426. nr = i_data[EXT4_TIND_BLOCK];
  3427. if (nr) {
  3428. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
  3429. i_data[EXT4_TIND_BLOCK] = 0;
  3430. }
  3431. case EXT4_TIND_BLOCK:
  3432. ;
  3433. }
  3434. up_write(&ei->i_data_sem);
  3435. inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
  3436. ext4_mark_inode_dirty(handle, inode);
  3437. /*
  3438. * In a multi-transaction truncate, we only make the final transaction
  3439. * synchronous
  3440. */
  3441. if (IS_SYNC(inode))
  3442. handle->h_sync = 1;
  3443. out_stop:
  3444. /*
  3445. * If this was a simple ftruncate(), and the file will remain alive
  3446. * then we need to clear up the orphan record which we created above.
  3447. * However, if this was a real unlink then we were called by
  3448. * ext4_delete_inode(), and we allow that function to clean up the
  3449. * orphan info for us.
  3450. */
  3451. if (inode->i_nlink)
  3452. ext4_orphan_del(handle, inode);
  3453. ext4_journal_stop(handle);
  3454. }
  3455. /*
  3456. * ext4_get_inode_loc returns with an extra refcount against the inode's
  3457. * underlying buffer_head on success. If 'in_mem' is true, we have all
  3458. * data in memory that is needed to recreate the on-disk version of this
  3459. * inode.
  3460. */
  3461. static int __ext4_get_inode_loc(struct inode *inode,
  3462. struct ext4_iloc *iloc, int in_mem)
  3463. {
  3464. struct ext4_group_desc *gdp;
  3465. struct buffer_head *bh;
  3466. struct super_block *sb = inode->i_sb;
  3467. ext4_fsblk_t block;
  3468. int inodes_per_block, inode_offset;
  3469. iloc->bh = 0;
  3470. if (!ext4_valid_inum(sb, inode->i_ino))
  3471. return -EIO;
  3472. iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
  3473. gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
  3474. if (!gdp)
  3475. return -EIO;
  3476. /*
  3477. * Figure out the offset within the block group inode table
  3478. */
  3479. inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
  3480. inode_offset = ((inode->i_ino - 1) %
  3481. EXT4_INODES_PER_GROUP(sb));
  3482. block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
  3483. iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
  3484. bh = sb_getblk(sb, block);
  3485. if (!bh) {
  3486. ext4_error(sb, "ext4_get_inode_loc", "unable to read "
  3487. "inode block - inode=%lu, block=%llu",
  3488. inode->i_ino, block);
  3489. return -EIO;
  3490. }
  3491. if (!buffer_uptodate(bh)) {
  3492. lock_buffer(bh);
  3493. /*
  3494. * If the buffer has the write error flag, we have failed
  3495. * to write out another inode in the same block. In this
  3496. * case, we don't have to read the block because we may
  3497. * read the old inode data successfully.
  3498. */
  3499. if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
  3500. set_buffer_uptodate(bh);
  3501. if (buffer_uptodate(bh)) {
  3502. /* someone brought it uptodate while we waited */
  3503. unlock_buffer(bh);
  3504. goto has_buffer;
  3505. }
  3506. /*
  3507. * If we have all information of the inode in memory and this
  3508. * is the only valid inode in the block, we need not read the
  3509. * block.
  3510. */
  3511. if (in_mem) {
  3512. struct buffer_head *bitmap_bh;
  3513. int i, start;
  3514. start = inode_offset & ~(inodes_per_block - 1);
  3515. /* Is the inode bitmap in cache? */
  3516. bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
  3517. if (!bitmap_bh)
  3518. goto make_io;
  3519. /*
  3520. * If the inode bitmap isn't in cache then the
  3521. * optimisation may end up performing two reads instead
  3522. * of one, so skip it.
  3523. */
  3524. if (!buffer_uptodate(bitmap_bh)) {
  3525. brelse(bitmap_bh);
  3526. goto make_io;
  3527. }
  3528. for (i = start; i < start + inodes_per_block; i++) {
  3529. if (i == inode_offset)
  3530. continue;
  3531. if (ext4_test_bit(i, bitmap_bh->b_data))
  3532. break;
  3533. }
  3534. brelse(bitmap_bh);
  3535. if (i == start + inodes_per_block) {
  3536. /* all other inodes are free, so skip I/O */
  3537. memset(bh->b_data, 0, bh->b_size);
  3538. set_buffer_uptodate(bh);
  3539. unlock_buffer(bh);
  3540. goto has_buffer;
  3541. }
  3542. }
  3543. make_io:
  3544. /*
  3545. * If we need to do any I/O, try to pre-readahead extra
  3546. * blocks from the inode table.
  3547. */
  3548. if (EXT4_SB(sb)->s_inode_readahead_blks) {
  3549. ext4_fsblk_t b, end, table;
  3550. unsigned num;
  3551. table = ext4_inode_table(sb, gdp);
  3552. /* Make sure s_inode_readahead_blks is a power of 2 */
  3553. while (EXT4_SB(sb)->s_inode_readahead_blks &
  3554. (EXT4_SB(sb)->s_inode_readahead_blks-1))
  3555. EXT4_SB(sb)->s_inode_readahead_blks =
  3556. (EXT4_SB(sb)->s_inode_readahead_blks &
  3557. (EXT4_SB(sb)->s_inode_readahead_blks-1));
  3558. b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
  3559. if (table > b)
  3560. b = table;
  3561. end = b + EXT4_SB(sb)->s_inode_readahead_blks;
  3562. num = EXT4_INODES_PER_GROUP(sb);
  3563. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3564. EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
  3565. num -= le16_to_cpu(gdp->bg_itable_unused);
  3566. table += num / inodes_per_block;
  3567. if (end > table)
  3568. end = table;
  3569. while (b <= end)
  3570. sb_breadahead(sb, b++);
  3571. }
  3572. /*
  3573. * There are other valid inodes in the buffer, this inode
  3574. * has in-inode xattrs, or we don't have this inode in memory.
  3575. * Read the block from disk.
  3576. */
  3577. get_bh(bh);
  3578. bh->b_end_io = end_buffer_read_sync;
  3579. submit_bh(READ_META, bh);
  3580. wait_on_buffer(bh);
  3581. if (!buffer_uptodate(bh)) {
  3582. ext4_error(sb, __func__,
  3583. "unable to read inode block - inode=%lu, "
  3584. "block=%llu", inode->i_ino, block);
  3585. brelse(bh);
  3586. return -EIO;
  3587. }
  3588. }
  3589. has_buffer:
  3590. iloc->bh = bh;
  3591. return 0;
  3592. }
  3593. int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
  3594. {
  3595. /* We have all inode data except xattrs in memory here. */
  3596. return __ext4_get_inode_loc(inode, iloc,
  3597. !(EXT4_I(inode)->i_state & EXT4_STATE_XATTR));
  3598. }
  3599. void ext4_set_inode_flags(struct inode *inode)
  3600. {
  3601. unsigned int flags = EXT4_I(inode)->i_flags;
  3602. inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
  3603. if (flags & EXT4_SYNC_FL)
  3604. inode->i_flags |= S_SYNC;
  3605. if (flags & EXT4_APPEND_FL)
  3606. inode->i_flags |= S_APPEND;
  3607. if (flags & EXT4_IMMUTABLE_FL)
  3608. inode->i_flags |= S_IMMUTABLE;
  3609. if (flags & EXT4_NOATIME_FL)
  3610. inode->i_flags |= S_NOATIME;
  3611. if (flags & EXT4_DIRSYNC_FL)
  3612. inode->i_flags |= S_DIRSYNC;
  3613. }
  3614. /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
  3615. void ext4_get_inode_flags(struct ext4_inode_info *ei)
  3616. {
  3617. unsigned int flags = ei->vfs_inode.i_flags;
  3618. ei->i_flags &= ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
  3619. EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|EXT4_DIRSYNC_FL);
  3620. if (flags & S_SYNC)
  3621. ei->i_flags |= EXT4_SYNC_FL;
  3622. if (flags & S_APPEND)
  3623. ei->i_flags |= EXT4_APPEND_FL;
  3624. if (flags & S_IMMUTABLE)
  3625. ei->i_flags |= EXT4_IMMUTABLE_FL;
  3626. if (flags & S_NOATIME)
  3627. ei->i_flags |= EXT4_NOATIME_FL;
  3628. if (flags & S_DIRSYNC)
  3629. ei->i_flags |= EXT4_DIRSYNC_FL;
  3630. }
  3631. static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
  3632. struct ext4_inode_info *ei)
  3633. {
  3634. blkcnt_t i_blocks ;
  3635. struct inode *inode = &(ei->vfs_inode);
  3636. struct super_block *sb = inode->i_sb;
  3637. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3638. EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
  3639. /* we are using combined 48 bit field */
  3640. i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
  3641. le32_to_cpu(raw_inode->i_blocks_lo);
  3642. if (ei->i_flags & EXT4_HUGE_FILE_FL) {
  3643. /* i_blocks represent file system block size */
  3644. return i_blocks << (inode->i_blkbits - 9);
  3645. } else {
  3646. return i_blocks;
  3647. }
  3648. } else {
  3649. return le32_to_cpu(raw_inode->i_blocks_lo);
  3650. }
  3651. }
  3652. struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
  3653. {
  3654. struct ext4_iloc iloc;
  3655. struct ext4_inode *raw_inode;
  3656. struct ext4_inode_info *ei;
  3657. struct buffer_head *bh;
  3658. struct inode *inode;
  3659. long ret;
  3660. int block;
  3661. inode = iget_locked(sb, ino);
  3662. if (!inode)
  3663. return ERR_PTR(-ENOMEM);
  3664. if (!(inode->i_state & I_NEW))
  3665. return inode;
  3666. ei = EXT4_I(inode);
  3667. #ifdef CONFIG_EXT4_FS_POSIX_ACL
  3668. ei->i_acl = EXT4_ACL_NOT_CACHED;
  3669. ei->i_default_acl = EXT4_ACL_NOT_CACHED;
  3670. #endif
  3671. ret = __ext4_get_inode_loc(inode, &iloc, 0);
  3672. if (ret < 0)
  3673. goto bad_inode;
  3674. bh = iloc.bh;
  3675. raw_inode = ext4_raw_inode(&iloc);
  3676. inode->i_mode = le16_to_cpu(raw_inode->i_mode);
  3677. inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
  3678. inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
  3679. if (!(test_opt(inode->i_sb, NO_UID32))) {
  3680. inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
  3681. inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
  3682. }
  3683. inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
  3684. ei->i_state = 0;
  3685. ei->i_dir_start_lookup = 0;
  3686. ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
  3687. /* We now have enough fields to check if the inode was active or not.
  3688. * This is needed because nfsd might try to access dead inodes
  3689. * the test is that same one that e2fsck uses
  3690. * NeilBrown 1999oct15
  3691. */
  3692. if (inode->i_nlink == 0) {
  3693. if (inode->i_mode == 0 ||
  3694. !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
  3695. /* this inode is deleted */
  3696. brelse(bh);
  3697. ret = -ESTALE;
  3698. goto bad_inode;
  3699. }
  3700. /* The only unlinked inodes we let through here have
  3701. * valid i_mode and are being read by the orphan
  3702. * recovery code: that's fine, we're about to complete
  3703. * the process of deleting those. */
  3704. }
  3705. ei->i_flags = le32_to_cpu(raw_inode->i_flags);
  3706. inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
  3707. ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
  3708. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  3709. cpu_to_le32(EXT4_OS_HURD)) {
  3710. ei->i_file_acl |=
  3711. ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
  3712. }
  3713. inode->i_size = ext4_isize(raw_inode);
  3714. ei->i_disksize = inode->i_size;
  3715. inode->i_generation = le32_to_cpu(raw_inode->i_generation);
  3716. ei->i_block_group = iloc.block_group;
  3717. /*
  3718. * NOTE! The in-memory inode i_data array is in little-endian order
  3719. * even on big-endian machines: we do NOT byteswap the block numbers!
  3720. */
  3721. for (block = 0; block < EXT4_N_BLOCKS; block++)
  3722. ei->i_data[block] = raw_inode->i_block[block];
  3723. INIT_LIST_HEAD(&ei->i_orphan);
  3724. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3725. ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
  3726. if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
  3727. EXT4_INODE_SIZE(inode->i_sb)) {
  3728. brelse(bh);
  3729. ret = -EIO;
  3730. goto bad_inode;
  3731. }
  3732. if (ei->i_extra_isize == 0) {
  3733. /* The extra space is currently unused. Use it. */
  3734. ei->i_extra_isize = sizeof(struct ext4_inode) -
  3735. EXT4_GOOD_OLD_INODE_SIZE;
  3736. } else {
  3737. __le32 *magic = (void *)raw_inode +
  3738. EXT4_GOOD_OLD_INODE_SIZE +
  3739. ei->i_extra_isize;
  3740. if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
  3741. ei->i_state |= EXT4_STATE_XATTR;
  3742. }
  3743. } else
  3744. ei->i_extra_isize = 0;
  3745. EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
  3746. EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
  3747. EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
  3748. EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
  3749. inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
  3750. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3751. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  3752. inode->i_version |=
  3753. (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
  3754. }
  3755. if (S_ISREG(inode->i_mode)) {
  3756. inode->i_op = &ext4_file_inode_operations;
  3757. inode->i_fop = &ext4_file_operations;
  3758. ext4_set_aops(inode);
  3759. } else if (S_ISDIR(inode->i_mode)) {
  3760. inode->i_op = &ext4_dir_inode_operations;
  3761. inode->i_fop = &ext4_dir_operations;
  3762. } else if (S_ISLNK(inode->i_mode)) {
  3763. if (ext4_inode_is_fast_symlink(inode))
  3764. inode->i_op = &ext4_fast_symlink_inode_operations;
  3765. else {
  3766. inode->i_op = &ext4_symlink_inode_operations;
  3767. ext4_set_aops(inode);
  3768. }
  3769. } else {
  3770. inode->i_op = &ext4_special_inode_operations;
  3771. if (raw_inode->i_block[0])
  3772. init_special_inode(inode, inode->i_mode,
  3773. old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
  3774. else
  3775. init_special_inode(inode, inode->i_mode,
  3776. new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
  3777. }
  3778. brelse(iloc.bh);
  3779. ext4_set_inode_flags(inode);
  3780. unlock_new_inode(inode);
  3781. return inode;
  3782. bad_inode:
  3783. iget_failed(inode);
  3784. return ERR_PTR(ret);
  3785. }
  3786. static int ext4_inode_blocks_set(handle_t *handle,
  3787. struct ext4_inode *raw_inode,
  3788. struct ext4_inode_info *ei)
  3789. {
  3790. struct inode *inode = &(ei->vfs_inode);
  3791. u64 i_blocks = inode->i_blocks;
  3792. struct super_block *sb = inode->i_sb;
  3793. if (i_blocks <= ~0U) {
  3794. /*
  3795. * i_blocks can be represnted in a 32 bit variable
  3796. * as multiple of 512 bytes
  3797. */
  3798. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3799. raw_inode->i_blocks_high = 0;
  3800. ei->i_flags &= ~EXT4_HUGE_FILE_FL;
  3801. return 0;
  3802. }
  3803. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
  3804. return -EFBIG;
  3805. if (i_blocks <= 0xffffffffffffULL) {
  3806. /*
  3807. * i_blocks can be represented in a 48 bit variable
  3808. * as multiple of 512 bytes
  3809. */
  3810. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3811. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  3812. ei->i_flags &= ~EXT4_HUGE_FILE_FL;
  3813. } else {
  3814. ei->i_flags |= EXT4_HUGE_FILE_FL;
  3815. /* i_block is stored in file system block size */
  3816. i_blocks = i_blocks >> (inode->i_blkbits - 9);
  3817. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3818. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  3819. }
  3820. return 0;
  3821. }
  3822. /*
  3823. * Post the struct inode info into an on-disk inode location in the
  3824. * buffer-cache. This gobbles the caller's reference to the
  3825. * buffer_head in the inode location struct.
  3826. *
  3827. * The caller must have write access to iloc->bh.
  3828. */
  3829. static int ext4_do_update_inode(handle_t *handle,
  3830. struct inode *inode,
  3831. struct ext4_iloc *iloc)
  3832. {
  3833. struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
  3834. struct ext4_inode_info *ei = EXT4_I(inode);
  3835. struct buffer_head *bh = iloc->bh;
  3836. int err = 0, rc, block;
  3837. /* For fields not not tracking in the in-memory inode,
  3838. * initialise them to zero for new inodes. */
  3839. if (ei->i_state & EXT4_STATE_NEW)
  3840. memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
  3841. ext4_get_inode_flags(ei);
  3842. raw_inode->i_mode = cpu_to_le16(inode->i_mode);
  3843. if (!(test_opt(inode->i_sb, NO_UID32))) {
  3844. raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
  3845. raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
  3846. /*
  3847. * Fix up interoperability with old kernels. Otherwise, old inodes get
  3848. * re-used with the upper 16 bits of the uid/gid intact
  3849. */
  3850. if (!ei->i_dtime) {
  3851. raw_inode->i_uid_high =
  3852. cpu_to_le16(high_16_bits(inode->i_uid));
  3853. raw_inode->i_gid_high =
  3854. cpu_to_le16(high_16_bits(inode->i_gid));
  3855. } else {
  3856. raw_inode->i_uid_high = 0;
  3857. raw_inode->i_gid_high = 0;
  3858. }
  3859. } else {
  3860. raw_inode->i_uid_low =
  3861. cpu_to_le16(fs_high2lowuid(inode->i_uid));
  3862. raw_inode->i_gid_low =
  3863. cpu_to_le16(fs_high2lowgid(inode->i_gid));
  3864. raw_inode->i_uid_high = 0;
  3865. raw_inode->i_gid_high = 0;
  3866. }
  3867. raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
  3868. EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
  3869. EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
  3870. EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
  3871. EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
  3872. if (ext4_inode_blocks_set(handle, raw_inode, ei))
  3873. goto out_brelse;
  3874. raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
  3875. /* clear the migrate flag in the raw_inode */
  3876. raw_inode->i_flags = cpu_to_le32(ei->i_flags & ~EXT4_EXT_MIGRATE);
  3877. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  3878. cpu_to_le32(EXT4_OS_HURD))
  3879. raw_inode->i_file_acl_high =
  3880. cpu_to_le16(ei->i_file_acl >> 32);
  3881. raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
  3882. ext4_isize_set(raw_inode, ei->i_disksize);
  3883. if (ei->i_disksize > 0x7fffffffULL) {
  3884. struct super_block *sb = inode->i_sb;
  3885. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3886. EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
  3887. EXT4_SB(sb)->s_es->s_rev_level ==
  3888. cpu_to_le32(EXT4_GOOD_OLD_REV)) {
  3889. /* If this is the first large file
  3890. * created, add a flag to the superblock.
  3891. */
  3892. err = ext4_journal_get_write_access(handle,
  3893. EXT4_SB(sb)->s_sbh);
  3894. if (err)
  3895. goto out_brelse;
  3896. ext4_update_dynamic_rev(sb);
  3897. EXT4_SET_RO_COMPAT_FEATURE(sb,
  3898. EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
  3899. sb->s_dirt = 1;
  3900. handle->h_sync = 1;
  3901. err = ext4_journal_dirty_metadata(handle,
  3902. EXT4_SB(sb)->s_sbh);
  3903. }
  3904. }
  3905. raw_inode->i_generation = cpu_to_le32(inode->i_generation);
  3906. if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
  3907. if (old_valid_dev(inode->i_rdev)) {
  3908. raw_inode->i_block[0] =
  3909. cpu_to_le32(old_encode_dev(inode->i_rdev));
  3910. raw_inode->i_block[1] = 0;
  3911. } else {
  3912. raw_inode->i_block[0] = 0;
  3913. raw_inode->i_block[1] =
  3914. cpu_to_le32(new_encode_dev(inode->i_rdev));
  3915. raw_inode->i_block[2] = 0;
  3916. }
  3917. } else for (block = 0; block < EXT4_N_BLOCKS; block++)
  3918. raw_inode->i_block[block] = ei->i_data[block];
  3919. raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
  3920. if (ei->i_extra_isize) {
  3921. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  3922. raw_inode->i_version_hi =
  3923. cpu_to_le32(inode->i_version >> 32);
  3924. raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
  3925. }
  3926. BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
  3927. rc = ext4_journal_dirty_metadata(handle, bh);
  3928. if (!err)
  3929. err = rc;
  3930. ei->i_state &= ~EXT4_STATE_NEW;
  3931. out_brelse:
  3932. brelse(bh);
  3933. ext4_std_error(inode->i_sb, err);
  3934. return err;
  3935. }
  3936. /*
  3937. * ext4_write_inode()
  3938. *
  3939. * We are called from a few places:
  3940. *
  3941. * - Within generic_file_write() for O_SYNC files.
  3942. * Here, there will be no transaction running. We wait for any running
  3943. * trasnaction to commit.
  3944. *
  3945. * - Within sys_sync(), kupdate and such.
  3946. * We wait on commit, if tol to.
  3947. *
  3948. * - Within prune_icache() (PF_MEMALLOC == true)
  3949. * Here we simply return. We can't afford to block kswapd on the
  3950. * journal commit.
  3951. *
  3952. * In all cases it is actually safe for us to return without doing anything,
  3953. * because the inode has been copied into a raw inode buffer in
  3954. * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
  3955. * knfsd.
  3956. *
  3957. * Note that we are absolutely dependent upon all inode dirtiers doing the
  3958. * right thing: they *must* call mark_inode_dirty() after dirtying info in
  3959. * which we are interested.
  3960. *
  3961. * It would be a bug for them to not do this. The code:
  3962. *
  3963. * mark_inode_dirty(inode)
  3964. * stuff();
  3965. * inode->i_size = expr;
  3966. *
  3967. * is in error because a kswapd-driven write_inode() could occur while
  3968. * `stuff()' is running, and the new i_size will be lost. Plus the inode
  3969. * will no longer be on the superblock's dirty inode list.
  3970. */
  3971. int ext4_write_inode(struct inode *inode, int wait)
  3972. {
  3973. if (current->flags & PF_MEMALLOC)
  3974. return 0;
  3975. if (ext4_journal_current_handle()) {
  3976. jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
  3977. dump_stack();
  3978. return -EIO;
  3979. }
  3980. if (!wait)
  3981. return 0;
  3982. return ext4_force_commit(inode->i_sb);
  3983. }
  3984. /*
  3985. * ext4_setattr()
  3986. *
  3987. * Called from notify_change.
  3988. *
  3989. * We want to trap VFS attempts to truncate the file as soon as
  3990. * possible. In particular, we want to make sure that when the VFS
  3991. * shrinks i_size, we put the inode on the orphan list and modify
  3992. * i_disksize immediately, so that during the subsequent flushing of
  3993. * dirty pages and freeing of disk blocks, we can guarantee that any
  3994. * commit will leave the blocks being flushed in an unused state on
  3995. * disk. (On recovery, the inode will get truncated and the blocks will
  3996. * be freed, so we have a strong guarantee that no future commit will
  3997. * leave these blocks visible to the user.)
  3998. *
  3999. * Another thing we have to assure is that if we are in ordered mode
  4000. * and inode is still attached to the committing transaction, we must
  4001. * we start writeout of all the dirty pages which are being truncated.
  4002. * This way we are sure that all the data written in the previous
  4003. * transaction are already on disk (truncate waits for pages under
  4004. * writeback).
  4005. *
  4006. * Called with inode->i_mutex down.
  4007. */
  4008. int ext4_setattr(struct dentry *dentry, struct iattr *attr)
  4009. {
  4010. struct inode *inode = dentry->d_inode;
  4011. int error, rc = 0;
  4012. const unsigned int ia_valid = attr->ia_valid;
  4013. error = inode_change_ok(inode, attr);
  4014. if (error)
  4015. return error;
  4016. if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
  4017. (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
  4018. handle_t *handle;
  4019. /* (user+group)*(old+new) structure, inode write (sb,
  4020. * inode block, ? - but truncate inode update has it) */
  4021. handle = ext4_journal_start(inode, 2*(EXT4_QUOTA_INIT_BLOCKS(inode->i_sb)+
  4022. EXT4_QUOTA_DEL_BLOCKS(inode->i_sb))+3);
  4023. if (IS_ERR(handle)) {
  4024. error = PTR_ERR(handle);
  4025. goto err_out;
  4026. }
  4027. error = DQUOT_TRANSFER(inode, attr) ? -EDQUOT : 0;
  4028. if (error) {
  4029. ext4_journal_stop(handle);
  4030. return error;
  4031. }
  4032. /* Update corresponding info in inode so that everything is in
  4033. * one transaction */
  4034. if (attr->ia_valid & ATTR_UID)
  4035. inode->i_uid = attr->ia_uid;
  4036. if (attr->ia_valid & ATTR_GID)
  4037. inode->i_gid = attr->ia_gid;
  4038. error = ext4_mark_inode_dirty(handle, inode);
  4039. ext4_journal_stop(handle);
  4040. }
  4041. if (attr->ia_valid & ATTR_SIZE) {
  4042. if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)) {
  4043. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  4044. if (attr->ia_size > sbi->s_bitmap_maxbytes) {
  4045. error = -EFBIG;
  4046. goto err_out;
  4047. }
  4048. }
  4049. }
  4050. if (S_ISREG(inode->i_mode) &&
  4051. attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
  4052. handle_t *handle;
  4053. handle = ext4_journal_start(inode, 3);
  4054. if (IS_ERR(handle)) {
  4055. error = PTR_ERR(handle);
  4056. goto err_out;
  4057. }
  4058. error = ext4_orphan_add(handle, inode);
  4059. EXT4_I(inode)->i_disksize = attr->ia_size;
  4060. rc = ext4_mark_inode_dirty(handle, inode);
  4061. if (!error)
  4062. error = rc;
  4063. ext4_journal_stop(handle);
  4064. if (ext4_should_order_data(inode)) {
  4065. error = ext4_begin_ordered_truncate(inode,
  4066. attr->ia_size);
  4067. if (error) {
  4068. /* Do as much error cleanup as possible */
  4069. handle = ext4_journal_start(inode, 3);
  4070. if (IS_ERR(handle)) {
  4071. ext4_orphan_del(NULL, inode);
  4072. goto err_out;
  4073. }
  4074. ext4_orphan_del(handle, inode);
  4075. ext4_journal_stop(handle);
  4076. goto err_out;
  4077. }
  4078. }
  4079. }
  4080. rc = inode_setattr(inode, attr);
  4081. /* If inode_setattr's call to ext4_truncate failed to get a
  4082. * transaction handle at all, we need to clean up the in-core
  4083. * orphan list manually. */
  4084. if (inode->i_nlink)
  4085. ext4_orphan_del(NULL, inode);
  4086. if (!rc && (ia_valid & ATTR_MODE))
  4087. rc = ext4_acl_chmod(inode);
  4088. err_out:
  4089. ext4_std_error(inode->i_sb, error);
  4090. if (!error)
  4091. error = rc;
  4092. return error;
  4093. }
  4094. int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
  4095. struct kstat *stat)
  4096. {
  4097. struct inode *inode;
  4098. unsigned long delalloc_blocks;
  4099. inode = dentry->d_inode;
  4100. generic_fillattr(inode, stat);
  4101. /*
  4102. * We can't update i_blocks if the block allocation is delayed
  4103. * otherwise in the case of system crash before the real block
  4104. * allocation is done, we will have i_blocks inconsistent with
  4105. * on-disk file blocks.
  4106. * We always keep i_blocks updated together with real
  4107. * allocation. But to not confuse with user, stat
  4108. * will return the blocks that include the delayed allocation
  4109. * blocks for this file.
  4110. */
  4111. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  4112. delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  4113. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  4114. stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
  4115. return 0;
  4116. }
  4117. static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
  4118. int chunk)
  4119. {
  4120. int indirects;
  4121. /* if nrblocks are contiguous */
  4122. if (chunk) {
  4123. /*
  4124. * With N contiguous data blocks, it need at most
  4125. * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
  4126. * 2 dindirect blocks
  4127. * 1 tindirect block
  4128. */
  4129. indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
  4130. return indirects + 3;
  4131. }
  4132. /*
  4133. * if nrblocks are not contiguous, worse case, each block touch
  4134. * a indirect block, and each indirect block touch a double indirect
  4135. * block, plus a triple indirect block
  4136. */
  4137. indirects = nrblocks * 2 + 1;
  4138. return indirects;
  4139. }
  4140. static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  4141. {
  4142. if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
  4143. return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
  4144. return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
  4145. }
  4146. /*
  4147. * Account for index blocks, block groups bitmaps and block group
  4148. * descriptor blocks if modify datablocks and index blocks
  4149. * worse case, the indexs blocks spread over different block groups
  4150. *
  4151. * If datablocks are discontiguous, they are possible to spread over
  4152. * different block groups too. If they are contiugous, with flexbg,
  4153. * they could still across block group boundary.
  4154. *
  4155. * Also account for superblock, inode, quota and xattr blocks
  4156. */
  4157. int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  4158. {
  4159. int groups, gdpblocks;
  4160. int idxblocks;
  4161. int ret = 0;
  4162. /*
  4163. * How many index blocks need to touch to modify nrblocks?
  4164. * The "Chunk" flag indicating whether the nrblocks is
  4165. * physically contiguous on disk
  4166. *
  4167. * For Direct IO and fallocate, they calls get_block to allocate
  4168. * one single extent at a time, so they could set the "Chunk" flag
  4169. */
  4170. idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
  4171. ret = idxblocks;
  4172. /*
  4173. * Now let's see how many group bitmaps and group descriptors need
  4174. * to account
  4175. */
  4176. groups = idxblocks;
  4177. if (chunk)
  4178. groups += 1;
  4179. else
  4180. groups += nrblocks;
  4181. gdpblocks = groups;
  4182. if (groups > EXT4_SB(inode->i_sb)->s_groups_count)
  4183. groups = EXT4_SB(inode->i_sb)->s_groups_count;
  4184. if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
  4185. gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
  4186. /* bitmaps and block group descriptor blocks */
  4187. ret += groups + gdpblocks;
  4188. /* Blocks for super block, inode, quota and xattr blocks */
  4189. ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
  4190. return ret;
  4191. }
  4192. /*
  4193. * Calulate the total number of credits to reserve to fit
  4194. * the modification of a single pages into a single transaction,
  4195. * which may include multiple chunks of block allocations.
  4196. *
  4197. * This could be called via ext4_write_begin()
  4198. *
  4199. * We need to consider the worse case, when
  4200. * one new block per extent.
  4201. */
  4202. int ext4_writepage_trans_blocks(struct inode *inode)
  4203. {
  4204. int bpp = ext4_journal_blocks_per_page(inode);
  4205. int ret;
  4206. ret = ext4_meta_trans_blocks(inode, bpp, 0);
  4207. /* Account for data blocks for journalled mode */
  4208. if (ext4_should_journal_data(inode))
  4209. ret += bpp;
  4210. return ret;
  4211. }
  4212. /*
  4213. * Calculate the journal credits for a chunk of data modification.
  4214. *
  4215. * This is called from DIO, fallocate or whoever calling
  4216. * ext4_get_blocks_wrap() to map/allocate a chunk of contigous disk blocks.
  4217. *
  4218. * journal buffers for data blocks are not included here, as DIO
  4219. * and fallocate do no need to journal data buffers.
  4220. */
  4221. int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
  4222. {
  4223. return ext4_meta_trans_blocks(inode, nrblocks, 1);
  4224. }
  4225. /*
  4226. * The caller must have previously called ext4_reserve_inode_write().
  4227. * Give this, we know that the caller already has write access to iloc->bh.
  4228. */
  4229. int ext4_mark_iloc_dirty(handle_t *handle,
  4230. struct inode *inode, struct ext4_iloc *iloc)
  4231. {
  4232. int err = 0;
  4233. if (test_opt(inode->i_sb, I_VERSION))
  4234. inode_inc_iversion(inode);
  4235. /* the do_update_inode consumes one bh->b_count */
  4236. get_bh(iloc->bh);
  4237. /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
  4238. err = ext4_do_update_inode(handle, inode, iloc);
  4239. put_bh(iloc->bh);
  4240. return err;
  4241. }
  4242. /*
  4243. * On success, We end up with an outstanding reference count against
  4244. * iloc->bh. This _must_ be cleaned up later.
  4245. */
  4246. int
  4247. ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
  4248. struct ext4_iloc *iloc)
  4249. {
  4250. int err = 0;
  4251. if (handle) {
  4252. err = ext4_get_inode_loc(inode, iloc);
  4253. if (!err) {
  4254. BUFFER_TRACE(iloc->bh, "get_write_access");
  4255. err = ext4_journal_get_write_access(handle, iloc->bh);
  4256. if (err) {
  4257. brelse(iloc->bh);
  4258. iloc->bh = NULL;
  4259. }
  4260. }
  4261. }
  4262. ext4_std_error(inode->i_sb, err);
  4263. return err;
  4264. }
  4265. /*
  4266. * Expand an inode by new_extra_isize bytes.
  4267. * Returns 0 on success or negative error number on failure.
  4268. */
  4269. static int ext4_expand_extra_isize(struct inode *inode,
  4270. unsigned int new_extra_isize,
  4271. struct ext4_iloc iloc,
  4272. handle_t *handle)
  4273. {
  4274. struct ext4_inode *raw_inode;
  4275. struct ext4_xattr_ibody_header *header;
  4276. struct ext4_xattr_entry *entry;
  4277. if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
  4278. return 0;
  4279. raw_inode = ext4_raw_inode(&iloc);
  4280. header = IHDR(inode, raw_inode);
  4281. entry = IFIRST(header);
  4282. /* No extended attributes present */
  4283. if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR) ||
  4284. header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
  4285. memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
  4286. new_extra_isize);
  4287. EXT4_I(inode)->i_extra_isize = new_extra_isize;
  4288. return 0;
  4289. }
  4290. /* try to expand with EAs present */
  4291. return ext4_expand_extra_isize_ea(inode, new_extra_isize,
  4292. raw_inode, handle);
  4293. }
  4294. /*
  4295. * What we do here is to mark the in-core inode as clean with respect to inode
  4296. * dirtiness (it may still be data-dirty).
  4297. * This means that the in-core inode may be reaped by prune_icache
  4298. * without having to perform any I/O. This is a very good thing,
  4299. * because *any* task may call prune_icache - even ones which
  4300. * have a transaction open against a different journal.
  4301. *
  4302. * Is this cheating? Not really. Sure, we haven't written the
  4303. * inode out, but prune_icache isn't a user-visible syncing function.
  4304. * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
  4305. * we start and wait on commits.
  4306. *
  4307. * Is this efficient/effective? Well, we're being nice to the system
  4308. * by cleaning up our inodes proactively so they can be reaped
  4309. * without I/O. But we are potentially leaving up to five seconds'
  4310. * worth of inodes floating about which prune_icache wants us to
  4311. * write out. One way to fix that would be to get prune_icache()
  4312. * to do a write_super() to free up some memory. It has the desired
  4313. * effect.
  4314. */
  4315. int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
  4316. {
  4317. struct ext4_iloc iloc;
  4318. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  4319. static unsigned int mnt_count;
  4320. int err, ret;
  4321. might_sleep();
  4322. err = ext4_reserve_inode_write(handle, inode, &iloc);
  4323. if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
  4324. !(EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND)) {
  4325. /*
  4326. * We need extra buffer credits since we may write into EA block
  4327. * with this same handle. If journal_extend fails, then it will
  4328. * only result in a minor loss of functionality for that inode.
  4329. * If this is felt to be critical, then e2fsck should be run to
  4330. * force a large enough s_min_extra_isize.
  4331. */
  4332. if ((jbd2_journal_extend(handle,
  4333. EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
  4334. ret = ext4_expand_extra_isize(inode,
  4335. sbi->s_want_extra_isize,
  4336. iloc, handle);
  4337. if (ret) {
  4338. EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
  4339. if (mnt_count !=
  4340. le16_to_cpu(sbi->s_es->s_mnt_count)) {
  4341. ext4_warning(inode->i_sb, __func__,
  4342. "Unable to expand inode %lu. Delete"
  4343. " some EAs or run e2fsck.",
  4344. inode->i_ino);
  4345. mnt_count =
  4346. le16_to_cpu(sbi->s_es->s_mnt_count);
  4347. }
  4348. }
  4349. }
  4350. }
  4351. if (!err)
  4352. err = ext4_mark_iloc_dirty(handle, inode, &iloc);
  4353. return err;
  4354. }
  4355. /*
  4356. * ext4_dirty_inode() is called from __mark_inode_dirty()
  4357. *
  4358. * We're really interested in the case where a file is being extended.
  4359. * i_size has been changed by generic_commit_write() and we thus need
  4360. * to include the updated inode in the current transaction.
  4361. *
  4362. * Also, DQUOT_ALLOC_SPACE() will always dirty the inode when blocks
  4363. * are allocated to the file.
  4364. *
  4365. * If the inode is marked synchronous, we don't honour that here - doing
  4366. * so would cause a commit on atime updates, which we don't bother doing.
  4367. * We handle synchronous inodes at the highest possible level.
  4368. */
  4369. void ext4_dirty_inode(struct inode *inode)
  4370. {
  4371. handle_t *current_handle = ext4_journal_current_handle();
  4372. handle_t *handle;
  4373. handle = ext4_journal_start(inode, 2);
  4374. if (IS_ERR(handle))
  4375. goto out;
  4376. if (current_handle &&
  4377. current_handle->h_transaction != handle->h_transaction) {
  4378. /* This task has a transaction open against a different fs */
  4379. printk(KERN_EMERG "%s: transactions do not match!\n",
  4380. __func__);
  4381. } else {
  4382. jbd_debug(5, "marking dirty. outer handle=%p\n",
  4383. current_handle);
  4384. ext4_mark_inode_dirty(handle, inode);
  4385. }
  4386. ext4_journal_stop(handle);
  4387. out:
  4388. return;
  4389. }
  4390. #if 0
  4391. /*
  4392. * Bind an inode's backing buffer_head into this transaction, to prevent
  4393. * it from being flushed to disk early. Unlike
  4394. * ext4_reserve_inode_write, this leaves behind no bh reference and
  4395. * returns no iloc structure, so the caller needs to repeat the iloc
  4396. * lookup to mark the inode dirty later.
  4397. */
  4398. static int ext4_pin_inode(handle_t *handle, struct inode *inode)
  4399. {
  4400. struct ext4_iloc iloc;
  4401. int err = 0;
  4402. if (handle) {
  4403. err = ext4_get_inode_loc(inode, &iloc);
  4404. if (!err) {
  4405. BUFFER_TRACE(iloc.bh, "get_write_access");
  4406. err = jbd2_journal_get_write_access(handle, iloc.bh);
  4407. if (!err)
  4408. err = ext4_journal_dirty_metadata(handle,
  4409. iloc.bh);
  4410. brelse(iloc.bh);
  4411. }
  4412. }
  4413. ext4_std_error(inode->i_sb, err);
  4414. return err;
  4415. }
  4416. #endif
  4417. int ext4_change_inode_journal_flag(struct inode *inode, int val)
  4418. {
  4419. journal_t *journal;
  4420. handle_t *handle;
  4421. int err;
  4422. /*
  4423. * We have to be very careful here: changing a data block's
  4424. * journaling status dynamically is dangerous. If we write a
  4425. * data block to the journal, change the status and then delete
  4426. * that block, we risk forgetting to revoke the old log record
  4427. * from the journal and so a subsequent replay can corrupt data.
  4428. * So, first we make sure that the journal is empty and that
  4429. * nobody is changing anything.
  4430. */
  4431. journal = EXT4_JOURNAL(inode);
  4432. if (is_journal_aborted(journal))
  4433. return -EROFS;
  4434. jbd2_journal_lock_updates(journal);
  4435. jbd2_journal_flush(journal);
  4436. /*
  4437. * OK, there are no updates running now, and all cached data is
  4438. * synced to disk. We are now in a completely consistent state
  4439. * which doesn't have anything in the journal, and we know that
  4440. * no filesystem updates are running, so it is safe to modify
  4441. * the inode's in-core data-journaling state flag now.
  4442. */
  4443. if (val)
  4444. EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL;
  4445. else
  4446. EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL;
  4447. ext4_set_aops(inode);
  4448. jbd2_journal_unlock_updates(journal);
  4449. /* Finally we can mark the inode as dirty. */
  4450. handle = ext4_journal_start(inode, 1);
  4451. if (IS_ERR(handle))
  4452. return PTR_ERR(handle);
  4453. err = ext4_mark_inode_dirty(handle, inode);
  4454. handle->h_sync = 1;
  4455. ext4_journal_stop(handle);
  4456. ext4_std_error(inode->i_sb, err);
  4457. return err;
  4458. }
  4459. static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
  4460. {
  4461. return !buffer_mapped(bh);
  4462. }
  4463. int ext4_page_mkwrite(struct vm_area_struct *vma, struct page *page)
  4464. {
  4465. loff_t size;
  4466. unsigned long len;
  4467. int ret = -EINVAL;
  4468. void *fsdata;
  4469. struct file *file = vma->vm_file;
  4470. struct inode *inode = file->f_path.dentry->d_inode;
  4471. struct address_space *mapping = inode->i_mapping;
  4472. /*
  4473. * Get i_alloc_sem to stop truncates messing with the inode. We cannot
  4474. * get i_mutex because we are already holding mmap_sem.
  4475. */
  4476. down_read(&inode->i_alloc_sem);
  4477. size = i_size_read(inode);
  4478. if (page->mapping != mapping || size <= page_offset(page)
  4479. || !PageUptodate(page)) {
  4480. /* page got truncated from under us? */
  4481. goto out_unlock;
  4482. }
  4483. ret = 0;
  4484. if (PageMappedToDisk(page))
  4485. goto out_unlock;
  4486. if (page->index == size >> PAGE_CACHE_SHIFT)
  4487. len = size & ~PAGE_CACHE_MASK;
  4488. else
  4489. len = PAGE_CACHE_SIZE;
  4490. if (page_has_buffers(page)) {
  4491. /* return if we have all the buffers mapped */
  4492. if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  4493. ext4_bh_unmapped))
  4494. goto out_unlock;
  4495. }
  4496. /*
  4497. * OK, we need to fill the hole... Do write_begin write_end
  4498. * to do block allocation/reservation.We are not holding
  4499. * inode.i__mutex here. That allow * parallel write_begin,
  4500. * write_end call. lock_page prevent this from happening
  4501. * on the same page though
  4502. */
  4503. ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
  4504. len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
  4505. if (ret < 0)
  4506. goto out_unlock;
  4507. ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
  4508. len, len, page, fsdata);
  4509. if (ret < 0)
  4510. goto out_unlock;
  4511. ret = 0;
  4512. out_unlock:
  4513. up_read(&inode->i_alloc_sem);
  4514. return ret;
  4515. }