inode.c 155 KB

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