inode.c 168 KB

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