inode.c 174 KB

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