inode.c 140 KB

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