inode.c 143 KB

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