file.c 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010
  1. /*
  2. * Copyright (C) 2007 Oracle. All rights reserved.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public
  6. * License v2 as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public
  14. * License along with this program; if not, write to the
  15. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  16. * Boston, MA 021110-1307, USA.
  17. */
  18. #include <linux/fs.h>
  19. #include <linux/pagemap.h>
  20. #include <linux/highmem.h>
  21. #include <linux/time.h>
  22. #include <linux/init.h>
  23. #include <linux/string.h>
  24. #include <linux/backing-dev.h>
  25. #include <linux/mpage.h>
  26. #include <linux/falloc.h>
  27. #include <linux/swap.h>
  28. #include <linux/writeback.h>
  29. #include <linux/statfs.h>
  30. #include <linux/compat.h>
  31. #include <linux/slab.h>
  32. #include <linux/btrfs.h>
  33. #include <linux/uio.h>
  34. #include "ctree.h"
  35. #include "disk-io.h"
  36. #include "transaction.h"
  37. #include "btrfs_inode.h"
  38. #include "print-tree.h"
  39. #include "tree-log.h"
  40. #include "locking.h"
  41. #include "volumes.h"
  42. #include "qgroup.h"
  43. #include "compression.h"
  44. static struct kmem_cache *btrfs_inode_defrag_cachep;
  45. /*
  46. * when auto defrag is enabled we
  47. * queue up these defrag structs to remember which
  48. * inodes need defragging passes
  49. */
  50. struct inode_defrag {
  51. struct rb_node rb_node;
  52. /* objectid */
  53. u64 ino;
  54. /*
  55. * transid where the defrag was added, we search for
  56. * extents newer than this
  57. */
  58. u64 transid;
  59. /* root objectid */
  60. u64 root;
  61. /* last offset we were able to defrag */
  62. u64 last_offset;
  63. /* if we've wrapped around back to zero once already */
  64. int cycled;
  65. };
  66. static int __compare_inode_defrag(struct inode_defrag *defrag1,
  67. struct inode_defrag *defrag2)
  68. {
  69. if (defrag1->root > defrag2->root)
  70. return 1;
  71. else if (defrag1->root < defrag2->root)
  72. return -1;
  73. else if (defrag1->ino > defrag2->ino)
  74. return 1;
  75. else if (defrag1->ino < defrag2->ino)
  76. return -1;
  77. else
  78. return 0;
  79. }
  80. /* pop a record for an inode into the defrag tree. The lock
  81. * must be held already
  82. *
  83. * If you're inserting a record for an older transid than an
  84. * existing record, the transid already in the tree is lowered
  85. *
  86. * If an existing record is found the defrag item you
  87. * pass in is freed
  88. */
  89. static int __btrfs_add_inode_defrag(struct inode *inode,
  90. struct inode_defrag *defrag)
  91. {
  92. struct btrfs_root *root = BTRFS_I(inode)->root;
  93. struct inode_defrag *entry;
  94. struct rb_node **p;
  95. struct rb_node *parent = NULL;
  96. int ret;
  97. p = &root->fs_info->defrag_inodes.rb_node;
  98. while (*p) {
  99. parent = *p;
  100. entry = rb_entry(parent, struct inode_defrag, rb_node);
  101. ret = __compare_inode_defrag(defrag, entry);
  102. if (ret < 0)
  103. p = &parent->rb_left;
  104. else if (ret > 0)
  105. p = &parent->rb_right;
  106. else {
  107. /* if we're reinserting an entry for
  108. * an old defrag run, make sure to
  109. * lower the transid of our existing record
  110. */
  111. if (defrag->transid < entry->transid)
  112. entry->transid = defrag->transid;
  113. if (defrag->last_offset > entry->last_offset)
  114. entry->last_offset = defrag->last_offset;
  115. return -EEXIST;
  116. }
  117. }
  118. set_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
  119. rb_link_node(&defrag->rb_node, parent, p);
  120. rb_insert_color(&defrag->rb_node, &root->fs_info->defrag_inodes);
  121. return 0;
  122. }
  123. static inline int __need_auto_defrag(struct btrfs_root *root)
  124. {
  125. if (!btrfs_test_opt(root, AUTO_DEFRAG))
  126. return 0;
  127. if (btrfs_fs_closing(root->fs_info))
  128. return 0;
  129. return 1;
  130. }
  131. /*
  132. * insert a defrag record for this inode if auto defrag is
  133. * enabled
  134. */
  135. int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
  136. struct inode *inode)
  137. {
  138. struct btrfs_root *root = BTRFS_I(inode)->root;
  139. struct inode_defrag *defrag;
  140. u64 transid;
  141. int ret;
  142. if (!__need_auto_defrag(root))
  143. return 0;
  144. if (test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags))
  145. return 0;
  146. if (trans)
  147. transid = trans->transid;
  148. else
  149. transid = BTRFS_I(inode)->root->last_trans;
  150. defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
  151. if (!defrag)
  152. return -ENOMEM;
  153. defrag->ino = btrfs_ino(inode);
  154. defrag->transid = transid;
  155. defrag->root = root->root_key.objectid;
  156. spin_lock(&root->fs_info->defrag_inodes_lock);
  157. if (!test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags)) {
  158. /*
  159. * If we set IN_DEFRAG flag and evict the inode from memory,
  160. * and then re-read this inode, this new inode doesn't have
  161. * IN_DEFRAG flag. At the case, we may find the existed defrag.
  162. */
  163. ret = __btrfs_add_inode_defrag(inode, defrag);
  164. if (ret)
  165. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  166. } else {
  167. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  168. }
  169. spin_unlock(&root->fs_info->defrag_inodes_lock);
  170. return 0;
  171. }
  172. /*
  173. * Requeue the defrag object. If there is a defrag object that points to
  174. * the same inode in the tree, we will merge them together (by
  175. * __btrfs_add_inode_defrag()) and free the one that we want to requeue.
  176. */
  177. static void btrfs_requeue_inode_defrag(struct inode *inode,
  178. struct inode_defrag *defrag)
  179. {
  180. struct btrfs_root *root = BTRFS_I(inode)->root;
  181. int ret;
  182. if (!__need_auto_defrag(root))
  183. goto out;
  184. /*
  185. * Here we don't check the IN_DEFRAG flag, because we need merge
  186. * them together.
  187. */
  188. spin_lock(&root->fs_info->defrag_inodes_lock);
  189. ret = __btrfs_add_inode_defrag(inode, defrag);
  190. spin_unlock(&root->fs_info->defrag_inodes_lock);
  191. if (ret)
  192. goto out;
  193. return;
  194. out:
  195. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  196. }
  197. /*
  198. * pick the defragable inode that we want, if it doesn't exist, we will get
  199. * the next one.
  200. */
  201. static struct inode_defrag *
  202. btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
  203. {
  204. struct inode_defrag *entry = NULL;
  205. struct inode_defrag tmp;
  206. struct rb_node *p;
  207. struct rb_node *parent = NULL;
  208. int ret;
  209. tmp.ino = ino;
  210. tmp.root = root;
  211. spin_lock(&fs_info->defrag_inodes_lock);
  212. p = fs_info->defrag_inodes.rb_node;
  213. while (p) {
  214. parent = p;
  215. entry = rb_entry(parent, struct inode_defrag, rb_node);
  216. ret = __compare_inode_defrag(&tmp, entry);
  217. if (ret < 0)
  218. p = parent->rb_left;
  219. else if (ret > 0)
  220. p = parent->rb_right;
  221. else
  222. goto out;
  223. }
  224. if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
  225. parent = rb_next(parent);
  226. if (parent)
  227. entry = rb_entry(parent, struct inode_defrag, rb_node);
  228. else
  229. entry = NULL;
  230. }
  231. out:
  232. if (entry)
  233. rb_erase(parent, &fs_info->defrag_inodes);
  234. spin_unlock(&fs_info->defrag_inodes_lock);
  235. return entry;
  236. }
  237. void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
  238. {
  239. struct inode_defrag *defrag;
  240. struct rb_node *node;
  241. spin_lock(&fs_info->defrag_inodes_lock);
  242. node = rb_first(&fs_info->defrag_inodes);
  243. while (node) {
  244. rb_erase(node, &fs_info->defrag_inodes);
  245. defrag = rb_entry(node, struct inode_defrag, rb_node);
  246. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  247. cond_resched_lock(&fs_info->defrag_inodes_lock);
  248. node = rb_first(&fs_info->defrag_inodes);
  249. }
  250. spin_unlock(&fs_info->defrag_inodes_lock);
  251. }
  252. #define BTRFS_DEFRAG_BATCH 1024
  253. static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
  254. struct inode_defrag *defrag)
  255. {
  256. struct btrfs_root *inode_root;
  257. struct inode *inode;
  258. struct btrfs_key key;
  259. struct btrfs_ioctl_defrag_range_args range;
  260. int num_defrag;
  261. int index;
  262. int ret;
  263. /* get the inode */
  264. key.objectid = defrag->root;
  265. key.type = BTRFS_ROOT_ITEM_KEY;
  266. key.offset = (u64)-1;
  267. index = srcu_read_lock(&fs_info->subvol_srcu);
  268. inode_root = btrfs_read_fs_root_no_name(fs_info, &key);
  269. if (IS_ERR(inode_root)) {
  270. ret = PTR_ERR(inode_root);
  271. goto cleanup;
  272. }
  273. key.objectid = defrag->ino;
  274. key.type = BTRFS_INODE_ITEM_KEY;
  275. key.offset = 0;
  276. inode = btrfs_iget(fs_info->sb, &key, inode_root, NULL);
  277. if (IS_ERR(inode)) {
  278. ret = PTR_ERR(inode);
  279. goto cleanup;
  280. }
  281. srcu_read_unlock(&fs_info->subvol_srcu, index);
  282. /* do a chunk of defrag */
  283. clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
  284. memset(&range, 0, sizeof(range));
  285. range.len = (u64)-1;
  286. range.start = defrag->last_offset;
  287. sb_start_write(fs_info->sb);
  288. num_defrag = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
  289. BTRFS_DEFRAG_BATCH);
  290. sb_end_write(fs_info->sb);
  291. /*
  292. * if we filled the whole defrag batch, there
  293. * must be more work to do. Queue this defrag
  294. * again
  295. */
  296. if (num_defrag == BTRFS_DEFRAG_BATCH) {
  297. defrag->last_offset = range.start;
  298. btrfs_requeue_inode_defrag(inode, defrag);
  299. } else if (defrag->last_offset && !defrag->cycled) {
  300. /*
  301. * we didn't fill our defrag batch, but
  302. * we didn't start at zero. Make sure we loop
  303. * around to the start of the file.
  304. */
  305. defrag->last_offset = 0;
  306. defrag->cycled = 1;
  307. btrfs_requeue_inode_defrag(inode, defrag);
  308. } else {
  309. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  310. }
  311. iput(inode);
  312. return 0;
  313. cleanup:
  314. srcu_read_unlock(&fs_info->subvol_srcu, index);
  315. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  316. return ret;
  317. }
  318. /*
  319. * run through the list of inodes in the FS that need
  320. * defragging
  321. */
  322. int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
  323. {
  324. struct inode_defrag *defrag;
  325. u64 first_ino = 0;
  326. u64 root_objectid = 0;
  327. atomic_inc(&fs_info->defrag_running);
  328. while (1) {
  329. /* Pause the auto defragger. */
  330. if (test_bit(BTRFS_FS_STATE_REMOUNTING,
  331. &fs_info->fs_state))
  332. break;
  333. if (!__need_auto_defrag(fs_info->tree_root))
  334. break;
  335. /* find an inode to defrag */
  336. defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
  337. first_ino);
  338. if (!defrag) {
  339. if (root_objectid || first_ino) {
  340. root_objectid = 0;
  341. first_ino = 0;
  342. continue;
  343. } else {
  344. break;
  345. }
  346. }
  347. first_ino = defrag->ino + 1;
  348. root_objectid = defrag->root;
  349. __btrfs_run_defrag_inode(fs_info, defrag);
  350. }
  351. atomic_dec(&fs_info->defrag_running);
  352. /*
  353. * during unmount, we use the transaction_wait queue to
  354. * wait for the defragger to stop
  355. */
  356. wake_up(&fs_info->transaction_wait);
  357. return 0;
  358. }
  359. /* simple helper to fault in pages and copy. This should go away
  360. * and be replaced with calls into generic code.
  361. */
  362. static noinline int btrfs_copy_from_user(loff_t pos, size_t write_bytes,
  363. struct page **prepared_pages,
  364. struct iov_iter *i)
  365. {
  366. size_t copied = 0;
  367. size_t total_copied = 0;
  368. int pg = 0;
  369. int offset = pos & (PAGE_SIZE - 1);
  370. while (write_bytes > 0) {
  371. size_t count = min_t(size_t,
  372. PAGE_SIZE - offset, write_bytes);
  373. struct page *page = prepared_pages[pg];
  374. /*
  375. * Copy data from userspace to the current page
  376. */
  377. copied = iov_iter_copy_from_user_atomic(page, i, offset, count);
  378. /* Flush processor's dcache for this page */
  379. flush_dcache_page(page);
  380. /*
  381. * if we get a partial write, we can end up with
  382. * partially up to date pages. These add
  383. * a lot of complexity, so make sure they don't
  384. * happen by forcing this copy to be retried.
  385. *
  386. * The rest of the btrfs_file_write code will fall
  387. * back to page at a time copies after we return 0.
  388. */
  389. if (!PageUptodate(page) && copied < count)
  390. copied = 0;
  391. iov_iter_advance(i, copied);
  392. write_bytes -= copied;
  393. total_copied += copied;
  394. /* Return to btrfs_file_write_iter to fault page */
  395. if (unlikely(copied == 0))
  396. break;
  397. if (copied < PAGE_SIZE - offset) {
  398. offset += copied;
  399. } else {
  400. pg++;
  401. offset = 0;
  402. }
  403. }
  404. return total_copied;
  405. }
  406. /*
  407. * unlocks pages after btrfs_file_write is done with them
  408. */
  409. static void btrfs_drop_pages(struct page **pages, size_t num_pages)
  410. {
  411. size_t i;
  412. for (i = 0; i < num_pages; i++) {
  413. /* page checked is some magic around finding pages that
  414. * have been modified without going through btrfs_set_page_dirty
  415. * clear it here. There should be no need to mark the pages
  416. * accessed as prepare_pages should have marked them accessed
  417. * in prepare_pages via find_or_create_page()
  418. */
  419. ClearPageChecked(pages[i]);
  420. unlock_page(pages[i]);
  421. put_page(pages[i]);
  422. }
  423. }
  424. /*
  425. * after copy_from_user, pages need to be dirtied and we need to make
  426. * sure holes are created between the current EOF and the start of
  427. * any next extents (if required).
  428. *
  429. * this also makes the decision about creating an inline extent vs
  430. * doing real data extents, marking pages dirty and delalloc as required.
  431. */
  432. int btrfs_dirty_pages(struct btrfs_root *root, struct inode *inode,
  433. struct page **pages, size_t num_pages,
  434. loff_t pos, size_t write_bytes,
  435. struct extent_state **cached)
  436. {
  437. int err = 0;
  438. int i;
  439. u64 num_bytes;
  440. u64 start_pos;
  441. u64 end_of_last_block;
  442. u64 end_pos = pos + write_bytes;
  443. loff_t isize = i_size_read(inode);
  444. start_pos = pos & ~((u64)root->sectorsize - 1);
  445. num_bytes = round_up(write_bytes + pos - start_pos, root->sectorsize);
  446. end_of_last_block = start_pos + num_bytes - 1;
  447. err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
  448. cached);
  449. if (err)
  450. return err;
  451. for (i = 0; i < num_pages; i++) {
  452. struct page *p = pages[i];
  453. SetPageUptodate(p);
  454. ClearPageChecked(p);
  455. set_page_dirty(p);
  456. }
  457. /*
  458. * we've only changed i_size in ram, and we haven't updated
  459. * the disk i_size. There is no need to log the inode
  460. * at this time.
  461. */
  462. if (end_pos > isize)
  463. i_size_write(inode, end_pos);
  464. return 0;
  465. }
  466. /*
  467. * this drops all the extents in the cache that intersect the range
  468. * [start, end]. Existing extents are split as required.
  469. */
  470. void btrfs_drop_extent_cache(struct inode *inode, u64 start, u64 end,
  471. int skip_pinned)
  472. {
  473. struct extent_map *em;
  474. struct extent_map *split = NULL;
  475. struct extent_map *split2 = NULL;
  476. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  477. u64 len = end - start + 1;
  478. u64 gen;
  479. int ret;
  480. int testend = 1;
  481. unsigned long flags;
  482. int compressed = 0;
  483. bool modified;
  484. WARN_ON(end < start);
  485. if (end == (u64)-1) {
  486. len = (u64)-1;
  487. testend = 0;
  488. }
  489. while (1) {
  490. int no_splits = 0;
  491. modified = false;
  492. if (!split)
  493. split = alloc_extent_map();
  494. if (!split2)
  495. split2 = alloc_extent_map();
  496. if (!split || !split2)
  497. no_splits = 1;
  498. write_lock(&em_tree->lock);
  499. em = lookup_extent_mapping(em_tree, start, len);
  500. if (!em) {
  501. write_unlock(&em_tree->lock);
  502. break;
  503. }
  504. flags = em->flags;
  505. gen = em->generation;
  506. if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
  507. if (testend && em->start + em->len >= start + len) {
  508. free_extent_map(em);
  509. write_unlock(&em_tree->lock);
  510. break;
  511. }
  512. start = em->start + em->len;
  513. if (testend)
  514. len = start + len - (em->start + em->len);
  515. free_extent_map(em);
  516. write_unlock(&em_tree->lock);
  517. continue;
  518. }
  519. compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
  520. clear_bit(EXTENT_FLAG_PINNED, &em->flags);
  521. clear_bit(EXTENT_FLAG_LOGGING, &flags);
  522. modified = !list_empty(&em->list);
  523. if (no_splits)
  524. goto next;
  525. if (em->start < start) {
  526. split->start = em->start;
  527. split->len = start - em->start;
  528. if (em->block_start < EXTENT_MAP_LAST_BYTE) {
  529. split->orig_start = em->orig_start;
  530. split->block_start = em->block_start;
  531. if (compressed)
  532. split->block_len = em->block_len;
  533. else
  534. split->block_len = split->len;
  535. split->orig_block_len = max(split->block_len,
  536. em->orig_block_len);
  537. split->ram_bytes = em->ram_bytes;
  538. } else {
  539. split->orig_start = split->start;
  540. split->block_len = 0;
  541. split->block_start = em->block_start;
  542. split->orig_block_len = 0;
  543. split->ram_bytes = split->len;
  544. }
  545. split->generation = gen;
  546. split->bdev = em->bdev;
  547. split->flags = flags;
  548. split->compress_type = em->compress_type;
  549. replace_extent_mapping(em_tree, em, split, modified);
  550. free_extent_map(split);
  551. split = split2;
  552. split2 = NULL;
  553. }
  554. if (testend && em->start + em->len > start + len) {
  555. u64 diff = start + len - em->start;
  556. split->start = start + len;
  557. split->len = em->start + em->len - (start + len);
  558. split->bdev = em->bdev;
  559. split->flags = flags;
  560. split->compress_type = em->compress_type;
  561. split->generation = gen;
  562. if (em->block_start < EXTENT_MAP_LAST_BYTE) {
  563. split->orig_block_len = max(em->block_len,
  564. em->orig_block_len);
  565. split->ram_bytes = em->ram_bytes;
  566. if (compressed) {
  567. split->block_len = em->block_len;
  568. split->block_start = em->block_start;
  569. split->orig_start = em->orig_start;
  570. } else {
  571. split->block_len = split->len;
  572. split->block_start = em->block_start
  573. + diff;
  574. split->orig_start = em->orig_start;
  575. }
  576. } else {
  577. split->ram_bytes = split->len;
  578. split->orig_start = split->start;
  579. split->block_len = 0;
  580. split->block_start = em->block_start;
  581. split->orig_block_len = 0;
  582. }
  583. if (extent_map_in_tree(em)) {
  584. replace_extent_mapping(em_tree, em, split,
  585. modified);
  586. } else {
  587. ret = add_extent_mapping(em_tree, split,
  588. modified);
  589. ASSERT(ret == 0); /* Logic error */
  590. }
  591. free_extent_map(split);
  592. split = NULL;
  593. }
  594. next:
  595. if (extent_map_in_tree(em))
  596. remove_extent_mapping(em_tree, em);
  597. write_unlock(&em_tree->lock);
  598. /* once for us */
  599. free_extent_map(em);
  600. /* once for the tree*/
  601. free_extent_map(em);
  602. }
  603. if (split)
  604. free_extent_map(split);
  605. if (split2)
  606. free_extent_map(split2);
  607. }
  608. /*
  609. * this is very complex, but the basic idea is to drop all extents
  610. * in the range start - end. hint_block is filled in with a block number
  611. * that would be a good hint to the block allocator for this file.
  612. *
  613. * If an extent intersects the range but is not entirely inside the range
  614. * it is either truncated or split. Anything entirely inside the range
  615. * is deleted from the tree.
  616. */
  617. int __btrfs_drop_extents(struct btrfs_trans_handle *trans,
  618. struct btrfs_root *root, struct inode *inode,
  619. struct btrfs_path *path, u64 start, u64 end,
  620. u64 *drop_end, int drop_cache,
  621. int replace_extent,
  622. u32 extent_item_size,
  623. int *key_inserted)
  624. {
  625. struct extent_buffer *leaf;
  626. struct btrfs_file_extent_item *fi;
  627. struct btrfs_key key;
  628. struct btrfs_key new_key;
  629. u64 ino = btrfs_ino(inode);
  630. u64 search_start = start;
  631. u64 disk_bytenr = 0;
  632. u64 num_bytes = 0;
  633. u64 extent_offset = 0;
  634. u64 extent_end = 0;
  635. int del_nr = 0;
  636. int del_slot = 0;
  637. int extent_type;
  638. int recow;
  639. int ret;
  640. int modify_tree = -1;
  641. int update_refs;
  642. int found = 0;
  643. int leafs_visited = 0;
  644. if (drop_cache)
  645. btrfs_drop_extent_cache(inode, start, end - 1, 0);
  646. if (start >= BTRFS_I(inode)->disk_i_size && !replace_extent)
  647. modify_tree = 0;
  648. update_refs = (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
  649. root == root->fs_info->tree_root);
  650. while (1) {
  651. recow = 0;
  652. ret = btrfs_lookup_file_extent(trans, root, path, ino,
  653. search_start, modify_tree);
  654. if (ret < 0)
  655. break;
  656. if (ret > 0 && path->slots[0] > 0 && search_start == start) {
  657. leaf = path->nodes[0];
  658. btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
  659. if (key.objectid == ino &&
  660. key.type == BTRFS_EXTENT_DATA_KEY)
  661. path->slots[0]--;
  662. }
  663. ret = 0;
  664. leafs_visited++;
  665. next_slot:
  666. leaf = path->nodes[0];
  667. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  668. BUG_ON(del_nr > 0);
  669. ret = btrfs_next_leaf(root, path);
  670. if (ret < 0)
  671. break;
  672. if (ret > 0) {
  673. ret = 0;
  674. break;
  675. }
  676. leafs_visited++;
  677. leaf = path->nodes[0];
  678. recow = 1;
  679. }
  680. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  681. if (key.objectid > ino)
  682. break;
  683. if (WARN_ON_ONCE(key.objectid < ino) ||
  684. key.type < BTRFS_EXTENT_DATA_KEY) {
  685. ASSERT(del_nr == 0);
  686. path->slots[0]++;
  687. goto next_slot;
  688. }
  689. if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
  690. break;
  691. fi = btrfs_item_ptr(leaf, path->slots[0],
  692. struct btrfs_file_extent_item);
  693. extent_type = btrfs_file_extent_type(leaf, fi);
  694. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  695. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  696. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  697. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  698. extent_offset = btrfs_file_extent_offset(leaf, fi);
  699. extent_end = key.offset +
  700. btrfs_file_extent_num_bytes(leaf, fi);
  701. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  702. extent_end = key.offset +
  703. btrfs_file_extent_inline_len(leaf,
  704. path->slots[0], fi);
  705. } else {
  706. /* can't happen */
  707. BUG();
  708. }
  709. /*
  710. * Don't skip extent items representing 0 byte lengths. They
  711. * used to be created (bug) if while punching holes we hit
  712. * -ENOSPC condition. So if we find one here, just ensure we
  713. * delete it, otherwise we would insert a new file extent item
  714. * with the same key (offset) as that 0 bytes length file
  715. * extent item in the call to setup_items_for_insert() later
  716. * in this function.
  717. */
  718. if (extent_end == key.offset && extent_end >= search_start)
  719. goto delete_extent_item;
  720. if (extent_end <= search_start) {
  721. path->slots[0]++;
  722. goto next_slot;
  723. }
  724. found = 1;
  725. search_start = max(key.offset, start);
  726. if (recow || !modify_tree) {
  727. modify_tree = -1;
  728. btrfs_release_path(path);
  729. continue;
  730. }
  731. /*
  732. * | - range to drop - |
  733. * | -------- extent -------- |
  734. */
  735. if (start > key.offset && end < extent_end) {
  736. BUG_ON(del_nr > 0);
  737. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  738. ret = -EOPNOTSUPP;
  739. break;
  740. }
  741. memcpy(&new_key, &key, sizeof(new_key));
  742. new_key.offset = start;
  743. ret = btrfs_duplicate_item(trans, root, path,
  744. &new_key);
  745. if (ret == -EAGAIN) {
  746. btrfs_release_path(path);
  747. continue;
  748. }
  749. if (ret < 0)
  750. break;
  751. leaf = path->nodes[0];
  752. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  753. struct btrfs_file_extent_item);
  754. btrfs_set_file_extent_num_bytes(leaf, fi,
  755. start - key.offset);
  756. fi = btrfs_item_ptr(leaf, path->slots[0],
  757. struct btrfs_file_extent_item);
  758. extent_offset += start - key.offset;
  759. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  760. btrfs_set_file_extent_num_bytes(leaf, fi,
  761. extent_end - start);
  762. btrfs_mark_buffer_dirty(leaf);
  763. if (update_refs && disk_bytenr > 0) {
  764. ret = btrfs_inc_extent_ref(trans, root,
  765. disk_bytenr, num_bytes, 0,
  766. root->root_key.objectid,
  767. new_key.objectid,
  768. start - extent_offset);
  769. BUG_ON(ret); /* -ENOMEM */
  770. }
  771. key.offset = start;
  772. }
  773. /*
  774. * | ---- range to drop ----- |
  775. * | -------- extent -------- |
  776. */
  777. if (start <= key.offset && end < extent_end) {
  778. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  779. ret = -EOPNOTSUPP;
  780. break;
  781. }
  782. memcpy(&new_key, &key, sizeof(new_key));
  783. new_key.offset = end;
  784. btrfs_set_item_key_safe(root->fs_info, path, &new_key);
  785. extent_offset += end - key.offset;
  786. btrfs_set_file_extent_offset(leaf, fi, extent_offset);
  787. btrfs_set_file_extent_num_bytes(leaf, fi,
  788. extent_end - end);
  789. btrfs_mark_buffer_dirty(leaf);
  790. if (update_refs && disk_bytenr > 0)
  791. inode_sub_bytes(inode, end - key.offset);
  792. break;
  793. }
  794. search_start = extent_end;
  795. /*
  796. * | ---- range to drop ----- |
  797. * | -------- extent -------- |
  798. */
  799. if (start > key.offset && end >= extent_end) {
  800. BUG_ON(del_nr > 0);
  801. if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  802. ret = -EOPNOTSUPP;
  803. break;
  804. }
  805. btrfs_set_file_extent_num_bytes(leaf, fi,
  806. start - key.offset);
  807. btrfs_mark_buffer_dirty(leaf);
  808. if (update_refs && disk_bytenr > 0)
  809. inode_sub_bytes(inode, extent_end - start);
  810. if (end == extent_end)
  811. break;
  812. path->slots[0]++;
  813. goto next_slot;
  814. }
  815. /*
  816. * | ---- range to drop ----- |
  817. * | ------ extent ------ |
  818. */
  819. if (start <= key.offset && end >= extent_end) {
  820. delete_extent_item:
  821. if (del_nr == 0) {
  822. del_slot = path->slots[0];
  823. del_nr = 1;
  824. } else {
  825. BUG_ON(del_slot + del_nr != path->slots[0]);
  826. del_nr++;
  827. }
  828. if (update_refs &&
  829. extent_type == BTRFS_FILE_EXTENT_INLINE) {
  830. inode_sub_bytes(inode,
  831. extent_end - key.offset);
  832. extent_end = ALIGN(extent_end,
  833. root->sectorsize);
  834. } else if (update_refs && disk_bytenr > 0) {
  835. ret = btrfs_free_extent(trans, root,
  836. disk_bytenr, num_bytes, 0,
  837. root->root_key.objectid,
  838. key.objectid, key.offset -
  839. extent_offset);
  840. BUG_ON(ret); /* -ENOMEM */
  841. inode_sub_bytes(inode,
  842. extent_end - key.offset);
  843. }
  844. if (end == extent_end)
  845. break;
  846. if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
  847. path->slots[0]++;
  848. goto next_slot;
  849. }
  850. ret = btrfs_del_items(trans, root, path, del_slot,
  851. del_nr);
  852. if (ret) {
  853. btrfs_abort_transaction(trans, root, ret);
  854. break;
  855. }
  856. del_nr = 0;
  857. del_slot = 0;
  858. btrfs_release_path(path);
  859. continue;
  860. }
  861. BUG_ON(1);
  862. }
  863. if (!ret && del_nr > 0) {
  864. /*
  865. * Set path->slots[0] to first slot, so that after the delete
  866. * if items are move off from our leaf to its immediate left or
  867. * right neighbor leafs, we end up with a correct and adjusted
  868. * path->slots[0] for our insertion (if replace_extent != 0).
  869. */
  870. path->slots[0] = del_slot;
  871. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  872. if (ret)
  873. btrfs_abort_transaction(trans, root, ret);
  874. }
  875. leaf = path->nodes[0];
  876. /*
  877. * If btrfs_del_items() was called, it might have deleted a leaf, in
  878. * which case it unlocked our path, so check path->locks[0] matches a
  879. * write lock.
  880. */
  881. if (!ret && replace_extent && leafs_visited == 1 &&
  882. (path->locks[0] == BTRFS_WRITE_LOCK_BLOCKING ||
  883. path->locks[0] == BTRFS_WRITE_LOCK) &&
  884. btrfs_leaf_free_space(root, leaf) >=
  885. sizeof(struct btrfs_item) + extent_item_size) {
  886. key.objectid = ino;
  887. key.type = BTRFS_EXTENT_DATA_KEY;
  888. key.offset = start;
  889. if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
  890. struct btrfs_key slot_key;
  891. btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
  892. if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
  893. path->slots[0]++;
  894. }
  895. setup_items_for_insert(root, path, &key,
  896. &extent_item_size,
  897. extent_item_size,
  898. sizeof(struct btrfs_item) +
  899. extent_item_size, 1);
  900. *key_inserted = 1;
  901. }
  902. if (!replace_extent || !(*key_inserted))
  903. btrfs_release_path(path);
  904. if (drop_end)
  905. *drop_end = found ? min(end, extent_end) : end;
  906. return ret;
  907. }
  908. int btrfs_drop_extents(struct btrfs_trans_handle *trans,
  909. struct btrfs_root *root, struct inode *inode, u64 start,
  910. u64 end, int drop_cache)
  911. {
  912. struct btrfs_path *path;
  913. int ret;
  914. path = btrfs_alloc_path();
  915. if (!path)
  916. return -ENOMEM;
  917. ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
  918. drop_cache, 0, 0, NULL);
  919. btrfs_free_path(path);
  920. return ret;
  921. }
  922. static int extent_mergeable(struct extent_buffer *leaf, int slot,
  923. u64 objectid, u64 bytenr, u64 orig_offset,
  924. u64 *start, u64 *end)
  925. {
  926. struct btrfs_file_extent_item *fi;
  927. struct btrfs_key key;
  928. u64 extent_end;
  929. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  930. return 0;
  931. btrfs_item_key_to_cpu(leaf, &key, slot);
  932. if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
  933. return 0;
  934. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  935. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
  936. btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
  937. btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
  938. btrfs_file_extent_compression(leaf, fi) ||
  939. btrfs_file_extent_encryption(leaf, fi) ||
  940. btrfs_file_extent_other_encoding(leaf, fi))
  941. return 0;
  942. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  943. if ((*start && *start != key.offset) || (*end && *end != extent_end))
  944. return 0;
  945. *start = key.offset;
  946. *end = extent_end;
  947. return 1;
  948. }
  949. /*
  950. * Mark extent in the range start - end as written.
  951. *
  952. * This changes extent type from 'pre-allocated' to 'regular'. If only
  953. * part of extent is marked as written, the extent will be split into
  954. * two or three.
  955. */
  956. int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
  957. struct inode *inode, u64 start, u64 end)
  958. {
  959. struct btrfs_root *root = BTRFS_I(inode)->root;
  960. struct extent_buffer *leaf;
  961. struct btrfs_path *path;
  962. struct btrfs_file_extent_item *fi;
  963. struct btrfs_key key;
  964. struct btrfs_key new_key;
  965. u64 bytenr;
  966. u64 num_bytes;
  967. u64 extent_end;
  968. u64 orig_offset;
  969. u64 other_start;
  970. u64 other_end;
  971. u64 split;
  972. int del_nr = 0;
  973. int del_slot = 0;
  974. int recow;
  975. int ret;
  976. u64 ino = btrfs_ino(inode);
  977. path = btrfs_alloc_path();
  978. if (!path)
  979. return -ENOMEM;
  980. again:
  981. recow = 0;
  982. split = start;
  983. key.objectid = ino;
  984. key.type = BTRFS_EXTENT_DATA_KEY;
  985. key.offset = split;
  986. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  987. if (ret < 0)
  988. goto out;
  989. if (ret > 0 && path->slots[0] > 0)
  990. path->slots[0]--;
  991. leaf = path->nodes[0];
  992. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  993. BUG_ON(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY);
  994. fi = btrfs_item_ptr(leaf, path->slots[0],
  995. struct btrfs_file_extent_item);
  996. BUG_ON(btrfs_file_extent_type(leaf, fi) !=
  997. BTRFS_FILE_EXTENT_PREALLOC);
  998. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  999. BUG_ON(key.offset > start || extent_end < end);
  1000. bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  1001. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  1002. orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
  1003. memcpy(&new_key, &key, sizeof(new_key));
  1004. if (start == key.offset && end < extent_end) {
  1005. other_start = 0;
  1006. other_end = start;
  1007. if (extent_mergeable(leaf, path->slots[0] - 1,
  1008. ino, bytenr, orig_offset,
  1009. &other_start, &other_end)) {
  1010. new_key.offset = end;
  1011. btrfs_set_item_key_safe(root->fs_info, path, &new_key);
  1012. fi = btrfs_item_ptr(leaf, path->slots[0],
  1013. struct btrfs_file_extent_item);
  1014. btrfs_set_file_extent_generation(leaf, fi,
  1015. trans->transid);
  1016. btrfs_set_file_extent_num_bytes(leaf, fi,
  1017. extent_end - end);
  1018. btrfs_set_file_extent_offset(leaf, fi,
  1019. end - orig_offset);
  1020. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  1021. struct btrfs_file_extent_item);
  1022. btrfs_set_file_extent_generation(leaf, fi,
  1023. trans->transid);
  1024. btrfs_set_file_extent_num_bytes(leaf, fi,
  1025. end - other_start);
  1026. btrfs_mark_buffer_dirty(leaf);
  1027. goto out;
  1028. }
  1029. }
  1030. if (start > key.offset && end == extent_end) {
  1031. other_start = end;
  1032. other_end = 0;
  1033. if (extent_mergeable(leaf, path->slots[0] + 1,
  1034. ino, bytenr, orig_offset,
  1035. &other_start, &other_end)) {
  1036. fi = btrfs_item_ptr(leaf, path->slots[0],
  1037. struct btrfs_file_extent_item);
  1038. btrfs_set_file_extent_num_bytes(leaf, fi,
  1039. start - key.offset);
  1040. btrfs_set_file_extent_generation(leaf, fi,
  1041. trans->transid);
  1042. path->slots[0]++;
  1043. new_key.offset = start;
  1044. btrfs_set_item_key_safe(root->fs_info, path, &new_key);
  1045. fi = btrfs_item_ptr(leaf, path->slots[0],
  1046. struct btrfs_file_extent_item);
  1047. btrfs_set_file_extent_generation(leaf, fi,
  1048. trans->transid);
  1049. btrfs_set_file_extent_num_bytes(leaf, fi,
  1050. other_end - start);
  1051. btrfs_set_file_extent_offset(leaf, fi,
  1052. start - orig_offset);
  1053. btrfs_mark_buffer_dirty(leaf);
  1054. goto out;
  1055. }
  1056. }
  1057. while (start > key.offset || end < extent_end) {
  1058. if (key.offset == start)
  1059. split = end;
  1060. new_key.offset = split;
  1061. ret = btrfs_duplicate_item(trans, root, path, &new_key);
  1062. if (ret == -EAGAIN) {
  1063. btrfs_release_path(path);
  1064. goto again;
  1065. }
  1066. if (ret < 0) {
  1067. btrfs_abort_transaction(trans, root, ret);
  1068. goto out;
  1069. }
  1070. leaf = path->nodes[0];
  1071. fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
  1072. struct btrfs_file_extent_item);
  1073. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1074. btrfs_set_file_extent_num_bytes(leaf, fi,
  1075. split - key.offset);
  1076. fi = btrfs_item_ptr(leaf, path->slots[0],
  1077. struct btrfs_file_extent_item);
  1078. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1079. btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
  1080. btrfs_set_file_extent_num_bytes(leaf, fi,
  1081. extent_end - split);
  1082. btrfs_mark_buffer_dirty(leaf);
  1083. ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0,
  1084. root->root_key.objectid,
  1085. ino, orig_offset);
  1086. BUG_ON(ret); /* -ENOMEM */
  1087. if (split == start) {
  1088. key.offset = start;
  1089. } else {
  1090. BUG_ON(start != key.offset);
  1091. path->slots[0]--;
  1092. extent_end = end;
  1093. }
  1094. recow = 1;
  1095. }
  1096. other_start = end;
  1097. other_end = 0;
  1098. if (extent_mergeable(leaf, path->slots[0] + 1,
  1099. ino, bytenr, orig_offset,
  1100. &other_start, &other_end)) {
  1101. if (recow) {
  1102. btrfs_release_path(path);
  1103. goto again;
  1104. }
  1105. extent_end = other_end;
  1106. del_slot = path->slots[0] + 1;
  1107. del_nr++;
  1108. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  1109. 0, root->root_key.objectid,
  1110. ino, orig_offset);
  1111. BUG_ON(ret); /* -ENOMEM */
  1112. }
  1113. other_start = 0;
  1114. other_end = start;
  1115. if (extent_mergeable(leaf, path->slots[0] - 1,
  1116. ino, bytenr, orig_offset,
  1117. &other_start, &other_end)) {
  1118. if (recow) {
  1119. btrfs_release_path(path);
  1120. goto again;
  1121. }
  1122. key.offset = other_start;
  1123. del_slot = path->slots[0];
  1124. del_nr++;
  1125. ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
  1126. 0, root->root_key.objectid,
  1127. ino, orig_offset);
  1128. BUG_ON(ret); /* -ENOMEM */
  1129. }
  1130. if (del_nr == 0) {
  1131. fi = btrfs_item_ptr(leaf, path->slots[0],
  1132. struct btrfs_file_extent_item);
  1133. btrfs_set_file_extent_type(leaf, fi,
  1134. BTRFS_FILE_EXTENT_REG);
  1135. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1136. btrfs_mark_buffer_dirty(leaf);
  1137. } else {
  1138. fi = btrfs_item_ptr(leaf, del_slot - 1,
  1139. struct btrfs_file_extent_item);
  1140. btrfs_set_file_extent_type(leaf, fi,
  1141. BTRFS_FILE_EXTENT_REG);
  1142. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  1143. btrfs_set_file_extent_num_bytes(leaf, fi,
  1144. extent_end - key.offset);
  1145. btrfs_mark_buffer_dirty(leaf);
  1146. ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
  1147. if (ret < 0) {
  1148. btrfs_abort_transaction(trans, root, ret);
  1149. goto out;
  1150. }
  1151. }
  1152. out:
  1153. btrfs_free_path(path);
  1154. return 0;
  1155. }
  1156. /*
  1157. * on error we return an unlocked page and the error value
  1158. * on success we return a locked page and 0
  1159. */
  1160. static int prepare_uptodate_page(struct inode *inode,
  1161. struct page *page, u64 pos,
  1162. bool force_uptodate)
  1163. {
  1164. int ret = 0;
  1165. if (((pos & (PAGE_SIZE - 1)) || force_uptodate) &&
  1166. !PageUptodate(page)) {
  1167. ret = btrfs_readpage(NULL, page);
  1168. if (ret)
  1169. return ret;
  1170. lock_page(page);
  1171. if (!PageUptodate(page)) {
  1172. unlock_page(page);
  1173. return -EIO;
  1174. }
  1175. if (page->mapping != inode->i_mapping) {
  1176. unlock_page(page);
  1177. return -EAGAIN;
  1178. }
  1179. }
  1180. return 0;
  1181. }
  1182. /*
  1183. * this just gets pages into the page cache and locks them down.
  1184. */
  1185. static noinline int prepare_pages(struct inode *inode, struct page **pages,
  1186. size_t num_pages, loff_t pos,
  1187. size_t write_bytes, bool force_uptodate)
  1188. {
  1189. int i;
  1190. unsigned long index = pos >> PAGE_SHIFT;
  1191. gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
  1192. int err = 0;
  1193. int faili;
  1194. for (i = 0; i < num_pages; i++) {
  1195. again:
  1196. pages[i] = find_or_create_page(inode->i_mapping, index + i,
  1197. mask | __GFP_WRITE);
  1198. if (!pages[i]) {
  1199. faili = i - 1;
  1200. err = -ENOMEM;
  1201. goto fail;
  1202. }
  1203. if (i == 0)
  1204. err = prepare_uptodate_page(inode, pages[i], pos,
  1205. force_uptodate);
  1206. if (!err && i == num_pages - 1)
  1207. err = prepare_uptodate_page(inode, pages[i],
  1208. pos + write_bytes, false);
  1209. if (err) {
  1210. put_page(pages[i]);
  1211. if (err == -EAGAIN) {
  1212. err = 0;
  1213. goto again;
  1214. }
  1215. faili = i - 1;
  1216. goto fail;
  1217. }
  1218. wait_on_page_writeback(pages[i]);
  1219. }
  1220. return 0;
  1221. fail:
  1222. while (faili >= 0) {
  1223. unlock_page(pages[faili]);
  1224. put_page(pages[faili]);
  1225. faili--;
  1226. }
  1227. return err;
  1228. }
  1229. /*
  1230. * This function locks the extent and properly waits for data=ordered extents
  1231. * to finish before allowing the pages to be modified if need.
  1232. *
  1233. * The return value:
  1234. * 1 - the extent is locked
  1235. * 0 - the extent is not locked, and everything is OK
  1236. * -EAGAIN - need re-prepare the pages
  1237. * the other < 0 number - Something wrong happens
  1238. */
  1239. static noinline int
  1240. lock_and_cleanup_extent_if_need(struct inode *inode, struct page **pages,
  1241. size_t num_pages, loff_t pos,
  1242. size_t write_bytes,
  1243. u64 *lockstart, u64 *lockend,
  1244. struct extent_state **cached_state)
  1245. {
  1246. struct btrfs_root *root = BTRFS_I(inode)->root;
  1247. u64 start_pos;
  1248. u64 last_pos;
  1249. int i;
  1250. int ret = 0;
  1251. start_pos = round_down(pos, root->sectorsize);
  1252. last_pos = start_pos
  1253. + round_up(pos + write_bytes - start_pos, root->sectorsize) - 1;
  1254. if (start_pos < inode->i_size) {
  1255. struct btrfs_ordered_extent *ordered;
  1256. lock_extent_bits(&BTRFS_I(inode)->io_tree,
  1257. start_pos, last_pos, cached_state);
  1258. ordered = btrfs_lookup_ordered_range(inode, start_pos,
  1259. last_pos - start_pos + 1);
  1260. if (ordered &&
  1261. ordered->file_offset + ordered->len > start_pos &&
  1262. ordered->file_offset <= last_pos) {
  1263. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1264. start_pos, last_pos,
  1265. cached_state, GFP_NOFS);
  1266. for (i = 0; i < num_pages; i++) {
  1267. unlock_page(pages[i]);
  1268. put_page(pages[i]);
  1269. }
  1270. btrfs_start_ordered_extent(inode, ordered, 1);
  1271. btrfs_put_ordered_extent(ordered);
  1272. return -EAGAIN;
  1273. }
  1274. if (ordered)
  1275. btrfs_put_ordered_extent(ordered);
  1276. clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos,
  1277. last_pos, EXTENT_DIRTY | EXTENT_DELALLOC |
  1278. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  1279. 0, 0, cached_state, GFP_NOFS);
  1280. *lockstart = start_pos;
  1281. *lockend = last_pos;
  1282. ret = 1;
  1283. }
  1284. for (i = 0; i < num_pages; i++) {
  1285. if (clear_page_dirty_for_io(pages[i]))
  1286. account_page_redirty(pages[i]);
  1287. set_page_extent_mapped(pages[i]);
  1288. WARN_ON(!PageLocked(pages[i]));
  1289. }
  1290. return ret;
  1291. }
  1292. static noinline int check_can_nocow(struct inode *inode, loff_t pos,
  1293. size_t *write_bytes)
  1294. {
  1295. struct btrfs_root *root = BTRFS_I(inode)->root;
  1296. struct btrfs_ordered_extent *ordered;
  1297. u64 lockstart, lockend;
  1298. u64 num_bytes;
  1299. int ret;
  1300. ret = btrfs_start_write_no_snapshoting(root);
  1301. if (!ret)
  1302. return -ENOSPC;
  1303. lockstart = round_down(pos, root->sectorsize);
  1304. lockend = round_up(pos + *write_bytes, root->sectorsize) - 1;
  1305. while (1) {
  1306. lock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1307. ordered = btrfs_lookup_ordered_range(inode, lockstart,
  1308. lockend - lockstart + 1);
  1309. if (!ordered) {
  1310. break;
  1311. }
  1312. unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1313. btrfs_start_ordered_extent(inode, ordered, 1);
  1314. btrfs_put_ordered_extent(ordered);
  1315. }
  1316. num_bytes = lockend - lockstart + 1;
  1317. ret = can_nocow_extent(inode, lockstart, &num_bytes, NULL, NULL, NULL);
  1318. if (ret <= 0) {
  1319. ret = 0;
  1320. btrfs_end_write_no_snapshoting(root);
  1321. } else {
  1322. *write_bytes = min_t(size_t, *write_bytes ,
  1323. num_bytes - pos + lockstart);
  1324. }
  1325. unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend);
  1326. return ret;
  1327. }
  1328. static noinline ssize_t __btrfs_buffered_write(struct file *file,
  1329. struct iov_iter *i,
  1330. loff_t pos)
  1331. {
  1332. struct inode *inode = file_inode(file);
  1333. struct btrfs_root *root = BTRFS_I(inode)->root;
  1334. struct page **pages = NULL;
  1335. struct extent_state *cached_state = NULL;
  1336. u64 release_bytes = 0;
  1337. u64 lockstart;
  1338. u64 lockend;
  1339. size_t num_written = 0;
  1340. int nrptrs;
  1341. int ret = 0;
  1342. bool only_release_metadata = false;
  1343. bool force_page_uptodate = false;
  1344. bool need_unlock;
  1345. nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE),
  1346. PAGE_SIZE / (sizeof(struct page *)));
  1347. nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
  1348. nrptrs = max(nrptrs, 8);
  1349. pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL);
  1350. if (!pages)
  1351. return -ENOMEM;
  1352. while (iov_iter_count(i) > 0) {
  1353. size_t offset = pos & (PAGE_SIZE - 1);
  1354. size_t sector_offset;
  1355. size_t write_bytes = min(iov_iter_count(i),
  1356. nrptrs * (size_t)PAGE_SIZE -
  1357. offset);
  1358. size_t num_pages = DIV_ROUND_UP(write_bytes + offset,
  1359. PAGE_SIZE);
  1360. size_t reserve_bytes;
  1361. size_t dirty_pages;
  1362. size_t copied;
  1363. size_t dirty_sectors;
  1364. size_t num_sectors;
  1365. WARN_ON(num_pages > nrptrs);
  1366. /*
  1367. * Fault pages before locking them in prepare_pages
  1368. * to avoid recursive lock
  1369. */
  1370. if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
  1371. ret = -EFAULT;
  1372. break;
  1373. }
  1374. sector_offset = pos & (root->sectorsize - 1);
  1375. reserve_bytes = round_up(write_bytes + sector_offset,
  1376. root->sectorsize);
  1377. ret = btrfs_check_data_free_space(inode, pos, write_bytes);
  1378. if (ret < 0) {
  1379. if ((BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW |
  1380. BTRFS_INODE_PREALLOC)) &&
  1381. check_can_nocow(inode, pos, &write_bytes) > 0) {
  1382. /*
  1383. * For nodata cow case, no need to reserve
  1384. * data space.
  1385. */
  1386. only_release_metadata = true;
  1387. /*
  1388. * our prealloc extent may be smaller than
  1389. * write_bytes, so scale down.
  1390. */
  1391. num_pages = DIV_ROUND_UP(write_bytes + offset,
  1392. PAGE_SIZE);
  1393. reserve_bytes = round_up(write_bytes +
  1394. sector_offset,
  1395. root->sectorsize);
  1396. } else {
  1397. break;
  1398. }
  1399. }
  1400. ret = btrfs_delalloc_reserve_metadata(inode, reserve_bytes);
  1401. if (ret) {
  1402. if (!only_release_metadata)
  1403. btrfs_free_reserved_data_space(inode, pos,
  1404. write_bytes);
  1405. else
  1406. btrfs_end_write_no_snapshoting(root);
  1407. break;
  1408. }
  1409. release_bytes = reserve_bytes;
  1410. need_unlock = false;
  1411. again:
  1412. /*
  1413. * This is going to setup the pages array with the number of
  1414. * pages we want, so we don't really need to worry about the
  1415. * contents of pages from loop to loop
  1416. */
  1417. ret = prepare_pages(inode, pages, num_pages,
  1418. pos, write_bytes,
  1419. force_page_uptodate);
  1420. if (ret)
  1421. break;
  1422. ret = lock_and_cleanup_extent_if_need(inode, pages, num_pages,
  1423. pos, write_bytes, &lockstart,
  1424. &lockend, &cached_state);
  1425. if (ret < 0) {
  1426. if (ret == -EAGAIN)
  1427. goto again;
  1428. break;
  1429. } else if (ret > 0) {
  1430. need_unlock = true;
  1431. ret = 0;
  1432. }
  1433. copied = btrfs_copy_from_user(pos, write_bytes, pages, i);
  1434. num_sectors = BTRFS_BYTES_TO_BLKS(root->fs_info,
  1435. reserve_bytes);
  1436. dirty_sectors = round_up(copied + sector_offset,
  1437. root->sectorsize);
  1438. dirty_sectors = BTRFS_BYTES_TO_BLKS(root->fs_info,
  1439. dirty_sectors);
  1440. /*
  1441. * if we have trouble faulting in the pages, fall
  1442. * back to one page at a time
  1443. */
  1444. if (copied < write_bytes)
  1445. nrptrs = 1;
  1446. if (copied == 0) {
  1447. force_page_uptodate = true;
  1448. dirty_sectors = 0;
  1449. dirty_pages = 0;
  1450. } else {
  1451. force_page_uptodate = false;
  1452. dirty_pages = DIV_ROUND_UP(copied + offset,
  1453. PAGE_SIZE);
  1454. }
  1455. /*
  1456. * If we had a short copy we need to release the excess delaloc
  1457. * bytes we reserved. We need to increment outstanding_extents
  1458. * because btrfs_delalloc_release_space and
  1459. * btrfs_delalloc_release_metadata will decrement it, but
  1460. * we still have an outstanding extent for the chunk we actually
  1461. * managed to copy.
  1462. */
  1463. if (num_sectors > dirty_sectors) {
  1464. /* release everything except the sectors we dirtied */
  1465. release_bytes -= dirty_sectors <<
  1466. root->fs_info->sb->s_blocksize_bits;
  1467. if (copied > 0) {
  1468. spin_lock(&BTRFS_I(inode)->lock);
  1469. BTRFS_I(inode)->outstanding_extents++;
  1470. spin_unlock(&BTRFS_I(inode)->lock);
  1471. }
  1472. if (only_release_metadata) {
  1473. btrfs_delalloc_release_metadata(inode,
  1474. release_bytes);
  1475. } else {
  1476. u64 __pos;
  1477. __pos = round_down(pos, root->sectorsize) +
  1478. (dirty_pages << PAGE_SHIFT);
  1479. btrfs_delalloc_release_space(inode, __pos,
  1480. release_bytes);
  1481. }
  1482. }
  1483. release_bytes = round_up(copied + sector_offset,
  1484. root->sectorsize);
  1485. if (copied > 0)
  1486. ret = btrfs_dirty_pages(root, inode, pages,
  1487. dirty_pages, pos, copied,
  1488. NULL);
  1489. if (need_unlock)
  1490. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  1491. lockstart, lockend, &cached_state,
  1492. GFP_NOFS);
  1493. if (ret) {
  1494. btrfs_drop_pages(pages, num_pages);
  1495. break;
  1496. }
  1497. release_bytes = 0;
  1498. if (only_release_metadata)
  1499. btrfs_end_write_no_snapshoting(root);
  1500. if (only_release_metadata && copied > 0) {
  1501. lockstart = round_down(pos, root->sectorsize);
  1502. lockend = round_up(pos + copied, root->sectorsize) - 1;
  1503. set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
  1504. lockend, EXTENT_NORESERVE, NULL,
  1505. NULL, GFP_NOFS);
  1506. only_release_metadata = false;
  1507. }
  1508. btrfs_drop_pages(pages, num_pages);
  1509. cond_resched();
  1510. balance_dirty_pages_ratelimited(inode->i_mapping);
  1511. if (dirty_pages < (root->nodesize >> PAGE_SHIFT) + 1)
  1512. btrfs_btree_balance_dirty(root);
  1513. pos += copied;
  1514. num_written += copied;
  1515. }
  1516. kfree(pages);
  1517. if (release_bytes) {
  1518. if (only_release_metadata) {
  1519. btrfs_end_write_no_snapshoting(root);
  1520. btrfs_delalloc_release_metadata(inode, release_bytes);
  1521. } else {
  1522. btrfs_delalloc_release_space(inode,
  1523. round_down(pos, root->sectorsize),
  1524. release_bytes);
  1525. }
  1526. }
  1527. return num_written ? num_written : ret;
  1528. }
  1529. static ssize_t __btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
  1530. {
  1531. struct file *file = iocb->ki_filp;
  1532. struct inode *inode = file_inode(file);
  1533. loff_t pos = iocb->ki_pos;
  1534. ssize_t written;
  1535. ssize_t written_buffered;
  1536. loff_t endbyte;
  1537. int err;
  1538. written = generic_file_direct_write(iocb, from);
  1539. if (written < 0 || !iov_iter_count(from))
  1540. return written;
  1541. pos += written;
  1542. written_buffered = __btrfs_buffered_write(file, from, pos);
  1543. if (written_buffered < 0) {
  1544. err = written_buffered;
  1545. goto out;
  1546. }
  1547. /*
  1548. * Ensure all data is persisted. We want the next direct IO read to be
  1549. * able to read what was just written.
  1550. */
  1551. endbyte = pos + written_buffered - 1;
  1552. err = btrfs_fdatawrite_range(inode, pos, endbyte);
  1553. if (err)
  1554. goto out;
  1555. err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
  1556. if (err)
  1557. goto out;
  1558. written += written_buffered;
  1559. iocb->ki_pos = pos + written_buffered;
  1560. invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT,
  1561. endbyte >> PAGE_SHIFT);
  1562. out:
  1563. return written ? written : err;
  1564. }
  1565. static void update_time_for_write(struct inode *inode)
  1566. {
  1567. struct timespec now;
  1568. if (IS_NOCMTIME(inode))
  1569. return;
  1570. now = current_fs_time(inode->i_sb);
  1571. if (!timespec_equal(&inode->i_mtime, &now))
  1572. inode->i_mtime = now;
  1573. if (!timespec_equal(&inode->i_ctime, &now))
  1574. inode->i_ctime = now;
  1575. if (IS_I_VERSION(inode))
  1576. inode_inc_iversion(inode);
  1577. }
  1578. static ssize_t btrfs_file_write_iter(struct kiocb *iocb,
  1579. struct iov_iter *from)
  1580. {
  1581. struct file *file = iocb->ki_filp;
  1582. struct inode *inode = file_inode(file);
  1583. struct btrfs_root *root = BTRFS_I(inode)->root;
  1584. u64 start_pos;
  1585. u64 end_pos;
  1586. ssize_t num_written = 0;
  1587. bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
  1588. ssize_t err;
  1589. loff_t pos;
  1590. size_t count;
  1591. loff_t oldsize;
  1592. int clean_page = 0;
  1593. inode_lock(inode);
  1594. err = generic_write_checks(iocb, from);
  1595. if (err <= 0) {
  1596. inode_unlock(inode);
  1597. return err;
  1598. }
  1599. current->backing_dev_info = inode_to_bdi(inode);
  1600. err = file_remove_privs(file);
  1601. if (err) {
  1602. inode_unlock(inode);
  1603. goto out;
  1604. }
  1605. /*
  1606. * If BTRFS flips readonly due to some impossible error
  1607. * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
  1608. * although we have opened a file as writable, we have
  1609. * to stop this write operation to ensure FS consistency.
  1610. */
  1611. if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
  1612. inode_unlock(inode);
  1613. err = -EROFS;
  1614. goto out;
  1615. }
  1616. /*
  1617. * We reserve space for updating the inode when we reserve space for the
  1618. * extent we are going to write, so we will enospc out there. We don't
  1619. * need to start yet another transaction to update the inode as we will
  1620. * update the inode when we finish writing whatever data we write.
  1621. */
  1622. update_time_for_write(inode);
  1623. pos = iocb->ki_pos;
  1624. count = iov_iter_count(from);
  1625. start_pos = round_down(pos, root->sectorsize);
  1626. oldsize = i_size_read(inode);
  1627. if (start_pos > oldsize) {
  1628. /* Expand hole size to cover write data, preventing empty gap */
  1629. end_pos = round_up(pos + count, root->sectorsize);
  1630. err = btrfs_cont_expand(inode, oldsize, end_pos);
  1631. if (err) {
  1632. inode_unlock(inode);
  1633. goto out;
  1634. }
  1635. if (start_pos > round_up(oldsize, root->sectorsize))
  1636. clean_page = 1;
  1637. }
  1638. if (sync)
  1639. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1640. if (iocb->ki_flags & IOCB_DIRECT) {
  1641. num_written = __btrfs_direct_write(iocb, from);
  1642. } else {
  1643. num_written = __btrfs_buffered_write(file, from, pos);
  1644. if (num_written > 0)
  1645. iocb->ki_pos = pos + num_written;
  1646. if (clean_page)
  1647. pagecache_isize_extended(inode, oldsize,
  1648. i_size_read(inode));
  1649. }
  1650. inode_unlock(inode);
  1651. /*
  1652. * We also have to set last_sub_trans to the current log transid,
  1653. * otherwise subsequent syncs to a file that's been synced in this
  1654. * transaction will appear to have already occurred.
  1655. */
  1656. spin_lock(&BTRFS_I(inode)->lock);
  1657. BTRFS_I(inode)->last_sub_trans = root->log_transid;
  1658. spin_unlock(&BTRFS_I(inode)->lock);
  1659. if (num_written > 0)
  1660. num_written = generic_write_sync(iocb, num_written);
  1661. if (sync)
  1662. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1663. out:
  1664. current->backing_dev_info = NULL;
  1665. return num_written ? num_written : err;
  1666. }
  1667. int btrfs_release_file(struct inode *inode, struct file *filp)
  1668. {
  1669. if (filp->private_data)
  1670. btrfs_ioctl_trans_end(filp);
  1671. /*
  1672. * ordered_data_close is set by settattr when we are about to truncate
  1673. * a file from a non-zero size to a zero size. This tries to
  1674. * flush down new bytes that may have been written if the
  1675. * application were using truncate to replace a file in place.
  1676. */
  1677. if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
  1678. &BTRFS_I(inode)->runtime_flags))
  1679. filemap_flush(inode->i_mapping);
  1680. return 0;
  1681. }
  1682. static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
  1683. {
  1684. int ret;
  1685. atomic_inc(&BTRFS_I(inode)->sync_writers);
  1686. ret = btrfs_fdatawrite_range(inode, start, end);
  1687. atomic_dec(&BTRFS_I(inode)->sync_writers);
  1688. return ret;
  1689. }
  1690. /*
  1691. * fsync call for both files and directories. This logs the inode into
  1692. * the tree log instead of forcing full commits whenever possible.
  1693. *
  1694. * It needs to call filemap_fdatawait so that all ordered extent updates are
  1695. * in the metadata btree are up to date for copying to the log.
  1696. *
  1697. * It drops the inode mutex before doing the tree log commit. This is an
  1698. * important optimization for directories because holding the mutex prevents
  1699. * new operations on the dir while we write to disk.
  1700. */
  1701. int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
  1702. {
  1703. struct dentry *dentry = file_dentry(file);
  1704. struct inode *inode = d_inode(dentry);
  1705. struct btrfs_root *root = BTRFS_I(inode)->root;
  1706. struct btrfs_trans_handle *trans;
  1707. struct btrfs_log_ctx ctx;
  1708. int ret = 0;
  1709. bool full_sync = 0;
  1710. u64 len;
  1711. /*
  1712. * The range length can be represented by u64, we have to do the typecasts
  1713. * to avoid signed overflow if it's [0, LLONG_MAX] eg. from fsync()
  1714. */
  1715. len = (u64)end - (u64)start + 1;
  1716. trace_btrfs_sync_file(file, datasync);
  1717. /*
  1718. * We write the dirty pages in the range and wait until they complete
  1719. * out of the ->i_mutex. If so, we can flush the dirty pages by
  1720. * multi-task, and make the performance up. See
  1721. * btrfs_wait_ordered_range for an explanation of the ASYNC check.
  1722. */
  1723. ret = start_ordered_ops(inode, start, end);
  1724. if (ret)
  1725. return ret;
  1726. inode_lock(inode);
  1727. atomic_inc(&root->log_batch);
  1728. full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1729. &BTRFS_I(inode)->runtime_flags);
  1730. /*
  1731. * We might have have had more pages made dirty after calling
  1732. * start_ordered_ops and before acquiring the inode's i_mutex.
  1733. */
  1734. if (full_sync) {
  1735. /*
  1736. * For a full sync, we need to make sure any ordered operations
  1737. * start and finish before we start logging the inode, so that
  1738. * all extents are persisted and the respective file extent
  1739. * items are in the fs/subvol btree.
  1740. */
  1741. ret = btrfs_wait_ordered_range(inode, start, len);
  1742. } else {
  1743. /*
  1744. * Start any new ordered operations before starting to log the
  1745. * inode. We will wait for them to finish in btrfs_sync_log().
  1746. *
  1747. * Right before acquiring the inode's mutex, we might have new
  1748. * writes dirtying pages, which won't immediately start the
  1749. * respective ordered operations - that is done through the
  1750. * fill_delalloc callbacks invoked from the writepage and
  1751. * writepages address space operations. So make sure we start
  1752. * all ordered operations before starting to log our inode. Not
  1753. * doing this means that while logging the inode, writeback
  1754. * could start and invoke writepage/writepages, which would call
  1755. * the fill_delalloc callbacks (cow_file_range,
  1756. * submit_compressed_extents). These callbacks add first an
  1757. * extent map to the modified list of extents and then create
  1758. * the respective ordered operation, which means in
  1759. * tree-log.c:btrfs_log_inode() we might capture all existing
  1760. * ordered operations (with btrfs_get_logged_extents()) before
  1761. * the fill_delalloc callback adds its ordered operation, and by
  1762. * the time we visit the modified list of extent maps (with
  1763. * btrfs_log_changed_extents()), we see and process the extent
  1764. * map they created. We then use the extent map to construct a
  1765. * file extent item for logging without waiting for the
  1766. * respective ordered operation to finish - this file extent
  1767. * item points to a disk location that might not have yet been
  1768. * written to, containing random data - so after a crash a log
  1769. * replay will make our inode have file extent items that point
  1770. * to disk locations containing invalid data, as we returned
  1771. * success to userspace without waiting for the respective
  1772. * ordered operation to finish, because it wasn't captured by
  1773. * btrfs_get_logged_extents().
  1774. */
  1775. ret = start_ordered_ops(inode, start, end);
  1776. }
  1777. if (ret) {
  1778. inode_unlock(inode);
  1779. goto out;
  1780. }
  1781. atomic_inc(&root->log_batch);
  1782. /*
  1783. * If the last transaction that changed this file was before the current
  1784. * transaction and we have the full sync flag set in our inode, we can
  1785. * bail out now without any syncing.
  1786. *
  1787. * Note that we can't bail out if the full sync flag isn't set. This is
  1788. * because when the full sync flag is set we start all ordered extents
  1789. * and wait for them to fully complete - when they complete they update
  1790. * the inode's last_trans field through:
  1791. *
  1792. * btrfs_finish_ordered_io() ->
  1793. * btrfs_update_inode_fallback() ->
  1794. * btrfs_update_inode() ->
  1795. * btrfs_set_inode_last_trans()
  1796. *
  1797. * So we are sure that last_trans is up to date and can do this check to
  1798. * bail out safely. For the fast path, when the full sync flag is not
  1799. * set in our inode, we can not do it because we start only our ordered
  1800. * extents and don't wait for them to complete (that is when
  1801. * btrfs_finish_ordered_io runs), so here at this point their last_trans
  1802. * value might be less than or equals to fs_info->last_trans_committed,
  1803. * and setting a speculative last_trans for an inode when a buffered
  1804. * write is made (such as fs_info->generation + 1 for example) would not
  1805. * be reliable since after setting the value and before fsync is called
  1806. * any number of transactions can start and commit (transaction kthread
  1807. * commits the current transaction periodically), and a transaction
  1808. * commit does not start nor waits for ordered extents to complete.
  1809. */
  1810. smp_mb();
  1811. if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
  1812. (full_sync && BTRFS_I(inode)->last_trans <=
  1813. root->fs_info->last_trans_committed) ||
  1814. (!btrfs_have_ordered_extents_in_range(inode, start, len) &&
  1815. BTRFS_I(inode)->last_trans
  1816. <= root->fs_info->last_trans_committed)) {
  1817. /*
  1818. * We've had everything committed since the last time we were
  1819. * modified so clear this flag in case it was set for whatever
  1820. * reason, it's no longer relevant.
  1821. */
  1822. clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  1823. &BTRFS_I(inode)->runtime_flags);
  1824. inode_unlock(inode);
  1825. goto out;
  1826. }
  1827. /*
  1828. * ok we haven't committed the transaction yet, lets do a commit
  1829. */
  1830. if (file->private_data)
  1831. btrfs_ioctl_trans_end(file);
  1832. /*
  1833. * We use start here because we will need to wait on the IO to complete
  1834. * in btrfs_sync_log, which could require joining a transaction (for
  1835. * example checking cross references in the nocow path). If we use join
  1836. * here we could get into a situation where we're waiting on IO to
  1837. * happen that is blocked on a transaction trying to commit. With start
  1838. * we inc the extwriter counter, so we wait for all extwriters to exit
  1839. * before we start blocking join'ers. This comment is to keep somebody
  1840. * from thinking they are super smart and changing this to
  1841. * btrfs_join_transaction *cough*Josef*cough*.
  1842. */
  1843. trans = btrfs_start_transaction(root, 0);
  1844. if (IS_ERR(trans)) {
  1845. ret = PTR_ERR(trans);
  1846. inode_unlock(inode);
  1847. goto out;
  1848. }
  1849. trans->sync = true;
  1850. btrfs_init_log_ctx(&ctx);
  1851. ret = btrfs_log_dentry_safe(trans, root, dentry, start, end, &ctx);
  1852. if (ret < 0) {
  1853. /* Fallthrough and commit/free transaction. */
  1854. ret = 1;
  1855. }
  1856. /* we've logged all the items and now have a consistent
  1857. * version of the file in the log. It is possible that
  1858. * someone will come in and modify the file, but that's
  1859. * fine because the log is consistent on disk, and we
  1860. * have references to all of the file's extents
  1861. *
  1862. * It is possible that someone will come in and log the
  1863. * file again, but that will end up using the synchronization
  1864. * inside btrfs_sync_log to keep things safe.
  1865. */
  1866. inode_unlock(inode);
  1867. /*
  1868. * If any of the ordered extents had an error, just return it to user
  1869. * space, so that the application knows some writes didn't succeed and
  1870. * can take proper action (retry for e.g.). Blindly committing the
  1871. * transaction in this case, would fool userspace that everything was
  1872. * successful. And we also want to make sure our log doesn't contain
  1873. * file extent items pointing to extents that weren't fully written to -
  1874. * just like in the non fast fsync path, where we check for the ordered
  1875. * operation's error flag before writing to the log tree and return -EIO
  1876. * if any of them had this flag set (btrfs_wait_ordered_range) -
  1877. * therefore we need to check for errors in the ordered operations,
  1878. * which are indicated by ctx.io_err.
  1879. */
  1880. if (ctx.io_err) {
  1881. btrfs_end_transaction(trans, root);
  1882. ret = ctx.io_err;
  1883. goto out;
  1884. }
  1885. if (ret != BTRFS_NO_LOG_SYNC) {
  1886. if (!ret) {
  1887. ret = btrfs_sync_log(trans, root, &ctx);
  1888. if (!ret) {
  1889. ret = btrfs_end_transaction(trans, root);
  1890. goto out;
  1891. }
  1892. }
  1893. if (!full_sync) {
  1894. ret = btrfs_wait_ordered_range(inode, start, len);
  1895. if (ret) {
  1896. btrfs_end_transaction(trans, root);
  1897. goto out;
  1898. }
  1899. }
  1900. ret = btrfs_commit_transaction(trans, root);
  1901. } else {
  1902. ret = btrfs_end_transaction(trans, root);
  1903. }
  1904. out:
  1905. return ret > 0 ? -EIO : ret;
  1906. }
  1907. static const struct vm_operations_struct btrfs_file_vm_ops = {
  1908. .fault = filemap_fault,
  1909. .map_pages = filemap_map_pages,
  1910. .page_mkwrite = btrfs_page_mkwrite,
  1911. };
  1912. static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
  1913. {
  1914. struct address_space *mapping = filp->f_mapping;
  1915. if (!mapping->a_ops->readpage)
  1916. return -ENOEXEC;
  1917. file_accessed(filp);
  1918. vma->vm_ops = &btrfs_file_vm_ops;
  1919. return 0;
  1920. }
  1921. static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
  1922. int slot, u64 start, u64 end)
  1923. {
  1924. struct btrfs_file_extent_item *fi;
  1925. struct btrfs_key key;
  1926. if (slot < 0 || slot >= btrfs_header_nritems(leaf))
  1927. return 0;
  1928. btrfs_item_key_to_cpu(leaf, &key, slot);
  1929. if (key.objectid != btrfs_ino(inode) ||
  1930. key.type != BTRFS_EXTENT_DATA_KEY)
  1931. return 0;
  1932. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  1933. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
  1934. return 0;
  1935. if (btrfs_file_extent_disk_bytenr(leaf, fi))
  1936. return 0;
  1937. if (key.offset == end)
  1938. return 1;
  1939. if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
  1940. return 1;
  1941. return 0;
  1942. }
  1943. static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
  1944. struct btrfs_path *path, u64 offset, u64 end)
  1945. {
  1946. struct btrfs_root *root = BTRFS_I(inode)->root;
  1947. struct extent_buffer *leaf;
  1948. struct btrfs_file_extent_item *fi;
  1949. struct extent_map *hole_em;
  1950. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  1951. struct btrfs_key key;
  1952. int ret;
  1953. if (btrfs_fs_incompat(root->fs_info, NO_HOLES))
  1954. goto out;
  1955. key.objectid = btrfs_ino(inode);
  1956. key.type = BTRFS_EXTENT_DATA_KEY;
  1957. key.offset = offset;
  1958. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  1959. if (ret < 0)
  1960. return ret;
  1961. BUG_ON(!ret);
  1962. leaf = path->nodes[0];
  1963. if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
  1964. u64 num_bytes;
  1965. path->slots[0]--;
  1966. fi = btrfs_item_ptr(leaf, path->slots[0],
  1967. struct btrfs_file_extent_item);
  1968. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
  1969. end - offset;
  1970. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1971. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1972. btrfs_set_file_extent_offset(leaf, fi, 0);
  1973. btrfs_mark_buffer_dirty(leaf);
  1974. goto out;
  1975. }
  1976. if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
  1977. u64 num_bytes;
  1978. key.offset = offset;
  1979. btrfs_set_item_key_safe(root->fs_info, path, &key);
  1980. fi = btrfs_item_ptr(leaf, path->slots[0],
  1981. struct btrfs_file_extent_item);
  1982. num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
  1983. offset;
  1984. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  1985. btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
  1986. btrfs_set_file_extent_offset(leaf, fi, 0);
  1987. btrfs_mark_buffer_dirty(leaf);
  1988. goto out;
  1989. }
  1990. btrfs_release_path(path);
  1991. ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
  1992. 0, 0, end - offset, 0, end - offset,
  1993. 0, 0, 0);
  1994. if (ret)
  1995. return ret;
  1996. out:
  1997. btrfs_release_path(path);
  1998. hole_em = alloc_extent_map();
  1999. if (!hole_em) {
  2000. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  2001. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  2002. &BTRFS_I(inode)->runtime_flags);
  2003. } else {
  2004. hole_em->start = offset;
  2005. hole_em->len = end - offset;
  2006. hole_em->ram_bytes = hole_em->len;
  2007. hole_em->orig_start = offset;
  2008. hole_em->block_start = EXTENT_MAP_HOLE;
  2009. hole_em->block_len = 0;
  2010. hole_em->orig_block_len = 0;
  2011. hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
  2012. hole_em->compress_type = BTRFS_COMPRESS_NONE;
  2013. hole_em->generation = trans->transid;
  2014. do {
  2015. btrfs_drop_extent_cache(inode, offset, end - 1, 0);
  2016. write_lock(&em_tree->lock);
  2017. ret = add_extent_mapping(em_tree, hole_em, 1);
  2018. write_unlock(&em_tree->lock);
  2019. } while (ret == -EEXIST);
  2020. free_extent_map(hole_em);
  2021. if (ret)
  2022. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  2023. &BTRFS_I(inode)->runtime_flags);
  2024. }
  2025. return 0;
  2026. }
  2027. /*
  2028. * Find a hole extent on given inode and change start/len to the end of hole
  2029. * extent.(hole/vacuum extent whose em->start <= start &&
  2030. * em->start + em->len > start)
  2031. * When a hole extent is found, return 1 and modify start/len.
  2032. */
  2033. static int find_first_non_hole(struct inode *inode, u64 *start, u64 *len)
  2034. {
  2035. struct extent_map *em;
  2036. int ret = 0;
  2037. em = btrfs_get_extent(inode, NULL, 0, *start, *len, 0);
  2038. if (IS_ERR_OR_NULL(em)) {
  2039. if (!em)
  2040. ret = -ENOMEM;
  2041. else
  2042. ret = PTR_ERR(em);
  2043. return ret;
  2044. }
  2045. /* Hole or vacuum extent(only exists in no-hole mode) */
  2046. if (em->block_start == EXTENT_MAP_HOLE) {
  2047. ret = 1;
  2048. *len = em->start + em->len > *start + *len ?
  2049. 0 : *start + *len - em->start - em->len;
  2050. *start = em->start + em->len;
  2051. }
  2052. free_extent_map(em);
  2053. return ret;
  2054. }
  2055. static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
  2056. {
  2057. struct btrfs_root *root = BTRFS_I(inode)->root;
  2058. struct extent_state *cached_state = NULL;
  2059. struct btrfs_path *path;
  2060. struct btrfs_block_rsv *rsv;
  2061. struct btrfs_trans_handle *trans;
  2062. u64 lockstart;
  2063. u64 lockend;
  2064. u64 tail_start;
  2065. u64 tail_len;
  2066. u64 orig_start = offset;
  2067. u64 cur_offset;
  2068. u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
  2069. u64 drop_end;
  2070. int ret = 0;
  2071. int err = 0;
  2072. unsigned int rsv_count;
  2073. bool same_block;
  2074. bool no_holes = btrfs_fs_incompat(root->fs_info, NO_HOLES);
  2075. u64 ino_size;
  2076. bool truncated_block = false;
  2077. bool updated_inode = false;
  2078. ret = btrfs_wait_ordered_range(inode, offset, len);
  2079. if (ret)
  2080. return ret;
  2081. inode_lock(inode);
  2082. ino_size = round_up(inode->i_size, root->sectorsize);
  2083. ret = find_first_non_hole(inode, &offset, &len);
  2084. if (ret < 0)
  2085. goto out_only_mutex;
  2086. if (ret && !len) {
  2087. /* Already in a large hole */
  2088. ret = 0;
  2089. goto out_only_mutex;
  2090. }
  2091. lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
  2092. lockend = round_down(offset + len,
  2093. BTRFS_I(inode)->root->sectorsize) - 1;
  2094. same_block = (BTRFS_BYTES_TO_BLKS(root->fs_info, offset))
  2095. == (BTRFS_BYTES_TO_BLKS(root->fs_info, offset + len - 1));
  2096. /*
  2097. * We needn't truncate any block which is beyond the end of the file
  2098. * because we are sure there is no data there.
  2099. */
  2100. /*
  2101. * Only do this if we are in the same block and we aren't doing the
  2102. * entire block.
  2103. */
  2104. if (same_block && len < root->sectorsize) {
  2105. if (offset < ino_size) {
  2106. truncated_block = true;
  2107. ret = btrfs_truncate_block(inode, offset, len, 0);
  2108. } else {
  2109. ret = 0;
  2110. }
  2111. goto out_only_mutex;
  2112. }
  2113. /* zero back part of the first block */
  2114. if (offset < ino_size) {
  2115. truncated_block = true;
  2116. ret = btrfs_truncate_block(inode, offset, 0, 0);
  2117. if (ret) {
  2118. inode_unlock(inode);
  2119. return ret;
  2120. }
  2121. }
  2122. /* Check the aligned pages after the first unaligned page,
  2123. * if offset != orig_start, which means the first unaligned page
  2124. * including several following pages are already in holes,
  2125. * the extra check can be skipped */
  2126. if (offset == orig_start) {
  2127. /* after truncate page, check hole again */
  2128. len = offset + len - lockstart;
  2129. offset = lockstart;
  2130. ret = find_first_non_hole(inode, &offset, &len);
  2131. if (ret < 0)
  2132. goto out_only_mutex;
  2133. if (ret && !len) {
  2134. ret = 0;
  2135. goto out_only_mutex;
  2136. }
  2137. lockstart = offset;
  2138. }
  2139. /* Check the tail unaligned part is in a hole */
  2140. tail_start = lockend + 1;
  2141. tail_len = offset + len - tail_start;
  2142. if (tail_len) {
  2143. ret = find_first_non_hole(inode, &tail_start, &tail_len);
  2144. if (unlikely(ret < 0))
  2145. goto out_only_mutex;
  2146. if (!ret) {
  2147. /* zero the front end of the last page */
  2148. if (tail_start + tail_len < ino_size) {
  2149. truncated_block = true;
  2150. ret = btrfs_truncate_block(inode,
  2151. tail_start + tail_len,
  2152. 0, 1);
  2153. if (ret)
  2154. goto out_only_mutex;
  2155. }
  2156. }
  2157. }
  2158. if (lockend < lockstart) {
  2159. ret = 0;
  2160. goto out_only_mutex;
  2161. }
  2162. while (1) {
  2163. struct btrfs_ordered_extent *ordered;
  2164. truncate_pagecache_range(inode, lockstart, lockend);
  2165. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2166. &cached_state);
  2167. ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
  2168. /*
  2169. * We need to make sure we have no ordered extents in this range
  2170. * and nobody raced in and read a page in this range, if we did
  2171. * we need to try again.
  2172. */
  2173. if ((!ordered ||
  2174. (ordered->file_offset + ordered->len <= lockstart ||
  2175. ordered->file_offset > lockend)) &&
  2176. !btrfs_page_exists_in_range(inode, lockstart, lockend)) {
  2177. if (ordered)
  2178. btrfs_put_ordered_extent(ordered);
  2179. break;
  2180. }
  2181. if (ordered)
  2182. btrfs_put_ordered_extent(ordered);
  2183. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
  2184. lockend, &cached_state, GFP_NOFS);
  2185. ret = btrfs_wait_ordered_range(inode, lockstart,
  2186. lockend - lockstart + 1);
  2187. if (ret) {
  2188. inode_unlock(inode);
  2189. return ret;
  2190. }
  2191. }
  2192. path = btrfs_alloc_path();
  2193. if (!path) {
  2194. ret = -ENOMEM;
  2195. goto out;
  2196. }
  2197. rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
  2198. if (!rsv) {
  2199. ret = -ENOMEM;
  2200. goto out_free;
  2201. }
  2202. rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
  2203. rsv->failfast = 1;
  2204. /*
  2205. * 1 - update the inode
  2206. * 1 - removing the extents in the range
  2207. * 1 - adding the hole extent if no_holes isn't set
  2208. */
  2209. rsv_count = no_holes ? 2 : 3;
  2210. trans = btrfs_start_transaction(root, rsv_count);
  2211. if (IS_ERR(trans)) {
  2212. err = PTR_ERR(trans);
  2213. goto out_free;
  2214. }
  2215. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
  2216. min_size, 0);
  2217. BUG_ON(ret);
  2218. trans->block_rsv = rsv;
  2219. cur_offset = lockstart;
  2220. len = lockend - cur_offset;
  2221. while (cur_offset < lockend) {
  2222. ret = __btrfs_drop_extents(trans, root, inode, path,
  2223. cur_offset, lockend + 1,
  2224. &drop_end, 1, 0, 0, NULL);
  2225. if (ret != -ENOSPC)
  2226. break;
  2227. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2228. if (cur_offset < ino_size) {
  2229. ret = fill_holes(trans, inode, path, cur_offset,
  2230. drop_end);
  2231. if (ret) {
  2232. err = ret;
  2233. break;
  2234. }
  2235. }
  2236. cur_offset = drop_end;
  2237. ret = btrfs_update_inode(trans, root, inode);
  2238. if (ret) {
  2239. err = ret;
  2240. break;
  2241. }
  2242. btrfs_end_transaction(trans, root);
  2243. btrfs_btree_balance_dirty(root);
  2244. trans = btrfs_start_transaction(root, rsv_count);
  2245. if (IS_ERR(trans)) {
  2246. ret = PTR_ERR(trans);
  2247. trans = NULL;
  2248. break;
  2249. }
  2250. ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
  2251. rsv, min_size, 0);
  2252. BUG_ON(ret); /* shouldn't happen */
  2253. trans->block_rsv = rsv;
  2254. ret = find_first_non_hole(inode, &cur_offset, &len);
  2255. if (unlikely(ret < 0))
  2256. break;
  2257. if (ret && !len) {
  2258. ret = 0;
  2259. break;
  2260. }
  2261. }
  2262. if (ret) {
  2263. err = ret;
  2264. goto out_trans;
  2265. }
  2266. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2267. /*
  2268. * If we are using the NO_HOLES feature we might have had already an
  2269. * hole that overlaps a part of the region [lockstart, lockend] and
  2270. * ends at (or beyond) lockend. Since we have no file extent items to
  2271. * represent holes, drop_end can be less than lockend and so we must
  2272. * make sure we have an extent map representing the existing hole (the
  2273. * call to __btrfs_drop_extents() might have dropped the existing extent
  2274. * map representing the existing hole), otherwise the fast fsync path
  2275. * will not record the existence of the hole region
  2276. * [existing_hole_start, lockend].
  2277. */
  2278. if (drop_end <= lockend)
  2279. drop_end = lockend + 1;
  2280. /*
  2281. * Don't insert file hole extent item if it's for a range beyond eof
  2282. * (because it's useless) or if it represents a 0 bytes range (when
  2283. * cur_offset == drop_end).
  2284. */
  2285. if (cur_offset < ino_size && cur_offset < drop_end) {
  2286. ret = fill_holes(trans, inode, path, cur_offset, drop_end);
  2287. if (ret) {
  2288. err = ret;
  2289. goto out_trans;
  2290. }
  2291. }
  2292. out_trans:
  2293. if (!trans)
  2294. goto out_free;
  2295. inode_inc_iversion(inode);
  2296. inode->i_mtime = inode->i_ctime = current_fs_time(inode->i_sb);
  2297. trans->block_rsv = &root->fs_info->trans_block_rsv;
  2298. ret = btrfs_update_inode(trans, root, inode);
  2299. updated_inode = true;
  2300. btrfs_end_transaction(trans, root);
  2301. btrfs_btree_balance_dirty(root);
  2302. out_free:
  2303. btrfs_free_path(path);
  2304. btrfs_free_block_rsv(root, rsv);
  2305. out:
  2306. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2307. &cached_state, GFP_NOFS);
  2308. out_only_mutex:
  2309. if (!updated_inode && truncated_block && !ret && !err) {
  2310. /*
  2311. * If we only end up zeroing part of a page, we still need to
  2312. * update the inode item, so that all the time fields are
  2313. * updated as well as the necessary btrfs inode in memory fields
  2314. * for detecting, at fsync time, if the inode isn't yet in the
  2315. * log tree or it's there but not up to date.
  2316. */
  2317. trans = btrfs_start_transaction(root, 1);
  2318. if (IS_ERR(trans)) {
  2319. err = PTR_ERR(trans);
  2320. } else {
  2321. err = btrfs_update_inode(trans, root, inode);
  2322. ret = btrfs_end_transaction(trans, root);
  2323. }
  2324. }
  2325. inode_unlock(inode);
  2326. if (ret && !err)
  2327. err = ret;
  2328. return err;
  2329. }
  2330. /* Helper structure to record which range is already reserved */
  2331. struct falloc_range {
  2332. struct list_head list;
  2333. u64 start;
  2334. u64 len;
  2335. };
  2336. /*
  2337. * Helper function to add falloc range
  2338. *
  2339. * Caller should have locked the larger range of extent containing
  2340. * [start, len)
  2341. */
  2342. static int add_falloc_range(struct list_head *head, u64 start, u64 len)
  2343. {
  2344. struct falloc_range *prev = NULL;
  2345. struct falloc_range *range = NULL;
  2346. if (list_empty(head))
  2347. goto insert;
  2348. /*
  2349. * As fallocate iterate by bytenr order, we only need to check
  2350. * the last range.
  2351. */
  2352. prev = list_entry(head->prev, struct falloc_range, list);
  2353. if (prev->start + prev->len == start) {
  2354. prev->len += len;
  2355. return 0;
  2356. }
  2357. insert:
  2358. range = kmalloc(sizeof(*range), GFP_KERNEL);
  2359. if (!range)
  2360. return -ENOMEM;
  2361. range->start = start;
  2362. range->len = len;
  2363. list_add_tail(&range->list, head);
  2364. return 0;
  2365. }
  2366. static long btrfs_fallocate(struct file *file, int mode,
  2367. loff_t offset, loff_t len)
  2368. {
  2369. struct inode *inode = file_inode(file);
  2370. struct extent_state *cached_state = NULL;
  2371. struct falloc_range *range;
  2372. struct falloc_range *tmp;
  2373. struct list_head reserve_list;
  2374. u64 cur_offset;
  2375. u64 last_byte;
  2376. u64 alloc_start;
  2377. u64 alloc_end;
  2378. u64 alloc_hint = 0;
  2379. u64 locked_end;
  2380. u64 actual_end = 0;
  2381. struct extent_map *em;
  2382. int blocksize = BTRFS_I(inode)->root->sectorsize;
  2383. int ret;
  2384. alloc_start = round_down(offset, blocksize);
  2385. alloc_end = round_up(offset + len, blocksize);
  2386. /* Make sure we aren't being give some crap mode */
  2387. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  2388. return -EOPNOTSUPP;
  2389. if (mode & FALLOC_FL_PUNCH_HOLE)
  2390. return btrfs_punch_hole(inode, offset, len);
  2391. /*
  2392. * Only trigger disk allocation, don't trigger qgroup reserve
  2393. *
  2394. * For qgroup space, it will be checked later.
  2395. */
  2396. ret = btrfs_alloc_data_chunk_ondemand(inode, alloc_end - alloc_start);
  2397. if (ret < 0)
  2398. return ret;
  2399. inode_lock(inode);
  2400. if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
  2401. ret = inode_newsize_ok(inode, offset + len);
  2402. if (ret)
  2403. goto out;
  2404. }
  2405. /*
  2406. * TODO: Move these two operations after we have checked
  2407. * accurate reserved space, or fallocate can still fail but
  2408. * with page truncated or size expanded.
  2409. *
  2410. * But that's a minor problem and won't do much harm BTW.
  2411. */
  2412. if (alloc_start > inode->i_size) {
  2413. ret = btrfs_cont_expand(inode, i_size_read(inode),
  2414. alloc_start);
  2415. if (ret)
  2416. goto out;
  2417. } else if (offset + len > inode->i_size) {
  2418. /*
  2419. * If we are fallocating from the end of the file onward we
  2420. * need to zero out the end of the block if i_size lands in the
  2421. * middle of a block.
  2422. */
  2423. ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
  2424. if (ret)
  2425. goto out;
  2426. }
  2427. /*
  2428. * wait for ordered IO before we have any locks. We'll loop again
  2429. * below with the locks held.
  2430. */
  2431. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2432. alloc_end - alloc_start);
  2433. if (ret)
  2434. goto out;
  2435. locked_end = alloc_end - 1;
  2436. while (1) {
  2437. struct btrfs_ordered_extent *ordered;
  2438. /* the extent lock is ordered inside the running
  2439. * transaction
  2440. */
  2441. lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
  2442. locked_end, &cached_state);
  2443. ordered = btrfs_lookup_first_ordered_extent(inode,
  2444. alloc_end - 1);
  2445. if (ordered &&
  2446. ordered->file_offset + ordered->len > alloc_start &&
  2447. ordered->file_offset < alloc_end) {
  2448. btrfs_put_ordered_extent(ordered);
  2449. unlock_extent_cached(&BTRFS_I(inode)->io_tree,
  2450. alloc_start, locked_end,
  2451. &cached_state, GFP_KERNEL);
  2452. /*
  2453. * we can't wait on the range with the transaction
  2454. * running or with the extent lock held
  2455. */
  2456. ret = btrfs_wait_ordered_range(inode, alloc_start,
  2457. alloc_end - alloc_start);
  2458. if (ret)
  2459. goto out;
  2460. } else {
  2461. if (ordered)
  2462. btrfs_put_ordered_extent(ordered);
  2463. break;
  2464. }
  2465. }
  2466. /* First, check if we exceed the qgroup limit */
  2467. INIT_LIST_HEAD(&reserve_list);
  2468. cur_offset = alloc_start;
  2469. while (1) {
  2470. em = btrfs_get_extent(inode, NULL, 0, cur_offset,
  2471. alloc_end - cur_offset, 0);
  2472. if (IS_ERR_OR_NULL(em)) {
  2473. if (!em)
  2474. ret = -ENOMEM;
  2475. else
  2476. ret = PTR_ERR(em);
  2477. break;
  2478. }
  2479. last_byte = min(extent_map_end(em), alloc_end);
  2480. actual_end = min_t(u64, extent_map_end(em), offset + len);
  2481. last_byte = ALIGN(last_byte, blocksize);
  2482. if (em->block_start == EXTENT_MAP_HOLE ||
  2483. (cur_offset >= inode->i_size &&
  2484. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
  2485. ret = add_falloc_range(&reserve_list, cur_offset,
  2486. last_byte - cur_offset);
  2487. if (ret < 0) {
  2488. free_extent_map(em);
  2489. break;
  2490. }
  2491. ret = btrfs_qgroup_reserve_data(inode, cur_offset,
  2492. last_byte - cur_offset);
  2493. if (ret < 0)
  2494. break;
  2495. }
  2496. free_extent_map(em);
  2497. cur_offset = last_byte;
  2498. if (cur_offset >= alloc_end)
  2499. break;
  2500. }
  2501. /*
  2502. * If ret is still 0, means we're OK to fallocate.
  2503. * Or just cleanup the list and exit.
  2504. */
  2505. list_for_each_entry_safe(range, tmp, &reserve_list, list) {
  2506. if (!ret)
  2507. ret = btrfs_prealloc_file_range(inode, mode,
  2508. range->start,
  2509. range->len, 1 << inode->i_blkbits,
  2510. offset + len, &alloc_hint);
  2511. list_del(&range->list);
  2512. kfree(range);
  2513. }
  2514. if (ret < 0)
  2515. goto out_unlock;
  2516. if (actual_end > inode->i_size &&
  2517. !(mode & FALLOC_FL_KEEP_SIZE)) {
  2518. struct btrfs_trans_handle *trans;
  2519. struct btrfs_root *root = BTRFS_I(inode)->root;
  2520. /*
  2521. * We didn't need to allocate any more space, but we
  2522. * still extended the size of the file so we need to
  2523. * update i_size and the inode item.
  2524. */
  2525. trans = btrfs_start_transaction(root, 1);
  2526. if (IS_ERR(trans)) {
  2527. ret = PTR_ERR(trans);
  2528. } else {
  2529. inode->i_ctime = current_fs_time(inode->i_sb);
  2530. i_size_write(inode, actual_end);
  2531. btrfs_ordered_update_i_size(inode, actual_end, NULL);
  2532. ret = btrfs_update_inode(trans, root, inode);
  2533. if (ret)
  2534. btrfs_end_transaction(trans, root);
  2535. else
  2536. ret = btrfs_end_transaction(trans, root);
  2537. }
  2538. }
  2539. out_unlock:
  2540. unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
  2541. &cached_state, GFP_KERNEL);
  2542. out:
  2543. /*
  2544. * As we waited the extent range, the data_rsv_map must be empty
  2545. * in the range, as written data range will be released from it.
  2546. * And for prealloacted extent, it will also be released when
  2547. * its metadata is written.
  2548. * So this is completely used as cleanup.
  2549. */
  2550. btrfs_qgroup_free_data(inode, alloc_start, alloc_end - alloc_start);
  2551. inode_unlock(inode);
  2552. /* Let go of our reservation. */
  2553. btrfs_free_reserved_data_space(inode, alloc_start,
  2554. alloc_end - alloc_start);
  2555. return ret;
  2556. }
  2557. static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
  2558. {
  2559. struct btrfs_root *root = BTRFS_I(inode)->root;
  2560. struct extent_map *em = NULL;
  2561. struct extent_state *cached_state = NULL;
  2562. u64 lockstart;
  2563. u64 lockend;
  2564. u64 start;
  2565. u64 len;
  2566. int ret = 0;
  2567. if (inode->i_size == 0)
  2568. return -ENXIO;
  2569. /*
  2570. * *offset can be negative, in this case we start finding DATA/HOLE from
  2571. * the very start of the file.
  2572. */
  2573. start = max_t(loff_t, 0, *offset);
  2574. lockstart = round_down(start, root->sectorsize);
  2575. lockend = round_up(i_size_read(inode), root->sectorsize);
  2576. if (lockend <= lockstart)
  2577. lockend = lockstart + root->sectorsize;
  2578. lockend--;
  2579. len = lockend - lockstart + 1;
  2580. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2581. &cached_state);
  2582. while (start < inode->i_size) {
  2583. em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
  2584. if (IS_ERR(em)) {
  2585. ret = PTR_ERR(em);
  2586. em = NULL;
  2587. break;
  2588. }
  2589. if (whence == SEEK_HOLE &&
  2590. (em->block_start == EXTENT_MAP_HOLE ||
  2591. test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2592. break;
  2593. else if (whence == SEEK_DATA &&
  2594. (em->block_start != EXTENT_MAP_HOLE &&
  2595. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
  2596. break;
  2597. start = em->start + em->len;
  2598. free_extent_map(em);
  2599. em = NULL;
  2600. cond_resched();
  2601. }
  2602. free_extent_map(em);
  2603. if (!ret) {
  2604. if (whence == SEEK_DATA && start >= inode->i_size)
  2605. ret = -ENXIO;
  2606. else
  2607. *offset = min_t(loff_t, start, inode->i_size);
  2608. }
  2609. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  2610. &cached_state, GFP_NOFS);
  2611. return ret;
  2612. }
  2613. static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
  2614. {
  2615. struct inode *inode = file->f_mapping->host;
  2616. int ret;
  2617. inode_lock(inode);
  2618. switch (whence) {
  2619. case SEEK_END:
  2620. case SEEK_CUR:
  2621. offset = generic_file_llseek(file, offset, whence);
  2622. goto out;
  2623. case SEEK_DATA:
  2624. case SEEK_HOLE:
  2625. if (offset >= i_size_read(inode)) {
  2626. inode_unlock(inode);
  2627. return -ENXIO;
  2628. }
  2629. ret = find_desired_extent(inode, &offset, whence);
  2630. if (ret) {
  2631. inode_unlock(inode);
  2632. return ret;
  2633. }
  2634. }
  2635. offset = vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
  2636. out:
  2637. inode_unlock(inode);
  2638. return offset;
  2639. }
  2640. const struct file_operations btrfs_file_operations = {
  2641. .llseek = btrfs_file_llseek,
  2642. .read_iter = generic_file_read_iter,
  2643. .splice_read = generic_file_splice_read,
  2644. .write_iter = btrfs_file_write_iter,
  2645. .mmap = btrfs_file_mmap,
  2646. .open = generic_file_open,
  2647. .release = btrfs_release_file,
  2648. .fsync = btrfs_sync_file,
  2649. .fallocate = btrfs_fallocate,
  2650. .unlocked_ioctl = btrfs_ioctl,
  2651. #ifdef CONFIG_COMPAT
  2652. .compat_ioctl = btrfs_compat_ioctl,
  2653. #endif
  2654. .copy_file_range = btrfs_copy_file_range,
  2655. .clone_file_range = btrfs_clone_file_range,
  2656. .dedupe_file_range = btrfs_dedupe_file_range,
  2657. };
  2658. void btrfs_auto_defrag_exit(void)
  2659. {
  2660. kmem_cache_destroy(btrfs_inode_defrag_cachep);
  2661. }
  2662. int btrfs_auto_defrag_init(void)
  2663. {
  2664. btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
  2665. sizeof(struct inode_defrag), 0,
  2666. SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
  2667. NULL);
  2668. if (!btrfs_inode_defrag_cachep)
  2669. return -ENOMEM;
  2670. return 0;
  2671. }
  2672. int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
  2673. {
  2674. int ret;
  2675. /*
  2676. * So with compression we will find and lock a dirty page and clear the
  2677. * first one as dirty, setup an async extent, and immediately return
  2678. * with the entire range locked but with nobody actually marked with
  2679. * writeback. So we can't just filemap_write_and_wait_range() and
  2680. * expect it to work since it will just kick off a thread to do the
  2681. * actual work. So we need to call filemap_fdatawrite_range _again_
  2682. * since it will wait on the page lock, which won't be unlocked until
  2683. * after the pages have been marked as writeback and so we're good to go
  2684. * from there. We have to do this otherwise we'll miss the ordered
  2685. * extents and that results in badness. Please Josef, do not think you
  2686. * know better and pull this out at some point in the future, it is
  2687. * right and you are wrong.
  2688. */
  2689. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2690. if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  2691. &BTRFS_I(inode)->runtime_flags))
  2692. ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
  2693. return ret;
  2694. }