inode.c 169 KB

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