xref: /linux/fs/bcachefs/move.c (revision 1b1934dbbdcf9aa2d507932ff488cec47999cf3f)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "alloc_background.h"
5 #include "alloc_foreground.h"
6 #include "backpointers.h"
7 #include "bkey_buf.h"
8 #include "btree_gc.h"
9 #include "btree_update.h"
10 #include "btree_update_interior.h"
11 #include "btree_write_buffer.h"
12 #include "disk_groups.h"
13 #include "ec.h"
14 #include "errcode.h"
15 #include "error.h"
16 #include "inode.h"
17 #include "io_read.h"
18 #include "io_write.h"
19 #include "journal_reclaim.h"
20 #include "keylist.h"
21 #include "move.h"
22 #include "replicas.h"
23 #include "snapshot.h"
24 #include "super-io.h"
25 #include "trace.h"
26 
27 #include <linux/ioprio.h>
28 #include <linux/kthread.h>
29 
30 const char * const bch2_data_ops_strs[] = {
31 #define x(t, n, ...) [n] = #t,
32 	BCH_DATA_OPS()
33 #undef x
34 	NULL
35 };
36 
37 static void trace_move_extent2(struct bch_fs *c, struct bkey_s_c k)
38 {
39 	if (trace_move_extent_enabled()) {
40 		struct printbuf buf = PRINTBUF;
41 
42 		bch2_bkey_val_to_text(&buf, c, k);
43 		trace_move_extent(c, buf.buf);
44 		printbuf_exit(&buf);
45 	}
46 }
47 
48 static void trace_move_extent_read2(struct bch_fs *c, struct bkey_s_c k)
49 {
50 	if (trace_move_extent_read_enabled()) {
51 		struct printbuf buf = PRINTBUF;
52 
53 		bch2_bkey_val_to_text(&buf, c, k);
54 		trace_move_extent_read(c, buf.buf);
55 		printbuf_exit(&buf);
56 	}
57 }
58 
59 struct moving_io {
60 	struct list_head		read_list;
61 	struct list_head		io_list;
62 	struct move_bucket_in_flight	*b;
63 	struct closure			cl;
64 	bool				read_completed;
65 
66 	unsigned			read_sectors;
67 	unsigned			write_sectors;
68 
69 	struct bch_read_bio		rbio;
70 
71 	struct data_update		write;
72 	/* Must be last since it is variable size */
73 	struct bio_vec			bi_inline_vecs[];
74 };
75 
76 static void move_free(struct moving_io *io)
77 {
78 	struct moving_context *ctxt = io->write.ctxt;
79 
80 	if (io->b)
81 		atomic_dec(&io->b->count);
82 
83 	bch2_data_update_exit(&io->write);
84 
85 	mutex_lock(&ctxt->lock);
86 	list_del(&io->io_list);
87 	wake_up(&ctxt->wait);
88 	mutex_unlock(&ctxt->lock);
89 
90 	kfree(io);
91 }
92 
93 static void move_write_done(struct bch_write_op *op)
94 {
95 	struct moving_io *io = container_of(op, struct moving_io, write.op);
96 	struct moving_context *ctxt = io->write.ctxt;
97 
98 	if (io->write.op.error)
99 		ctxt->write_error = true;
100 
101 	atomic_sub(io->write_sectors, &io->write.ctxt->write_sectors);
102 	atomic_dec(&io->write.ctxt->write_ios);
103 	move_free(io);
104 	closure_put(&ctxt->cl);
105 }
106 
107 static void move_write(struct moving_io *io)
108 {
109 	if (unlikely(io->rbio.bio.bi_status || io->rbio.hole)) {
110 		move_free(io);
111 		return;
112 	}
113 
114 	closure_get(&io->write.ctxt->cl);
115 	atomic_add(io->write_sectors, &io->write.ctxt->write_sectors);
116 	atomic_inc(&io->write.ctxt->write_ios);
117 
118 	bch2_data_update_read_done(&io->write, io->rbio.pick.crc);
119 }
120 
121 struct moving_io *bch2_moving_ctxt_next_pending_write(struct moving_context *ctxt)
122 {
123 	struct moving_io *io =
124 		list_first_entry_or_null(&ctxt->reads, struct moving_io, read_list);
125 
126 	return io && io->read_completed ? io : NULL;
127 }
128 
129 static void move_read_endio(struct bio *bio)
130 {
131 	struct moving_io *io = container_of(bio, struct moving_io, rbio.bio);
132 	struct moving_context *ctxt = io->write.ctxt;
133 
134 	atomic_sub(io->read_sectors, &ctxt->read_sectors);
135 	atomic_dec(&ctxt->read_ios);
136 	io->read_completed = true;
137 
138 	wake_up(&ctxt->wait);
139 	closure_put(&ctxt->cl);
140 }
141 
142 void bch2_moving_ctxt_do_pending_writes(struct moving_context *ctxt)
143 {
144 	struct moving_io *io;
145 
146 	while ((io = bch2_moving_ctxt_next_pending_write(ctxt))) {
147 		bch2_trans_unlock_long(ctxt->trans);
148 		list_del(&io->read_list);
149 		move_write(io);
150 	}
151 }
152 
153 void bch2_move_ctxt_wait_for_io(struct moving_context *ctxt)
154 {
155 	unsigned sectors_pending = atomic_read(&ctxt->write_sectors);
156 
157 	move_ctxt_wait_event(ctxt,
158 		!atomic_read(&ctxt->write_sectors) ||
159 		atomic_read(&ctxt->write_sectors) != sectors_pending);
160 }
161 
162 void bch2_moving_ctxt_flush_all(struct moving_context *ctxt)
163 {
164 	move_ctxt_wait_event(ctxt, list_empty(&ctxt->reads));
165 	bch2_trans_unlock_long(ctxt->trans);
166 	closure_sync(&ctxt->cl);
167 }
168 
169 void bch2_moving_ctxt_exit(struct moving_context *ctxt)
170 {
171 	struct bch_fs *c = ctxt->trans->c;
172 
173 	bch2_moving_ctxt_flush_all(ctxt);
174 
175 	EBUG_ON(atomic_read(&ctxt->write_sectors));
176 	EBUG_ON(atomic_read(&ctxt->write_ios));
177 	EBUG_ON(atomic_read(&ctxt->read_sectors));
178 	EBUG_ON(atomic_read(&ctxt->read_ios));
179 
180 	mutex_lock(&c->moving_context_lock);
181 	list_del(&ctxt->list);
182 	mutex_unlock(&c->moving_context_lock);
183 
184 	bch2_trans_put(ctxt->trans);
185 	memset(ctxt, 0, sizeof(*ctxt));
186 }
187 
188 void bch2_moving_ctxt_init(struct moving_context *ctxt,
189 			   struct bch_fs *c,
190 			   struct bch_ratelimit *rate,
191 			   struct bch_move_stats *stats,
192 			   struct write_point_specifier wp,
193 			   bool wait_on_copygc)
194 {
195 	memset(ctxt, 0, sizeof(*ctxt));
196 
197 	ctxt->trans	= bch2_trans_get(c);
198 	ctxt->fn	= (void *) _RET_IP_;
199 	ctxt->rate	= rate;
200 	ctxt->stats	= stats;
201 	ctxt->wp	= wp;
202 	ctxt->wait_on_copygc = wait_on_copygc;
203 
204 	closure_init_stack(&ctxt->cl);
205 
206 	mutex_init(&ctxt->lock);
207 	INIT_LIST_HEAD(&ctxt->reads);
208 	INIT_LIST_HEAD(&ctxt->ios);
209 	init_waitqueue_head(&ctxt->wait);
210 
211 	mutex_lock(&c->moving_context_lock);
212 	list_add(&ctxt->list, &c->moving_context_list);
213 	mutex_unlock(&c->moving_context_lock);
214 }
215 
216 void bch2_move_stats_exit(struct bch_move_stats *stats, struct bch_fs *c)
217 {
218 	trace_move_data(c, stats);
219 }
220 
221 void bch2_move_stats_init(struct bch_move_stats *stats, const char *name)
222 {
223 	memset(stats, 0, sizeof(*stats));
224 	stats->data_type = BCH_DATA_user;
225 	scnprintf(stats->name, sizeof(stats->name), "%s", name);
226 }
227 
228 int bch2_move_extent(struct moving_context *ctxt,
229 		     struct move_bucket_in_flight *bucket_in_flight,
230 		     struct btree_iter *iter,
231 		     struct bkey_s_c k,
232 		     struct bch_io_opts io_opts,
233 		     struct data_update_opts data_opts)
234 {
235 	struct btree_trans *trans = ctxt->trans;
236 	struct bch_fs *c = trans->c;
237 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
238 	struct moving_io *io;
239 	const union bch_extent_entry *entry;
240 	struct extent_ptr_decoded p;
241 	unsigned sectors = k.k->size, pages;
242 	int ret = -ENOMEM;
243 
244 	if (ctxt->stats)
245 		ctxt->stats->pos = BBPOS(iter->btree_id, iter->pos);
246 	trace_move_extent2(c, k);
247 
248 	bch2_data_update_opts_normalize(k, &data_opts);
249 
250 	if (!data_opts.rewrite_ptrs &&
251 	    !data_opts.extra_replicas) {
252 		if (data_opts.kill_ptrs)
253 			return bch2_extent_drop_ptrs(trans, iter, k, data_opts);
254 		return 0;
255 	}
256 
257 	/*
258 	 * Before memory allocations & taking nocow locks in
259 	 * bch2_data_update_init():
260 	 */
261 	bch2_trans_unlock(trans);
262 
263 	/* write path might have to decompress data: */
264 	bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
265 		sectors = max_t(unsigned, sectors, p.crc.uncompressed_size);
266 
267 	pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
268 	io = kzalloc(sizeof(struct moving_io) +
269 		     sizeof(struct bio_vec) * pages, GFP_KERNEL);
270 	if (!io)
271 		goto err;
272 
273 	INIT_LIST_HEAD(&io->io_list);
274 	io->write.ctxt		= ctxt;
275 	io->read_sectors	= k.k->size;
276 	io->write_sectors	= k.k->size;
277 
278 	bio_init(&io->write.op.wbio.bio, NULL, io->bi_inline_vecs, pages, 0);
279 	bio_set_prio(&io->write.op.wbio.bio,
280 		     IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
281 
282 	if (bch2_bio_alloc_pages(&io->write.op.wbio.bio, sectors << 9,
283 				 GFP_KERNEL))
284 		goto err_free;
285 
286 	io->rbio.c		= c;
287 	io->rbio.opts		= io_opts;
288 	bio_init(&io->rbio.bio, NULL, io->bi_inline_vecs, pages, 0);
289 	io->rbio.bio.bi_vcnt = pages;
290 	bio_set_prio(&io->rbio.bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
291 	io->rbio.bio.bi_iter.bi_size = sectors << 9;
292 
293 	io->rbio.bio.bi_opf		= REQ_OP_READ;
294 	io->rbio.bio.bi_iter.bi_sector	= bkey_start_offset(k.k);
295 	io->rbio.bio.bi_end_io		= move_read_endio;
296 
297 	ret = bch2_data_update_init(trans, iter, ctxt, &io->write, ctxt->wp,
298 				    io_opts, data_opts, iter->btree_id, k);
299 	if (ret)
300 		goto err_free_pages;
301 
302 	io->write.op.end_io = move_write_done;
303 
304 	if (ctxt->rate)
305 		bch2_ratelimit_increment(ctxt->rate, k.k->size);
306 
307 	if (ctxt->stats) {
308 		atomic64_inc(&ctxt->stats->keys_moved);
309 		atomic64_add(k.k->size, &ctxt->stats->sectors_moved);
310 	}
311 
312 	if (bucket_in_flight) {
313 		io->b = bucket_in_flight;
314 		atomic_inc(&io->b->count);
315 	}
316 
317 	this_cpu_add(c->counters[BCH_COUNTER_io_move], k.k->size);
318 	this_cpu_add(c->counters[BCH_COUNTER_move_extent_read], k.k->size);
319 	trace_move_extent_read2(c, k);
320 
321 	mutex_lock(&ctxt->lock);
322 	atomic_add(io->read_sectors, &ctxt->read_sectors);
323 	atomic_inc(&ctxt->read_ios);
324 
325 	list_add_tail(&io->read_list, &ctxt->reads);
326 	list_add_tail(&io->io_list, &ctxt->ios);
327 	mutex_unlock(&ctxt->lock);
328 
329 	/*
330 	 * dropped by move_read_endio() - guards against use after free of
331 	 * ctxt when doing wakeup
332 	 */
333 	closure_get(&ctxt->cl);
334 	bch2_read_extent(trans, &io->rbio,
335 			 bkey_start_pos(k.k),
336 			 iter->btree_id, k, 0,
337 			 BCH_READ_NODECODE|
338 			 BCH_READ_LAST_FRAGMENT);
339 	return 0;
340 err_free_pages:
341 	bio_free_pages(&io->write.op.wbio.bio);
342 err_free:
343 	kfree(io);
344 err:
345 	if (ret == -BCH_ERR_data_update_done)
346 		return 0;
347 
348 	if (bch2_err_matches(ret, EROFS) ||
349 	    bch2_err_matches(ret, BCH_ERR_transaction_restart))
350 		return ret;
351 
352 	count_event(c, move_extent_start_fail);
353 
354 	if (trace_move_extent_start_fail_enabled()) {
355 		struct printbuf buf = PRINTBUF;
356 
357 		bch2_bkey_val_to_text(&buf, c, k);
358 		prt_str(&buf, ": ");
359 		prt_str(&buf, bch2_err_str(ret));
360 		trace_move_extent_start_fail(c, buf.buf);
361 		printbuf_exit(&buf);
362 	}
363 	return ret;
364 }
365 
366 struct bch_io_opts *bch2_move_get_io_opts(struct btree_trans *trans,
367 			  struct per_snapshot_io_opts *io_opts,
368 			  struct bkey_s_c extent_k)
369 {
370 	struct bch_fs *c = trans->c;
371 	u32 restart_count = trans->restart_count;
372 	int ret = 0;
373 
374 	if (io_opts->cur_inum != extent_k.k->p.inode) {
375 		io_opts->d.nr = 0;
376 
377 		ret = for_each_btree_key(trans, iter, BTREE_ID_inodes, POS(0, extent_k.k->p.inode),
378 					 BTREE_ITER_ALL_SNAPSHOTS, k, ({
379 			if (k.k->p.offset != extent_k.k->p.inode)
380 				break;
381 
382 			if (!bkey_is_inode(k.k))
383 				continue;
384 
385 			struct bch_inode_unpacked inode;
386 			BUG_ON(bch2_inode_unpack(k, &inode));
387 
388 			struct snapshot_io_opts_entry e = { .snapshot = k.k->p.snapshot };
389 			bch2_inode_opts_get(&e.io_opts, trans->c, &inode);
390 
391 			darray_push(&io_opts->d, e);
392 		}));
393 		io_opts->cur_inum = extent_k.k->p.inode;
394 	}
395 
396 	ret = ret ?: trans_was_restarted(trans, restart_count);
397 	if (ret)
398 		return ERR_PTR(ret);
399 
400 	if (extent_k.k->p.snapshot)
401 		darray_for_each(io_opts->d, i)
402 			if (bch2_snapshot_is_ancestor(c, extent_k.k->p.snapshot, i->snapshot))
403 				return &i->io_opts;
404 
405 	return &io_opts->fs_io_opts;
406 }
407 
408 int bch2_move_get_io_opts_one(struct btree_trans *trans,
409 			      struct bch_io_opts *io_opts,
410 			      struct bkey_s_c extent_k)
411 {
412 	struct btree_iter iter;
413 	struct bkey_s_c k;
414 	int ret;
415 
416 	/* reflink btree? */
417 	if (!extent_k.k->p.inode) {
418 		*io_opts = bch2_opts_to_inode_opts(trans->c->opts);
419 		return 0;
420 	}
421 
422 	k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_inodes,
423 			       SPOS(0, extent_k.k->p.inode, extent_k.k->p.snapshot),
424 			       BTREE_ITER_CACHED);
425 	ret = bkey_err(k);
426 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
427 		return ret;
428 
429 	if (!ret && bkey_is_inode(k.k)) {
430 		struct bch_inode_unpacked inode;
431 		bch2_inode_unpack(k, &inode);
432 		bch2_inode_opts_get(io_opts, trans->c, &inode);
433 	} else {
434 		*io_opts = bch2_opts_to_inode_opts(trans->c->opts);
435 	}
436 
437 	bch2_trans_iter_exit(trans, &iter);
438 	return 0;
439 }
440 
441 int bch2_move_ratelimit(struct moving_context *ctxt)
442 {
443 	struct bch_fs *c = ctxt->trans->c;
444 	bool is_kthread = current->flags & PF_KTHREAD;
445 	u64 delay;
446 
447 	if (ctxt->wait_on_copygc && c->copygc_running) {
448 		bch2_moving_ctxt_flush_all(ctxt);
449 		wait_event_killable(c->copygc_running_wq,
450 				    !c->copygc_running ||
451 				    (is_kthread && kthread_should_stop()));
452 	}
453 
454 	do {
455 		delay = ctxt->rate ? bch2_ratelimit_delay(ctxt->rate) : 0;
456 
457 		if (is_kthread && kthread_should_stop())
458 			return 1;
459 
460 		if (delay)
461 			move_ctxt_wait_event_timeout(ctxt,
462 					freezing(current) ||
463 					(is_kthread && kthread_should_stop()),
464 					delay);
465 
466 		if (unlikely(freezing(current))) {
467 			bch2_moving_ctxt_flush_all(ctxt);
468 			try_to_freeze();
469 		}
470 	} while (delay);
471 
472 	/*
473 	 * XXX: these limits really ought to be per device, SSDs and hard drives
474 	 * will want different limits
475 	 */
476 	move_ctxt_wait_event(ctxt,
477 		atomic_read(&ctxt->write_sectors) < c->opts.move_bytes_in_flight >> 9 &&
478 		atomic_read(&ctxt->read_sectors) < c->opts.move_bytes_in_flight >> 9 &&
479 		atomic_read(&ctxt->write_ios) < c->opts.move_ios_in_flight &&
480 		atomic_read(&ctxt->read_ios) < c->opts.move_ios_in_flight);
481 
482 	return 0;
483 }
484 
485 static int bch2_move_data_btree(struct moving_context *ctxt,
486 				struct bpos start,
487 				struct bpos end,
488 				move_pred_fn pred, void *arg,
489 				enum btree_id btree_id)
490 {
491 	struct btree_trans *trans = ctxt->trans;
492 	struct bch_fs *c = trans->c;
493 	struct per_snapshot_io_opts snapshot_io_opts;
494 	struct bch_io_opts *io_opts;
495 	struct bkey_buf sk;
496 	struct btree_iter iter;
497 	struct bkey_s_c k;
498 	struct data_update_opts data_opts;
499 	int ret = 0, ret2;
500 
501 	per_snapshot_io_opts_init(&snapshot_io_opts, c);
502 	bch2_bkey_buf_init(&sk);
503 
504 	if (ctxt->stats) {
505 		ctxt->stats->data_type	= BCH_DATA_user;
506 		ctxt->stats->pos	= BBPOS(btree_id, start);
507 	}
508 
509 	bch2_trans_iter_init(trans, &iter, btree_id, start,
510 			     BTREE_ITER_PREFETCH|
511 			     BTREE_ITER_ALL_SNAPSHOTS);
512 
513 	if (ctxt->rate)
514 		bch2_ratelimit_reset(ctxt->rate);
515 
516 	while (!bch2_move_ratelimit(ctxt)) {
517 		bch2_trans_begin(trans);
518 
519 		k = bch2_btree_iter_peek(&iter);
520 		if (!k.k)
521 			break;
522 
523 		ret = bkey_err(k);
524 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
525 			continue;
526 		if (ret)
527 			break;
528 
529 		if (bkey_ge(bkey_start_pos(k.k), end))
530 			break;
531 
532 		if (ctxt->stats)
533 			ctxt->stats->pos = BBPOS(iter.btree_id, iter.pos);
534 
535 		if (!bkey_extent_is_direct_data(k.k))
536 			goto next_nondata;
537 
538 		io_opts = bch2_move_get_io_opts(trans, &snapshot_io_opts, k);
539 		ret = PTR_ERR_OR_ZERO(io_opts);
540 		if (ret)
541 			continue;
542 
543 		memset(&data_opts, 0, sizeof(data_opts));
544 		if (!pred(c, arg, k, io_opts, &data_opts))
545 			goto next;
546 
547 		/*
548 		 * The iterator gets unlocked by __bch2_read_extent - need to
549 		 * save a copy of @k elsewhere:
550 		 */
551 		bch2_bkey_buf_reassemble(&sk, c, k);
552 		k = bkey_i_to_s_c(sk.k);
553 
554 		ret2 = bch2_move_extent(ctxt, NULL, &iter, k, *io_opts, data_opts);
555 		if (ret2) {
556 			if (bch2_err_matches(ret2, BCH_ERR_transaction_restart))
557 				continue;
558 
559 			if (ret2 == -ENOMEM) {
560 				/* memory allocation failure, wait for some IO to finish */
561 				bch2_move_ctxt_wait_for_io(ctxt);
562 				continue;
563 			}
564 
565 			/* XXX signal failure */
566 			goto next;
567 		}
568 next:
569 		if (ctxt->stats)
570 			atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
571 next_nondata:
572 		bch2_btree_iter_advance(&iter);
573 	}
574 
575 	bch2_trans_iter_exit(trans, &iter);
576 	bch2_bkey_buf_exit(&sk, c);
577 	per_snapshot_io_opts_exit(&snapshot_io_opts);
578 
579 	return ret;
580 }
581 
582 int __bch2_move_data(struct moving_context *ctxt,
583 		     struct bbpos start,
584 		     struct bbpos end,
585 		     move_pred_fn pred, void *arg)
586 {
587 	struct bch_fs *c = ctxt->trans->c;
588 	enum btree_id id;
589 	int ret = 0;
590 
591 	for (id = start.btree;
592 	     id <= min_t(unsigned, end.btree, btree_id_nr_alive(c) - 1);
593 	     id++) {
594 		ctxt->stats->pos = BBPOS(id, POS_MIN);
595 
596 		if (!btree_type_has_ptrs(id) ||
597 		    !bch2_btree_id_root(c, id)->b)
598 			continue;
599 
600 		ret = bch2_move_data_btree(ctxt,
601 				       id == start.btree ? start.pos : POS_MIN,
602 				       id == end.btree   ? end.pos   : POS_MAX,
603 				       pred, arg, id);
604 		if (ret)
605 			break;
606 	}
607 
608 	return ret;
609 }
610 
611 int bch2_move_data(struct bch_fs *c,
612 		   struct bbpos start,
613 		   struct bbpos end,
614 		   struct bch_ratelimit *rate,
615 		   struct bch_move_stats *stats,
616 		   struct write_point_specifier wp,
617 		   bool wait_on_copygc,
618 		   move_pred_fn pred, void *arg)
619 {
620 
621 	struct moving_context ctxt;
622 	int ret;
623 
624 	bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
625 	ret = __bch2_move_data(&ctxt, start, end, pred, arg);
626 	bch2_moving_ctxt_exit(&ctxt);
627 
628 	return ret;
629 }
630 
631 int bch2_evacuate_bucket(struct moving_context *ctxt,
632 			   struct move_bucket_in_flight *bucket_in_flight,
633 			   struct bpos bucket, int gen,
634 			   struct data_update_opts _data_opts)
635 {
636 	struct btree_trans *trans = ctxt->trans;
637 	struct bch_fs *c = trans->c;
638 	bool is_kthread = current->flags & PF_KTHREAD;
639 	struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
640 	struct btree_iter iter;
641 	struct bkey_buf sk;
642 	struct bch_backpointer bp;
643 	struct bch_alloc_v4 a_convert;
644 	const struct bch_alloc_v4 *a;
645 	struct bkey_s_c k;
646 	struct data_update_opts data_opts;
647 	unsigned dirty_sectors, bucket_size;
648 	u64 fragmentation;
649 	struct bpos bp_pos = POS_MIN;
650 	int ret = 0;
651 
652 	trace_bucket_evacuate(c, &bucket);
653 
654 	bch2_bkey_buf_init(&sk);
655 
656 	/*
657 	 * We're not run in a context that handles transaction restarts:
658 	 */
659 	bch2_trans_begin(trans);
660 
661 	bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
662 			     bucket, BTREE_ITER_CACHED);
663 	ret = lockrestart_do(trans,
664 			bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
665 	bch2_trans_iter_exit(trans, &iter);
666 
667 	bch_err_msg(c, ret, "looking up alloc key");
668 	if (ret)
669 		goto err;
670 
671 	a = bch2_alloc_to_v4(k, &a_convert);
672 	dirty_sectors = bch2_bucket_sectors_dirty(*a);
673 	bucket_size = bch_dev_bkey_exists(c, bucket.inode)->mi.bucket_size;
674 	fragmentation = a->fragmentation_lru;
675 
676 	ret = bch2_btree_write_buffer_tryflush(trans);
677 	bch_err_msg(c, ret, "flushing btree write buffer");
678 	if (ret)
679 		goto err;
680 
681 	while (!(ret = bch2_move_ratelimit(ctxt))) {
682 		if (is_kthread && kthread_should_stop())
683 			break;
684 
685 		bch2_trans_begin(trans);
686 
687 		ret = bch2_get_next_backpointer(trans, bucket, gen,
688 						&bp_pos, &bp,
689 						BTREE_ITER_CACHED);
690 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
691 			continue;
692 		if (ret)
693 			goto err;
694 		if (bkey_eq(bp_pos, POS_MAX))
695 			break;
696 
697 		if (!bp.level) {
698 			k = bch2_backpointer_get_key(trans, &iter, bp_pos, bp, 0);
699 			ret = bkey_err(k);
700 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
701 				continue;
702 			if (ret)
703 				goto err;
704 			if (!k.k)
705 				goto next;
706 
707 			bch2_bkey_buf_reassemble(&sk, c, k);
708 			k = bkey_i_to_s_c(sk.k);
709 
710 			ret = bch2_move_get_io_opts_one(trans, &io_opts, k);
711 			if (ret) {
712 				bch2_trans_iter_exit(trans, &iter);
713 				continue;
714 			}
715 
716 			data_opts = _data_opts;
717 			data_opts.target	= io_opts.background_target;
718 			data_opts.rewrite_ptrs = 0;
719 
720 			unsigned i = 0;
721 			bkey_for_each_ptr(bch2_bkey_ptrs_c(k), ptr) {
722 				if (ptr->dev == bucket.inode) {
723 					data_opts.rewrite_ptrs |= 1U << i;
724 					if (ptr->cached) {
725 						bch2_trans_iter_exit(trans, &iter);
726 						goto next;
727 					}
728 				}
729 				i++;
730 			}
731 
732 			ret = bch2_move_extent(ctxt, bucket_in_flight,
733 					       &iter, k, io_opts, data_opts);
734 			bch2_trans_iter_exit(trans, &iter);
735 
736 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
737 				continue;
738 			if (ret == -ENOMEM) {
739 				/* memory allocation failure, wait for some IO to finish */
740 				bch2_move_ctxt_wait_for_io(ctxt);
741 				continue;
742 			}
743 			if (ret)
744 				goto err;
745 
746 			if (ctxt->stats)
747 				atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
748 		} else {
749 			struct btree *b;
750 
751 			b = bch2_backpointer_get_node(trans, &iter, bp_pos, bp);
752 			ret = PTR_ERR_OR_ZERO(b);
753 			if (ret == -BCH_ERR_backpointer_to_overwritten_btree_node)
754 				continue;
755 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
756 				continue;
757 			if (ret)
758 				goto err;
759 			if (!b)
760 				goto next;
761 
762 			ret = bch2_btree_node_rewrite(trans, &iter, b, 0);
763 			bch2_trans_iter_exit(trans, &iter);
764 
765 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
766 				continue;
767 			if (ret)
768 				goto err;
769 
770 			if (ctxt->rate)
771 				bch2_ratelimit_increment(ctxt->rate,
772 							 c->opts.btree_node_size >> 9);
773 			if (ctxt->stats) {
774 				atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_seen);
775 				atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_moved);
776 			}
777 		}
778 next:
779 		bp_pos = bpos_nosnap_successor(bp_pos);
780 	}
781 
782 	trace_evacuate_bucket(c, &bucket, dirty_sectors, bucket_size, fragmentation, ret);
783 err:
784 	bch2_bkey_buf_exit(&sk, c);
785 	return ret;
786 }
787 
788 typedef bool (*move_btree_pred)(struct bch_fs *, void *,
789 				struct btree *, struct bch_io_opts *,
790 				struct data_update_opts *);
791 
792 static int bch2_move_btree(struct bch_fs *c,
793 			   struct bbpos start,
794 			   struct bbpos end,
795 			   move_btree_pred pred, void *arg,
796 			   struct bch_move_stats *stats)
797 {
798 	bool kthread = (current->flags & PF_KTHREAD) != 0;
799 	struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
800 	struct moving_context ctxt;
801 	struct btree_trans *trans;
802 	struct btree_iter iter;
803 	struct btree *b;
804 	enum btree_id btree;
805 	struct data_update_opts data_opts;
806 	int ret = 0;
807 
808 	bch2_moving_ctxt_init(&ctxt, c, NULL, stats,
809 			      writepoint_ptr(&c->btree_write_point),
810 			      true);
811 	trans = ctxt.trans;
812 
813 	stats->data_type = BCH_DATA_btree;
814 
815 	for (btree = start.btree;
816 	     btree <= min_t(unsigned, end.btree, btree_id_nr_alive(c) - 1);
817 	     btree ++) {
818 		stats->pos = BBPOS(btree, POS_MIN);
819 
820 		if (!bch2_btree_id_root(c, btree)->b)
821 			continue;
822 
823 		bch2_trans_node_iter_init(trans, &iter, btree, POS_MIN, 0, 0,
824 					  BTREE_ITER_PREFETCH);
825 retry:
826 		ret = 0;
827 		while (bch2_trans_begin(trans),
828 		       (b = bch2_btree_iter_peek_node(&iter)) &&
829 		       !(ret = PTR_ERR_OR_ZERO(b))) {
830 			if (kthread && kthread_should_stop())
831 				break;
832 
833 			if ((cmp_int(btree, end.btree) ?:
834 			     bpos_cmp(b->key.k.p, end.pos)) > 0)
835 				break;
836 
837 			stats->pos = BBPOS(iter.btree_id, iter.pos);
838 
839 			if (!pred(c, arg, b, &io_opts, &data_opts))
840 				goto next;
841 
842 			ret = bch2_btree_node_rewrite(trans, &iter, b, 0) ?: ret;
843 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
844 				continue;
845 			if (ret)
846 				break;
847 next:
848 			bch2_btree_iter_next_node(&iter);
849 		}
850 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
851 			goto retry;
852 
853 		bch2_trans_iter_exit(trans, &iter);
854 
855 		if (kthread && kthread_should_stop())
856 			break;
857 	}
858 
859 	bch_err_fn(c, ret);
860 	bch2_moving_ctxt_exit(&ctxt);
861 	bch2_btree_interior_updates_flush(c);
862 
863 	return ret;
864 }
865 
866 static bool rereplicate_pred(struct bch_fs *c, void *arg,
867 			     struct bkey_s_c k,
868 			     struct bch_io_opts *io_opts,
869 			     struct data_update_opts *data_opts)
870 {
871 	unsigned nr_good = bch2_bkey_durability(c, k);
872 	unsigned replicas = bkey_is_btree_ptr(k.k)
873 		? c->opts.metadata_replicas
874 		: io_opts->data_replicas;
875 
876 	if (!nr_good || nr_good >= replicas)
877 		return false;
878 
879 	data_opts->target		= 0;
880 	data_opts->extra_replicas	= replicas - nr_good;
881 	data_opts->btree_insert_flags	= 0;
882 	return true;
883 }
884 
885 static bool migrate_pred(struct bch_fs *c, void *arg,
886 			 struct bkey_s_c k,
887 			 struct bch_io_opts *io_opts,
888 			 struct data_update_opts *data_opts)
889 {
890 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
891 	struct bch_ioctl_data *op = arg;
892 	unsigned i = 0;
893 
894 	data_opts->rewrite_ptrs		= 0;
895 	data_opts->target		= 0;
896 	data_opts->extra_replicas	= 0;
897 	data_opts->btree_insert_flags	= 0;
898 
899 	bkey_for_each_ptr(ptrs, ptr) {
900 		if (ptr->dev == op->migrate.dev)
901 			data_opts->rewrite_ptrs |= 1U << i;
902 		i++;
903 	}
904 
905 	return data_opts->rewrite_ptrs != 0;
906 }
907 
908 static bool rereplicate_btree_pred(struct bch_fs *c, void *arg,
909 				   struct btree *b,
910 				   struct bch_io_opts *io_opts,
911 				   struct data_update_opts *data_opts)
912 {
913 	return rereplicate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
914 }
915 
916 static bool migrate_btree_pred(struct bch_fs *c, void *arg,
917 			       struct btree *b,
918 			       struct bch_io_opts *io_opts,
919 			       struct data_update_opts *data_opts)
920 {
921 	return migrate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
922 }
923 
924 static bool bformat_needs_redo(struct bkey_format *f)
925 {
926 	unsigned i;
927 
928 	for (i = 0; i < f->nr_fields; i++) {
929 		unsigned unpacked_bits = bch2_bkey_format_current.bits_per_field[i];
930 		u64 unpacked_mask = ~((~0ULL << 1) << (unpacked_bits - 1));
931 		u64 field_offset = le64_to_cpu(f->field_offset[i]);
932 
933 		if (f->bits_per_field[i] > unpacked_bits)
934 			return true;
935 
936 		if ((f->bits_per_field[i] == unpacked_bits) && field_offset)
937 			return true;
938 
939 		if (((field_offset + ((1ULL << f->bits_per_field[i]) - 1)) &
940 		     unpacked_mask) <
941 		    field_offset)
942 			return true;
943 	}
944 
945 	return false;
946 }
947 
948 static bool rewrite_old_nodes_pred(struct bch_fs *c, void *arg,
949 				   struct btree *b,
950 				   struct bch_io_opts *io_opts,
951 				   struct data_update_opts *data_opts)
952 {
953 	if (b->version_ondisk != c->sb.version ||
954 	    btree_node_need_rewrite(b) ||
955 	    bformat_needs_redo(&b->format)) {
956 		data_opts->target		= 0;
957 		data_opts->extra_replicas	= 0;
958 		data_opts->btree_insert_flags	= 0;
959 		return true;
960 	}
961 
962 	return false;
963 }
964 
965 int bch2_scan_old_btree_nodes(struct bch_fs *c, struct bch_move_stats *stats)
966 {
967 	int ret;
968 
969 	ret = bch2_move_btree(c,
970 			      BBPOS_MIN,
971 			      BBPOS_MAX,
972 			      rewrite_old_nodes_pred, c, stats);
973 	if (!ret) {
974 		mutex_lock(&c->sb_lock);
975 		c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
976 		c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
977 		c->disk_sb.sb->version_min = c->disk_sb.sb->version;
978 		bch2_write_super(c);
979 		mutex_unlock(&c->sb_lock);
980 	}
981 
982 	bch_err_fn(c, ret);
983 	return ret;
984 }
985 
986 static bool drop_extra_replicas_pred(struct bch_fs *c, void *arg,
987 			     struct bkey_s_c k,
988 			     struct bch_io_opts *io_opts,
989 			     struct data_update_opts *data_opts)
990 {
991 	unsigned durability = bch2_bkey_durability(c, k);
992 	unsigned replicas = bkey_is_btree_ptr(k.k)
993 		? c->opts.metadata_replicas
994 		: io_opts->data_replicas;
995 	const union bch_extent_entry *entry;
996 	struct extent_ptr_decoded p;
997 	unsigned i = 0;
998 
999 	bkey_for_each_ptr_decode(k.k, bch2_bkey_ptrs_c(k), p, entry) {
1000 		unsigned d = bch2_extent_ptr_durability(c, &p);
1001 
1002 		if (d && durability - d >= replicas) {
1003 			data_opts->kill_ptrs |= BIT(i);
1004 			durability -= d;
1005 		}
1006 
1007 		i++;
1008 	}
1009 
1010 	return data_opts->kill_ptrs != 0;
1011 }
1012 
1013 static bool drop_extra_replicas_btree_pred(struct bch_fs *c, void *arg,
1014 				   struct btree *b,
1015 				   struct bch_io_opts *io_opts,
1016 				   struct data_update_opts *data_opts)
1017 {
1018 	return drop_extra_replicas_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
1019 }
1020 
1021 int bch2_data_job(struct bch_fs *c,
1022 		  struct bch_move_stats *stats,
1023 		  struct bch_ioctl_data op)
1024 {
1025 	struct bbpos start	= BBPOS(op.start_btree, op.start_pos);
1026 	struct bbpos end	= BBPOS(op.end_btree, op.end_pos);
1027 	int ret = 0;
1028 
1029 	if (op.op >= BCH_DATA_OP_NR)
1030 		return -EINVAL;
1031 
1032 	bch2_move_stats_init(stats, bch2_data_ops_strs[op.op]);
1033 
1034 	switch (op.op) {
1035 	case BCH_DATA_OP_rereplicate:
1036 		stats->data_type = BCH_DATA_journal;
1037 		ret = bch2_journal_flush_device_pins(&c->journal, -1);
1038 		ret = bch2_move_btree(c, start, end,
1039 				      rereplicate_btree_pred, c, stats) ?: ret;
1040 		ret = bch2_move_data(c, start, end,
1041 				     NULL,
1042 				     stats,
1043 				     writepoint_hashed((unsigned long) current),
1044 				     true,
1045 				     rereplicate_pred, c) ?: ret;
1046 		ret = bch2_replicas_gc2(c) ?: ret;
1047 		break;
1048 	case BCH_DATA_OP_migrate:
1049 		if (op.migrate.dev >= c->sb.nr_devices)
1050 			return -EINVAL;
1051 
1052 		stats->data_type = BCH_DATA_journal;
1053 		ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
1054 		ret = bch2_move_btree(c, start, end,
1055 				      migrate_btree_pred, &op, stats) ?: ret;
1056 		ret = bch2_move_data(c, start, end,
1057 				     NULL,
1058 				     stats,
1059 				     writepoint_hashed((unsigned long) current),
1060 				     true,
1061 				     migrate_pred, &op) ?: ret;
1062 		ret = bch2_replicas_gc2(c) ?: ret;
1063 		break;
1064 	case BCH_DATA_OP_rewrite_old_nodes:
1065 		ret = bch2_scan_old_btree_nodes(c, stats);
1066 		break;
1067 	case BCH_DATA_OP_drop_extra_replicas:
1068 		ret = bch2_move_btree(c, start, end,
1069 				drop_extra_replicas_btree_pred, c, stats) ?: ret;
1070 		ret = bch2_move_data(c, start, end, NULL, stats,
1071 				writepoint_hashed((unsigned long) current),
1072 				true,
1073 				drop_extra_replicas_pred, c) ?: ret;
1074 		ret = bch2_replicas_gc2(c) ?: ret;
1075 		break;
1076 	default:
1077 		ret = -EINVAL;
1078 	}
1079 
1080 	bch2_move_stats_exit(stats, c);
1081 	return ret;
1082 }
1083 
1084 void bch2_move_stats_to_text(struct printbuf *out, struct bch_move_stats *stats)
1085 {
1086 	prt_printf(out, "%s: data type=%s pos=",
1087 		   stats->name,
1088 		   bch2_data_types[stats->data_type]);
1089 	bch2_bbpos_to_text(out, stats->pos);
1090 	prt_newline(out);
1091 	printbuf_indent_add(out, 2);
1092 
1093 	prt_str(out, "keys moved:  ");
1094 	prt_u64(out, atomic64_read(&stats->keys_moved));
1095 	prt_newline(out);
1096 
1097 	prt_str(out, "keys raced:  ");
1098 	prt_u64(out, atomic64_read(&stats->keys_raced));
1099 	prt_newline(out);
1100 
1101 	prt_str(out, "bytes seen:  ");
1102 	prt_human_readable_u64(out, atomic64_read(&stats->sectors_seen) << 9);
1103 	prt_newline(out);
1104 
1105 	prt_str(out, "bytes moved: ");
1106 	prt_human_readable_u64(out, atomic64_read(&stats->sectors_moved) << 9);
1107 	prt_newline(out);
1108 
1109 	prt_str(out, "bytes raced: ");
1110 	prt_human_readable_u64(out, atomic64_read(&stats->sectors_raced) << 9);
1111 	prt_newline(out);
1112 
1113 	printbuf_indent_sub(out, 2);
1114 }
1115 
1116 static void bch2_moving_ctxt_to_text(struct printbuf *out, struct bch_fs *c, struct moving_context *ctxt)
1117 {
1118 	struct moving_io *io;
1119 
1120 	bch2_move_stats_to_text(out, ctxt->stats);
1121 	printbuf_indent_add(out, 2);
1122 
1123 	prt_printf(out, "reads: ios %u/%u sectors %u/%u",
1124 		   atomic_read(&ctxt->read_ios),
1125 		   c->opts.move_ios_in_flight,
1126 		   atomic_read(&ctxt->read_sectors),
1127 		   c->opts.move_bytes_in_flight >> 9);
1128 	prt_newline(out);
1129 
1130 	prt_printf(out, "writes: ios %u/%u sectors %u/%u",
1131 		   atomic_read(&ctxt->write_ios),
1132 		   c->opts.move_ios_in_flight,
1133 		   atomic_read(&ctxt->write_sectors),
1134 		   c->opts.move_bytes_in_flight >> 9);
1135 	prt_newline(out);
1136 
1137 	printbuf_indent_add(out, 2);
1138 
1139 	mutex_lock(&ctxt->lock);
1140 	list_for_each_entry(io, &ctxt->ios, io_list)
1141 		bch2_write_op_to_text(out, &io->write.op);
1142 	mutex_unlock(&ctxt->lock);
1143 
1144 	printbuf_indent_sub(out, 4);
1145 }
1146 
1147 void bch2_fs_moving_ctxts_to_text(struct printbuf *out, struct bch_fs *c)
1148 {
1149 	struct moving_context *ctxt;
1150 
1151 	mutex_lock(&c->moving_context_lock);
1152 	list_for_each_entry(ctxt, &c->moving_context_list, list)
1153 		bch2_moving_ctxt_to_text(out, c, ctxt);
1154 	mutex_unlock(&c->moving_context_lock);
1155 }
1156 
1157 void bch2_fs_move_init(struct bch_fs *c)
1158 {
1159 	INIT_LIST_HEAD(&c->moving_context_list);
1160 	mutex_init(&c->moving_context_lock);
1161 }
1162