inode.c 168 KB

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