inode.c 169 KB

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