inode.c 175 KB

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