]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/move.c
Update bcachefs sources to 5963d1b1a4 bcacehfs: Fix bch2_get_alloc_in_memory_pos()
[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         /*
265          * Before memory allocations & taking nocow locks in
266          * bch2_data_update_init():
267          */
268         bch2_trans_unlock(trans);
269
270         /* write path might have to decompress data: */
271         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
272                 sectors = max_t(unsigned, sectors, p.crc.uncompressed_size);
273
274         pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
275         io = kzalloc(sizeof(struct moving_io) +
276                      sizeof(struct bio_vec) * pages, GFP_KERNEL);
277         if (!io)
278                 goto err;
279
280         io->write.ctxt          = ctxt;
281         io->read_sectors        = k.k->size;
282         io->write_sectors       = k.k->size;
283
284         bio_init(&io->write.op.wbio.bio, NULL, io->bi_inline_vecs, pages, 0);
285         bio_set_prio(&io->write.op.wbio.bio,
286                      IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
287
288         if (bch2_bio_alloc_pages(&io->write.op.wbio.bio, sectors << 9,
289                                  GFP_KERNEL))
290                 goto err_free;
291
292         io->rbio.c              = c;
293         io->rbio.opts           = io_opts;
294         bio_init(&io->rbio.bio, NULL, io->bi_inline_vecs, pages, 0);
295         io->rbio.bio.bi_vcnt = pages;
296         bio_set_prio(&io->rbio.bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
297         io->rbio.bio.bi_iter.bi_size = sectors << 9;
298
299         bio_set_op_attrs(&io->rbio.bio, REQ_OP_READ, 0);
300         io->rbio.bio.bi_iter.bi_sector  = bkey_start_offset(k.k);
301         io->rbio.bio.bi_end_io          = move_read_endio;
302
303         ret = bch2_data_update_init(c, &io->write, ctxt->wp, io_opts,
304                                     data_opts, btree_id, k);
305         if (ret && ret != -BCH_ERR_unwritten_extent_update)
306                 goto err_free_pages;
307
308         io->write.ctxt = ctxt;
309         io->write.op.end_io = move_write_done;
310
311         atomic64_inc(&ctxt->stats->keys_moved);
312         atomic64_add(k.k->size, &ctxt->stats->sectors_moved);
313
314         if (ret == -BCH_ERR_unwritten_extent_update) {
315                 bch2_update_unwritten_extent(trans, &io->write);
316                 move_free(io);
317                 return 0;
318         }
319
320         BUG_ON(ret);
321
322         this_cpu_add(c->counters[BCH_COUNTER_io_move], k.k->size);
323         this_cpu_add(c->counters[BCH_COUNTER_move_extent_read], k.k->size);
324         trace_move_extent_read(k.k);
325
326         atomic_add(io->read_sectors, &ctxt->read_sectors);
327         list_add_tail(&io->list, &ctxt->reads);
328
329         /*
330          * dropped by move_read_endio() - guards against use after free of
331          * ctxt when doing wakeup
332          */
333         closure_get(&ctxt->cl);
334         bch2_read_extent(trans, &io->rbio,
335                          bkey_start_pos(k.k),
336                          btree_id, k, 0,
337                          BCH_READ_NODECODE|
338                          BCH_READ_LAST_FRAGMENT);
339         return 0;
340 err_free_pages:
341         bio_free_pages(&io->write.op.wbio.bio);
342 err_free:
343         kfree(io);
344 err:
345         percpu_ref_put(&c->writes);
346         trace_and_count(c, move_extent_alloc_mem_fail, k.k);
347         return ret;
348 }
349
350 static int lookup_inode(struct btree_trans *trans, struct bpos pos,
351                         struct bch_inode_unpacked *inode)
352 {
353         struct btree_iter iter;
354         struct bkey_s_c k;
355         int ret;
356
357         bch2_trans_iter_init(trans, &iter, BTREE_ID_inodes, pos,
358                              BTREE_ITER_ALL_SNAPSHOTS);
359         k = bch2_btree_iter_peek(&iter);
360         ret = bkey_err(k);
361         if (ret)
362                 goto err;
363
364         if (!k.k || !bkey_eq(k.k->p, pos)) {
365                 ret = -ENOENT;
366                 goto err;
367         }
368
369         ret = bkey_is_inode(k.k) ? 0 : -EIO;
370         if (ret)
371                 goto err;
372
373         ret = bch2_inode_unpack(k, inode);
374         if (ret)
375                 goto err;
376 err:
377         bch2_trans_iter_exit(trans, &iter);
378         return ret;
379 }
380
381 static int move_ratelimit(struct btree_trans *trans,
382                           struct moving_context *ctxt)
383 {
384         struct bch_fs *c = trans->c;
385         u64 delay;
386
387         if (ctxt->wait_on_copygc) {
388                 bch2_trans_unlock(trans);
389                 wait_event_killable(c->copygc_running_wq,
390                                     !c->copygc_running ||
391                                     kthread_should_stop());
392         }
393
394         do {
395                 delay = ctxt->rate ? bch2_ratelimit_delay(ctxt->rate) : 0;
396
397                 if (delay) {
398                         bch2_trans_unlock(trans);
399                         set_current_state(TASK_INTERRUPTIBLE);
400                 }
401
402                 if ((current->flags & PF_KTHREAD) && kthread_should_stop()) {
403                         __set_current_state(TASK_RUNNING);
404                         return 1;
405                 }
406
407                 if (delay)
408                         schedule_timeout(delay);
409
410                 if (unlikely(freezing(current))) {
411                         move_ctxt_wait_event(ctxt, trans, list_empty(&ctxt->reads));
412                         try_to_freeze();
413                 }
414         } while (delay);
415
416         move_ctxt_wait_event(ctxt, trans,
417                 atomic_read(&ctxt->write_sectors) <
418                 c->opts.move_bytes_in_flight >> 9);
419
420         move_ctxt_wait_event(ctxt, trans,
421                 atomic_read(&ctxt->read_sectors) <
422                 c->opts.move_bytes_in_flight >> 9);
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 data_update_opts data_opts;
667         u64 bp_offset = 0, cur_inum = U64_MAX;
668         int ret = 0;
669
670         bch2_bkey_buf_init(&sk);
671         bch2_trans_init(&trans, c, 0, 0);
672
673         while (!(ret = move_ratelimit(&trans, ctxt))) {
674                 bch2_trans_begin(&trans);
675
676                 ret = bch2_get_next_backpointer(&trans, bucket, gen,
677                                                 &bp_offset, &bp,
678                                                 BTREE_ITER_CACHED);
679                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
680                         continue;
681                 if (ret)
682                         goto err;
683                 if (bp_offset == U64_MAX)
684                         break;
685
686                 if (!bp.level) {
687                         const struct bch_extent_ptr *ptr;
688                         struct bkey_s_c k;
689                         unsigned i = 0;
690
691                         k = bch2_backpointer_get_key(&trans, &iter,
692                                                 bucket, bp_offset, bp);
693                         ret = bkey_err(k);
694                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
695                                 continue;
696                         if (ret)
697                                 goto err;
698                         if (!k.k)
699                                 continue;
700
701                         bch2_bkey_buf_reassemble(&sk, c, k);
702                         k = bkey_i_to_s_c(sk.k);
703
704                         ret = move_get_io_opts(&trans, &io_opts, k, &cur_inum);
705                         if (ret) {
706                                 bch2_trans_iter_exit(&trans, &iter);
707                                 continue;
708                         }
709
710                         data_opts = _data_opts;
711                         data_opts.target        = io_opts.background_target;
712                         data_opts.rewrite_ptrs = 0;
713
714                         bkey_for_each_ptr(bch2_bkey_ptrs_c(k), ptr) {
715                                 if (ptr->dev == bucket.inode)
716                                         data_opts.rewrite_ptrs |= 1U << i;
717                                 i++;
718                         }
719
720                         ret = bch2_move_extent(&trans, &iter, ctxt, io_opts,
721                                                bp.btree_id, k, data_opts);
722                         bch2_trans_iter_exit(&trans, &iter);
723
724                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
725                                 continue;
726                         if (ret == -ENOMEM) {
727                                 /* memory allocation failure, wait for some IO to finish */
728                                 bch2_move_ctxt_wait_for_io(ctxt, &trans);
729                                 continue;
730                         }
731                         if (ret)
732                                 goto err;
733
734                         if (ctxt->rate)
735                                 bch2_ratelimit_increment(ctxt->rate, k.k->size);
736                         atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
737                 } else {
738                         struct btree *b;
739
740                         b = bch2_backpointer_get_node(&trans, &iter,
741                                                 bucket, bp_offset, bp);
742                         ret = PTR_ERR_OR_ZERO(b);
743                         if (ret == -BCH_ERR_backpointer_to_overwritten_btree_node)
744                                 continue;
745                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
746                                 continue;
747                         if (ret)
748                                 goto err;
749                         if (!b)
750                                 continue;
751
752                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0);
753                         bch2_trans_iter_exit(&trans, &iter);
754
755                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
756                                 continue;
757                         if (ret)
758                                 goto err;
759
760                         if (ctxt->rate)
761                                 bch2_ratelimit_increment(ctxt->rate,
762                                                          c->opts.btree_node_size >> 9);
763                         atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_seen);
764                         atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_moved);
765                 }
766
767                 bp_offset++;
768         }
769
770         if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) && gen >= 0) {
771                 bch2_trans_unlock(&trans);
772                 move_ctxt_wait_event(ctxt, NULL, list_empty(&ctxt->reads));
773                 closure_sync(&ctxt->cl);
774                 if (!ctxt->write_error)
775                         lockrestart_do(&trans, verify_bucket_evacuated(&trans, bucket, gen));
776         }
777 err:
778         bch2_trans_exit(&trans);
779         bch2_bkey_buf_exit(&sk, c);
780         return ret;
781 }
782
783 int bch2_evacuate_bucket(struct bch_fs *c,
784                          struct bpos bucket, int gen,
785                          struct data_update_opts data_opts,
786                          struct bch_ratelimit *rate,
787                          struct bch_move_stats *stats,
788                          struct write_point_specifier wp,
789                          bool wait_on_copygc)
790 {
791         struct moving_context ctxt;
792         int ret;
793
794         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
795         ret = __bch2_evacuate_bucket(&ctxt, bucket, gen, data_opts);
796         bch2_moving_ctxt_exit(&ctxt);
797
798         return ret;
799 }
800
801 typedef bool (*move_btree_pred)(struct bch_fs *, void *,
802                                 struct btree *, struct bch_io_opts *,
803                                 struct data_update_opts *);
804
805 static int bch2_move_btree(struct bch_fs *c,
806                            enum btree_id start_btree_id, struct bpos start_pos,
807                            enum btree_id end_btree_id,   struct bpos end_pos,
808                            move_btree_pred pred, void *arg,
809                            struct bch_move_stats *stats)
810 {
811         bool kthread = (current->flags & PF_KTHREAD) != 0;
812         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
813         struct btree_trans trans;
814         struct btree_iter iter;
815         struct btree *b;
816         enum btree_id id;
817         struct data_update_opts data_opts;
818         int ret = 0;
819
820         bch2_trans_init(&trans, c, 0, 0);
821         progress_list_add(c, stats);
822
823         stats->data_type = BCH_DATA_btree;
824
825         for (id = start_btree_id;
826              id <= min_t(unsigned, end_btree_id, BTREE_ID_NR - 1);
827              id++) {
828                 stats->btree_id = id;
829
830                 bch2_trans_node_iter_init(&trans, &iter, id, POS_MIN, 0, 0,
831                                           BTREE_ITER_PREFETCH);
832 retry:
833                 ret = 0;
834                 while (bch2_trans_begin(&trans),
835                        (b = bch2_btree_iter_peek_node(&iter)) &&
836                        !(ret = PTR_ERR_OR_ZERO(b))) {
837                         if (kthread && kthread_should_stop())
838                                 break;
839
840                         if ((cmp_int(id, end_btree_id) ?:
841                              bpos_cmp(b->key.k.p, end_pos)) > 0)
842                                 break;
843
844                         stats->pos = iter.pos;
845
846                         if (!pred(c, arg, b, &io_opts, &data_opts))
847                                 goto next;
848
849                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0) ?: ret;
850                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
851                                 continue;
852                         if (ret)
853                                 break;
854 next:
855                         bch2_btree_iter_next_node(&iter);
856                 }
857                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
858                         goto retry;
859
860                 bch2_trans_iter_exit(&trans, &iter);
861
862                 if (kthread && kthread_should_stop())
863                         break;
864         }
865
866         bch2_trans_exit(&trans);
867
868         if (ret)
869                 bch_err(c, "error in %s(): %s", __func__, bch2_err_str(ret));
870
871         bch2_btree_interior_updates_flush(c);
872
873         progress_list_del(c, stats);
874         return ret;
875 }
876
877 static bool rereplicate_pred(struct bch_fs *c, void *arg,
878                              struct bkey_s_c k,
879                              struct bch_io_opts *io_opts,
880                              struct data_update_opts *data_opts)
881 {
882         unsigned nr_good = bch2_bkey_durability(c, k);
883         unsigned replicas = bkey_is_btree_ptr(k.k)
884                 ? c->opts.metadata_replicas
885                 : io_opts->data_replicas;
886
887         if (!nr_good || nr_good >= replicas)
888                 return false;
889
890         data_opts->target               = 0;
891         data_opts->extra_replicas       = replicas - nr_good;
892         data_opts->btree_insert_flags   = 0;
893         return true;
894 }
895
896 static bool migrate_pred(struct bch_fs *c, void *arg,
897                          struct bkey_s_c k,
898                          struct bch_io_opts *io_opts,
899                          struct data_update_opts *data_opts)
900 {
901         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
902         const struct bch_extent_ptr *ptr;
903         struct bch_ioctl_data *op = arg;
904         unsigned i = 0;
905
906         data_opts->rewrite_ptrs         = 0;
907         data_opts->target               = 0;
908         data_opts->extra_replicas       = 0;
909         data_opts->btree_insert_flags   = 0;
910
911         bkey_for_each_ptr(ptrs, ptr) {
912                 if (ptr->dev == op->migrate.dev)
913                         data_opts->rewrite_ptrs |= 1U << i;
914                 i++;
915         }
916
917         return data_opts->rewrite_ptrs != 0;
918 }
919
920 static bool rereplicate_btree_pred(struct bch_fs *c, void *arg,
921                                    struct btree *b,
922                                    struct bch_io_opts *io_opts,
923                                    struct data_update_opts *data_opts)
924 {
925         return rereplicate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
926 }
927
928 static bool migrate_btree_pred(struct bch_fs *c, void *arg,
929                                struct btree *b,
930                                struct bch_io_opts *io_opts,
931                                struct data_update_opts *data_opts)
932 {
933         return migrate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
934 }
935
936 static bool bformat_needs_redo(struct bkey_format *f)
937 {
938         unsigned i;
939
940         for (i = 0; i < f->nr_fields; i++) {
941                 unsigned unpacked_bits = bch2_bkey_format_current.bits_per_field[i];
942                 u64 unpacked_mask = ~((~0ULL << 1) << (unpacked_bits - 1));
943                 u64 field_offset = le64_to_cpu(f->field_offset[i]);
944
945                 if (f->bits_per_field[i] > unpacked_bits)
946                         return true;
947
948                 if ((f->bits_per_field[i] == unpacked_bits) && field_offset)
949                         return true;
950
951                 if (((field_offset + ((1ULL << f->bits_per_field[i]) - 1)) &
952                      unpacked_mask) <
953                     field_offset)
954                         return true;
955         }
956
957         return false;
958 }
959
960 static bool rewrite_old_nodes_pred(struct bch_fs *c, void *arg,
961                                    struct btree *b,
962                                    struct bch_io_opts *io_opts,
963                                    struct data_update_opts *data_opts)
964 {
965         if (b->version_ondisk != c->sb.version ||
966             btree_node_need_rewrite(b) ||
967             bformat_needs_redo(&b->format)) {
968                 data_opts->target               = 0;
969                 data_opts->extra_replicas       = 0;
970                 data_opts->btree_insert_flags   = 0;
971                 return true;
972         }
973
974         return false;
975 }
976
977 int bch2_scan_old_btree_nodes(struct bch_fs *c, struct bch_move_stats *stats)
978 {
979         int ret;
980
981         ret = bch2_move_btree(c,
982                               0,                POS_MIN,
983                               BTREE_ID_NR,      SPOS_MAX,
984                               rewrite_old_nodes_pred, c, stats);
985         if (!ret) {
986                 mutex_lock(&c->sb_lock);
987                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
988                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
989                 c->disk_sb.sb->version_min = c->disk_sb.sb->version;
990                 bch2_write_super(c);
991                 mutex_unlock(&c->sb_lock);
992         }
993
994         return ret;
995 }
996
997 int bch2_data_job(struct bch_fs *c,
998                   struct bch_move_stats *stats,
999                   struct bch_ioctl_data op)
1000 {
1001         int ret = 0;
1002
1003         switch (op.op) {
1004         case BCH_DATA_OP_REREPLICATE:
1005                 bch2_move_stats_init(stats, "rereplicate");
1006                 stats->data_type = BCH_DATA_journal;
1007                 ret = bch2_journal_flush_device_pins(&c->journal, -1);
1008
1009                 ret = bch2_move_btree(c,
1010                                       op.start_btree,   op.start_pos,
1011                                       op.end_btree,     op.end_pos,
1012                                       rereplicate_btree_pred, c, stats) ?: ret;
1013                 ret = bch2_replicas_gc2(c) ?: ret;
1014
1015                 ret = bch2_move_data(c,
1016                                      op.start_btree,    op.start_pos,
1017                                      op.end_btree,      op.end_pos,
1018                                      NULL,
1019                                      stats,
1020                                      writepoint_hashed((unsigned long) current),
1021                                      true,
1022                                      rereplicate_pred, c) ?: ret;
1023                 ret = bch2_replicas_gc2(c) ?: ret;
1024                 break;
1025         case BCH_DATA_OP_MIGRATE:
1026                 if (op.migrate.dev >= c->sb.nr_devices)
1027                         return -EINVAL;
1028
1029                 bch2_move_stats_init(stats, "migrate");
1030                 stats->data_type = BCH_DATA_journal;
1031                 ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
1032
1033                 ret = bch2_move_btree(c,
1034                                       op.start_btree,   op.start_pos,
1035                                       op.end_btree,     op.end_pos,
1036                                       migrate_btree_pred, &op, stats) ?: ret;
1037                 ret = bch2_replicas_gc2(c) ?: ret;
1038
1039                 ret = bch2_move_data(c,
1040                                      op.start_btree,    op.start_pos,
1041                                      op.end_btree,      op.end_pos,
1042                                      NULL,
1043                                      stats,
1044                                      writepoint_hashed((unsigned long) current),
1045                                      true,
1046                                      migrate_pred, &op) ?: ret;
1047                 ret = bch2_replicas_gc2(c) ?: ret;
1048                 break;
1049         case BCH_DATA_OP_REWRITE_OLD_NODES:
1050                 bch2_move_stats_init(stats, "rewrite_old_nodes");
1051                 ret = bch2_scan_old_btree_nodes(c, stats);
1052                 break;
1053         default:
1054                 ret = -EINVAL;
1055         }
1056
1057         return ret;
1058 }