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