inode.c 143 KB

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