inode.c 154 KB

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