inode.c 170 KB

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