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