inode.c 173 KB

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