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