inode.c 171 KB

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