inode.c 170 KB

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