inode.c 155 KB

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