inode.c 172 KB

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