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