inode.c 174 KB

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