inode.c 170 KB

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