inode.c 174 KB

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