inode.c 133 KB

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