inode.c 148 KB

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