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