]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/move.c
Update bcachefs sources to 3e93567c51 bcachefs: Switch to local_clock() for fastpath...
[bcachefs-tools-debian] / libbcachefs / move.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "alloc_foreground.h"
5 #include "backpointers.h"
6 #include "bkey_buf.h"
7 #include "btree_gc.h"
8 #include "btree_update.h"
9 #include "btree_update_interior.h"
10 #include "disk_groups.h"
11 #include "ec.h"
12 #include "errcode.h"
13 #include "error.h"
14 #include "inode.h"
15 #include "io.h"
16 #include "journal_reclaim.h"
17 #include "move.h"
18 #include "replicas.h"
19 #include "super-io.h"
20 #include "keylist.h"
21
22 #include <linux/ioprio.h>
23 #include <linux/kthread.h>
24
25 #include <trace/events/bcachefs.h>
26
27 static void progress_list_add(struct bch_fs *c, struct bch_move_stats *stats)
28 {
29         mutex_lock(&c->data_progress_lock);
30         list_add(&stats->list, &c->data_progress_list);
31         mutex_unlock(&c->data_progress_lock);
32 }
33
34 static void progress_list_del(struct bch_fs *c, struct bch_move_stats *stats)
35 {
36         mutex_lock(&c->data_progress_lock);
37         list_del(&stats->list);
38         mutex_unlock(&c->data_progress_lock);
39 }
40
41 struct moving_io {
42         struct list_head        list;
43         struct closure          cl;
44         bool                    read_completed;
45
46         unsigned                read_sectors;
47         unsigned                write_sectors;
48
49         struct bch_read_bio     rbio;
50
51         struct data_update      write;
52         /* Must be last since it is variable size */
53         struct bio_vec          bi_inline_vecs[0];
54 };
55
56 static void move_free(struct closure *cl)
57 {
58         struct moving_io *io = container_of(cl, struct moving_io, cl);
59         struct moving_context *ctxt = io->write.ctxt;
60         struct bch_fs *c = ctxt->c;
61
62         bch2_data_update_exit(&io->write);
63         wake_up(&ctxt->wait);
64         percpu_ref_put(&c->writes);
65         kfree(io);
66 }
67
68 static void move_write_done(struct closure *cl)
69 {
70         struct moving_io *io = container_of(cl, struct moving_io, cl);
71         struct moving_context *ctxt = io->write.ctxt;
72
73         if (io->write.op.error)
74                 ctxt->write_error = true;
75
76         atomic_sub(io->write_sectors, &io->write.ctxt->write_sectors);
77         closure_return_with_destructor(cl, move_free);
78 }
79
80 static void move_write(struct closure *cl)
81 {
82         struct moving_io *io = container_of(cl, struct moving_io, cl);
83
84         if (unlikely(io->rbio.bio.bi_status || io->rbio.hole)) {
85                 closure_return_with_destructor(cl, move_free);
86                 return;
87         }
88
89         atomic_add(io->write_sectors, &io->write.ctxt->write_sectors);
90
91         bch2_data_update_read_done(&io->write, io->rbio.pick.crc, cl);
92         continue_at(cl, move_write_done, NULL);
93 }
94
95 static inline struct moving_io *next_pending_write(struct moving_context *ctxt)
96 {
97         struct moving_io *io =
98                 list_first_entry_or_null(&ctxt->reads, struct moving_io, list);
99
100         return io && io->read_completed ? io : NULL;
101 }
102
103 static void move_read_endio(struct bio *bio)
104 {
105         struct moving_io *io = container_of(bio, struct moving_io, rbio.bio);
106         struct moving_context *ctxt = io->write.ctxt;
107
108         atomic_sub(io->read_sectors, &ctxt->read_sectors);
109         io->read_completed = true;
110
111         wake_up(&ctxt->wait);
112         closure_put(&ctxt->cl);
113 }
114
115 static void do_pending_writes(struct moving_context *ctxt, struct btree_trans *trans)
116 {
117         struct moving_io *io;
118
119         if (trans)
120                 bch2_trans_unlock(trans);
121
122         while ((io = next_pending_write(ctxt))) {
123                 list_del(&io->list);
124                 closure_call(&io->cl, move_write, NULL, &ctxt->cl);
125         }
126 }
127
128 #define move_ctxt_wait_event(_ctxt, _trans, _cond)              \
129 do {                                                            \
130         do_pending_writes(_ctxt, _trans);                       \
131                                                                 \
132         if (_cond)                                              \
133                 break;                                          \
134         __wait_event((_ctxt)->wait,                             \
135                      next_pending_write(_ctxt) || (_cond));     \
136 } while (1)
137
138 static void bch2_move_ctxt_wait_for_io(struct moving_context *ctxt,
139                                        struct btree_trans *trans)
140 {
141         unsigned sectors_pending = atomic_read(&ctxt->write_sectors);
142
143         move_ctxt_wait_event(ctxt, trans,
144                 !atomic_read(&ctxt->write_sectors) ||
145                 atomic_read(&ctxt->write_sectors) != sectors_pending);
146 }
147
148 void bch2_moving_ctxt_exit(struct moving_context *ctxt)
149 {
150         move_ctxt_wait_event(ctxt, NULL, list_empty(&ctxt->reads));
151         closure_sync(&ctxt->cl);
152         EBUG_ON(atomic_read(&ctxt->write_sectors));
153
154         if (ctxt->stats) {
155                 progress_list_del(ctxt->c, ctxt->stats);
156
157                 trace_move_data(ctxt->c,
158                                 atomic64_read(&ctxt->stats->sectors_moved),
159                                 atomic64_read(&ctxt->stats->keys_moved));
160         }
161 }
162
163 void bch2_moving_ctxt_init(struct moving_context *ctxt,
164                            struct bch_fs *c,
165                            struct bch_ratelimit *rate,
166                            struct bch_move_stats *stats,
167                            struct write_point_specifier wp,
168                            bool wait_on_copygc)
169 {
170         memset(ctxt, 0, sizeof(*ctxt));
171
172         ctxt->c         = c;
173         ctxt->rate      = rate;
174         ctxt->stats     = stats;
175         ctxt->wp        = wp;
176         ctxt->wait_on_copygc = wait_on_copygc;
177
178         closure_init_stack(&ctxt->cl);
179         INIT_LIST_HEAD(&ctxt->reads);
180         init_waitqueue_head(&ctxt->wait);
181
182         if (stats) {
183                 progress_list_add(c, stats);
184                 stats->data_type = BCH_DATA_user;
185         }
186 }
187
188 void bch_move_stats_init(struct bch_move_stats *stats, char *name)
189 {
190         memset(stats, 0, sizeof(*stats));
191         scnprintf(stats->name, sizeof(stats->name), "%s", name);
192 }
193
194 static int bch2_extent_drop_ptrs(struct btree_trans *trans,
195                                  struct btree_iter *iter,
196                                  struct bkey_s_c k,
197                                  struct data_update_opts data_opts)
198 {
199         struct bch_fs *c = trans->c;
200         struct bkey_i *n;
201         int ret;
202
203         n = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
204         ret = PTR_ERR_OR_ZERO(n);
205         if (ret)
206                 return ret;
207
208         bkey_reassemble(n, k);
209
210         while (data_opts.kill_ptrs) {
211                 unsigned i = 0, drop = __fls(data_opts.kill_ptrs);
212                 struct bch_extent_ptr *ptr;
213
214                 bch2_bkey_drop_ptrs(bkey_i_to_s(n), ptr, i++ == drop);
215                 data_opts.kill_ptrs ^= 1U << drop;
216         }
217
218         /*
219          * If the new extent no longer has any pointers, bch2_extent_normalize()
220          * will do the appropriate thing with it (turning it into a
221          * KEY_TYPE_error key, or just a discard if it was a cached extent)
222          */
223         bch2_extent_normalize(c, bkey_i_to_s(n));
224
225         /*
226          * Since we're not inserting through an extent iterator
227          * (BTREE_ITER_ALL_SNAPSHOTS iterators aren't extent iterators),
228          * we aren't using the extent overwrite path to delete, we're
229          * just using the normal key deletion path:
230          */
231         if (bkey_deleted(&n->k))
232                 n->k.size = 0;
233
234         return bch2_trans_update(trans, iter, n, BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE) ?:
235                 bch2_trans_commit(trans, NULL, NULL, BTREE_INSERT_NOFAIL);
236 }
237
238 static int bch2_move_extent(struct btree_trans *trans,
239                             struct btree_iter *iter,
240                             struct moving_context *ctxt,
241                             struct bch_io_opts io_opts,
242                             enum btree_id btree_id,
243                             struct bkey_s_c k,
244                             struct data_update_opts data_opts)
245 {
246         struct bch_fs *c = trans->c;
247         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
248         struct moving_io *io;
249         const union bch_extent_entry *entry;
250         struct extent_ptr_decoded p;
251         unsigned sectors = k.k->size, pages;
252         int ret = -ENOMEM;
253
254         bch2_data_update_opts_normalize(k, &data_opts);
255
256         if (!data_opts.rewrite_ptrs &&
257             !data_opts.extra_replicas) {
258                 if (data_opts.kill_ptrs)
259                         return bch2_extent_drop_ptrs(trans, iter, k, data_opts);
260                 return 0;
261         }
262
263         if (!percpu_ref_tryget_live(&c->writes))
264                 return -EROFS;
265
266         /* write path might have to decompress data: */
267         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
268                 sectors = max_t(unsigned, sectors, p.crc.uncompressed_size);
269
270         pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
271         io = kzalloc(sizeof(struct moving_io) +
272                      sizeof(struct bio_vec) * pages, GFP_KERNEL);
273         if (!io)
274                 goto err;
275
276         io->write.ctxt          = ctxt;
277         io->read_sectors        = k.k->size;
278         io->write_sectors       = k.k->size;
279
280         bio_init(&io->write.op.wbio.bio, NULL, io->bi_inline_vecs, pages, 0);
281         bio_set_prio(&io->write.op.wbio.bio,
282                      IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
283
284         if (bch2_bio_alloc_pages(&io->write.op.wbio.bio, sectors << 9,
285                                  GFP_KERNEL))
286                 goto err_free;
287
288         io->rbio.c              = c;
289         io->rbio.opts           = io_opts;
290         bio_init(&io->rbio.bio, NULL, io->bi_inline_vecs, pages, 0);
291         io->rbio.bio.bi_vcnt = pages;
292         bio_set_prio(&io->rbio.bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
293         io->rbio.bio.bi_iter.bi_size = sectors << 9;
294
295         bio_set_op_attrs(&io->rbio.bio, REQ_OP_READ, 0);
296         io->rbio.bio.bi_iter.bi_sector  = bkey_start_offset(k.k);
297         io->rbio.bio.bi_end_io          = move_read_endio;
298
299         ret = bch2_data_update_init(c, &io->write, ctxt->wp, io_opts,
300                                     data_opts, btree_id, k);
301         if (ret)
302                 goto err_free_pages;
303
304         io->write.ctxt = ctxt;
305
306         atomic64_inc(&ctxt->stats->keys_moved);
307         atomic64_add(k.k->size, &ctxt->stats->sectors_moved);
308         this_cpu_add(c->counters[BCH_COUNTER_io_move], k.k->size);
309         this_cpu_add(c->counters[BCH_COUNTER_move_extent_read], k.k->size);
310         trace_move_extent_read(k.k);
311
312         atomic_add(io->read_sectors, &ctxt->read_sectors);
313         list_add_tail(&io->list, &ctxt->reads);
314
315         /*
316          * dropped by move_read_endio() - guards against use after free of
317          * ctxt when doing wakeup
318          */
319         closure_get(&ctxt->cl);
320         bch2_read_extent(trans, &io->rbio,
321                          bkey_start_pos(k.k),
322                          btree_id, k, 0,
323                          BCH_READ_NODECODE|
324                          BCH_READ_LAST_FRAGMENT);
325         return 0;
326 err_free_pages:
327         bio_free_pages(&io->write.op.wbio.bio);
328 err_free:
329         kfree(io);
330 err:
331         percpu_ref_put(&c->writes);
332         trace_and_count(c, move_extent_alloc_mem_fail, k.k);
333         return ret;
334 }
335
336 static int lookup_inode(struct btree_trans *trans, struct bpos pos,
337                         struct bch_inode_unpacked *inode)
338 {
339         struct btree_iter iter;
340         struct bkey_s_c k;
341         int ret;
342
343         bch2_trans_iter_init(trans, &iter, BTREE_ID_inodes, pos,
344                              BTREE_ITER_ALL_SNAPSHOTS);
345         k = bch2_btree_iter_peek(&iter);
346         ret = bkey_err(k);
347         if (ret)
348                 goto err;
349
350         if (!k.k || bkey_cmp(k.k->p, pos)) {
351                 ret = -ENOENT;
352                 goto err;
353         }
354
355         ret = bkey_is_inode(k.k) ? 0 : -EIO;
356         if (ret)
357                 goto err;
358
359         ret = bch2_inode_unpack(k, inode);
360         if (ret)
361                 goto err;
362 err:
363         bch2_trans_iter_exit(trans, &iter);
364         return ret;
365 }
366
367 static int move_ratelimit(struct btree_trans *trans,
368                           struct moving_context *ctxt)
369 {
370         struct bch_fs *c = trans->c;
371         u64 delay;
372
373         if (ctxt->wait_on_copygc) {
374                 bch2_trans_unlock(trans);
375                 wait_event_killable(c->copygc_running_wq,
376                                     !c->copygc_running ||
377                                     kthread_should_stop());
378         }
379
380         do {
381                 delay = ctxt->rate ? bch2_ratelimit_delay(ctxt->rate) : 0;
382
383                 if (delay) {
384                         bch2_trans_unlock(trans);
385                         set_current_state(TASK_INTERRUPTIBLE);
386                 }
387
388                 if ((current->flags & PF_KTHREAD) && kthread_should_stop()) {
389                         __set_current_state(TASK_RUNNING);
390                         return 1;
391                 }
392
393                 if (delay)
394                         schedule_timeout(delay);
395
396                 if (unlikely(freezing(current))) {
397                         move_ctxt_wait_event(ctxt, trans, list_empty(&ctxt->reads));
398                         try_to_freeze();
399                 }
400         } while (delay);
401
402         move_ctxt_wait_event(ctxt, trans,
403                 atomic_read(&ctxt->write_sectors) <
404                 c->opts.move_bytes_in_flight >> 9);
405
406         move_ctxt_wait_event(ctxt, trans,
407                 atomic_read(&ctxt->read_sectors) <
408                 c->opts.move_bytes_in_flight >> 9);
409
410         return 0;
411 }
412
413 static int move_get_io_opts(struct btree_trans *trans,
414                             struct bch_io_opts *io_opts,
415                             struct bkey_s_c k, u64 *cur_inum)
416 {
417         struct bch_inode_unpacked inode;
418         int ret;
419
420         if (*cur_inum == k.k->p.inode)
421                 return 0;
422
423         *io_opts = bch2_opts_to_inode_opts(trans->c->opts);
424
425         ret = lookup_inode(trans,
426                            SPOS(0, k.k->p.inode, k.k->p.snapshot),
427                            &inode);
428         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
429                 return ret;
430
431         if (!ret)
432                 bch2_io_opts_apply(io_opts, bch2_inode_opts_get(&inode));
433
434         *cur_inum = k.k->p.inode;
435         return 0;
436 }
437
438 static int __bch2_move_data(struct moving_context *ctxt,
439                             struct bpos start,
440                             struct bpos end,
441                             move_pred_fn pred, void *arg,
442                             enum btree_id btree_id)
443 {
444         struct bch_fs *c = ctxt->c;
445         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
446         struct bkey_buf sk;
447         struct btree_trans trans;
448         struct btree_iter iter;
449         struct bkey_s_c k;
450         struct data_update_opts data_opts;
451         u64 cur_inum = U64_MAX;
452         int ret = 0, ret2;
453
454         bch2_bkey_buf_init(&sk);
455         bch2_trans_init(&trans, c, 0, 0);
456
457         ctxt->stats->data_type  = BCH_DATA_user;
458         ctxt->stats->btree_id   = btree_id;
459         ctxt->stats->pos        = start;
460
461         bch2_trans_iter_init(&trans, &iter, btree_id, start,
462                              BTREE_ITER_PREFETCH|
463                              BTREE_ITER_ALL_SNAPSHOTS);
464
465         if (ctxt->rate)
466                 bch2_ratelimit_reset(ctxt->rate);
467
468         while (!move_ratelimit(&trans, ctxt)) {
469                 bch2_trans_begin(&trans);
470
471                 k = bch2_btree_iter_peek(&iter);
472                 if (!k.k)
473                         break;
474
475                 ret = bkey_err(k);
476                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
477                         continue;
478                 if (ret)
479                         break;
480
481                 if (bkey_cmp(bkey_start_pos(k.k), end) >= 0)
482                         break;
483
484                 ctxt->stats->pos = iter.pos;
485
486                 if (!bkey_extent_is_direct_data(k.k))
487                         goto next_nondata;
488
489                 ret = move_get_io_opts(&trans, &io_opts, k, &cur_inum);
490                 if (ret)
491                         continue;
492
493                 memset(&data_opts, 0, sizeof(data_opts));
494                 if (!pred(c, arg, k, &io_opts, &data_opts))
495                         goto next;
496
497                 /*
498                  * The iterator gets unlocked by __bch2_read_extent - need to
499                  * save a copy of @k elsewhere:
500                   */
501                 bch2_bkey_buf_reassemble(&sk, c, k);
502                 k = bkey_i_to_s_c(sk.k);
503
504                 ret2 = bch2_move_extent(&trans, &iter, ctxt, io_opts,
505                                         btree_id, k, data_opts);
506                 if (ret2) {
507                         if (bch2_err_matches(ret2, BCH_ERR_transaction_restart))
508                                 continue;
509
510                         if (ret2 == -ENOMEM) {
511                                 /* memory allocation failure, wait for some IO to finish */
512                                 bch2_move_ctxt_wait_for_io(ctxt, &trans);
513                                 continue;
514                         }
515
516                         /* XXX signal failure */
517                         goto next;
518                 }
519
520                 if (ctxt->rate)
521                         bch2_ratelimit_increment(ctxt->rate, k.k->size);
522 next:
523                 atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
524 next_nondata:
525                 bch2_btree_iter_advance(&iter);
526         }
527
528         bch2_trans_iter_exit(&trans, &iter);
529         bch2_trans_exit(&trans);
530         bch2_bkey_buf_exit(&sk, c);
531
532         return ret;
533 }
534
535 int bch2_move_data(struct bch_fs *c,
536                    enum btree_id start_btree_id, struct bpos start_pos,
537                    enum btree_id end_btree_id,   struct bpos end_pos,
538                    struct bch_ratelimit *rate,
539                    struct bch_move_stats *stats,
540                    struct write_point_specifier wp,
541                    bool wait_on_copygc,
542                    move_pred_fn pred, void *arg)
543 {
544         struct moving_context ctxt;
545         enum btree_id id;
546         int ret;
547
548         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
549
550         for (id = start_btree_id;
551              id <= min_t(unsigned, end_btree_id, BTREE_ID_NR - 1);
552              id++) {
553                 stats->btree_id = id;
554
555                 if (id != BTREE_ID_extents &&
556                     id != BTREE_ID_reflink)
557                         continue;
558
559                 ret = __bch2_move_data(&ctxt,
560                                        id == start_btree_id ? start_pos : POS_MIN,
561                                        id == end_btree_id   ? end_pos   : POS_MAX,
562                                        pred, arg, id);
563                 if (ret)
564                         break;
565         }
566
567         bch2_moving_ctxt_exit(&ctxt);
568
569         return ret;
570 }
571
572 static int verify_bucket_evacuated(struct btree_trans *trans, struct bpos bucket, int gen)
573 {
574         struct bch_fs *c = trans->c;
575         struct btree_iter iter;
576         struct bkey_s_c k;
577         int ret;
578
579         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
580                              bucket, BTREE_ITER_CACHED);
581 again:
582         k = bch2_btree_iter_peek_slot(&iter);
583         ret = bkey_err(k);
584
585         if (!ret && k.k->type == KEY_TYPE_alloc_v4) {
586                 struct bkey_s_c_alloc_v4 a = bkey_s_c_to_alloc_v4(k);
587
588                 if (a.v->gen == gen &&
589                     a.v->dirty_sectors) {
590                         struct printbuf buf = PRINTBUF;
591
592                         if (a.v->data_type == BCH_DATA_btree) {
593                                 bch2_trans_unlock(trans);
594                                 if (bch2_btree_interior_updates_flush(c))
595                                         goto again;
596                         }
597
598                         prt_str(&buf, "failed to evacuate bucket ");
599                         bch2_bkey_val_to_text(&buf, c, k);
600
601                         bch_err(c, "%s", buf.buf);
602                         printbuf_exit(&buf);
603                 }
604         }
605
606         bch2_trans_iter_exit(trans, &iter);
607         return ret;
608 }
609
610 int __bch2_evacuate_bucket(struct moving_context *ctxt,
611                            struct bpos bucket, int gen,
612                            struct data_update_opts _data_opts)
613 {
614         struct bch_fs *c = ctxt->c;
615         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
616         struct btree_trans trans;
617         struct btree_iter iter;
618         struct bkey_buf sk;
619         struct bch_backpointer bp;
620         struct data_update_opts data_opts;
621         u64 bp_offset = 0, cur_inum = U64_MAX;
622         int ret = 0;
623
624         bch2_bkey_buf_init(&sk);
625         bch2_trans_init(&trans, c, 0, 0);
626
627         while (!(ret = move_ratelimit(&trans, ctxt))) {
628                 bch2_trans_begin(&trans);
629
630                 ret = bch2_get_next_backpointer(&trans, bucket, gen,
631                                                 &bp_offset, &bp,
632                                                 BTREE_ITER_CACHED);
633                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
634                         continue;
635                 if (ret)
636                         goto err;
637                 if (bp_offset == U64_MAX)
638                         break;
639
640                 if (!bp.level) {
641                         const struct bch_extent_ptr *ptr;
642                         struct bkey_s_c k;
643                         unsigned i = 0;
644
645                         k = bch2_backpointer_get_key(&trans, &iter,
646                                                 bucket, bp_offset, bp);
647                         ret = bkey_err(k);
648                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
649                                 continue;
650                         if (ret)
651                                 goto err;
652                         if (!k.k)
653                                 continue;
654
655                         bch2_bkey_buf_reassemble(&sk, c, k);
656                         k = bkey_i_to_s_c(sk.k);
657
658                         ret = move_get_io_opts(&trans, &io_opts, k, &cur_inum);
659                         if (ret) {
660                                 bch2_trans_iter_exit(&trans, &iter);
661                                 continue;
662                         }
663
664                         data_opts = _data_opts;
665                         data_opts.target        = io_opts.background_target;
666                         data_opts.rewrite_ptrs = 0;
667
668                         bkey_for_each_ptr(bch2_bkey_ptrs_c(k), ptr) {
669                                 if (ptr->dev == bucket.inode)
670                                         data_opts.rewrite_ptrs |= 1U << i;
671                                 i++;
672                         }
673
674                         ret = bch2_move_extent(&trans, &iter, ctxt, io_opts,
675                                                bp.btree_id, k, data_opts);
676                         bch2_trans_iter_exit(&trans, &iter);
677
678                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
679                                 continue;
680                         if (ret == -ENOMEM) {
681                                 /* memory allocation failure, wait for some IO to finish */
682                                 bch2_move_ctxt_wait_for_io(ctxt, &trans);
683                                 continue;
684                         }
685                         if (ret)
686                                 goto err;
687
688                         if (ctxt->rate)
689                                 bch2_ratelimit_increment(ctxt->rate, k.k->size);
690                         atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
691                 } else {
692                         struct btree *b;
693
694                         b = bch2_backpointer_get_node(&trans, &iter,
695                                                 bucket, bp_offset, bp);
696                         ret = PTR_ERR_OR_ZERO(b);
697                         if (ret == -BCH_ERR_backpointer_to_overwritten_btree_node)
698                                 continue;
699                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
700                                 continue;
701                         if (ret)
702                                 goto err;
703                         if (!b)
704                                 continue;
705
706                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0);
707                         bch2_trans_iter_exit(&trans, &iter);
708
709                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
710                                 continue;
711                         if (ret)
712                                 goto err;
713
714                         if (ctxt->rate)
715                                 bch2_ratelimit_increment(ctxt->rate,
716                                                          c->opts.btree_node_size >> 9);
717                         atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_seen);
718                         atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_moved);
719                 }
720
721                 bp_offset++;
722         }
723
724         if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) && gen >= 0) {
725                 bch2_trans_unlock(&trans);
726                 move_ctxt_wait_event(ctxt, NULL, list_empty(&ctxt->reads));
727                 closure_sync(&ctxt->cl);
728                 if (!ctxt->write_error)
729                         lockrestart_do(&trans, verify_bucket_evacuated(&trans, bucket, gen));
730         }
731 err:
732         bch2_trans_exit(&trans);
733         bch2_bkey_buf_exit(&sk, c);
734         return ret;
735 }
736
737 int bch2_evacuate_bucket(struct bch_fs *c,
738                          struct bpos bucket, int gen,
739                          struct data_update_opts data_opts,
740                          struct bch_ratelimit *rate,
741                          struct bch_move_stats *stats,
742                          struct write_point_specifier wp,
743                          bool wait_on_copygc)
744 {
745         struct moving_context ctxt;
746         int ret;
747
748         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
749         ret = __bch2_evacuate_bucket(&ctxt, bucket, gen, data_opts);
750         bch2_moving_ctxt_exit(&ctxt);
751
752         return ret;
753 }
754
755 typedef bool (*move_btree_pred)(struct bch_fs *, void *,
756                                 struct btree *, struct bch_io_opts *,
757                                 struct data_update_opts *);
758
759 static int bch2_move_btree(struct bch_fs *c,
760                            enum btree_id start_btree_id, struct bpos start_pos,
761                            enum btree_id end_btree_id,   struct bpos end_pos,
762                            move_btree_pred pred, void *arg,
763                            struct bch_move_stats *stats)
764 {
765         bool kthread = (current->flags & PF_KTHREAD) != 0;
766         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
767         struct btree_trans trans;
768         struct btree_iter iter;
769         struct btree *b;
770         enum btree_id id;
771         struct data_update_opts data_opts;
772         int ret = 0;
773
774         bch2_trans_init(&trans, c, 0, 0);
775         progress_list_add(c, stats);
776
777         stats->data_type = BCH_DATA_btree;
778
779         for (id = start_btree_id;
780              id <= min_t(unsigned, end_btree_id, BTREE_ID_NR - 1);
781              id++) {
782                 stats->btree_id = id;
783
784                 bch2_trans_node_iter_init(&trans, &iter, id, POS_MIN, 0, 0,
785                                           BTREE_ITER_PREFETCH);
786 retry:
787                 ret = 0;
788                 while (bch2_trans_begin(&trans),
789                        (b = bch2_btree_iter_peek_node(&iter)) &&
790                        !(ret = PTR_ERR_OR_ZERO(b))) {
791                         if (kthread && kthread_should_stop())
792                                 break;
793
794                         if ((cmp_int(id, end_btree_id) ?:
795                              bpos_cmp(b->key.k.p, end_pos)) > 0)
796                                 break;
797
798                         stats->pos = iter.pos;
799
800                         if (!pred(c, arg, b, &io_opts, &data_opts))
801                                 goto next;
802
803                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0) ?: ret;
804                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
805                                 continue;
806                         if (ret)
807                                 break;
808 next:
809                         bch2_btree_iter_next_node(&iter);
810                 }
811                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
812                         goto retry;
813
814                 bch2_trans_iter_exit(&trans, &iter);
815
816                 if (kthread && kthread_should_stop())
817                         break;
818         }
819
820         bch2_trans_exit(&trans);
821
822         if (ret)
823                 bch_err(c, "error in %s(): %s", __func__, bch2_err_str(ret));
824
825         bch2_btree_interior_updates_flush(c);
826
827         progress_list_del(c, stats);
828         return ret;
829 }
830
831 static bool rereplicate_pred(struct bch_fs *c, void *arg,
832                              struct bkey_s_c k,
833                              struct bch_io_opts *io_opts,
834                              struct data_update_opts *data_opts)
835 {
836         unsigned nr_good = bch2_bkey_durability(c, k);
837         unsigned replicas = bkey_is_btree_ptr(k.k)
838                 ? c->opts.metadata_replicas
839                 : io_opts->data_replicas;
840
841         if (!nr_good || nr_good >= replicas)
842                 return false;
843
844         data_opts->target               = 0;
845         data_opts->extra_replicas       = replicas - nr_good;
846         data_opts->btree_insert_flags   = 0;
847         return true;
848 }
849
850 static bool migrate_pred(struct bch_fs *c, void *arg,
851                          struct bkey_s_c k,
852                          struct bch_io_opts *io_opts,
853                          struct data_update_opts *data_opts)
854 {
855         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
856         const struct bch_extent_ptr *ptr;
857         struct bch_ioctl_data *op = arg;
858         unsigned i = 0;
859
860         data_opts->rewrite_ptrs         = 0;
861         data_opts->target               = 0;
862         data_opts->extra_replicas       = 0;
863         data_opts->btree_insert_flags   = 0;
864
865         bkey_for_each_ptr(ptrs, ptr) {
866                 if (ptr->dev == op->migrate.dev)
867                         data_opts->rewrite_ptrs |= 1U << i;
868                 i++;
869         }
870
871         return data_opts->rewrite_ptrs != 0;;
872 }
873
874 static bool rereplicate_btree_pred(struct bch_fs *c, void *arg,
875                                    struct btree *b,
876                                    struct bch_io_opts *io_opts,
877                                    struct data_update_opts *data_opts)
878 {
879         return rereplicate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
880 }
881
882 static bool migrate_btree_pred(struct bch_fs *c, void *arg,
883                                struct btree *b,
884                                struct bch_io_opts *io_opts,
885                                struct data_update_opts *data_opts)
886 {
887         return migrate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
888 }
889
890 static bool bformat_needs_redo(struct bkey_format *f)
891 {
892         unsigned i;
893
894         for (i = 0; i < f->nr_fields; i++) {
895                 unsigned unpacked_bits = bch2_bkey_format_current.bits_per_field[i];
896                 u64 unpacked_mask = ~((~0ULL << 1) << (unpacked_bits - 1));
897                 u64 field_offset = le64_to_cpu(f->field_offset[i]);
898
899                 if (f->bits_per_field[i] > unpacked_bits)
900                         return true;
901
902                 if ((f->bits_per_field[i] == unpacked_bits) && field_offset)
903                         return true;
904
905                 if (((field_offset + ((1ULL << f->bits_per_field[i]) - 1)) &
906                      unpacked_mask) <
907                     field_offset)
908                         return true;
909         }
910
911         return false;
912 }
913
914 static bool rewrite_old_nodes_pred(struct bch_fs *c, void *arg,
915                                    struct btree *b,
916                                    struct bch_io_opts *io_opts,
917                                    struct data_update_opts *data_opts)
918 {
919         if (b->version_ondisk != c->sb.version ||
920             btree_node_need_rewrite(b) ||
921             bformat_needs_redo(&b->format)) {
922                 data_opts->target               = 0;
923                 data_opts->extra_replicas       = 0;
924                 data_opts->btree_insert_flags   = 0;
925                 return true;
926         }
927
928         return false;
929 }
930
931 int bch2_scan_old_btree_nodes(struct bch_fs *c, struct bch_move_stats *stats)
932 {
933         int ret;
934
935         ret = bch2_move_btree(c,
936                               0,                POS_MIN,
937                               BTREE_ID_NR,      SPOS_MAX,
938                               rewrite_old_nodes_pred, c, stats);
939         if (!ret) {
940                 mutex_lock(&c->sb_lock);
941                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
942                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
943                 c->disk_sb.sb->version_min = c->disk_sb.sb->version;
944                 bch2_write_super(c);
945                 mutex_unlock(&c->sb_lock);
946         }
947
948         return ret;
949 }
950
951 int bch2_data_job(struct bch_fs *c,
952                   struct bch_move_stats *stats,
953                   struct bch_ioctl_data op)
954 {
955         int ret = 0;
956
957         switch (op.op) {
958         case BCH_DATA_OP_REREPLICATE:
959                 bch_move_stats_init(stats, "rereplicate");
960                 stats->data_type = BCH_DATA_journal;
961                 ret = bch2_journal_flush_device_pins(&c->journal, -1);
962
963                 ret = bch2_move_btree(c,
964                                       op.start_btree,   op.start_pos,
965                                       op.end_btree,     op.end_pos,
966                                       rereplicate_btree_pred, c, stats) ?: ret;
967                 ret = bch2_replicas_gc2(c) ?: ret;
968
969                 ret = bch2_move_data(c,
970                                      op.start_btree,    op.start_pos,
971                                      op.end_btree,      op.end_pos,
972                                      NULL,
973                                      stats,
974                                      writepoint_hashed((unsigned long) current),
975                                      true,
976                                      rereplicate_pred, c) ?: ret;
977                 ret = bch2_replicas_gc2(c) ?: ret;
978                 break;
979         case BCH_DATA_OP_MIGRATE:
980                 if (op.migrate.dev >= c->sb.nr_devices)
981                         return -EINVAL;
982
983                 bch_move_stats_init(stats, "migrate");
984                 stats->data_type = BCH_DATA_journal;
985                 ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
986
987                 ret = bch2_move_btree(c,
988                                       op.start_btree,   op.start_pos,
989                                       op.end_btree,     op.end_pos,
990                                       migrate_btree_pred, &op, stats) ?: ret;
991                 ret = bch2_replicas_gc2(c) ?: ret;
992
993                 ret = bch2_move_data(c,
994                                      op.start_btree,    op.start_pos,
995                                      op.end_btree,      op.end_pos,
996                                      NULL,
997                                      stats,
998                                      writepoint_hashed((unsigned long) current),
999                                      true,
1000                                      migrate_pred, &op) ?: ret;
1001                 ret = bch2_replicas_gc2(c) ?: ret;
1002                 break;
1003         case BCH_DATA_OP_REWRITE_OLD_NODES:
1004                 bch_move_stats_init(stats, "rewrite_old_nodes");
1005                 ret = bch2_scan_old_btree_nodes(c, stats);
1006                 break;
1007         default:
1008                 ret = -EINVAL;
1009         }
1010
1011         return ret;
1012 }