inode.c 128 KB

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