inode.c 132 KB

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