inode.c 146 KB

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