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