inode.c 155 KB

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