inode.c 148 KB

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