inode.c 158 KB

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