inode.c 149 KB

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