inode.c 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889
  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. * 64-bit file support on 64-bit platforms by Jakub Jelinek
  16. * (jj@sunsite.ms.mff.cuni.cz)
  17. *
  18. * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
  19. */
  20. #include <linux/fs.h>
  21. #include <linux/time.h>
  22. #include <linux/jbd2.h>
  23. #include <linux/highuid.h>
  24. #include <linux/pagemap.h>
  25. #include <linux/quotaops.h>
  26. #include <linux/string.h>
  27. #include <linux/buffer_head.h>
  28. #include <linux/writeback.h>
  29. #include <linux/pagevec.h>
  30. #include <linux/mpage.h>
  31. #include <linux/namei.h>
  32. #include <linux/uio.h>
  33. #include <linux/bio.h>
  34. #include <linux/workqueue.h>
  35. #include <linux/kernel.h>
  36. #include <linux/printk.h>
  37. #include <linux/slab.h>
  38. #include <linux/ratelimit.h>
  39. #include <linux/bitops.h>
  40. #include "ext4_jbd2.h"
  41. #include "xattr.h"
  42. #include "acl.h"
  43. #include "truncate.h"
  44. #include <trace/events/ext4.h>
  45. #define MPAGE_DA_EXTENT_TAIL 0x01
  46. static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
  47. struct ext4_inode_info *ei)
  48. {
  49. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  50. __u16 csum_lo;
  51. __u16 csum_hi = 0;
  52. __u32 csum;
  53. csum_lo = raw->i_checksum_lo;
  54. raw->i_checksum_lo = 0;
  55. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
  56. EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
  57. csum_hi = raw->i_checksum_hi;
  58. raw->i_checksum_hi = 0;
  59. }
  60. csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
  61. EXT4_INODE_SIZE(inode->i_sb));
  62. raw->i_checksum_lo = csum_lo;
  63. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
  64. EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
  65. raw->i_checksum_hi = csum_hi;
  66. return csum;
  67. }
  68. static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
  69. struct ext4_inode_info *ei)
  70. {
  71. __u32 provided, calculated;
  72. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  73. cpu_to_le32(EXT4_OS_LINUX) ||
  74. !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
  75. EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
  76. return 1;
  77. provided = le16_to_cpu(raw->i_checksum_lo);
  78. calculated = ext4_inode_csum(inode, raw, ei);
  79. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
  80. EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
  81. provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
  82. else
  83. calculated &= 0xFFFF;
  84. return provided == calculated;
  85. }
  86. static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
  87. struct ext4_inode_info *ei)
  88. {
  89. __u32 csum;
  90. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  91. cpu_to_le32(EXT4_OS_LINUX) ||
  92. !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
  93. EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
  94. return;
  95. csum = ext4_inode_csum(inode, raw, ei);
  96. raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
  97. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
  98. EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
  99. raw->i_checksum_hi = cpu_to_le16(csum >> 16);
  100. }
  101. static inline int ext4_begin_ordered_truncate(struct inode *inode,
  102. loff_t new_size)
  103. {
  104. trace_ext4_begin_ordered_truncate(inode, new_size);
  105. /*
  106. * If jinode is zero, then we never opened the file for
  107. * writing, so there's no need to call
  108. * jbd2_journal_begin_ordered_truncate() since there's no
  109. * outstanding writes we need to flush.
  110. */
  111. if (!EXT4_I(inode)->jinode)
  112. return 0;
  113. return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
  114. EXT4_I(inode)->jinode,
  115. new_size);
  116. }
  117. static void ext4_invalidatepage(struct page *page, unsigned long offset);
  118. static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
  119. struct buffer_head *bh_result, int create);
  120. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
  121. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
  122. static int __ext4_journalled_writepage(struct page *page, unsigned int len);
  123. static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
  124. static int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
  125. struct inode *inode, struct page *page, loff_t from,
  126. loff_t length, int flags);
  127. /*
  128. * Test whether an inode is a fast symlink.
  129. */
  130. static int ext4_inode_is_fast_symlink(struct inode *inode)
  131. {
  132. int ea_blocks = EXT4_I(inode)->i_file_acl ?
  133. (inode->i_sb->s_blocksize >> 9) : 0;
  134. return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
  135. }
  136. /*
  137. * Restart the transaction associated with *handle. This does a commit,
  138. * so before we call here everything must be consistently dirtied against
  139. * this transaction.
  140. */
  141. int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
  142. int nblocks)
  143. {
  144. int ret;
  145. /*
  146. * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
  147. * moment, get_block can be called only for blocks inside i_size since
  148. * page cache has been already dropped and writes are blocked by
  149. * i_mutex. So we can safely drop the i_data_sem here.
  150. */
  151. BUG_ON(EXT4_JOURNAL(inode) == NULL);
  152. jbd_debug(2, "restarting handle %p\n", handle);
  153. up_write(&EXT4_I(inode)->i_data_sem);
  154. ret = ext4_journal_restart(handle, nblocks);
  155. down_write(&EXT4_I(inode)->i_data_sem);
  156. ext4_discard_preallocations(inode);
  157. return ret;
  158. }
  159. /*
  160. * Called at the last iput() if i_nlink is zero.
  161. */
  162. void ext4_evict_inode(struct inode *inode)
  163. {
  164. handle_t *handle;
  165. int err;
  166. trace_ext4_evict_inode(inode);
  167. ext4_ioend_wait(inode);
  168. if (inode->i_nlink) {
  169. /*
  170. * When journalling data dirty buffers are tracked only in the
  171. * journal. So although mm thinks everything is clean and
  172. * ready for reaping the inode might still have some pages to
  173. * write in the running transaction or waiting to be
  174. * checkpointed. Thus calling jbd2_journal_invalidatepage()
  175. * (via truncate_inode_pages()) to discard these buffers can
  176. * cause data loss. Also even if we did not discard these
  177. * buffers, we would have no way to find them after the inode
  178. * is reaped and thus user could see stale data if he tries to
  179. * read them before the transaction is checkpointed. So be
  180. * careful and force everything to disk here... We use
  181. * ei->i_datasync_tid to store the newest transaction
  182. * containing inode's data.
  183. *
  184. * Note that directories do not have this problem because they
  185. * don't use page cache.
  186. */
  187. if (ext4_should_journal_data(inode) &&
  188. (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
  189. inode->i_ino != EXT4_JOURNAL_INO) {
  190. journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
  191. tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
  192. jbd2_complete_transaction(journal, commit_tid);
  193. filemap_write_and_wait(&inode->i_data);
  194. }
  195. truncate_inode_pages(&inode->i_data, 0);
  196. goto no_delete;
  197. }
  198. if (is_bad_inode(inode))
  199. goto no_delete;
  200. dquot_initialize(inode);
  201. if (ext4_should_order_data(inode))
  202. ext4_begin_ordered_truncate(inode, 0);
  203. truncate_inode_pages(&inode->i_data, 0);
  204. handle = ext4_journal_start(inode, ext4_blocks_for_truncate(inode)+3);
  205. if (IS_ERR(handle)) {
  206. ext4_std_error(inode->i_sb, PTR_ERR(handle));
  207. /*
  208. * If we're going to skip the normal cleanup, we still need to
  209. * make sure that the in-core orphan linked list is properly
  210. * cleaned up.
  211. */
  212. ext4_orphan_del(NULL, inode);
  213. goto no_delete;
  214. }
  215. if (IS_SYNC(inode))
  216. ext4_handle_sync(handle);
  217. inode->i_size = 0;
  218. err = ext4_mark_inode_dirty(handle, inode);
  219. if (err) {
  220. ext4_warning(inode->i_sb,
  221. "couldn't mark inode dirty (err %d)", err);
  222. goto stop_handle;
  223. }
  224. if (inode->i_blocks)
  225. ext4_truncate(inode);
  226. /*
  227. * ext4_ext_truncate() doesn't reserve any slop when it
  228. * restarts journal transactions; therefore there may not be
  229. * enough credits left in the handle to remove the inode from
  230. * the orphan list and set the dtime field.
  231. */
  232. if (!ext4_handle_has_enough_credits(handle, 3)) {
  233. err = ext4_journal_extend(handle, 3);
  234. if (err > 0)
  235. err = ext4_journal_restart(handle, 3);
  236. if (err != 0) {
  237. ext4_warning(inode->i_sb,
  238. "couldn't extend journal (err %d)", err);
  239. stop_handle:
  240. ext4_journal_stop(handle);
  241. ext4_orphan_del(NULL, inode);
  242. goto no_delete;
  243. }
  244. }
  245. /*
  246. * Kill off the orphan record which ext4_truncate created.
  247. * AKPM: I think this can be inside the above `if'.
  248. * Note that ext4_orphan_del() has to be able to cope with the
  249. * deletion of a non-existent orphan - this is because we don't
  250. * know if ext4_truncate() actually created an orphan record.
  251. * (Well, we could do this if we need to, but heck - it works)
  252. */
  253. ext4_orphan_del(handle, inode);
  254. EXT4_I(inode)->i_dtime = get_seconds();
  255. /*
  256. * One subtle ordering requirement: if anything has gone wrong
  257. * (transaction abort, IO errors, whatever), then we can still
  258. * do these next steps (the fs will already have been marked as
  259. * having errors), but we can't free the inode if the mark_dirty
  260. * fails.
  261. */
  262. if (ext4_mark_inode_dirty(handle, inode))
  263. /* If that failed, just do the required in-core inode clear. */
  264. ext4_clear_inode(inode);
  265. else
  266. ext4_free_inode(handle, inode);
  267. ext4_journal_stop(handle);
  268. return;
  269. no_delete:
  270. ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
  271. }
  272. #ifdef CONFIG_QUOTA
  273. qsize_t *ext4_get_reserved_space(struct inode *inode)
  274. {
  275. return &EXT4_I(inode)->i_reserved_quota;
  276. }
  277. #endif
  278. /*
  279. * Calculate the number of metadata blocks need to reserve
  280. * to allocate a block located at @lblock
  281. */
  282. static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
  283. {
  284. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  285. return ext4_ext_calc_metadata_amount(inode, lblock);
  286. return ext4_ind_calc_metadata_amount(inode, lblock);
  287. }
  288. /*
  289. * Called with i_data_sem down, which is important since we can call
  290. * ext4_discard_preallocations() from here.
  291. */
  292. void ext4_da_update_reserve_space(struct inode *inode,
  293. int used, int quota_claim)
  294. {
  295. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  296. struct ext4_inode_info *ei = EXT4_I(inode);
  297. spin_lock(&ei->i_block_reservation_lock);
  298. trace_ext4_da_update_reserve_space(inode, used, quota_claim);
  299. if (unlikely(used > ei->i_reserved_data_blocks)) {
  300. ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
  301. "with only %d reserved data blocks",
  302. __func__, inode->i_ino, used,
  303. ei->i_reserved_data_blocks);
  304. WARN_ON(1);
  305. used = ei->i_reserved_data_blocks;
  306. }
  307. if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
  308. ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, allocated %d "
  309. "with only %d reserved metadata blocks\n", __func__,
  310. inode->i_ino, ei->i_allocated_meta_blocks,
  311. ei->i_reserved_meta_blocks);
  312. WARN_ON(1);
  313. ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
  314. }
  315. /* Update per-inode reservations */
  316. ei->i_reserved_data_blocks -= used;
  317. ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
  318. percpu_counter_sub(&sbi->s_dirtyclusters_counter,
  319. used + ei->i_allocated_meta_blocks);
  320. ei->i_allocated_meta_blocks = 0;
  321. if (ei->i_reserved_data_blocks == 0) {
  322. /*
  323. * We can release all of the reserved metadata blocks
  324. * only when we have written all of the delayed
  325. * allocation blocks.
  326. */
  327. percpu_counter_sub(&sbi->s_dirtyclusters_counter,
  328. ei->i_reserved_meta_blocks);
  329. ei->i_reserved_meta_blocks = 0;
  330. ei->i_da_metadata_calc_len = 0;
  331. }
  332. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  333. /* Update quota subsystem for data blocks */
  334. if (quota_claim)
  335. dquot_claim_block(inode, EXT4_C2B(sbi, used));
  336. else {
  337. /*
  338. * We did fallocate with an offset that is already delayed
  339. * allocated. So on delayed allocated writeback we should
  340. * not re-claim the quota for fallocated blocks.
  341. */
  342. dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
  343. }
  344. /*
  345. * If we have done all the pending block allocations and if
  346. * there aren't any writers on the inode, we can discard the
  347. * inode's preallocations.
  348. */
  349. if ((ei->i_reserved_data_blocks == 0) &&
  350. (atomic_read(&inode->i_writecount) == 0))
  351. ext4_discard_preallocations(inode);
  352. }
  353. static int __check_block_validity(struct inode *inode, const char *func,
  354. unsigned int line,
  355. struct ext4_map_blocks *map)
  356. {
  357. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
  358. map->m_len)) {
  359. printk(KERN_ERR "printing inode..\n");
  360. print_block_data(inode->i_sb, 0, (unsigned char *)inode,
  361. 0, EXT4_INODE_SIZE(inode->i_sb));
  362. ext4_error_inode(inode, func, line, map->m_pblk,
  363. "lblock %lu mapped to illegal pblock "
  364. "(length %d)", (unsigned long) map->m_lblk,
  365. map->m_len);
  366. return -EIO;
  367. }
  368. return 0;
  369. }
  370. #define check_block_validity(inode, map) \
  371. __check_block_validity((inode), __func__, __LINE__, (map))
  372. /*
  373. * Return the number of contiguous dirty pages in a given inode
  374. * starting at page frame idx.
  375. */
  376. static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
  377. unsigned int max_pages)
  378. {
  379. struct address_space *mapping = inode->i_mapping;
  380. pgoff_t index;
  381. struct pagevec pvec;
  382. pgoff_t num = 0;
  383. int i, nr_pages, done = 0;
  384. if (max_pages == 0)
  385. return 0;
  386. pagevec_init(&pvec, 0);
  387. while (!done) {
  388. index = idx;
  389. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
  390. PAGECACHE_TAG_DIRTY,
  391. (pgoff_t)PAGEVEC_SIZE);
  392. if (nr_pages == 0)
  393. break;
  394. for (i = 0; i < nr_pages; i++) {
  395. struct page *page = pvec.pages[i];
  396. struct buffer_head *bh, *head;
  397. lock_page(page);
  398. if (unlikely(page->mapping != mapping) ||
  399. !PageDirty(page) ||
  400. PageWriteback(page) ||
  401. page->index != idx) {
  402. done = 1;
  403. unlock_page(page);
  404. break;
  405. }
  406. if (page_has_buffers(page)) {
  407. bh = head = page_buffers(page);
  408. do {
  409. if (!buffer_delay(bh) &&
  410. !buffer_unwritten(bh))
  411. done = 1;
  412. bh = bh->b_this_page;
  413. } while (!done && (bh != head));
  414. }
  415. unlock_page(page);
  416. if (done)
  417. break;
  418. idx++;
  419. num++;
  420. if (num >= max_pages) {
  421. done = 1;
  422. break;
  423. }
  424. }
  425. pagevec_release(&pvec);
  426. }
  427. return num;
  428. }
  429. /*
  430. * Sets the BH_Da_Mapped bit on the buffer heads corresponding to the given map.
  431. */
  432. static void set_buffers_da_mapped(struct inode *inode,
  433. struct ext4_map_blocks *map)
  434. {
  435. struct address_space *mapping = inode->i_mapping;
  436. struct pagevec pvec;
  437. int i, nr_pages;
  438. pgoff_t index, end;
  439. index = map->m_lblk >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
  440. end = (map->m_lblk + map->m_len - 1) >>
  441. (PAGE_CACHE_SHIFT - inode->i_blkbits);
  442. pagevec_init(&pvec, 0);
  443. while (index <= end) {
  444. nr_pages = pagevec_lookup(&pvec, mapping, index,
  445. min(end - index + 1,
  446. (pgoff_t)PAGEVEC_SIZE));
  447. if (nr_pages == 0)
  448. break;
  449. for (i = 0; i < nr_pages; i++) {
  450. struct page *page = pvec.pages[i];
  451. struct buffer_head *bh, *head;
  452. if (unlikely(page->mapping != mapping) ||
  453. !PageDirty(page))
  454. break;
  455. if (page_has_buffers(page)) {
  456. bh = head = page_buffers(page);
  457. do {
  458. set_buffer_da_mapped(bh);
  459. bh = bh->b_this_page;
  460. } while (bh != head);
  461. }
  462. index++;
  463. }
  464. pagevec_release(&pvec);
  465. }
  466. }
  467. /*
  468. * The ext4_map_blocks() function tries to look up the requested blocks,
  469. * and returns if the blocks are already mapped.
  470. *
  471. * Otherwise it takes the write lock of the i_data_sem and allocate blocks
  472. * and store the allocated blocks in the result buffer head and mark it
  473. * mapped.
  474. *
  475. * If file type is extents based, it will call ext4_ext_map_blocks(),
  476. * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
  477. * based files
  478. *
  479. * On success, it returns the number of blocks being mapped or allocate.
  480. * if create==0 and the blocks are pre-allocated and uninitialized block,
  481. * the result buffer head is unmapped. If the create ==1, it will make sure
  482. * the buffer head is mapped.
  483. *
  484. * It returns 0 if plain look up failed (blocks have not been allocated), in
  485. * that case, buffer head is unmapped
  486. *
  487. * It returns the error in case of allocation failure.
  488. */
  489. int ext4_map_blocks(handle_t *handle, struct inode *inode,
  490. struct ext4_map_blocks *map, int flags)
  491. {
  492. int retval;
  493. map->m_flags = 0;
  494. ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
  495. "logical block %lu\n", inode->i_ino, flags, map->m_len,
  496. (unsigned long) map->m_lblk);
  497. /*
  498. * Try to see if we can get the block without requesting a new
  499. * file system block.
  500. */
  501. down_read((&EXT4_I(inode)->i_data_sem));
  502. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  503. retval = ext4_ext_map_blocks(handle, inode, map, flags &
  504. EXT4_GET_BLOCKS_KEEP_SIZE);
  505. } else {
  506. retval = ext4_ind_map_blocks(handle, inode, map, flags &
  507. EXT4_GET_BLOCKS_KEEP_SIZE);
  508. }
  509. up_read((&EXT4_I(inode)->i_data_sem));
  510. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
  511. int ret = check_block_validity(inode, map);
  512. if (ret != 0)
  513. return ret;
  514. }
  515. /* If it is only a block(s) look up */
  516. if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
  517. return retval;
  518. /*
  519. * Returns if the blocks have already allocated
  520. *
  521. * Note that if blocks have been preallocated
  522. * ext4_ext_get_block() returns the create = 0
  523. * with buffer head unmapped.
  524. */
  525. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
  526. return retval;
  527. /*
  528. * When we call get_blocks without the create flag, the
  529. * BH_Unwritten flag could have gotten set if the blocks
  530. * requested were part of a uninitialized extent. We need to
  531. * clear this flag now that we are committed to convert all or
  532. * part of the uninitialized extent to be an initialized
  533. * extent. This is because we need to avoid the combination
  534. * of BH_Unwritten and BH_Mapped flags being simultaneously
  535. * set on the buffer_head.
  536. */
  537. map->m_flags &= ~EXT4_MAP_UNWRITTEN;
  538. /*
  539. * New blocks allocate and/or writing to uninitialized extent
  540. * will possibly result in updating i_data, so we take
  541. * the write lock of i_data_sem, and call get_blocks()
  542. * with create == 1 flag.
  543. */
  544. down_write((&EXT4_I(inode)->i_data_sem));
  545. /*
  546. * if the caller is from delayed allocation writeout path
  547. * we have already reserved fs blocks for allocation
  548. * let the underlying get_block() function know to
  549. * avoid double accounting
  550. */
  551. if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
  552. ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
  553. /*
  554. * We need to check for EXT4 here because migrate
  555. * could have changed the inode type in between
  556. */
  557. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  558. retval = ext4_ext_map_blocks(handle, inode, map, flags);
  559. } else {
  560. retval = ext4_ind_map_blocks(handle, inode, map, flags);
  561. if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
  562. /*
  563. * We allocated new blocks which will result in
  564. * i_data's format changing. Force the migrate
  565. * to fail by clearing migrate flags
  566. */
  567. ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
  568. }
  569. /*
  570. * Update reserved blocks/metadata blocks after successful
  571. * block allocation which had been deferred till now. We don't
  572. * support fallocate for non extent files. So we can update
  573. * reserve space here.
  574. */
  575. if ((retval > 0) &&
  576. (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
  577. ext4_da_update_reserve_space(inode, retval, 1);
  578. }
  579. if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
  580. ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
  581. /* If we have successfully mapped the delayed allocated blocks,
  582. * set the BH_Da_Mapped bit on them. Its important to do this
  583. * under the protection of i_data_sem.
  584. */
  585. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
  586. set_buffers_da_mapped(inode, map);
  587. }
  588. up_write((&EXT4_I(inode)->i_data_sem));
  589. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
  590. int ret = check_block_validity(inode, map);
  591. if (ret != 0)
  592. return ret;
  593. }
  594. return retval;
  595. }
  596. /* Maximum number of blocks we map for direct IO at once. */
  597. #define DIO_MAX_BLOCKS 4096
  598. static int _ext4_get_block(struct inode *inode, sector_t iblock,
  599. struct buffer_head *bh, int flags)
  600. {
  601. handle_t *handle = ext4_journal_current_handle();
  602. struct ext4_map_blocks map;
  603. int ret = 0, started = 0;
  604. int dio_credits;
  605. map.m_lblk = iblock;
  606. map.m_len = bh->b_size >> inode->i_blkbits;
  607. if (flags && !handle) {
  608. /* Direct IO write... */
  609. if (map.m_len > DIO_MAX_BLOCKS)
  610. map.m_len = DIO_MAX_BLOCKS;
  611. dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
  612. handle = ext4_journal_start(inode, dio_credits);
  613. if (IS_ERR(handle)) {
  614. ret = PTR_ERR(handle);
  615. return ret;
  616. }
  617. started = 1;
  618. }
  619. ret = ext4_map_blocks(handle, inode, &map, flags);
  620. if (ret > 0) {
  621. map_bh(bh, inode->i_sb, map.m_pblk);
  622. bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
  623. bh->b_size = inode->i_sb->s_blocksize * map.m_len;
  624. ret = 0;
  625. }
  626. if (started)
  627. ext4_journal_stop(handle);
  628. return ret;
  629. }
  630. int ext4_get_block(struct inode *inode, sector_t iblock,
  631. struct buffer_head *bh, int create)
  632. {
  633. return _ext4_get_block(inode, iblock, bh,
  634. create ? EXT4_GET_BLOCKS_CREATE : 0);
  635. }
  636. /*
  637. * `handle' can be NULL if create is zero
  638. */
  639. struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
  640. ext4_lblk_t block, int create, int *errp)
  641. {
  642. struct ext4_map_blocks map;
  643. struct buffer_head *bh;
  644. int fatal = 0, err;
  645. J_ASSERT(handle != NULL || create == 0);
  646. map.m_lblk = block;
  647. map.m_len = 1;
  648. err = ext4_map_blocks(handle, inode, &map,
  649. create ? EXT4_GET_BLOCKS_CREATE : 0);
  650. if (err < 0)
  651. *errp = err;
  652. if (err <= 0)
  653. return NULL;
  654. *errp = 0;
  655. bh = sb_getblk(inode->i_sb, map.m_pblk);
  656. if (!bh) {
  657. *errp = -ENOMEM;
  658. return NULL;
  659. }
  660. if (map.m_flags & EXT4_MAP_NEW) {
  661. J_ASSERT(create != 0);
  662. J_ASSERT(handle != NULL);
  663. /*
  664. * Now that we do not always journal data, we should
  665. * keep in mind whether this should always journal the
  666. * new buffer as metadata. For now, regular file
  667. * writes use ext4_get_block instead, so it's not a
  668. * problem.
  669. */
  670. lock_buffer(bh);
  671. BUFFER_TRACE(bh, "call get_create_access");
  672. fatal = ext4_journal_get_create_access(handle, bh);
  673. if (!fatal && !buffer_uptodate(bh)) {
  674. memset(bh->b_data, 0, inode->i_sb->s_blocksize);
  675. set_buffer_uptodate(bh);
  676. }
  677. unlock_buffer(bh);
  678. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  679. err = ext4_handle_dirty_metadata(handle, inode, bh);
  680. if (!fatal)
  681. fatal = err;
  682. } else {
  683. BUFFER_TRACE(bh, "not a new buffer");
  684. }
  685. if (fatal) {
  686. *errp = fatal;
  687. brelse(bh);
  688. bh = NULL;
  689. }
  690. return bh;
  691. }
  692. struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
  693. ext4_lblk_t block, int create, int *err)
  694. {
  695. struct buffer_head *bh;
  696. bh = ext4_getblk(handle, inode, block, create, err);
  697. if (!bh)
  698. return bh;
  699. if (buffer_uptodate(bh))
  700. return bh;
  701. ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
  702. wait_on_buffer(bh);
  703. if (buffer_uptodate(bh))
  704. return bh;
  705. put_bh(bh);
  706. *err = -EIO;
  707. return NULL;
  708. }
  709. static int walk_page_buffers(handle_t *handle,
  710. struct buffer_head *head,
  711. unsigned from,
  712. unsigned to,
  713. int *partial,
  714. int (*fn)(handle_t *handle,
  715. struct buffer_head *bh))
  716. {
  717. struct buffer_head *bh;
  718. unsigned block_start, block_end;
  719. unsigned blocksize = head->b_size;
  720. int err, ret = 0;
  721. struct buffer_head *next;
  722. for (bh = head, block_start = 0;
  723. ret == 0 && (bh != head || !block_start);
  724. block_start = block_end, bh = next) {
  725. next = bh->b_this_page;
  726. block_end = block_start + blocksize;
  727. if (block_end <= from || block_start >= to) {
  728. if (partial && !buffer_uptodate(bh))
  729. *partial = 1;
  730. continue;
  731. }
  732. err = (*fn)(handle, bh);
  733. if (!ret)
  734. ret = err;
  735. }
  736. return ret;
  737. }
  738. /*
  739. * To preserve ordering, it is essential that the hole instantiation and
  740. * the data write be encapsulated in a single transaction. We cannot
  741. * close off a transaction and start a new one between the ext4_get_block()
  742. * and the commit_write(). So doing the jbd2_journal_start at the start of
  743. * prepare_write() is the right place.
  744. *
  745. * Also, this function can nest inside ext4_writepage() ->
  746. * block_write_full_page(). In that case, we *know* that ext4_writepage()
  747. * has generated enough buffer credits to do the whole page. So we won't
  748. * block on the journal in that case, which is good, because the caller may
  749. * be PF_MEMALLOC.
  750. *
  751. * By accident, ext4 can be reentered when a transaction is open via
  752. * quota file writes. If we were to commit the transaction while thus
  753. * reentered, there can be a deadlock - we would be holding a quota
  754. * lock, and the commit would never complete if another thread had a
  755. * transaction open and was blocking on the quota lock - a ranking
  756. * violation.
  757. *
  758. * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
  759. * will _not_ run commit under these circumstances because handle->h_ref
  760. * is elevated. We'll still have enough credits for the tiny quotafile
  761. * write.
  762. */
  763. static int do_journal_get_write_access(handle_t *handle,
  764. struct buffer_head *bh)
  765. {
  766. int dirty = buffer_dirty(bh);
  767. int ret;
  768. if (!buffer_mapped(bh) || buffer_freed(bh))
  769. return 0;
  770. /*
  771. * __block_write_begin() could have dirtied some buffers. Clean
  772. * the dirty bit as jbd2_journal_get_write_access() could complain
  773. * otherwise about fs integrity issues. Setting of the dirty bit
  774. * by __block_write_begin() isn't a real problem here as we clear
  775. * the bit before releasing a page lock and thus writeback cannot
  776. * ever write the buffer.
  777. */
  778. if (dirty)
  779. clear_buffer_dirty(bh);
  780. ret = ext4_journal_get_write_access(handle, bh);
  781. if (!ret && dirty)
  782. ret = ext4_handle_dirty_metadata(handle, NULL, bh);
  783. return ret;
  784. }
  785. static int ext4_get_block_write(struct inode *inode, sector_t iblock,
  786. struct buffer_head *bh_result, int create);
  787. static int ext4_write_begin(struct file *file, struct address_space *mapping,
  788. loff_t pos, unsigned len, unsigned flags,
  789. struct page **pagep, void **fsdata)
  790. {
  791. struct inode *inode = mapping->host;
  792. int ret, needed_blocks;
  793. handle_t *handle;
  794. int retries = 0;
  795. struct page *page;
  796. pgoff_t index;
  797. unsigned from, to;
  798. trace_ext4_write_begin(inode, pos, len, flags);
  799. /*
  800. * Reserve one block more for addition to orphan list in case
  801. * we allocate blocks but write fails for some reason
  802. */
  803. needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
  804. index = pos >> PAGE_CACHE_SHIFT;
  805. from = pos & (PAGE_CACHE_SIZE - 1);
  806. to = from + len;
  807. /*
  808. * grab_cache_page_write_begin() can take a long time if the
  809. * system is thrashing due to memory pressure, or if the page
  810. * is being written back. So grab it first before we start
  811. * the transaction handle. This also allows us to allocate
  812. * the page (if needed) without using GFP_NOFS.
  813. */
  814. retry_grab:
  815. page = grab_cache_page_write_begin(mapping, index, flags);
  816. if (!page)
  817. return -ENOMEM;
  818. unlock_page(page);
  819. retry_journal:
  820. handle = ext4_journal_start(inode, needed_blocks);
  821. if (IS_ERR(handle)) {
  822. page_cache_release(page);
  823. return PTR_ERR(handle);
  824. }
  825. lock_page(page);
  826. if (page->mapping != mapping) {
  827. /* The page got truncated from under us */
  828. unlock_page(page);
  829. page_cache_release(page);
  830. ext4_journal_stop(handle);
  831. goto retry_grab;
  832. }
  833. wait_on_page_writeback(page);
  834. if (ext4_should_dioread_nolock(inode))
  835. ret = __block_write_begin(page, pos, len, ext4_get_block_write);
  836. else
  837. ret = __block_write_begin(page, pos, len, ext4_get_block);
  838. if (!ret && ext4_should_journal_data(inode)) {
  839. ret = walk_page_buffers(handle, page_buffers(page),
  840. from, to, NULL, do_journal_get_write_access);
  841. }
  842. if (ret) {
  843. unlock_page(page);
  844. /*
  845. * __block_write_begin may have instantiated a few blocks
  846. * outside i_size. Trim these off again. Don't need
  847. * i_size_read because we hold i_mutex.
  848. *
  849. * Add inode to orphan list in case we crash before
  850. * truncate finishes
  851. */
  852. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  853. ext4_orphan_add(handle, inode);
  854. ext4_journal_stop(handle);
  855. if (pos + len > inode->i_size) {
  856. ext4_truncate_failed_write(inode);
  857. /*
  858. * If truncate failed early the inode might
  859. * still be on the orphan list; we need to
  860. * make sure the inode is removed from the
  861. * orphan list in that case.
  862. */
  863. if (inode->i_nlink)
  864. ext4_orphan_del(NULL, inode);
  865. }
  866. if (ret == -ENOSPC &&
  867. ext4_should_retry_alloc(inode->i_sb, &retries))
  868. goto retry_journal;
  869. page_cache_release(page);
  870. return ret;
  871. }
  872. *pagep = page;
  873. return ret;
  874. }
  875. /* For write_end() in data=journal mode */
  876. static int write_end_fn(handle_t *handle, struct buffer_head *bh)
  877. {
  878. if (!buffer_mapped(bh) || buffer_freed(bh))
  879. return 0;
  880. set_buffer_uptodate(bh);
  881. return ext4_handle_dirty_metadata(handle, NULL, bh);
  882. }
  883. static int ext4_generic_write_end(struct file *file,
  884. struct address_space *mapping,
  885. loff_t pos, unsigned len, unsigned copied,
  886. struct page *page, void *fsdata)
  887. {
  888. int i_size_changed = 0;
  889. struct inode *inode = mapping->host;
  890. handle_t *handle = ext4_journal_current_handle();
  891. copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
  892. /*
  893. * No need to use i_size_read() here, the i_size
  894. * cannot change under us because we hold i_mutex.
  895. *
  896. * But it's important to update i_size while still holding page lock:
  897. * page writeout could otherwise come in and zero beyond i_size.
  898. */
  899. if (pos + copied > inode->i_size) {
  900. i_size_write(inode, pos + copied);
  901. i_size_changed = 1;
  902. }
  903. if (pos + copied > EXT4_I(inode)->i_disksize) {
  904. /* We need to mark inode dirty even if
  905. * new_i_size is less that inode->i_size
  906. * bu greater than i_disksize.(hint delalloc)
  907. */
  908. ext4_update_i_disksize(inode, (pos + copied));
  909. i_size_changed = 1;
  910. }
  911. unlock_page(page);
  912. page_cache_release(page);
  913. /*
  914. * Don't mark the inode dirty under page lock. First, it unnecessarily
  915. * makes the holding time of page lock longer. Second, it forces lock
  916. * ordering of page lock and transaction start for journaling
  917. * filesystems.
  918. */
  919. if (i_size_changed)
  920. ext4_mark_inode_dirty(handle, inode);
  921. return copied;
  922. }
  923. /*
  924. * We need to pick up the new inode size which generic_commit_write gave us
  925. * `file' can be NULL - eg, when called from page_symlink().
  926. *
  927. * ext4 never places buffers on inode->i_mapping->private_list. metadata
  928. * buffers are managed internally.
  929. */
  930. static int ext4_ordered_write_end(struct file *file,
  931. struct address_space *mapping,
  932. loff_t pos, unsigned len, unsigned copied,
  933. struct page *page, void *fsdata)
  934. {
  935. handle_t *handle = ext4_journal_current_handle();
  936. struct inode *inode = mapping->host;
  937. int ret = 0, ret2;
  938. trace_ext4_ordered_write_end(inode, pos, len, copied);
  939. ret = ext4_jbd2_file_inode(handle, inode);
  940. if (ret == 0) {
  941. ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
  942. page, fsdata);
  943. copied = ret2;
  944. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  945. /* if we have allocated more blocks and copied
  946. * less. We will have blocks allocated outside
  947. * inode->i_size. So truncate them
  948. */
  949. ext4_orphan_add(handle, inode);
  950. if (ret2 < 0)
  951. ret = ret2;
  952. } else {
  953. unlock_page(page);
  954. page_cache_release(page);
  955. }
  956. ret2 = ext4_journal_stop(handle);
  957. if (!ret)
  958. ret = ret2;
  959. if (pos + len > inode->i_size) {
  960. ext4_truncate_failed_write(inode);
  961. /*
  962. * If truncate failed early the inode might still be
  963. * on the orphan list; we need to make sure the inode
  964. * is removed from the orphan list in that case.
  965. */
  966. if (inode->i_nlink)
  967. ext4_orphan_del(NULL, inode);
  968. }
  969. return ret ? ret : copied;
  970. }
  971. static int ext4_writeback_write_end(struct file *file,
  972. struct address_space *mapping,
  973. loff_t pos, unsigned len, unsigned copied,
  974. struct page *page, void *fsdata)
  975. {
  976. handle_t *handle = ext4_journal_current_handle();
  977. struct inode *inode = mapping->host;
  978. int ret = 0, ret2;
  979. trace_ext4_writeback_write_end(inode, pos, len, copied);
  980. ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
  981. page, fsdata);
  982. copied = ret2;
  983. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  984. /* if we have allocated more blocks and copied
  985. * less. We will have blocks allocated outside
  986. * inode->i_size. So truncate them
  987. */
  988. ext4_orphan_add(handle, inode);
  989. if (ret2 < 0)
  990. ret = ret2;
  991. ret2 = ext4_journal_stop(handle);
  992. if (!ret)
  993. ret = ret2;
  994. if (pos + len > inode->i_size) {
  995. ext4_truncate_failed_write(inode);
  996. /*
  997. * If truncate failed early the inode might still be
  998. * on the orphan list; we need to make sure the inode
  999. * is removed from the orphan list in that case.
  1000. */
  1001. if (inode->i_nlink)
  1002. ext4_orphan_del(NULL, inode);
  1003. }
  1004. return ret ? ret : copied;
  1005. }
  1006. static int ext4_journalled_write_end(struct file *file,
  1007. struct address_space *mapping,
  1008. loff_t pos, unsigned len, unsigned copied,
  1009. struct page *page, void *fsdata)
  1010. {
  1011. handle_t *handle = ext4_journal_current_handle();
  1012. struct inode *inode = mapping->host;
  1013. int ret = 0, ret2;
  1014. int partial = 0;
  1015. unsigned from, to;
  1016. loff_t new_i_size;
  1017. trace_ext4_journalled_write_end(inode, pos, len, copied);
  1018. from = pos & (PAGE_CACHE_SIZE - 1);
  1019. to = from + len;
  1020. BUG_ON(!ext4_handle_valid(handle));
  1021. if (copied < len) {
  1022. if (!PageUptodate(page))
  1023. copied = 0;
  1024. page_zero_new_buffers(page, from+copied, to);
  1025. }
  1026. ret = walk_page_buffers(handle, page_buffers(page), from,
  1027. to, &partial, write_end_fn);
  1028. if (!partial)
  1029. SetPageUptodate(page);
  1030. new_i_size = pos + copied;
  1031. if (new_i_size > inode->i_size)
  1032. i_size_write(inode, pos+copied);
  1033. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  1034. EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
  1035. if (new_i_size > EXT4_I(inode)->i_disksize) {
  1036. ext4_update_i_disksize(inode, new_i_size);
  1037. ret2 = ext4_mark_inode_dirty(handle, inode);
  1038. if (!ret)
  1039. ret = ret2;
  1040. }
  1041. unlock_page(page);
  1042. page_cache_release(page);
  1043. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  1044. /* if we have allocated more blocks and copied
  1045. * less. We will have blocks allocated outside
  1046. * inode->i_size. So truncate them
  1047. */
  1048. ext4_orphan_add(handle, inode);
  1049. ret2 = ext4_journal_stop(handle);
  1050. if (!ret)
  1051. ret = ret2;
  1052. if (pos + len > inode->i_size) {
  1053. ext4_truncate_failed_write(inode);
  1054. /*
  1055. * If truncate failed early the inode might still be
  1056. * on the orphan list; we need to make sure the inode
  1057. * is removed from the orphan list in that case.
  1058. */
  1059. if (inode->i_nlink)
  1060. ext4_orphan_del(NULL, inode);
  1061. }
  1062. return ret ? ret : copied;
  1063. }
  1064. /*
  1065. * Reserve a single cluster located at lblock
  1066. */
  1067. static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
  1068. {
  1069. int retries = 0;
  1070. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1071. struct ext4_inode_info *ei = EXT4_I(inode);
  1072. unsigned int md_needed;
  1073. int ret;
  1074. ext4_lblk_t save_last_lblock;
  1075. int save_len;
  1076. /*
  1077. * We will charge metadata quota at writeout time; this saves
  1078. * us from metadata over-estimation, though we may go over by
  1079. * a small amount in the end. Here we just reserve for data.
  1080. */
  1081. ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
  1082. if (ret)
  1083. return ret;
  1084. /*
  1085. * recalculate the amount of metadata blocks to reserve
  1086. * in order to allocate nrblocks
  1087. * worse case is one extent per block
  1088. */
  1089. repeat:
  1090. spin_lock(&ei->i_block_reservation_lock);
  1091. /*
  1092. * ext4_calc_metadata_amount() has side effects, which we have
  1093. * to be prepared undo if we fail to claim space.
  1094. */
  1095. save_len = ei->i_da_metadata_calc_len;
  1096. save_last_lblock = ei->i_da_metadata_calc_last_lblock;
  1097. md_needed = EXT4_NUM_B2C(sbi,
  1098. ext4_calc_metadata_amount(inode, lblock));
  1099. trace_ext4_da_reserve_space(inode, md_needed);
  1100. /*
  1101. * We do still charge estimated metadata to the sb though;
  1102. * we cannot afford to run out of free blocks.
  1103. */
  1104. if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
  1105. ei->i_da_metadata_calc_len = save_len;
  1106. ei->i_da_metadata_calc_last_lblock = save_last_lblock;
  1107. spin_unlock(&ei->i_block_reservation_lock);
  1108. if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
  1109. yield();
  1110. goto repeat;
  1111. }
  1112. dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
  1113. return -ENOSPC;
  1114. }
  1115. ei->i_reserved_data_blocks++;
  1116. ei->i_reserved_meta_blocks += md_needed;
  1117. spin_unlock(&ei->i_block_reservation_lock);
  1118. return 0; /* success */
  1119. }
  1120. static void ext4_da_release_space(struct inode *inode, int to_free)
  1121. {
  1122. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1123. struct ext4_inode_info *ei = EXT4_I(inode);
  1124. if (!to_free)
  1125. return; /* Nothing to release, exit */
  1126. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  1127. trace_ext4_da_release_space(inode, to_free);
  1128. if (unlikely(to_free > ei->i_reserved_data_blocks)) {
  1129. /*
  1130. * if there aren't enough reserved blocks, then the
  1131. * counter is messed up somewhere. Since this
  1132. * function is called from invalidate page, it's
  1133. * harmless to return without any action.
  1134. */
  1135. ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
  1136. "ino %lu, to_free %d with only %d reserved "
  1137. "data blocks", inode->i_ino, to_free,
  1138. ei->i_reserved_data_blocks);
  1139. WARN_ON(1);
  1140. to_free = ei->i_reserved_data_blocks;
  1141. }
  1142. ei->i_reserved_data_blocks -= to_free;
  1143. if (ei->i_reserved_data_blocks == 0) {
  1144. /*
  1145. * We can release all of the reserved metadata blocks
  1146. * only when we have written all of the delayed
  1147. * allocation blocks.
  1148. * Note that in case of bigalloc, i_reserved_meta_blocks,
  1149. * i_reserved_data_blocks, etc. refer to number of clusters.
  1150. */
  1151. percpu_counter_sub(&sbi->s_dirtyclusters_counter,
  1152. ei->i_reserved_meta_blocks);
  1153. ei->i_reserved_meta_blocks = 0;
  1154. ei->i_da_metadata_calc_len = 0;
  1155. }
  1156. /* update fs dirty data blocks counter */
  1157. percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
  1158. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  1159. dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
  1160. }
  1161. static void ext4_da_page_release_reservation(struct page *page,
  1162. unsigned long offset)
  1163. {
  1164. int to_release = 0;
  1165. struct buffer_head *head, *bh;
  1166. unsigned int curr_off = 0;
  1167. struct inode *inode = page->mapping->host;
  1168. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1169. int num_clusters;
  1170. head = page_buffers(page);
  1171. bh = head;
  1172. do {
  1173. unsigned int next_off = curr_off + bh->b_size;
  1174. if ((offset <= curr_off) && (buffer_delay(bh))) {
  1175. to_release++;
  1176. clear_buffer_delay(bh);
  1177. clear_buffer_da_mapped(bh);
  1178. }
  1179. curr_off = next_off;
  1180. } while ((bh = bh->b_this_page) != head);
  1181. /* If we have released all the blocks belonging to a cluster, then we
  1182. * need to release the reserved space for that cluster. */
  1183. num_clusters = EXT4_NUM_B2C(sbi, to_release);
  1184. while (num_clusters > 0) {
  1185. ext4_fsblk_t lblk;
  1186. lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
  1187. ((num_clusters - 1) << sbi->s_cluster_bits);
  1188. if (sbi->s_cluster_ratio == 1 ||
  1189. !ext4_find_delalloc_cluster(inode, lblk, 1))
  1190. ext4_da_release_space(inode, 1);
  1191. num_clusters--;
  1192. }
  1193. }
  1194. /*
  1195. * Delayed allocation stuff
  1196. */
  1197. /*
  1198. * mpage_da_submit_io - walks through extent of pages and try to write
  1199. * them with writepage() call back
  1200. *
  1201. * @mpd->inode: inode
  1202. * @mpd->first_page: first page of the extent
  1203. * @mpd->next_page: page after the last page of the extent
  1204. *
  1205. * By the time mpage_da_submit_io() is called we expect all blocks
  1206. * to be allocated. this may be wrong if allocation failed.
  1207. *
  1208. * As pages are already locked by write_cache_pages(), we can't use it
  1209. */
  1210. static int mpage_da_submit_io(struct mpage_da_data *mpd,
  1211. struct ext4_map_blocks *map)
  1212. {
  1213. struct pagevec pvec;
  1214. unsigned long index, end;
  1215. int ret = 0, err, nr_pages, i;
  1216. struct inode *inode = mpd->inode;
  1217. struct address_space *mapping = inode->i_mapping;
  1218. loff_t size = i_size_read(inode);
  1219. unsigned int len, block_start;
  1220. struct buffer_head *bh, *page_bufs = NULL;
  1221. int journal_data = ext4_should_journal_data(inode);
  1222. sector_t pblock = 0, cur_logical = 0;
  1223. struct ext4_io_submit io_submit;
  1224. BUG_ON(mpd->next_page <= mpd->first_page);
  1225. memset(&io_submit, 0, sizeof(io_submit));
  1226. /*
  1227. * We need to start from the first_page to the next_page - 1
  1228. * to make sure we also write the mapped dirty buffer_heads.
  1229. * If we look at mpd->b_blocknr we would only be looking
  1230. * at the currently mapped buffer_heads.
  1231. */
  1232. index = mpd->first_page;
  1233. end = mpd->next_page - 1;
  1234. pagevec_init(&pvec, 0);
  1235. while (index <= end) {
  1236. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1237. if (nr_pages == 0)
  1238. break;
  1239. for (i = 0; i < nr_pages; i++) {
  1240. int commit_write = 0, skip_page = 0;
  1241. struct page *page = pvec.pages[i];
  1242. index = page->index;
  1243. if (index > end)
  1244. break;
  1245. if (index == size >> PAGE_CACHE_SHIFT)
  1246. len = size & ~PAGE_CACHE_MASK;
  1247. else
  1248. len = PAGE_CACHE_SIZE;
  1249. if (map) {
  1250. cur_logical = index << (PAGE_CACHE_SHIFT -
  1251. inode->i_blkbits);
  1252. pblock = map->m_pblk + (cur_logical -
  1253. map->m_lblk);
  1254. }
  1255. index++;
  1256. BUG_ON(!PageLocked(page));
  1257. BUG_ON(PageWriteback(page));
  1258. /*
  1259. * If the page does not have buffers (for
  1260. * whatever reason), try to create them using
  1261. * __block_write_begin. If this fails,
  1262. * skip the page and move on.
  1263. */
  1264. if (!page_has_buffers(page)) {
  1265. if (__block_write_begin(page, 0, len,
  1266. noalloc_get_block_write)) {
  1267. skip_page:
  1268. unlock_page(page);
  1269. continue;
  1270. }
  1271. commit_write = 1;
  1272. }
  1273. bh = page_bufs = page_buffers(page);
  1274. block_start = 0;
  1275. do {
  1276. if (!bh)
  1277. goto skip_page;
  1278. if (map && (cur_logical >= map->m_lblk) &&
  1279. (cur_logical <= (map->m_lblk +
  1280. (map->m_len - 1)))) {
  1281. if (buffer_delay(bh)) {
  1282. clear_buffer_delay(bh);
  1283. bh->b_blocknr = pblock;
  1284. }
  1285. if (buffer_da_mapped(bh))
  1286. clear_buffer_da_mapped(bh);
  1287. if (buffer_unwritten(bh) ||
  1288. buffer_mapped(bh))
  1289. BUG_ON(bh->b_blocknr != pblock);
  1290. if (map->m_flags & EXT4_MAP_UNINIT)
  1291. set_buffer_uninit(bh);
  1292. clear_buffer_unwritten(bh);
  1293. }
  1294. /*
  1295. * skip page if block allocation undone and
  1296. * block is dirty
  1297. */
  1298. if (ext4_bh_delay_or_unwritten(NULL, bh))
  1299. skip_page = 1;
  1300. bh = bh->b_this_page;
  1301. block_start += bh->b_size;
  1302. cur_logical++;
  1303. pblock++;
  1304. } while (bh != page_bufs);
  1305. if (skip_page)
  1306. goto skip_page;
  1307. if (commit_write)
  1308. /* mark the buffer_heads as dirty & uptodate */
  1309. block_commit_write(page, 0, len);
  1310. clear_page_dirty_for_io(page);
  1311. /*
  1312. * Delalloc doesn't support data journalling,
  1313. * but eventually maybe we'll lift this
  1314. * restriction.
  1315. */
  1316. if (unlikely(journal_data && PageChecked(page)))
  1317. err = __ext4_journalled_writepage(page, len);
  1318. else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
  1319. err = ext4_bio_write_page(&io_submit, page,
  1320. len, mpd->wbc);
  1321. else if (buffer_uninit(page_bufs)) {
  1322. ext4_set_bh_endio(page_bufs, inode);
  1323. err = block_write_full_page_endio(page,
  1324. noalloc_get_block_write,
  1325. mpd->wbc, ext4_end_io_buffer_write);
  1326. } else
  1327. err = block_write_full_page(page,
  1328. noalloc_get_block_write, mpd->wbc);
  1329. if (!err)
  1330. mpd->pages_written++;
  1331. /*
  1332. * In error case, we have to continue because
  1333. * remaining pages are still locked
  1334. */
  1335. if (ret == 0)
  1336. ret = err;
  1337. }
  1338. pagevec_release(&pvec);
  1339. }
  1340. ext4_io_submit(&io_submit);
  1341. return ret;
  1342. }
  1343. static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
  1344. {
  1345. int nr_pages, i;
  1346. pgoff_t index, end;
  1347. struct pagevec pvec;
  1348. struct inode *inode = mpd->inode;
  1349. struct address_space *mapping = inode->i_mapping;
  1350. index = mpd->first_page;
  1351. end = mpd->next_page - 1;
  1352. pagevec_init(&pvec, 0);
  1353. while (index <= end) {
  1354. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1355. if (nr_pages == 0)
  1356. break;
  1357. for (i = 0; i < nr_pages; i++) {
  1358. struct page *page = pvec.pages[i];
  1359. if (page->index > end)
  1360. break;
  1361. BUG_ON(!PageLocked(page));
  1362. BUG_ON(PageWriteback(page));
  1363. block_invalidatepage(page, 0);
  1364. ClearPageUptodate(page);
  1365. unlock_page(page);
  1366. }
  1367. index = pvec.pages[nr_pages - 1]->index + 1;
  1368. pagevec_release(&pvec);
  1369. }
  1370. return;
  1371. }
  1372. static void ext4_print_free_blocks(struct inode *inode)
  1373. {
  1374. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1375. struct super_block *sb = inode->i_sb;
  1376. ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
  1377. EXT4_C2B(EXT4_SB(inode->i_sb),
  1378. ext4_count_free_clusters(inode->i_sb)));
  1379. ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
  1380. ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
  1381. (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
  1382. percpu_counter_sum(&sbi->s_freeclusters_counter)));
  1383. ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
  1384. (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
  1385. percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
  1386. ext4_msg(sb, KERN_CRIT, "Block reservation details");
  1387. ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
  1388. EXT4_I(inode)->i_reserved_data_blocks);
  1389. ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
  1390. EXT4_I(inode)->i_reserved_meta_blocks);
  1391. return;
  1392. }
  1393. /*
  1394. * mpage_da_map_and_submit - go through given space, map them
  1395. * if necessary, and then submit them for I/O
  1396. *
  1397. * @mpd - bh describing space
  1398. *
  1399. * The function skips space we know is already mapped to disk blocks.
  1400. *
  1401. */
  1402. static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
  1403. {
  1404. int err, blks, get_blocks_flags;
  1405. struct ext4_map_blocks map, *mapp = NULL;
  1406. sector_t next = mpd->b_blocknr;
  1407. unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
  1408. loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
  1409. handle_t *handle = NULL;
  1410. /*
  1411. * If the blocks are mapped already, or we couldn't accumulate
  1412. * any blocks, then proceed immediately to the submission stage.
  1413. */
  1414. if ((mpd->b_size == 0) ||
  1415. ((mpd->b_state & (1 << BH_Mapped)) &&
  1416. !(mpd->b_state & (1 << BH_Delay)) &&
  1417. !(mpd->b_state & (1 << BH_Unwritten))))
  1418. goto submit_io;
  1419. handle = ext4_journal_current_handle();
  1420. BUG_ON(!handle);
  1421. /*
  1422. * Call ext4_map_blocks() to allocate any delayed allocation
  1423. * blocks, or to convert an uninitialized extent to be
  1424. * initialized (in the case where we have written into
  1425. * one or more preallocated blocks).
  1426. *
  1427. * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
  1428. * indicate that we are on the delayed allocation path. This
  1429. * affects functions in many different parts of the allocation
  1430. * call path. This flag exists primarily because we don't
  1431. * want to change *many* call functions, so ext4_map_blocks()
  1432. * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
  1433. * inode's allocation semaphore is taken.
  1434. *
  1435. * If the blocks in questions were delalloc blocks, set
  1436. * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
  1437. * variables are updated after the blocks have been allocated.
  1438. */
  1439. map.m_lblk = next;
  1440. map.m_len = max_blocks;
  1441. get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
  1442. if (ext4_should_dioread_nolock(mpd->inode))
  1443. get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
  1444. if (mpd->b_state & (1 << BH_Delay))
  1445. get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
  1446. blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
  1447. if (blks < 0) {
  1448. struct super_block *sb = mpd->inode->i_sb;
  1449. err = blks;
  1450. /*
  1451. * If get block returns EAGAIN or ENOSPC and there
  1452. * appears to be free blocks we will just let
  1453. * mpage_da_submit_io() unlock all of the pages.
  1454. */
  1455. if (err == -EAGAIN)
  1456. goto submit_io;
  1457. if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
  1458. mpd->retval = err;
  1459. goto submit_io;
  1460. }
  1461. /*
  1462. * get block failure will cause us to loop in
  1463. * writepages, because a_ops->writepage won't be able
  1464. * to make progress. The page will be redirtied by
  1465. * writepage and writepages will again try to write
  1466. * the same.
  1467. */
  1468. if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
  1469. ext4_msg(sb, KERN_CRIT,
  1470. "delayed block allocation failed for inode %lu "
  1471. "at logical offset %llu with max blocks %zd "
  1472. "with error %d", mpd->inode->i_ino,
  1473. (unsigned long long) next,
  1474. mpd->b_size >> mpd->inode->i_blkbits, err);
  1475. ext4_msg(sb, KERN_CRIT,
  1476. "This should not happen!! Data will be lost\n");
  1477. if (err == -ENOSPC)
  1478. ext4_print_free_blocks(mpd->inode);
  1479. }
  1480. /* invalidate all the pages */
  1481. ext4_da_block_invalidatepages(mpd);
  1482. /* Mark this page range as having been completed */
  1483. mpd->io_done = 1;
  1484. return;
  1485. }
  1486. BUG_ON(blks == 0);
  1487. mapp = &map;
  1488. if (map.m_flags & EXT4_MAP_NEW) {
  1489. struct block_device *bdev = mpd->inode->i_sb->s_bdev;
  1490. int i;
  1491. for (i = 0; i < map.m_len; i++)
  1492. unmap_underlying_metadata(bdev, map.m_pblk + i);
  1493. if (ext4_should_order_data(mpd->inode)) {
  1494. err = ext4_jbd2_file_inode(handle, mpd->inode);
  1495. if (err) {
  1496. /* Only if the journal is aborted */
  1497. mpd->retval = err;
  1498. goto submit_io;
  1499. }
  1500. }
  1501. }
  1502. /*
  1503. * Update on-disk size along with block allocation.
  1504. */
  1505. disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
  1506. if (disksize > i_size_read(mpd->inode))
  1507. disksize = i_size_read(mpd->inode);
  1508. if (disksize > EXT4_I(mpd->inode)->i_disksize) {
  1509. ext4_update_i_disksize(mpd->inode, disksize);
  1510. err = ext4_mark_inode_dirty(handle, mpd->inode);
  1511. if (err)
  1512. ext4_error(mpd->inode->i_sb,
  1513. "Failed to mark inode %lu dirty",
  1514. mpd->inode->i_ino);
  1515. }
  1516. submit_io:
  1517. mpage_da_submit_io(mpd, mapp);
  1518. mpd->io_done = 1;
  1519. }
  1520. #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
  1521. (1 << BH_Delay) | (1 << BH_Unwritten))
  1522. /*
  1523. * mpage_add_bh_to_extent - try to add one more block to extent of blocks
  1524. *
  1525. * @mpd->lbh - extent of blocks
  1526. * @logical - logical number of the block in the file
  1527. * @bh - bh of the block (used to access block's state)
  1528. *
  1529. * the function is used to collect contig. blocks in same state
  1530. */
  1531. static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
  1532. sector_t logical, size_t b_size,
  1533. unsigned long b_state)
  1534. {
  1535. sector_t next;
  1536. int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
  1537. /*
  1538. * XXX Don't go larger than mballoc is willing to allocate
  1539. * This is a stopgap solution. We eventually need to fold
  1540. * mpage_da_submit_io() into this function and then call
  1541. * ext4_map_blocks() multiple times in a loop
  1542. */
  1543. if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
  1544. goto flush_it;
  1545. /* check if thereserved journal credits might overflow */
  1546. if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
  1547. if (nrblocks >= EXT4_MAX_TRANS_DATA) {
  1548. /*
  1549. * With non-extent format we are limited by the journal
  1550. * credit available. Total credit needed to insert
  1551. * nrblocks contiguous blocks is dependent on the
  1552. * nrblocks. So limit nrblocks.
  1553. */
  1554. goto flush_it;
  1555. } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
  1556. EXT4_MAX_TRANS_DATA) {
  1557. /*
  1558. * Adding the new buffer_head would make it cross the
  1559. * allowed limit for which we have journal credit
  1560. * reserved. So limit the new bh->b_size
  1561. */
  1562. b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
  1563. mpd->inode->i_blkbits;
  1564. /* we will do mpage_da_submit_io in the next loop */
  1565. }
  1566. }
  1567. /*
  1568. * First block in the extent
  1569. */
  1570. if (mpd->b_size == 0) {
  1571. mpd->b_blocknr = logical;
  1572. mpd->b_size = b_size;
  1573. mpd->b_state = b_state & BH_FLAGS;
  1574. return;
  1575. }
  1576. next = mpd->b_blocknr + nrblocks;
  1577. /*
  1578. * Can we merge the block to our big extent?
  1579. */
  1580. if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
  1581. mpd->b_size += b_size;
  1582. return;
  1583. }
  1584. flush_it:
  1585. /*
  1586. * We couldn't merge the block to our extent, so we
  1587. * need to flush current extent and start new one
  1588. */
  1589. mpage_da_map_and_submit(mpd);
  1590. return;
  1591. }
  1592. static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
  1593. {
  1594. return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
  1595. }
  1596. /*
  1597. * This function is grabs code from the very beginning of
  1598. * ext4_map_blocks, but assumes that the caller is from delayed write
  1599. * time. This function looks up the requested blocks and sets the
  1600. * buffer delay bit under the protection of i_data_sem.
  1601. */
  1602. static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
  1603. struct ext4_map_blocks *map,
  1604. struct buffer_head *bh)
  1605. {
  1606. int retval;
  1607. sector_t invalid_block = ~((sector_t) 0xffff);
  1608. if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
  1609. invalid_block = ~0;
  1610. map->m_flags = 0;
  1611. ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
  1612. "logical block %lu\n", inode->i_ino, map->m_len,
  1613. (unsigned long) map->m_lblk);
  1614. /*
  1615. * Try to see if we can get the block without requesting a new
  1616. * file system block.
  1617. */
  1618. down_read((&EXT4_I(inode)->i_data_sem));
  1619. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  1620. retval = ext4_ext_map_blocks(NULL, inode, map, 0);
  1621. else
  1622. retval = ext4_ind_map_blocks(NULL, inode, map, 0);
  1623. if (retval == 0) {
  1624. /*
  1625. * XXX: __block_prepare_write() unmaps passed block,
  1626. * is it OK?
  1627. */
  1628. /* If the block was allocated from previously allocated cluster,
  1629. * then we dont need to reserve it again. */
  1630. if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
  1631. retval = ext4_da_reserve_space(inode, iblock);
  1632. if (retval)
  1633. /* not enough space to reserve */
  1634. goto out_unlock;
  1635. }
  1636. /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
  1637. * and it should not appear on the bh->b_state.
  1638. */
  1639. map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
  1640. map_bh(bh, inode->i_sb, invalid_block);
  1641. set_buffer_new(bh);
  1642. set_buffer_delay(bh);
  1643. }
  1644. out_unlock:
  1645. up_read((&EXT4_I(inode)->i_data_sem));
  1646. return retval;
  1647. }
  1648. /*
  1649. * This is a special get_blocks_t callback which is used by
  1650. * ext4_da_write_begin(). It will either return mapped block or
  1651. * reserve space for a single block.
  1652. *
  1653. * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
  1654. * We also have b_blocknr = -1 and b_bdev initialized properly
  1655. *
  1656. * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
  1657. * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
  1658. * initialized properly.
  1659. */
  1660. static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
  1661. struct buffer_head *bh, int create)
  1662. {
  1663. struct ext4_map_blocks map;
  1664. int ret = 0;
  1665. BUG_ON(create == 0);
  1666. BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
  1667. map.m_lblk = iblock;
  1668. map.m_len = 1;
  1669. /*
  1670. * first, we need to know whether the block is allocated already
  1671. * preallocated blocks are unmapped but should treated
  1672. * the same as allocated blocks.
  1673. */
  1674. ret = ext4_da_map_blocks(inode, iblock, &map, bh);
  1675. if (ret <= 0)
  1676. return ret;
  1677. map_bh(bh, inode->i_sb, map.m_pblk);
  1678. bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
  1679. if (buffer_unwritten(bh)) {
  1680. /* A delayed write to unwritten bh should be marked
  1681. * new and mapped. Mapped ensures that we don't do
  1682. * get_block multiple times when we write to the same
  1683. * offset and new ensures that we do proper zero out
  1684. * for partial write.
  1685. */
  1686. set_buffer_new(bh);
  1687. set_buffer_mapped(bh);
  1688. }
  1689. return 0;
  1690. }
  1691. /*
  1692. * This function is used as a standard get_block_t calback function
  1693. * when there is no desire to allocate any blocks. It is used as a
  1694. * callback function for block_write_begin() and block_write_full_page().
  1695. * These functions should only try to map a single block at a time.
  1696. *
  1697. * Since this function doesn't do block allocations even if the caller
  1698. * requests it by passing in create=1, it is critically important that
  1699. * any caller checks to make sure that any buffer heads are returned
  1700. * by this function are either all already mapped or marked for
  1701. * delayed allocation before calling block_write_full_page(). Otherwise,
  1702. * b_blocknr could be left unitialized, and the page write functions will
  1703. * be taken by surprise.
  1704. */
  1705. static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
  1706. struct buffer_head *bh_result, int create)
  1707. {
  1708. BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
  1709. return _ext4_get_block(inode, iblock, bh_result, 0);
  1710. }
  1711. static int bget_one(handle_t *handle, struct buffer_head *bh)
  1712. {
  1713. get_bh(bh);
  1714. return 0;
  1715. }
  1716. static int bput_one(handle_t *handle, struct buffer_head *bh)
  1717. {
  1718. put_bh(bh);
  1719. return 0;
  1720. }
  1721. static int __ext4_journalled_writepage(struct page *page,
  1722. unsigned int len)
  1723. {
  1724. struct address_space *mapping = page->mapping;
  1725. struct inode *inode = mapping->host;
  1726. struct buffer_head *page_bufs;
  1727. handle_t *handle = NULL;
  1728. int ret = 0;
  1729. int err;
  1730. ClearPageChecked(page);
  1731. page_bufs = page_buffers(page);
  1732. BUG_ON(!page_bufs);
  1733. walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
  1734. /*
  1735. * We need to release the page lock before we start the
  1736. * journal, so grab a reference so the page won't disappear
  1737. * out from under us.
  1738. */
  1739. get_page(page);
  1740. unlock_page(page);
  1741. handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
  1742. if (IS_ERR(handle)) {
  1743. ret = PTR_ERR(handle);
  1744. put_page(page);
  1745. goto out_no_pagelock;
  1746. }
  1747. BUG_ON(!ext4_handle_valid(handle));
  1748. lock_page(page);
  1749. put_page(page);
  1750. if (page->mapping != mapping) {
  1751. /* The page got truncated from under us */
  1752. ext4_journal_stop(handle);
  1753. ret = 0;
  1754. goto out;
  1755. }
  1756. ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
  1757. do_journal_get_write_access);
  1758. err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
  1759. write_end_fn);
  1760. if (ret == 0)
  1761. ret = err;
  1762. EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
  1763. err = ext4_journal_stop(handle);
  1764. if (!ret)
  1765. ret = err;
  1766. walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
  1767. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  1768. out:
  1769. unlock_page(page);
  1770. out_no_pagelock:
  1771. return ret;
  1772. }
  1773. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
  1774. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
  1775. /*
  1776. * Note that we don't need to start a transaction unless we're journaling data
  1777. * because we should have holes filled from ext4_page_mkwrite(). We even don't
  1778. * need to file the inode to the transaction's list in ordered mode because if
  1779. * we are writing back data added by write(), the inode is already there and if
  1780. * we are writing back data modified via mmap(), no one guarantees in which
  1781. * transaction the data will hit the disk. In case we are journaling data, we
  1782. * cannot start transaction directly because transaction start ranks above page
  1783. * lock so we have to do some magic.
  1784. *
  1785. * This function can get called via...
  1786. * - ext4_da_writepages after taking page lock (have journal handle)
  1787. * - journal_submit_inode_data_buffers (no journal handle)
  1788. * - shrink_page_list via pdflush (no journal handle)
  1789. * - grab_page_cache when doing write_begin (have journal handle)
  1790. *
  1791. * We don't do any block allocation in this function. If we have page with
  1792. * multiple blocks we need to write those buffer_heads that are mapped. This
  1793. * is important for mmaped based write. So if we do with blocksize 1K
  1794. * truncate(f, 1024);
  1795. * a = mmap(f, 0, 4096);
  1796. * a[0] = 'a';
  1797. * truncate(f, 4096);
  1798. * we have in the page first buffer_head mapped via page_mkwrite call back
  1799. * but other buffer_heads would be unmapped but dirty (dirty done via the
  1800. * do_wp_page). So writepage should write the first block. If we modify
  1801. * the mmap area beyond 1024 we will again get a page_fault and the
  1802. * page_mkwrite callback will do the block allocation and mark the
  1803. * buffer_heads mapped.
  1804. *
  1805. * We redirty the page if we have any buffer_heads that is either delay or
  1806. * unwritten in the page.
  1807. *
  1808. * We can get recursively called as show below.
  1809. *
  1810. * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
  1811. * ext4_writepage()
  1812. *
  1813. * But since we don't do any block allocation we should not deadlock.
  1814. * Page also have the dirty flag cleared so we don't get recurive page_lock.
  1815. */
  1816. static int ext4_writepage(struct page *page,
  1817. struct writeback_control *wbc)
  1818. {
  1819. int ret = 0, commit_write = 0;
  1820. loff_t size;
  1821. unsigned int len;
  1822. struct buffer_head *page_bufs = NULL;
  1823. struct inode *inode = page->mapping->host;
  1824. trace_ext4_writepage(page);
  1825. size = i_size_read(inode);
  1826. if (page->index == size >> PAGE_CACHE_SHIFT)
  1827. len = size & ~PAGE_CACHE_MASK;
  1828. else
  1829. len = PAGE_CACHE_SIZE;
  1830. /*
  1831. * If the page does not have buffers (for whatever reason),
  1832. * try to create them using __block_write_begin. If this
  1833. * fails, redirty the page and move on.
  1834. */
  1835. if (!page_has_buffers(page)) {
  1836. if (__block_write_begin(page, 0, len,
  1837. noalloc_get_block_write)) {
  1838. redirty_page:
  1839. redirty_page_for_writepage(wbc, page);
  1840. unlock_page(page);
  1841. return 0;
  1842. }
  1843. commit_write = 1;
  1844. }
  1845. page_bufs = page_buffers(page);
  1846. if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  1847. ext4_bh_delay_or_unwritten)) {
  1848. /*
  1849. * We don't want to do block allocation, so redirty
  1850. * the page and return. We may reach here when we do
  1851. * a journal commit via journal_submit_inode_data_buffers.
  1852. * We can also reach here via shrink_page_list but it
  1853. * should never be for direct reclaim so warn if that
  1854. * happens
  1855. */
  1856. WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
  1857. PF_MEMALLOC);
  1858. goto redirty_page;
  1859. }
  1860. if (commit_write)
  1861. /* now mark the buffer_heads as dirty and uptodate */
  1862. block_commit_write(page, 0, len);
  1863. if (PageChecked(page) && ext4_should_journal_data(inode))
  1864. /*
  1865. * It's mmapped pagecache. Add buffers and journal it. There
  1866. * doesn't seem much point in redirtying the page here.
  1867. */
  1868. return __ext4_journalled_writepage(page, len);
  1869. if (buffer_uninit(page_bufs)) {
  1870. ext4_set_bh_endio(page_bufs, inode);
  1871. ret = block_write_full_page_endio(page, noalloc_get_block_write,
  1872. wbc, ext4_end_io_buffer_write);
  1873. } else
  1874. ret = block_write_full_page(page, noalloc_get_block_write,
  1875. wbc);
  1876. return ret;
  1877. }
  1878. /*
  1879. * This is called via ext4_da_writepages() to
  1880. * calculate the total number of credits to reserve to fit
  1881. * a single extent allocation into a single transaction,
  1882. * ext4_da_writpeages() will loop calling this before
  1883. * the block allocation.
  1884. */
  1885. static int ext4_da_writepages_trans_blocks(struct inode *inode)
  1886. {
  1887. int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  1888. /*
  1889. * With non-extent format the journal credit needed to
  1890. * insert nrblocks contiguous block is dependent on
  1891. * number of contiguous block. So we will limit
  1892. * number of contiguous block to a sane value
  1893. */
  1894. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
  1895. (max_blocks > EXT4_MAX_TRANS_DATA))
  1896. max_blocks = EXT4_MAX_TRANS_DATA;
  1897. return ext4_chunk_trans_blocks(inode, max_blocks);
  1898. }
  1899. /*
  1900. * write_cache_pages_da - walk the list of dirty pages of the given
  1901. * address space and accumulate pages that need writing, and call
  1902. * mpage_da_map_and_submit to map a single contiguous memory region
  1903. * and then write them.
  1904. */
  1905. static int write_cache_pages_da(struct address_space *mapping,
  1906. struct writeback_control *wbc,
  1907. struct mpage_da_data *mpd,
  1908. pgoff_t *done_index)
  1909. {
  1910. struct buffer_head *bh, *head;
  1911. struct inode *inode = mapping->host;
  1912. struct pagevec pvec;
  1913. unsigned int nr_pages;
  1914. sector_t logical;
  1915. pgoff_t index, end;
  1916. long nr_to_write = wbc->nr_to_write;
  1917. int i, tag, ret = 0;
  1918. memset(mpd, 0, sizeof(struct mpage_da_data));
  1919. mpd->wbc = wbc;
  1920. mpd->inode = inode;
  1921. pagevec_init(&pvec, 0);
  1922. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  1923. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  1924. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1925. tag = PAGECACHE_TAG_TOWRITE;
  1926. else
  1927. tag = PAGECACHE_TAG_DIRTY;
  1928. *done_index = index;
  1929. while (index <= end) {
  1930. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
  1931. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
  1932. if (nr_pages == 0)
  1933. return 0;
  1934. for (i = 0; i < nr_pages; i++) {
  1935. struct page *page = pvec.pages[i];
  1936. /*
  1937. * At this point, the page may be truncated or
  1938. * invalidated (changing page->mapping to NULL), or
  1939. * even swizzled back from swapper_space to tmpfs file
  1940. * mapping. However, page->index will not change
  1941. * because we have a reference on the page.
  1942. */
  1943. if (page->index > end)
  1944. goto out;
  1945. *done_index = page->index + 1;
  1946. /*
  1947. * If we can't merge this page, and we have
  1948. * accumulated an contiguous region, write it
  1949. */
  1950. if ((mpd->next_page != page->index) &&
  1951. (mpd->next_page != mpd->first_page)) {
  1952. mpage_da_map_and_submit(mpd);
  1953. goto ret_extent_tail;
  1954. }
  1955. lock_page(page);
  1956. /*
  1957. * If the page is no longer dirty, or its
  1958. * mapping no longer corresponds to inode we
  1959. * are writing (which means it has been
  1960. * truncated or invalidated), or the page is
  1961. * already under writeback and we are not
  1962. * doing a data integrity writeback, skip the page
  1963. */
  1964. if (!PageDirty(page) ||
  1965. (PageWriteback(page) &&
  1966. (wbc->sync_mode == WB_SYNC_NONE)) ||
  1967. unlikely(page->mapping != mapping)) {
  1968. unlock_page(page);
  1969. continue;
  1970. }
  1971. wait_on_page_writeback(page);
  1972. BUG_ON(PageWriteback(page));
  1973. if (mpd->next_page != page->index)
  1974. mpd->first_page = page->index;
  1975. mpd->next_page = page->index + 1;
  1976. logical = (sector_t) page->index <<
  1977. (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1978. if (!page_has_buffers(page)) {
  1979. mpage_add_bh_to_extent(mpd, logical,
  1980. PAGE_CACHE_SIZE,
  1981. (1 << BH_Dirty) | (1 << BH_Uptodate));
  1982. if (mpd->io_done)
  1983. goto ret_extent_tail;
  1984. } else {
  1985. /*
  1986. * Page with regular buffer heads,
  1987. * just add all dirty ones
  1988. */
  1989. head = page_buffers(page);
  1990. bh = head;
  1991. do {
  1992. BUG_ON(buffer_locked(bh));
  1993. /*
  1994. * We need to try to allocate
  1995. * unmapped blocks in the same page.
  1996. * Otherwise we won't make progress
  1997. * with the page in ext4_writepage
  1998. */
  1999. if (ext4_bh_delay_or_unwritten(NULL, bh)) {
  2000. mpage_add_bh_to_extent(mpd, logical,
  2001. bh->b_size,
  2002. bh->b_state);
  2003. if (mpd->io_done)
  2004. goto ret_extent_tail;
  2005. } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
  2006. /*
  2007. * mapped dirty buffer. We need
  2008. * to update the b_state
  2009. * because we look at b_state
  2010. * in mpage_da_map_blocks. We
  2011. * don't update b_size because
  2012. * if we find an unmapped
  2013. * buffer_head later we need to
  2014. * use the b_state flag of that
  2015. * buffer_head.
  2016. */
  2017. if (mpd->b_size == 0)
  2018. mpd->b_state = bh->b_state & BH_FLAGS;
  2019. }
  2020. logical++;
  2021. } while ((bh = bh->b_this_page) != head);
  2022. }
  2023. if (nr_to_write > 0) {
  2024. nr_to_write--;
  2025. if (nr_to_write == 0 &&
  2026. wbc->sync_mode == WB_SYNC_NONE)
  2027. /*
  2028. * We stop writing back only if we are
  2029. * not doing integrity sync. In case of
  2030. * integrity sync we have to keep going
  2031. * because someone may be concurrently
  2032. * dirtying pages, and we might have
  2033. * synced a lot of newly appeared dirty
  2034. * pages, but have not synced all of the
  2035. * old dirty pages.
  2036. */
  2037. goto out;
  2038. }
  2039. }
  2040. pagevec_release(&pvec);
  2041. cond_resched();
  2042. }
  2043. return 0;
  2044. ret_extent_tail:
  2045. ret = MPAGE_DA_EXTENT_TAIL;
  2046. out:
  2047. pagevec_release(&pvec);
  2048. cond_resched();
  2049. return ret;
  2050. }
  2051. static int ext4_da_writepages(struct address_space *mapping,
  2052. struct writeback_control *wbc)
  2053. {
  2054. pgoff_t index;
  2055. int range_whole = 0;
  2056. handle_t *handle = NULL;
  2057. struct mpage_da_data mpd;
  2058. struct inode *inode = mapping->host;
  2059. int pages_written = 0;
  2060. unsigned int max_pages;
  2061. int range_cyclic, cycled = 1, io_done = 0;
  2062. int needed_blocks, ret = 0;
  2063. long desired_nr_to_write, nr_to_writebump = 0;
  2064. loff_t range_start = wbc->range_start;
  2065. struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
  2066. pgoff_t done_index = 0;
  2067. pgoff_t end;
  2068. struct blk_plug plug;
  2069. trace_ext4_da_writepages(inode, wbc);
  2070. /*
  2071. * No pages to write? This is mainly a kludge to avoid starting
  2072. * a transaction for special inodes like journal inode on last iput()
  2073. * because that could violate lock ordering on umount
  2074. */
  2075. if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
  2076. return 0;
  2077. /*
  2078. * If the filesystem has aborted, it is read-only, so return
  2079. * right away instead of dumping stack traces later on that
  2080. * will obscure the real source of the problem. We test
  2081. * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
  2082. * the latter could be true if the filesystem is mounted
  2083. * read-only, and in that case, ext4_da_writepages should
  2084. * *never* be called, so if that ever happens, we would want
  2085. * the stack trace.
  2086. */
  2087. if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
  2088. return -EROFS;
  2089. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  2090. range_whole = 1;
  2091. range_cyclic = wbc->range_cyclic;
  2092. if (wbc->range_cyclic) {
  2093. index = mapping->writeback_index;
  2094. if (index)
  2095. cycled = 0;
  2096. wbc->range_start = index << PAGE_CACHE_SHIFT;
  2097. wbc->range_end = LLONG_MAX;
  2098. wbc->range_cyclic = 0;
  2099. end = -1;
  2100. } else {
  2101. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  2102. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  2103. }
  2104. /*
  2105. * This works around two forms of stupidity. The first is in
  2106. * the writeback code, which caps the maximum number of pages
  2107. * written to be 1024 pages. This is wrong on multiple
  2108. * levels; different architectues have a different page size,
  2109. * which changes the maximum amount of data which gets
  2110. * written. Secondly, 4 megabytes is way too small. XFS
  2111. * forces this value to be 16 megabytes by multiplying
  2112. * nr_to_write parameter by four, and then relies on its
  2113. * allocator to allocate larger extents to make them
  2114. * contiguous. Unfortunately this brings us to the second
  2115. * stupidity, which is that ext4's mballoc code only allocates
  2116. * at most 2048 blocks. So we force contiguous writes up to
  2117. * the number of dirty blocks in the inode, or
  2118. * sbi->max_writeback_mb_bump whichever is smaller.
  2119. */
  2120. max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
  2121. if (!range_cyclic && range_whole) {
  2122. if (wbc->nr_to_write == LONG_MAX)
  2123. desired_nr_to_write = wbc->nr_to_write;
  2124. else
  2125. desired_nr_to_write = wbc->nr_to_write * 8;
  2126. } else
  2127. desired_nr_to_write = ext4_num_dirty_pages(inode, index,
  2128. max_pages);
  2129. if (desired_nr_to_write > max_pages)
  2130. desired_nr_to_write = max_pages;
  2131. if (wbc->nr_to_write < desired_nr_to_write) {
  2132. nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
  2133. wbc->nr_to_write = desired_nr_to_write;
  2134. }
  2135. retry:
  2136. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  2137. tag_pages_for_writeback(mapping, index, end);
  2138. blk_start_plug(&plug);
  2139. while (!ret && wbc->nr_to_write > 0) {
  2140. /*
  2141. * we insert one extent at a time. So we need
  2142. * credit needed for single extent allocation.
  2143. * journalled mode is currently not supported
  2144. * by delalloc
  2145. */
  2146. BUG_ON(ext4_should_journal_data(inode));
  2147. needed_blocks = ext4_da_writepages_trans_blocks(inode);
  2148. /* start a new transaction*/
  2149. handle = ext4_journal_start(inode, needed_blocks);
  2150. if (IS_ERR(handle)) {
  2151. ret = PTR_ERR(handle);
  2152. ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
  2153. "%ld pages, ino %lu; err %d", __func__,
  2154. wbc->nr_to_write, inode->i_ino, ret);
  2155. blk_finish_plug(&plug);
  2156. goto out_writepages;
  2157. }
  2158. /*
  2159. * Now call write_cache_pages_da() to find the next
  2160. * contiguous region of logical blocks that need
  2161. * blocks to be allocated by ext4 and submit them.
  2162. */
  2163. ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
  2164. /*
  2165. * If we have a contiguous extent of pages and we
  2166. * haven't done the I/O yet, map the blocks and submit
  2167. * them for I/O.
  2168. */
  2169. if (!mpd.io_done && mpd.next_page != mpd.first_page) {
  2170. mpage_da_map_and_submit(&mpd);
  2171. ret = MPAGE_DA_EXTENT_TAIL;
  2172. }
  2173. trace_ext4_da_write_pages(inode, &mpd);
  2174. wbc->nr_to_write -= mpd.pages_written;
  2175. ext4_journal_stop(handle);
  2176. if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
  2177. /* commit the transaction which would
  2178. * free blocks released in the transaction
  2179. * and try again
  2180. */
  2181. jbd2_journal_force_commit_nested(sbi->s_journal);
  2182. ret = 0;
  2183. } else if (ret == MPAGE_DA_EXTENT_TAIL) {
  2184. /*
  2185. * Got one extent now try with rest of the pages.
  2186. * If mpd.retval is set -EIO, journal is aborted.
  2187. * So we don't need to write any more.
  2188. */
  2189. pages_written += mpd.pages_written;
  2190. ret = mpd.retval;
  2191. io_done = 1;
  2192. } else if (wbc->nr_to_write)
  2193. /*
  2194. * There is no more writeout needed
  2195. * or we requested for a noblocking writeout
  2196. * and we found the device congested
  2197. */
  2198. break;
  2199. }
  2200. blk_finish_plug(&plug);
  2201. if (!io_done && !cycled) {
  2202. cycled = 1;
  2203. index = 0;
  2204. wbc->range_start = index << PAGE_CACHE_SHIFT;
  2205. wbc->range_end = mapping->writeback_index - 1;
  2206. goto retry;
  2207. }
  2208. /* Update index */
  2209. wbc->range_cyclic = range_cyclic;
  2210. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  2211. /*
  2212. * set the writeback_index so that range_cyclic
  2213. * mode will write it back later
  2214. */
  2215. mapping->writeback_index = done_index;
  2216. out_writepages:
  2217. wbc->nr_to_write -= nr_to_writebump;
  2218. wbc->range_start = range_start;
  2219. trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
  2220. return ret;
  2221. }
  2222. #define FALL_BACK_TO_NONDELALLOC 1
  2223. static int ext4_nonda_switch(struct super_block *sb)
  2224. {
  2225. s64 free_blocks, dirty_blocks;
  2226. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2227. /*
  2228. * switch to non delalloc mode if we are running low
  2229. * on free block. The free block accounting via percpu
  2230. * counters can get slightly wrong with percpu_counter_batch getting
  2231. * accumulated on each CPU without updating global counters
  2232. * Delalloc need an accurate free block accounting. So switch
  2233. * to non delalloc when we are near to error range.
  2234. */
  2235. free_blocks = EXT4_C2B(sbi,
  2236. percpu_counter_read_positive(&sbi->s_freeclusters_counter));
  2237. dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
  2238. /*
  2239. * Start pushing delalloc when 1/2 of free blocks are dirty.
  2240. */
  2241. if (dirty_blocks && (free_blocks < 2 * dirty_blocks) &&
  2242. !writeback_in_progress(sb->s_bdi) &&
  2243. down_read_trylock(&sb->s_umount)) {
  2244. writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
  2245. up_read(&sb->s_umount);
  2246. }
  2247. if (2 * free_blocks < 3 * dirty_blocks ||
  2248. free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
  2249. /*
  2250. * free block count is less than 150% of dirty blocks
  2251. * or free blocks is less than watermark
  2252. */
  2253. return 1;
  2254. }
  2255. return 0;
  2256. }
  2257. /* We always reserve for an inode update; the superblock could be there too */
  2258. static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
  2259. {
  2260. if (likely(EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
  2261. EXT4_FEATURE_RO_COMPAT_LARGE_FILE)))
  2262. return 1;
  2263. if (pos + len <= 0x7fffffffULL)
  2264. return 1;
  2265. /* We might need to update the superblock to set LARGE_FILE */
  2266. return 2;
  2267. }
  2268. static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
  2269. loff_t pos, unsigned len, unsigned flags,
  2270. struct page **pagep, void **fsdata)
  2271. {
  2272. int ret, retries = 0;
  2273. struct page *page;
  2274. pgoff_t index;
  2275. struct inode *inode = mapping->host;
  2276. handle_t *handle;
  2277. index = pos >> PAGE_CACHE_SHIFT;
  2278. if (ext4_nonda_switch(inode->i_sb)) {
  2279. *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
  2280. return ext4_write_begin(file, mapping, pos,
  2281. len, flags, pagep, fsdata);
  2282. }
  2283. *fsdata = (void *)0;
  2284. trace_ext4_da_write_begin(inode, pos, len, flags);
  2285. /*
  2286. * grab_cache_page_write_begin() can take a long time if the
  2287. * system is thrashing due to memory pressure, or if the page
  2288. * is being written back. So grab it first before we start
  2289. * the transaction handle. This also allows us to allocate
  2290. * the page (if needed) without using GFP_NOFS.
  2291. */
  2292. retry_grab:
  2293. page = grab_cache_page_write_begin(mapping, index, flags);
  2294. if (!page)
  2295. return -ENOMEM;
  2296. unlock_page(page);
  2297. /*
  2298. * With delayed allocation, we don't log the i_disksize update
  2299. * if there is delayed block allocation. But we still need
  2300. * to journalling the i_disksize update if writes to the end
  2301. * of file which has an already mapped buffer.
  2302. */
  2303. retry_journal:
  2304. handle = ext4_journal_start(inode,
  2305. ext4_da_write_credits(inode, pos, len));
  2306. if (IS_ERR(handle)) {
  2307. page_cache_release(page);
  2308. return PTR_ERR(handle);
  2309. }
  2310. lock_page(page);
  2311. if (page->mapping != mapping) {
  2312. /* The page got truncated from under us */
  2313. unlock_page(page);
  2314. page_cache_release(page);
  2315. ext4_journal_stop(handle);
  2316. goto retry_grab;
  2317. }
  2318. /* In case writeback began while the page was unlocked */
  2319. wait_on_page_writeback(page);
  2320. ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
  2321. if (ret < 0) {
  2322. unlock_page(page);
  2323. ext4_journal_stop(handle);
  2324. /*
  2325. * block_write_begin may have instantiated a few blocks
  2326. * outside i_size. Trim these off again. Don't need
  2327. * i_size_read because we hold i_mutex.
  2328. */
  2329. if (pos + len > inode->i_size)
  2330. ext4_truncate_failed_write(inode);
  2331. if (ret == -ENOSPC &&
  2332. ext4_should_retry_alloc(inode->i_sb, &retries))
  2333. goto retry_journal;
  2334. page_cache_release(page);
  2335. return ret;
  2336. }
  2337. *pagep = page;
  2338. return ret;
  2339. }
  2340. /*
  2341. * Check if we should update i_disksize
  2342. * when write to the end of file but not require block allocation
  2343. */
  2344. static int ext4_da_should_update_i_disksize(struct page *page,
  2345. unsigned long offset)
  2346. {
  2347. struct buffer_head *bh;
  2348. struct inode *inode = page->mapping->host;
  2349. unsigned int idx;
  2350. int i;
  2351. bh = page_buffers(page);
  2352. idx = offset >> inode->i_blkbits;
  2353. for (i = 0; i < idx; i++)
  2354. bh = bh->b_this_page;
  2355. if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
  2356. return 0;
  2357. return 1;
  2358. }
  2359. static int ext4_da_write_end(struct file *file,
  2360. struct address_space *mapping,
  2361. loff_t pos, unsigned len, unsigned copied,
  2362. struct page *page, void *fsdata)
  2363. {
  2364. struct inode *inode = mapping->host;
  2365. int ret = 0, ret2;
  2366. handle_t *handle = ext4_journal_current_handle();
  2367. loff_t new_i_size;
  2368. unsigned long start, end;
  2369. int write_mode = (int)(unsigned long)fsdata;
  2370. if (write_mode == FALL_BACK_TO_NONDELALLOC) {
  2371. switch (ext4_inode_journal_mode(inode)) {
  2372. case EXT4_INODE_ORDERED_DATA_MODE:
  2373. return ext4_ordered_write_end(file, mapping, pos,
  2374. len, copied, page, fsdata);
  2375. case EXT4_INODE_WRITEBACK_DATA_MODE:
  2376. return ext4_writeback_write_end(file, mapping, pos,
  2377. len, copied, page, fsdata);
  2378. default:
  2379. BUG();
  2380. }
  2381. }
  2382. trace_ext4_da_write_end(inode, pos, len, copied);
  2383. start = pos & (PAGE_CACHE_SIZE - 1);
  2384. end = start + copied - 1;
  2385. /*
  2386. * generic_write_end() will run mark_inode_dirty() if i_size
  2387. * changes. So let's piggyback the i_disksize mark_inode_dirty
  2388. * into that.
  2389. */
  2390. new_i_size = pos + copied;
  2391. if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
  2392. if (ext4_da_should_update_i_disksize(page, end)) {
  2393. down_write(&EXT4_I(inode)->i_data_sem);
  2394. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2395. /*
  2396. * Updating i_disksize when extending file
  2397. * without needing block allocation
  2398. */
  2399. if (ext4_should_order_data(inode))
  2400. ret = ext4_jbd2_file_inode(handle,
  2401. inode);
  2402. EXT4_I(inode)->i_disksize = new_i_size;
  2403. }
  2404. up_write(&EXT4_I(inode)->i_data_sem);
  2405. /* We need to mark inode dirty even if
  2406. * new_i_size is less that inode->i_size
  2407. * bu greater than i_disksize.(hint delalloc)
  2408. */
  2409. ext4_mark_inode_dirty(handle, inode);
  2410. }
  2411. }
  2412. ret2 = generic_write_end(file, mapping, pos, len, copied,
  2413. page, fsdata);
  2414. copied = ret2;
  2415. if (ret2 < 0)
  2416. ret = ret2;
  2417. ret2 = ext4_journal_stop(handle);
  2418. if (!ret)
  2419. ret = ret2;
  2420. return ret ? ret : copied;
  2421. }
  2422. static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
  2423. {
  2424. /*
  2425. * Drop reserved blocks
  2426. */
  2427. BUG_ON(!PageLocked(page));
  2428. if (!page_has_buffers(page))
  2429. goto out;
  2430. ext4_da_page_release_reservation(page, offset);
  2431. out:
  2432. ext4_invalidatepage(page, offset);
  2433. return;
  2434. }
  2435. /*
  2436. * Force all delayed allocation blocks to be allocated for a given inode.
  2437. */
  2438. int ext4_alloc_da_blocks(struct inode *inode)
  2439. {
  2440. trace_ext4_alloc_da_blocks(inode);
  2441. if (!EXT4_I(inode)->i_reserved_data_blocks &&
  2442. !EXT4_I(inode)->i_reserved_meta_blocks)
  2443. return 0;
  2444. /*
  2445. * We do something simple for now. The filemap_flush() will
  2446. * also start triggering a write of the data blocks, which is
  2447. * not strictly speaking necessary (and for users of
  2448. * laptop_mode, not even desirable). However, to do otherwise
  2449. * would require replicating code paths in:
  2450. *
  2451. * ext4_da_writepages() ->
  2452. * write_cache_pages() ---> (via passed in callback function)
  2453. * __mpage_da_writepage() -->
  2454. * mpage_add_bh_to_extent()
  2455. * mpage_da_map_blocks()
  2456. *
  2457. * The problem is that write_cache_pages(), located in
  2458. * mm/page-writeback.c, marks pages clean in preparation for
  2459. * doing I/O, which is not desirable if we're not planning on
  2460. * doing I/O at all.
  2461. *
  2462. * We could call write_cache_pages(), and then redirty all of
  2463. * the pages by calling redirty_page_for_writepage() but that
  2464. * would be ugly in the extreme. So instead we would need to
  2465. * replicate parts of the code in the above functions,
  2466. * simplifying them because we wouldn't actually intend to
  2467. * write out the pages, but rather only collect contiguous
  2468. * logical block extents, call the multi-block allocator, and
  2469. * then update the buffer heads with the block allocations.
  2470. *
  2471. * For now, though, we'll cheat by calling filemap_flush(),
  2472. * which will map the blocks, and start the I/O, but not
  2473. * actually wait for the I/O to complete.
  2474. */
  2475. return filemap_flush(inode->i_mapping);
  2476. }
  2477. /*
  2478. * bmap() is special. It gets used by applications such as lilo and by
  2479. * the swapper to find the on-disk block of a specific piece of data.
  2480. *
  2481. * Naturally, this is dangerous if the block concerned is still in the
  2482. * journal. If somebody makes a swapfile on an ext4 data-journaling
  2483. * filesystem and enables swap, then they may get a nasty shock when the
  2484. * data getting swapped to that swapfile suddenly gets overwritten by
  2485. * the original zero's written out previously to the journal and
  2486. * awaiting writeback in the kernel's buffer cache.
  2487. *
  2488. * So, if we see any bmap calls here on a modified, data-journaled file,
  2489. * take extra steps to flush any blocks which might be in the cache.
  2490. */
  2491. static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
  2492. {
  2493. struct inode *inode = mapping->host;
  2494. journal_t *journal;
  2495. int err;
  2496. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
  2497. test_opt(inode->i_sb, DELALLOC)) {
  2498. /*
  2499. * With delalloc we want to sync the file
  2500. * so that we can make sure we allocate
  2501. * blocks for file
  2502. */
  2503. filemap_write_and_wait(mapping);
  2504. }
  2505. if (EXT4_JOURNAL(inode) &&
  2506. ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
  2507. /*
  2508. * This is a REALLY heavyweight approach, but the use of
  2509. * bmap on dirty files is expected to be extremely rare:
  2510. * only if we run lilo or swapon on a freshly made file
  2511. * do we expect this to happen.
  2512. *
  2513. * (bmap requires CAP_SYS_RAWIO so this does not
  2514. * represent an unprivileged user DOS attack --- we'd be
  2515. * in trouble if mortal users could trigger this path at
  2516. * will.)
  2517. *
  2518. * NB. EXT4_STATE_JDATA is not set on files other than
  2519. * regular files. If somebody wants to bmap a directory
  2520. * or symlink and gets confused because the buffer
  2521. * hasn't yet been flushed to disk, they deserve
  2522. * everything they get.
  2523. */
  2524. ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
  2525. journal = EXT4_JOURNAL(inode);
  2526. jbd2_journal_lock_updates(journal);
  2527. err = jbd2_journal_flush(journal);
  2528. jbd2_journal_unlock_updates(journal);
  2529. if (err)
  2530. return 0;
  2531. }
  2532. return generic_block_bmap(mapping, block, ext4_get_block);
  2533. }
  2534. static int ext4_readpage(struct file *file, struct page *page)
  2535. {
  2536. trace_ext4_readpage(page);
  2537. return mpage_readpage(page, ext4_get_block);
  2538. }
  2539. static int
  2540. ext4_readpages(struct file *file, struct address_space *mapping,
  2541. struct list_head *pages, unsigned nr_pages)
  2542. {
  2543. return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
  2544. }
  2545. static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
  2546. {
  2547. struct buffer_head *head, *bh;
  2548. unsigned int curr_off = 0;
  2549. if (!page_has_buffers(page))
  2550. return;
  2551. head = bh = page_buffers(page);
  2552. do {
  2553. if (offset <= curr_off && test_clear_buffer_uninit(bh)
  2554. && bh->b_private) {
  2555. ext4_free_io_end(bh->b_private);
  2556. bh->b_private = NULL;
  2557. bh->b_end_io = NULL;
  2558. }
  2559. curr_off = curr_off + bh->b_size;
  2560. bh = bh->b_this_page;
  2561. } while (bh != head);
  2562. }
  2563. static void ext4_invalidatepage(struct page *page, unsigned long offset)
  2564. {
  2565. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  2566. trace_ext4_invalidatepage(page, offset);
  2567. /*
  2568. * free any io_end structure allocated for buffers to be discarded
  2569. */
  2570. if (ext4_should_dioread_nolock(page->mapping->host))
  2571. ext4_invalidatepage_free_endio(page, offset);
  2572. /*
  2573. * If it's a full truncate we just forget about the pending dirtying
  2574. */
  2575. if (offset == 0)
  2576. ClearPageChecked(page);
  2577. if (journal)
  2578. jbd2_journal_invalidatepage(journal, page, offset);
  2579. else
  2580. block_invalidatepage(page, offset);
  2581. }
  2582. static int ext4_releasepage(struct page *page, gfp_t wait)
  2583. {
  2584. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  2585. trace_ext4_releasepage(page);
  2586. WARN_ON(PageChecked(page));
  2587. if (!page_has_buffers(page))
  2588. return 0;
  2589. if (journal)
  2590. return jbd2_journal_try_to_free_buffers(journal, page, wait);
  2591. else
  2592. return try_to_free_buffers(page);
  2593. }
  2594. /*
  2595. * ext4_get_block used when preparing for a DIO write or buffer write.
  2596. * We allocate an uinitialized extent if blocks haven't been allocated.
  2597. * The extent will be converted to initialized after the IO is complete.
  2598. */
  2599. static int ext4_get_block_write(struct inode *inode, sector_t iblock,
  2600. struct buffer_head *bh_result, int create)
  2601. {
  2602. ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
  2603. inode->i_ino, create);
  2604. return _ext4_get_block(inode, iblock, bh_result,
  2605. EXT4_GET_BLOCKS_IO_CREATE_EXT);
  2606. }
  2607. static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
  2608. ssize_t size, void *private, int ret,
  2609. bool is_async)
  2610. {
  2611. struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
  2612. ext4_io_end_t *io_end = iocb->private;
  2613. struct workqueue_struct *wq;
  2614. unsigned long flags;
  2615. struct ext4_inode_info *ei;
  2616. /* if not async direct IO or dio with 0 bytes write, just return */
  2617. if (!io_end || !size)
  2618. goto out;
  2619. ext_debug("ext4_end_io_dio(): io_end 0x%p "
  2620. "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
  2621. iocb->private, io_end->inode->i_ino, iocb, offset,
  2622. size);
  2623. iocb->private = NULL;
  2624. /* if not aio dio with unwritten extents, just free io and return */
  2625. if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
  2626. ext4_free_io_end(io_end);
  2627. out:
  2628. inode_dio_done(inode);
  2629. if (is_async)
  2630. aio_complete(iocb, ret, 0);
  2631. return;
  2632. }
  2633. io_end->offset = offset;
  2634. io_end->size = size;
  2635. if (is_async) {
  2636. io_end->iocb = iocb;
  2637. io_end->result = ret;
  2638. }
  2639. wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
  2640. /* Add the io_end to per-inode completed aio dio list*/
  2641. ei = EXT4_I(io_end->inode);
  2642. spin_lock_irqsave(&ei->i_completed_io_lock, flags);
  2643. list_add_tail(&io_end->list, &ei->i_completed_io_list);
  2644. spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
  2645. /* queue the work to convert unwritten extents to written */
  2646. queue_work(wq, &io_end->work);
  2647. }
  2648. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
  2649. {
  2650. ext4_io_end_t *io_end = bh->b_private;
  2651. struct workqueue_struct *wq;
  2652. struct inode *inode;
  2653. unsigned long flags;
  2654. if (!test_clear_buffer_uninit(bh) || !io_end)
  2655. goto out;
  2656. if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
  2657. ext4_msg(io_end->inode->i_sb, KERN_INFO,
  2658. "sb umounted, discard end_io request for inode %lu",
  2659. io_end->inode->i_ino);
  2660. ext4_free_io_end(io_end);
  2661. goto out;
  2662. }
  2663. /*
  2664. * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
  2665. * but being more careful is always safe for the future change.
  2666. */
  2667. inode = io_end->inode;
  2668. ext4_set_io_unwritten_flag(inode, io_end);
  2669. /* Add the io_end to per-inode completed io list*/
  2670. spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
  2671. list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
  2672. spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
  2673. wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
  2674. /* queue the work to convert unwritten extents to written */
  2675. queue_work(wq, &io_end->work);
  2676. out:
  2677. bh->b_private = NULL;
  2678. bh->b_end_io = NULL;
  2679. clear_buffer_uninit(bh);
  2680. end_buffer_async_write(bh, uptodate);
  2681. }
  2682. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
  2683. {
  2684. ext4_io_end_t *io_end;
  2685. struct page *page = bh->b_page;
  2686. loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
  2687. size_t size = bh->b_size;
  2688. retry:
  2689. io_end = ext4_init_io_end(inode, GFP_ATOMIC);
  2690. if (!io_end) {
  2691. pr_warn_ratelimited("%s: allocation fail\n", __func__);
  2692. schedule();
  2693. goto retry;
  2694. }
  2695. io_end->offset = offset;
  2696. io_end->size = size;
  2697. /*
  2698. * We need to hold a reference to the page to make sure it
  2699. * doesn't get evicted before ext4_end_io_work() has a chance
  2700. * to convert the extent from written to unwritten.
  2701. */
  2702. io_end->page = page;
  2703. get_page(io_end->page);
  2704. bh->b_private = io_end;
  2705. bh->b_end_io = ext4_end_io_buffer_write;
  2706. return 0;
  2707. }
  2708. /*
  2709. * For ext4 extent files, ext4 will do direct-io write to holes,
  2710. * preallocated extents, and those write extend the file, no need to
  2711. * fall back to buffered IO.
  2712. *
  2713. * For holes, we fallocate those blocks, mark them as uninitialized
  2714. * If those blocks were preallocated, we mark sure they are splited, but
  2715. * still keep the range to write as uninitialized.
  2716. *
  2717. * The unwrritten extents will be converted to written when DIO is completed.
  2718. * For async direct IO, since the IO may still pending when return, we
  2719. * set up an end_io call back function, which will do the conversion
  2720. * when async direct IO completed.
  2721. *
  2722. * If the O_DIRECT write will extend the file then add this inode to the
  2723. * orphan list. So recovery will truncate it back to the original size
  2724. * if the machine crashes during the write.
  2725. *
  2726. */
  2727. static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
  2728. const struct iovec *iov, loff_t offset,
  2729. unsigned long nr_segs)
  2730. {
  2731. struct file *file = iocb->ki_filp;
  2732. struct inode *inode = file->f_mapping->host;
  2733. ssize_t ret;
  2734. size_t count = iov_length(iov, nr_segs);
  2735. loff_t final_size = offset + count;
  2736. if (rw == WRITE && final_size <= inode->i_size) {
  2737. /*
  2738. * We could direct write to holes and fallocate.
  2739. *
  2740. * Allocated blocks to fill the hole are marked as uninitialized
  2741. * to prevent parallel buffered read to expose the stale data
  2742. * before DIO complete the data IO.
  2743. *
  2744. * As to previously fallocated extents, ext4 get_block
  2745. * will just simply mark the buffer mapped but still
  2746. * keep the extents uninitialized.
  2747. *
  2748. * for non AIO case, we will convert those unwritten extents
  2749. * to written after return back from blockdev_direct_IO.
  2750. *
  2751. * for async DIO, the conversion needs to be defered when
  2752. * the IO is completed. The ext4 end_io callback function
  2753. * will be called to take care of the conversion work.
  2754. * Here for async case, we allocate an io_end structure to
  2755. * hook to the iocb.
  2756. */
  2757. iocb->private = NULL;
  2758. EXT4_I(inode)->cur_aio_dio = NULL;
  2759. if (!is_sync_kiocb(iocb)) {
  2760. ext4_io_end_t *io_end =
  2761. ext4_init_io_end(inode, GFP_NOFS);
  2762. if (!io_end)
  2763. return -ENOMEM;
  2764. io_end->flag |= EXT4_IO_END_DIRECT;
  2765. iocb->private = io_end;
  2766. /*
  2767. * we save the io structure for current async
  2768. * direct IO, so that later ext4_map_blocks()
  2769. * could flag the io structure whether there
  2770. * is a unwritten extents needs to be converted
  2771. * when IO is completed.
  2772. */
  2773. EXT4_I(inode)->cur_aio_dio = iocb->private;
  2774. }
  2775. ret = __blockdev_direct_IO(rw, iocb, inode,
  2776. inode->i_sb->s_bdev, iov,
  2777. offset, nr_segs,
  2778. ext4_get_block_write,
  2779. ext4_end_io_dio,
  2780. NULL,
  2781. DIO_LOCKING);
  2782. if (iocb->private)
  2783. EXT4_I(inode)->cur_aio_dio = NULL;
  2784. /*
  2785. * The io_end structure takes a reference to the inode,
  2786. * that structure needs to be destroyed and the
  2787. * reference to the inode need to be dropped, when IO is
  2788. * complete, even with 0 byte write, or failed.
  2789. *
  2790. * In the successful AIO DIO case, the io_end structure will be
  2791. * desctroyed and the reference to the inode will be dropped
  2792. * after the end_io call back function is called.
  2793. *
  2794. * In the case there is 0 byte write, or error case, since
  2795. * VFS direct IO won't invoke the end_io call back function,
  2796. * we need to free the end_io structure here.
  2797. */
  2798. if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
  2799. ext4_free_io_end(iocb->private);
  2800. iocb->private = NULL;
  2801. } else if (ret > 0 && ext4_test_inode_state(inode,
  2802. EXT4_STATE_DIO_UNWRITTEN)) {
  2803. int err;
  2804. /*
  2805. * for non AIO case, since the IO is already
  2806. * completed, we could do the conversion right here
  2807. */
  2808. err = ext4_convert_unwritten_extents(inode,
  2809. offset, ret);
  2810. if (err < 0)
  2811. ret = err;
  2812. ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
  2813. }
  2814. return ret;
  2815. }
  2816. /* for write the the end of file case, we fall back to old way */
  2817. return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
  2818. }
  2819. static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
  2820. const struct iovec *iov, loff_t offset,
  2821. unsigned long nr_segs)
  2822. {
  2823. struct file *file = iocb->ki_filp;
  2824. struct inode *inode = file->f_mapping->host;
  2825. ssize_t ret;
  2826. /*
  2827. * If we are doing data journalling we don't support O_DIRECT
  2828. */
  2829. if (ext4_should_journal_data(inode))
  2830. return 0;
  2831. trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
  2832. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  2833. ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
  2834. else
  2835. ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
  2836. trace_ext4_direct_IO_exit(inode, offset,
  2837. iov_length(iov, nr_segs), rw, ret);
  2838. return ret;
  2839. }
  2840. /*
  2841. * Pages can be marked dirty completely asynchronously from ext4's journalling
  2842. * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
  2843. * much here because ->set_page_dirty is called under VFS locks. The page is
  2844. * not necessarily locked.
  2845. *
  2846. * We cannot just dirty the page and leave attached buffers clean, because the
  2847. * buffers' dirty state is "definitive". We cannot just set the buffers dirty
  2848. * or jbddirty because all the journalling code will explode.
  2849. *
  2850. * So what we do is to mark the page "pending dirty" and next time writepage
  2851. * is called, propagate that into the buffers appropriately.
  2852. */
  2853. static int ext4_journalled_set_page_dirty(struct page *page)
  2854. {
  2855. SetPageChecked(page);
  2856. return __set_page_dirty_nobuffers(page);
  2857. }
  2858. static const struct address_space_operations ext4_ordered_aops = {
  2859. .readpage = ext4_readpage,
  2860. .readpages = ext4_readpages,
  2861. .writepage = ext4_writepage,
  2862. .write_begin = ext4_write_begin,
  2863. .write_end = ext4_ordered_write_end,
  2864. .bmap = ext4_bmap,
  2865. .invalidatepage = ext4_invalidatepage,
  2866. .releasepage = ext4_releasepage,
  2867. .direct_IO = ext4_direct_IO,
  2868. .migratepage = buffer_migrate_page,
  2869. .is_partially_uptodate = block_is_partially_uptodate,
  2870. .error_remove_page = generic_error_remove_page,
  2871. };
  2872. static const struct address_space_operations ext4_writeback_aops = {
  2873. .readpage = ext4_readpage,
  2874. .readpages = ext4_readpages,
  2875. .writepage = ext4_writepage,
  2876. .write_begin = ext4_write_begin,
  2877. .write_end = ext4_writeback_write_end,
  2878. .bmap = ext4_bmap,
  2879. .invalidatepage = ext4_invalidatepage,
  2880. .releasepage = ext4_releasepage,
  2881. .direct_IO = ext4_direct_IO,
  2882. .migratepage = buffer_migrate_page,
  2883. .is_partially_uptodate = block_is_partially_uptodate,
  2884. .error_remove_page = generic_error_remove_page,
  2885. };
  2886. static const struct address_space_operations ext4_journalled_aops = {
  2887. .readpage = ext4_readpage,
  2888. .readpages = ext4_readpages,
  2889. .writepage = ext4_writepage,
  2890. .write_begin = ext4_write_begin,
  2891. .write_end = ext4_journalled_write_end,
  2892. .set_page_dirty = ext4_journalled_set_page_dirty,
  2893. .bmap = ext4_bmap,
  2894. .invalidatepage = ext4_invalidatepage,
  2895. .releasepage = ext4_releasepage,
  2896. .direct_IO = ext4_direct_IO,
  2897. .is_partially_uptodate = block_is_partially_uptodate,
  2898. .error_remove_page = generic_error_remove_page,
  2899. };
  2900. static const struct address_space_operations ext4_da_aops = {
  2901. .readpage = ext4_readpage,
  2902. .readpages = ext4_readpages,
  2903. .writepage = ext4_writepage,
  2904. .writepages = ext4_da_writepages,
  2905. .write_begin = ext4_da_write_begin,
  2906. .write_end = ext4_da_write_end,
  2907. .bmap = ext4_bmap,
  2908. .invalidatepage = ext4_da_invalidatepage,
  2909. .releasepage = ext4_releasepage,
  2910. .direct_IO = ext4_direct_IO,
  2911. .migratepage = buffer_migrate_page,
  2912. .is_partially_uptodate = block_is_partially_uptodate,
  2913. .error_remove_page = generic_error_remove_page,
  2914. };
  2915. void ext4_set_aops(struct inode *inode)
  2916. {
  2917. switch (ext4_inode_journal_mode(inode)) {
  2918. case EXT4_INODE_ORDERED_DATA_MODE:
  2919. if (test_opt(inode->i_sb, DELALLOC))
  2920. inode->i_mapping->a_ops = &ext4_da_aops;
  2921. else
  2922. inode->i_mapping->a_ops = &ext4_ordered_aops;
  2923. break;
  2924. case EXT4_INODE_WRITEBACK_DATA_MODE:
  2925. if (test_opt(inode->i_sb, DELALLOC))
  2926. inode->i_mapping->a_ops = &ext4_da_aops;
  2927. else
  2928. inode->i_mapping->a_ops = &ext4_writeback_aops;
  2929. break;
  2930. case EXT4_INODE_JOURNAL_DATA_MODE:
  2931. inode->i_mapping->a_ops = &ext4_journalled_aops;
  2932. break;
  2933. default:
  2934. BUG();
  2935. }
  2936. }
  2937. /*
  2938. * ext4_discard_partial_page_buffers()
  2939. * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
  2940. * This function finds and locks the page containing the offset
  2941. * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
  2942. * Calling functions that already have the page locked should call
  2943. * ext4_discard_partial_page_buffers_no_lock directly.
  2944. */
  2945. int ext4_discard_partial_page_buffers(handle_t *handle,
  2946. struct address_space *mapping, loff_t from,
  2947. loff_t length, int flags)
  2948. {
  2949. struct inode *inode = mapping->host;
  2950. struct page *page;
  2951. int err = 0;
  2952. page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
  2953. mapping_gfp_mask(mapping) & ~__GFP_FS);
  2954. if (!page)
  2955. return -ENOMEM;
  2956. err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
  2957. from, length, flags);
  2958. unlock_page(page);
  2959. page_cache_release(page);
  2960. return err;
  2961. }
  2962. /*
  2963. * ext4_discard_partial_page_buffers_no_lock()
  2964. * Zeros a page range of length 'length' starting from offset 'from'.
  2965. * Buffer heads that correspond to the block aligned regions of the
  2966. * zeroed range will be unmapped. Unblock aligned regions
  2967. * will have the corresponding buffer head mapped if needed so that
  2968. * that region of the page can be updated with the partial zero out.
  2969. *
  2970. * This function assumes that the page has already been locked. The
  2971. * The range to be discarded must be contained with in the given page.
  2972. * If the specified range exceeds the end of the page it will be shortened
  2973. * to the end of the page that corresponds to 'from'. This function is
  2974. * appropriate for updating a page and it buffer heads to be unmapped and
  2975. * zeroed for blocks that have been either released, or are going to be
  2976. * released.
  2977. *
  2978. * handle: The journal handle
  2979. * inode: The files inode
  2980. * page: A locked page that contains the offset "from"
  2981. * from: The starting byte offset (from the begining of the file)
  2982. * to begin discarding
  2983. * len: The length of bytes to discard
  2984. * flags: Optional flags that may be used:
  2985. *
  2986. * EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
  2987. * Only zero the regions of the page whose buffer heads
  2988. * have already been unmapped. This flag is appropriate
  2989. * for updateing the contents of a page whose blocks may
  2990. * have already been released, and we only want to zero
  2991. * out the regions that correspond to those released blocks.
  2992. *
  2993. * Returns zero on sucess or negative on failure.
  2994. */
  2995. static int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
  2996. struct inode *inode, struct page *page, loff_t from,
  2997. loff_t length, int flags)
  2998. {
  2999. ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
  3000. unsigned int offset = from & (PAGE_CACHE_SIZE-1);
  3001. unsigned int blocksize, max, pos;
  3002. ext4_lblk_t iblock;
  3003. struct buffer_head *bh;
  3004. int err = 0;
  3005. blocksize = inode->i_sb->s_blocksize;
  3006. max = PAGE_CACHE_SIZE - offset;
  3007. if (index != page->index)
  3008. return -EINVAL;
  3009. /*
  3010. * correct length if it does not fall between
  3011. * 'from' and the end of the page
  3012. */
  3013. if (length > max || length < 0)
  3014. length = max;
  3015. iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
  3016. if (!page_has_buffers(page))
  3017. create_empty_buffers(page, blocksize, 0);
  3018. /* Find the buffer that contains "offset" */
  3019. bh = page_buffers(page);
  3020. pos = blocksize;
  3021. while (offset >= pos) {
  3022. bh = bh->b_this_page;
  3023. iblock++;
  3024. pos += blocksize;
  3025. }
  3026. pos = offset;
  3027. while (pos < offset + length) {
  3028. unsigned int end_of_block, range_to_discard;
  3029. err = 0;
  3030. /* The length of space left to zero and unmap */
  3031. range_to_discard = offset + length - pos;
  3032. /* The length of space until the end of the block */
  3033. end_of_block = blocksize - (pos & (blocksize-1));
  3034. /*
  3035. * Do not unmap or zero past end of block
  3036. * for this buffer head
  3037. */
  3038. if (range_to_discard > end_of_block)
  3039. range_to_discard = end_of_block;
  3040. /*
  3041. * Skip this buffer head if we are only zeroing unampped
  3042. * regions of the page
  3043. */
  3044. if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
  3045. buffer_mapped(bh))
  3046. goto next;
  3047. /* If the range is block aligned, unmap */
  3048. if (range_to_discard == blocksize) {
  3049. clear_buffer_dirty(bh);
  3050. bh->b_bdev = NULL;
  3051. clear_buffer_mapped(bh);
  3052. clear_buffer_req(bh);
  3053. clear_buffer_new(bh);
  3054. clear_buffer_delay(bh);
  3055. clear_buffer_unwritten(bh);
  3056. clear_buffer_uptodate(bh);
  3057. zero_user(page, pos, range_to_discard);
  3058. BUFFER_TRACE(bh, "Buffer discarded");
  3059. goto next;
  3060. }
  3061. /*
  3062. * If this block is not completely contained in the range
  3063. * to be discarded, then it is not going to be released. Because
  3064. * we need to keep this block, we need to make sure this part
  3065. * of the page is uptodate before we modify it by writeing
  3066. * partial zeros on it.
  3067. */
  3068. if (!buffer_mapped(bh)) {
  3069. /*
  3070. * Buffer head must be mapped before we can read
  3071. * from the block
  3072. */
  3073. BUFFER_TRACE(bh, "unmapped");
  3074. ext4_get_block(inode, iblock, bh, 0);
  3075. /* unmapped? It's a hole - nothing to do */
  3076. if (!buffer_mapped(bh)) {
  3077. BUFFER_TRACE(bh, "still unmapped");
  3078. goto next;
  3079. }
  3080. }
  3081. /* Ok, it's mapped. Make sure it's up-to-date */
  3082. if (PageUptodate(page))
  3083. set_buffer_uptodate(bh);
  3084. if (!buffer_uptodate(bh)) {
  3085. err = -EIO;
  3086. ll_rw_block(READ, 1, &bh);
  3087. wait_on_buffer(bh);
  3088. /* Uhhuh. Read error. Complain and punt.*/
  3089. if (!buffer_uptodate(bh))
  3090. goto next;
  3091. }
  3092. if (ext4_should_journal_data(inode)) {
  3093. BUFFER_TRACE(bh, "get write access");
  3094. err = ext4_journal_get_write_access(handle, bh);
  3095. if (err)
  3096. goto next;
  3097. }
  3098. zero_user(page, pos, range_to_discard);
  3099. err = 0;
  3100. if (ext4_should_journal_data(inode)) {
  3101. err = ext4_handle_dirty_metadata(handle, inode, bh);
  3102. } else
  3103. mark_buffer_dirty(bh);
  3104. BUFFER_TRACE(bh, "Partial buffer zeroed");
  3105. next:
  3106. bh = bh->b_this_page;
  3107. iblock++;
  3108. pos += range_to_discard;
  3109. }
  3110. return err;
  3111. }
  3112. int ext4_can_truncate(struct inode *inode)
  3113. {
  3114. if (S_ISREG(inode->i_mode))
  3115. return 1;
  3116. if (S_ISDIR(inode->i_mode))
  3117. return 1;
  3118. if (S_ISLNK(inode->i_mode))
  3119. return !ext4_inode_is_fast_symlink(inode);
  3120. return 0;
  3121. }
  3122. /*
  3123. * ext4_punch_hole: punches a hole in a file by releaseing the blocks
  3124. * associated with the given offset and length
  3125. *
  3126. * @inode: File inode
  3127. * @offset: The offset where the hole will begin
  3128. * @len: The length of the hole
  3129. *
  3130. * Returns: 0 on sucess or negative on failure
  3131. */
  3132. int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
  3133. {
  3134. #if 0
  3135. struct inode *inode = file->f_path.dentry->d_inode;
  3136. if (!S_ISREG(inode->i_mode))
  3137. return -EOPNOTSUPP;
  3138. if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  3139. /* TODO: Add support for non extent hole punching */
  3140. return -EOPNOTSUPP;
  3141. }
  3142. if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
  3143. /* TODO: Add support for bigalloc file systems */
  3144. return -EOPNOTSUPP;
  3145. }
  3146. return ext4_ext_punch_hole(file, offset, length);
  3147. #else
  3148. /*
  3149. * Disabled as per b/28760453
  3150. */
  3151. return -EOPNOTSUPP;
  3152. #endif
  3153. }
  3154. /*
  3155. * ext4_truncate()
  3156. *
  3157. * We block out ext4_get_block() block instantiations across the entire
  3158. * transaction, and VFS/VM ensures that ext4_truncate() cannot run
  3159. * simultaneously on behalf of the same inode.
  3160. *
  3161. * As we work through the truncate and commit bits of it to the journal there
  3162. * is one core, guiding principle: the file's tree must always be consistent on
  3163. * disk. We must be able to restart the truncate after a crash.
  3164. *
  3165. * The file's tree may be transiently inconsistent in memory (although it
  3166. * probably isn't), but whenever we close off and commit a journal transaction,
  3167. * the contents of (the filesystem + the journal) must be consistent and
  3168. * restartable. It's pretty simple, really: bottom up, right to left (although
  3169. * left-to-right works OK too).
  3170. *
  3171. * Note that at recovery time, journal replay occurs *before* the restart of
  3172. * truncate against the orphan inode list.
  3173. *
  3174. * The committed inode has the new, desired i_size (which is the same as
  3175. * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
  3176. * that this inode's truncate did not complete and it will again call
  3177. * ext4_truncate() to have another go. So there will be instantiated blocks
  3178. * to the right of the truncation point in a crashed ext4 filesystem. But
  3179. * that's fine - as long as they are linked from the inode, the post-crash
  3180. * ext4_truncate() run will find them and release them.
  3181. */
  3182. void ext4_truncate(struct inode *inode)
  3183. {
  3184. trace_ext4_truncate_enter(inode);
  3185. if (!ext4_can_truncate(inode))
  3186. return;
  3187. ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
  3188. if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
  3189. ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
  3190. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  3191. ext4_ext_truncate(inode);
  3192. else
  3193. ext4_ind_truncate(inode);
  3194. trace_ext4_truncate_exit(inode);
  3195. }
  3196. /*
  3197. * ext4_get_inode_loc returns with an extra refcount against the inode's
  3198. * underlying buffer_head on success. If 'in_mem' is true, we have all
  3199. * data in memory that is needed to recreate the on-disk version of this
  3200. * inode.
  3201. */
  3202. static int __ext4_get_inode_loc(struct inode *inode,
  3203. struct ext4_iloc *iloc, int in_mem)
  3204. {
  3205. struct ext4_group_desc *gdp;
  3206. struct buffer_head *bh;
  3207. struct super_block *sb = inode->i_sb;
  3208. ext4_fsblk_t block;
  3209. int inodes_per_block, inode_offset;
  3210. iloc->bh = NULL;
  3211. if (inode->i_ino < EXT4_ROOT_INO ||
  3212. inode->i_ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
  3213. return -EIO;
  3214. iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
  3215. gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
  3216. if (!gdp)
  3217. return -EIO;
  3218. /*
  3219. * Figure out the offset within the block group inode table
  3220. */
  3221. inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
  3222. inode_offset = ((inode->i_ino - 1) %
  3223. EXT4_INODES_PER_GROUP(sb));
  3224. block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
  3225. iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
  3226. bh = sb_getblk(sb, block);
  3227. if (!bh)
  3228. return -ENOMEM;
  3229. if (!buffer_uptodate(bh)) {
  3230. lock_buffer(bh);
  3231. /*
  3232. * If the buffer has the write error flag, we have failed
  3233. * to write out another inode in the same block. In this
  3234. * case, we don't have to read the block because we may
  3235. * read the old inode data successfully.
  3236. */
  3237. if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
  3238. set_buffer_uptodate(bh);
  3239. if (buffer_uptodate(bh)) {
  3240. /* someone brought it uptodate while we waited */
  3241. unlock_buffer(bh);
  3242. goto has_buffer;
  3243. }
  3244. /*
  3245. * If we have all information of the inode in memory and this
  3246. * is the only valid inode in the block, we need not read the
  3247. * block.
  3248. */
  3249. if (in_mem) {
  3250. struct buffer_head *bitmap_bh;
  3251. int i, start;
  3252. start = inode_offset & ~(inodes_per_block - 1);
  3253. /* Is the inode bitmap in cache? */
  3254. bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
  3255. if (!bitmap_bh)
  3256. goto make_io;
  3257. /*
  3258. * If the inode bitmap isn't in cache then the
  3259. * optimisation may end up performing two reads instead
  3260. * of one, so skip it.
  3261. */
  3262. if (!buffer_uptodate(bitmap_bh)) {
  3263. brelse(bitmap_bh);
  3264. goto make_io;
  3265. }
  3266. for (i = start; i < start + inodes_per_block; i++) {
  3267. if (i == inode_offset)
  3268. continue;
  3269. if (ext4_test_bit(i, bitmap_bh->b_data))
  3270. break;
  3271. }
  3272. brelse(bitmap_bh);
  3273. if (i == start + inodes_per_block) {
  3274. /* all other inodes are free, so skip I/O */
  3275. memset(bh->b_data, 0, bh->b_size);
  3276. set_buffer_uptodate(bh);
  3277. unlock_buffer(bh);
  3278. goto has_buffer;
  3279. }
  3280. }
  3281. make_io:
  3282. /*
  3283. * If we need to do any I/O, try to pre-readahead extra
  3284. * blocks from the inode table.
  3285. */
  3286. if (EXT4_SB(sb)->s_inode_readahead_blks) {
  3287. ext4_fsblk_t b, end, table;
  3288. unsigned num;
  3289. table = ext4_inode_table(sb, gdp);
  3290. /* s_inode_readahead_blks is always a power of 2 */
  3291. b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
  3292. if (table > b)
  3293. b = table;
  3294. end = b + EXT4_SB(sb)->s_inode_readahead_blks;
  3295. num = EXT4_INODES_PER_GROUP(sb);
  3296. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3297. EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
  3298. num -= ext4_itable_unused_count(sb, gdp);
  3299. table += num / inodes_per_block;
  3300. if (end > table)
  3301. end = table;
  3302. while (b <= end)
  3303. sb_breadahead(sb, b++);
  3304. }
  3305. /*
  3306. * There are other valid inodes in the buffer, this inode
  3307. * has in-inode xattrs, or we don't have this inode in memory.
  3308. * Read the block from disk.
  3309. */
  3310. trace_ext4_load_inode(inode);
  3311. get_bh(bh);
  3312. bh->b_end_io = end_buffer_read_sync;
  3313. submit_bh(READ | REQ_META | REQ_PRIO, bh);
  3314. wait_on_buffer(bh);
  3315. if (!buffer_uptodate(bh)) {
  3316. EXT4_ERROR_INODE_BLOCK(inode, block,
  3317. "unable to read itable block");
  3318. brelse(bh);
  3319. return -EIO;
  3320. }
  3321. }
  3322. has_buffer:
  3323. iloc->bh = bh;
  3324. return 0;
  3325. }
  3326. int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
  3327. {
  3328. /* We have all inode data except xattrs in memory here. */
  3329. return __ext4_get_inode_loc(inode, iloc,
  3330. !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
  3331. }
  3332. void ext4_set_inode_flags(struct inode *inode)
  3333. {
  3334. unsigned int flags = EXT4_I(inode)->i_flags;
  3335. unsigned int new_fl = 0;
  3336. if (flags & EXT4_SYNC_FL)
  3337. new_fl |= S_SYNC;
  3338. if (flags & EXT4_APPEND_FL)
  3339. new_fl |= S_APPEND;
  3340. if (flags & EXT4_IMMUTABLE_FL)
  3341. new_fl |= S_IMMUTABLE;
  3342. if (flags & EXT4_NOATIME_FL)
  3343. new_fl |= S_NOATIME;
  3344. if (flags & EXT4_DIRSYNC_FL)
  3345. new_fl |= S_DIRSYNC;
  3346. set_mask_bits(&inode->i_flags,
  3347. S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC, new_fl);
  3348. }
  3349. /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
  3350. void ext4_get_inode_flags(struct ext4_inode_info *ei)
  3351. {
  3352. unsigned int vfs_fl;
  3353. unsigned long old_fl, new_fl;
  3354. do {
  3355. vfs_fl = ei->vfs_inode.i_flags;
  3356. old_fl = ei->i_flags;
  3357. new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
  3358. EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
  3359. EXT4_DIRSYNC_FL);
  3360. if (vfs_fl & S_SYNC)
  3361. new_fl |= EXT4_SYNC_FL;
  3362. if (vfs_fl & S_APPEND)
  3363. new_fl |= EXT4_APPEND_FL;
  3364. if (vfs_fl & S_IMMUTABLE)
  3365. new_fl |= EXT4_IMMUTABLE_FL;
  3366. if (vfs_fl & S_NOATIME)
  3367. new_fl |= EXT4_NOATIME_FL;
  3368. if (vfs_fl & S_DIRSYNC)
  3369. new_fl |= EXT4_DIRSYNC_FL;
  3370. } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
  3371. }
  3372. static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
  3373. struct ext4_inode_info *ei)
  3374. {
  3375. blkcnt_t i_blocks ;
  3376. struct inode *inode = &(ei->vfs_inode);
  3377. struct super_block *sb = inode->i_sb;
  3378. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3379. EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
  3380. /* we are using combined 48 bit field */
  3381. i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
  3382. le32_to_cpu(raw_inode->i_blocks_lo);
  3383. if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
  3384. /* i_blocks represent file system block size */
  3385. return i_blocks << (inode->i_blkbits - 9);
  3386. } else {
  3387. return i_blocks;
  3388. }
  3389. } else {
  3390. return le32_to_cpu(raw_inode->i_blocks_lo);
  3391. }
  3392. }
  3393. struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
  3394. {
  3395. struct ext4_iloc iloc;
  3396. struct ext4_inode *raw_inode;
  3397. struct ext4_inode_info *ei;
  3398. struct inode *inode;
  3399. journal_t *journal = EXT4_SB(sb)->s_journal;
  3400. long ret;
  3401. int block;
  3402. inode = iget_locked(sb, ino);
  3403. if (!inode)
  3404. return ERR_PTR(-ENOMEM);
  3405. if (!(inode->i_state & I_NEW))
  3406. return inode;
  3407. ei = EXT4_I(inode);
  3408. iloc.bh = NULL;
  3409. ret = __ext4_get_inode_loc(inode, &iloc, 0);
  3410. if (ret < 0) {
  3411. print_iloc_info(sb,iloc);
  3412. goto bad_inode;
  3413. }
  3414. raw_inode = ext4_raw_inode(&iloc);
  3415. if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
  3416. EXT4_ERROR_INODE(inode, "root inode unallocated");
  3417. ret = -EIO;
  3418. goto bad_inode;
  3419. }
  3420. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3421. ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
  3422. if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
  3423. EXT4_INODE_SIZE(inode->i_sb)) {
  3424. EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
  3425. EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
  3426. EXT4_INODE_SIZE(inode->i_sb));
  3427. ret = -EIO;
  3428. goto bad_inode;
  3429. }
  3430. } else
  3431. ei->i_extra_isize = 0;
  3432. /* Precompute checksum seed for inode metadata */
  3433. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3434. EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
  3435. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  3436. __u32 csum;
  3437. __le32 inum = cpu_to_le32(inode->i_ino);
  3438. __le32 gen = raw_inode->i_generation;
  3439. csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
  3440. sizeof(inum));
  3441. ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
  3442. sizeof(gen));
  3443. }
  3444. if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
  3445. EXT4_ERROR_INODE(inode, "checksum invalid");
  3446. ret = -EIO;
  3447. goto bad_inode;
  3448. }
  3449. inode->i_mode = le16_to_cpu(raw_inode->i_mode);
  3450. inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
  3451. inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
  3452. if (!(test_opt(inode->i_sb, NO_UID32))) {
  3453. inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
  3454. inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
  3455. }
  3456. set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
  3457. ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
  3458. ei->i_dir_start_lookup = 0;
  3459. ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
  3460. /* We now have enough fields to check if the inode was active or not.
  3461. * This is needed because nfsd might try to access dead inodes
  3462. * the test is that same one that e2fsck uses
  3463. * NeilBrown 1999oct15
  3464. */
  3465. if (inode->i_nlink == 0) {
  3466. if (inode->i_mode == 0 ||
  3467. !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
  3468. /* this inode is deleted */
  3469. ret = -ESTALE;
  3470. print_iloc_info(sb,iloc);
  3471. goto bad_inode;
  3472. }
  3473. /* The only unlinked inodes we let through here have
  3474. * valid i_mode and are being read by the orphan
  3475. * recovery code: that's fine, we're about to complete
  3476. * the process of deleting those. */
  3477. }
  3478. ei->i_flags = le32_to_cpu(raw_inode->i_flags);
  3479. inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
  3480. ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
  3481. if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
  3482. ei->i_file_acl |=
  3483. ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
  3484. inode->i_size = ext4_isize(raw_inode);
  3485. ei->i_disksize = inode->i_size;
  3486. #ifdef CONFIG_QUOTA
  3487. ei->i_reserved_quota = 0;
  3488. #endif
  3489. inode->i_generation = le32_to_cpu(raw_inode->i_generation);
  3490. ei->i_block_group = iloc.block_group;
  3491. ei->i_last_alloc_group = ~0;
  3492. /*
  3493. * NOTE! The in-memory inode i_data array is in little-endian order
  3494. * even on big-endian machines: we do NOT byteswap the block numbers!
  3495. */
  3496. for (block = 0; block < EXT4_N_BLOCKS; block++)
  3497. ei->i_data[block] = raw_inode->i_block[block];
  3498. INIT_LIST_HEAD(&ei->i_orphan);
  3499. /*
  3500. * Set transaction id's of transactions that have to be committed
  3501. * to finish f[data]sync. We set them to currently running transaction
  3502. * as we cannot be sure that the inode or some of its metadata isn't
  3503. * part of the transaction - the inode could have been reclaimed and
  3504. * now it is reread from disk.
  3505. */
  3506. if (journal) {
  3507. transaction_t *transaction;
  3508. tid_t tid;
  3509. read_lock(&journal->j_state_lock);
  3510. if (journal->j_running_transaction)
  3511. transaction = journal->j_running_transaction;
  3512. else
  3513. transaction = journal->j_committing_transaction;
  3514. if (transaction)
  3515. tid = transaction->t_tid;
  3516. else
  3517. tid = journal->j_commit_sequence;
  3518. read_unlock(&journal->j_state_lock);
  3519. ei->i_sync_tid = tid;
  3520. ei->i_datasync_tid = tid;
  3521. }
  3522. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3523. if (ei->i_extra_isize == 0) {
  3524. /* The extra space is currently unused. Use it. */
  3525. ei->i_extra_isize = sizeof(struct ext4_inode) -
  3526. EXT4_GOOD_OLD_INODE_SIZE;
  3527. } else {
  3528. __le32 *magic = (void *)raw_inode +
  3529. EXT4_GOOD_OLD_INODE_SIZE +
  3530. ei->i_extra_isize;
  3531. if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
  3532. ext4_set_inode_state(inode, EXT4_STATE_XATTR);
  3533. }
  3534. }
  3535. EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
  3536. EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
  3537. EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
  3538. EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
  3539. inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
  3540. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3541. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  3542. inode->i_version |=
  3543. (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
  3544. }
  3545. ret = 0;
  3546. if (ei->i_file_acl &&
  3547. !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
  3548. print_iloc_info(sb,iloc);
  3549. EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
  3550. ei->i_file_acl);
  3551. ret = -EIO;
  3552. goto bad_inode;
  3553. } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  3554. if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
  3555. (S_ISLNK(inode->i_mode) &&
  3556. !ext4_inode_is_fast_symlink(inode)))
  3557. /* Validate extent which is part of inode */
  3558. ret = ext4_ext_check_inode(inode);
  3559. } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
  3560. (S_ISLNK(inode->i_mode) &&
  3561. !ext4_inode_is_fast_symlink(inode))) {
  3562. /* Validate block references which are part of inode */
  3563. ret = ext4_ind_check_inode(inode);
  3564. }
  3565. if (ret) {
  3566. print_iloc_info(sb,iloc);
  3567. goto bad_inode;
  3568. }
  3569. if (S_ISREG(inode->i_mode)) {
  3570. inode->i_op = &ext4_file_inode_operations;
  3571. inode->i_fop = &ext4_file_operations;
  3572. ext4_set_aops(inode);
  3573. } else if (S_ISDIR(inode->i_mode)) {
  3574. inode->i_op = &ext4_dir_inode_operations;
  3575. inode->i_fop = &ext4_dir_operations;
  3576. } else if (S_ISLNK(inode->i_mode)) {
  3577. if (ext4_inode_is_fast_symlink(inode)) {
  3578. inode->i_op = &ext4_fast_symlink_inode_operations;
  3579. nd_terminate_link(ei->i_data, inode->i_size,
  3580. sizeof(ei->i_data) - 1);
  3581. } else {
  3582. inode->i_op = &ext4_symlink_inode_operations;
  3583. ext4_set_aops(inode);
  3584. }
  3585. } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
  3586. S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
  3587. inode->i_op = &ext4_special_inode_operations;
  3588. if (raw_inode->i_block[0])
  3589. init_special_inode(inode, inode->i_mode,
  3590. old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
  3591. else
  3592. init_special_inode(inode, inode->i_mode,
  3593. new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
  3594. } else {
  3595. ret = -EIO;
  3596. print_iloc_info(sb,iloc);
  3597. EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
  3598. goto bad_inode;
  3599. }
  3600. brelse(iloc.bh);
  3601. ext4_set_inode_flags(inode);
  3602. unlock_new_inode(inode);
  3603. return inode;
  3604. bad_inode:
  3605. brelse(iloc.bh);
  3606. iget_failed(inode);
  3607. return ERR_PTR(ret);
  3608. }
  3609. struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
  3610. {
  3611. if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
  3612. return ERR_PTR(-EIO);
  3613. return ext4_iget(sb, ino);
  3614. }
  3615. static int ext4_inode_blocks_set(handle_t *handle,
  3616. struct ext4_inode *raw_inode,
  3617. struct ext4_inode_info *ei)
  3618. {
  3619. struct inode *inode = &(ei->vfs_inode);
  3620. u64 i_blocks = inode->i_blocks;
  3621. struct super_block *sb = inode->i_sb;
  3622. if (i_blocks <= ~0U) {
  3623. /*
  3624. * i_blocks can be represnted in a 32 bit variable
  3625. * as multiple of 512 bytes
  3626. */
  3627. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3628. raw_inode->i_blocks_high = 0;
  3629. ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  3630. return 0;
  3631. }
  3632. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
  3633. return -EFBIG;
  3634. if (i_blocks <= 0xffffffffffffULL) {
  3635. /*
  3636. * i_blocks can be represented in a 48 bit variable
  3637. * as multiple of 512 bytes
  3638. */
  3639. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3640. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  3641. ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  3642. } else {
  3643. ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  3644. /* i_block is stored in file system block size */
  3645. i_blocks = i_blocks >> (inode->i_blkbits - 9);
  3646. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3647. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  3648. }
  3649. return 0;
  3650. }
  3651. /*
  3652. * Post the struct inode info into an on-disk inode location in the
  3653. * buffer-cache. This gobbles the caller's reference to the
  3654. * buffer_head in the inode location struct.
  3655. *
  3656. * The caller must have write access to iloc->bh.
  3657. */
  3658. static int ext4_do_update_inode(handle_t *handle,
  3659. struct inode *inode,
  3660. struct ext4_iloc *iloc)
  3661. {
  3662. struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
  3663. struct ext4_inode_info *ei = EXT4_I(inode);
  3664. struct buffer_head *bh = iloc->bh;
  3665. int err = 0, rc, block;
  3666. int need_datasync = 0;
  3667. /* For fields not not tracking in the in-memory inode,
  3668. * initialise them to zero for new inodes. */
  3669. if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
  3670. memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
  3671. ext4_get_inode_flags(ei);
  3672. raw_inode->i_mode = cpu_to_le16(inode->i_mode);
  3673. if (!(test_opt(inode->i_sb, NO_UID32))) {
  3674. raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
  3675. raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
  3676. /*
  3677. * Fix up interoperability with old kernels. Otherwise, old inodes get
  3678. * re-used with the upper 16 bits of the uid/gid intact
  3679. */
  3680. if (ei->i_dtime && list_empty(&ei->i_orphan)) {
  3681. raw_inode->i_uid_high = 0;
  3682. raw_inode->i_gid_high = 0;
  3683. } else {
  3684. raw_inode->i_uid_high =
  3685. cpu_to_le16(high_16_bits(inode->i_uid));
  3686. raw_inode->i_gid_high =
  3687. cpu_to_le16(high_16_bits(inode->i_gid));
  3688. }
  3689. } else {
  3690. raw_inode->i_uid_low =
  3691. cpu_to_le16(fs_high2lowuid(inode->i_uid));
  3692. raw_inode->i_gid_low =
  3693. cpu_to_le16(fs_high2lowgid(inode->i_gid));
  3694. raw_inode->i_uid_high = 0;
  3695. raw_inode->i_gid_high = 0;
  3696. }
  3697. raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
  3698. EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
  3699. EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
  3700. EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
  3701. EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
  3702. if (ext4_inode_blocks_set(handle, raw_inode, ei))
  3703. goto out_brelse;
  3704. raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
  3705. raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
  3706. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  3707. cpu_to_le32(EXT4_OS_HURD))
  3708. raw_inode->i_file_acl_high =
  3709. cpu_to_le16(ei->i_file_acl >> 32);
  3710. raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
  3711. if (ei->i_disksize != ext4_isize(raw_inode)) {
  3712. ext4_isize_set(raw_inode, ei->i_disksize);
  3713. need_datasync = 1;
  3714. }
  3715. if (ei->i_disksize > 0x7fffffffULL) {
  3716. struct super_block *sb = inode->i_sb;
  3717. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3718. EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
  3719. EXT4_SB(sb)->s_es->s_rev_level ==
  3720. cpu_to_le32(EXT4_GOOD_OLD_REV)) {
  3721. /* If this is the first large file
  3722. * created, add a flag to the superblock.
  3723. */
  3724. err = ext4_journal_get_write_access(handle,
  3725. EXT4_SB(sb)->s_sbh);
  3726. if (err)
  3727. goto out_brelse;
  3728. ext4_update_dynamic_rev(sb);
  3729. EXT4_SET_RO_COMPAT_FEATURE(sb,
  3730. EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
  3731. ext4_handle_sync(handle);
  3732. err = ext4_handle_dirty_super_now(handle, sb);
  3733. }
  3734. }
  3735. raw_inode->i_generation = cpu_to_le32(inode->i_generation);
  3736. if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
  3737. if (old_valid_dev(inode->i_rdev)) {
  3738. raw_inode->i_block[0] =
  3739. cpu_to_le32(old_encode_dev(inode->i_rdev));
  3740. raw_inode->i_block[1] = 0;
  3741. } else {
  3742. raw_inode->i_block[0] = 0;
  3743. raw_inode->i_block[1] =
  3744. cpu_to_le32(new_encode_dev(inode->i_rdev));
  3745. raw_inode->i_block[2] = 0;
  3746. }
  3747. } else
  3748. for (block = 0; block < EXT4_N_BLOCKS; block++)
  3749. raw_inode->i_block[block] = ei->i_data[block];
  3750. raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
  3751. if (ei->i_extra_isize) {
  3752. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  3753. raw_inode->i_version_hi =
  3754. cpu_to_le32(inode->i_version >> 32);
  3755. raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
  3756. }
  3757. ext4_inode_csum_set(inode, raw_inode, ei);
  3758. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  3759. rc = ext4_handle_dirty_metadata(handle, NULL, bh);
  3760. if (!err)
  3761. err = rc;
  3762. ext4_clear_inode_state(inode, EXT4_STATE_NEW);
  3763. ext4_update_inode_fsync_trans(handle, inode, need_datasync);
  3764. out_brelse:
  3765. brelse(bh);
  3766. ext4_std_error(inode->i_sb, err);
  3767. return err;
  3768. }
  3769. /*
  3770. * ext4_write_inode()
  3771. *
  3772. * We are called from a few places:
  3773. *
  3774. * - Within generic_file_write() for O_SYNC files.
  3775. * Here, there will be no transaction running. We wait for any running
  3776. * trasnaction to commit.
  3777. *
  3778. * - Within sys_sync(), kupdate and such.
  3779. * We wait on commit, if tol to.
  3780. *
  3781. * - Within prune_icache() (PF_MEMALLOC == true)
  3782. * Here we simply return. We can't afford to block kswapd on the
  3783. * journal commit.
  3784. *
  3785. * In all cases it is actually safe for us to return without doing anything,
  3786. * because the inode has been copied into a raw inode buffer in
  3787. * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
  3788. * knfsd.
  3789. *
  3790. * Note that we are absolutely dependent upon all inode dirtiers doing the
  3791. * right thing: they *must* call mark_inode_dirty() after dirtying info in
  3792. * which we are interested.
  3793. *
  3794. * It would be a bug for them to not do this. The code:
  3795. *
  3796. * mark_inode_dirty(inode)
  3797. * stuff();
  3798. * inode->i_size = expr;
  3799. *
  3800. * is in error because a kswapd-driven write_inode() could occur while
  3801. * `stuff()' is running, and the new i_size will be lost. Plus the inode
  3802. * will no longer be on the superblock's dirty inode list.
  3803. */
  3804. int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
  3805. {
  3806. int err;
  3807. if (current->flags & PF_MEMALLOC)
  3808. return 0;
  3809. if (EXT4_SB(inode->i_sb)->s_journal) {
  3810. if (ext4_journal_current_handle()) {
  3811. jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
  3812. dump_stack();
  3813. return -EIO;
  3814. }
  3815. if (wbc->sync_mode != WB_SYNC_ALL)
  3816. return 0;
  3817. err = ext4_force_commit(inode->i_sb);
  3818. } else {
  3819. struct ext4_iloc iloc;
  3820. err = __ext4_get_inode_loc(inode, &iloc, 0);
  3821. if (err)
  3822. return err;
  3823. if (wbc->sync_mode == WB_SYNC_ALL)
  3824. sync_dirty_buffer(iloc.bh);
  3825. if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
  3826. EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
  3827. "IO error syncing inode");
  3828. err = -EIO;
  3829. }
  3830. brelse(iloc.bh);
  3831. }
  3832. return err;
  3833. }
  3834. /*
  3835. * ext4_setattr()
  3836. *
  3837. * Called from notify_change.
  3838. *
  3839. * We want to trap VFS attempts to truncate the file as soon as
  3840. * possible. In particular, we want to make sure that when the VFS
  3841. * shrinks i_size, we put the inode on the orphan list and modify
  3842. * i_disksize immediately, so that during the subsequent flushing of
  3843. * dirty pages and freeing of disk blocks, we can guarantee that any
  3844. * commit will leave the blocks being flushed in an unused state on
  3845. * disk. (On recovery, the inode will get truncated and the blocks will
  3846. * be freed, so we have a strong guarantee that no future commit will
  3847. * leave these blocks visible to the user.)
  3848. *
  3849. * Another thing we have to assure is that if we are in ordered mode
  3850. * and inode is still attached to the committing transaction, we must
  3851. * we start writeout of all the dirty pages which are being truncated.
  3852. * This way we are sure that all the data written in the previous
  3853. * transaction are already on disk (truncate waits for pages under
  3854. * writeback).
  3855. *
  3856. * Called with inode->i_mutex down.
  3857. */
  3858. int ext4_setattr(struct dentry *dentry, struct iattr *attr)
  3859. {
  3860. struct inode *inode = dentry->d_inode;
  3861. int error, rc = 0;
  3862. int orphan = 0;
  3863. const unsigned int ia_valid = attr->ia_valid;
  3864. error = inode_change_ok(inode, attr);
  3865. if (error)
  3866. return error;
  3867. if (is_quota_modification(inode, attr))
  3868. dquot_initialize(inode);
  3869. if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
  3870. (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
  3871. handle_t *handle;
  3872. /* (user+group)*(old+new) structure, inode write (sb,
  3873. * inode block, ? - but truncate inode update has it) */
  3874. handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
  3875. EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
  3876. if (IS_ERR(handle)) {
  3877. error = PTR_ERR(handle);
  3878. goto err_out;
  3879. }
  3880. error = dquot_transfer(inode, attr);
  3881. if (error) {
  3882. ext4_journal_stop(handle);
  3883. return error;
  3884. }
  3885. /* Update corresponding info in inode so that everything is in
  3886. * one transaction */
  3887. if (attr->ia_valid & ATTR_UID)
  3888. inode->i_uid = attr->ia_uid;
  3889. if (attr->ia_valid & ATTR_GID)
  3890. inode->i_gid = attr->ia_gid;
  3891. error = ext4_mark_inode_dirty(handle, inode);
  3892. ext4_journal_stop(handle);
  3893. }
  3894. if (attr->ia_valid & ATTR_SIZE) {
  3895. inode_dio_wait(inode);
  3896. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
  3897. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  3898. if (attr->ia_size > sbi->s_bitmap_maxbytes)
  3899. return -EFBIG;
  3900. }
  3901. }
  3902. if (S_ISREG(inode->i_mode) &&
  3903. attr->ia_valid & ATTR_SIZE &&
  3904. (attr->ia_size < inode->i_size)) {
  3905. handle_t *handle;
  3906. handle = ext4_journal_start(inode, 3);
  3907. if (IS_ERR(handle)) {
  3908. error = PTR_ERR(handle);
  3909. goto err_out;
  3910. }
  3911. if (ext4_handle_valid(handle)) {
  3912. error = ext4_orphan_add(handle, inode);
  3913. orphan = 1;
  3914. }
  3915. EXT4_I(inode)->i_disksize = attr->ia_size;
  3916. rc = ext4_mark_inode_dirty(handle, inode);
  3917. if (!error)
  3918. error = rc;
  3919. ext4_journal_stop(handle);
  3920. if (ext4_should_order_data(inode)) {
  3921. error = ext4_begin_ordered_truncate(inode,
  3922. attr->ia_size);
  3923. if (error) {
  3924. /* Do as much error cleanup as possible */
  3925. handle = ext4_journal_start(inode, 3);
  3926. if (IS_ERR(handle)) {
  3927. ext4_orphan_del(NULL, inode);
  3928. goto err_out;
  3929. }
  3930. ext4_orphan_del(handle, inode);
  3931. orphan = 0;
  3932. ext4_journal_stop(handle);
  3933. goto err_out;
  3934. }
  3935. }
  3936. }
  3937. if (attr->ia_valid & ATTR_SIZE) {
  3938. if (attr->ia_size != i_size_read(inode))
  3939. truncate_setsize(inode, attr->ia_size);
  3940. ext4_truncate(inode);
  3941. }
  3942. if (!rc) {
  3943. setattr_copy(inode, attr);
  3944. mark_inode_dirty(inode);
  3945. }
  3946. /*
  3947. * If the call to ext4_truncate failed to get a transaction handle at
  3948. * all, we need to clean up the in-core orphan list manually.
  3949. */
  3950. if (orphan && inode->i_nlink)
  3951. ext4_orphan_del(NULL, inode);
  3952. if (!rc && (ia_valid & ATTR_MODE))
  3953. rc = ext4_acl_chmod(inode);
  3954. err_out:
  3955. ext4_std_error(inode->i_sb, error);
  3956. if (!error)
  3957. error = rc;
  3958. return error;
  3959. }
  3960. int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
  3961. struct kstat *stat)
  3962. {
  3963. struct inode *inode;
  3964. unsigned long long delalloc_blocks;
  3965. inode = dentry->d_inode;
  3966. generic_fillattr(inode, stat);
  3967. /*
  3968. * We can't update i_blocks if the block allocation is delayed
  3969. * otherwise in the case of system crash before the real block
  3970. * allocation is done, we will have i_blocks inconsistent with
  3971. * on-disk file blocks.
  3972. * We always keep i_blocks updated together with real
  3973. * allocation. But to not confuse with user, stat
  3974. * will return the blocks that include the delayed allocation
  3975. * blocks for this file.
  3976. */
  3977. delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  3978. stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits-9);
  3979. return 0;
  3980. }
  3981. static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  3982. {
  3983. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
  3984. return ext4_ind_trans_blocks(inode, nrblocks, chunk);
  3985. return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
  3986. }
  3987. /*
  3988. * Account for index blocks, block groups bitmaps and block group
  3989. * descriptor blocks if modify datablocks and index blocks
  3990. * worse case, the indexs blocks spread over different block groups
  3991. *
  3992. * If datablocks are discontiguous, they are possible to spread over
  3993. * different block groups too. If they are contiuguous, with flexbg,
  3994. * they could still across block group boundary.
  3995. *
  3996. * Also account for superblock, inode, quota and xattr blocks
  3997. */
  3998. static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  3999. {
  4000. ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
  4001. int gdpblocks;
  4002. int idxblocks;
  4003. int ret = 0;
  4004. /*
  4005. * How many index blocks need to touch to modify nrblocks?
  4006. * The "Chunk" flag indicating whether the nrblocks is
  4007. * physically contiguous on disk
  4008. *
  4009. * For Direct IO and fallocate, they calls get_block to allocate
  4010. * one single extent at a time, so they could set the "Chunk" flag
  4011. */
  4012. idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
  4013. ret = idxblocks;
  4014. /*
  4015. * Now let's see how many group bitmaps and group descriptors need
  4016. * to account
  4017. */
  4018. groups = idxblocks;
  4019. if (chunk)
  4020. groups += 1;
  4021. else
  4022. groups += nrblocks;
  4023. gdpblocks = groups;
  4024. if (groups > ngroups)
  4025. groups = ngroups;
  4026. if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
  4027. gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
  4028. /* bitmaps and block group descriptor blocks */
  4029. ret += groups + gdpblocks;
  4030. /* Blocks for super block, inode, quota and xattr blocks */
  4031. ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
  4032. return ret;
  4033. }
  4034. /*
  4035. * Calculate the total number of credits to reserve to fit
  4036. * the modification of a single pages into a single transaction,
  4037. * which may include multiple chunks of block allocations.
  4038. *
  4039. * This could be called via ext4_write_begin()
  4040. *
  4041. * We need to consider the worse case, when
  4042. * one new block per extent.
  4043. */
  4044. int ext4_writepage_trans_blocks(struct inode *inode)
  4045. {
  4046. int bpp = ext4_journal_blocks_per_page(inode);
  4047. int ret;
  4048. ret = ext4_meta_trans_blocks(inode, bpp, 0);
  4049. /* Account for data blocks for journalled mode */
  4050. if (ext4_should_journal_data(inode))
  4051. ret += bpp;
  4052. return ret;
  4053. }
  4054. /*
  4055. * Calculate the journal credits for a chunk of data modification.
  4056. *
  4057. * This is called from DIO, fallocate or whoever calling
  4058. * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
  4059. *
  4060. * journal buffers for data blocks are not included here, as DIO
  4061. * and fallocate do no need to journal data buffers.
  4062. */
  4063. int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
  4064. {
  4065. return ext4_meta_trans_blocks(inode, nrblocks, 1);
  4066. }
  4067. /*
  4068. * The caller must have previously called ext4_reserve_inode_write().
  4069. * Give this, we know that the caller already has write access to iloc->bh.
  4070. */
  4071. int ext4_mark_iloc_dirty(handle_t *handle,
  4072. struct inode *inode, struct ext4_iloc *iloc)
  4073. {
  4074. int err = 0;
  4075. if (IS_I_VERSION(inode))
  4076. inode_inc_iversion(inode);
  4077. /* the do_update_inode consumes one bh->b_count */
  4078. get_bh(iloc->bh);
  4079. /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
  4080. err = ext4_do_update_inode(handle, inode, iloc);
  4081. put_bh(iloc->bh);
  4082. return err;
  4083. }
  4084. /*
  4085. * On success, We end up with an outstanding reference count against
  4086. * iloc->bh. This _must_ be cleaned up later.
  4087. */
  4088. int
  4089. ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
  4090. struct ext4_iloc *iloc)
  4091. {
  4092. int err;
  4093. err = ext4_get_inode_loc(inode, iloc);
  4094. if (!err) {
  4095. BUFFER_TRACE(iloc->bh, "get_write_access");
  4096. err = ext4_journal_get_write_access(handle, iloc->bh);
  4097. if (err) {
  4098. brelse(iloc->bh);
  4099. iloc->bh = NULL;
  4100. }
  4101. }
  4102. ext4_std_error(inode->i_sb, err);
  4103. return err;
  4104. }
  4105. /*
  4106. * Expand an inode by new_extra_isize bytes.
  4107. * Returns 0 on success or negative error number on failure.
  4108. */
  4109. static int ext4_expand_extra_isize(struct inode *inode,
  4110. unsigned int new_extra_isize,
  4111. struct ext4_iloc iloc,
  4112. handle_t *handle)
  4113. {
  4114. struct ext4_inode *raw_inode;
  4115. struct ext4_xattr_ibody_header *header;
  4116. if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
  4117. return 0;
  4118. raw_inode = ext4_raw_inode(&iloc);
  4119. header = IHDR(inode, raw_inode);
  4120. /* No extended attributes present */
  4121. if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
  4122. header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
  4123. memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
  4124. new_extra_isize);
  4125. EXT4_I(inode)->i_extra_isize = new_extra_isize;
  4126. return 0;
  4127. }
  4128. /* try to expand with EAs present */
  4129. return ext4_expand_extra_isize_ea(inode, new_extra_isize,
  4130. raw_inode, handle);
  4131. }
  4132. /*
  4133. * What we do here is to mark the in-core inode as clean with respect to inode
  4134. * dirtiness (it may still be data-dirty).
  4135. * This means that the in-core inode may be reaped by prune_icache
  4136. * without having to perform any I/O. This is a very good thing,
  4137. * because *any* task may call prune_icache - even ones which
  4138. * have a transaction open against a different journal.
  4139. *
  4140. * Is this cheating? Not really. Sure, we haven't written the
  4141. * inode out, but prune_icache isn't a user-visible syncing function.
  4142. * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
  4143. * we start and wait on commits.
  4144. *
  4145. * Is this efficient/effective? Well, we're being nice to the system
  4146. * by cleaning up our inodes proactively so they can be reaped
  4147. * without I/O. But we are potentially leaving up to five seconds'
  4148. * worth of inodes floating about which prune_icache wants us to
  4149. * write out. One way to fix that would be to get prune_icache()
  4150. * to do a write_super() to free up some memory. It has the desired
  4151. * effect.
  4152. */
  4153. int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
  4154. {
  4155. struct ext4_iloc iloc;
  4156. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  4157. static unsigned int mnt_count;
  4158. int err, ret;
  4159. might_sleep();
  4160. trace_ext4_mark_inode_dirty(inode, _RET_IP_);
  4161. err = ext4_reserve_inode_write(handle, inode, &iloc);
  4162. if (ext4_handle_valid(handle) &&
  4163. EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
  4164. !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
  4165. /*
  4166. * We need extra buffer credits since we may write into EA block
  4167. * with this same handle. If journal_extend fails, then it will
  4168. * only result in a minor loss of functionality for that inode.
  4169. * If this is felt to be critical, then e2fsck should be run to
  4170. * force a large enough s_min_extra_isize.
  4171. */
  4172. if ((jbd2_journal_extend(handle,
  4173. EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
  4174. ret = ext4_expand_extra_isize(inode,
  4175. sbi->s_want_extra_isize,
  4176. iloc, handle);
  4177. if (ret) {
  4178. ext4_set_inode_state(inode,
  4179. EXT4_STATE_NO_EXPAND);
  4180. if (mnt_count !=
  4181. le16_to_cpu(sbi->s_es->s_mnt_count)) {
  4182. ext4_warning(inode->i_sb,
  4183. "Unable to expand inode %lu. Delete"
  4184. " some EAs or run e2fsck.",
  4185. inode->i_ino);
  4186. mnt_count =
  4187. le16_to_cpu(sbi->s_es->s_mnt_count);
  4188. }
  4189. }
  4190. }
  4191. }
  4192. if (!err)
  4193. err = ext4_mark_iloc_dirty(handle, inode, &iloc);
  4194. return err;
  4195. }
  4196. /*
  4197. * ext4_dirty_inode() is called from __mark_inode_dirty()
  4198. *
  4199. * We're really interested in the case where a file is being extended.
  4200. * i_size has been changed by generic_commit_write() and we thus need
  4201. * to include the updated inode in the current transaction.
  4202. *
  4203. * Also, dquot_alloc_block() will always dirty the inode when blocks
  4204. * are allocated to the file.
  4205. *
  4206. * If the inode is marked synchronous, we don't honour that here - doing
  4207. * so would cause a commit on atime updates, which we don't bother doing.
  4208. * We handle synchronous inodes at the highest possible level.
  4209. */
  4210. void ext4_dirty_inode(struct inode *inode, int flags)
  4211. {
  4212. handle_t *handle;
  4213. handle = ext4_journal_start(inode, 2);
  4214. if (IS_ERR(handle))
  4215. goto out;
  4216. ext4_mark_inode_dirty(handle, inode);
  4217. ext4_journal_stop(handle);
  4218. out:
  4219. return;
  4220. }
  4221. #if 0
  4222. /*
  4223. * Bind an inode's backing buffer_head into this transaction, to prevent
  4224. * it from being flushed to disk early. Unlike
  4225. * ext4_reserve_inode_write, this leaves behind no bh reference and
  4226. * returns no iloc structure, so the caller needs to repeat the iloc
  4227. * lookup to mark the inode dirty later.
  4228. */
  4229. static int ext4_pin_inode(handle_t *handle, struct inode *inode)
  4230. {
  4231. struct ext4_iloc iloc;
  4232. int err = 0;
  4233. if (handle) {
  4234. err = ext4_get_inode_loc(inode, &iloc);
  4235. if (!err) {
  4236. BUFFER_TRACE(iloc.bh, "get_write_access");
  4237. err = jbd2_journal_get_write_access(handle, iloc.bh);
  4238. if (!err)
  4239. err = ext4_handle_dirty_metadata(handle,
  4240. NULL,
  4241. iloc.bh);
  4242. brelse(iloc.bh);
  4243. }
  4244. }
  4245. ext4_std_error(inode->i_sb, err);
  4246. return err;
  4247. }
  4248. #endif
  4249. int ext4_change_inode_journal_flag(struct inode *inode, int val)
  4250. {
  4251. journal_t *journal;
  4252. handle_t *handle;
  4253. int err;
  4254. /*
  4255. * We have to be very careful here: changing a data block's
  4256. * journaling status dynamically is dangerous. If we write a
  4257. * data block to the journal, change the status and then delete
  4258. * that block, we risk forgetting to revoke the old log record
  4259. * from the journal and so a subsequent replay can corrupt data.
  4260. * So, first we make sure that the journal is empty and that
  4261. * nobody is changing anything.
  4262. */
  4263. journal = EXT4_JOURNAL(inode);
  4264. if (!journal)
  4265. return 0;
  4266. if (is_journal_aborted(journal))
  4267. return -EROFS;
  4268. /* We have to allocate physical blocks for delalloc blocks
  4269. * before flushing journal. otherwise delalloc blocks can not
  4270. * be allocated any more. even more truncate on delalloc blocks
  4271. * could trigger BUG by flushing delalloc blocks in journal.
  4272. * There is no delalloc block in non-journal data mode.
  4273. */
  4274. if (val && test_opt(inode->i_sb, DELALLOC)) {
  4275. err = ext4_alloc_da_blocks(inode);
  4276. if (err < 0)
  4277. return err;
  4278. }
  4279. jbd2_journal_lock_updates(journal);
  4280. /*
  4281. * OK, there are no updates running now, and all cached data is
  4282. * synced to disk. We are now in a completely consistent state
  4283. * which doesn't have anything in the journal, and we know that
  4284. * no filesystem updates are running, so it is safe to modify
  4285. * the inode's in-core data-journaling state flag now.
  4286. */
  4287. if (val)
  4288. ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  4289. else {
  4290. jbd2_journal_flush(journal);
  4291. ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  4292. }
  4293. ext4_set_aops(inode);
  4294. jbd2_journal_unlock_updates(journal);
  4295. /* Finally we can mark the inode as dirty. */
  4296. handle = ext4_journal_start(inode, 1);
  4297. if (IS_ERR(handle))
  4298. return PTR_ERR(handle);
  4299. err = ext4_mark_inode_dirty(handle, inode);
  4300. ext4_handle_sync(handle);
  4301. ext4_journal_stop(handle);
  4302. ext4_std_error(inode->i_sb, err);
  4303. return err;
  4304. }
  4305. static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
  4306. {
  4307. return !buffer_mapped(bh);
  4308. }
  4309. int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
  4310. {
  4311. struct page *page = vmf->page;
  4312. loff_t size;
  4313. unsigned long len;
  4314. int ret;
  4315. struct file *file = vma->vm_file;
  4316. struct inode *inode = file->f_path.dentry->d_inode;
  4317. struct address_space *mapping = inode->i_mapping;
  4318. handle_t *handle;
  4319. get_block_t *get_block;
  4320. int retries = 0;
  4321. /*
  4322. * This check is racy but catches the common case. We rely on
  4323. * __block_page_mkwrite() to do a reliable check.
  4324. */
  4325. vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
  4326. /* Delalloc case is easy... */
  4327. if (test_opt(inode->i_sb, DELALLOC) &&
  4328. !ext4_should_journal_data(inode) &&
  4329. !ext4_nonda_switch(inode->i_sb)) {
  4330. do {
  4331. ret = __block_page_mkwrite(vma, vmf,
  4332. ext4_da_get_block_prep);
  4333. } while (ret == -ENOSPC &&
  4334. ext4_should_retry_alloc(inode->i_sb, &retries));
  4335. goto out_ret;
  4336. }
  4337. lock_page(page);
  4338. size = i_size_read(inode);
  4339. /* Page got truncated from under us? */
  4340. if (page->mapping != mapping || page_offset(page) > size) {
  4341. unlock_page(page);
  4342. ret = VM_FAULT_NOPAGE;
  4343. goto out;
  4344. }
  4345. if (page->index == size >> PAGE_CACHE_SHIFT)
  4346. len = size & ~PAGE_CACHE_MASK;
  4347. else
  4348. len = PAGE_CACHE_SIZE;
  4349. /*
  4350. * Return if we have all the buffers mapped. This avoids the need to do
  4351. * journal_start/journal_stop which can block and take a long time
  4352. */
  4353. if (page_has_buffers(page)) {
  4354. if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  4355. ext4_bh_unmapped)) {
  4356. /* Wait so that we don't change page under IO */
  4357. wait_on_page_writeback(page);
  4358. ret = VM_FAULT_LOCKED;
  4359. goto out;
  4360. }
  4361. }
  4362. unlock_page(page);
  4363. /* OK, we need to fill the hole... */
  4364. if (ext4_should_dioread_nolock(inode))
  4365. get_block = ext4_get_block_write;
  4366. else
  4367. get_block = ext4_get_block;
  4368. retry_alloc:
  4369. handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
  4370. if (IS_ERR(handle)) {
  4371. ret = VM_FAULT_SIGBUS;
  4372. goto out;
  4373. }
  4374. ret = __block_page_mkwrite(vma, vmf, get_block);
  4375. if (!ret && ext4_should_journal_data(inode)) {
  4376. if (walk_page_buffers(handle, page_buffers(page), 0,
  4377. PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
  4378. unlock_page(page);
  4379. ret = VM_FAULT_SIGBUS;
  4380. ext4_journal_stop(handle);
  4381. goto out;
  4382. }
  4383. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  4384. }
  4385. ext4_journal_stop(handle);
  4386. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  4387. goto retry_alloc;
  4388. out_ret:
  4389. ret = block_page_mkwrite_return(ret);
  4390. out:
  4391. return ret;
  4392. }