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