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