]> git.ipfire.org Git - people/ms/linux.git/blame - fs/btrfs/tree-log.c
Btrfs: fix use-after-free on root->orphan_block_rsv
[people/ms/linux.git] / fs / btrfs / tree-log.c
CommitLineData
e02119d5
CM
1/*
2 * Copyright (C) 2008 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
19#include <linux/sched.h>
5a0e3ad6 20#include <linux/slab.h>
c6adc9cc 21#include <linux/blkdev.h>
5dc562c5 22#include <linux/list_sort.h>
995946dd 23#include "tree-log.h"
e02119d5
CM
24#include "disk-io.h"
25#include "locking.h"
26#include "print-tree.h"
f186373f 27#include "backref.h"
f186373f 28#include "hash.h"
ebb8765b 29#include "compression.h"
df2c95f3 30#include "qgroup.h"
e02119d5
CM
31
32/* magic values for the inode_only field in btrfs_log_inode:
33 *
34 * LOG_INODE_ALL means to log everything
35 * LOG_INODE_EXISTS means to log just enough to recreate the inode
36 * during log replay
37 */
38#define LOG_INODE_ALL 0
39#define LOG_INODE_EXISTS 1
781feef7 40#define LOG_OTHER_INODE 2
e02119d5 41
12fcfd22
CM
42/*
43 * directory trouble cases
44 *
45 * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
46 * log, we must force a full commit before doing an fsync of the directory
47 * where the unlink was done.
48 * ---> record transid of last unlink/rename per directory
49 *
50 * mkdir foo/some_dir
51 * normal commit
52 * rename foo/some_dir foo2/some_dir
53 * mkdir foo/some_dir
54 * fsync foo/some_dir/some_file
55 *
56 * The fsync above will unlink the original some_dir without recording
57 * it in its new location (foo2). After a crash, some_dir will be gone
58 * unless the fsync of some_file forces a full commit
59 *
60 * 2) we must log any new names for any file or dir that is in the fsync
61 * log. ---> check inode while renaming/linking.
62 *
63 * 2a) we must log any new names for any file or dir during rename
64 * when the directory they are being removed from was logged.
65 * ---> check inode and old parent dir during rename
66 *
67 * 2a is actually the more important variant. With the extra logging
68 * a crash might unlink the old name without recreating the new one
69 *
70 * 3) after a crash, we must go through any directories with a link count
71 * of zero and redo the rm -rf
72 *
73 * mkdir f1/foo
74 * normal commit
75 * rm -rf f1/foo
76 * fsync(f1)
77 *
78 * The directory f1 was fully removed from the FS, but fsync was never
79 * called on f1, only its parent dir. After a crash the rm -rf must
80 * be replayed. This must be able to recurse down the entire
81 * directory tree. The inode link count fixup code takes care of the
82 * ugly details.
83 */
84
e02119d5
CM
85/*
86 * stages for the tree walking. The first
87 * stage (0) is to only pin down the blocks we find
88 * the second stage (1) is to make sure that all the inodes
89 * we find in the log are created in the subvolume.
90 *
91 * The last stage is to deal with directories and links and extents
92 * and all the other fun semantics
93 */
94#define LOG_WALK_PIN_ONLY 0
95#define LOG_WALK_REPLAY_INODES 1
dd8e7217
JB
96#define LOG_WALK_REPLAY_DIR_INDEX 2
97#define LOG_WALK_REPLAY_ALL 3
e02119d5 98
12fcfd22 99static int btrfs_log_inode(struct btrfs_trans_handle *trans,
a59108a7 100 struct btrfs_root *root, struct btrfs_inode *inode,
49dae1bc
FM
101 int inode_only,
102 const loff_t start,
8407f553
FM
103 const loff_t end,
104 struct btrfs_log_ctx *ctx);
ec051c0f
YZ
105static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
106 struct btrfs_root *root,
107 struct btrfs_path *path, u64 objectid);
12fcfd22
CM
108static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
109 struct btrfs_root *root,
110 struct btrfs_root *log,
111 struct btrfs_path *path,
112 u64 dirid, int del_all);
e02119d5
CM
113
114/*
115 * tree logging is a special write ahead log used to make sure that
116 * fsyncs and O_SYNCs can happen without doing full tree commits.
117 *
118 * Full tree commits are expensive because they require commonly
119 * modified blocks to be recowed, creating many dirty pages in the
120 * extent tree an 4x-6x higher write load than ext3.
121 *
122 * Instead of doing a tree commit on every fsync, we use the
123 * key ranges and transaction ids to find items for a given file or directory
124 * that have changed in this transaction. Those items are copied into
125 * a special tree (one per subvolume root), that tree is written to disk
126 * and then the fsync is considered complete.
127 *
128 * After a crash, items are copied out of the log-tree back into the
129 * subvolume tree. Any file data extents found are recorded in the extent
130 * allocation tree, and the log-tree freed.
131 *
132 * The log tree is read three times, once to pin down all the extents it is
133 * using in ram and once, once to create all the inodes logged in the tree
134 * and once to do all the other items.
135 */
136
e02119d5
CM
137/*
138 * start a sub transaction and setup the log tree
139 * this increments the log tree writer count to make the people
140 * syncing the tree wait for us to finish
141 */
142static int start_log_trans(struct btrfs_trans_handle *trans,
8b050d35
MX
143 struct btrfs_root *root,
144 struct btrfs_log_ctx *ctx)
e02119d5 145{
0b246afa 146 struct btrfs_fs_info *fs_info = root->fs_info;
34eb2a52 147 int ret = 0;
7237f183
YZ
148
149 mutex_lock(&root->log_mutex);
34eb2a52 150
7237f183 151 if (root->log_root) {
0b246afa 152 if (btrfs_need_log_full_commit(fs_info, trans)) {
50471a38
MX
153 ret = -EAGAIN;
154 goto out;
155 }
34eb2a52 156
ff782e0a 157 if (!root->log_start_pid) {
27cdeb70 158 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
34eb2a52 159 root->log_start_pid = current->pid;
ff782e0a 160 } else if (root->log_start_pid != current->pid) {
27cdeb70 161 set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
ff782e0a 162 }
34eb2a52 163 } else {
0b246afa
JM
164 mutex_lock(&fs_info->tree_log_mutex);
165 if (!fs_info->log_root_tree)
166 ret = btrfs_init_log_root_tree(trans, fs_info);
167 mutex_unlock(&fs_info->tree_log_mutex);
34eb2a52
Z
168 if (ret)
169 goto out;
ff782e0a 170
e02119d5 171 ret = btrfs_add_log_tree(trans, root);
4a500fd1 172 if (ret)
e87ac136 173 goto out;
34eb2a52
Z
174
175 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
176 root->log_start_pid = current->pid;
e02119d5 177 }
34eb2a52 178
2ecb7923 179 atomic_inc(&root->log_batch);
7237f183 180 atomic_inc(&root->log_writers);
8b050d35 181 if (ctx) {
34eb2a52 182 int index = root->log_transid % 2;
8b050d35 183 list_add_tail(&ctx->list, &root->log_ctxs[index]);
d1433deb 184 ctx->log_transid = root->log_transid;
8b050d35 185 }
34eb2a52 186
e87ac136 187out:
7237f183 188 mutex_unlock(&root->log_mutex);
e87ac136 189 return ret;
e02119d5
CM
190}
191
192/*
193 * returns 0 if there was a log transaction running and we were able
194 * to join, or returns -ENOENT if there were not transactions
195 * in progress
196 */
197static int join_running_log_trans(struct btrfs_root *root)
198{
199 int ret = -ENOENT;
200
201 smp_mb();
202 if (!root->log_root)
203 return -ENOENT;
204
7237f183 205 mutex_lock(&root->log_mutex);
e02119d5
CM
206 if (root->log_root) {
207 ret = 0;
7237f183 208 atomic_inc(&root->log_writers);
e02119d5 209 }
7237f183 210 mutex_unlock(&root->log_mutex);
e02119d5
CM
211 return ret;
212}
213
12fcfd22
CM
214/*
215 * This either makes the current running log transaction wait
216 * until you call btrfs_end_log_trans() or it makes any future
217 * log transactions wait until you call btrfs_end_log_trans()
218 */
219int btrfs_pin_log_trans(struct btrfs_root *root)
220{
221 int ret = -ENOENT;
222
223 mutex_lock(&root->log_mutex);
224 atomic_inc(&root->log_writers);
225 mutex_unlock(&root->log_mutex);
226 return ret;
227}
228
e02119d5
CM
229/*
230 * indicate we're done making changes to the log tree
231 * and wake up anyone waiting to do a sync
232 */
143bede5 233void btrfs_end_log_trans(struct btrfs_root *root)
e02119d5 234{
7237f183 235 if (atomic_dec_and_test(&root->log_writers)) {
779adf0f
DS
236 /*
237 * Implicit memory barrier after atomic_dec_and_test
238 */
7237f183
YZ
239 if (waitqueue_active(&root->log_writer_wait))
240 wake_up(&root->log_writer_wait);
241 }
e02119d5
CM
242}
243
244
245/*
246 * the walk control struct is used to pass state down the chain when
247 * processing the log tree. The stage field tells us which part
248 * of the log tree processing we are currently doing. The others
249 * are state fields used for that specific part
250 */
251struct walk_control {
252 /* should we free the extent on disk when done? This is used
253 * at transaction commit time while freeing a log tree
254 */
255 int free;
256
257 /* should we write out the extent buffer? This is used
258 * while flushing the log tree to disk during a sync
259 */
260 int write;
261
262 /* should we wait for the extent buffer io to finish? Also used
263 * while flushing the log tree to disk for a sync
264 */
265 int wait;
266
267 /* pin only walk, we record which extents on disk belong to the
268 * log trees
269 */
270 int pin;
271
272 /* what stage of the replay code we're currently in */
273 int stage;
274
275 /* the root we are currently replaying */
276 struct btrfs_root *replay_dest;
277
278 /* the trans handle for the current replay */
279 struct btrfs_trans_handle *trans;
280
281 /* the function that gets used to process blocks we find in the
282 * tree. Note the extent_buffer might not be up to date when it is
283 * passed in, and it must be checked or read if you need the data
284 * inside it
285 */
286 int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
287 struct walk_control *wc, u64 gen);
288};
289
290/*
291 * process_func used to pin down extents, write them or wait on them
292 */
293static int process_one_buffer(struct btrfs_root *log,
294 struct extent_buffer *eb,
295 struct walk_control *wc, u64 gen)
296{
0b246afa 297 struct btrfs_fs_info *fs_info = log->fs_info;
b50c6e25
JB
298 int ret = 0;
299
8c2a1a30
JB
300 /*
301 * If this fs is mixed then we need to be able to process the leaves to
302 * pin down any logged extents, so we have to read the block.
303 */
0b246afa 304 if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8c2a1a30
JB
305 ret = btrfs_read_buffer(eb, gen);
306 if (ret)
307 return ret;
308 }
309
04018de5 310 if (wc->pin)
2ff7e61e
JM
311 ret = btrfs_pin_extent_for_log_replay(fs_info, eb->start,
312 eb->len);
e02119d5 313
b50c6e25 314 if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
8c2a1a30 315 if (wc->pin && btrfs_header_level(eb) == 0)
2ff7e61e 316 ret = btrfs_exclude_logged_extents(fs_info, eb);
e02119d5
CM
317 if (wc->write)
318 btrfs_write_tree_block(eb);
319 if (wc->wait)
320 btrfs_wait_tree_block_writeback(eb);
321 }
b50c6e25 322 return ret;
e02119d5
CM
323}
324
325/*
326 * Item overwrite used by replay and tree logging. eb, slot and key all refer
327 * to the src data we are copying out.
328 *
329 * root is the tree we are copying into, and path is a scratch
330 * path for use in this function (it should be released on entry and
331 * will be released on exit).
332 *
333 * If the key is already in the destination tree the existing item is
334 * overwritten. If the existing item isn't big enough, it is extended.
335 * If it is too large, it is truncated.
336 *
337 * If the key isn't in the destination yet, a new item is inserted.
338 */
339static noinline int overwrite_item(struct btrfs_trans_handle *trans,
340 struct btrfs_root *root,
341 struct btrfs_path *path,
342 struct extent_buffer *eb, int slot,
343 struct btrfs_key *key)
344{
2ff7e61e 345 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5
CM
346 int ret;
347 u32 item_size;
348 u64 saved_i_size = 0;
349 int save_old_i_size = 0;
350 unsigned long src_ptr;
351 unsigned long dst_ptr;
352 int overwrite_root = 0;
4bc4bee4 353 bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
e02119d5
CM
354
355 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
356 overwrite_root = 1;
357
358 item_size = btrfs_item_size_nr(eb, slot);
359 src_ptr = btrfs_item_ptr_offset(eb, slot);
360
361 /* look for the key in the destination tree */
362 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
4bc4bee4
JB
363 if (ret < 0)
364 return ret;
365
e02119d5
CM
366 if (ret == 0) {
367 char *src_copy;
368 char *dst_copy;
369 u32 dst_size = btrfs_item_size_nr(path->nodes[0],
370 path->slots[0]);
371 if (dst_size != item_size)
372 goto insert;
373
374 if (item_size == 0) {
b3b4aa74 375 btrfs_release_path(path);
e02119d5
CM
376 return 0;
377 }
378 dst_copy = kmalloc(item_size, GFP_NOFS);
379 src_copy = kmalloc(item_size, GFP_NOFS);
2a29edc6 380 if (!dst_copy || !src_copy) {
b3b4aa74 381 btrfs_release_path(path);
2a29edc6 382 kfree(dst_copy);
383 kfree(src_copy);
384 return -ENOMEM;
385 }
e02119d5
CM
386
387 read_extent_buffer(eb, src_copy, src_ptr, item_size);
388
389 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
390 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
391 item_size);
392 ret = memcmp(dst_copy, src_copy, item_size);
393
394 kfree(dst_copy);
395 kfree(src_copy);
396 /*
397 * they have the same contents, just return, this saves
398 * us from cowing blocks in the destination tree and doing
399 * extra writes that may not have been done by a previous
400 * sync
401 */
402 if (ret == 0) {
b3b4aa74 403 btrfs_release_path(path);
e02119d5
CM
404 return 0;
405 }
406
4bc4bee4
JB
407 /*
408 * We need to load the old nbytes into the inode so when we
409 * replay the extents we've logged we get the right nbytes.
410 */
411 if (inode_item) {
412 struct btrfs_inode_item *item;
413 u64 nbytes;
d555438b 414 u32 mode;
4bc4bee4
JB
415
416 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
417 struct btrfs_inode_item);
418 nbytes = btrfs_inode_nbytes(path->nodes[0], item);
419 item = btrfs_item_ptr(eb, slot,
420 struct btrfs_inode_item);
421 btrfs_set_inode_nbytes(eb, item, nbytes);
d555438b
JB
422
423 /*
424 * If this is a directory we need to reset the i_size to
425 * 0 so that we can set it up properly when replaying
426 * the rest of the items in this log.
427 */
428 mode = btrfs_inode_mode(eb, item);
429 if (S_ISDIR(mode))
430 btrfs_set_inode_size(eb, item, 0);
4bc4bee4
JB
431 }
432 } else if (inode_item) {
433 struct btrfs_inode_item *item;
d555438b 434 u32 mode;
4bc4bee4
JB
435
436 /*
437 * New inode, set nbytes to 0 so that the nbytes comes out
438 * properly when we replay the extents.
439 */
440 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
441 btrfs_set_inode_nbytes(eb, item, 0);
d555438b
JB
442
443 /*
444 * If this is a directory we need to reset the i_size to 0 so
445 * that we can set it up properly when replaying the rest of
446 * the items in this log.
447 */
448 mode = btrfs_inode_mode(eb, item);
449 if (S_ISDIR(mode))
450 btrfs_set_inode_size(eb, item, 0);
e02119d5
CM
451 }
452insert:
b3b4aa74 453 btrfs_release_path(path);
e02119d5 454 /* try to insert the key into the destination tree */
df8d116f 455 path->skip_release_on_error = 1;
e02119d5
CM
456 ret = btrfs_insert_empty_item(trans, root, path,
457 key, item_size);
df8d116f 458 path->skip_release_on_error = 0;
e02119d5
CM
459
460 /* make sure any existing item is the correct size */
df8d116f 461 if (ret == -EEXIST || ret == -EOVERFLOW) {
e02119d5
CM
462 u32 found_size;
463 found_size = btrfs_item_size_nr(path->nodes[0],
464 path->slots[0]);
143bede5 465 if (found_size > item_size)
2ff7e61e 466 btrfs_truncate_item(fs_info, path, item_size, 1);
143bede5 467 else if (found_size < item_size)
2ff7e61e 468 btrfs_extend_item(fs_info, path,
143bede5 469 item_size - found_size);
e02119d5 470 } else if (ret) {
4a500fd1 471 return ret;
e02119d5
CM
472 }
473 dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
474 path->slots[0]);
475
476 /* don't overwrite an existing inode if the generation number
477 * was logged as zero. This is done when the tree logging code
478 * is just logging an inode to make sure it exists after recovery.
479 *
480 * Also, don't overwrite i_size on directories during replay.
481 * log replay inserts and removes directory items based on the
482 * state of the tree found in the subvolume, and i_size is modified
483 * as it goes
484 */
485 if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
486 struct btrfs_inode_item *src_item;
487 struct btrfs_inode_item *dst_item;
488
489 src_item = (struct btrfs_inode_item *)src_ptr;
490 dst_item = (struct btrfs_inode_item *)dst_ptr;
491
1a4bcf47
FM
492 if (btrfs_inode_generation(eb, src_item) == 0) {
493 struct extent_buffer *dst_eb = path->nodes[0];
2f2ff0ee 494 const u64 ino_size = btrfs_inode_size(eb, src_item);
1a4bcf47 495
2f2ff0ee
FM
496 /*
497 * For regular files an ino_size == 0 is used only when
498 * logging that an inode exists, as part of a directory
499 * fsync, and the inode wasn't fsynced before. In this
500 * case don't set the size of the inode in the fs/subvol
501 * tree, otherwise we would be throwing valid data away.
502 */
1a4bcf47 503 if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
2f2ff0ee
FM
504 S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
505 ino_size != 0) {
1a4bcf47 506 struct btrfs_map_token token;
1a4bcf47
FM
507
508 btrfs_init_map_token(&token);
509 btrfs_set_token_inode_size(dst_eb, dst_item,
510 ino_size, &token);
511 }
e02119d5 512 goto no_copy;
1a4bcf47 513 }
e02119d5
CM
514
515 if (overwrite_root &&
516 S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
517 S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
518 save_old_i_size = 1;
519 saved_i_size = btrfs_inode_size(path->nodes[0],
520 dst_item);
521 }
522 }
523
524 copy_extent_buffer(path->nodes[0], eb, dst_ptr,
525 src_ptr, item_size);
526
527 if (save_old_i_size) {
528 struct btrfs_inode_item *dst_item;
529 dst_item = (struct btrfs_inode_item *)dst_ptr;
530 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
531 }
532
533 /* make sure the generation is filled in */
534 if (key->type == BTRFS_INODE_ITEM_KEY) {
535 struct btrfs_inode_item *dst_item;
536 dst_item = (struct btrfs_inode_item *)dst_ptr;
537 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
538 btrfs_set_inode_generation(path->nodes[0], dst_item,
539 trans->transid);
540 }
541 }
542no_copy:
543 btrfs_mark_buffer_dirty(path->nodes[0]);
b3b4aa74 544 btrfs_release_path(path);
e02119d5
CM
545 return 0;
546}
547
548/*
549 * simple helper to read an inode off the disk from a given root
550 * This can only be called for subvolume roots and not for the log
551 */
552static noinline struct inode *read_one_inode(struct btrfs_root *root,
553 u64 objectid)
554{
5d4f98a2 555 struct btrfs_key key;
e02119d5 556 struct inode *inode;
e02119d5 557
5d4f98a2
YZ
558 key.objectid = objectid;
559 key.type = BTRFS_INODE_ITEM_KEY;
560 key.offset = 0;
73f73415 561 inode = btrfs_iget(root->fs_info->sb, &key, root, NULL);
5d4f98a2
YZ
562 if (IS_ERR(inode)) {
563 inode = NULL;
564 } else if (is_bad_inode(inode)) {
e02119d5
CM
565 iput(inode);
566 inode = NULL;
567 }
568 return inode;
569}
570
571/* replays a single extent in 'eb' at 'slot' with 'key' into the
572 * subvolume 'root'. path is released on entry and should be released
573 * on exit.
574 *
575 * extents in the log tree have not been allocated out of the extent
576 * tree yet. So, this completes the allocation, taking a reference
577 * as required if the extent already exists or creating a new extent
578 * if it isn't in the extent allocation tree yet.
579 *
580 * The extent is inserted into the file, dropping any existing extents
581 * from the file that overlap the new one.
582 */
583static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
584 struct btrfs_root *root,
585 struct btrfs_path *path,
586 struct extent_buffer *eb, int slot,
587 struct btrfs_key *key)
588{
0b246afa 589 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5 590 int found_type;
e02119d5 591 u64 extent_end;
e02119d5 592 u64 start = key->offset;
4bc4bee4 593 u64 nbytes = 0;
e02119d5
CM
594 struct btrfs_file_extent_item *item;
595 struct inode *inode = NULL;
596 unsigned long size;
597 int ret = 0;
598
599 item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
600 found_type = btrfs_file_extent_type(eb, item);
601
d899e052 602 if (found_type == BTRFS_FILE_EXTENT_REG ||
4bc4bee4
JB
603 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
604 nbytes = btrfs_file_extent_num_bytes(eb, item);
605 extent_end = start + nbytes;
606
607 /*
608 * We don't add to the inodes nbytes if we are prealloc or a
609 * hole.
610 */
611 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
612 nbytes = 0;
613 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
514ac8ad 614 size = btrfs_file_extent_inline_len(eb, slot, item);
4bc4bee4 615 nbytes = btrfs_file_extent_ram_bytes(eb, item);
da17066c 616 extent_end = ALIGN(start + size,
0b246afa 617 fs_info->sectorsize);
e02119d5
CM
618 } else {
619 ret = 0;
620 goto out;
621 }
622
623 inode = read_one_inode(root, key->objectid);
624 if (!inode) {
625 ret = -EIO;
626 goto out;
627 }
628
629 /*
630 * first check to see if we already have this extent in the
631 * file. This must be done before the btrfs_drop_extents run
632 * so we don't try to drop this extent.
633 */
f85b7379
DS
634 ret = btrfs_lookup_file_extent(trans, root, path,
635 btrfs_ino(BTRFS_I(inode)), start, 0);
e02119d5 636
d899e052
YZ
637 if (ret == 0 &&
638 (found_type == BTRFS_FILE_EXTENT_REG ||
639 found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
e02119d5
CM
640 struct btrfs_file_extent_item cmp1;
641 struct btrfs_file_extent_item cmp2;
642 struct btrfs_file_extent_item *existing;
643 struct extent_buffer *leaf;
644
645 leaf = path->nodes[0];
646 existing = btrfs_item_ptr(leaf, path->slots[0],
647 struct btrfs_file_extent_item);
648
649 read_extent_buffer(eb, &cmp1, (unsigned long)item,
650 sizeof(cmp1));
651 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
652 sizeof(cmp2));
653
654 /*
655 * we already have a pointer to this exact extent,
656 * we don't have to do anything
657 */
658 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
b3b4aa74 659 btrfs_release_path(path);
e02119d5
CM
660 goto out;
661 }
662 }
b3b4aa74 663 btrfs_release_path(path);
e02119d5
CM
664
665 /* drop any overlapping extents */
2671485d 666 ret = btrfs_drop_extents(trans, root, inode, start, extent_end, 1);
3650860b
JB
667 if (ret)
668 goto out;
e02119d5 669
07d400a6
YZ
670 if (found_type == BTRFS_FILE_EXTENT_REG ||
671 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5d4f98a2 672 u64 offset;
07d400a6
YZ
673 unsigned long dest_offset;
674 struct btrfs_key ins;
675
3168021c
FM
676 if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
677 btrfs_fs_incompat(fs_info, NO_HOLES))
678 goto update_inode;
679
07d400a6
YZ
680 ret = btrfs_insert_empty_item(trans, root, path, key,
681 sizeof(*item));
3650860b
JB
682 if (ret)
683 goto out;
07d400a6
YZ
684 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
685 path->slots[0]);
686 copy_extent_buffer(path->nodes[0], eb, dest_offset,
687 (unsigned long)item, sizeof(*item));
688
689 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
690 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
691 ins.type = BTRFS_EXTENT_ITEM_KEY;
5d4f98a2 692 offset = key->offset - btrfs_file_extent_offset(eb, item);
07d400a6 693
df2c95f3
QW
694 /*
695 * Manually record dirty extent, as here we did a shallow
696 * file extent item copy and skip normal backref update,
697 * but modifying extent tree all by ourselves.
698 * So need to manually record dirty extent for qgroup,
699 * as the owner of the file extent changed from log tree
700 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
701 */
0b246afa 702 ret = btrfs_qgroup_trace_extent(trans, fs_info,
df2c95f3
QW
703 btrfs_file_extent_disk_bytenr(eb, item),
704 btrfs_file_extent_disk_num_bytes(eb, item),
705 GFP_NOFS);
706 if (ret < 0)
707 goto out;
708
07d400a6
YZ
709 if (ins.objectid > 0) {
710 u64 csum_start;
711 u64 csum_end;
712 LIST_HEAD(ordered_sums);
713 /*
714 * is this extent already allocated in the extent
715 * allocation tree? If so, just add a reference
716 */
2ff7e61e 717 ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
07d400a6
YZ
718 ins.offset);
719 if (ret == 0) {
84f7d8e6 720 ret = btrfs_inc_extent_ref(trans, root,
07d400a6 721 ins.objectid, ins.offset,
5d4f98a2 722 0, root->root_key.objectid,
b06c4bf5 723 key->objectid, offset);
b50c6e25
JB
724 if (ret)
725 goto out;
07d400a6
YZ
726 } else {
727 /*
728 * insert the extent pointer in the extent
729 * allocation tree
730 */
5d4f98a2 731 ret = btrfs_alloc_logged_file_extent(trans,
2ff7e61e
JM
732 fs_info,
733 root->root_key.objectid,
5d4f98a2 734 key->objectid, offset, &ins);
b50c6e25
JB
735 if (ret)
736 goto out;
07d400a6 737 }
b3b4aa74 738 btrfs_release_path(path);
07d400a6
YZ
739
740 if (btrfs_file_extent_compression(eb, item)) {
741 csum_start = ins.objectid;
742 csum_end = csum_start + ins.offset;
743 } else {
744 csum_start = ins.objectid +
745 btrfs_file_extent_offset(eb, item);
746 csum_end = csum_start +
747 btrfs_file_extent_num_bytes(eb, item);
748 }
749
750 ret = btrfs_lookup_csums_range(root->log_root,
751 csum_start, csum_end - 1,
a2de733c 752 &ordered_sums, 0);
3650860b
JB
753 if (ret)
754 goto out;
b84b8390
FM
755 /*
756 * Now delete all existing cums in the csum root that
757 * cover our range. We do this because we can have an
758 * extent that is completely referenced by one file
759 * extent item and partially referenced by another
760 * file extent item (like after using the clone or
761 * extent_same ioctls). In this case if we end up doing
762 * the replay of the one that partially references the
763 * extent first, and we do not do the csum deletion
764 * below, we can get 2 csum items in the csum tree that
765 * overlap each other. For example, imagine our log has
766 * the two following file extent items:
767 *
768 * key (257 EXTENT_DATA 409600)
769 * extent data disk byte 12845056 nr 102400
770 * extent data offset 20480 nr 20480 ram 102400
771 *
772 * key (257 EXTENT_DATA 819200)
773 * extent data disk byte 12845056 nr 102400
774 * extent data offset 0 nr 102400 ram 102400
775 *
776 * Where the second one fully references the 100K extent
777 * that starts at disk byte 12845056, and the log tree
778 * has a single csum item that covers the entire range
779 * of the extent:
780 *
781 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
782 *
783 * After the first file extent item is replayed, the
784 * csum tree gets the following csum item:
785 *
786 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
787 *
788 * Which covers the 20K sub-range starting at offset 20K
789 * of our extent. Now when we replay the second file
790 * extent item, if we do not delete existing csum items
791 * that cover any of its blocks, we end up getting two
792 * csum items in our csum tree that overlap each other:
793 *
794 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
795 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
796 *
797 * Which is a problem, because after this anyone trying
798 * to lookup up for the checksum of any block of our
799 * extent starting at an offset of 40K or higher, will
800 * end up looking at the second csum item only, which
801 * does not contain the checksum for any block starting
802 * at offset 40K or higher of our extent.
803 */
07d400a6
YZ
804 while (!list_empty(&ordered_sums)) {
805 struct btrfs_ordered_sum *sums;
806 sums = list_entry(ordered_sums.next,
807 struct btrfs_ordered_sum,
808 list);
b84b8390 809 if (!ret)
0b246afa 810 ret = btrfs_del_csums(trans, fs_info,
5b4aacef
JM
811 sums->bytenr,
812 sums->len);
3650860b
JB
813 if (!ret)
814 ret = btrfs_csum_file_blocks(trans,
0b246afa 815 fs_info->csum_root, sums);
07d400a6
YZ
816 list_del(&sums->list);
817 kfree(sums);
818 }
3650860b
JB
819 if (ret)
820 goto out;
07d400a6 821 } else {
b3b4aa74 822 btrfs_release_path(path);
07d400a6
YZ
823 }
824 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
825 /* inline extents are easy, we just overwrite them */
826 ret = overwrite_item(trans, root, path, eb, slot, key);
3650860b
JB
827 if (ret)
828 goto out;
07d400a6 829 }
e02119d5 830
4bc4bee4 831 inode_add_bytes(inode, nbytes);
3168021c 832update_inode:
b9959295 833 ret = btrfs_update_inode(trans, root, inode);
e02119d5
CM
834out:
835 if (inode)
836 iput(inode);
837 return ret;
838}
839
840/*
841 * when cleaning up conflicts between the directory names in the
842 * subvolume, directory names in the log and directory names in the
843 * inode back references, we may have to unlink inodes from directories.
844 *
845 * This is a helper function to do the unlink of a specific directory
846 * item
847 */
848static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
849 struct btrfs_root *root,
850 struct btrfs_path *path,
207e7d92 851 struct btrfs_inode *dir,
e02119d5
CM
852 struct btrfs_dir_item *di)
853{
2ff7e61e 854 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5
CM
855 struct inode *inode;
856 char *name;
857 int name_len;
858 struct extent_buffer *leaf;
859 struct btrfs_key location;
860 int ret;
861
862 leaf = path->nodes[0];
863
864 btrfs_dir_item_key_to_cpu(leaf, di, &location);
865 name_len = btrfs_dir_name_len(leaf, di);
866 name = kmalloc(name_len, GFP_NOFS);
2a29edc6 867 if (!name)
868 return -ENOMEM;
869
e02119d5 870 read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
b3b4aa74 871 btrfs_release_path(path);
e02119d5
CM
872
873 inode = read_one_inode(root, location.objectid);
c00e9493 874 if (!inode) {
3650860b
JB
875 ret = -EIO;
876 goto out;
c00e9493 877 }
e02119d5 878
ec051c0f 879 ret = link_to_fixup_dir(trans, root, path, location.objectid);
3650860b
JB
880 if (ret)
881 goto out;
12fcfd22 882
207e7d92
NB
883 ret = btrfs_unlink_inode(trans, root, dir, BTRFS_I(inode), name,
884 name_len);
3650860b
JB
885 if (ret)
886 goto out;
ada9af21 887 else
2ff7e61e 888 ret = btrfs_run_delayed_items(trans, fs_info);
3650860b 889out:
e02119d5 890 kfree(name);
e02119d5
CM
891 iput(inode);
892 return ret;
893}
894
895/*
896 * helper function to see if a given name and sequence number found
897 * in an inode back reference are already in a directory and correctly
898 * point to this inode
899 */
900static noinline int inode_in_dir(struct btrfs_root *root,
901 struct btrfs_path *path,
902 u64 dirid, u64 objectid, u64 index,
903 const char *name, int name_len)
904{
905 struct btrfs_dir_item *di;
906 struct btrfs_key location;
907 int match = 0;
908
909 di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
910 index, name, name_len, 0);
911 if (di && !IS_ERR(di)) {
912 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
913 if (location.objectid != objectid)
914 goto out;
915 } else
916 goto out;
b3b4aa74 917 btrfs_release_path(path);
e02119d5
CM
918
919 di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
920 if (di && !IS_ERR(di)) {
921 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
922 if (location.objectid != objectid)
923 goto out;
924 } else
925 goto out;
926 match = 1;
927out:
b3b4aa74 928 btrfs_release_path(path);
e02119d5
CM
929 return match;
930}
931
932/*
933 * helper function to check a log tree for a named back reference in
934 * an inode. This is used to decide if a back reference that is
935 * found in the subvolume conflicts with what we find in the log.
936 *
937 * inode backreferences may have multiple refs in a single item,
938 * during replay we process one reference at a time, and we don't
939 * want to delete valid links to a file from the subvolume if that
940 * link is also in the log.
941 */
942static noinline int backref_in_log(struct btrfs_root *log,
943 struct btrfs_key *key,
f186373f 944 u64 ref_objectid,
df8d116f 945 const char *name, int namelen)
e02119d5
CM
946{
947 struct btrfs_path *path;
948 struct btrfs_inode_ref *ref;
949 unsigned long ptr;
950 unsigned long ptr_end;
951 unsigned long name_ptr;
952 int found_name_len;
953 int item_size;
954 int ret;
955 int match = 0;
956
957 path = btrfs_alloc_path();
2a29edc6 958 if (!path)
959 return -ENOMEM;
960
e02119d5
CM
961 ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
962 if (ret != 0)
963 goto out;
964
e02119d5 965 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
f186373f
MF
966
967 if (key->type == BTRFS_INODE_EXTREF_KEY) {
968 if (btrfs_find_name_in_ext_backref(path, ref_objectid,
969 name, namelen, NULL))
970 match = 1;
971
972 goto out;
973 }
974
975 item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
e02119d5
CM
976 ptr_end = ptr + item_size;
977 while (ptr < ptr_end) {
978 ref = (struct btrfs_inode_ref *)ptr;
979 found_name_len = btrfs_inode_ref_name_len(path->nodes[0], ref);
980 if (found_name_len == namelen) {
981 name_ptr = (unsigned long)(ref + 1);
982 ret = memcmp_extent_buffer(path->nodes[0], name,
983 name_ptr, namelen);
984 if (ret == 0) {
985 match = 1;
986 goto out;
987 }
988 }
989 ptr = (unsigned long)(ref + 1) + found_name_len;
990 }
991out:
992 btrfs_free_path(path);
993 return match;
994}
995
5a1d7843 996static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
e02119d5 997 struct btrfs_root *root,
e02119d5 998 struct btrfs_path *path,
5a1d7843 999 struct btrfs_root *log_root,
94c91a1f
NB
1000 struct btrfs_inode *dir,
1001 struct btrfs_inode *inode,
f186373f
MF
1002 u64 inode_objectid, u64 parent_objectid,
1003 u64 ref_index, char *name, int namelen,
1004 int *search_done)
e02119d5 1005{
2ff7e61e 1006 struct btrfs_fs_info *fs_info = root->fs_info;
34f3e4f2 1007 int ret;
f186373f
MF
1008 char *victim_name;
1009 int victim_name_len;
1010 struct extent_buffer *leaf;
5a1d7843 1011 struct btrfs_dir_item *di;
f186373f
MF
1012 struct btrfs_key search_key;
1013 struct btrfs_inode_extref *extref;
c622ae60 1014
f186373f
MF
1015again:
1016 /* Search old style refs */
1017 search_key.objectid = inode_objectid;
1018 search_key.type = BTRFS_INODE_REF_KEY;
1019 search_key.offset = parent_objectid;
1020 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
e02119d5 1021 if (ret == 0) {
e02119d5
CM
1022 struct btrfs_inode_ref *victim_ref;
1023 unsigned long ptr;
1024 unsigned long ptr_end;
f186373f
MF
1025
1026 leaf = path->nodes[0];
e02119d5
CM
1027
1028 /* are we trying to overwrite a back ref for the root directory
1029 * if so, just jump out, we're done
1030 */
f186373f 1031 if (search_key.objectid == search_key.offset)
5a1d7843 1032 return 1;
e02119d5
CM
1033
1034 /* check all the names in this back reference to see
1035 * if they are in the log. if so, we allow them to stay
1036 * otherwise they must be unlinked as a conflict
1037 */
1038 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1039 ptr_end = ptr + btrfs_item_size_nr(leaf, path->slots[0]);
d397712b 1040 while (ptr < ptr_end) {
e02119d5
CM
1041 victim_ref = (struct btrfs_inode_ref *)ptr;
1042 victim_name_len = btrfs_inode_ref_name_len(leaf,
1043 victim_ref);
1044 victim_name = kmalloc(victim_name_len, GFP_NOFS);
3650860b
JB
1045 if (!victim_name)
1046 return -ENOMEM;
e02119d5
CM
1047
1048 read_extent_buffer(leaf, victim_name,
1049 (unsigned long)(victim_ref + 1),
1050 victim_name_len);
1051
f186373f
MF
1052 if (!backref_in_log(log_root, &search_key,
1053 parent_objectid,
1054 victim_name,
e02119d5 1055 victim_name_len)) {
94c91a1f 1056 inc_nlink(&inode->vfs_inode);
b3b4aa74 1057 btrfs_release_path(path);
12fcfd22 1058
94c91a1f 1059 ret = btrfs_unlink_inode(trans, root, dir, inode,
4ec5934e 1060 victim_name, victim_name_len);
f186373f 1061 kfree(victim_name);
3650860b
JB
1062 if (ret)
1063 return ret;
2ff7e61e 1064 ret = btrfs_run_delayed_items(trans, fs_info);
ada9af21
FDBM
1065 if (ret)
1066 return ret;
f186373f
MF
1067 *search_done = 1;
1068 goto again;
e02119d5
CM
1069 }
1070 kfree(victim_name);
f186373f 1071
e02119d5
CM
1072 ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
1073 }
e02119d5 1074
c622ae60 1075 /*
1076 * NOTE: we have searched root tree and checked the
bb7ab3b9 1077 * corresponding ref, it does not need to check again.
c622ae60 1078 */
5a1d7843 1079 *search_done = 1;
e02119d5 1080 }
b3b4aa74 1081 btrfs_release_path(path);
e02119d5 1082
f186373f
MF
1083 /* Same search but for extended refs */
1084 extref = btrfs_lookup_inode_extref(NULL, root, path, name, namelen,
1085 inode_objectid, parent_objectid, 0,
1086 0);
1087 if (!IS_ERR_OR_NULL(extref)) {
1088 u32 item_size;
1089 u32 cur_offset = 0;
1090 unsigned long base;
1091 struct inode *victim_parent;
1092
1093 leaf = path->nodes[0];
1094
1095 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1096 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1097
1098 while (cur_offset < item_size) {
dd9ef135 1099 extref = (struct btrfs_inode_extref *)(base + cur_offset);
f186373f
MF
1100
1101 victim_name_len = btrfs_inode_extref_name_len(leaf, extref);
1102
1103 if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1104 goto next;
1105
1106 victim_name = kmalloc(victim_name_len, GFP_NOFS);
3650860b
JB
1107 if (!victim_name)
1108 return -ENOMEM;
f186373f
MF
1109 read_extent_buffer(leaf, victim_name, (unsigned long)&extref->name,
1110 victim_name_len);
1111
1112 search_key.objectid = inode_objectid;
1113 search_key.type = BTRFS_INODE_EXTREF_KEY;
1114 search_key.offset = btrfs_extref_hash(parent_objectid,
1115 victim_name,
1116 victim_name_len);
1117 ret = 0;
1118 if (!backref_in_log(log_root, &search_key,
1119 parent_objectid, victim_name,
1120 victim_name_len)) {
1121 ret = -ENOENT;
1122 victim_parent = read_one_inode(root,
94c91a1f 1123 parent_objectid);
f186373f 1124 if (victim_parent) {
94c91a1f 1125 inc_nlink(&inode->vfs_inode);
f186373f
MF
1126 btrfs_release_path(path);
1127
1128 ret = btrfs_unlink_inode(trans, root,
4ec5934e 1129 BTRFS_I(victim_parent),
94c91a1f 1130 inode,
4ec5934e
NB
1131 victim_name,
1132 victim_name_len);
ada9af21
FDBM
1133 if (!ret)
1134 ret = btrfs_run_delayed_items(
2ff7e61e
JM
1135 trans,
1136 fs_info);
f186373f 1137 }
f186373f
MF
1138 iput(victim_parent);
1139 kfree(victim_name);
3650860b
JB
1140 if (ret)
1141 return ret;
f186373f
MF
1142 *search_done = 1;
1143 goto again;
1144 }
1145 kfree(victim_name);
f186373f
MF
1146next:
1147 cur_offset += victim_name_len + sizeof(*extref);
1148 }
1149 *search_done = 1;
1150 }
1151 btrfs_release_path(path);
1152
34f3e4f2 1153 /* look for a conflicting sequence number */
94c91a1f 1154 di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
f186373f 1155 ref_index, name, namelen, 0);
34f3e4f2 1156 if (di && !IS_ERR(di)) {
94c91a1f 1157 ret = drop_one_dir_item(trans, root, path, dir, di);
3650860b
JB
1158 if (ret)
1159 return ret;
34f3e4f2 1160 }
1161 btrfs_release_path(path);
1162
1163 /* look for a conflicing name */
94c91a1f 1164 di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir),
34f3e4f2 1165 name, namelen, 0);
1166 if (di && !IS_ERR(di)) {
94c91a1f 1167 ret = drop_one_dir_item(trans, root, path, dir, di);
3650860b
JB
1168 if (ret)
1169 return ret;
34f3e4f2 1170 }
1171 btrfs_release_path(path);
1172
5a1d7843
JS
1173 return 0;
1174}
e02119d5 1175
bae15d95
QW
1176static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1177 u32 *namelen, char **name, u64 *index,
1178 u64 *parent_objectid)
f186373f
MF
1179{
1180 struct btrfs_inode_extref *extref;
1181
1182 extref = (struct btrfs_inode_extref *)ref_ptr;
1183
1184 *namelen = btrfs_inode_extref_name_len(eb, extref);
1185 *name = kmalloc(*namelen, GFP_NOFS);
1186 if (*name == NULL)
1187 return -ENOMEM;
1188
1189 read_extent_buffer(eb, *name, (unsigned long)&extref->name,
1190 *namelen);
1191
1192 *index = btrfs_inode_extref_index(eb, extref);
1193 if (parent_objectid)
1194 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1195
1196 return 0;
1197}
1198
bae15d95
QW
1199static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1200 u32 *namelen, char **name, u64 *index)
f186373f
MF
1201{
1202 struct btrfs_inode_ref *ref;
1203
1204 ref = (struct btrfs_inode_ref *)ref_ptr;
1205
1206 *namelen = btrfs_inode_ref_name_len(eb, ref);
1207 *name = kmalloc(*namelen, GFP_NOFS);
1208 if (*name == NULL)
1209 return -ENOMEM;
1210
1211 read_extent_buffer(eb, *name, (unsigned long)(ref + 1), *namelen);
1212
1213 *index = btrfs_inode_ref_index(eb, ref);
1214
1215 return 0;
1216}
1217
5a1d7843
JS
1218/*
1219 * replay one inode back reference item found in the log tree.
1220 * eb, slot and key refer to the buffer and key found in the log tree.
1221 * root is the destination we are replaying into, and path is for temp
1222 * use by this function. (it should be released on return).
1223 */
1224static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1225 struct btrfs_root *root,
1226 struct btrfs_root *log,
1227 struct btrfs_path *path,
1228 struct extent_buffer *eb, int slot,
1229 struct btrfs_key *key)
1230{
03b2f08b
GB
1231 struct inode *dir = NULL;
1232 struct inode *inode = NULL;
5a1d7843
JS
1233 unsigned long ref_ptr;
1234 unsigned long ref_end;
03b2f08b 1235 char *name = NULL;
5a1d7843
JS
1236 int namelen;
1237 int ret;
1238 int search_done = 0;
f186373f
MF
1239 int log_ref_ver = 0;
1240 u64 parent_objectid;
1241 u64 inode_objectid;
f46dbe3d 1242 u64 ref_index = 0;
f186373f
MF
1243 int ref_struct_size;
1244
1245 ref_ptr = btrfs_item_ptr_offset(eb, slot);
1246 ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
1247
1248 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1249 struct btrfs_inode_extref *r;
1250
1251 ref_struct_size = sizeof(struct btrfs_inode_extref);
1252 log_ref_ver = 1;
1253 r = (struct btrfs_inode_extref *)ref_ptr;
1254 parent_objectid = btrfs_inode_extref_parent(eb, r);
1255 } else {
1256 ref_struct_size = sizeof(struct btrfs_inode_ref);
1257 parent_objectid = key->offset;
1258 }
1259 inode_objectid = key->objectid;
e02119d5 1260
5a1d7843
JS
1261 /*
1262 * it is possible that we didn't log all the parent directories
1263 * for a given inode. If we don't find the dir, just don't
1264 * copy the back ref in. The link count fixup code will take
1265 * care of the rest
1266 */
f186373f 1267 dir = read_one_inode(root, parent_objectid);
03b2f08b
GB
1268 if (!dir) {
1269 ret = -ENOENT;
1270 goto out;
1271 }
5a1d7843 1272
f186373f 1273 inode = read_one_inode(root, inode_objectid);
5a1d7843 1274 if (!inode) {
03b2f08b
GB
1275 ret = -EIO;
1276 goto out;
5a1d7843
JS
1277 }
1278
5a1d7843 1279 while (ref_ptr < ref_end) {
f186373f 1280 if (log_ref_ver) {
bae15d95
QW
1281 ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1282 &ref_index, &parent_objectid);
f186373f
MF
1283 /*
1284 * parent object can change from one array
1285 * item to another.
1286 */
1287 if (!dir)
1288 dir = read_one_inode(root, parent_objectid);
03b2f08b
GB
1289 if (!dir) {
1290 ret = -ENOENT;
1291 goto out;
1292 }
f186373f 1293 } else {
bae15d95
QW
1294 ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1295 &ref_index);
f186373f
MF
1296 }
1297 if (ret)
03b2f08b 1298 goto out;
5a1d7843
JS
1299
1300 /* if we already have a perfect match, we're done */
f85b7379
DS
1301 if (!inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1302 btrfs_ino(BTRFS_I(inode)), ref_index,
1303 name, namelen)) {
5a1d7843
JS
1304 /*
1305 * look for a conflicting back reference in the
1306 * metadata. if we find one we have to unlink that name
1307 * of the file before we add our new link. Later on, we
1308 * overwrite any existing back reference, and we don't
1309 * want to create dangling pointers in the directory.
1310 */
1311
1312 if (!search_done) {
1313 ret = __add_inode_ref(trans, root, path, log,
94c91a1f 1314 BTRFS_I(dir),
d75eefdf 1315 BTRFS_I(inode),
f186373f
MF
1316 inode_objectid,
1317 parent_objectid,
1318 ref_index, name, namelen,
5a1d7843 1319 &search_done);
03b2f08b
GB
1320 if (ret) {
1321 if (ret == 1)
1322 ret = 0;
3650860b
JB
1323 goto out;
1324 }
5a1d7843
JS
1325 }
1326
1327 /* insert our name */
db0a669f
NB
1328 ret = btrfs_add_link(trans, BTRFS_I(dir),
1329 BTRFS_I(inode),
1330 name, namelen, 0, ref_index);
3650860b
JB
1331 if (ret)
1332 goto out;
5a1d7843
JS
1333
1334 btrfs_update_inode(trans, root, inode);
1335 }
1336
f186373f 1337 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
5a1d7843 1338 kfree(name);
03b2f08b 1339 name = NULL;
f186373f
MF
1340 if (log_ref_ver) {
1341 iput(dir);
1342 dir = NULL;
1343 }
5a1d7843 1344 }
e02119d5
CM
1345
1346 /* finally write the back reference in the inode */
1347 ret = overwrite_item(trans, root, path, eb, slot, key);
5a1d7843 1348out:
b3b4aa74 1349 btrfs_release_path(path);
03b2f08b 1350 kfree(name);
e02119d5
CM
1351 iput(dir);
1352 iput(inode);
3650860b 1353 return ret;
e02119d5
CM
1354}
1355
c71bf099 1356static int insert_orphan_item(struct btrfs_trans_handle *trans,
9c4f61f0 1357 struct btrfs_root *root, u64 ino)
c71bf099
YZ
1358{
1359 int ret;
381cf658 1360
9c4f61f0
DS
1361 ret = btrfs_insert_orphan_item(trans, root, ino);
1362 if (ret == -EEXIST)
1363 ret = 0;
381cf658 1364
c71bf099
YZ
1365 return ret;
1366}
1367
f186373f 1368static int count_inode_extrefs(struct btrfs_root *root,
36283658 1369 struct btrfs_inode *inode, struct btrfs_path *path)
f186373f
MF
1370{
1371 int ret = 0;
1372 int name_len;
1373 unsigned int nlink = 0;
1374 u32 item_size;
1375 u32 cur_offset = 0;
36283658 1376 u64 inode_objectid = btrfs_ino(inode);
f186373f
MF
1377 u64 offset = 0;
1378 unsigned long ptr;
1379 struct btrfs_inode_extref *extref;
1380 struct extent_buffer *leaf;
1381
1382 while (1) {
1383 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1384 &extref, &offset);
1385 if (ret)
1386 break;
c71bf099 1387
f186373f
MF
1388 leaf = path->nodes[0];
1389 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1390 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
2c2c452b 1391 cur_offset = 0;
f186373f
MF
1392
1393 while (cur_offset < item_size) {
1394 extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1395 name_len = btrfs_inode_extref_name_len(leaf, extref);
1396
1397 nlink++;
1398
1399 cur_offset += name_len + sizeof(*extref);
1400 }
1401
1402 offset++;
1403 btrfs_release_path(path);
1404 }
1405 btrfs_release_path(path);
1406
2c2c452b 1407 if (ret < 0 && ret != -ENOENT)
f186373f
MF
1408 return ret;
1409 return nlink;
1410}
1411
1412static int count_inode_refs(struct btrfs_root *root,
f329e319 1413 struct btrfs_inode *inode, struct btrfs_path *path)
e02119d5 1414{
e02119d5
CM
1415 int ret;
1416 struct btrfs_key key;
f186373f 1417 unsigned int nlink = 0;
e02119d5
CM
1418 unsigned long ptr;
1419 unsigned long ptr_end;
1420 int name_len;
f329e319 1421 u64 ino = btrfs_ino(inode);
e02119d5 1422
33345d01 1423 key.objectid = ino;
e02119d5
CM
1424 key.type = BTRFS_INODE_REF_KEY;
1425 key.offset = (u64)-1;
1426
d397712b 1427 while (1) {
e02119d5
CM
1428 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1429 if (ret < 0)
1430 break;
1431 if (ret > 0) {
1432 if (path->slots[0] == 0)
1433 break;
1434 path->slots[0]--;
1435 }
e93ae26f 1436process_slot:
e02119d5
CM
1437 btrfs_item_key_to_cpu(path->nodes[0], &key,
1438 path->slots[0]);
33345d01 1439 if (key.objectid != ino ||
e02119d5
CM
1440 key.type != BTRFS_INODE_REF_KEY)
1441 break;
1442 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1443 ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
1444 path->slots[0]);
d397712b 1445 while (ptr < ptr_end) {
e02119d5
CM
1446 struct btrfs_inode_ref *ref;
1447
1448 ref = (struct btrfs_inode_ref *)ptr;
1449 name_len = btrfs_inode_ref_name_len(path->nodes[0],
1450 ref);
1451 ptr = (unsigned long)(ref + 1) + name_len;
1452 nlink++;
1453 }
1454
1455 if (key.offset == 0)
1456 break;
e93ae26f
FDBM
1457 if (path->slots[0] > 0) {
1458 path->slots[0]--;
1459 goto process_slot;
1460 }
e02119d5 1461 key.offset--;
b3b4aa74 1462 btrfs_release_path(path);
e02119d5 1463 }
b3b4aa74 1464 btrfs_release_path(path);
f186373f
MF
1465
1466 return nlink;
1467}
1468
1469/*
1470 * There are a few corners where the link count of the file can't
1471 * be properly maintained during replay. So, instead of adding
1472 * lots of complexity to the log code, we just scan the backrefs
1473 * for any file that has been through replay.
1474 *
1475 * The scan will update the link count on the inode to reflect the
1476 * number of back refs found. If it goes down to zero, the iput
1477 * will free the inode.
1478 */
1479static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1480 struct btrfs_root *root,
1481 struct inode *inode)
1482{
1483 struct btrfs_path *path;
1484 int ret;
1485 u64 nlink = 0;
4a0cc7ca 1486 u64 ino = btrfs_ino(BTRFS_I(inode));
f186373f
MF
1487
1488 path = btrfs_alloc_path();
1489 if (!path)
1490 return -ENOMEM;
1491
f329e319 1492 ret = count_inode_refs(root, BTRFS_I(inode), path);
f186373f
MF
1493 if (ret < 0)
1494 goto out;
1495
1496 nlink = ret;
1497
36283658 1498 ret = count_inode_extrefs(root, BTRFS_I(inode), path);
f186373f
MF
1499 if (ret < 0)
1500 goto out;
1501
1502 nlink += ret;
1503
1504 ret = 0;
1505
e02119d5 1506 if (nlink != inode->i_nlink) {
bfe86848 1507 set_nlink(inode, nlink);
e02119d5
CM
1508 btrfs_update_inode(trans, root, inode);
1509 }
8d5bf1cb 1510 BTRFS_I(inode)->index_cnt = (u64)-1;
e02119d5 1511
c71bf099
YZ
1512 if (inode->i_nlink == 0) {
1513 if (S_ISDIR(inode->i_mode)) {
1514 ret = replay_dir_deletes(trans, root, NULL, path,
33345d01 1515 ino, 1);
3650860b
JB
1516 if (ret)
1517 goto out;
c71bf099 1518 }
33345d01 1519 ret = insert_orphan_item(trans, root, ino);
12fcfd22 1520 }
12fcfd22 1521
f186373f
MF
1522out:
1523 btrfs_free_path(path);
1524 return ret;
e02119d5
CM
1525}
1526
1527static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1528 struct btrfs_root *root,
1529 struct btrfs_path *path)
1530{
1531 int ret;
1532 struct btrfs_key key;
1533 struct inode *inode;
1534
1535 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1536 key.type = BTRFS_ORPHAN_ITEM_KEY;
1537 key.offset = (u64)-1;
d397712b 1538 while (1) {
e02119d5
CM
1539 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1540 if (ret < 0)
1541 break;
1542
1543 if (ret == 1) {
1544 if (path->slots[0] == 0)
1545 break;
1546 path->slots[0]--;
1547 }
1548
1549 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1550 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1551 key.type != BTRFS_ORPHAN_ITEM_KEY)
1552 break;
1553
1554 ret = btrfs_del_item(trans, root, path);
65a246c5
TI
1555 if (ret)
1556 goto out;
e02119d5 1557
b3b4aa74 1558 btrfs_release_path(path);
e02119d5 1559 inode = read_one_inode(root, key.offset);
c00e9493
TI
1560 if (!inode)
1561 return -EIO;
e02119d5
CM
1562
1563 ret = fixup_inode_link_count(trans, root, inode);
e02119d5 1564 iput(inode);
3650860b
JB
1565 if (ret)
1566 goto out;
e02119d5 1567
12fcfd22
CM
1568 /*
1569 * fixup on a directory may create new entries,
1570 * make sure we always look for the highset possible
1571 * offset
1572 */
1573 key.offset = (u64)-1;
e02119d5 1574 }
65a246c5
TI
1575 ret = 0;
1576out:
b3b4aa74 1577 btrfs_release_path(path);
65a246c5 1578 return ret;
e02119d5
CM
1579}
1580
1581
1582/*
1583 * record a given inode in the fixup dir so we can check its link
1584 * count when replay is done. The link count is incremented here
1585 * so the inode won't go away until we check it
1586 */
1587static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1588 struct btrfs_root *root,
1589 struct btrfs_path *path,
1590 u64 objectid)
1591{
1592 struct btrfs_key key;
1593 int ret = 0;
1594 struct inode *inode;
1595
1596 inode = read_one_inode(root, objectid);
c00e9493
TI
1597 if (!inode)
1598 return -EIO;
e02119d5
CM
1599
1600 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
962a298f 1601 key.type = BTRFS_ORPHAN_ITEM_KEY;
e02119d5
CM
1602 key.offset = objectid;
1603
1604 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1605
b3b4aa74 1606 btrfs_release_path(path);
e02119d5 1607 if (ret == 0) {
9bf7a489
JB
1608 if (!inode->i_nlink)
1609 set_nlink(inode, 1);
1610 else
8b558c5f 1611 inc_nlink(inode);
b9959295 1612 ret = btrfs_update_inode(trans, root, inode);
e02119d5
CM
1613 } else if (ret == -EEXIST) {
1614 ret = 0;
1615 } else {
3650860b 1616 BUG(); /* Logic Error */
e02119d5
CM
1617 }
1618 iput(inode);
1619
1620 return ret;
1621}
1622
1623/*
1624 * when replaying the log for a directory, we only insert names
1625 * for inodes that actually exist. This means an fsync on a directory
1626 * does not implicitly fsync all the new files in it
1627 */
1628static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1629 struct btrfs_root *root,
e02119d5 1630 u64 dirid, u64 index,
60d53eb3 1631 char *name, int name_len,
e02119d5
CM
1632 struct btrfs_key *location)
1633{
1634 struct inode *inode;
1635 struct inode *dir;
1636 int ret;
1637
1638 inode = read_one_inode(root, location->objectid);
1639 if (!inode)
1640 return -ENOENT;
1641
1642 dir = read_one_inode(root, dirid);
1643 if (!dir) {
1644 iput(inode);
1645 return -EIO;
1646 }
d555438b 1647
db0a669f
NB
1648 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1649 name_len, 1, index);
e02119d5
CM
1650
1651 /* FIXME, put inode into FIXUP list */
1652
1653 iput(inode);
1654 iput(dir);
1655 return ret;
1656}
1657
df8d116f
FM
1658/*
1659 * Return true if an inode reference exists in the log for the given name,
1660 * inode and parent inode.
1661 */
1662static bool name_in_log_ref(struct btrfs_root *log_root,
1663 const char *name, const int name_len,
1664 const u64 dirid, const u64 ino)
1665{
1666 struct btrfs_key search_key;
1667
1668 search_key.objectid = ino;
1669 search_key.type = BTRFS_INODE_REF_KEY;
1670 search_key.offset = dirid;
1671 if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1672 return true;
1673
1674 search_key.type = BTRFS_INODE_EXTREF_KEY;
1675 search_key.offset = btrfs_extref_hash(dirid, name, name_len);
1676 if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1677 return true;
1678
1679 return false;
1680}
1681
e02119d5
CM
1682/*
1683 * take a single entry in a log directory item and replay it into
1684 * the subvolume.
1685 *
1686 * if a conflicting item exists in the subdirectory already,
1687 * the inode it points to is unlinked and put into the link count
1688 * fix up tree.
1689 *
1690 * If a name from the log points to a file or directory that does
1691 * not exist in the FS, it is skipped. fsyncs on directories
1692 * do not force down inodes inside that directory, just changes to the
1693 * names or unlinks in a directory.
bb53eda9
FM
1694 *
1695 * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1696 * non-existing inode) and 1 if the name was replayed.
e02119d5
CM
1697 */
1698static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1699 struct btrfs_root *root,
1700 struct btrfs_path *path,
1701 struct extent_buffer *eb,
1702 struct btrfs_dir_item *di,
1703 struct btrfs_key *key)
1704{
1705 char *name;
1706 int name_len;
1707 struct btrfs_dir_item *dst_di;
1708 struct btrfs_key found_key;
1709 struct btrfs_key log_key;
1710 struct inode *dir;
e02119d5 1711 u8 log_type;
4bef0848 1712 int exists;
3650860b 1713 int ret = 0;
d555438b 1714 bool update_size = (key->type == BTRFS_DIR_INDEX_KEY);
bb53eda9 1715 bool name_added = false;
e02119d5
CM
1716
1717 dir = read_one_inode(root, key->objectid);
c00e9493
TI
1718 if (!dir)
1719 return -EIO;
e02119d5
CM
1720
1721 name_len = btrfs_dir_name_len(eb, di);
1722 name = kmalloc(name_len, GFP_NOFS);
2bac325e
FDBM
1723 if (!name) {
1724 ret = -ENOMEM;
1725 goto out;
1726 }
2a29edc6 1727
e02119d5
CM
1728 log_type = btrfs_dir_type(eb, di);
1729 read_extent_buffer(eb, name, (unsigned long)(di + 1),
1730 name_len);
1731
1732 btrfs_dir_item_key_to_cpu(eb, di, &log_key);
4bef0848
CM
1733 exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1734 if (exists == 0)
1735 exists = 1;
1736 else
1737 exists = 0;
b3b4aa74 1738 btrfs_release_path(path);
4bef0848 1739
e02119d5
CM
1740 if (key->type == BTRFS_DIR_ITEM_KEY) {
1741 dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1742 name, name_len, 1);
d397712b 1743 } else if (key->type == BTRFS_DIR_INDEX_KEY) {
e02119d5
CM
1744 dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1745 key->objectid,
1746 key->offset, name,
1747 name_len, 1);
1748 } else {
3650860b
JB
1749 /* Corruption */
1750 ret = -EINVAL;
1751 goto out;
e02119d5 1752 }
c704005d 1753 if (IS_ERR_OR_NULL(dst_di)) {
e02119d5
CM
1754 /* we need a sequence number to insert, so we only
1755 * do inserts for the BTRFS_DIR_INDEX_KEY types
1756 */
1757 if (key->type != BTRFS_DIR_INDEX_KEY)
1758 goto out;
1759 goto insert;
1760 }
1761
1762 btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1763 /* the existing item matches the logged item */
1764 if (found_key.objectid == log_key.objectid &&
1765 found_key.type == log_key.type &&
1766 found_key.offset == log_key.offset &&
1767 btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
a2cc11db 1768 update_size = false;
e02119d5
CM
1769 goto out;
1770 }
1771
1772 /*
1773 * don't drop the conflicting directory entry if the inode
1774 * for the new entry doesn't exist
1775 */
4bef0848 1776 if (!exists)
e02119d5
CM
1777 goto out;
1778
207e7d92 1779 ret = drop_one_dir_item(trans, root, path, BTRFS_I(dir), dst_di);
3650860b
JB
1780 if (ret)
1781 goto out;
e02119d5
CM
1782
1783 if (key->type == BTRFS_DIR_INDEX_KEY)
1784 goto insert;
1785out:
b3b4aa74 1786 btrfs_release_path(path);
d555438b 1787 if (!ret && update_size) {
6ef06d27 1788 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name_len * 2);
d555438b
JB
1789 ret = btrfs_update_inode(trans, root, dir);
1790 }
e02119d5
CM
1791 kfree(name);
1792 iput(dir);
bb53eda9
FM
1793 if (!ret && name_added)
1794 ret = 1;
3650860b 1795 return ret;
e02119d5
CM
1796
1797insert:
df8d116f
FM
1798 if (name_in_log_ref(root->log_root, name, name_len,
1799 key->objectid, log_key.objectid)) {
1800 /* The dentry will be added later. */
1801 ret = 0;
1802 update_size = false;
1803 goto out;
1804 }
b3b4aa74 1805 btrfs_release_path(path);
60d53eb3
Z
1806 ret = insert_one_name(trans, root, key->objectid, key->offset,
1807 name, name_len, &log_key);
df8d116f 1808 if (ret && ret != -ENOENT && ret != -EEXIST)
3650860b 1809 goto out;
bb53eda9
FM
1810 if (!ret)
1811 name_added = true;
d555438b 1812 update_size = false;
3650860b 1813 ret = 0;
e02119d5
CM
1814 goto out;
1815}
1816
1817/*
1818 * find all the names in a directory item and reconcile them into
1819 * the subvolume. Only BTRFS_DIR_ITEM_KEY types will have more than
1820 * one name in a directory item, but the same code gets used for
1821 * both directory index types
1822 */
1823static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1824 struct btrfs_root *root,
1825 struct btrfs_path *path,
1826 struct extent_buffer *eb, int slot,
1827 struct btrfs_key *key)
1828{
bb53eda9 1829 int ret = 0;
e02119d5
CM
1830 u32 item_size = btrfs_item_size_nr(eb, slot);
1831 struct btrfs_dir_item *di;
1832 int name_len;
1833 unsigned long ptr;
1834 unsigned long ptr_end;
bb53eda9 1835 struct btrfs_path *fixup_path = NULL;
e02119d5
CM
1836
1837 ptr = btrfs_item_ptr_offset(eb, slot);
1838 ptr_end = ptr + item_size;
d397712b 1839 while (ptr < ptr_end) {
e02119d5
CM
1840 di = (struct btrfs_dir_item *)ptr;
1841 name_len = btrfs_dir_name_len(eb, di);
1842 ret = replay_one_name(trans, root, path, eb, di, key);
bb53eda9
FM
1843 if (ret < 0)
1844 break;
e02119d5
CM
1845 ptr = (unsigned long)(di + 1);
1846 ptr += name_len;
bb53eda9
FM
1847
1848 /*
1849 * If this entry refers to a non-directory (directories can not
1850 * have a link count > 1) and it was added in the transaction
1851 * that was not committed, make sure we fixup the link count of
1852 * the inode it the entry points to. Otherwise something like
1853 * the following would result in a directory pointing to an
1854 * inode with a wrong link that does not account for this dir
1855 * entry:
1856 *
1857 * mkdir testdir
1858 * touch testdir/foo
1859 * touch testdir/bar
1860 * sync
1861 *
1862 * ln testdir/bar testdir/bar_link
1863 * ln testdir/foo testdir/foo_link
1864 * xfs_io -c "fsync" testdir/bar
1865 *
1866 * <power failure>
1867 *
1868 * mount fs, log replay happens
1869 *
1870 * File foo would remain with a link count of 1 when it has two
1871 * entries pointing to it in the directory testdir. This would
1872 * make it impossible to ever delete the parent directory has
1873 * it would result in stale dentries that can never be deleted.
1874 */
1875 if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
1876 struct btrfs_key di_key;
1877
1878 if (!fixup_path) {
1879 fixup_path = btrfs_alloc_path();
1880 if (!fixup_path) {
1881 ret = -ENOMEM;
1882 break;
1883 }
1884 }
1885
1886 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1887 ret = link_to_fixup_dir(trans, root, fixup_path,
1888 di_key.objectid);
1889 if (ret)
1890 break;
1891 }
1892 ret = 0;
e02119d5 1893 }
bb53eda9
FM
1894 btrfs_free_path(fixup_path);
1895 return ret;
e02119d5
CM
1896}
1897
1898/*
1899 * directory replay has two parts. There are the standard directory
1900 * items in the log copied from the subvolume, and range items
1901 * created in the log while the subvolume was logged.
1902 *
1903 * The range items tell us which parts of the key space the log
1904 * is authoritative for. During replay, if a key in the subvolume
1905 * directory is in a logged range item, but not actually in the log
1906 * that means it was deleted from the directory before the fsync
1907 * and should be removed.
1908 */
1909static noinline int find_dir_range(struct btrfs_root *root,
1910 struct btrfs_path *path,
1911 u64 dirid, int key_type,
1912 u64 *start_ret, u64 *end_ret)
1913{
1914 struct btrfs_key key;
1915 u64 found_end;
1916 struct btrfs_dir_log_item *item;
1917 int ret;
1918 int nritems;
1919
1920 if (*start_ret == (u64)-1)
1921 return 1;
1922
1923 key.objectid = dirid;
1924 key.type = key_type;
1925 key.offset = *start_ret;
1926
1927 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1928 if (ret < 0)
1929 goto out;
1930 if (ret > 0) {
1931 if (path->slots[0] == 0)
1932 goto out;
1933 path->slots[0]--;
1934 }
1935 if (ret != 0)
1936 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1937
1938 if (key.type != key_type || key.objectid != dirid) {
1939 ret = 1;
1940 goto next;
1941 }
1942 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1943 struct btrfs_dir_log_item);
1944 found_end = btrfs_dir_log_end(path->nodes[0], item);
1945
1946 if (*start_ret >= key.offset && *start_ret <= found_end) {
1947 ret = 0;
1948 *start_ret = key.offset;
1949 *end_ret = found_end;
1950 goto out;
1951 }
1952 ret = 1;
1953next:
1954 /* check the next slot in the tree to see if it is a valid item */
1955 nritems = btrfs_header_nritems(path->nodes[0]);
2a7bf53f 1956 path->slots[0]++;
e02119d5
CM
1957 if (path->slots[0] >= nritems) {
1958 ret = btrfs_next_leaf(root, path);
1959 if (ret)
1960 goto out;
e02119d5
CM
1961 }
1962
1963 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1964
1965 if (key.type != key_type || key.objectid != dirid) {
1966 ret = 1;
1967 goto out;
1968 }
1969 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1970 struct btrfs_dir_log_item);
1971 found_end = btrfs_dir_log_end(path->nodes[0], item);
1972 *start_ret = key.offset;
1973 *end_ret = found_end;
1974 ret = 0;
1975out:
b3b4aa74 1976 btrfs_release_path(path);
e02119d5
CM
1977 return ret;
1978}
1979
1980/*
1981 * this looks for a given directory item in the log. If the directory
1982 * item is not in the log, the item is removed and the inode it points
1983 * to is unlinked
1984 */
1985static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
1986 struct btrfs_root *root,
1987 struct btrfs_root *log,
1988 struct btrfs_path *path,
1989 struct btrfs_path *log_path,
1990 struct inode *dir,
1991 struct btrfs_key *dir_key)
1992{
2ff7e61e 1993 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5
CM
1994 int ret;
1995 struct extent_buffer *eb;
1996 int slot;
1997 u32 item_size;
1998 struct btrfs_dir_item *di;
1999 struct btrfs_dir_item *log_di;
2000 int name_len;
2001 unsigned long ptr;
2002 unsigned long ptr_end;
2003 char *name;
2004 struct inode *inode;
2005 struct btrfs_key location;
2006
2007again:
2008 eb = path->nodes[0];
2009 slot = path->slots[0];
2010 item_size = btrfs_item_size_nr(eb, slot);
2011 ptr = btrfs_item_ptr_offset(eb, slot);
2012 ptr_end = ptr + item_size;
d397712b 2013 while (ptr < ptr_end) {
e02119d5
CM
2014 di = (struct btrfs_dir_item *)ptr;
2015 name_len = btrfs_dir_name_len(eb, di);
2016 name = kmalloc(name_len, GFP_NOFS);
2017 if (!name) {
2018 ret = -ENOMEM;
2019 goto out;
2020 }
2021 read_extent_buffer(eb, name, (unsigned long)(di + 1),
2022 name_len);
2023 log_di = NULL;
12fcfd22 2024 if (log && dir_key->type == BTRFS_DIR_ITEM_KEY) {
e02119d5
CM
2025 log_di = btrfs_lookup_dir_item(trans, log, log_path,
2026 dir_key->objectid,
2027 name, name_len, 0);
12fcfd22 2028 } else if (log && dir_key->type == BTRFS_DIR_INDEX_KEY) {
e02119d5
CM
2029 log_di = btrfs_lookup_dir_index_item(trans, log,
2030 log_path,
2031 dir_key->objectid,
2032 dir_key->offset,
2033 name, name_len, 0);
2034 }
269d040f 2035 if (!log_di || (IS_ERR(log_di) && PTR_ERR(log_di) == -ENOENT)) {
e02119d5 2036 btrfs_dir_item_key_to_cpu(eb, di, &location);
b3b4aa74
DS
2037 btrfs_release_path(path);
2038 btrfs_release_path(log_path);
e02119d5 2039 inode = read_one_inode(root, location.objectid);
c00e9493
TI
2040 if (!inode) {
2041 kfree(name);
2042 return -EIO;
2043 }
e02119d5
CM
2044
2045 ret = link_to_fixup_dir(trans, root,
2046 path, location.objectid);
3650860b
JB
2047 if (ret) {
2048 kfree(name);
2049 iput(inode);
2050 goto out;
2051 }
2052
8b558c5f 2053 inc_nlink(inode);
4ec5934e
NB
2054 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
2055 BTRFS_I(inode), name, name_len);
3650860b 2056 if (!ret)
2ff7e61e 2057 ret = btrfs_run_delayed_items(trans, fs_info);
e02119d5
CM
2058 kfree(name);
2059 iput(inode);
3650860b
JB
2060 if (ret)
2061 goto out;
e02119d5
CM
2062
2063 /* there might still be more names under this key
2064 * check and repeat if required
2065 */
2066 ret = btrfs_search_slot(NULL, root, dir_key, path,
2067 0, 0);
2068 if (ret == 0)
2069 goto again;
2070 ret = 0;
2071 goto out;
269d040f
FDBM
2072 } else if (IS_ERR(log_di)) {
2073 kfree(name);
2074 return PTR_ERR(log_di);
e02119d5 2075 }
b3b4aa74 2076 btrfs_release_path(log_path);
e02119d5
CM
2077 kfree(name);
2078
2079 ptr = (unsigned long)(di + 1);
2080 ptr += name_len;
2081 }
2082 ret = 0;
2083out:
b3b4aa74
DS
2084 btrfs_release_path(path);
2085 btrfs_release_path(log_path);
e02119d5
CM
2086 return ret;
2087}
2088
4f764e51
FM
2089static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2090 struct btrfs_root *root,
2091 struct btrfs_root *log,
2092 struct btrfs_path *path,
2093 const u64 ino)
2094{
2095 struct btrfs_key search_key;
2096 struct btrfs_path *log_path;
2097 int i;
2098 int nritems;
2099 int ret;
2100
2101 log_path = btrfs_alloc_path();
2102 if (!log_path)
2103 return -ENOMEM;
2104
2105 search_key.objectid = ino;
2106 search_key.type = BTRFS_XATTR_ITEM_KEY;
2107 search_key.offset = 0;
2108again:
2109 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2110 if (ret < 0)
2111 goto out;
2112process_leaf:
2113 nritems = btrfs_header_nritems(path->nodes[0]);
2114 for (i = path->slots[0]; i < nritems; i++) {
2115 struct btrfs_key key;
2116 struct btrfs_dir_item *di;
2117 struct btrfs_dir_item *log_di;
2118 u32 total_size;
2119 u32 cur;
2120
2121 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2122 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2123 ret = 0;
2124 goto out;
2125 }
2126
2127 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2128 total_size = btrfs_item_size_nr(path->nodes[0], i);
2129 cur = 0;
2130 while (cur < total_size) {
2131 u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2132 u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2133 u32 this_len = sizeof(*di) + name_len + data_len;
2134 char *name;
2135
2136 name = kmalloc(name_len, GFP_NOFS);
2137 if (!name) {
2138 ret = -ENOMEM;
2139 goto out;
2140 }
2141 read_extent_buffer(path->nodes[0], name,
2142 (unsigned long)(di + 1), name_len);
2143
2144 log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2145 name, name_len, 0);
2146 btrfs_release_path(log_path);
2147 if (!log_di) {
2148 /* Doesn't exist in log tree, so delete it. */
2149 btrfs_release_path(path);
2150 di = btrfs_lookup_xattr(trans, root, path, ino,
2151 name, name_len, -1);
2152 kfree(name);
2153 if (IS_ERR(di)) {
2154 ret = PTR_ERR(di);
2155 goto out;
2156 }
2157 ASSERT(di);
2158 ret = btrfs_delete_one_dir_name(trans, root,
2159 path, di);
2160 if (ret)
2161 goto out;
2162 btrfs_release_path(path);
2163 search_key = key;
2164 goto again;
2165 }
2166 kfree(name);
2167 if (IS_ERR(log_di)) {
2168 ret = PTR_ERR(log_di);
2169 goto out;
2170 }
2171 cur += this_len;
2172 di = (struct btrfs_dir_item *)((char *)di + this_len);
2173 }
2174 }
2175 ret = btrfs_next_leaf(root, path);
2176 if (ret > 0)
2177 ret = 0;
2178 else if (ret == 0)
2179 goto process_leaf;
2180out:
2181 btrfs_free_path(log_path);
2182 btrfs_release_path(path);
2183 return ret;
2184}
2185
2186
e02119d5
CM
2187/*
2188 * deletion replay happens before we copy any new directory items
2189 * out of the log or out of backreferences from inodes. It
2190 * scans the log to find ranges of keys that log is authoritative for,
2191 * and then scans the directory to find items in those ranges that are
2192 * not present in the log.
2193 *
2194 * Anything we don't find in the log is unlinked and removed from the
2195 * directory.
2196 */
2197static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2198 struct btrfs_root *root,
2199 struct btrfs_root *log,
2200 struct btrfs_path *path,
12fcfd22 2201 u64 dirid, int del_all)
e02119d5
CM
2202{
2203 u64 range_start;
2204 u64 range_end;
2205 int key_type = BTRFS_DIR_LOG_ITEM_KEY;
2206 int ret = 0;
2207 struct btrfs_key dir_key;
2208 struct btrfs_key found_key;
2209 struct btrfs_path *log_path;
2210 struct inode *dir;
2211
2212 dir_key.objectid = dirid;
2213 dir_key.type = BTRFS_DIR_ITEM_KEY;
2214 log_path = btrfs_alloc_path();
2215 if (!log_path)
2216 return -ENOMEM;
2217
2218 dir = read_one_inode(root, dirid);
2219 /* it isn't an error if the inode isn't there, that can happen
2220 * because we replay the deletes before we copy in the inode item
2221 * from the log
2222 */
2223 if (!dir) {
2224 btrfs_free_path(log_path);
2225 return 0;
2226 }
2227again:
2228 range_start = 0;
2229 range_end = 0;
d397712b 2230 while (1) {
12fcfd22
CM
2231 if (del_all)
2232 range_end = (u64)-1;
2233 else {
2234 ret = find_dir_range(log, path, dirid, key_type,
2235 &range_start, &range_end);
2236 if (ret != 0)
2237 break;
2238 }
e02119d5
CM
2239
2240 dir_key.offset = range_start;
d397712b 2241 while (1) {
e02119d5
CM
2242 int nritems;
2243 ret = btrfs_search_slot(NULL, root, &dir_key, path,
2244 0, 0);
2245 if (ret < 0)
2246 goto out;
2247
2248 nritems = btrfs_header_nritems(path->nodes[0]);
2249 if (path->slots[0] >= nritems) {
2250 ret = btrfs_next_leaf(root, path);
2251 if (ret)
2252 break;
2253 }
2254 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2255 path->slots[0]);
2256 if (found_key.objectid != dirid ||
2257 found_key.type != dir_key.type)
2258 goto next_type;
2259
2260 if (found_key.offset > range_end)
2261 break;
2262
2263 ret = check_item_in_log(trans, root, log, path,
12fcfd22
CM
2264 log_path, dir,
2265 &found_key);
3650860b
JB
2266 if (ret)
2267 goto out;
e02119d5
CM
2268 if (found_key.offset == (u64)-1)
2269 break;
2270 dir_key.offset = found_key.offset + 1;
2271 }
b3b4aa74 2272 btrfs_release_path(path);
e02119d5
CM
2273 if (range_end == (u64)-1)
2274 break;
2275 range_start = range_end + 1;
2276 }
2277
2278next_type:
2279 ret = 0;
2280 if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
2281 key_type = BTRFS_DIR_LOG_INDEX_KEY;
2282 dir_key.type = BTRFS_DIR_INDEX_KEY;
b3b4aa74 2283 btrfs_release_path(path);
e02119d5
CM
2284 goto again;
2285 }
2286out:
b3b4aa74 2287 btrfs_release_path(path);
e02119d5
CM
2288 btrfs_free_path(log_path);
2289 iput(dir);
2290 return ret;
2291}
2292
2293/*
2294 * the process_func used to replay items from the log tree. This
2295 * gets called in two different stages. The first stage just looks
2296 * for inodes and makes sure they are all copied into the subvolume.
2297 *
2298 * The second stage copies all the other item types from the log into
2299 * the subvolume. The two stage approach is slower, but gets rid of
2300 * lots of complexity around inodes referencing other inodes that exist
2301 * only in the log (references come from either directory items or inode
2302 * back refs).
2303 */
2304static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2305 struct walk_control *wc, u64 gen)
2306{
2307 int nritems;
2308 struct btrfs_path *path;
2309 struct btrfs_root *root = wc->replay_dest;
2310 struct btrfs_key key;
e02119d5
CM
2311 int level;
2312 int i;
2313 int ret;
2314
018642a1
TI
2315 ret = btrfs_read_buffer(eb, gen);
2316 if (ret)
2317 return ret;
e02119d5
CM
2318
2319 level = btrfs_header_level(eb);
2320
2321 if (level != 0)
2322 return 0;
2323
2324 path = btrfs_alloc_path();
1e5063d0
MF
2325 if (!path)
2326 return -ENOMEM;
e02119d5
CM
2327
2328 nritems = btrfs_header_nritems(eb);
2329 for (i = 0; i < nritems; i++) {
2330 btrfs_item_key_to_cpu(eb, &key, i);
e02119d5
CM
2331
2332 /* inode keys are done during the first stage */
2333 if (key.type == BTRFS_INODE_ITEM_KEY &&
2334 wc->stage == LOG_WALK_REPLAY_INODES) {
e02119d5
CM
2335 struct btrfs_inode_item *inode_item;
2336 u32 mode;
2337
2338 inode_item = btrfs_item_ptr(eb, i,
2339 struct btrfs_inode_item);
4f764e51
FM
2340 ret = replay_xattr_deletes(wc->trans, root, log,
2341 path, key.objectid);
2342 if (ret)
2343 break;
e02119d5
CM
2344 mode = btrfs_inode_mode(eb, inode_item);
2345 if (S_ISDIR(mode)) {
2346 ret = replay_dir_deletes(wc->trans,
12fcfd22 2347 root, log, path, key.objectid, 0);
b50c6e25
JB
2348 if (ret)
2349 break;
e02119d5
CM
2350 }
2351 ret = overwrite_item(wc->trans, root, path,
2352 eb, i, &key);
b50c6e25
JB
2353 if (ret)
2354 break;
e02119d5 2355
c71bf099 2356 /* for regular files, make sure corresponding
01327610 2357 * orphan item exist. extents past the new EOF
c71bf099 2358 * will be truncated later by orphan cleanup.
e02119d5
CM
2359 */
2360 if (S_ISREG(mode)) {
c71bf099
YZ
2361 ret = insert_orphan_item(wc->trans, root,
2362 key.objectid);
b50c6e25
JB
2363 if (ret)
2364 break;
e02119d5 2365 }
c71bf099 2366
e02119d5
CM
2367 ret = link_to_fixup_dir(wc->trans, root,
2368 path, key.objectid);
b50c6e25
JB
2369 if (ret)
2370 break;
e02119d5 2371 }
dd8e7217
JB
2372
2373 if (key.type == BTRFS_DIR_INDEX_KEY &&
2374 wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2375 ret = replay_one_dir_item(wc->trans, root, path,
2376 eb, i, &key);
2377 if (ret)
2378 break;
2379 }
2380
e02119d5
CM
2381 if (wc->stage < LOG_WALK_REPLAY_ALL)
2382 continue;
2383
2384 /* these keys are simply copied */
2385 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2386 ret = overwrite_item(wc->trans, root, path,
2387 eb, i, &key);
b50c6e25
JB
2388 if (ret)
2389 break;
2da1c669
LB
2390 } else if (key.type == BTRFS_INODE_REF_KEY ||
2391 key.type == BTRFS_INODE_EXTREF_KEY) {
f186373f
MF
2392 ret = add_inode_ref(wc->trans, root, log, path,
2393 eb, i, &key);
b50c6e25
JB
2394 if (ret && ret != -ENOENT)
2395 break;
2396 ret = 0;
e02119d5
CM
2397 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2398 ret = replay_one_extent(wc->trans, root, path,
2399 eb, i, &key);
b50c6e25
JB
2400 if (ret)
2401 break;
dd8e7217 2402 } else if (key.type == BTRFS_DIR_ITEM_KEY) {
e02119d5
CM
2403 ret = replay_one_dir_item(wc->trans, root, path,
2404 eb, i, &key);
b50c6e25
JB
2405 if (ret)
2406 break;
e02119d5
CM
2407 }
2408 }
2409 btrfs_free_path(path);
b50c6e25 2410 return ret;
e02119d5
CM
2411}
2412
d397712b 2413static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
e02119d5
CM
2414 struct btrfs_root *root,
2415 struct btrfs_path *path, int *level,
2416 struct walk_control *wc)
2417{
0b246afa 2418 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5 2419 u64 root_owner;
e02119d5
CM
2420 u64 bytenr;
2421 u64 ptr_gen;
2422 struct extent_buffer *next;
2423 struct extent_buffer *cur;
2424 struct extent_buffer *parent;
2425 u32 blocksize;
2426 int ret = 0;
2427
2428 WARN_ON(*level < 0);
2429 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2430
d397712b 2431 while (*level > 0) {
e02119d5
CM
2432 WARN_ON(*level < 0);
2433 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2434 cur = path->nodes[*level];
2435
fae7f21c 2436 WARN_ON(btrfs_header_level(cur) != *level);
e02119d5
CM
2437
2438 if (path->slots[*level] >=
2439 btrfs_header_nritems(cur))
2440 break;
2441
2442 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2443 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
0b246afa 2444 blocksize = fs_info->nodesize;
e02119d5
CM
2445
2446 parent = path->nodes[*level];
2447 root_owner = btrfs_header_owner(parent);
e02119d5 2448
2ff7e61e 2449 next = btrfs_find_create_tree_block(fs_info, bytenr);
c871b0f2
LB
2450 if (IS_ERR(next))
2451 return PTR_ERR(next);
e02119d5 2452
e02119d5 2453 if (*level == 1) {
1e5063d0 2454 ret = wc->process_func(root, next, wc, ptr_gen);
b50c6e25
JB
2455 if (ret) {
2456 free_extent_buffer(next);
1e5063d0 2457 return ret;
b50c6e25 2458 }
4a500fd1 2459
e02119d5
CM
2460 path->slots[*level]++;
2461 if (wc->free) {
018642a1
TI
2462 ret = btrfs_read_buffer(next, ptr_gen);
2463 if (ret) {
2464 free_extent_buffer(next);
2465 return ret;
2466 }
e02119d5 2467
681ae509
JB
2468 if (trans) {
2469 btrfs_tree_lock(next);
2470 btrfs_set_lock_blocking(next);
7c302b49 2471 clean_tree_block(fs_info, next);
681ae509
JB
2472 btrfs_wait_tree_block_writeback(next);
2473 btrfs_tree_unlock(next);
1846430c
LB
2474 } else {
2475 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2476 clear_extent_buffer_dirty(next);
681ae509 2477 }
e02119d5 2478
e02119d5
CM
2479 WARN_ON(root_owner !=
2480 BTRFS_TREE_LOG_OBJECTID);
2ff7e61e
JM
2481 ret = btrfs_free_and_pin_reserved_extent(
2482 fs_info, bytenr,
2483 blocksize);
3650860b
JB
2484 if (ret) {
2485 free_extent_buffer(next);
2486 return ret;
2487 }
e02119d5
CM
2488 }
2489 free_extent_buffer(next);
2490 continue;
2491 }
018642a1
TI
2492 ret = btrfs_read_buffer(next, ptr_gen);
2493 if (ret) {
2494 free_extent_buffer(next);
2495 return ret;
2496 }
e02119d5
CM
2497
2498 WARN_ON(*level <= 0);
2499 if (path->nodes[*level-1])
2500 free_extent_buffer(path->nodes[*level-1]);
2501 path->nodes[*level-1] = next;
2502 *level = btrfs_header_level(next);
2503 path->slots[*level] = 0;
2504 cond_resched();
2505 }
2506 WARN_ON(*level < 0);
2507 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2508
4a500fd1 2509 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
e02119d5
CM
2510
2511 cond_resched();
2512 return 0;
2513}
2514
d397712b 2515static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
e02119d5
CM
2516 struct btrfs_root *root,
2517 struct btrfs_path *path, int *level,
2518 struct walk_control *wc)
2519{
0b246afa 2520 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5 2521 u64 root_owner;
e02119d5
CM
2522 int i;
2523 int slot;
2524 int ret;
2525
d397712b 2526 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
e02119d5 2527 slot = path->slots[i];
4a500fd1 2528 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
e02119d5
CM
2529 path->slots[i]++;
2530 *level = i;
2531 WARN_ON(*level == 0);
2532 return 0;
2533 } else {
31840ae1
ZY
2534 struct extent_buffer *parent;
2535 if (path->nodes[*level] == root->node)
2536 parent = path->nodes[*level];
2537 else
2538 parent = path->nodes[*level + 1];
2539
2540 root_owner = btrfs_header_owner(parent);
1e5063d0 2541 ret = wc->process_func(root, path->nodes[*level], wc,
e02119d5 2542 btrfs_header_generation(path->nodes[*level]));
1e5063d0
MF
2543 if (ret)
2544 return ret;
2545
e02119d5
CM
2546 if (wc->free) {
2547 struct extent_buffer *next;
2548
2549 next = path->nodes[*level];
2550
681ae509
JB
2551 if (trans) {
2552 btrfs_tree_lock(next);
2553 btrfs_set_lock_blocking(next);
7c302b49 2554 clean_tree_block(fs_info, next);
681ae509
JB
2555 btrfs_wait_tree_block_writeback(next);
2556 btrfs_tree_unlock(next);
1846430c
LB
2557 } else {
2558 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2559 clear_extent_buffer_dirty(next);
681ae509 2560 }
e02119d5 2561
e02119d5 2562 WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
2ff7e61e
JM
2563 ret = btrfs_free_and_pin_reserved_extent(
2564 fs_info,
e02119d5 2565 path->nodes[*level]->start,
d00aff00 2566 path->nodes[*level]->len);
3650860b
JB
2567 if (ret)
2568 return ret;
e02119d5
CM
2569 }
2570 free_extent_buffer(path->nodes[*level]);
2571 path->nodes[*level] = NULL;
2572 *level = i + 1;
2573 }
2574 }
2575 return 1;
2576}
2577
2578/*
2579 * drop the reference count on the tree rooted at 'snap'. This traverses
2580 * the tree freeing any blocks that have a ref count of zero after being
2581 * decremented.
2582 */
2583static int walk_log_tree(struct btrfs_trans_handle *trans,
2584 struct btrfs_root *log, struct walk_control *wc)
2585{
2ff7e61e 2586 struct btrfs_fs_info *fs_info = log->fs_info;
e02119d5
CM
2587 int ret = 0;
2588 int wret;
2589 int level;
2590 struct btrfs_path *path;
e02119d5
CM
2591 int orig_level;
2592
2593 path = btrfs_alloc_path();
db5b493a
TI
2594 if (!path)
2595 return -ENOMEM;
e02119d5
CM
2596
2597 level = btrfs_header_level(log->node);
2598 orig_level = level;
2599 path->nodes[level] = log->node;
2600 extent_buffer_get(log->node);
2601 path->slots[level] = 0;
2602
d397712b 2603 while (1) {
e02119d5
CM
2604 wret = walk_down_log_tree(trans, log, path, &level, wc);
2605 if (wret > 0)
2606 break;
79787eaa 2607 if (wret < 0) {
e02119d5 2608 ret = wret;
79787eaa
JM
2609 goto out;
2610 }
e02119d5
CM
2611
2612 wret = walk_up_log_tree(trans, log, path, &level, wc);
2613 if (wret > 0)
2614 break;
79787eaa 2615 if (wret < 0) {
e02119d5 2616 ret = wret;
79787eaa
JM
2617 goto out;
2618 }
e02119d5
CM
2619 }
2620
2621 /* was the root node processed? if not, catch it here */
2622 if (path->nodes[orig_level]) {
79787eaa 2623 ret = wc->process_func(log, path->nodes[orig_level], wc,
e02119d5 2624 btrfs_header_generation(path->nodes[orig_level]));
79787eaa
JM
2625 if (ret)
2626 goto out;
e02119d5
CM
2627 if (wc->free) {
2628 struct extent_buffer *next;
2629
2630 next = path->nodes[orig_level];
2631
681ae509
JB
2632 if (trans) {
2633 btrfs_tree_lock(next);
2634 btrfs_set_lock_blocking(next);
7c302b49 2635 clean_tree_block(fs_info, next);
681ae509
JB
2636 btrfs_wait_tree_block_writeback(next);
2637 btrfs_tree_unlock(next);
1846430c
LB
2638 } else {
2639 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2640 clear_extent_buffer_dirty(next);
681ae509 2641 }
e02119d5 2642
e02119d5
CM
2643 WARN_ON(log->root_key.objectid !=
2644 BTRFS_TREE_LOG_OBJECTID);
2ff7e61e
JM
2645 ret = btrfs_free_and_pin_reserved_extent(fs_info,
2646 next->start, next->len);
3650860b
JB
2647 if (ret)
2648 goto out;
e02119d5
CM
2649 }
2650 }
2651
79787eaa 2652out:
e02119d5 2653 btrfs_free_path(path);
e02119d5
CM
2654 return ret;
2655}
2656
7237f183
YZ
2657/*
2658 * helper function to update the item for a given subvolumes log root
2659 * in the tree of log roots
2660 */
2661static int update_log_root(struct btrfs_trans_handle *trans,
2662 struct btrfs_root *log)
2663{
0b246afa 2664 struct btrfs_fs_info *fs_info = log->fs_info;
7237f183
YZ
2665 int ret;
2666
2667 if (log->log_transid == 1) {
2668 /* insert root item on the first sync */
0b246afa 2669 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
7237f183
YZ
2670 &log->root_key, &log->root_item);
2671 } else {
0b246afa 2672 ret = btrfs_update_root(trans, fs_info->log_root_tree,
7237f183
YZ
2673 &log->root_key, &log->root_item);
2674 }
2675 return ret;
2676}
2677
60d53eb3 2678static void wait_log_commit(struct btrfs_root *root, int transid)
e02119d5
CM
2679{
2680 DEFINE_WAIT(wait);
7237f183 2681 int index = transid % 2;
e02119d5 2682
7237f183
YZ
2683 /*
2684 * we only allow two pending log transactions at a time,
2685 * so we know that if ours is more than 2 older than the
2686 * current transaction, we're done
2687 */
49e83f57 2688 for (;;) {
7237f183
YZ
2689 prepare_to_wait(&root->log_commit_wait[index],
2690 &wait, TASK_UNINTERRUPTIBLE);
12fcfd22 2691
49e83f57
LB
2692 if (!(root->log_transid_committed < transid &&
2693 atomic_read(&root->log_commit[index])))
2694 break;
12fcfd22 2695
49e83f57
LB
2696 mutex_unlock(&root->log_mutex);
2697 schedule();
7237f183 2698 mutex_lock(&root->log_mutex);
49e83f57
LB
2699 }
2700 finish_wait(&root->log_commit_wait[index], &wait);
7237f183
YZ
2701}
2702
60d53eb3 2703static void wait_for_writer(struct btrfs_root *root)
7237f183
YZ
2704{
2705 DEFINE_WAIT(wait);
8b050d35 2706
49e83f57
LB
2707 for (;;) {
2708 prepare_to_wait(&root->log_writer_wait, &wait,
2709 TASK_UNINTERRUPTIBLE);
2710 if (!atomic_read(&root->log_writers))
2711 break;
2712
7237f183 2713 mutex_unlock(&root->log_mutex);
49e83f57 2714 schedule();
575849ec 2715 mutex_lock(&root->log_mutex);
7237f183 2716 }
49e83f57 2717 finish_wait(&root->log_writer_wait, &wait);
e02119d5
CM
2718}
2719
8b050d35
MX
2720static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2721 struct btrfs_log_ctx *ctx)
2722{
2723 if (!ctx)
2724 return;
2725
2726 mutex_lock(&root->log_mutex);
2727 list_del_init(&ctx->list);
2728 mutex_unlock(&root->log_mutex);
2729}
2730
2731/*
2732 * Invoked in log mutex context, or be sure there is no other task which
2733 * can access the list.
2734 */
2735static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2736 int index, int error)
2737{
2738 struct btrfs_log_ctx *ctx;
570dd450 2739 struct btrfs_log_ctx *safe;
8b050d35 2740
570dd450
CM
2741 list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2742 list_del_init(&ctx->list);
8b050d35 2743 ctx->log_ret = error;
570dd450 2744 }
8b050d35
MX
2745
2746 INIT_LIST_HEAD(&root->log_ctxs[index]);
2747}
2748
e02119d5
CM
2749/*
2750 * btrfs_sync_log does sends a given tree log down to the disk and
2751 * updates the super blocks to record it. When this call is done,
12fcfd22
CM
2752 * you know that any inodes previously logged are safely on disk only
2753 * if it returns 0.
2754 *
2755 * Any other return value means you need to call btrfs_commit_transaction.
2756 * Some of the edge cases for fsyncing directories that have had unlinks
2757 * or renames done in the past mean that sometimes the only safe
2758 * fsync is to commit the whole FS. When btrfs_sync_log returns -EAGAIN,
2759 * that has happened.
e02119d5
CM
2760 */
2761int btrfs_sync_log(struct btrfs_trans_handle *trans,
8b050d35 2762 struct btrfs_root *root, struct btrfs_log_ctx *ctx)
e02119d5 2763{
7237f183
YZ
2764 int index1;
2765 int index2;
8cef4e16 2766 int mark;
e02119d5 2767 int ret;
0b246afa 2768 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5 2769 struct btrfs_root *log = root->log_root;
0b246afa 2770 struct btrfs_root *log_root_tree = fs_info->log_root_tree;
bb14a59b 2771 int log_transid = 0;
8b050d35 2772 struct btrfs_log_ctx root_log_ctx;
c6adc9cc 2773 struct blk_plug plug;
e02119d5 2774
7237f183 2775 mutex_lock(&root->log_mutex);
d1433deb
MX
2776 log_transid = ctx->log_transid;
2777 if (root->log_transid_committed >= log_transid) {
2778 mutex_unlock(&root->log_mutex);
2779 return ctx->log_ret;
2780 }
2781
2782 index1 = log_transid % 2;
7237f183 2783 if (atomic_read(&root->log_commit[index1])) {
60d53eb3 2784 wait_log_commit(root, log_transid);
7237f183 2785 mutex_unlock(&root->log_mutex);
8b050d35 2786 return ctx->log_ret;
e02119d5 2787 }
d1433deb 2788 ASSERT(log_transid == root->log_transid);
7237f183
YZ
2789 atomic_set(&root->log_commit[index1], 1);
2790
2791 /* wait for previous tree log sync to complete */
2792 if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
60d53eb3 2793 wait_log_commit(root, log_transid - 1);
48cab2e0 2794
86df7eb9 2795 while (1) {
2ecb7923 2796 int batch = atomic_read(&root->log_batch);
cd354ad6 2797 /* when we're on an ssd, just kick the log commit out */
0b246afa 2798 if (!btrfs_test_opt(fs_info, SSD) &&
27cdeb70 2799 test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
86df7eb9
YZ
2800 mutex_unlock(&root->log_mutex);
2801 schedule_timeout_uninterruptible(1);
2802 mutex_lock(&root->log_mutex);
2803 }
60d53eb3 2804 wait_for_writer(root);
2ecb7923 2805 if (batch == atomic_read(&root->log_batch))
e02119d5
CM
2806 break;
2807 }
e02119d5 2808
12fcfd22 2809 /* bail out if we need to do a full commit */
0b246afa 2810 if (btrfs_need_log_full_commit(fs_info, trans)) {
12fcfd22 2811 ret = -EAGAIN;
2ab28f32 2812 btrfs_free_logged_extents(log, log_transid);
12fcfd22
CM
2813 mutex_unlock(&root->log_mutex);
2814 goto out;
2815 }
2816
8cef4e16
YZ
2817 if (log_transid % 2 == 0)
2818 mark = EXTENT_DIRTY;
2819 else
2820 mark = EXTENT_NEW;
2821
690587d1
CM
2822 /* we start IO on all the marked extents here, but we don't actually
2823 * wait for them until later.
2824 */
c6adc9cc 2825 blk_start_plug(&plug);
2ff7e61e 2826 ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
79787eaa 2827 if (ret) {
c6adc9cc 2828 blk_finish_plug(&plug);
66642832 2829 btrfs_abort_transaction(trans, ret);
2ab28f32 2830 btrfs_free_logged_extents(log, log_transid);
0b246afa 2831 btrfs_set_log_full_commit(fs_info, trans);
79787eaa
JM
2832 mutex_unlock(&root->log_mutex);
2833 goto out;
2834 }
7237f183 2835
5d4f98a2 2836 btrfs_set_root_node(&log->root_item, log->node);
7237f183 2837
7237f183
YZ
2838 root->log_transid++;
2839 log->log_transid = root->log_transid;
ff782e0a 2840 root->log_start_pid = 0;
7237f183 2841 /*
8cef4e16
YZ
2842 * IO has been started, blocks of the log tree have WRITTEN flag set
2843 * in their headers. new modifications of the log will be written to
2844 * new positions. so it's safe to allow log writers to go in.
7237f183
YZ
2845 */
2846 mutex_unlock(&root->log_mutex);
2847
28a23593 2848 btrfs_init_log_ctx(&root_log_ctx, NULL);
d1433deb 2849
7237f183 2850 mutex_lock(&log_root_tree->log_mutex);
2ecb7923 2851 atomic_inc(&log_root_tree->log_batch);
7237f183 2852 atomic_inc(&log_root_tree->log_writers);
d1433deb
MX
2853
2854 index2 = log_root_tree->log_transid % 2;
2855 list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
2856 root_log_ctx.log_transid = log_root_tree->log_transid;
2857
7237f183
YZ
2858 mutex_unlock(&log_root_tree->log_mutex);
2859
2860 ret = update_log_root(trans, log);
7237f183
YZ
2861
2862 mutex_lock(&log_root_tree->log_mutex);
2863 if (atomic_dec_and_test(&log_root_tree->log_writers)) {
779adf0f
DS
2864 /*
2865 * Implicit memory barrier after atomic_dec_and_test
2866 */
7237f183
YZ
2867 if (waitqueue_active(&log_root_tree->log_writer_wait))
2868 wake_up(&log_root_tree->log_writer_wait);
2869 }
2870
4a500fd1 2871 if (ret) {
d1433deb
MX
2872 if (!list_empty(&root_log_ctx.list))
2873 list_del_init(&root_log_ctx.list);
2874
c6adc9cc 2875 blk_finish_plug(&plug);
0b246afa 2876 btrfs_set_log_full_commit(fs_info, trans);
995946dd 2877
79787eaa 2878 if (ret != -ENOSPC) {
66642832 2879 btrfs_abort_transaction(trans, ret);
79787eaa
JM
2880 mutex_unlock(&log_root_tree->log_mutex);
2881 goto out;
2882 }
bf89d38f 2883 btrfs_wait_tree_log_extents(log, mark);
2ab28f32 2884 btrfs_free_logged_extents(log, log_transid);
4a500fd1
YZ
2885 mutex_unlock(&log_root_tree->log_mutex);
2886 ret = -EAGAIN;
2887 goto out;
2888 }
2889
d1433deb 2890 if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
3da5ab56 2891 blk_finish_plug(&plug);
cbd60aa7 2892 list_del_init(&root_log_ctx.list);
d1433deb
MX
2893 mutex_unlock(&log_root_tree->log_mutex);
2894 ret = root_log_ctx.log_ret;
2895 goto out;
2896 }
8b050d35 2897
d1433deb 2898 index2 = root_log_ctx.log_transid % 2;
7237f183 2899 if (atomic_read(&log_root_tree->log_commit[index2])) {
c6adc9cc 2900 blk_finish_plug(&plug);
bf89d38f 2901 ret = btrfs_wait_tree_log_extents(log, mark);
50d9aa99 2902 btrfs_wait_logged_extents(trans, log, log_transid);
60d53eb3 2903 wait_log_commit(log_root_tree,
d1433deb 2904 root_log_ctx.log_transid);
7237f183 2905 mutex_unlock(&log_root_tree->log_mutex);
5ab5e44a
FM
2906 if (!ret)
2907 ret = root_log_ctx.log_ret;
7237f183
YZ
2908 goto out;
2909 }
d1433deb 2910 ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
7237f183
YZ
2911 atomic_set(&log_root_tree->log_commit[index2], 1);
2912
12fcfd22 2913 if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
60d53eb3 2914 wait_log_commit(log_root_tree,
d1433deb 2915 root_log_ctx.log_transid - 1);
12fcfd22
CM
2916 }
2917
60d53eb3 2918 wait_for_writer(log_root_tree);
7237f183 2919
12fcfd22
CM
2920 /*
2921 * now that we've moved on to the tree of log tree roots,
2922 * check the full commit flag again
2923 */
0b246afa 2924 if (btrfs_need_log_full_commit(fs_info, trans)) {
c6adc9cc 2925 blk_finish_plug(&plug);
bf89d38f 2926 btrfs_wait_tree_log_extents(log, mark);
2ab28f32 2927 btrfs_free_logged_extents(log, log_transid);
12fcfd22
CM
2928 mutex_unlock(&log_root_tree->log_mutex);
2929 ret = -EAGAIN;
2930 goto out_wake_log_root;
2931 }
7237f183 2932
2ff7e61e 2933 ret = btrfs_write_marked_extents(fs_info,
c6adc9cc
MX
2934 &log_root_tree->dirty_log_pages,
2935 EXTENT_DIRTY | EXTENT_NEW);
2936 blk_finish_plug(&plug);
79787eaa 2937 if (ret) {
0b246afa 2938 btrfs_set_log_full_commit(fs_info, trans);
66642832 2939 btrfs_abort_transaction(trans, ret);
2ab28f32 2940 btrfs_free_logged_extents(log, log_transid);
79787eaa
JM
2941 mutex_unlock(&log_root_tree->log_mutex);
2942 goto out_wake_log_root;
2943 }
bf89d38f 2944 ret = btrfs_wait_tree_log_extents(log, mark);
5ab5e44a 2945 if (!ret)
bf89d38f
JM
2946 ret = btrfs_wait_tree_log_extents(log_root_tree,
2947 EXTENT_NEW | EXTENT_DIRTY);
5ab5e44a 2948 if (ret) {
0b246afa 2949 btrfs_set_log_full_commit(fs_info, trans);
5ab5e44a
FM
2950 btrfs_free_logged_extents(log, log_transid);
2951 mutex_unlock(&log_root_tree->log_mutex);
2952 goto out_wake_log_root;
2953 }
50d9aa99 2954 btrfs_wait_logged_extents(trans, log, log_transid);
e02119d5 2955
0b246afa
JM
2956 btrfs_set_super_log_root(fs_info->super_for_commit,
2957 log_root_tree->node->start);
2958 btrfs_set_super_log_root_level(fs_info->super_for_commit,
2959 btrfs_header_level(log_root_tree->node));
e02119d5 2960
7237f183 2961 log_root_tree->log_transid++;
7237f183
YZ
2962 mutex_unlock(&log_root_tree->log_mutex);
2963
2964 /*
2965 * nobody else is going to jump in and write the the ctree
2966 * super here because the log_commit atomic below is protecting
2967 * us. We must be called with a transaction handle pinning
2968 * the running transaction open, so a full commit can't hop
2969 * in and cause problems either.
2970 */
eece6a9c 2971 ret = write_all_supers(fs_info, 1);
5af3e8cc 2972 if (ret) {
0b246afa 2973 btrfs_set_log_full_commit(fs_info, trans);
66642832 2974 btrfs_abort_transaction(trans, ret);
5af3e8cc
SB
2975 goto out_wake_log_root;
2976 }
7237f183 2977
257c62e1
CM
2978 mutex_lock(&root->log_mutex);
2979 if (root->last_log_commit < log_transid)
2980 root->last_log_commit = log_transid;
2981 mutex_unlock(&root->log_mutex);
2982
12fcfd22 2983out_wake_log_root:
570dd450 2984 mutex_lock(&log_root_tree->log_mutex);
8b050d35
MX
2985 btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
2986
d1433deb 2987 log_root_tree->log_transid_committed++;
7237f183 2988 atomic_set(&log_root_tree->log_commit[index2], 0);
d1433deb
MX
2989 mutex_unlock(&log_root_tree->log_mutex);
2990
33a9eca7
DS
2991 /*
2992 * The barrier before waitqueue_active is implied by mutex_unlock
2993 */
7237f183
YZ
2994 if (waitqueue_active(&log_root_tree->log_commit_wait[index2]))
2995 wake_up(&log_root_tree->log_commit_wait[index2]);
e02119d5 2996out:
d1433deb 2997 mutex_lock(&root->log_mutex);
570dd450 2998 btrfs_remove_all_log_ctxs(root, index1, ret);
d1433deb 2999 root->log_transid_committed++;
7237f183 3000 atomic_set(&root->log_commit[index1], 0);
d1433deb 3001 mutex_unlock(&root->log_mutex);
8b050d35 3002
33a9eca7
DS
3003 /*
3004 * The barrier before waitqueue_active is implied by mutex_unlock
3005 */
7237f183
YZ
3006 if (waitqueue_active(&root->log_commit_wait[index1]))
3007 wake_up(&root->log_commit_wait[index1]);
b31eabd8 3008 return ret;
e02119d5
CM
3009}
3010
4a500fd1
YZ
3011static void free_log_tree(struct btrfs_trans_handle *trans,
3012 struct btrfs_root *log)
e02119d5
CM
3013{
3014 int ret;
d0c803c4
CM
3015 u64 start;
3016 u64 end;
e02119d5
CM
3017 struct walk_control wc = {
3018 .free = 1,
3019 .process_func = process_one_buffer
3020 };
3021
681ae509
JB
3022 ret = walk_log_tree(trans, log, &wc);
3023 /* I don't think this can happen but just in case */
3024 if (ret)
66642832 3025 btrfs_abort_transaction(trans, ret);
e02119d5 3026
d397712b 3027 while (1) {
d0c803c4 3028 ret = find_first_extent_bit(&log->dirty_log_pages,
55237a5f
LB
3029 0, &start, &end,
3030 EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT,
e6138876 3031 NULL);
d0c803c4
CM
3032 if (ret)
3033 break;
3034
8cef4e16 3035 clear_extent_bits(&log->dirty_log_pages, start, end,
55237a5f 3036 EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
d0c803c4
CM
3037 }
3038
2ab28f32
JB
3039 /*
3040 * We may have short-circuited the log tree with the full commit logic
3041 * and left ordered extents on our list, so clear these out to keep us
3042 * from leaking inodes and memory.
3043 */
3044 btrfs_free_logged_extents(log, 0);
3045 btrfs_free_logged_extents(log, 1);
3046
7237f183
YZ
3047 free_extent_buffer(log->node);
3048 kfree(log);
4a500fd1
YZ
3049}
3050
3051/*
3052 * free all the extents used by the tree log. This should be called
3053 * at commit time of the full transaction
3054 */
3055int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3056{
3057 if (root->log_root) {
3058 free_log_tree(trans, root->log_root);
3059 root->log_root = NULL;
3060 }
3061 return 0;
3062}
3063
3064int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
3065 struct btrfs_fs_info *fs_info)
3066{
3067 if (fs_info->log_root_tree) {
3068 free_log_tree(trans, fs_info->log_root_tree);
3069 fs_info->log_root_tree = NULL;
3070 }
e02119d5
CM
3071 return 0;
3072}
3073
e02119d5
CM
3074/*
3075 * If both a file and directory are logged, and unlinks or renames are
3076 * mixed in, we have a few interesting corners:
3077 *
3078 * create file X in dir Y
3079 * link file X to X.link in dir Y
3080 * fsync file X
3081 * unlink file X but leave X.link
3082 * fsync dir Y
3083 *
3084 * After a crash we would expect only X.link to exist. But file X
3085 * didn't get fsync'd again so the log has back refs for X and X.link.
3086 *
3087 * We solve this by removing directory entries and inode backrefs from the
3088 * log when a file that was logged in the current transaction is
3089 * unlinked. Any later fsync will include the updated log entries, and
3090 * we'll be able to reconstruct the proper directory items from backrefs.
3091 *
3092 * This optimizations allows us to avoid relogging the entire inode
3093 * or the entire directory.
3094 */
3095int btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3096 struct btrfs_root *root,
3097 const char *name, int name_len,
49f34d1f 3098 struct btrfs_inode *dir, u64 index)
e02119d5
CM
3099{
3100 struct btrfs_root *log;
3101 struct btrfs_dir_item *di;
3102 struct btrfs_path *path;
3103 int ret;
4a500fd1 3104 int err = 0;
e02119d5 3105 int bytes_del = 0;
49f34d1f 3106 u64 dir_ino = btrfs_ino(dir);
e02119d5 3107
49f34d1f 3108 if (dir->logged_trans < trans->transid)
3a5f1d45
CM
3109 return 0;
3110
e02119d5
CM
3111 ret = join_running_log_trans(root);
3112 if (ret)
3113 return 0;
3114
49f34d1f 3115 mutex_lock(&dir->log_mutex);
e02119d5
CM
3116
3117 log = root->log_root;
3118 path = btrfs_alloc_path();
a62f44a5
TI
3119 if (!path) {
3120 err = -ENOMEM;
3121 goto out_unlock;
3122 }
2a29edc6 3123
33345d01 3124 di = btrfs_lookup_dir_item(trans, log, path, dir_ino,
e02119d5 3125 name, name_len, -1);
4a500fd1
YZ
3126 if (IS_ERR(di)) {
3127 err = PTR_ERR(di);
3128 goto fail;
3129 }
3130 if (di) {
e02119d5
CM
3131 ret = btrfs_delete_one_dir_name(trans, log, path, di);
3132 bytes_del += name_len;
3650860b
JB
3133 if (ret) {
3134 err = ret;
3135 goto fail;
3136 }
e02119d5 3137 }
b3b4aa74 3138 btrfs_release_path(path);
33345d01 3139 di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
e02119d5 3140 index, name, name_len, -1);
4a500fd1
YZ
3141 if (IS_ERR(di)) {
3142 err = PTR_ERR(di);
3143 goto fail;
3144 }
3145 if (di) {
e02119d5
CM
3146 ret = btrfs_delete_one_dir_name(trans, log, path, di);
3147 bytes_del += name_len;
3650860b
JB
3148 if (ret) {
3149 err = ret;
3150 goto fail;
3151 }
e02119d5
CM
3152 }
3153
3154 /* update the directory size in the log to reflect the names
3155 * we have removed
3156 */
3157 if (bytes_del) {
3158 struct btrfs_key key;
3159
33345d01 3160 key.objectid = dir_ino;
e02119d5
CM
3161 key.offset = 0;
3162 key.type = BTRFS_INODE_ITEM_KEY;
b3b4aa74 3163 btrfs_release_path(path);
e02119d5
CM
3164
3165 ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
4a500fd1
YZ
3166 if (ret < 0) {
3167 err = ret;
3168 goto fail;
3169 }
e02119d5
CM
3170 if (ret == 0) {
3171 struct btrfs_inode_item *item;
3172 u64 i_size;
3173
3174 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3175 struct btrfs_inode_item);
3176 i_size = btrfs_inode_size(path->nodes[0], item);
3177 if (i_size > bytes_del)
3178 i_size -= bytes_del;
3179 else
3180 i_size = 0;
3181 btrfs_set_inode_size(path->nodes[0], item, i_size);
3182 btrfs_mark_buffer_dirty(path->nodes[0]);
3183 } else
3184 ret = 0;
b3b4aa74 3185 btrfs_release_path(path);
e02119d5 3186 }
4a500fd1 3187fail:
e02119d5 3188 btrfs_free_path(path);
a62f44a5 3189out_unlock:
49f34d1f 3190 mutex_unlock(&dir->log_mutex);
4a500fd1 3191 if (ret == -ENOSPC) {
995946dd 3192 btrfs_set_log_full_commit(root->fs_info, trans);
4a500fd1 3193 ret = 0;
79787eaa 3194 } else if (ret < 0)
66642832 3195 btrfs_abort_transaction(trans, ret);
79787eaa 3196
12fcfd22 3197 btrfs_end_log_trans(root);
e02119d5 3198
411fc6bc 3199 return err;
e02119d5
CM
3200}
3201
3202/* see comments for btrfs_del_dir_entries_in_log */
3203int btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3204 struct btrfs_root *root,
3205 const char *name, int name_len,
a491abb2 3206 struct btrfs_inode *inode, u64 dirid)
e02119d5 3207{
0b246afa 3208 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5
CM
3209 struct btrfs_root *log;
3210 u64 index;
3211 int ret;
3212
a491abb2 3213 if (inode->logged_trans < trans->transid)
3a5f1d45
CM
3214 return 0;
3215
e02119d5
CM
3216 ret = join_running_log_trans(root);
3217 if (ret)
3218 return 0;
3219 log = root->log_root;
a491abb2 3220 mutex_lock(&inode->log_mutex);
e02119d5 3221
a491abb2 3222 ret = btrfs_del_inode_ref(trans, log, name, name_len, btrfs_ino(inode),
e02119d5 3223 dirid, &index);
a491abb2 3224 mutex_unlock(&inode->log_mutex);
4a500fd1 3225 if (ret == -ENOSPC) {
0b246afa 3226 btrfs_set_log_full_commit(fs_info, trans);
4a500fd1 3227 ret = 0;
79787eaa 3228 } else if (ret < 0 && ret != -ENOENT)
66642832 3229 btrfs_abort_transaction(trans, ret);
12fcfd22 3230 btrfs_end_log_trans(root);
e02119d5 3231
e02119d5
CM
3232 return ret;
3233}
3234
3235/*
3236 * creates a range item in the log for 'dirid'. first_offset and
3237 * last_offset tell us which parts of the key space the log should
3238 * be considered authoritative for.
3239 */
3240static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3241 struct btrfs_root *log,
3242 struct btrfs_path *path,
3243 int key_type, u64 dirid,
3244 u64 first_offset, u64 last_offset)
3245{
3246 int ret;
3247 struct btrfs_key key;
3248 struct btrfs_dir_log_item *item;
3249
3250 key.objectid = dirid;
3251 key.offset = first_offset;
3252 if (key_type == BTRFS_DIR_ITEM_KEY)
3253 key.type = BTRFS_DIR_LOG_ITEM_KEY;
3254 else
3255 key.type = BTRFS_DIR_LOG_INDEX_KEY;
3256 ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
4a500fd1
YZ
3257 if (ret)
3258 return ret;
e02119d5
CM
3259
3260 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3261 struct btrfs_dir_log_item);
3262 btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3263 btrfs_mark_buffer_dirty(path->nodes[0]);
b3b4aa74 3264 btrfs_release_path(path);
e02119d5
CM
3265 return 0;
3266}
3267
3268/*
3269 * log all the items included in the current transaction for a given
3270 * directory. This also creates the range items in the log tree required
3271 * to replay anything deleted before the fsync
3272 */
3273static noinline int log_dir_items(struct btrfs_trans_handle *trans,
684a5773 3274 struct btrfs_root *root, struct btrfs_inode *inode,
e02119d5
CM
3275 struct btrfs_path *path,
3276 struct btrfs_path *dst_path, int key_type,
2f2ff0ee 3277 struct btrfs_log_ctx *ctx,
e02119d5
CM
3278 u64 min_offset, u64 *last_offset_ret)
3279{
3280 struct btrfs_key min_key;
e02119d5
CM
3281 struct btrfs_root *log = root->log_root;
3282 struct extent_buffer *src;
4a500fd1 3283 int err = 0;
e02119d5
CM
3284 int ret;
3285 int i;
3286 int nritems;
3287 u64 first_offset = min_offset;
3288 u64 last_offset = (u64)-1;
684a5773 3289 u64 ino = btrfs_ino(inode);
e02119d5
CM
3290
3291 log = root->log_root;
e02119d5 3292
33345d01 3293 min_key.objectid = ino;
e02119d5
CM
3294 min_key.type = key_type;
3295 min_key.offset = min_offset;
3296
6174d3cb 3297 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
e02119d5
CM
3298
3299 /*
3300 * we didn't find anything from this transaction, see if there
3301 * is anything at all
3302 */
33345d01
LZ
3303 if (ret != 0 || min_key.objectid != ino || min_key.type != key_type) {
3304 min_key.objectid = ino;
e02119d5
CM
3305 min_key.type = key_type;
3306 min_key.offset = (u64)-1;
b3b4aa74 3307 btrfs_release_path(path);
e02119d5
CM
3308 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3309 if (ret < 0) {
b3b4aa74 3310 btrfs_release_path(path);
e02119d5
CM
3311 return ret;
3312 }
33345d01 3313 ret = btrfs_previous_item(root, path, ino, key_type);
e02119d5
CM
3314
3315 /* if ret == 0 there are items for this type,
3316 * create a range to tell us the last key of this type.
3317 * otherwise, there are no items in this directory after
3318 * *min_offset, and we create a range to indicate that.
3319 */
3320 if (ret == 0) {
3321 struct btrfs_key tmp;
3322 btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3323 path->slots[0]);
d397712b 3324 if (key_type == tmp.type)
e02119d5 3325 first_offset = max(min_offset, tmp.offset) + 1;
e02119d5
CM
3326 }
3327 goto done;
3328 }
3329
3330 /* go backward to find any previous key */
33345d01 3331 ret = btrfs_previous_item(root, path, ino, key_type);
e02119d5
CM
3332 if (ret == 0) {
3333 struct btrfs_key tmp;
3334 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3335 if (key_type == tmp.type) {
3336 first_offset = tmp.offset;
3337 ret = overwrite_item(trans, log, dst_path,
3338 path->nodes[0], path->slots[0],
3339 &tmp);
4a500fd1
YZ
3340 if (ret) {
3341 err = ret;
3342 goto done;
3343 }
e02119d5
CM
3344 }
3345 }
b3b4aa74 3346 btrfs_release_path(path);
e02119d5
CM
3347
3348 /* find the first key from this transaction again */
3349 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
fae7f21c 3350 if (WARN_ON(ret != 0))
e02119d5 3351 goto done;
e02119d5
CM
3352
3353 /*
3354 * we have a block from this transaction, log every item in it
3355 * from our directory
3356 */
d397712b 3357 while (1) {
e02119d5
CM
3358 struct btrfs_key tmp;
3359 src = path->nodes[0];
3360 nritems = btrfs_header_nritems(src);
3361 for (i = path->slots[0]; i < nritems; i++) {
2f2ff0ee
FM
3362 struct btrfs_dir_item *di;
3363
e02119d5
CM
3364 btrfs_item_key_to_cpu(src, &min_key, i);
3365
33345d01 3366 if (min_key.objectid != ino || min_key.type != key_type)
e02119d5
CM
3367 goto done;
3368 ret = overwrite_item(trans, log, dst_path, src, i,
3369 &min_key);
4a500fd1
YZ
3370 if (ret) {
3371 err = ret;
3372 goto done;
3373 }
2f2ff0ee
FM
3374
3375 /*
3376 * We must make sure that when we log a directory entry,
3377 * the corresponding inode, after log replay, has a
3378 * matching link count. For example:
3379 *
3380 * touch foo
3381 * mkdir mydir
3382 * sync
3383 * ln foo mydir/bar
3384 * xfs_io -c "fsync" mydir
3385 * <crash>
3386 * <mount fs and log replay>
3387 *
3388 * Would result in a fsync log that when replayed, our
3389 * file inode would have a link count of 1, but we get
3390 * two directory entries pointing to the same inode.
3391 * After removing one of the names, it would not be
3392 * possible to remove the other name, which resulted
3393 * always in stale file handle errors, and would not
3394 * be possible to rmdir the parent directory, since
3395 * its i_size could never decrement to the value
3396 * BTRFS_EMPTY_DIR_SIZE, resulting in -ENOTEMPTY errors.
3397 */
3398 di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3399 btrfs_dir_item_key_to_cpu(src, di, &tmp);
3400 if (ctx &&
3401 (btrfs_dir_transid(src, di) == trans->transid ||
3402 btrfs_dir_type(src, di) == BTRFS_FT_DIR) &&
3403 tmp.type != BTRFS_ROOT_ITEM_KEY)
3404 ctx->log_new_dentries = true;
e02119d5
CM
3405 }
3406 path->slots[0] = nritems;
3407
3408 /*
3409 * look ahead to the next item and see if it is also
3410 * from this directory and from this transaction
3411 */
3412 ret = btrfs_next_leaf(root, path);
3413 if (ret == 1) {
3414 last_offset = (u64)-1;
3415 goto done;
3416 }
3417 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
33345d01 3418 if (tmp.objectid != ino || tmp.type != key_type) {
e02119d5
CM
3419 last_offset = (u64)-1;
3420 goto done;
3421 }
3422 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3423 ret = overwrite_item(trans, log, dst_path,
3424 path->nodes[0], path->slots[0],
3425 &tmp);
4a500fd1
YZ
3426 if (ret)
3427 err = ret;
3428 else
3429 last_offset = tmp.offset;
e02119d5
CM
3430 goto done;
3431 }
3432 }
3433done:
b3b4aa74
DS
3434 btrfs_release_path(path);
3435 btrfs_release_path(dst_path);
e02119d5 3436
4a500fd1
YZ
3437 if (err == 0) {
3438 *last_offset_ret = last_offset;
3439 /*
3440 * insert the log range keys to indicate where the log
3441 * is valid
3442 */
3443 ret = insert_dir_log_key(trans, log, path, key_type,
33345d01 3444 ino, first_offset, last_offset);
4a500fd1
YZ
3445 if (ret)
3446 err = ret;
3447 }
3448 return err;
e02119d5
CM
3449}
3450
3451/*
3452 * logging directories is very similar to logging inodes, We find all the items
3453 * from the current transaction and write them to the log.
3454 *
3455 * The recovery code scans the directory in the subvolume, and if it finds a
3456 * key in the range logged that is not present in the log tree, then it means
3457 * that dir entry was unlinked during the transaction.
3458 *
3459 * In order for that scan to work, we must include one key smaller than
3460 * the smallest logged by this transaction and one key larger than the largest
3461 * key logged by this transaction.
3462 */
3463static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
dbf39ea4 3464 struct btrfs_root *root, struct btrfs_inode *inode,
e02119d5 3465 struct btrfs_path *path,
2f2ff0ee
FM
3466 struct btrfs_path *dst_path,
3467 struct btrfs_log_ctx *ctx)
e02119d5
CM
3468{
3469 u64 min_key;
3470 u64 max_key;
3471 int ret;
3472 int key_type = BTRFS_DIR_ITEM_KEY;
3473
3474again:
3475 min_key = 0;
3476 max_key = 0;
d397712b 3477 while (1) {
dbf39ea4
NB
3478 ret = log_dir_items(trans, root, inode, path, dst_path, key_type,
3479 ctx, min_key, &max_key);
4a500fd1
YZ
3480 if (ret)
3481 return ret;
e02119d5
CM
3482 if (max_key == (u64)-1)
3483 break;
3484 min_key = max_key + 1;
3485 }
3486
3487 if (key_type == BTRFS_DIR_ITEM_KEY) {
3488 key_type = BTRFS_DIR_INDEX_KEY;
3489 goto again;
3490 }
3491 return 0;
3492}
3493
3494/*
3495 * a helper function to drop items from the log before we relog an
3496 * inode. max_key_type indicates the highest item type to remove.
3497 * This cannot be run for file data extents because it does not
3498 * free the extents they point to.
3499 */
3500static int drop_objectid_items(struct btrfs_trans_handle *trans,
3501 struct btrfs_root *log,
3502 struct btrfs_path *path,
3503 u64 objectid, int max_key_type)
3504{
3505 int ret;
3506 struct btrfs_key key;
3507 struct btrfs_key found_key;
18ec90d6 3508 int start_slot;
e02119d5
CM
3509
3510 key.objectid = objectid;
3511 key.type = max_key_type;
3512 key.offset = (u64)-1;
3513
d397712b 3514 while (1) {
e02119d5 3515 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
3650860b 3516 BUG_ON(ret == 0); /* Logic error */
4a500fd1 3517 if (ret < 0)
e02119d5
CM
3518 break;
3519
3520 if (path->slots[0] == 0)
3521 break;
3522
3523 path->slots[0]--;
3524 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
3525 path->slots[0]);
3526
3527 if (found_key.objectid != objectid)
3528 break;
3529
18ec90d6
JB
3530 found_key.offset = 0;
3531 found_key.type = 0;
3532 ret = btrfs_bin_search(path->nodes[0], &found_key, 0,
3533 &start_slot);
3534
3535 ret = btrfs_del_items(trans, log, path, start_slot,
3536 path->slots[0] - start_slot + 1);
3537 /*
3538 * If start slot isn't 0 then we don't need to re-search, we've
3539 * found the last guy with the objectid in this tree.
3540 */
3541 if (ret || start_slot != 0)
65a246c5 3542 break;
b3b4aa74 3543 btrfs_release_path(path);
e02119d5 3544 }
b3b4aa74 3545 btrfs_release_path(path);
5bdbeb21
JB
3546 if (ret > 0)
3547 ret = 0;
4a500fd1 3548 return ret;
e02119d5
CM
3549}
3550
94edf4ae
JB
3551static void fill_inode_item(struct btrfs_trans_handle *trans,
3552 struct extent_buffer *leaf,
3553 struct btrfs_inode_item *item,
1a4bcf47
FM
3554 struct inode *inode, int log_inode_only,
3555 u64 logged_isize)
94edf4ae 3556{
0b1c6cca
JB
3557 struct btrfs_map_token token;
3558
3559 btrfs_init_map_token(&token);
94edf4ae
JB
3560
3561 if (log_inode_only) {
3562 /* set the generation to zero so the recover code
3563 * can tell the difference between an logging
3564 * just to say 'this inode exists' and a logging
3565 * to say 'update this inode with these values'
3566 */
0b1c6cca 3567 btrfs_set_token_inode_generation(leaf, item, 0, &token);
1a4bcf47 3568 btrfs_set_token_inode_size(leaf, item, logged_isize, &token);
94edf4ae 3569 } else {
0b1c6cca
JB
3570 btrfs_set_token_inode_generation(leaf, item,
3571 BTRFS_I(inode)->generation,
3572 &token);
3573 btrfs_set_token_inode_size(leaf, item, inode->i_size, &token);
3574 }
3575
3576 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3577 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3578 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3579 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3580
a937b979 3581 btrfs_set_token_timespec_sec(leaf, &item->atime,
0b1c6cca 3582 inode->i_atime.tv_sec, &token);
a937b979 3583 btrfs_set_token_timespec_nsec(leaf, &item->atime,
0b1c6cca
JB
3584 inode->i_atime.tv_nsec, &token);
3585
a937b979 3586 btrfs_set_token_timespec_sec(leaf, &item->mtime,
0b1c6cca 3587 inode->i_mtime.tv_sec, &token);
a937b979 3588 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
0b1c6cca
JB
3589 inode->i_mtime.tv_nsec, &token);
3590
a937b979 3591 btrfs_set_token_timespec_sec(leaf, &item->ctime,
0b1c6cca 3592 inode->i_ctime.tv_sec, &token);
a937b979 3593 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
0b1c6cca
JB
3594 inode->i_ctime.tv_nsec, &token);
3595
3596 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3597 &token);
3598
3599 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3600 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3601 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3602 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3603 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
94edf4ae
JB
3604}
3605
a95249b3
JB
3606static int log_inode_item(struct btrfs_trans_handle *trans,
3607 struct btrfs_root *log, struct btrfs_path *path,
6d889a3b 3608 struct btrfs_inode *inode)
a95249b3
JB
3609{
3610 struct btrfs_inode_item *inode_item;
a95249b3
JB
3611 int ret;
3612
efd0c405 3613 ret = btrfs_insert_empty_item(trans, log, path,
6d889a3b 3614 &inode->location, sizeof(*inode_item));
a95249b3
JB
3615 if (ret && ret != -EEXIST)
3616 return ret;
3617 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3618 struct btrfs_inode_item);
6d889a3b
NB
3619 fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
3620 0, 0);
a95249b3
JB
3621 btrfs_release_path(path);
3622 return 0;
3623}
3624
31ff1cd2 3625static noinline int copy_items(struct btrfs_trans_handle *trans,
44d70e19 3626 struct btrfs_inode *inode,
31ff1cd2 3627 struct btrfs_path *dst_path,
16e7549f 3628 struct btrfs_path *src_path, u64 *last_extent,
1a4bcf47
FM
3629 int start_slot, int nr, int inode_only,
3630 u64 logged_isize)
31ff1cd2 3631{
44d70e19 3632 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
31ff1cd2
CM
3633 unsigned long src_offset;
3634 unsigned long dst_offset;
44d70e19 3635 struct btrfs_root *log = inode->root->log_root;
31ff1cd2
CM
3636 struct btrfs_file_extent_item *extent;
3637 struct btrfs_inode_item *inode_item;
16e7549f
JB
3638 struct extent_buffer *src = src_path->nodes[0];
3639 struct btrfs_key first_key, last_key, key;
31ff1cd2
CM
3640 int ret;
3641 struct btrfs_key *ins_keys;
3642 u32 *ins_sizes;
3643 char *ins_data;
3644 int i;
d20f7043 3645 struct list_head ordered_sums;
44d70e19 3646 int skip_csum = inode->flags & BTRFS_INODE_NODATASUM;
16e7549f 3647 bool has_extents = false;
74121f7c 3648 bool need_find_last_extent = true;
16e7549f 3649 bool done = false;
d20f7043
CM
3650
3651 INIT_LIST_HEAD(&ordered_sums);
31ff1cd2
CM
3652
3653 ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
3654 nr * sizeof(u32), GFP_NOFS);
2a29edc6 3655 if (!ins_data)
3656 return -ENOMEM;
3657
16e7549f
JB
3658 first_key.objectid = (u64)-1;
3659
31ff1cd2
CM
3660 ins_sizes = (u32 *)ins_data;
3661 ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
3662
3663 for (i = 0; i < nr; i++) {
3664 ins_sizes[i] = btrfs_item_size_nr(src, i + start_slot);
3665 btrfs_item_key_to_cpu(src, ins_keys + i, i + start_slot);
3666 }
3667 ret = btrfs_insert_empty_items(trans, log, dst_path,
3668 ins_keys, ins_sizes, nr);
4a500fd1
YZ
3669 if (ret) {
3670 kfree(ins_data);
3671 return ret;
3672 }
31ff1cd2 3673
5d4f98a2 3674 for (i = 0; i < nr; i++, dst_path->slots[0]++) {
31ff1cd2
CM
3675 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0],
3676 dst_path->slots[0]);
3677
3678 src_offset = btrfs_item_ptr_offset(src, start_slot + i);
3679
0dde10be 3680 if (i == nr - 1)
16e7549f
JB
3681 last_key = ins_keys[i];
3682
94edf4ae 3683 if (ins_keys[i].type == BTRFS_INODE_ITEM_KEY) {
31ff1cd2
CM
3684 inode_item = btrfs_item_ptr(dst_path->nodes[0],
3685 dst_path->slots[0],
3686 struct btrfs_inode_item);
94edf4ae 3687 fill_inode_item(trans, dst_path->nodes[0], inode_item,
f85b7379
DS
3688 &inode->vfs_inode,
3689 inode_only == LOG_INODE_EXISTS,
1a4bcf47 3690 logged_isize);
94edf4ae
JB
3691 } else {
3692 copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
3693 src_offset, ins_sizes[i]);
31ff1cd2 3694 }
94edf4ae 3695
16e7549f
JB
3696 /*
3697 * We set need_find_last_extent here in case we know we were
3698 * processing other items and then walk into the first extent in
3699 * the inode. If we don't hit an extent then nothing changes,
3700 * we'll do the last search the next time around.
3701 */
3702 if (ins_keys[i].type == BTRFS_EXTENT_DATA_KEY) {
3703 has_extents = true;
74121f7c 3704 if (first_key.objectid == (u64)-1)
16e7549f
JB
3705 first_key = ins_keys[i];
3706 } else {
3707 need_find_last_extent = false;
3708 }
3709
31ff1cd2
CM
3710 /* take a reference on file data extents so that truncates
3711 * or deletes of this inode don't have to relog the inode
3712 * again
3713 */
962a298f 3714 if (ins_keys[i].type == BTRFS_EXTENT_DATA_KEY &&
d2794405 3715 !skip_csum) {
31ff1cd2
CM
3716 int found_type;
3717 extent = btrfs_item_ptr(src, start_slot + i,
3718 struct btrfs_file_extent_item);
3719
8e531cdf 3720 if (btrfs_file_extent_generation(src, extent) < trans->transid)
3721 continue;
3722
31ff1cd2 3723 found_type = btrfs_file_extent_type(src, extent);
6f1fed77 3724 if (found_type == BTRFS_FILE_EXTENT_REG) {
5d4f98a2
YZ
3725 u64 ds, dl, cs, cl;
3726 ds = btrfs_file_extent_disk_bytenr(src,
3727 extent);
3728 /* ds == 0 is a hole */
3729 if (ds == 0)
3730 continue;
3731
3732 dl = btrfs_file_extent_disk_num_bytes(src,
3733 extent);
3734 cs = btrfs_file_extent_offset(src, extent);
3735 cl = btrfs_file_extent_num_bytes(src,
a419aef8 3736 extent);
580afd76
CM
3737 if (btrfs_file_extent_compression(src,
3738 extent)) {
3739 cs = 0;
3740 cl = dl;
3741 }
5d4f98a2
YZ
3742
3743 ret = btrfs_lookup_csums_range(
0b246afa 3744 fs_info->csum_root,
5d4f98a2 3745 ds + cs, ds + cs + cl - 1,
a2de733c 3746 &ordered_sums, 0);
3650860b
JB
3747 if (ret) {
3748 btrfs_release_path(dst_path);
3749 kfree(ins_data);
3750 return ret;
3751 }
31ff1cd2
CM
3752 }
3753 }
31ff1cd2
CM
3754 }
3755
3756 btrfs_mark_buffer_dirty(dst_path->nodes[0]);
b3b4aa74 3757 btrfs_release_path(dst_path);
31ff1cd2 3758 kfree(ins_data);
d20f7043
CM
3759
3760 /*
3761 * we have to do this after the loop above to avoid changing the
3762 * log tree while trying to change the log tree.
3763 */
4a500fd1 3764 ret = 0;
d397712b 3765 while (!list_empty(&ordered_sums)) {
d20f7043
CM
3766 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
3767 struct btrfs_ordered_sum,
3768 list);
4a500fd1
YZ
3769 if (!ret)
3770 ret = btrfs_csum_file_blocks(trans, log, sums);
d20f7043
CM
3771 list_del(&sums->list);
3772 kfree(sums);
3773 }
16e7549f
JB
3774
3775 if (!has_extents)
3776 return ret;
3777
74121f7c
FM
3778 if (need_find_last_extent && *last_extent == first_key.offset) {
3779 /*
3780 * We don't have any leafs between our current one and the one
3781 * we processed before that can have file extent items for our
3782 * inode (and have a generation number smaller than our current
3783 * transaction id).
3784 */
3785 need_find_last_extent = false;
3786 }
3787
16e7549f
JB
3788 /*
3789 * Because we use btrfs_search_forward we could skip leaves that were
3790 * not modified and then assume *last_extent is valid when it really
3791 * isn't. So back up to the previous leaf and read the end of the last
3792 * extent before we go and fill in holes.
3793 */
3794 if (need_find_last_extent) {
3795 u64 len;
3796
44d70e19 3797 ret = btrfs_prev_leaf(inode->root, src_path);
16e7549f
JB
3798 if (ret < 0)
3799 return ret;
3800 if (ret)
3801 goto fill_holes;
3802 if (src_path->slots[0])
3803 src_path->slots[0]--;
3804 src = src_path->nodes[0];
3805 btrfs_item_key_to_cpu(src, &key, src_path->slots[0]);
44d70e19 3806 if (key.objectid != btrfs_ino(inode) ||
16e7549f
JB
3807 key.type != BTRFS_EXTENT_DATA_KEY)
3808 goto fill_holes;
3809 extent = btrfs_item_ptr(src, src_path->slots[0],
3810 struct btrfs_file_extent_item);
3811 if (btrfs_file_extent_type(src, extent) ==
3812 BTRFS_FILE_EXTENT_INLINE) {
514ac8ad
CM
3813 len = btrfs_file_extent_inline_len(src,
3814 src_path->slots[0],
3815 extent);
16e7549f 3816 *last_extent = ALIGN(key.offset + len,
0b246afa 3817 fs_info->sectorsize);
16e7549f
JB
3818 } else {
3819 len = btrfs_file_extent_num_bytes(src, extent);
3820 *last_extent = key.offset + len;
3821 }
3822 }
3823fill_holes:
3824 /* So we did prev_leaf, now we need to move to the next leaf, but a few
3825 * things could have happened
3826 *
3827 * 1) A merge could have happened, so we could currently be on a leaf
3828 * that holds what we were copying in the first place.
3829 * 2) A split could have happened, and now not all of the items we want
3830 * are on the same leaf.
3831 *
3832 * So we need to adjust how we search for holes, we need to drop the
3833 * path and re-search for the first extent key we found, and then walk
3834 * forward until we hit the last one we copied.
3835 */
3836 if (need_find_last_extent) {
3837 /* btrfs_prev_leaf could return 1 without releasing the path */
3838 btrfs_release_path(src_path);
f85b7379
DS
3839 ret = btrfs_search_slot(NULL, inode->root, &first_key,
3840 src_path, 0, 0);
16e7549f
JB
3841 if (ret < 0)
3842 return ret;
3843 ASSERT(ret == 0);
3844 src = src_path->nodes[0];
3845 i = src_path->slots[0];
3846 } else {
3847 i = start_slot;
3848 }
3849
3850 /*
3851 * Ok so here we need to go through and fill in any holes we may have
3852 * to make sure that holes are punched for those areas in case they had
3853 * extents previously.
3854 */
3855 while (!done) {
3856 u64 offset, len;
3857 u64 extent_end;
3858
3859 if (i >= btrfs_header_nritems(src_path->nodes[0])) {
44d70e19 3860 ret = btrfs_next_leaf(inode->root, src_path);
16e7549f
JB
3861 if (ret < 0)
3862 return ret;
3863 ASSERT(ret == 0);
3864 src = src_path->nodes[0];
3865 i = 0;
3866 }
3867
3868 btrfs_item_key_to_cpu(src, &key, i);
3869 if (!btrfs_comp_cpu_keys(&key, &last_key))
3870 done = true;
44d70e19 3871 if (key.objectid != btrfs_ino(inode) ||
16e7549f
JB
3872 key.type != BTRFS_EXTENT_DATA_KEY) {
3873 i++;
3874 continue;
3875 }
3876 extent = btrfs_item_ptr(src, i, struct btrfs_file_extent_item);
3877 if (btrfs_file_extent_type(src, extent) ==
3878 BTRFS_FILE_EXTENT_INLINE) {
514ac8ad 3879 len = btrfs_file_extent_inline_len(src, i, extent);
da17066c 3880 extent_end = ALIGN(key.offset + len,
0b246afa 3881 fs_info->sectorsize);
16e7549f
JB
3882 } else {
3883 len = btrfs_file_extent_num_bytes(src, extent);
3884 extent_end = key.offset + len;
3885 }
3886 i++;
3887
3888 if (*last_extent == key.offset) {
3889 *last_extent = extent_end;
3890 continue;
3891 }
3892 offset = *last_extent;
3893 len = key.offset - *last_extent;
44d70e19 3894 ret = btrfs_insert_file_extent(trans, log, btrfs_ino(inode),
f85b7379 3895 offset, 0, 0, len, 0, len, 0, 0, 0);
16e7549f
JB
3896 if (ret)
3897 break;
74121f7c 3898 *last_extent = extent_end;
16e7549f
JB
3899 }
3900 /*
3901 * Need to let the callers know we dropped the path so they should
3902 * re-search.
3903 */
3904 if (!ret && need_find_last_extent)
3905 ret = 1;
4a500fd1 3906 return ret;
31ff1cd2
CM
3907}
3908
5dc562c5
JB
3909static int extent_cmp(void *priv, struct list_head *a, struct list_head *b)
3910{
3911 struct extent_map *em1, *em2;
3912
3913 em1 = list_entry(a, struct extent_map, list);
3914 em2 = list_entry(b, struct extent_map, list);
3915
3916 if (em1->start < em2->start)
3917 return -1;
3918 else if (em1->start > em2->start)
3919 return 1;
3920 return 0;
3921}
3922
8407f553
FM
3923static int wait_ordered_extents(struct btrfs_trans_handle *trans,
3924 struct inode *inode,
3925 struct btrfs_root *root,
3926 const struct extent_map *em,
3927 const struct list_head *logged_list,
3928 bool *ordered_io_error)
5dc562c5 3929{
0b246afa 3930 struct btrfs_fs_info *fs_info = root->fs_info;
2ab28f32 3931 struct btrfs_ordered_extent *ordered;
8407f553 3932 struct btrfs_root *log = root->log_root;
2ab28f32
JB
3933 u64 mod_start = em->mod_start;
3934 u64 mod_len = em->mod_len;
8407f553 3935 const bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2ab28f32
JB
3936 u64 csum_offset;
3937 u64 csum_len;
8407f553
FM
3938 LIST_HEAD(ordered_sums);
3939 int ret = 0;
0aa4a17d 3940
8407f553 3941 *ordered_io_error = false;
0aa4a17d 3942
8407f553
FM
3943 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
3944 em->block_start == EXTENT_MAP_HOLE)
70c8a91c 3945 return 0;
5dc562c5 3946
2ab28f32 3947 /*
8407f553
FM
3948 * Wait far any ordered extent that covers our extent map. If it
3949 * finishes without an error, first check and see if our csums are on
3950 * our outstanding ordered extents.
2ab28f32 3951 */
827463c4 3952 list_for_each_entry(ordered, logged_list, log_list) {
2ab28f32
JB
3953 struct btrfs_ordered_sum *sum;
3954
3955 if (!mod_len)
3956 break;
3957
2ab28f32
JB
3958 if (ordered->file_offset + ordered->len <= mod_start ||
3959 mod_start + mod_len <= ordered->file_offset)
3960 continue;
3961
8407f553
FM
3962 if (!test_bit(BTRFS_ORDERED_IO_DONE, &ordered->flags) &&
3963 !test_bit(BTRFS_ORDERED_IOERR, &ordered->flags) &&
3964 !test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags)) {
3965 const u64 start = ordered->file_offset;
3966 const u64 end = ordered->file_offset + ordered->len - 1;
3967
3968 WARN_ON(ordered->inode != inode);
3969 filemap_fdatawrite_range(inode->i_mapping, start, end);
3970 }
3971
3972 wait_event(ordered->wait,
3973 (test_bit(BTRFS_ORDERED_IO_DONE, &ordered->flags) ||
3974 test_bit(BTRFS_ORDERED_IOERR, &ordered->flags)));
3975
3976 if (test_bit(BTRFS_ORDERED_IOERR, &ordered->flags)) {
b38ef71c
FM
3977 /*
3978 * Clear the AS_EIO/AS_ENOSPC flags from the inode's
3979 * i_mapping flags, so that the next fsync won't get
3980 * an outdated io error too.
3981 */
f0312210 3982 filemap_check_errors(inode->i_mapping);
8407f553
FM
3983 *ordered_io_error = true;
3984 break;
3985 }
2ab28f32
JB
3986 /*
3987 * We are going to copy all the csums on this ordered extent, so
3988 * go ahead and adjust mod_start and mod_len in case this
3989 * ordered extent has already been logged.
3990 */
3991 if (ordered->file_offset > mod_start) {
3992 if (ordered->file_offset + ordered->len >=
3993 mod_start + mod_len)
3994 mod_len = ordered->file_offset - mod_start;
3995 /*
3996 * If we have this case
3997 *
3998 * |--------- logged extent ---------|
3999 * |----- ordered extent ----|
4000 *
4001 * Just don't mess with mod_start and mod_len, we'll
4002 * just end up logging more csums than we need and it
4003 * will be ok.
4004 */
4005 } else {
4006 if (ordered->file_offset + ordered->len <
4007 mod_start + mod_len) {
4008 mod_len = (mod_start + mod_len) -
4009 (ordered->file_offset + ordered->len);
4010 mod_start = ordered->file_offset +
4011 ordered->len;
4012 } else {
4013 mod_len = 0;
4014 }
4015 }
4016
8407f553
FM
4017 if (skip_csum)
4018 continue;
4019
2ab28f32
JB
4020 /*
4021 * To keep us from looping for the above case of an ordered
4022 * extent that falls inside of the logged extent.
4023 */
4024 if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM,
4025 &ordered->flags))
4026 continue;
2ab28f32 4027
2ab28f32
JB
4028 list_for_each_entry(sum, &ordered->list, list) {
4029 ret = btrfs_csum_file_blocks(trans, log, sum);
827463c4 4030 if (ret)
8407f553 4031 break;
2ab28f32 4032 }
2ab28f32 4033 }
2ab28f32 4034
8407f553 4035 if (*ordered_io_error || !mod_len || ret || skip_csum)
2ab28f32
JB
4036 return ret;
4037
488111aa
FDBM
4038 if (em->compress_type) {
4039 csum_offset = 0;
8407f553 4040 csum_len = max(em->block_len, em->orig_block_len);
488111aa
FDBM
4041 } else {
4042 csum_offset = mod_start - em->start;
4043 csum_len = mod_len;
4044 }
2ab28f32 4045
70c8a91c 4046 /* block start is already adjusted for the file extent offset. */
0b246afa 4047 ret = btrfs_lookup_csums_range(fs_info->csum_root,
70c8a91c
JB
4048 em->block_start + csum_offset,
4049 em->block_start + csum_offset +
4050 csum_len - 1, &ordered_sums, 0);
4051 if (ret)
4052 return ret;
5dc562c5 4053
70c8a91c
JB
4054 while (!list_empty(&ordered_sums)) {
4055 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4056 struct btrfs_ordered_sum,
4057 list);
4058 if (!ret)
4059 ret = btrfs_csum_file_blocks(trans, log, sums);
4060 list_del(&sums->list);
4061 kfree(sums);
5dc562c5
JB
4062 }
4063
70c8a91c 4064 return ret;
5dc562c5
JB
4065}
4066
8407f553 4067static int log_one_extent(struct btrfs_trans_handle *trans,
9d122629 4068 struct btrfs_inode *inode, struct btrfs_root *root,
8407f553
FM
4069 const struct extent_map *em,
4070 struct btrfs_path *path,
4071 const struct list_head *logged_list,
4072 struct btrfs_log_ctx *ctx)
4073{
4074 struct btrfs_root *log = root->log_root;
4075 struct btrfs_file_extent_item *fi;
4076 struct extent_buffer *leaf;
4077 struct btrfs_map_token token;
4078 struct btrfs_key key;
4079 u64 extent_offset = em->start - em->orig_start;
4080 u64 block_len;
4081 int ret;
4082 int extent_inserted = 0;
4083 bool ordered_io_err = false;
4084
f85b7379
DS
4085 ret = wait_ordered_extents(trans, &inode->vfs_inode, root, em,
4086 logged_list, &ordered_io_err);
8407f553
FM
4087 if (ret)
4088 return ret;
4089
4090 if (ordered_io_err) {
4091 ctx->io_err = -EIO;
ebb70442 4092 return ctx->io_err;
8407f553
FM
4093 }
4094
4095 btrfs_init_map_token(&token);
4096
9d122629 4097 ret = __btrfs_drop_extents(trans, log, &inode->vfs_inode, path, em->start,
8407f553
FM
4098 em->start + em->len, NULL, 0, 1,
4099 sizeof(*fi), &extent_inserted);
4100 if (ret)
4101 return ret;
4102
4103 if (!extent_inserted) {
9d122629 4104 key.objectid = btrfs_ino(inode);
8407f553
FM
4105 key.type = BTRFS_EXTENT_DATA_KEY;
4106 key.offset = em->start;
4107
4108 ret = btrfs_insert_empty_item(trans, log, path, &key,
4109 sizeof(*fi));
4110 if (ret)
4111 return ret;
4112 }
4113 leaf = path->nodes[0];
4114 fi = btrfs_item_ptr(leaf, path->slots[0],
4115 struct btrfs_file_extent_item);
4116
50d9aa99 4117 btrfs_set_token_file_extent_generation(leaf, fi, trans->transid,
8407f553
FM
4118 &token);
4119 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4120 btrfs_set_token_file_extent_type(leaf, fi,
4121 BTRFS_FILE_EXTENT_PREALLOC,
4122 &token);
4123 else
4124 btrfs_set_token_file_extent_type(leaf, fi,
4125 BTRFS_FILE_EXTENT_REG,
4126 &token);
4127
4128 block_len = max(em->block_len, em->orig_block_len);
4129 if (em->compress_type != BTRFS_COMPRESS_NONE) {
4130 btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
4131 em->block_start,
4132 &token);
4133 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
4134 &token);
4135 } else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4136 btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
4137 em->block_start -
4138 extent_offset, &token);
4139 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
4140 &token);
4141 } else {
4142 btrfs_set_token_file_extent_disk_bytenr(leaf, fi, 0, &token);
4143 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, 0,
4144 &token);
4145 }
4146
4147 btrfs_set_token_file_extent_offset(leaf, fi, extent_offset, &token);
4148 btrfs_set_token_file_extent_num_bytes(leaf, fi, em->len, &token);
4149 btrfs_set_token_file_extent_ram_bytes(leaf, fi, em->ram_bytes, &token);
4150 btrfs_set_token_file_extent_compression(leaf, fi, em->compress_type,
4151 &token);
4152 btrfs_set_token_file_extent_encryption(leaf, fi, 0, &token);
4153 btrfs_set_token_file_extent_other_encoding(leaf, fi, 0, &token);
4154 btrfs_mark_buffer_dirty(leaf);
4155
4156 btrfs_release_path(path);
4157
4158 return ret;
4159}
4160
5dc562c5
JB
4161static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
4162 struct btrfs_root *root,
9d122629 4163 struct btrfs_inode *inode,
827463c4 4164 struct btrfs_path *path,
8407f553 4165 struct list_head *logged_list,
de0ee0ed
FM
4166 struct btrfs_log_ctx *ctx,
4167 const u64 start,
4168 const u64 end)
5dc562c5 4169{
5dc562c5
JB
4170 struct extent_map *em, *n;
4171 struct list_head extents;
9d122629 4172 struct extent_map_tree *tree = &inode->extent_tree;
8c6c5928 4173 u64 logged_start, logged_end;
5dc562c5
JB
4174 u64 test_gen;
4175 int ret = 0;
2ab28f32 4176 int num = 0;
5dc562c5
JB
4177
4178 INIT_LIST_HEAD(&extents);
4179
9d122629 4180 down_write(&inode->dio_sem);
5dc562c5
JB
4181 write_lock(&tree->lock);
4182 test_gen = root->fs_info->last_trans_committed;
8c6c5928
JB
4183 logged_start = start;
4184 logged_end = end;
5dc562c5
JB
4185
4186 list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
4187 list_del_init(&em->list);
2ab28f32
JB
4188 /*
4189 * Just an arbitrary number, this can be really CPU intensive
4190 * once we start getting a lot of extents, and really once we
4191 * have a bunch of extents we just want to commit since it will
4192 * be faster.
4193 */
4194 if (++num > 32768) {
4195 list_del_init(&tree->modified_extents);
4196 ret = -EFBIG;
4197 goto process;
4198 }
4199
5dc562c5
JB
4200 if (em->generation <= test_gen)
4201 continue;
8c6c5928
JB
4202
4203 if (em->start < logged_start)
4204 logged_start = em->start;
4205 if ((em->start + em->len - 1) > logged_end)
4206 logged_end = em->start + em->len - 1;
4207
ff44c6e3 4208 /* Need a ref to keep it from getting evicted from cache */
490b54d6 4209 refcount_inc(&em->refs);
ff44c6e3 4210 set_bit(EXTENT_FLAG_LOGGING, &em->flags);
5dc562c5 4211 list_add_tail(&em->list, &extents);
2ab28f32 4212 num++;
5dc562c5
JB
4213 }
4214
4215 list_sort(NULL, &extents, extent_cmp);
8c6c5928 4216 btrfs_get_logged_extents(inode, logged_list, logged_start, logged_end);
de0ee0ed 4217 /*
5f9a8a51
FM
4218 * Some ordered extents started by fsync might have completed
4219 * before we could collect them into the list logged_list, which
4220 * means they're gone, not in our logged_list nor in the inode's
4221 * ordered tree. We want the application/user space to know an
4222 * error happened while attempting to persist file data so that
4223 * it can take proper action. If such error happened, we leave
4224 * without writing to the log tree and the fsync must report the
4225 * file data write error and not commit the current transaction.
de0ee0ed 4226 */
9d122629 4227 ret = filemap_check_errors(inode->vfs_inode.i_mapping);
5f9a8a51
FM
4228 if (ret)
4229 ctx->io_err = ret;
2ab28f32 4230process:
5dc562c5
JB
4231 while (!list_empty(&extents)) {
4232 em = list_entry(extents.next, struct extent_map, list);
4233
4234 list_del_init(&em->list);
4235
4236 /*
4237 * If we had an error we just need to delete everybody from our
4238 * private list.
4239 */
ff44c6e3 4240 if (ret) {
201a9038 4241 clear_em_logging(tree, em);
ff44c6e3 4242 free_extent_map(em);
5dc562c5 4243 continue;
ff44c6e3
JB
4244 }
4245
4246 write_unlock(&tree->lock);
5dc562c5 4247
8407f553
FM
4248 ret = log_one_extent(trans, inode, root, em, path, logged_list,
4249 ctx);
ff44c6e3 4250 write_lock(&tree->lock);
201a9038
JB
4251 clear_em_logging(tree, em);
4252 free_extent_map(em);
5dc562c5 4253 }
ff44c6e3
JB
4254 WARN_ON(!list_empty(&extents));
4255 write_unlock(&tree->lock);
9d122629 4256 up_write(&inode->dio_sem);
5dc562c5 4257
5dc562c5 4258 btrfs_release_path(path);
5dc562c5
JB
4259 return ret;
4260}
4261
481b01c0 4262static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
1a4bcf47
FM
4263 struct btrfs_path *path, u64 *size_ret)
4264{
4265 struct btrfs_key key;
4266 int ret;
4267
481b01c0 4268 key.objectid = btrfs_ino(inode);
1a4bcf47
FM
4269 key.type = BTRFS_INODE_ITEM_KEY;
4270 key.offset = 0;
4271
4272 ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
4273 if (ret < 0) {
4274 return ret;
4275 } else if (ret > 0) {
2f2ff0ee 4276 *size_ret = 0;
1a4bcf47
FM
4277 } else {
4278 struct btrfs_inode_item *item;
4279
4280 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4281 struct btrfs_inode_item);
4282 *size_ret = btrfs_inode_size(path->nodes[0], item);
4283 }
4284
4285 btrfs_release_path(path);
4286 return 0;
4287}
4288
36283bf7
FM
4289/*
4290 * At the moment we always log all xattrs. This is to figure out at log replay
4291 * time which xattrs must have their deletion replayed. If a xattr is missing
4292 * in the log tree and exists in the fs/subvol tree, we delete it. This is
4293 * because if a xattr is deleted, the inode is fsynced and a power failure
4294 * happens, causing the log to be replayed the next time the fs is mounted,
4295 * we want the xattr to not exist anymore (same behaviour as other filesystems
4296 * with a journal, ext3/4, xfs, f2fs, etc).
4297 */
4298static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
4299 struct btrfs_root *root,
1a93c36a 4300 struct btrfs_inode *inode,
36283bf7
FM
4301 struct btrfs_path *path,
4302 struct btrfs_path *dst_path)
4303{
4304 int ret;
4305 struct btrfs_key key;
1a93c36a 4306 const u64 ino = btrfs_ino(inode);
36283bf7
FM
4307 int ins_nr = 0;
4308 int start_slot = 0;
4309
4310 key.objectid = ino;
4311 key.type = BTRFS_XATTR_ITEM_KEY;
4312 key.offset = 0;
4313
4314 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4315 if (ret < 0)
4316 return ret;
4317
4318 while (true) {
4319 int slot = path->slots[0];
4320 struct extent_buffer *leaf = path->nodes[0];
4321 int nritems = btrfs_header_nritems(leaf);
4322
4323 if (slot >= nritems) {
4324 if (ins_nr > 0) {
4325 u64 last_extent = 0;
4326
1a93c36a 4327 ret = copy_items(trans, inode, dst_path, path,
36283bf7
FM
4328 &last_extent, start_slot,
4329 ins_nr, 1, 0);
4330 /* can't be 1, extent items aren't processed */
4331 ASSERT(ret <= 0);
4332 if (ret < 0)
4333 return ret;
4334 ins_nr = 0;
4335 }
4336 ret = btrfs_next_leaf(root, path);
4337 if (ret < 0)
4338 return ret;
4339 else if (ret > 0)
4340 break;
4341 continue;
4342 }
4343
4344 btrfs_item_key_to_cpu(leaf, &key, slot);
4345 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
4346 break;
4347
4348 if (ins_nr == 0)
4349 start_slot = slot;
4350 ins_nr++;
4351 path->slots[0]++;
4352 cond_resched();
4353 }
4354 if (ins_nr > 0) {
4355 u64 last_extent = 0;
4356
1a93c36a 4357 ret = copy_items(trans, inode, dst_path, path,
36283bf7
FM
4358 &last_extent, start_slot,
4359 ins_nr, 1, 0);
4360 /* can't be 1, extent items aren't processed */
4361 ASSERT(ret <= 0);
4362 if (ret < 0)
4363 return ret;
4364 }
4365
4366 return 0;
4367}
4368
a89ca6f2
FM
4369/*
4370 * If the no holes feature is enabled we need to make sure any hole between the
4371 * last extent and the i_size of our inode is explicitly marked in the log. This
4372 * is to make sure that doing something like:
4373 *
4374 * 1) create file with 128Kb of data
4375 * 2) truncate file to 64Kb
4376 * 3) truncate file to 256Kb
4377 * 4) fsync file
4378 * 5) <crash/power failure>
4379 * 6) mount fs and trigger log replay
4380 *
4381 * Will give us a file with a size of 256Kb, the first 64Kb of data match what
4382 * the file had in its first 64Kb of data at step 1 and the last 192Kb of the
4383 * file correspond to a hole. The presence of explicit holes in a log tree is
4384 * what guarantees that log replay will remove/adjust file extent items in the
4385 * fs/subvol tree.
4386 *
4387 * Here we do not need to care about holes between extents, that is already done
4388 * by copy_items(). We also only need to do this in the full sync path, where we
4389 * lookup for extents from the fs/subvol tree only. In the fast path case, we
4390 * lookup the list of modified extent maps and if any represents a hole, we
4391 * insert a corresponding extent representing a hole in the log tree.
4392 */
4393static int btrfs_log_trailing_hole(struct btrfs_trans_handle *trans,
4394 struct btrfs_root *root,
a0308dd7 4395 struct btrfs_inode *inode,
a89ca6f2
FM
4396 struct btrfs_path *path)
4397{
0b246afa 4398 struct btrfs_fs_info *fs_info = root->fs_info;
a89ca6f2
FM
4399 int ret;
4400 struct btrfs_key key;
4401 u64 hole_start;
4402 u64 hole_size;
4403 struct extent_buffer *leaf;
4404 struct btrfs_root *log = root->log_root;
a0308dd7
NB
4405 const u64 ino = btrfs_ino(inode);
4406 const u64 i_size = i_size_read(&inode->vfs_inode);
a89ca6f2 4407
0b246afa 4408 if (!btrfs_fs_incompat(fs_info, NO_HOLES))
a89ca6f2
FM
4409 return 0;
4410
4411 key.objectid = ino;
4412 key.type = BTRFS_EXTENT_DATA_KEY;
4413 key.offset = (u64)-1;
4414
4415 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4416 ASSERT(ret != 0);
4417 if (ret < 0)
4418 return ret;
4419
4420 ASSERT(path->slots[0] > 0);
4421 path->slots[0]--;
4422 leaf = path->nodes[0];
4423 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4424
4425 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
4426 /* inode does not have any extents */
4427 hole_start = 0;
4428 hole_size = i_size;
4429 } else {
4430 struct btrfs_file_extent_item *extent;
4431 u64 len;
4432
4433 /*
4434 * If there's an extent beyond i_size, an explicit hole was
4435 * already inserted by copy_items().
4436 */
4437 if (key.offset >= i_size)
4438 return 0;
4439
4440 extent = btrfs_item_ptr(leaf, path->slots[0],
4441 struct btrfs_file_extent_item);
4442
4443 if (btrfs_file_extent_type(leaf, extent) ==
4444 BTRFS_FILE_EXTENT_INLINE) {
4445 len = btrfs_file_extent_inline_len(leaf,
4446 path->slots[0],
4447 extent);
6399fb5a
FM
4448 ASSERT(len == i_size ||
4449 (len == fs_info->sectorsize &&
4450 btrfs_file_extent_compression(leaf, extent) !=
4451 BTRFS_COMPRESS_NONE));
a89ca6f2
FM
4452 return 0;
4453 }
4454
4455 len = btrfs_file_extent_num_bytes(leaf, extent);
4456 /* Last extent goes beyond i_size, no need to log a hole. */
4457 if (key.offset + len > i_size)
4458 return 0;
4459 hole_start = key.offset + len;
4460 hole_size = i_size - hole_start;
4461 }
4462 btrfs_release_path(path);
4463
4464 /* Last extent ends at i_size. */
4465 if (hole_size == 0)
4466 return 0;
4467
0b246afa 4468 hole_size = ALIGN(hole_size, fs_info->sectorsize);
a89ca6f2
FM
4469 ret = btrfs_insert_file_extent(trans, log, ino, hole_start, 0, 0,
4470 hole_size, 0, hole_size, 0, 0, 0);
4471 return ret;
4472}
4473
56f23fdb
FM
4474/*
4475 * When we are logging a new inode X, check if it doesn't have a reference that
4476 * matches the reference from some other inode Y created in a past transaction
4477 * and that was renamed in the current transaction. If we don't do this, then at
4478 * log replay time we can lose inode Y (and all its files if it's a directory):
4479 *
4480 * mkdir /mnt/x
4481 * echo "hello world" > /mnt/x/foobar
4482 * sync
4483 * mv /mnt/x /mnt/y
4484 * mkdir /mnt/x # or touch /mnt/x
4485 * xfs_io -c fsync /mnt/x
4486 * <power fail>
4487 * mount fs, trigger log replay
4488 *
4489 * After the log replay procedure, we would lose the first directory and all its
4490 * files (file foobar).
4491 * For the case where inode Y is not a directory we simply end up losing it:
4492 *
4493 * echo "123" > /mnt/foo
4494 * sync
4495 * mv /mnt/foo /mnt/bar
4496 * echo "abc" > /mnt/foo
4497 * xfs_io -c fsync /mnt/foo
4498 * <power fail>
4499 *
4500 * We also need this for cases where a snapshot entry is replaced by some other
4501 * entry (file or directory) otherwise we end up with an unreplayable log due to
4502 * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
4503 * if it were a regular entry:
4504 *
4505 * mkdir /mnt/x
4506 * btrfs subvolume snapshot /mnt /mnt/x/snap
4507 * btrfs subvolume delete /mnt/x/snap
4508 * rmdir /mnt/x
4509 * mkdir /mnt/x
4510 * fsync /mnt/x or fsync some new file inside it
4511 * <power fail>
4512 *
4513 * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
4514 * the same transaction.
4515 */
4516static int btrfs_check_ref_name_override(struct extent_buffer *eb,
4517 const int slot,
4518 const struct btrfs_key *key,
4791c8f1 4519 struct btrfs_inode *inode,
44f714da 4520 u64 *other_ino)
56f23fdb
FM
4521{
4522 int ret;
4523 struct btrfs_path *search_path;
4524 char *name = NULL;
4525 u32 name_len = 0;
4526 u32 item_size = btrfs_item_size_nr(eb, slot);
4527 u32 cur_offset = 0;
4528 unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
4529
4530 search_path = btrfs_alloc_path();
4531 if (!search_path)
4532 return -ENOMEM;
4533 search_path->search_commit_root = 1;
4534 search_path->skip_locking = 1;
4535
4536 while (cur_offset < item_size) {
4537 u64 parent;
4538 u32 this_name_len;
4539 u32 this_len;
4540 unsigned long name_ptr;
4541 struct btrfs_dir_item *di;
4542
4543 if (key->type == BTRFS_INODE_REF_KEY) {
4544 struct btrfs_inode_ref *iref;
4545
4546 iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
4547 parent = key->offset;
4548 this_name_len = btrfs_inode_ref_name_len(eb, iref);
4549 name_ptr = (unsigned long)(iref + 1);
4550 this_len = sizeof(*iref) + this_name_len;
4551 } else {
4552 struct btrfs_inode_extref *extref;
4553
4554 extref = (struct btrfs_inode_extref *)(ptr +
4555 cur_offset);
4556 parent = btrfs_inode_extref_parent(eb, extref);
4557 this_name_len = btrfs_inode_extref_name_len(eb, extref);
4558 name_ptr = (unsigned long)&extref->name;
4559 this_len = sizeof(*extref) + this_name_len;
4560 }
4561
4562 if (this_name_len > name_len) {
4563 char *new_name;
4564
4565 new_name = krealloc(name, this_name_len, GFP_NOFS);
4566 if (!new_name) {
4567 ret = -ENOMEM;
4568 goto out;
4569 }
4570 name_len = this_name_len;
4571 name = new_name;
4572 }
4573
4574 read_extent_buffer(eb, name, name_ptr, this_name_len);
4791c8f1
NB
4575 di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
4576 parent, name, this_name_len, 0);
56f23fdb 4577 if (di && !IS_ERR(di)) {
44f714da
FM
4578 struct btrfs_key di_key;
4579
4580 btrfs_dir_item_key_to_cpu(search_path->nodes[0],
4581 di, &di_key);
4582 if (di_key.type == BTRFS_INODE_ITEM_KEY) {
4583 ret = 1;
4584 *other_ino = di_key.objectid;
4585 } else {
4586 ret = -EAGAIN;
4587 }
56f23fdb
FM
4588 goto out;
4589 } else if (IS_ERR(di)) {
4590 ret = PTR_ERR(di);
4591 goto out;
4592 }
4593 btrfs_release_path(search_path);
4594
4595 cur_offset += this_len;
4596 }
4597 ret = 0;
4598out:
4599 btrfs_free_path(search_path);
4600 kfree(name);
4601 return ret;
4602}
4603
e02119d5
CM
4604/* log a single inode in the tree log.
4605 * At least one parent directory for this inode must exist in the tree
4606 * or be logged already.
4607 *
4608 * Any items from this inode changed by the current transaction are copied
4609 * to the log tree. An extra reference is taken on any extents in this
4610 * file, allowing us to avoid a whole pile of corner cases around logging
4611 * blocks that have been removed from the tree.
4612 *
4613 * See LOG_INODE_ALL and related defines for a description of what inode_only
4614 * does.
4615 *
4616 * This handles both files and directories.
4617 */
12fcfd22 4618static int btrfs_log_inode(struct btrfs_trans_handle *trans,
a59108a7 4619 struct btrfs_root *root, struct btrfs_inode *inode,
49dae1bc
FM
4620 int inode_only,
4621 const loff_t start,
8407f553
FM
4622 const loff_t end,
4623 struct btrfs_log_ctx *ctx)
e02119d5 4624{
0b246afa 4625 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5
CM
4626 struct btrfs_path *path;
4627 struct btrfs_path *dst_path;
4628 struct btrfs_key min_key;
4629 struct btrfs_key max_key;
4630 struct btrfs_root *log = root->log_root;
827463c4 4631 LIST_HEAD(logged_list);
16e7549f 4632 u64 last_extent = 0;
4a500fd1 4633 int err = 0;
e02119d5 4634 int ret;
3a5f1d45 4635 int nritems;
31ff1cd2
CM
4636 int ins_start_slot = 0;
4637 int ins_nr;
5dc562c5 4638 bool fast_search = false;
a59108a7
NB
4639 u64 ino = btrfs_ino(inode);
4640 struct extent_map_tree *em_tree = &inode->extent_tree;
1a4bcf47 4641 u64 logged_isize = 0;
e4545de5 4642 bool need_log_inode_item = true;
e02119d5 4643
e02119d5 4644 path = btrfs_alloc_path();
5df67083
TI
4645 if (!path)
4646 return -ENOMEM;
e02119d5 4647 dst_path = btrfs_alloc_path();
5df67083
TI
4648 if (!dst_path) {
4649 btrfs_free_path(path);
4650 return -ENOMEM;
4651 }
e02119d5 4652
33345d01 4653 min_key.objectid = ino;
e02119d5
CM
4654 min_key.type = BTRFS_INODE_ITEM_KEY;
4655 min_key.offset = 0;
4656
33345d01 4657 max_key.objectid = ino;
12fcfd22 4658
12fcfd22 4659
5dc562c5 4660 /* today the code can only do partial logging of directories */
a59108a7 4661 if (S_ISDIR(inode->vfs_inode.i_mode) ||
5269b67e 4662 (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
a59108a7 4663 &inode->runtime_flags) &&
781feef7 4664 inode_only >= LOG_INODE_EXISTS))
e02119d5
CM
4665 max_key.type = BTRFS_XATTR_ITEM_KEY;
4666 else
4667 max_key.type = (u8)-1;
4668 max_key.offset = (u64)-1;
4669
2c2c452b
FM
4670 /*
4671 * Only run delayed items if we are a dir or a new file.
4672 * Otherwise commit the delayed inode only, which is needed in
4673 * order for the log replay code to mark inodes for link count
4674 * fixup (create temporary BTRFS_TREE_LOG_FIXUP_OBJECTID items).
4675 */
a59108a7
NB
4676 if (S_ISDIR(inode->vfs_inode.i_mode) ||
4677 inode->generation > fs_info->last_trans_committed)
4678 ret = btrfs_commit_inode_delayed_items(trans, inode);
2c2c452b 4679 else
a59108a7 4680 ret = btrfs_commit_inode_delayed_inode(inode);
2c2c452b
FM
4681
4682 if (ret) {
4683 btrfs_free_path(path);
4684 btrfs_free_path(dst_path);
4685 return ret;
16cdcec7
MX
4686 }
4687
781feef7
LB
4688 if (inode_only == LOG_OTHER_INODE) {
4689 inode_only = LOG_INODE_EXISTS;
a59108a7 4690 mutex_lock_nested(&inode->log_mutex, SINGLE_DEPTH_NESTING);
781feef7 4691 } else {
a59108a7 4692 mutex_lock(&inode->log_mutex);
781feef7 4693 }
e02119d5
CM
4694
4695 /*
4696 * a brute force approach to making sure we get the most uptodate
4697 * copies of everything.
4698 */
a59108a7 4699 if (S_ISDIR(inode->vfs_inode.i_mode)) {
e02119d5
CM
4700 int max_key_type = BTRFS_DIR_LOG_INDEX_KEY;
4701
4f764e51
FM
4702 if (inode_only == LOG_INODE_EXISTS)
4703 max_key_type = BTRFS_XATTR_ITEM_KEY;
33345d01 4704 ret = drop_objectid_items(trans, log, path, ino, max_key_type);
e02119d5 4705 } else {
1a4bcf47
FM
4706 if (inode_only == LOG_INODE_EXISTS) {
4707 /*
4708 * Make sure the new inode item we write to the log has
4709 * the same isize as the current one (if it exists).
4710 * This is necessary to prevent data loss after log
4711 * replay, and also to prevent doing a wrong expanding
4712 * truncate - for e.g. create file, write 4K into offset
4713 * 0, fsync, write 4K into offset 4096, add hard link,
4714 * fsync some other file (to sync log), power fail - if
4715 * we use the inode's current i_size, after log replay
4716 * we get a 8Kb file, with the last 4Kb extent as a hole
4717 * (zeroes), as if an expanding truncate happened,
4718 * instead of getting a file of 4Kb only.
4719 */
a59108a7 4720 err = logged_inode_size(log, inode, path, &logged_isize);
1a4bcf47
FM
4721 if (err)
4722 goto out_unlock;
4723 }
a742994a 4724 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
a59108a7 4725 &inode->runtime_flags)) {
a742994a 4726 if (inode_only == LOG_INODE_EXISTS) {
4f764e51 4727 max_key.type = BTRFS_XATTR_ITEM_KEY;
a742994a
FM
4728 ret = drop_objectid_items(trans, log, path, ino,
4729 max_key.type);
4730 } else {
4731 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
a59108a7 4732 &inode->runtime_flags);
a742994a 4733 clear_bit(BTRFS_INODE_COPY_EVERYTHING,
a59108a7 4734 &inode->runtime_flags);
28ed1345
CM
4735 while(1) {
4736 ret = btrfs_truncate_inode_items(trans,
a59108a7 4737 log, &inode->vfs_inode, 0, 0);
28ed1345
CM
4738 if (ret != -EAGAIN)
4739 break;
4740 }
a742994a 4741 }
4f764e51 4742 } else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
a59108a7 4743 &inode->runtime_flags) ||
6cfab851 4744 inode_only == LOG_INODE_EXISTS) {
4f764e51 4745 if (inode_only == LOG_INODE_ALL)
183f37fa 4746 fast_search = true;
4f764e51 4747 max_key.type = BTRFS_XATTR_ITEM_KEY;
5dc562c5 4748 ret = drop_objectid_items(trans, log, path, ino,
e9976151 4749 max_key.type);
a95249b3
JB
4750 } else {
4751 if (inode_only == LOG_INODE_ALL)
4752 fast_search = true;
a95249b3 4753 goto log_extents;
5dc562c5 4754 }
a95249b3 4755
e02119d5 4756 }
4a500fd1
YZ
4757 if (ret) {
4758 err = ret;
4759 goto out_unlock;
4760 }
e02119d5 4761
d397712b 4762 while (1) {
31ff1cd2 4763 ins_nr = 0;
6174d3cb 4764 ret = btrfs_search_forward(root, &min_key,
de78b51a 4765 path, trans->transid);
fb770ae4
LB
4766 if (ret < 0) {
4767 err = ret;
4768 goto out_unlock;
4769 }
e02119d5
CM
4770 if (ret != 0)
4771 break;
3a5f1d45 4772again:
31ff1cd2 4773 /* note, ins_nr might be > 0 here, cleanup outside the loop */
33345d01 4774 if (min_key.objectid != ino)
e02119d5
CM
4775 break;
4776 if (min_key.type > max_key.type)
4777 break;
31ff1cd2 4778
e4545de5
FM
4779 if (min_key.type == BTRFS_INODE_ITEM_KEY)
4780 need_log_inode_item = false;
4781
56f23fdb
FM
4782 if ((min_key.type == BTRFS_INODE_REF_KEY ||
4783 min_key.type == BTRFS_INODE_EXTREF_KEY) &&
a59108a7 4784 inode->generation == trans->transid) {
44f714da
FM
4785 u64 other_ino = 0;
4786
56f23fdb 4787 ret = btrfs_check_ref_name_override(path->nodes[0],
a59108a7
NB
4788 path->slots[0], &min_key, inode,
4789 &other_ino);
56f23fdb
FM
4790 if (ret < 0) {
4791 err = ret;
4792 goto out_unlock;
28a23593 4793 } else if (ret > 0 && ctx &&
4a0cc7ca 4794 other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
44f714da
FM
4795 struct btrfs_key inode_key;
4796 struct inode *other_inode;
4797
4798 if (ins_nr > 0) {
4799 ins_nr++;
4800 } else {
4801 ins_nr = 1;
4802 ins_start_slot = path->slots[0];
4803 }
a59108a7 4804 ret = copy_items(trans, inode, dst_path, path,
44f714da
FM
4805 &last_extent, ins_start_slot,
4806 ins_nr, inode_only,
4807 logged_isize);
4808 if (ret < 0) {
4809 err = ret;
4810 goto out_unlock;
4811 }
4812 ins_nr = 0;
4813 btrfs_release_path(path);
4814 inode_key.objectid = other_ino;
4815 inode_key.type = BTRFS_INODE_ITEM_KEY;
4816 inode_key.offset = 0;
0b246afa 4817 other_inode = btrfs_iget(fs_info->sb,
44f714da
FM
4818 &inode_key, root,
4819 NULL);
4820 /*
4821 * If the other inode that had a conflicting dir
4822 * entry was deleted in the current transaction,
4823 * we don't need to do more work nor fallback to
4824 * a transaction commit.
4825 */
4826 if (IS_ERR(other_inode) &&
4827 PTR_ERR(other_inode) == -ENOENT) {
4828 goto next_key;
4829 } else if (IS_ERR(other_inode)) {
4830 err = PTR_ERR(other_inode);
4831 goto out_unlock;
4832 }
4833 /*
4834 * We are safe logging the other inode without
4835 * acquiring its i_mutex as long as we log with
4836 * the LOG_INODE_EXISTS mode. We're safe against
4837 * concurrent renames of the other inode as well
4838 * because during a rename we pin the log and
4839 * update the log with the new name before we
4840 * unpin it.
4841 */
a59108a7
NB
4842 err = btrfs_log_inode(trans, root,
4843 BTRFS_I(other_inode),
4844 LOG_OTHER_INODE, 0, LLONG_MAX,
4845 ctx);
44f714da
FM
4846 iput(other_inode);
4847 if (err)
4848 goto out_unlock;
4849 else
4850 goto next_key;
56f23fdb
FM
4851 }
4852 }
4853
36283bf7
FM
4854 /* Skip xattrs, we log them later with btrfs_log_all_xattrs() */
4855 if (min_key.type == BTRFS_XATTR_ITEM_KEY) {
4856 if (ins_nr == 0)
4857 goto next_slot;
a59108a7 4858 ret = copy_items(trans, inode, dst_path, path,
36283bf7
FM
4859 &last_extent, ins_start_slot,
4860 ins_nr, inode_only, logged_isize);
4861 if (ret < 0) {
4862 err = ret;
4863 goto out_unlock;
4864 }
4865 ins_nr = 0;
4866 if (ret) {
4867 btrfs_release_path(path);
4868 continue;
4869 }
4870 goto next_slot;
4871 }
4872
31ff1cd2
CM
4873 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
4874 ins_nr++;
4875 goto next_slot;
4876 } else if (!ins_nr) {
4877 ins_start_slot = path->slots[0];
4878 ins_nr = 1;
4879 goto next_slot;
e02119d5
CM
4880 }
4881
a59108a7 4882 ret = copy_items(trans, inode, dst_path, path, &last_extent,
1a4bcf47
FM
4883 ins_start_slot, ins_nr, inode_only,
4884 logged_isize);
16e7549f 4885 if (ret < 0) {
4a500fd1
YZ
4886 err = ret;
4887 goto out_unlock;
a71db86e
RV
4888 }
4889 if (ret) {
16e7549f
JB
4890 ins_nr = 0;
4891 btrfs_release_path(path);
4892 continue;
4a500fd1 4893 }
31ff1cd2
CM
4894 ins_nr = 1;
4895 ins_start_slot = path->slots[0];
4896next_slot:
e02119d5 4897
3a5f1d45
CM
4898 nritems = btrfs_header_nritems(path->nodes[0]);
4899 path->slots[0]++;
4900 if (path->slots[0] < nritems) {
4901 btrfs_item_key_to_cpu(path->nodes[0], &min_key,
4902 path->slots[0]);
4903 goto again;
4904 }
31ff1cd2 4905 if (ins_nr) {
a59108a7 4906 ret = copy_items(trans, inode, dst_path, path,
16e7549f 4907 &last_extent, ins_start_slot,
1a4bcf47 4908 ins_nr, inode_only, logged_isize);
16e7549f 4909 if (ret < 0) {
4a500fd1
YZ
4910 err = ret;
4911 goto out_unlock;
4912 }
16e7549f 4913 ret = 0;
31ff1cd2
CM
4914 ins_nr = 0;
4915 }
b3b4aa74 4916 btrfs_release_path(path);
44f714da 4917next_key:
3d41d702 4918 if (min_key.offset < (u64)-1) {
e02119d5 4919 min_key.offset++;
3d41d702 4920 } else if (min_key.type < max_key.type) {
e02119d5 4921 min_key.type++;
3d41d702
FDBM
4922 min_key.offset = 0;
4923 } else {
e02119d5 4924 break;
3d41d702 4925 }
e02119d5 4926 }
31ff1cd2 4927 if (ins_nr) {
a59108a7 4928 ret = copy_items(trans, inode, dst_path, path, &last_extent,
1a4bcf47
FM
4929 ins_start_slot, ins_nr, inode_only,
4930 logged_isize);
16e7549f 4931 if (ret < 0) {
4a500fd1
YZ
4932 err = ret;
4933 goto out_unlock;
4934 }
16e7549f 4935 ret = 0;
31ff1cd2
CM
4936 ins_nr = 0;
4937 }
5dc562c5 4938
36283bf7
FM
4939 btrfs_release_path(path);
4940 btrfs_release_path(dst_path);
a59108a7 4941 err = btrfs_log_all_xattrs(trans, root, inode, path, dst_path);
36283bf7
FM
4942 if (err)
4943 goto out_unlock;
a89ca6f2
FM
4944 if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
4945 btrfs_release_path(path);
4946 btrfs_release_path(dst_path);
a59108a7 4947 err = btrfs_log_trailing_hole(trans, root, inode, path);
a89ca6f2
FM
4948 if (err)
4949 goto out_unlock;
4950 }
a95249b3 4951log_extents:
f3b15ccd
JB
4952 btrfs_release_path(path);
4953 btrfs_release_path(dst_path);
e4545de5 4954 if (need_log_inode_item) {
a59108a7 4955 err = log_inode_item(trans, log, dst_path, inode);
e4545de5
FM
4956 if (err)
4957 goto out_unlock;
4958 }
5dc562c5 4959 if (fast_search) {
a59108a7 4960 ret = btrfs_log_changed_extents(trans, root, inode, dst_path,
de0ee0ed 4961 &logged_list, ctx, start, end);
5dc562c5
JB
4962 if (ret) {
4963 err = ret;
4964 goto out_unlock;
4965 }
d006a048 4966 } else if (inode_only == LOG_INODE_ALL) {
06d3d22b
LB
4967 struct extent_map *em, *n;
4968
49dae1bc
FM
4969 write_lock(&em_tree->lock);
4970 /*
4971 * We can't just remove every em if we're called for a ranged
4972 * fsync - that is, one that doesn't cover the whole possible
4973 * file range (0 to LLONG_MAX). This is because we can have
4974 * em's that fall outside the range we're logging and therefore
4975 * their ordered operations haven't completed yet
4976 * (btrfs_finish_ordered_io() not invoked yet). This means we
4977 * didn't get their respective file extent item in the fs/subvol
4978 * tree yet, and need to let the next fast fsync (one which
4979 * consults the list of modified extent maps) find the em so
4980 * that it logs a matching file extent item and waits for the
4981 * respective ordered operation to complete (if it's still
4982 * running).
4983 *
4984 * Removing every em outside the range we're logging would make
4985 * the next fast fsync not log their matching file extent items,
4986 * therefore making us lose data after a log replay.
4987 */
4988 list_for_each_entry_safe(em, n, &em_tree->modified_extents,
4989 list) {
4990 const u64 mod_end = em->mod_start + em->mod_len - 1;
4991
4992 if (em->mod_start >= start && mod_end <= end)
4993 list_del_init(&em->list);
4994 }
4995 write_unlock(&em_tree->lock);
5dc562c5
JB
4996 }
4997
a59108a7
NB
4998 if (inode_only == LOG_INODE_ALL && S_ISDIR(inode->vfs_inode.i_mode)) {
4999 ret = log_directory_changes(trans, root, inode, path, dst_path,
5000 ctx);
4a500fd1
YZ
5001 if (ret) {
5002 err = ret;
5003 goto out_unlock;
5004 }
e02119d5 5005 }
49dae1bc 5006
a59108a7
NB
5007 spin_lock(&inode->lock);
5008 inode->logged_trans = trans->transid;
5009 inode->last_log_commit = inode->last_sub_trans;
5010 spin_unlock(&inode->lock);
4a500fd1 5011out_unlock:
827463c4
MX
5012 if (unlikely(err))
5013 btrfs_put_logged_extents(&logged_list);
5014 else
5015 btrfs_submit_logged_extents(&logged_list, log);
a59108a7 5016 mutex_unlock(&inode->log_mutex);
e02119d5
CM
5017
5018 btrfs_free_path(path);
5019 btrfs_free_path(dst_path);
4a500fd1 5020 return err;
e02119d5
CM
5021}
5022
2be63d5c
FM
5023/*
5024 * Check if we must fallback to a transaction commit when logging an inode.
5025 * This must be called after logging the inode and is used only in the context
5026 * when fsyncing an inode requires the need to log some other inode - in which
5027 * case we can't lock the i_mutex of each other inode we need to log as that
5028 * can lead to deadlocks with concurrent fsync against other inodes (as we can
5029 * log inodes up or down in the hierarchy) or rename operations for example. So
5030 * we take the log_mutex of the inode after we have logged it and then check for
5031 * its last_unlink_trans value - this is safe because any task setting
5032 * last_unlink_trans must take the log_mutex and it must do this before it does
5033 * the actual unlink operation, so if we do this check before a concurrent task
5034 * sets last_unlink_trans it means we've logged a consistent version/state of
5035 * all the inode items, otherwise we are not sure and must do a transaction
01327610 5036 * commit (the concurrent task might have only updated last_unlink_trans before
2be63d5c
FM
5037 * we logged the inode or it might have also done the unlink).
5038 */
5039static bool btrfs_must_commit_transaction(struct btrfs_trans_handle *trans,
ab1717b2 5040 struct btrfs_inode *inode)
2be63d5c 5041{
ab1717b2 5042 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2be63d5c
FM
5043 bool ret = false;
5044
ab1717b2
NB
5045 mutex_lock(&inode->log_mutex);
5046 if (inode->last_unlink_trans > fs_info->last_trans_committed) {
2be63d5c
FM
5047 /*
5048 * Make sure any commits to the log are forced to be full
5049 * commits.
5050 */
5051 btrfs_set_log_full_commit(fs_info, trans);
5052 ret = true;
5053 }
ab1717b2 5054 mutex_unlock(&inode->log_mutex);
2be63d5c
FM
5055
5056 return ret;
5057}
5058
12fcfd22
CM
5059/*
5060 * follow the dentry parent pointers up the chain and see if any
5061 * of the directories in it require a full commit before they can
5062 * be logged. Returns zero if nothing special needs to be done or 1 if
5063 * a full commit is required.
5064 */
5065static noinline int check_parent_dirs_for_sync(struct btrfs_trans_handle *trans,
aefa6115 5066 struct btrfs_inode *inode,
12fcfd22
CM
5067 struct dentry *parent,
5068 struct super_block *sb,
5069 u64 last_committed)
e02119d5 5070{
12fcfd22 5071 int ret = 0;
6a912213 5072 struct dentry *old_parent = NULL;
aefa6115 5073 struct btrfs_inode *orig_inode = inode;
e02119d5 5074
af4176b4
CM
5075 /*
5076 * for regular files, if its inode is already on disk, we don't
5077 * have to worry about the parents at all. This is because
5078 * we can use the last_unlink_trans field to record renames
5079 * and other fun in this file.
5080 */
aefa6115
NB
5081 if (S_ISREG(inode->vfs_inode.i_mode) &&
5082 inode->generation <= last_committed &&
5083 inode->last_unlink_trans <= last_committed)
5084 goto out;
af4176b4 5085
aefa6115 5086 if (!S_ISDIR(inode->vfs_inode.i_mode)) {
fc64005c 5087 if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
12fcfd22 5088 goto out;
aefa6115 5089 inode = BTRFS_I(d_inode(parent));
12fcfd22
CM
5090 }
5091
5092 while (1) {
de2b530b
JB
5093 /*
5094 * If we are logging a directory then we start with our inode,
01327610 5095 * not our parent's inode, so we need to skip setting the
de2b530b
JB
5096 * logged_trans so that further down in the log code we don't
5097 * think this inode has already been logged.
5098 */
5099 if (inode != orig_inode)
aefa6115 5100 inode->logged_trans = trans->transid;
12fcfd22
CM
5101 smp_mb();
5102
aefa6115 5103 if (btrfs_must_commit_transaction(trans, inode)) {
12fcfd22
CM
5104 ret = 1;
5105 break;
5106 }
5107
fc64005c 5108 if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
12fcfd22
CM
5109 break;
5110
44f714da 5111 if (IS_ROOT(parent)) {
aefa6115
NB
5112 inode = BTRFS_I(d_inode(parent));
5113 if (btrfs_must_commit_transaction(trans, inode))
44f714da 5114 ret = 1;
12fcfd22 5115 break;
44f714da 5116 }
12fcfd22 5117
6a912213
JB
5118 parent = dget_parent(parent);
5119 dput(old_parent);
5120 old_parent = parent;
aefa6115 5121 inode = BTRFS_I(d_inode(parent));
12fcfd22
CM
5122
5123 }
6a912213 5124 dput(old_parent);
12fcfd22 5125out:
e02119d5
CM
5126 return ret;
5127}
5128
2f2ff0ee
FM
5129struct btrfs_dir_list {
5130 u64 ino;
5131 struct list_head list;
5132};
5133
5134/*
5135 * Log the inodes of the new dentries of a directory. See log_dir_items() for
5136 * details about the why it is needed.
5137 * This is a recursive operation - if an existing dentry corresponds to a
5138 * directory, that directory's new entries are logged too (same behaviour as
5139 * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5140 * the dentries point to we do not lock their i_mutex, otherwise lockdep
5141 * complains about the following circular lock dependency / possible deadlock:
5142 *
5143 * CPU0 CPU1
5144 * ---- ----
5145 * lock(&type->i_mutex_dir_key#3/2);
5146 * lock(sb_internal#2);
5147 * lock(&type->i_mutex_dir_key#3/2);
5148 * lock(&sb->s_type->i_mutex_key#14);
5149 *
5150 * Where sb_internal is the lock (a counter that works as a lock) acquired by
5151 * sb_start_intwrite() in btrfs_start_transaction().
5152 * Not locking i_mutex of the inodes is still safe because:
5153 *
5154 * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5155 * that while logging the inode new references (names) are added or removed
5156 * from the inode, leaving the logged inode item with a link count that does
5157 * not match the number of logged inode reference items. This is fine because
5158 * at log replay time we compute the real number of links and correct the
5159 * link count in the inode item (see replay_one_buffer() and
5160 * link_to_fixup_dir());
5161 *
5162 * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5163 * while logging the inode's items new items with keys BTRFS_DIR_ITEM_KEY and
5164 * BTRFS_DIR_INDEX_KEY are added to fs/subvol tree and the logged inode item
5165 * has a size that doesn't match the sum of the lengths of all the logged
5166 * names. This does not result in a problem because if a dir_item key is
5167 * logged but its matching dir_index key is not logged, at log replay time we
5168 * don't use it to replay the respective name (see replay_one_name()). On the
5169 * other hand if only the dir_index key ends up being logged, the respective
5170 * name is added to the fs/subvol tree with both the dir_item and dir_index
5171 * keys created (see replay_one_name()).
5172 * The directory's inode item with a wrong i_size is not a problem as well,
5173 * since we don't use it at log replay time to set the i_size in the inode
5174 * item of the fs/subvol tree (see overwrite_item()).
5175 */
5176static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5177 struct btrfs_root *root,
51cc0d32 5178 struct btrfs_inode *start_inode,
2f2ff0ee
FM
5179 struct btrfs_log_ctx *ctx)
5180{
0b246afa 5181 struct btrfs_fs_info *fs_info = root->fs_info;
2f2ff0ee
FM
5182 struct btrfs_root *log = root->log_root;
5183 struct btrfs_path *path;
5184 LIST_HEAD(dir_list);
5185 struct btrfs_dir_list *dir_elem;
5186 int ret = 0;
5187
5188 path = btrfs_alloc_path();
5189 if (!path)
5190 return -ENOMEM;
5191
5192 dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5193 if (!dir_elem) {
5194 btrfs_free_path(path);
5195 return -ENOMEM;
5196 }
51cc0d32 5197 dir_elem->ino = btrfs_ino(start_inode);
2f2ff0ee
FM
5198 list_add_tail(&dir_elem->list, &dir_list);
5199
5200 while (!list_empty(&dir_list)) {
5201 struct extent_buffer *leaf;
5202 struct btrfs_key min_key;
5203 int nritems;
5204 int i;
5205
5206 dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list,
5207 list);
5208 if (ret)
5209 goto next_dir_inode;
5210
5211 min_key.objectid = dir_elem->ino;
5212 min_key.type = BTRFS_DIR_ITEM_KEY;
5213 min_key.offset = 0;
5214again:
5215 btrfs_release_path(path);
5216 ret = btrfs_search_forward(log, &min_key, path, trans->transid);
5217 if (ret < 0) {
5218 goto next_dir_inode;
5219 } else if (ret > 0) {
5220 ret = 0;
5221 goto next_dir_inode;
5222 }
5223
5224process_leaf:
5225 leaf = path->nodes[0];
5226 nritems = btrfs_header_nritems(leaf);
5227 for (i = path->slots[0]; i < nritems; i++) {
5228 struct btrfs_dir_item *di;
5229 struct btrfs_key di_key;
5230 struct inode *di_inode;
5231 struct btrfs_dir_list *new_dir_elem;
5232 int log_mode = LOG_INODE_EXISTS;
5233 int type;
5234
5235 btrfs_item_key_to_cpu(leaf, &min_key, i);
5236 if (min_key.objectid != dir_elem->ino ||
5237 min_key.type != BTRFS_DIR_ITEM_KEY)
5238 goto next_dir_inode;
5239
5240 di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
5241 type = btrfs_dir_type(leaf, di);
5242 if (btrfs_dir_transid(leaf, di) < trans->transid &&
5243 type != BTRFS_FT_DIR)
5244 continue;
5245 btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5246 if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5247 continue;
5248
ec125cfb 5249 btrfs_release_path(path);
0b246afa 5250 di_inode = btrfs_iget(fs_info->sb, &di_key, root, NULL);
2f2ff0ee
FM
5251 if (IS_ERR(di_inode)) {
5252 ret = PTR_ERR(di_inode);
5253 goto next_dir_inode;
5254 }
5255
0f8939b8 5256 if (btrfs_inode_in_log(BTRFS_I(di_inode), trans->transid)) {
2f2ff0ee 5257 iput(di_inode);
ec125cfb 5258 break;
2f2ff0ee
FM
5259 }
5260
5261 ctx->log_new_dentries = false;
3f9749f6 5262 if (type == BTRFS_FT_DIR || type == BTRFS_FT_SYMLINK)
2f2ff0ee 5263 log_mode = LOG_INODE_ALL;
a59108a7 5264 ret = btrfs_log_inode(trans, root, BTRFS_I(di_inode),
2f2ff0ee 5265 log_mode, 0, LLONG_MAX, ctx);
2be63d5c 5266 if (!ret &&
ab1717b2 5267 btrfs_must_commit_transaction(trans, BTRFS_I(di_inode)))
2be63d5c 5268 ret = 1;
2f2ff0ee
FM
5269 iput(di_inode);
5270 if (ret)
5271 goto next_dir_inode;
5272 if (ctx->log_new_dentries) {
5273 new_dir_elem = kmalloc(sizeof(*new_dir_elem),
5274 GFP_NOFS);
5275 if (!new_dir_elem) {
5276 ret = -ENOMEM;
5277 goto next_dir_inode;
5278 }
5279 new_dir_elem->ino = di_key.objectid;
5280 list_add_tail(&new_dir_elem->list, &dir_list);
5281 }
5282 break;
5283 }
5284 if (i == nritems) {
5285 ret = btrfs_next_leaf(log, path);
5286 if (ret < 0) {
5287 goto next_dir_inode;
5288 } else if (ret > 0) {
5289 ret = 0;
5290 goto next_dir_inode;
5291 }
5292 goto process_leaf;
5293 }
5294 if (min_key.offset < (u64)-1) {
5295 min_key.offset++;
5296 goto again;
5297 }
5298next_dir_inode:
5299 list_del(&dir_elem->list);
5300 kfree(dir_elem);
5301 }
5302
5303 btrfs_free_path(path);
5304 return ret;
5305}
5306
18aa0922 5307static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
d0a0b78d 5308 struct btrfs_inode *inode,
18aa0922
FM
5309 struct btrfs_log_ctx *ctx)
5310{
d0a0b78d 5311 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
18aa0922
FM
5312 int ret;
5313 struct btrfs_path *path;
5314 struct btrfs_key key;
d0a0b78d
NB
5315 struct btrfs_root *root = inode->root;
5316 const u64 ino = btrfs_ino(inode);
18aa0922
FM
5317
5318 path = btrfs_alloc_path();
5319 if (!path)
5320 return -ENOMEM;
5321 path->skip_locking = 1;
5322 path->search_commit_root = 1;
5323
5324 key.objectid = ino;
5325 key.type = BTRFS_INODE_REF_KEY;
5326 key.offset = 0;
5327 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5328 if (ret < 0)
5329 goto out;
5330
5331 while (true) {
5332 struct extent_buffer *leaf = path->nodes[0];
5333 int slot = path->slots[0];
5334 u32 cur_offset = 0;
5335 u32 item_size;
5336 unsigned long ptr;
5337
5338 if (slot >= btrfs_header_nritems(leaf)) {
5339 ret = btrfs_next_leaf(root, path);
5340 if (ret < 0)
5341 goto out;
5342 else if (ret > 0)
5343 break;
5344 continue;
5345 }
5346
5347 btrfs_item_key_to_cpu(leaf, &key, slot);
5348 /* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
5349 if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
5350 break;
5351
5352 item_size = btrfs_item_size_nr(leaf, slot);
5353 ptr = btrfs_item_ptr_offset(leaf, slot);
5354 while (cur_offset < item_size) {
5355 struct btrfs_key inode_key;
5356 struct inode *dir_inode;
5357
5358 inode_key.type = BTRFS_INODE_ITEM_KEY;
5359 inode_key.offset = 0;
5360
5361 if (key.type == BTRFS_INODE_EXTREF_KEY) {
5362 struct btrfs_inode_extref *extref;
5363
5364 extref = (struct btrfs_inode_extref *)
5365 (ptr + cur_offset);
5366 inode_key.objectid = btrfs_inode_extref_parent(
5367 leaf, extref);
5368 cur_offset += sizeof(*extref);
5369 cur_offset += btrfs_inode_extref_name_len(leaf,
5370 extref);
5371 } else {
5372 inode_key.objectid = key.offset;
5373 cur_offset = item_size;
5374 }
5375
0b246afa 5376 dir_inode = btrfs_iget(fs_info->sb, &inode_key,
18aa0922
FM
5377 root, NULL);
5378 /* If parent inode was deleted, skip it. */
5379 if (IS_ERR(dir_inode))
5380 continue;
5381
657ed1aa
FM
5382 if (ctx)
5383 ctx->log_new_dentries = false;
a59108a7 5384 ret = btrfs_log_inode(trans, root, BTRFS_I(dir_inode),
18aa0922 5385 LOG_INODE_ALL, 0, LLONG_MAX, ctx);
2be63d5c 5386 if (!ret &&
ab1717b2 5387 btrfs_must_commit_transaction(trans, BTRFS_I(dir_inode)))
2be63d5c 5388 ret = 1;
657ed1aa
FM
5389 if (!ret && ctx && ctx->log_new_dentries)
5390 ret = log_new_dir_dentries(trans, root,
f85b7379 5391 BTRFS_I(dir_inode), ctx);
18aa0922
FM
5392 iput(dir_inode);
5393 if (ret)
5394 goto out;
5395 }
5396 path->slots[0]++;
5397 }
5398 ret = 0;
5399out:
5400 btrfs_free_path(path);
5401 return ret;
5402}
5403
e02119d5
CM
5404/*
5405 * helper function around btrfs_log_inode to make sure newly created
5406 * parent directories also end up in the log. A minimal inode and backref
5407 * only logging is done of any parent directories that are older than
5408 * the last committed transaction
5409 */
48a3b636 5410static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
19df27a9
NB
5411 struct btrfs_root *root,
5412 struct btrfs_inode *inode,
49dae1bc
FM
5413 struct dentry *parent,
5414 const loff_t start,
5415 const loff_t end,
41a1eada 5416 int inode_only,
8b050d35 5417 struct btrfs_log_ctx *ctx)
e02119d5 5418{
0b246afa 5419 struct btrfs_fs_info *fs_info = root->fs_info;
e02119d5 5420 struct super_block *sb;
6a912213 5421 struct dentry *old_parent = NULL;
12fcfd22 5422 int ret = 0;
0b246afa 5423 u64 last_committed = fs_info->last_trans_committed;
2f2ff0ee 5424 bool log_dentries = false;
19df27a9 5425 struct btrfs_inode *orig_inode = inode;
12fcfd22 5426
19df27a9 5427 sb = inode->vfs_inode.i_sb;
12fcfd22 5428
0b246afa 5429 if (btrfs_test_opt(fs_info, NOTREELOG)) {
3a5e1404
SW
5430 ret = 1;
5431 goto end_no_trans;
5432 }
5433
995946dd
MX
5434 /*
5435 * The prev transaction commit doesn't complete, we need do
5436 * full commit by ourselves.
5437 */
0b246afa
JM
5438 if (fs_info->last_trans_log_full_commit >
5439 fs_info->last_trans_committed) {
12fcfd22
CM
5440 ret = 1;
5441 goto end_no_trans;
5442 }
5443
19df27a9 5444 if (root != inode->root || btrfs_root_refs(&root->root_item) == 0) {
76dda93c
YZ
5445 ret = 1;
5446 goto end_no_trans;
5447 }
5448
19df27a9
NB
5449 ret = check_parent_dirs_for_sync(trans, inode, parent, sb,
5450 last_committed);
12fcfd22
CM
5451 if (ret)
5452 goto end_no_trans;
e02119d5 5453
19df27a9 5454 if (btrfs_inode_in_log(inode, trans->transid)) {
257c62e1
CM
5455 ret = BTRFS_NO_LOG_SYNC;
5456 goto end_no_trans;
5457 }
5458
8b050d35 5459 ret = start_log_trans(trans, root, ctx);
4a500fd1 5460 if (ret)
e87ac136 5461 goto end_no_trans;
e02119d5 5462
19df27a9 5463 ret = btrfs_log_inode(trans, root, inode, inode_only, start, end, ctx);
4a500fd1
YZ
5464 if (ret)
5465 goto end_trans;
12fcfd22 5466
af4176b4
CM
5467 /*
5468 * for regular files, if its inode is already on disk, we don't
5469 * have to worry about the parents at all. This is because
5470 * we can use the last_unlink_trans field to record renames
5471 * and other fun in this file.
5472 */
19df27a9
NB
5473 if (S_ISREG(inode->vfs_inode.i_mode) &&
5474 inode->generation <= last_committed &&
5475 inode->last_unlink_trans <= last_committed) {
4a500fd1
YZ
5476 ret = 0;
5477 goto end_trans;
5478 }
af4176b4 5479
19df27a9 5480 if (S_ISDIR(inode->vfs_inode.i_mode) && ctx && ctx->log_new_dentries)
2f2ff0ee
FM
5481 log_dentries = true;
5482
18aa0922 5483 /*
01327610 5484 * On unlink we must make sure all our current and old parent directory
18aa0922
FM
5485 * inodes are fully logged. This is to prevent leaving dangling
5486 * directory index entries in directories that were our parents but are
5487 * not anymore. Not doing this results in old parent directory being
5488 * impossible to delete after log replay (rmdir will always fail with
5489 * error -ENOTEMPTY).
5490 *
5491 * Example 1:
5492 *
5493 * mkdir testdir
5494 * touch testdir/foo
5495 * ln testdir/foo testdir/bar
5496 * sync
5497 * unlink testdir/bar
5498 * xfs_io -c fsync testdir/foo
5499 * <power failure>
5500 * mount fs, triggers log replay
5501 *
5502 * If we don't log the parent directory (testdir), after log replay the
5503 * directory still has an entry pointing to the file inode using the bar
5504 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
5505 * the file inode has a link count of 1.
5506 *
5507 * Example 2:
5508 *
5509 * mkdir testdir
5510 * touch foo
5511 * ln foo testdir/foo2
5512 * ln foo testdir/foo3
5513 * sync
5514 * unlink testdir/foo3
5515 * xfs_io -c fsync foo
5516 * <power failure>
5517 * mount fs, triggers log replay
5518 *
5519 * Similar as the first example, after log replay the parent directory
5520 * testdir still has an entry pointing to the inode file with name foo3
5521 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
5522 * and has a link count of 2.
5523 */
19df27a9 5524 if (inode->last_unlink_trans > last_committed) {
18aa0922
FM
5525 ret = btrfs_log_all_parents(trans, orig_inode, ctx);
5526 if (ret)
5527 goto end_trans;
5528 }
5529
12fcfd22 5530 while (1) {
fc64005c 5531 if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
e02119d5
CM
5532 break;
5533
19df27a9
NB
5534 inode = BTRFS_I(d_inode(parent));
5535 if (root != inode->root)
76dda93c
YZ
5536 break;
5537
19df27a9
NB
5538 if (inode->generation > last_committed) {
5539 ret = btrfs_log_inode(trans, root, inode,
5540 LOG_INODE_EXISTS, 0, LLONG_MAX, ctx);
4a500fd1
YZ
5541 if (ret)
5542 goto end_trans;
12fcfd22 5543 }
76dda93c 5544 if (IS_ROOT(parent))
e02119d5 5545 break;
12fcfd22 5546
6a912213
JB
5547 parent = dget_parent(parent);
5548 dput(old_parent);
5549 old_parent = parent;
e02119d5 5550 }
2f2ff0ee 5551 if (log_dentries)
19df27a9 5552 ret = log_new_dir_dentries(trans, root, orig_inode, ctx);
2f2ff0ee
FM
5553 else
5554 ret = 0;
4a500fd1 5555end_trans:
6a912213 5556 dput(old_parent);
4a500fd1 5557 if (ret < 0) {
0b246afa 5558 btrfs_set_log_full_commit(fs_info, trans);
4a500fd1
YZ
5559 ret = 1;
5560 }
8b050d35
MX
5561
5562 if (ret)
5563 btrfs_remove_log_ctx(root, ctx);
12fcfd22
CM
5564 btrfs_end_log_trans(root);
5565end_no_trans:
5566 return ret;
e02119d5
CM
5567}
5568
5569/*
5570 * it is not safe to log dentry if the chunk root has added new
5571 * chunks. This returns 0 if the dentry was logged, and 1 otherwise.
5572 * If this returns 1, you must commit the transaction to safely get your
5573 * data on disk.
5574 */
5575int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
8b050d35 5576 struct btrfs_root *root, struct dentry *dentry,
49dae1bc
FM
5577 const loff_t start,
5578 const loff_t end,
8b050d35 5579 struct btrfs_log_ctx *ctx)
e02119d5 5580{
6a912213
JB
5581 struct dentry *parent = dget_parent(dentry);
5582 int ret;
5583
19df27a9 5584 ret = btrfs_log_inode_parent(trans, root, BTRFS_I(d_inode(dentry)),
41a1eada 5585 parent, start, end, LOG_INODE_ALL, ctx);
6a912213
JB
5586 dput(parent);
5587
5588 return ret;
e02119d5
CM
5589}
5590
5591/*
5592 * should be called during mount to recover any replay any log trees
5593 * from the FS
5594 */
5595int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
5596{
5597 int ret;
5598 struct btrfs_path *path;
5599 struct btrfs_trans_handle *trans;
5600 struct btrfs_key key;
5601 struct btrfs_key found_key;
5602 struct btrfs_key tmp_key;
5603 struct btrfs_root *log;
5604 struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
5605 struct walk_control wc = {
5606 .process_func = process_one_buffer,
5607 .stage = 0,
5608 };
5609
e02119d5 5610 path = btrfs_alloc_path();
db5b493a
TI
5611 if (!path)
5612 return -ENOMEM;
5613
afcdd129 5614 set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
e02119d5 5615
4a500fd1 5616 trans = btrfs_start_transaction(fs_info->tree_root, 0);
79787eaa
JM
5617 if (IS_ERR(trans)) {
5618 ret = PTR_ERR(trans);
5619 goto error;
5620 }
e02119d5
CM
5621
5622 wc.trans = trans;
5623 wc.pin = 1;
5624
db5b493a 5625 ret = walk_log_tree(trans, log_root_tree, &wc);
79787eaa 5626 if (ret) {
5d163e0e
JM
5627 btrfs_handle_fs_error(fs_info, ret,
5628 "Failed to pin buffers while recovering log root tree.");
79787eaa
JM
5629 goto error;
5630 }
e02119d5
CM
5631
5632again:
5633 key.objectid = BTRFS_TREE_LOG_OBJECTID;
5634 key.offset = (u64)-1;
962a298f 5635 key.type = BTRFS_ROOT_ITEM_KEY;
e02119d5 5636
d397712b 5637 while (1) {
e02119d5 5638 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
79787eaa
JM
5639
5640 if (ret < 0) {
34d97007 5641 btrfs_handle_fs_error(fs_info, ret,
79787eaa
JM
5642 "Couldn't find tree log root.");
5643 goto error;
5644 }
e02119d5
CM
5645 if (ret > 0) {
5646 if (path->slots[0] == 0)
5647 break;
5648 path->slots[0]--;
5649 }
5650 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
5651 path->slots[0]);
b3b4aa74 5652 btrfs_release_path(path);
e02119d5
CM
5653 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
5654 break;
5655
cb517eab 5656 log = btrfs_read_fs_root(log_root_tree, &found_key);
79787eaa
JM
5657 if (IS_ERR(log)) {
5658 ret = PTR_ERR(log);
34d97007 5659 btrfs_handle_fs_error(fs_info, ret,
79787eaa
JM
5660 "Couldn't read tree log root.");
5661 goto error;
5662 }
e02119d5
CM
5663
5664 tmp_key.objectid = found_key.offset;
5665 tmp_key.type = BTRFS_ROOT_ITEM_KEY;
5666 tmp_key.offset = (u64)-1;
5667
5668 wc.replay_dest = btrfs_read_fs_root_no_name(fs_info, &tmp_key);
79787eaa
JM
5669 if (IS_ERR(wc.replay_dest)) {
5670 ret = PTR_ERR(wc.replay_dest);
b50c6e25
JB
5671 free_extent_buffer(log->node);
5672 free_extent_buffer(log->commit_root);
5673 kfree(log);
5d163e0e
JM
5674 btrfs_handle_fs_error(fs_info, ret,
5675 "Couldn't read target root for tree log recovery.");
79787eaa
JM
5676 goto error;
5677 }
e02119d5 5678
07d400a6 5679 wc.replay_dest->log_root = log;
5d4f98a2 5680 btrfs_record_root_in_trans(trans, wc.replay_dest);
e02119d5 5681 ret = walk_log_tree(trans, log, &wc);
e02119d5 5682
b50c6e25 5683 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
e02119d5
CM
5684 ret = fixup_inode_link_counts(trans, wc.replay_dest,
5685 path);
e02119d5
CM
5686 }
5687
5688 key.offset = found_key.offset - 1;
07d400a6 5689 wc.replay_dest->log_root = NULL;
e02119d5 5690 free_extent_buffer(log->node);
b263c2c8 5691 free_extent_buffer(log->commit_root);
e02119d5
CM
5692 kfree(log);
5693
b50c6e25
JB
5694 if (ret)
5695 goto error;
5696
e02119d5
CM
5697 if (found_key.offset == 0)
5698 break;
5699 }
b3b4aa74 5700 btrfs_release_path(path);
e02119d5
CM
5701
5702 /* step one is to pin it all, step two is to replay just inodes */
5703 if (wc.pin) {
5704 wc.pin = 0;
5705 wc.process_func = replay_one_buffer;
5706 wc.stage = LOG_WALK_REPLAY_INODES;
5707 goto again;
5708 }
5709 /* step three is to replay everything */
5710 if (wc.stage < LOG_WALK_REPLAY_ALL) {
5711 wc.stage++;
5712 goto again;
5713 }
5714
5715 btrfs_free_path(path);
5716
abefa55a 5717 /* step 4: commit the transaction, which also unpins the blocks */
3a45bb20 5718 ret = btrfs_commit_transaction(trans);
abefa55a
JB
5719 if (ret)
5720 return ret;
5721
e02119d5
CM
5722 free_extent_buffer(log_root_tree->node);
5723 log_root_tree->log_root = NULL;
afcdd129 5724 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
e02119d5 5725 kfree(log_root_tree);
79787eaa 5726
abefa55a 5727 return 0;
79787eaa 5728error:
b50c6e25 5729 if (wc.trans)
3a45bb20 5730 btrfs_end_transaction(wc.trans);
79787eaa
JM
5731 btrfs_free_path(path);
5732 return ret;
e02119d5 5733}
12fcfd22
CM
5734
5735/*
5736 * there are some corner cases where we want to force a full
5737 * commit instead of allowing a directory to be logged.
5738 *
5739 * They revolve around files there were unlinked from the directory, and
5740 * this function updates the parent directory so that a full commit is
5741 * properly done if it is fsync'd later after the unlinks are done.
2be63d5c
FM
5742 *
5743 * Must be called before the unlink operations (updates to the subvolume tree,
5744 * inodes, etc) are done.
12fcfd22
CM
5745 */
5746void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
4176bdbf 5747 struct btrfs_inode *dir, struct btrfs_inode *inode,
12fcfd22
CM
5748 int for_rename)
5749{
af4176b4
CM
5750 /*
5751 * when we're logging a file, if it hasn't been renamed
5752 * or unlinked, and its inode is fully committed on disk,
5753 * we don't have to worry about walking up the directory chain
5754 * to log its parents.
5755 *
5756 * So, we use the last_unlink_trans field to put this transid
5757 * into the file. When the file is logged we check it and
5758 * don't log the parents if the file is fully on disk.
5759 */
4176bdbf
NB
5760 mutex_lock(&inode->log_mutex);
5761 inode->last_unlink_trans = trans->transid;
5762 mutex_unlock(&inode->log_mutex);
af4176b4 5763
12fcfd22
CM
5764 /*
5765 * if this directory was already logged any new
5766 * names for this file/dir will get recorded
5767 */
5768 smp_mb();
4176bdbf 5769 if (dir->logged_trans == trans->transid)
12fcfd22
CM
5770 return;
5771
5772 /*
5773 * if the inode we're about to unlink was logged,
5774 * the log will be properly updated for any new names
5775 */
4176bdbf 5776 if (inode->logged_trans == trans->transid)
12fcfd22
CM
5777 return;
5778
5779 /*
5780 * when renaming files across directories, if the directory
5781 * there we're unlinking from gets fsync'd later on, there's
5782 * no way to find the destination directory later and fsync it
5783 * properly. So, we have to be conservative and force commits
5784 * so the new name gets discovered.
5785 */
5786 if (for_rename)
5787 goto record;
5788
5789 /* we can safely do the unlink without any special recording */
5790 return;
5791
5792record:
4176bdbf
NB
5793 mutex_lock(&dir->log_mutex);
5794 dir->last_unlink_trans = trans->transid;
5795 mutex_unlock(&dir->log_mutex);
1ec9a1ae
FM
5796}
5797
5798/*
5799 * Make sure that if someone attempts to fsync the parent directory of a deleted
5800 * snapshot, it ends up triggering a transaction commit. This is to guarantee
5801 * that after replaying the log tree of the parent directory's root we will not
5802 * see the snapshot anymore and at log replay time we will not see any log tree
5803 * corresponding to the deleted snapshot's root, which could lead to replaying
5804 * it after replaying the log tree of the parent directory (which would replay
5805 * the snapshot delete operation).
2be63d5c
FM
5806 *
5807 * Must be called before the actual snapshot destroy operation (updates to the
5808 * parent root and tree of tree roots trees, etc) are done.
1ec9a1ae
FM
5809 */
5810void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
43663557 5811 struct btrfs_inode *dir)
1ec9a1ae 5812{
43663557
NB
5813 mutex_lock(&dir->log_mutex);
5814 dir->last_unlink_trans = trans->transid;
5815 mutex_unlock(&dir->log_mutex);
12fcfd22
CM
5816}
5817
5818/*
5819 * Call this after adding a new name for a file and it will properly
5820 * update the log to reflect the new name.
5821 *
5822 * It will return zero if all goes well, and it will return 1 if a
5823 * full transaction commit is required.
5824 */
5825int btrfs_log_new_name(struct btrfs_trans_handle *trans,
9ca5fbfb 5826 struct btrfs_inode *inode, struct btrfs_inode *old_dir,
12fcfd22
CM
5827 struct dentry *parent)
5828{
9ca5fbfb 5829 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
f85b7379 5830 struct btrfs_root *root = inode->root;
12fcfd22 5831
af4176b4
CM
5832 /*
5833 * this will force the logging code to walk the dentry chain
5834 * up for the file
5835 */
9ca5fbfb
NB
5836 if (S_ISREG(inode->vfs_inode.i_mode))
5837 inode->last_unlink_trans = trans->transid;
af4176b4 5838
12fcfd22
CM
5839 /*
5840 * if this inode hasn't been logged and directory we're renaming it
5841 * from hasn't been logged, we don't need to log it
5842 */
9ca5fbfb
NB
5843 if (inode->logged_trans <= fs_info->last_trans_committed &&
5844 (!old_dir || old_dir->logged_trans <= fs_info->last_trans_committed))
12fcfd22
CM
5845 return 0;
5846
19df27a9 5847 return btrfs_log_inode_parent(trans, root, inode, parent, 0,
41a1eada 5848 LLONG_MAX, LOG_INODE_EXISTS, NULL);
12fcfd22
CM
5849}
5850