]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/move.c
rust: Fix ptr casting in Fs::open()
[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         io->write.ctxt = ctxt;
308         io->write.op.end_io = move_write_done;
309
310         atomic64_inc(&ctxt->stats->keys_moved);
311         atomic64_add(k.k->size, &ctxt->stats->sectors_moved);
312
313         if (ret == -BCH_ERR_unwritten_extent_update) {
314                 bch2_update_unwritten_extent(trans, &io->write);
315                 move_free(io);
316                 return 0;
317         }
318
319         BUG_ON(ret);
320
321         this_cpu_add(c->counters[BCH_COUNTER_io_move], k.k->size);
322         this_cpu_add(c->counters[BCH_COUNTER_move_extent_read], k.k->size);
323         trace_move_extent_read(k.k);
324
325         atomic_add(io->read_sectors, &ctxt->read_sectors);
326         atomic_inc(&ctxt->read_ios);
327         list_add_tail(&io->list, &ctxt->reads);
328
329         /*
330          * dropped by move_read_endio() - guards against use after free of
331          * ctxt when doing wakeup
332          */
333         closure_get(&ctxt->cl);
334         bch2_read_extent(trans, &io->rbio,
335                          bkey_start_pos(k.k),
336                          btree_id, k, 0,
337                          BCH_READ_NODECODE|
338                          BCH_READ_LAST_FRAGMENT);
339         return 0;
340 err_free_pages:
341         bio_free_pages(&io->write.op.wbio.bio);
342 err_free:
343         kfree(io);
344 err:
345         bch2_write_ref_put(c, BCH_WRITE_REF_move);
346         trace_and_count(c, move_extent_alloc_mem_fail, k.k);
347         return ret;
348 }
349
350 static int lookup_inode(struct btree_trans *trans, struct bpos pos,
351                         struct bch_inode_unpacked *inode)
352 {
353         struct btree_iter iter;
354         struct bkey_s_c k;
355         int ret;
356
357         bch2_trans_iter_init(trans, &iter, BTREE_ID_inodes, pos,
358                              BTREE_ITER_ALL_SNAPSHOTS);
359         k = bch2_btree_iter_peek(&iter);
360         ret = bkey_err(k);
361         if (ret)
362                 goto err;
363
364         if (!k.k || !bkey_eq(k.k->p, pos)) {
365                 ret = -ENOENT;
366                 goto err;
367         }
368
369         ret = bkey_is_inode(k.k) ? 0 : -EIO;
370         if (ret)
371                 goto err;
372
373         ret = bch2_inode_unpack(k, inode);
374         if (ret)
375                 goto err;
376 err:
377         bch2_trans_iter_exit(trans, &iter);
378         return ret;
379 }
380
381 static int move_ratelimit(struct btree_trans *trans,
382                           struct moving_context *ctxt)
383 {
384         struct bch_fs *c = trans->c;
385         u64 delay;
386
387         if (ctxt->wait_on_copygc) {
388                 bch2_trans_unlock(trans);
389                 wait_event_killable(c->copygc_running_wq,
390                                     !c->copygc_running ||
391                                     kthread_should_stop());
392         }
393
394         do {
395                 delay = ctxt->rate ? bch2_ratelimit_delay(ctxt->rate) : 0;
396
397                 if (delay) {
398                         bch2_trans_unlock(trans);
399                         set_current_state(TASK_INTERRUPTIBLE);
400                 }
401
402                 if ((current->flags & PF_KTHREAD) && kthread_should_stop()) {
403                         __set_current_state(TASK_RUNNING);
404                         return 1;
405                 }
406
407                 if (delay)
408                         schedule_timeout(delay);
409
410                 if (unlikely(freezing(current))) {
411                         move_ctxt_wait_event(ctxt, trans, list_empty(&ctxt->reads));
412                         try_to_freeze();
413                 }
414         } while (delay);
415
416         /*
417          * XXX: these limits really ought to be per device, SSDs and hard drives
418          * will want different limits
419          */
420         move_ctxt_wait_event(ctxt, trans,
421                 atomic_read(&ctxt->write_sectors) < c->opts.move_bytes_in_flight >> 9 &&
422                 atomic_read(&ctxt->read_sectors) < c->opts.move_bytes_in_flight >> 9 &&
423                 atomic_read(&ctxt->write_ios) < c->opts.move_ios_in_flight &&
424                 atomic_read(&ctxt->read_ios) < c->opts.move_ios_in_flight);
425
426         return 0;
427 }
428
429 static int move_get_io_opts(struct btree_trans *trans,
430                             struct bch_io_opts *io_opts,
431                             struct bkey_s_c k, u64 *cur_inum)
432 {
433         struct bch_inode_unpacked inode;
434         int ret;
435
436         if (*cur_inum == k.k->p.inode)
437                 return 0;
438
439         ret = lookup_inode(trans,
440                            SPOS(0, k.k->p.inode, k.k->p.snapshot),
441                            &inode);
442         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
443                 return ret;
444
445         if (!ret)
446                 bch2_inode_opts_get(io_opts, trans->c, &inode);
447         else
448                 *io_opts = bch2_opts_to_inode_opts(trans->c->opts);
449         *cur_inum = k.k->p.inode;
450         return 0;
451 }
452
453 static int __bch2_move_data(struct moving_context *ctxt,
454                             struct bpos start,
455                             struct bpos end,
456                             move_pred_fn pred, void *arg,
457                             enum btree_id btree_id)
458 {
459         struct bch_fs *c = ctxt->c;
460         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
461         struct bkey_buf sk;
462         struct btree_trans trans;
463         struct btree_iter iter;
464         struct bkey_s_c k;
465         struct data_update_opts data_opts;
466         u64 cur_inum = U64_MAX;
467         int ret = 0, ret2;
468
469         bch2_bkey_buf_init(&sk);
470         bch2_trans_init(&trans, c, 0, 0);
471
472         ctxt->stats->data_type  = BCH_DATA_user;
473         ctxt->stats->btree_id   = btree_id;
474         ctxt->stats->pos        = start;
475
476         bch2_trans_iter_init(&trans, &iter, btree_id, start,
477                              BTREE_ITER_PREFETCH|
478                              BTREE_ITER_ALL_SNAPSHOTS);
479
480         if (ctxt->rate)
481                 bch2_ratelimit_reset(ctxt->rate);
482
483         while (!move_ratelimit(&trans, ctxt)) {
484                 bch2_trans_begin(&trans);
485
486                 k = bch2_btree_iter_peek(&iter);
487                 if (!k.k)
488                         break;
489
490                 ret = bkey_err(k);
491                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
492                         continue;
493                 if (ret)
494                         break;
495
496                 if (bkey_ge(bkey_start_pos(k.k), end))
497                         break;
498
499                 ctxt->stats->pos = iter.pos;
500
501                 if (!bkey_extent_is_direct_data(k.k))
502                         goto next_nondata;
503
504                 ret = move_get_io_opts(&trans, &io_opts, k, &cur_inum);
505                 if (ret)
506                         continue;
507
508                 memset(&data_opts, 0, sizeof(data_opts));
509                 if (!pred(c, arg, k, &io_opts, &data_opts))
510                         goto next;
511
512                 /*
513                  * The iterator gets unlocked by __bch2_read_extent - need to
514                  * save a copy of @k elsewhere:
515                  */
516                 bch2_bkey_buf_reassemble(&sk, c, k);
517                 k = bkey_i_to_s_c(sk.k);
518                 bch2_trans_unlock(&trans);
519
520                 ret2 = bch2_move_extent(&trans, &iter, ctxt, io_opts,
521                                         btree_id, k, data_opts);
522                 if (ret2) {
523                         if (bch2_err_matches(ret2, BCH_ERR_transaction_restart))
524                                 continue;
525
526                         if (ret2 == -ENOMEM) {
527                                 /* memory allocation failure, wait for some IO to finish */
528                                 bch2_move_ctxt_wait_for_io(ctxt, &trans);
529                                 continue;
530                         }
531
532                         /* XXX signal failure */
533                         goto next;
534                 }
535
536                 if (ctxt->rate)
537                         bch2_ratelimit_increment(ctxt->rate, k.k->size);
538 next:
539                 atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
540 next_nondata:
541                 bch2_btree_iter_advance(&iter);
542         }
543
544         bch2_trans_iter_exit(&trans, &iter);
545         bch2_trans_exit(&trans);
546         bch2_bkey_buf_exit(&sk, c);
547
548         return ret;
549 }
550
551 int bch2_move_data(struct bch_fs *c,
552                    enum btree_id start_btree_id, struct bpos start_pos,
553                    enum btree_id end_btree_id,   struct bpos end_pos,
554                    struct bch_ratelimit *rate,
555                    struct bch_move_stats *stats,
556                    struct write_point_specifier wp,
557                    bool wait_on_copygc,
558                    move_pred_fn pred, void *arg)
559 {
560         struct moving_context ctxt;
561         enum btree_id id;
562         int ret;
563
564         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
565
566         for (id = start_btree_id;
567              id <= min_t(unsigned, end_btree_id, BTREE_ID_NR - 1);
568              id++) {
569                 stats->btree_id = id;
570
571                 if (id != BTREE_ID_extents &&
572                     id != BTREE_ID_reflink)
573                         continue;
574
575                 ret = __bch2_move_data(&ctxt,
576                                        id == start_btree_id ? start_pos : POS_MIN,
577                                        id == end_btree_id   ? end_pos   : POS_MAX,
578                                        pred, arg, id);
579                 if (ret)
580                         break;
581         }
582
583         bch2_moving_ctxt_exit(&ctxt);
584
585         return ret;
586 }
587
588 static noinline void verify_bucket_evacuated(struct btree_trans *trans, struct bpos bucket, int gen)
589 {
590         struct bch_fs *c = trans->c;
591         struct btree_iter iter;
592         struct bkey_s_c k;
593         struct printbuf buf = PRINTBUF;
594         struct bch_backpointer bp;
595         u64 bp_offset = 0;
596         int ret;
597
598         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
599                              bucket, BTREE_ITER_CACHED);
600 again:
601         ret = lockrestart_do(trans,
602                         bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
603
604         if (!ret && k.k->type == KEY_TYPE_alloc_v4) {
605                 struct bkey_s_c_alloc_v4 a = bkey_s_c_to_alloc_v4(k);
606
607                 if (a.v->gen == gen &&
608                     a.v->dirty_sectors) {
609                         if (a.v->data_type == BCH_DATA_btree) {
610                                 bch2_trans_unlock(trans);
611                                 if (bch2_btree_interior_updates_flush(c))
612                                         goto again;
613                                 goto failed_to_evacuate;
614                         }
615                 }
616         }
617
618         bch2_trans_iter_exit(trans, &iter);
619         return;
620 failed_to_evacuate:
621         bch2_trans_iter_exit(trans, &iter);
622
623         prt_printf(&buf, bch2_log_msg(c, "failed to evacuate bucket "));
624         bch2_bkey_val_to_text(&buf, c, k);
625
626         while (1) {
627                 bch2_trans_begin(trans);
628
629                 ret = bch2_get_next_backpointer(trans, bucket, gen,
630                                                 &bp_offset, &bp,
631                                                 BTREE_ITER_CACHED);
632                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
633                         continue;
634                 if (ret)
635                         break;
636                 if (bp_offset == U64_MAX)
637                         break;
638
639                 k = bch2_backpointer_get_key(trans, &iter,
640                                              bucket, bp_offset, bp);
641                 ret = bkey_err(k);
642                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
643                         continue;
644                 if (ret)
645                         break;
646                 if (!k.k)
647                         continue;
648                 prt_newline(&buf);
649                 bch2_bkey_val_to_text(&buf, c, k);
650                 bch2_trans_iter_exit(trans, &iter);
651         }
652
653         bch2_print_string_as_lines(KERN_ERR, buf.buf);
654         printbuf_exit(&buf);
655 }
656
657 int __bch2_evacuate_bucket(struct btree_trans *trans,
658                            struct moving_context *ctxt,
659                            struct bpos bucket, int gen,
660                            struct data_update_opts _data_opts)
661 {
662         struct bch_fs *c = ctxt->c;
663         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
664         struct btree_iter iter;
665         struct bkey_buf sk;
666         struct bch_backpointer bp;
667         struct bch_alloc_v4 a_convert;
668         const struct bch_alloc_v4 *a;
669         struct bkey_s_c k;
670         struct data_update_opts data_opts;
671         unsigned dirty_sectors, bucket_size;
672         u64 fragmentation;
673         u64 bp_offset = 0, cur_inum = U64_MAX;
674         int ret = 0;
675
676         bch2_bkey_buf_init(&sk);
677
678         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
679                              bucket, BTREE_ITER_CACHED);
680         ret = lockrestart_do(trans,
681                         bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
682         bch2_trans_iter_exit(trans, &iter);
683
684         if (ret) {
685                 bch_err(c, "%s: error looking up alloc key: %s", __func__, bch2_err_str(ret));
686                 goto err;
687         }
688
689         a = bch2_alloc_to_v4(k, &a_convert);
690         dirty_sectors = a->dirty_sectors;
691         bucket_size = bch_dev_bkey_exists(c, bucket.inode)->mi.bucket_size;
692         fragmentation = a->fragmentation_lru;
693
694         ret = bch2_btree_write_buffer_flush(trans);
695         if (ret) {
696                 bch_err(c, "%s: error flushing btree write buffer: %s", __func__, bch2_err_str(ret));
697                 goto err;
698         }
699
700         while (!(ret = move_ratelimit(trans, ctxt))) {
701                 bch2_trans_begin(trans);
702
703                 ret = bch2_get_next_backpointer(trans, bucket, gen,
704                                                 &bp_offset, &bp,
705                                                 BTREE_ITER_CACHED);
706                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
707                         continue;
708                 if (ret)
709                         goto err;
710                 if (bp_offset == U64_MAX)
711                         break;
712
713                 if (!bp.level) {
714                         const struct bch_extent_ptr *ptr;
715                         struct bkey_s_c k;
716                         unsigned i = 0;
717
718                         k = bch2_backpointer_get_key(trans, &iter,
719                                                 bucket, bp_offset, bp);
720                         ret = bkey_err(k);
721                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
722                                 continue;
723                         if (ret)
724                                 goto err;
725                         if (!k.k)
726                                 goto next;
727
728                         bch2_bkey_buf_reassemble(&sk, c, k);
729                         k = bkey_i_to_s_c(sk.k);
730
731                         ret = move_get_io_opts(trans, &io_opts, k, &cur_inum);
732                         if (ret) {
733                                 bch2_trans_iter_exit(trans, &iter);
734                                 continue;
735                         }
736
737                         data_opts = _data_opts;
738                         data_opts.target        = io_opts.background_target;
739                         data_opts.rewrite_ptrs = 0;
740
741                         bkey_for_each_ptr(bch2_bkey_ptrs_c(k), ptr) {
742                                 if (ptr->dev == bucket.inode)
743                                         data_opts.rewrite_ptrs |= 1U << i;
744                                 i++;
745                         }
746
747                         ret = bch2_move_extent(trans, &iter, ctxt, io_opts,
748                                                bp.btree_id, k, data_opts);
749                         bch2_trans_iter_exit(trans, &iter);
750
751                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
752                                 continue;
753                         if (ret == -ENOMEM) {
754                                 /* memory allocation failure, wait for some IO to finish */
755                                 bch2_move_ctxt_wait_for_io(ctxt, trans);
756                                 continue;
757                         }
758                         if (ret)
759                                 goto err;
760
761                         if (ctxt->rate)
762                                 bch2_ratelimit_increment(ctxt->rate, k.k->size);
763                         atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
764                 } else {
765                         struct btree *b;
766
767                         b = bch2_backpointer_get_node(trans, &iter,
768                                                 bucket, bp_offset, bp);
769                         ret = PTR_ERR_OR_ZERO(b);
770                         if (ret == -BCH_ERR_backpointer_to_overwritten_btree_node)
771                                 continue;
772                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
773                                 continue;
774                         if (ret)
775                                 goto err;
776                         if (!b)
777                                 goto next;
778
779                         ret = bch2_btree_node_rewrite(trans, &iter, b, 0);
780                         bch2_trans_iter_exit(trans, &iter);
781
782                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
783                                 continue;
784                         if (ret)
785                                 goto err;
786
787                         if (ctxt->rate)
788                                 bch2_ratelimit_increment(ctxt->rate,
789                                                          c->opts.btree_node_size >> 9);
790                         atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_seen);
791                         atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_moved);
792                 }
793 next:
794                 bp_offset++;
795         }
796
797         trace_evacuate_bucket(c, &bucket, dirty_sectors, bucket_size, fragmentation, ret);
798
799         if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) && gen >= 0) {
800                 bch2_trans_unlock(trans);
801                 move_ctxt_wait_event(ctxt, NULL, list_empty(&ctxt->reads));
802                 closure_sync(&ctxt->cl);
803                 if (!ctxt->write_error)
804                         verify_bucket_evacuated(trans, bucket, gen);
805         }
806 err:
807         bch2_bkey_buf_exit(&sk, c);
808         return ret;
809 }
810
811 int bch2_evacuate_bucket(struct bch_fs *c,
812                          struct bpos bucket, int gen,
813                          struct data_update_opts data_opts,
814                          struct bch_ratelimit *rate,
815                          struct bch_move_stats *stats,
816                          struct write_point_specifier wp,
817                          bool wait_on_copygc)
818 {
819         struct btree_trans trans;
820         struct moving_context ctxt;
821         int ret;
822
823         bch2_trans_init(&trans, c, 0, 0);
824         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
825         ret = __bch2_evacuate_bucket(&trans, &ctxt, bucket, gen, data_opts);
826         bch2_moving_ctxt_exit(&ctxt);
827         bch2_trans_exit(&trans);
828
829         return ret;
830 }
831
832 typedef bool (*move_btree_pred)(struct bch_fs *, void *,
833                                 struct btree *, struct bch_io_opts *,
834                                 struct data_update_opts *);
835
836 static int bch2_move_btree(struct bch_fs *c,
837                            enum btree_id start_btree_id, struct bpos start_pos,
838                            enum btree_id end_btree_id,   struct bpos end_pos,
839                            move_btree_pred pred, void *arg,
840                            struct bch_move_stats *stats)
841 {
842         bool kthread = (current->flags & PF_KTHREAD) != 0;
843         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
844         struct btree_trans trans;
845         struct btree_iter iter;
846         struct btree *b;
847         enum btree_id id;
848         struct data_update_opts data_opts;
849         int ret = 0;
850
851         bch2_trans_init(&trans, c, 0, 0);
852         progress_list_add(c, stats);
853
854         stats->data_type = BCH_DATA_btree;
855
856         for (id = start_btree_id;
857              id <= min_t(unsigned, end_btree_id, BTREE_ID_NR - 1);
858              id++) {
859                 stats->btree_id = id;
860
861                 bch2_trans_node_iter_init(&trans, &iter, id, POS_MIN, 0, 0,
862                                           BTREE_ITER_PREFETCH);
863 retry:
864                 ret = 0;
865                 while (bch2_trans_begin(&trans),
866                        (b = bch2_btree_iter_peek_node(&iter)) &&
867                        !(ret = PTR_ERR_OR_ZERO(b))) {
868                         if (kthread && kthread_should_stop())
869                                 break;
870
871                         if ((cmp_int(id, end_btree_id) ?:
872                              bpos_cmp(b->key.k.p, end_pos)) > 0)
873                                 break;
874
875                         stats->pos = iter.pos;
876
877                         if (!pred(c, arg, b, &io_opts, &data_opts))
878                                 goto next;
879
880                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0) ?: ret;
881                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
882                                 continue;
883                         if (ret)
884                                 break;
885 next:
886                         bch2_btree_iter_next_node(&iter);
887                 }
888                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
889                         goto retry;
890
891                 bch2_trans_iter_exit(&trans, &iter);
892
893                 if (kthread && kthread_should_stop())
894                         break;
895         }
896
897         bch2_trans_exit(&trans);
898
899         if (ret)
900                 bch_err(c, "error in %s(): %s", __func__, bch2_err_str(ret));
901
902         bch2_btree_interior_updates_flush(c);
903
904         progress_list_del(c, stats);
905         return ret;
906 }
907
908 static bool rereplicate_pred(struct bch_fs *c, void *arg,
909                              struct bkey_s_c k,
910                              struct bch_io_opts *io_opts,
911                              struct data_update_opts *data_opts)
912 {
913         unsigned nr_good = bch2_bkey_durability(c, k);
914         unsigned replicas = bkey_is_btree_ptr(k.k)
915                 ? c->opts.metadata_replicas
916                 : io_opts->data_replicas;
917
918         if (!nr_good || nr_good >= replicas)
919                 return false;
920
921         data_opts->target               = 0;
922         data_opts->extra_replicas       = replicas - nr_good;
923         data_opts->btree_insert_flags   = 0;
924         return true;
925 }
926
927 static bool migrate_pred(struct bch_fs *c, void *arg,
928                          struct bkey_s_c k,
929                          struct bch_io_opts *io_opts,
930                          struct data_update_opts *data_opts)
931 {
932         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
933         const struct bch_extent_ptr *ptr;
934         struct bch_ioctl_data *op = arg;
935         unsigned i = 0;
936
937         data_opts->rewrite_ptrs         = 0;
938         data_opts->target               = 0;
939         data_opts->extra_replicas       = 0;
940         data_opts->btree_insert_flags   = 0;
941
942         bkey_for_each_ptr(ptrs, ptr) {
943                 if (ptr->dev == op->migrate.dev)
944                         data_opts->rewrite_ptrs |= 1U << i;
945                 i++;
946         }
947
948         return data_opts->rewrite_ptrs != 0;
949 }
950
951 static bool rereplicate_btree_pred(struct bch_fs *c, void *arg,
952                                    struct btree *b,
953                                    struct bch_io_opts *io_opts,
954                                    struct data_update_opts *data_opts)
955 {
956         return rereplicate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
957 }
958
959 static bool migrate_btree_pred(struct bch_fs *c, void *arg,
960                                struct btree *b,
961                                struct bch_io_opts *io_opts,
962                                struct data_update_opts *data_opts)
963 {
964         return migrate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
965 }
966
967 static bool bformat_needs_redo(struct bkey_format *f)
968 {
969         unsigned i;
970
971         for (i = 0; i < f->nr_fields; i++) {
972                 unsigned unpacked_bits = bch2_bkey_format_current.bits_per_field[i];
973                 u64 unpacked_mask = ~((~0ULL << 1) << (unpacked_bits - 1));
974                 u64 field_offset = le64_to_cpu(f->field_offset[i]);
975
976                 if (f->bits_per_field[i] > unpacked_bits)
977                         return true;
978
979                 if ((f->bits_per_field[i] == unpacked_bits) && field_offset)
980                         return true;
981
982                 if (((field_offset + ((1ULL << f->bits_per_field[i]) - 1)) &
983                      unpacked_mask) <
984                     field_offset)
985                         return true;
986         }
987
988         return false;
989 }
990
991 static bool rewrite_old_nodes_pred(struct bch_fs *c, void *arg,
992                                    struct btree *b,
993                                    struct bch_io_opts *io_opts,
994                                    struct data_update_opts *data_opts)
995 {
996         if (b->version_ondisk != c->sb.version ||
997             btree_node_need_rewrite(b) ||
998             bformat_needs_redo(&b->format)) {
999                 data_opts->target               = 0;
1000                 data_opts->extra_replicas       = 0;
1001                 data_opts->btree_insert_flags   = 0;
1002                 return true;
1003         }
1004
1005         return false;
1006 }
1007
1008 int bch2_scan_old_btree_nodes(struct bch_fs *c, struct bch_move_stats *stats)
1009 {
1010         int ret;
1011
1012         ret = bch2_move_btree(c,
1013                               0,                POS_MIN,
1014                               BTREE_ID_NR,      SPOS_MAX,
1015                               rewrite_old_nodes_pred, c, stats);
1016         if (!ret) {
1017                 mutex_lock(&c->sb_lock);
1018                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
1019                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
1020                 c->disk_sb.sb->version_min = c->disk_sb.sb->version;
1021                 bch2_write_super(c);
1022                 mutex_unlock(&c->sb_lock);
1023         }
1024
1025         return ret;
1026 }
1027
1028 int bch2_data_job(struct bch_fs *c,
1029                   struct bch_move_stats *stats,
1030                   struct bch_ioctl_data op)
1031 {
1032         int ret = 0;
1033
1034         switch (op.op) {
1035         case BCH_DATA_OP_REREPLICATE:
1036                 bch2_move_stats_init(stats, "rereplicate");
1037                 stats->data_type = BCH_DATA_journal;
1038                 ret = bch2_journal_flush_device_pins(&c->journal, -1);
1039
1040                 ret = bch2_move_btree(c,
1041                                       op.start_btree,   op.start_pos,
1042                                       op.end_btree,     op.end_pos,
1043                                       rereplicate_btree_pred, c, stats) ?: ret;
1044                 ret = bch2_replicas_gc2(c) ?: ret;
1045
1046                 ret = bch2_move_data(c,
1047                                      op.start_btree,    op.start_pos,
1048                                      op.end_btree,      op.end_pos,
1049                                      NULL,
1050                                      stats,
1051                                      writepoint_hashed((unsigned long) current),
1052                                      true,
1053                                      rereplicate_pred, c) ?: ret;
1054                 ret = bch2_replicas_gc2(c) ?: ret;
1055                 break;
1056         case BCH_DATA_OP_MIGRATE:
1057                 if (op.migrate.dev >= c->sb.nr_devices)
1058                         return -EINVAL;
1059
1060                 bch2_move_stats_init(stats, "migrate");
1061                 stats->data_type = BCH_DATA_journal;
1062                 ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
1063
1064                 ret = bch2_move_btree(c,
1065                                       op.start_btree,   op.start_pos,
1066                                       op.end_btree,     op.end_pos,
1067                                       migrate_btree_pred, &op, stats) ?: ret;
1068                 ret = bch2_replicas_gc2(c) ?: ret;
1069
1070                 ret = bch2_move_data(c,
1071                                      op.start_btree,    op.start_pos,
1072                                      op.end_btree,      op.end_pos,
1073                                      NULL,
1074                                      stats,
1075                                      writepoint_hashed((unsigned long) current),
1076                                      true,
1077                                      migrate_pred, &op) ?: ret;
1078                 ret = bch2_replicas_gc2(c) ?: ret;
1079                 break;
1080         case BCH_DATA_OP_REWRITE_OLD_NODES:
1081                 bch2_move_stats_init(stats, "rewrite_old_nodes");
1082                 ret = bch2_scan_old_btree_nodes(c, stats);
1083                 break;
1084         default:
1085                 ret = -EINVAL;
1086         }
1087
1088         return ret;
1089 }