reflink.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/blkdev.h>
  3. #include <linux/iversion.h>
  4. #include "ctree.h"
  5. #include "fs.h"
  6. #include "messages.h"
  7. #include "compression.h"
  8. #include "delalloc-space.h"
  9. #include "disk-io.h"
  10. #include "reflink.h"
  11. #include "transaction.h"
  12. #include "subpage.h"
  13. #include "accessors.h"
  14. #include "file-item.h"
  15. #include "file.h"
  16. #include "super.h"
  17. #define BTRFS_MAX_DEDUPE_LEN SZ_16M
  18. static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
  19. struct inode *inode,
  20. u64 endoff,
  21. const u64 destoff,
  22. const u64 olen,
  23. int no_time_update)
  24. {
  25. int ret;
  26. inode_inc_iversion(inode);
  27. if (!no_time_update) {
  28. inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
  29. }
  30. /*
  31. * We round up to the block size at eof when determining which
  32. * extents to clone above, but shouldn't round up the file size.
  33. */
  34. if (endoff > destoff + olen)
  35. endoff = destoff + olen;
  36. if (endoff > inode->i_size) {
  37. i_size_write(inode, endoff);
  38. btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
  39. }
  40. ret = btrfs_update_inode(trans, BTRFS_I(inode));
  41. if (ret) {
  42. btrfs_abort_transaction(trans, ret);
  43. btrfs_end_transaction(trans);
  44. goto out;
  45. }
  46. ret = btrfs_end_transaction(trans);
  47. out:
  48. return ret;
  49. }
  50. static int copy_inline_to_page(struct btrfs_inode *inode,
  51. const u64 file_offset,
  52. char *inline_data,
  53. const u64 size,
  54. const u64 datal,
  55. const u8 comp_type)
  56. {
  57. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  58. const u32 block_size = fs_info->sectorsize;
  59. const u64 range_end = file_offset + block_size - 1;
  60. const size_t inline_size = size - btrfs_file_extent_calc_inline_size(0);
  61. char *data_start = inline_data + btrfs_file_extent_calc_inline_size(0);
  62. struct extent_changeset *data_reserved = NULL;
  63. struct folio *folio = NULL;
  64. struct address_space *mapping = inode->vfs_inode.i_mapping;
  65. int ret;
  66. ASSERT(IS_ALIGNED(file_offset, block_size));
  67. /*
  68. * We have flushed and locked the ranges of the source and destination
  69. * inodes, we also have locked the inodes, so we are safe to do a
  70. * reservation here. Also we must not do the reservation while holding
  71. * a transaction open, otherwise we would deadlock.
  72. */
  73. ret = btrfs_delalloc_reserve_space(inode, &data_reserved, file_offset,
  74. block_size);
  75. if (ret)
  76. goto out;
  77. folio = __filemap_get_folio(mapping, file_offset >> PAGE_SHIFT,
  78. FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
  79. btrfs_alloc_write_mask(mapping));
  80. if (IS_ERR(folio)) {
  81. ret = -ENOMEM;
  82. goto out_unlock;
  83. }
  84. ret = set_folio_extent_mapped(folio);
  85. if (ret < 0)
  86. goto out_unlock;
  87. clear_extent_bit(&inode->io_tree, file_offset, range_end,
  88. EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  89. NULL);
  90. ret = btrfs_set_extent_delalloc(inode, file_offset, range_end, 0, NULL);
  91. if (ret)
  92. goto out_unlock;
  93. /*
  94. * After dirtying the page our caller will need to start a transaction,
  95. * and if we are low on metadata free space, that can cause flushing of
  96. * delalloc for all inodes in order to get metadata space released.
  97. * However we are holding the range locked for the whole duration of
  98. * the clone/dedupe operation, so we may deadlock if that happens and no
  99. * other task releases enough space. So mark this inode as not being
  100. * possible to flush to avoid such deadlock. We will clear that flag
  101. * when we finish cloning all extents, since a transaction is started
  102. * after finding each extent to clone.
  103. */
  104. set_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &inode->runtime_flags);
  105. if (comp_type == BTRFS_COMPRESS_NONE) {
  106. memcpy_to_folio(folio, offset_in_folio(folio, file_offset), data_start,
  107. datal);
  108. } else {
  109. ret = btrfs_decompress(comp_type, data_start, folio,
  110. offset_in_folio(folio, file_offset),
  111. inline_size, datal);
  112. if (ret)
  113. goto out_unlock;
  114. flush_dcache_folio(folio);
  115. }
  116. /*
  117. * If our inline data is smaller then the block/page size, then the
  118. * remaining of the block/page is equivalent to zeroes. We had something
  119. * like the following done:
  120. *
  121. * $ xfs_io -f -c "pwrite -S 0xab 0 500" file
  122. * $ sync # (or fsync)
  123. * $ xfs_io -c "falloc 0 4K" file
  124. * $ xfs_io -c "pwrite -S 0xcd 4K 4K"
  125. *
  126. * So what's in the range [500, 4095] corresponds to zeroes.
  127. */
  128. if (datal < block_size)
  129. folio_zero_range(folio, datal, block_size - datal);
  130. btrfs_folio_set_uptodate(fs_info, folio, file_offset, block_size);
  131. btrfs_folio_clear_checked(fs_info, folio, file_offset, block_size);
  132. btrfs_folio_set_dirty(fs_info, folio, file_offset, block_size);
  133. out_unlock:
  134. if (!IS_ERR(folio)) {
  135. folio_unlock(folio);
  136. folio_put(folio);
  137. }
  138. if (ret)
  139. btrfs_delalloc_release_space(inode, data_reserved, file_offset,
  140. block_size, true);
  141. btrfs_delalloc_release_extents(inode, block_size);
  142. out:
  143. extent_changeset_free(data_reserved);
  144. return ret;
  145. }
  146. /*
  147. * Deal with cloning of inline extents. We try to copy the inline extent from
  148. * the source inode to destination inode when possible. When not possible we
  149. * copy the inline extent's data into the respective page of the inode.
  150. */
  151. static int clone_copy_inline_extent(struct inode *dst,
  152. struct btrfs_path *path,
  153. struct btrfs_key *new_key,
  154. const u64 drop_start,
  155. const u64 datal,
  156. const u64 size,
  157. const u8 comp_type,
  158. char *inline_data,
  159. struct btrfs_trans_handle **trans_out)
  160. {
  161. struct btrfs_fs_info *fs_info = inode_to_fs_info(dst);
  162. struct btrfs_root *root = BTRFS_I(dst)->root;
  163. const u64 aligned_end = ALIGN(new_key->offset + datal,
  164. fs_info->sectorsize);
  165. struct btrfs_trans_handle *trans = NULL;
  166. struct btrfs_drop_extents_args drop_args = { 0 };
  167. int ret;
  168. struct btrfs_key key;
  169. if (new_key->offset > 0) {
  170. ret = copy_inline_to_page(BTRFS_I(dst), new_key->offset,
  171. inline_data, size, datal, comp_type);
  172. goto out;
  173. }
  174. key.objectid = btrfs_ino(BTRFS_I(dst));
  175. key.type = BTRFS_EXTENT_DATA_KEY;
  176. key.offset = 0;
  177. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  178. if (ret < 0) {
  179. return ret;
  180. } else if (ret > 0) {
  181. if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
  182. ret = btrfs_next_leaf(root, path);
  183. if (ret < 0)
  184. return ret;
  185. else if (ret > 0)
  186. goto copy_inline_extent;
  187. }
  188. btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
  189. if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
  190. key.type == BTRFS_EXTENT_DATA_KEY) {
  191. /*
  192. * There's an implicit hole at file offset 0, copy the
  193. * inline extent's data to the page.
  194. */
  195. ASSERT(key.offset > 0);
  196. goto copy_to_page;
  197. }
  198. } else if (i_size_read(dst) <= datal) {
  199. struct btrfs_file_extent_item *ei;
  200. ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
  201. struct btrfs_file_extent_item);
  202. /*
  203. * If it's an inline extent replace it with the source inline
  204. * extent, otherwise copy the source inline extent data into
  205. * the respective page at the destination inode.
  206. */
  207. if (btrfs_file_extent_type(path->nodes[0], ei) ==
  208. BTRFS_FILE_EXTENT_INLINE)
  209. goto copy_inline_extent;
  210. goto copy_to_page;
  211. }
  212. copy_inline_extent:
  213. /*
  214. * We have no extent items, or we have an extent at offset 0 which may
  215. * or may not be inlined. All these cases are dealt the same way.
  216. */
  217. if (i_size_read(dst) > datal) {
  218. /*
  219. * At the destination offset 0 we have either a hole, a regular
  220. * extent or an inline extent larger then the one we want to
  221. * clone. Deal with all these cases by copying the inline extent
  222. * data into the respective page at the destination inode.
  223. */
  224. goto copy_to_page;
  225. }
  226. /*
  227. * Release path before starting a new transaction so we don't hold locks
  228. * that would confuse lockdep.
  229. */
  230. btrfs_release_path(path);
  231. /*
  232. * If we end up here it means were copy the inline extent into a leaf
  233. * of the destination inode. We know we will drop or adjust at most one
  234. * extent item in the destination root.
  235. *
  236. * 1 unit - adjusting old extent (we may have to split it)
  237. * 1 unit - add new extent
  238. * 1 unit - inode update
  239. */
  240. trans = btrfs_start_transaction(root, 3);
  241. if (IS_ERR(trans)) {
  242. ret = PTR_ERR(trans);
  243. trans = NULL;
  244. goto out;
  245. }
  246. drop_args.path = path;
  247. drop_args.start = drop_start;
  248. drop_args.end = aligned_end;
  249. drop_args.drop_cache = true;
  250. ret = btrfs_drop_extents(trans, root, BTRFS_I(dst), &drop_args);
  251. if (ret)
  252. goto out;
  253. ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
  254. if (ret)
  255. goto out;
  256. write_extent_buffer(path->nodes[0], inline_data,
  257. btrfs_item_ptr_offset(path->nodes[0],
  258. path->slots[0]),
  259. size);
  260. btrfs_update_inode_bytes(BTRFS_I(dst), datal, drop_args.bytes_found);
  261. btrfs_set_inode_full_sync(BTRFS_I(dst));
  262. ret = btrfs_inode_set_file_extent_range(BTRFS_I(dst), 0, aligned_end);
  263. out:
  264. if (!ret && !trans) {
  265. /*
  266. * No transaction here means we copied the inline extent into a
  267. * page of the destination inode.
  268. *
  269. * 1 unit to update inode item
  270. */
  271. trans = btrfs_start_transaction(root, 1);
  272. if (IS_ERR(trans)) {
  273. ret = PTR_ERR(trans);
  274. trans = NULL;
  275. }
  276. }
  277. if (ret && trans) {
  278. btrfs_abort_transaction(trans, ret);
  279. btrfs_end_transaction(trans);
  280. }
  281. if (!ret)
  282. *trans_out = trans;
  283. return ret;
  284. copy_to_page:
  285. /*
  286. * Release our path because we don't need it anymore and also because
  287. * copy_inline_to_page() needs to reserve data and metadata, which may
  288. * need to flush delalloc when we are low on available space and
  289. * therefore cause a deadlock if writeback of an inline extent needs to
  290. * write to the same leaf or an ordered extent completion needs to write
  291. * to the same leaf.
  292. */
  293. btrfs_release_path(path);
  294. ret = copy_inline_to_page(BTRFS_I(dst), new_key->offset,
  295. inline_data, size, datal, comp_type);
  296. goto out;
  297. }
  298. /*
  299. * Clone a range from inode file to another.
  300. *
  301. * @src: Inode to clone from
  302. * @inode: Inode to clone to
  303. * @off: Offset within source to start clone from
  304. * @olen: Original length, passed by user, of range to clone
  305. * @olen_aligned: Block-aligned value of olen
  306. * @destoff: Offset within @inode to start clone
  307. * @no_time_update: Whether to update mtime/ctime on the target inode
  308. */
  309. static int btrfs_clone(struct inode *src, struct inode *inode,
  310. const u64 off, const u64 olen, const u64 olen_aligned,
  311. const u64 destoff, int no_time_update)
  312. {
  313. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  314. struct btrfs_path *path = NULL;
  315. struct extent_buffer *leaf;
  316. struct btrfs_trans_handle *trans;
  317. char *buf = NULL;
  318. struct btrfs_key key;
  319. u32 nritems;
  320. int slot;
  321. int ret;
  322. const u64 len = olen_aligned;
  323. u64 last_dest_end = destoff;
  324. u64 prev_extent_end = off;
  325. ret = -ENOMEM;
  326. buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
  327. if (!buf)
  328. return ret;
  329. path = btrfs_alloc_path();
  330. if (!path) {
  331. kvfree(buf);
  332. return ret;
  333. }
  334. path->reada = READA_FORWARD;
  335. /* Clone data */
  336. key.objectid = btrfs_ino(BTRFS_I(src));
  337. key.type = BTRFS_EXTENT_DATA_KEY;
  338. key.offset = off;
  339. while (1) {
  340. struct btrfs_file_extent_item *extent;
  341. u64 extent_gen;
  342. int type;
  343. u32 size;
  344. struct btrfs_key new_key;
  345. u64 disko = 0, diskl = 0;
  346. u64 datao = 0, datal = 0;
  347. u8 comp;
  348. u64 drop_start;
  349. /* Note the key will change type as we walk through the tree */
  350. ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
  351. 0, 0);
  352. if (ret < 0)
  353. goto out;
  354. /*
  355. * First search, if no extent item that starts at offset off was
  356. * found but the previous item is an extent item, it's possible
  357. * it might overlap our target range, therefore process it.
  358. */
  359. if (key.offset == off && ret > 0 && path->slots[0] > 0) {
  360. btrfs_item_key_to_cpu(path->nodes[0], &key,
  361. path->slots[0] - 1);
  362. if (key.type == BTRFS_EXTENT_DATA_KEY)
  363. path->slots[0]--;
  364. }
  365. nritems = btrfs_header_nritems(path->nodes[0]);
  366. process_slot:
  367. if (path->slots[0] >= nritems) {
  368. ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
  369. if (ret < 0)
  370. goto out;
  371. if (ret > 0)
  372. break;
  373. nritems = btrfs_header_nritems(path->nodes[0]);
  374. }
  375. leaf = path->nodes[0];
  376. slot = path->slots[0];
  377. btrfs_item_key_to_cpu(leaf, &key, slot);
  378. if (key.type > BTRFS_EXTENT_DATA_KEY ||
  379. key.objectid != btrfs_ino(BTRFS_I(src)))
  380. break;
  381. ASSERT(key.type == BTRFS_EXTENT_DATA_KEY);
  382. extent = btrfs_item_ptr(leaf, slot,
  383. struct btrfs_file_extent_item);
  384. extent_gen = btrfs_file_extent_generation(leaf, extent);
  385. comp = btrfs_file_extent_compression(leaf, extent);
  386. type = btrfs_file_extent_type(leaf, extent);
  387. if (type == BTRFS_FILE_EXTENT_REG ||
  388. type == BTRFS_FILE_EXTENT_PREALLOC) {
  389. disko = btrfs_file_extent_disk_bytenr(leaf, extent);
  390. diskl = btrfs_file_extent_disk_num_bytes(leaf, extent);
  391. datao = btrfs_file_extent_offset(leaf, extent);
  392. datal = btrfs_file_extent_num_bytes(leaf, extent);
  393. } else if (type == BTRFS_FILE_EXTENT_INLINE) {
  394. /* Take upper bound, may be compressed */
  395. datal = btrfs_file_extent_ram_bytes(leaf, extent);
  396. }
  397. /*
  398. * The first search might have left us at an extent item that
  399. * ends before our target range's start, can happen if we have
  400. * holes and NO_HOLES feature enabled.
  401. *
  402. * Subsequent searches may leave us on a file range we have
  403. * processed before - this happens due to a race with ordered
  404. * extent completion for a file range that is outside our source
  405. * range, but that range was part of a file extent item that
  406. * also covered a leading part of our source range.
  407. */
  408. if (key.offset + datal <= prev_extent_end) {
  409. path->slots[0]++;
  410. goto process_slot;
  411. } else if (key.offset >= off + len) {
  412. break;
  413. }
  414. prev_extent_end = key.offset + datal;
  415. size = btrfs_item_size(leaf, slot);
  416. read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot),
  417. size);
  418. btrfs_release_path(path);
  419. memcpy(&new_key, &key, sizeof(new_key));
  420. new_key.objectid = btrfs_ino(BTRFS_I(inode));
  421. if (off <= key.offset)
  422. new_key.offset = key.offset + destoff - off;
  423. else
  424. new_key.offset = destoff;
  425. /*
  426. * Deal with a hole that doesn't have an extent item that
  427. * represents it (NO_HOLES feature enabled).
  428. * This hole is either in the middle of the cloning range or at
  429. * the beginning (fully overlaps it or partially overlaps it).
  430. */
  431. if (new_key.offset != last_dest_end)
  432. drop_start = last_dest_end;
  433. else
  434. drop_start = new_key.offset;
  435. if (type == BTRFS_FILE_EXTENT_REG ||
  436. type == BTRFS_FILE_EXTENT_PREALLOC) {
  437. struct btrfs_replace_extent_info clone_info;
  438. /*
  439. * a | --- range to clone ---| b
  440. * | ------------- extent ------------- |
  441. */
  442. /* Subtract range b */
  443. if (key.offset + datal > off + len)
  444. datal = off + len - key.offset;
  445. /* Subtract range a */
  446. if (off > key.offset) {
  447. datao += off - key.offset;
  448. datal -= off - key.offset;
  449. }
  450. clone_info.disk_offset = disko;
  451. clone_info.disk_len = diskl;
  452. clone_info.data_offset = datao;
  453. clone_info.data_len = datal;
  454. clone_info.file_offset = new_key.offset;
  455. clone_info.extent_buf = buf;
  456. clone_info.is_new_extent = false;
  457. clone_info.update_times = !no_time_update;
  458. ret = btrfs_replace_file_extents(BTRFS_I(inode), path,
  459. drop_start, new_key.offset + datal - 1,
  460. &clone_info, &trans);
  461. if (ret)
  462. goto out;
  463. } else {
  464. ASSERT(type == BTRFS_FILE_EXTENT_INLINE);
  465. /*
  466. * Inline extents always have to start at file offset 0
  467. * and can never be bigger then the sector size. We can
  468. * never clone only parts of an inline extent, since all
  469. * reflink operations must start at a sector size aligned
  470. * offset, and the length must be aligned too or end at
  471. * the i_size (which implies the whole inlined data).
  472. */
  473. ASSERT(key.offset == 0);
  474. ASSERT(datal <= fs_info->sectorsize);
  475. if (WARN_ON(type != BTRFS_FILE_EXTENT_INLINE) ||
  476. WARN_ON(key.offset != 0) ||
  477. WARN_ON(datal > fs_info->sectorsize)) {
  478. ret = -EUCLEAN;
  479. goto out;
  480. }
  481. ret = clone_copy_inline_extent(inode, path, &new_key,
  482. drop_start, datal, size,
  483. comp, buf, &trans);
  484. if (ret)
  485. goto out;
  486. }
  487. btrfs_release_path(path);
  488. /*
  489. * Whenever we share an extent we update the last_reflink_trans
  490. * of each inode to the current transaction. This is needed to
  491. * make sure fsync does not log multiple checksum items with
  492. * overlapping ranges (because some extent items might refer
  493. * only to sections of the original extent). For the destination
  494. * inode we do this regardless of the generation of the extents
  495. * or even if they are inline extents or explicit holes, to make
  496. * sure a full fsync does not skip them. For the source inode,
  497. * we only need to update last_reflink_trans in case it's a new
  498. * extent that is not a hole or an inline extent, to deal with
  499. * the checksums problem on fsync.
  500. */
  501. if (extent_gen == trans->transid && disko > 0)
  502. BTRFS_I(src)->last_reflink_trans = trans->transid;
  503. BTRFS_I(inode)->last_reflink_trans = trans->transid;
  504. last_dest_end = ALIGN(new_key.offset + datal,
  505. fs_info->sectorsize);
  506. ret = clone_finish_inode_update(trans, inode, last_dest_end,
  507. destoff, olen, no_time_update);
  508. if (ret)
  509. goto out;
  510. if (new_key.offset + datal >= destoff + len)
  511. break;
  512. btrfs_release_path(path);
  513. key.offset = prev_extent_end;
  514. if (fatal_signal_pending(current)) {
  515. ret = -EINTR;
  516. goto out;
  517. }
  518. cond_resched();
  519. }
  520. ret = 0;
  521. if (last_dest_end < destoff + len) {
  522. /*
  523. * We have an implicit hole that fully or partially overlaps our
  524. * cloning range at its end. This means that we either have the
  525. * NO_HOLES feature enabled or the implicit hole happened due to
  526. * mixing buffered and direct IO writes against this file.
  527. */
  528. btrfs_release_path(path);
  529. /*
  530. * When using NO_HOLES and we are cloning a range that covers
  531. * only a hole (no extents) into a range beyond the current
  532. * i_size, punching a hole in the target range will not create
  533. * an extent map defining a hole, because the range starts at or
  534. * beyond current i_size. If the file previously had an i_size
  535. * greater than the new i_size set by this clone operation, we
  536. * need to make sure the next fsync is a full fsync, so that it
  537. * detects and logs a hole covering a range from the current
  538. * i_size to the new i_size. If the clone range covers extents,
  539. * besides a hole, then we know the full sync flag was already
  540. * set by previous calls to btrfs_replace_file_extents() that
  541. * replaced file extent items.
  542. */
  543. if (last_dest_end >= i_size_read(inode))
  544. btrfs_set_inode_full_sync(BTRFS_I(inode));
  545. ret = btrfs_replace_file_extents(BTRFS_I(inode), path,
  546. last_dest_end, destoff + len - 1, NULL, &trans);
  547. if (ret)
  548. goto out;
  549. ret = clone_finish_inode_update(trans, inode, destoff + len,
  550. destoff, olen, no_time_update);
  551. }
  552. out:
  553. btrfs_free_path(path);
  554. kvfree(buf);
  555. clear_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &BTRFS_I(inode)->runtime_flags);
  556. return ret;
  557. }
  558. static void btrfs_double_mmap_lock(struct inode *inode1, struct inode *inode2)
  559. {
  560. if (inode1 < inode2)
  561. swap(inode1, inode2);
  562. down_write(&BTRFS_I(inode1)->i_mmap_lock);
  563. down_write_nested(&BTRFS_I(inode2)->i_mmap_lock, SINGLE_DEPTH_NESTING);
  564. }
  565. static void btrfs_double_mmap_unlock(struct inode *inode1, struct inode *inode2)
  566. {
  567. up_write(&BTRFS_I(inode1)->i_mmap_lock);
  568. up_write(&BTRFS_I(inode2)->i_mmap_lock);
  569. }
  570. static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 len,
  571. struct inode *dst, u64 dst_loff)
  572. {
  573. const u64 end = dst_loff + len - 1;
  574. struct extent_state *cached_state = NULL;
  575. struct btrfs_fs_info *fs_info = BTRFS_I(src)->root->fs_info;
  576. const u64 bs = fs_info->sectorsize;
  577. int ret;
  578. /*
  579. * Lock destination range to serialize with concurrent readahead(), and
  580. * we are safe from concurrency with relocation of source extents
  581. * because we have already locked the inode's i_mmap_lock in exclusive
  582. * mode.
  583. */
  584. lock_extent(&BTRFS_I(dst)->io_tree, dst_loff, end, &cached_state);
  585. ret = btrfs_clone(src, dst, loff, len, ALIGN(len, bs), dst_loff, 1);
  586. unlock_extent(&BTRFS_I(dst)->io_tree, dst_loff, end, &cached_state);
  587. btrfs_btree_balance_dirty(fs_info);
  588. return ret;
  589. }
  590. static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
  591. struct inode *dst, u64 dst_loff)
  592. {
  593. int ret = 0;
  594. u64 i, tail_len, chunk_count;
  595. struct btrfs_root *root_dst = BTRFS_I(dst)->root;
  596. spin_lock(&root_dst->root_item_lock);
  597. if (root_dst->send_in_progress) {
  598. btrfs_warn_rl(root_dst->fs_info,
  599. "cannot deduplicate to root %llu while send operations are using it (%d in progress)",
  600. btrfs_root_id(root_dst),
  601. root_dst->send_in_progress);
  602. spin_unlock(&root_dst->root_item_lock);
  603. return -EAGAIN;
  604. }
  605. root_dst->dedupe_in_progress++;
  606. spin_unlock(&root_dst->root_item_lock);
  607. tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
  608. chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
  609. for (i = 0; i < chunk_count; i++) {
  610. ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
  611. dst, dst_loff);
  612. if (ret)
  613. goto out;
  614. loff += BTRFS_MAX_DEDUPE_LEN;
  615. dst_loff += BTRFS_MAX_DEDUPE_LEN;
  616. }
  617. if (tail_len > 0)
  618. ret = btrfs_extent_same_range(src, loff, tail_len, dst, dst_loff);
  619. out:
  620. spin_lock(&root_dst->root_item_lock);
  621. root_dst->dedupe_in_progress--;
  622. spin_unlock(&root_dst->root_item_lock);
  623. return ret;
  624. }
  625. static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
  626. u64 off, u64 olen, u64 destoff)
  627. {
  628. struct extent_state *cached_state = NULL;
  629. struct inode *inode = file_inode(file);
  630. struct inode *src = file_inode(file_src);
  631. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  632. int ret;
  633. int wb_ret;
  634. u64 len = olen;
  635. u64 bs = fs_info->sectorsize;
  636. u64 end;
  637. /*
  638. * VFS's generic_remap_file_range_prep() protects us from cloning the
  639. * eof block into the middle of a file, which would result in corruption
  640. * if the file size is not blocksize aligned. So we don't need to check
  641. * for that case here.
  642. */
  643. if (off + len == src->i_size)
  644. len = ALIGN(src->i_size, bs) - off;
  645. if (destoff > inode->i_size) {
  646. const u64 wb_start = ALIGN_DOWN(inode->i_size, bs);
  647. ret = btrfs_cont_expand(BTRFS_I(inode), inode->i_size, destoff);
  648. if (ret)
  649. return ret;
  650. /*
  651. * We may have truncated the last block if the inode's size is
  652. * not sector size aligned, so we need to wait for writeback to
  653. * complete before proceeding further, otherwise we can race
  654. * with cloning and attempt to increment a reference to an
  655. * extent that no longer exists (writeback completed right after
  656. * we found the previous extent covering eof and before we
  657. * attempted to increment its reference count).
  658. */
  659. ret = btrfs_wait_ordered_range(BTRFS_I(inode), wb_start,
  660. destoff - wb_start);
  661. if (ret)
  662. return ret;
  663. }
  664. /*
  665. * Lock destination range to serialize with concurrent readahead(), and
  666. * we are safe from concurrency with relocation of source extents
  667. * because we have already locked the inode's i_mmap_lock in exclusive
  668. * mode.
  669. */
  670. end = destoff + len - 1;
  671. lock_extent(&BTRFS_I(inode)->io_tree, destoff, end, &cached_state);
  672. ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
  673. unlock_extent(&BTRFS_I(inode)->io_tree, destoff, end, &cached_state);
  674. /*
  675. * We may have copied an inline extent into a page of the destination
  676. * range, so wait for writeback to complete before truncating pages
  677. * from the page cache. This is a rare case.
  678. */
  679. wb_ret = btrfs_wait_ordered_range(BTRFS_I(inode), destoff, len);
  680. ret = ret ? ret : wb_ret;
  681. /*
  682. * Truncate page cache pages so that future reads will see the cloned
  683. * data immediately and not the previous data.
  684. */
  685. truncate_inode_pages_range(&inode->i_data,
  686. round_down(destoff, PAGE_SIZE),
  687. round_up(destoff + len, PAGE_SIZE) - 1);
  688. btrfs_btree_balance_dirty(fs_info);
  689. return ret;
  690. }
  691. static int btrfs_remap_file_range_prep(struct file *file_in, loff_t pos_in,
  692. struct file *file_out, loff_t pos_out,
  693. loff_t *len, unsigned int remap_flags)
  694. {
  695. struct inode *inode_in = file_inode(file_in);
  696. struct inode *inode_out = file_inode(file_out);
  697. u64 bs = BTRFS_I(inode_out)->root->fs_info->sectorsize;
  698. u64 wb_len;
  699. int ret;
  700. if (!(remap_flags & REMAP_FILE_DEDUP)) {
  701. struct btrfs_root *root_out = BTRFS_I(inode_out)->root;
  702. if (btrfs_root_readonly(root_out))
  703. return -EROFS;
  704. ASSERT(inode_in->i_sb == inode_out->i_sb);
  705. }
  706. /* Don't make the dst file partly checksummed */
  707. if ((BTRFS_I(inode_in)->flags & BTRFS_INODE_NODATASUM) !=
  708. (BTRFS_I(inode_out)->flags & BTRFS_INODE_NODATASUM)) {
  709. return -EINVAL;
  710. }
  711. /*
  712. * Now that the inodes are locked, we need to start writeback ourselves
  713. * and can not rely on the writeback from the VFS's generic helper
  714. * generic_remap_file_range_prep() because:
  715. *
  716. * 1) For compression we must call filemap_fdatawrite_range() range
  717. * twice (btrfs_fdatawrite_range() does it for us), and the generic
  718. * helper only calls it once;
  719. *
  720. * 2) filemap_fdatawrite_range(), called by the generic helper only
  721. * waits for the writeback to complete, i.e. for IO to be done, and
  722. * not for the ordered extents to complete. We need to wait for them
  723. * to complete so that new file extent items are in the fs tree.
  724. */
  725. if (*len == 0 && !(remap_flags & REMAP_FILE_DEDUP))
  726. wb_len = ALIGN(inode_in->i_size, bs) - ALIGN_DOWN(pos_in, bs);
  727. else
  728. wb_len = ALIGN(*len, bs);
  729. /*
  730. * Workaround to make sure NOCOW buffered write reach disk as NOCOW.
  731. *
  732. * Btrfs' back references do not have a block level granularity, they
  733. * work at the whole extent level.
  734. * NOCOW buffered write without data space reserved may not be able
  735. * to fall back to CoW due to lack of data space, thus could cause
  736. * data loss.
  737. *
  738. * Here we take a shortcut by flushing the whole inode, so that all
  739. * nocow write should reach disk as nocow before we increase the
  740. * reference of the extent. We could do better by only flushing NOCOW
  741. * data, but that needs extra accounting.
  742. *
  743. * Also we don't need to check ASYNC_EXTENT, as async extent will be
  744. * CoWed anyway, not affecting nocow part.
  745. */
  746. ret = filemap_flush(inode_in->i_mapping);
  747. if (ret < 0)
  748. return ret;
  749. ret = btrfs_wait_ordered_range(BTRFS_I(inode_in), ALIGN_DOWN(pos_in, bs),
  750. wb_len);
  751. if (ret < 0)
  752. return ret;
  753. ret = btrfs_wait_ordered_range(BTRFS_I(inode_out), ALIGN_DOWN(pos_out, bs),
  754. wb_len);
  755. if (ret < 0)
  756. return ret;
  757. return generic_remap_file_range_prep(file_in, pos_in, file_out, pos_out,
  758. len, remap_flags);
  759. }
  760. static bool file_sync_write(const struct file *file)
  761. {
  762. if (file->f_flags & (__O_SYNC | O_DSYNC))
  763. return true;
  764. if (IS_SYNC(file_inode(file)))
  765. return true;
  766. return false;
  767. }
  768. loff_t btrfs_remap_file_range(struct file *src_file, loff_t off,
  769. struct file *dst_file, loff_t destoff, loff_t len,
  770. unsigned int remap_flags)
  771. {
  772. struct inode *src_inode = file_inode(src_file);
  773. struct inode *dst_inode = file_inode(dst_file);
  774. bool same_inode = dst_inode == src_inode;
  775. int ret;
  776. if (remap_flags & ~(REMAP_FILE_DEDUP | REMAP_FILE_ADVISORY))
  777. return -EINVAL;
  778. if (same_inode) {
  779. btrfs_inode_lock(BTRFS_I(src_inode), BTRFS_ILOCK_MMAP);
  780. } else {
  781. lock_two_nondirectories(src_inode, dst_inode);
  782. btrfs_double_mmap_lock(src_inode, dst_inode);
  783. }
  784. ret = btrfs_remap_file_range_prep(src_file, off, dst_file, destoff,
  785. &len, remap_flags);
  786. if (ret < 0 || len == 0)
  787. goto out_unlock;
  788. if (remap_flags & REMAP_FILE_DEDUP)
  789. ret = btrfs_extent_same(src_inode, off, len, dst_inode, destoff);
  790. else
  791. ret = btrfs_clone_files(dst_file, src_file, off, len, destoff);
  792. out_unlock:
  793. if (same_inode) {
  794. btrfs_inode_unlock(BTRFS_I(src_inode), BTRFS_ILOCK_MMAP);
  795. } else {
  796. btrfs_double_mmap_unlock(src_inode, dst_inode);
  797. unlock_two_nondirectories(src_inode, dst_inode);
  798. }
  799. /*
  800. * If either the source or the destination file was opened with O_SYNC,
  801. * O_DSYNC or has the S_SYNC attribute, fsync both the destination and
  802. * source files/ranges, so that after a successful return (0) followed
  803. * by a power failure results in the reflinked data to be readable from
  804. * both files/ranges.
  805. */
  806. if (ret == 0 && len > 0 &&
  807. (file_sync_write(src_file) || file_sync_write(dst_file))) {
  808. ret = btrfs_sync_file(src_file, off, off + len - 1, 0);
  809. if (ret == 0)
  810. ret = btrfs_sync_file(dst_file, destoff,
  811. destoff + len - 1, 0);
  812. }
  813. return ret < 0 ? ret : len;
  814. }