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