]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/move.c
New upstream release
[bcachefs-tools-debian] / libbcachefs / move.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "alloc_foreground.h"
5 #include "backpointers.h"
6 #include "bkey_buf.h"
7 #include "btree_gc.h"
8 #include "btree_update.h"
9 #include "btree_update_interior.h"
10 #include "disk_groups.h"
11 #include "ec.h"
12 #include "errcode.h"
13 #include "error.h"
14 #include "inode.h"
15 #include "io.h"
16 #include "journal_reclaim.h"
17 #include "move.h"
18 #include "replicas.h"
19 #include "super-io.h"
20 #include "keylist.h"
21
22 #include <linux/ioprio.h>
23 #include <linux/kthread.h>
24
25 #include <trace/events/bcachefs.h>
26
27 static void progress_list_add(struct bch_fs *c, struct bch_move_stats *stats)
28 {
29         mutex_lock(&c->data_progress_lock);
30         list_add(&stats->list, &c->data_progress_list);
31         mutex_unlock(&c->data_progress_lock);
32 }
33
34 static void progress_list_del(struct bch_fs *c, struct bch_move_stats *stats)
35 {
36         mutex_lock(&c->data_progress_lock);
37         list_del(&stats->list);
38         mutex_unlock(&c->data_progress_lock);
39 }
40
41 struct moving_io {
42         struct list_head        list;
43         struct closure          cl;
44         bool                    read_completed;
45
46         unsigned                read_sectors;
47         unsigned                write_sectors;
48
49         struct bch_read_bio     rbio;
50
51         struct data_update      write;
52         /* Must be last since it is variable size */
53         struct bio_vec          bi_inline_vecs[0];
54 };
55
56 static void move_free(struct moving_io *io)
57 {
58         struct moving_context *ctxt = io->write.ctxt;
59         struct bch_fs *c = ctxt->c;
60
61         bch2_data_update_exit(&io->write);
62         wake_up(&ctxt->wait);
63         percpu_ref_put(&c->writes);
64         kfree(io);
65 }
66
67 static void move_write_done(struct bch_write_op *op)
68 {
69         struct moving_io *io = container_of(op, struct moving_io, write.op);
70         struct moving_context *ctxt = io->write.ctxt;
71
72         if (io->write.op.error)
73                 ctxt->write_error = true;
74
75         atomic_sub(io->write_sectors, &io->write.ctxt->write_sectors);
76         move_free(io);
77         closure_put(&ctxt->cl);
78 }
79
80 static void move_write(struct moving_io *io)
81 {
82         if (unlikely(io->rbio.bio.bi_status || io->rbio.hole)) {
83                 move_free(io);
84                 return;
85         }
86
87         closure_get(&io->write.ctxt->cl);
88         atomic_add(io->write_sectors, &io->write.ctxt->write_sectors);
89
90         bch2_data_update_read_done(&io->write, io->rbio.pick.crc);
91 }
92
93 static inline struct moving_io *next_pending_write(struct moving_context *ctxt)
94 {
95         struct moving_io *io =
96                 list_first_entry_or_null(&ctxt->reads, struct moving_io, list);
97
98         return io && io->read_completed ? io : NULL;
99 }
100
101 static void move_read_endio(struct bio *bio)
102 {
103         struct moving_io *io = container_of(bio, struct moving_io, rbio.bio);
104         struct moving_context *ctxt = io->write.ctxt;
105
106         atomic_sub(io->read_sectors, &ctxt->read_sectors);
107         io->read_completed = true;
108
109         wake_up(&ctxt->wait);
110         closure_put(&ctxt->cl);
111 }
112
113 static void do_pending_writes(struct moving_context *ctxt, struct btree_trans *trans)
114 {
115         struct moving_io *io;
116
117         if (trans)
118                 bch2_trans_unlock(trans);
119
120         while ((io = next_pending_write(ctxt))) {
121                 list_del(&io->list);
122                 move_write(io);
123         }
124 }
125
126 #define move_ctxt_wait_event(_ctxt, _trans, _cond)              \
127 do {                                                            \
128         do_pending_writes(_ctxt, _trans);                       \
129                                                                 \
130         if (_cond)                                              \
131                 break;                                          \
132         __wait_event((_ctxt)->wait,                             \
133                      next_pending_write(_ctxt) || (_cond));     \
134 } while (1)
135
136 static void bch2_move_ctxt_wait_for_io(struct moving_context *ctxt,
137                                        struct btree_trans *trans)
138 {
139         unsigned sectors_pending = atomic_read(&ctxt->write_sectors);
140
141         move_ctxt_wait_event(ctxt, trans,
142                 !atomic_read(&ctxt->write_sectors) ||
143                 atomic_read(&ctxt->write_sectors) != sectors_pending);
144 }
145
146 void bch2_moving_ctxt_exit(struct moving_context *ctxt)
147 {
148         move_ctxt_wait_event(ctxt, NULL, list_empty(&ctxt->reads));
149         closure_sync(&ctxt->cl);
150         EBUG_ON(atomic_read(&ctxt->write_sectors));
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_trans_kmalloc(trans, bkey_bytes(k.k));
202         ret = PTR_ERR_OR_ZERO(n);
203         if (ret)
204                 return ret;
205
206         bkey_reassemble(n, k);
207
208         while (data_opts.kill_ptrs) {
209                 unsigned i = 0, drop = __fls(data_opts.kill_ptrs);
210                 struct bch_extent_ptr *ptr;
211
212                 bch2_bkey_drop_ptrs(bkey_i_to_s(n), ptr, i++ == drop);
213                 data_opts.kill_ptrs ^= 1U << drop;
214         }
215
216         /*
217          * If the new extent no longer has any pointers, bch2_extent_normalize()
218          * will do the appropriate thing with it (turning it into a
219          * KEY_TYPE_error key, or just a discard if it was a cached extent)
220          */
221         bch2_extent_normalize(c, bkey_i_to_s(n));
222
223         /*
224          * Since we're not inserting through an extent iterator
225          * (BTREE_ITER_ALL_SNAPSHOTS iterators aren't extent iterators),
226          * we aren't using the extent overwrite path to delete, we're
227          * just using the normal key deletion path:
228          */
229         if (bkey_deleted(&n->k))
230                 n->k.size = 0;
231
232         return bch2_trans_update(trans, iter, n, BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE) ?:
233                 bch2_trans_commit(trans, NULL, NULL, BTREE_INSERT_NOFAIL);
234 }
235
236 static int bch2_move_extent(struct btree_trans *trans,
237                             struct btree_iter *iter,
238                             struct moving_context *ctxt,
239                             struct bch_io_opts io_opts,
240                             enum btree_id btree_id,
241                             struct bkey_s_c k,
242                             struct data_update_opts data_opts)
243 {
244         struct bch_fs *c = trans->c;
245         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
246         struct moving_io *io;
247         const union bch_extent_entry *entry;
248         struct extent_ptr_decoded p;
249         unsigned sectors = k.k->size, pages;
250         int ret = -ENOMEM;
251
252         bch2_data_update_opts_normalize(k, &data_opts);
253
254         if (!data_opts.rewrite_ptrs &&
255             !data_opts.extra_replicas) {
256                 if (data_opts.kill_ptrs)
257                         return bch2_extent_drop_ptrs(trans, iter, k, data_opts);
258                 return 0;
259         }
260
261         if (!percpu_ref_tryget_live(&c->writes))
262                 return -EROFS;
263
264         /*
265          * Before memory allocations & taking nocow locks in
266          * bch2_data_update_init():
267          */
268         bch2_trans_unlock(trans);
269
270         /* write path might have to decompress data: */
271         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
272                 sectors = max_t(unsigned, sectors, p.crc.uncompressed_size);
273
274         pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
275         io = kzalloc(sizeof(struct moving_io) +
276                      sizeof(struct bio_vec) * pages, GFP_KERNEL);
277         if (!io)
278                 goto err;
279
280         io->write.ctxt          = ctxt;
281         io->read_sectors        = k.k->size;
282         io->write_sectors       = k.k->size;
283
284         bio_init(&io->write.op.wbio.bio, NULL, io->bi_inline_vecs, pages, 0);
285         bio_set_prio(&io->write.op.wbio.bio,
286                      IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
287
288         if (bch2_bio_alloc_pages(&io->write.op.wbio.bio, sectors << 9,
289                                  GFP_KERNEL))
290                 goto err_free;
291
292         io->rbio.c              = c;
293         io->rbio.opts           = io_opts;
294         bio_init(&io->rbio.bio, NULL, io->bi_inline_vecs, pages, 0);
295         io->rbio.bio.bi_vcnt = pages;
296         bio_set_prio(&io->rbio.bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
297         io->rbio.bio.bi_iter.bi_size = sectors << 9;
298
299         bio_set_op_attrs(&io->rbio.bio, REQ_OP_READ, 0);
300         io->rbio.bio.bi_iter.bi_sector  = bkey_start_offset(k.k);
301         io->rbio.bio.bi_end_io          = move_read_endio;
302
303         ret = bch2_data_update_init(c, &io->write, ctxt->wp, io_opts,
304                                     data_opts, btree_id, k);
305         if (ret && ret != -BCH_ERR_unwritten_extent_update)
306                 goto err_free_pages;
307
308         io->write.ctxt = ctxt;
309         io->write.op.end_io = move_write_done;
310
311         atomic64_inc(&ctxt->stats->keys_moved);
312         atomic64_add(k.k->size, &ctxt->stats->sectors_moved);
313
314         if (ret == -BCH_ERR_unwritten_extent_update) {
315                 bch2_update_unwritten_extent(trans, &io->write);
316                 move_free(io);
317                 return 0;
318         }
319
320         BUG_ON(ret);
321
322         this_cpu_add(c->counters[BCH_COUNTER_io_move], k.k->size);
323         this_cpu_add(c->counters[BCH_COUNTER_move_extent_read], k.k->size);
324         trace_move_extent_read(k.k);
325
326         atomic_add(io->read_sectors, &ctxt->read_sectors);
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         percpu_ref_put(&c->writes);
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_cmp(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         move_ctxt_wait_event(ctxt, trans,
417                 atomic_read(&ctxt->write_sectors) <
418                 c->opts.move_bytes_in_flight >> 9);
419
420         move_ctxt_wait_event(ctxt, trans,
421                 atomic_read(&ctxt->read_sectors) <
422                 c->opts.move_bytes_in_flight >> 9);
423
424         return 0;
425 }
426
427 static int move_get_io_opts(struct btree_trans *trans,
428                             struct bch_io_opts *io_opts,
429                             struct bkey_s_c k, u64 *cur_inum)
430 {
431         struct bch_inode_unpacked inode;
432         int ret;
433
434         if (*cur_inum == k.k->p.inode)
435                 return 0;
436
437         *io_opts = bch2_opts_to_inode_opts(trans->c->opts);
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_io_opts_apply(io_opts, bch2_inode_opts_get(&inode));
447
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_cmp(bkey_start_pos(k.k), end) >= 0)
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 int 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         k = bch2_btree_iter_peek_slot(&iter);
601         ret = bkey_err(k);
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 ret;
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         return 0;
655 }
656
657 int __bch2_evacuate_bucket(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_trans trans;
664         struct btree_iter iter;
665         struct bkey_buf sk;
666         struct bch_backpointer bp;
667         struct data_update_opts data_opts;
668         u64 bp_offset = 0, cur_inum = U64_MAX;
669         int ret = 0;
670
671         bch2_bkey_buf_init(&sk);
672         bch2_trans_init(&trans, c, 0, 0);
673
674         while (!(ret = move_ratelimit(&trans, ctxt))) {
675                 bch2_trans_begin(&trans);
676
677                 ret = bch2_get_next_backpointer(&trans, bucket, gen,
678                                                 &bp_offset, &bp,
679                                                 BTREE_ITER_CACHED);
680                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
681                         continue;
682                 if (ret)
683                         goto err;
684                 if (bp_offset == U64_MAX)
685                         break;
686
687                 if (!bp.level) {
688                         const struct bch_extent_ptr *ptr;
689                         struct bkey_s_c k;
690                         unsigned i = 0;
691
692                         k = bch2_backpointer_get_key(&trans, &iter,
693                                                 bucket, bp_offset, bp);
694                         ret = bkey_err(k);
695                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
696                                 continue;
697                         if (ret)
698                                 goto err;
699                         if (!k.k)
700                                 continue;
701
702                         bch2_bkey_buf_reassemble(&sk, c, k);
703                         k = bkey_i_to_s_c(sk.k);
704
705                         ret = move_get_io_opts(&trans, &io_opts, k, &cur_inum);
706                         if (ret) {
707                                 bch2_trans_iter_exit(&trans, &iter);
708                                 continue;
709                         }
710
711                         data_opts = _data_opts;
712                         data_opts.target        = io_opts.background_target;
713                         data_opts.rewrite_ptrs = 0;
714
715                         bkey_for_each_ptr(bch2_bkey_ptrs_c(k), ptr) {
716                                 if (ptr->dev == bucket.inode)
717                                         data_opts.rewrite_ptrs |= 1U << i;
718                                 i++;
719                         }
720
721                         ret = bch2_move_extent(&trans, &iter, ctxt, io_opts,
722                                                bp.btree_id, k, data_opts);
723                         bch2_trans_iter_exit(&trans, &iter);
724
725                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
726                                 continue;
727                         if (ret == -ENOMEM) {
728                                 /* memory allocation failure, wait for some IO to finish */
729                                 bch2_move_ctxt_wait_for_io(ctxt, &trans);
730                                 continue;
731                         }
732                         if (ret)
733                                 goto err;
734
735                         if (ctxt->rate)
736                                 bch2_ratelimit_increment(ctxt->rate, k.k->size);
737                         atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
738                 } else {
739                         struct btree *b;
740
741                         b = bch2_backpointer_get_node(&trans, &iter,
742                                                 bucket, bp_offset, bp);
743                         ret = PTR_ERR_OR_ZERO(b);
744                         if (ret == -BCH_ERR_backpointer_to_overwritten_btree_node)
745                                 continue;
746                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
747                                 continue;
748                         if (ret)
749                                 goto err;
750                         if (!b)
751                                 continue;
752
753                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0);
754                         bch2_trans_iter_exit(&trans, &iter);
755
756                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
757                                 continue;
758                         if (ret)
759                                 goto err;
760
761                         if (ctxt->rate)
762                                 bch2_ratelimit_increment(ctxt->rate,
763                                                          c->opts.btree_node_size >> 9);
764                         atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_seen);
765                         atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_moved);
766                 }
767
768                 bp_offset++;
769         }
770
771         if (IS_ENABLED(CONFIG_BCACHEFS_DEBUG) && gen >= 0) {
772                 bch2_trans_unlock(&trans);
773                 move_ctxt_wait_event(ctxt, NULL, list_empty(&ctxt->reads));
774                 closure_sync(&ctxt->cl);
775                 if (!ctxt->write_error)
776                         lockrestart_do(&trans, verify_bucket_evacuated(&trans, bucket, gen));
777         }
778 err:
779         bch2_trans_exit(&trans);
780         bch2_bkey_buf_exit(&sk, c);
781         return ret;
782 }
783
784 int bch2_evacuate_bucket(struct bch_fs *c,
785                          struct bpos bucket, int gen,
786                          struct data_update_opts data_opts,
787                          struct bch_ratelimit *rate,
788                          struct bch_move_stats *stats,
789                          struct write_point_specifier wp,
790                          bool wait_on_copygc)
791 {
792         struct moving_context ctxt;
793         int ret;
794
795         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
796         ret = __bch2_evacuate_bucket(&ctxt, bucket, gen, data_opts);
797         bch2_moving_ctxt_exit(&ctxt);
798
799         return ret;
800 }
801
802 typedef bool (*move_btree_pred)(struct bch_fs *, void *,
803                                 struct btree *, struct bch_io_opts *,
804                                 struct data_update_opts *);
805
806 static int bch2_move_btree(struct bch_fs *c,
807                            enum btree_id start_btree_id, struct bpos start_pos,
808                            enum btree_id end_btree_id,   struct bpos end_pos,
809                            move_btree_pred pred, void *arg,
810                            struct bch_move_stats *stats)
811 {
812         bool kthread = (current->flags & PF_KTHREAD) != 0;
813         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
814         struct btree_trans trans;
815         struct btree_iter iter;
816         struct btree *b;
817         enum btree_id id;
818         struct data_update_opts data_opts;
819         int ret = 0;
820
821         bch2_trans_init(&trans, c, 0, 0);
822         progress_list_add(c, stats);
823
824         stats->data_type = BCH_DATA_btree;
825
826         for (id = start_btree_id;
827              id <= min_t(unsigned, end_btree_id, BTREE_ID_NR - 1);
828              id++) {
829                 stats->btree_id = id;
830
831                 bch2_trans_node_iter_init(&trans, &iter, id, POS_MIN, 0, 0,
832                                           BTREE_ITER_PREFETCH);
833 retry:
834                 ret = 0;
835                 while (bch2_trans_begin(&trans),
836                        (b = bch2_btree_iter_peek_node(&iter)) &&
837                        !(ret = PTR_ERR_OR_ZERO(b))) {
838                         if (kthread && kthread_should_stop())
839                                 break;
840
841                         if ((cmp_int(id, end_btree_id) ?:
842                              bpos_cmp(b->key.k.p, end_pos)) > 0)
843                                 break;
844
845                         stats->pos = iter.pos;
846
847                         if (!pred(c, arg, b, &io_opts, &data_opts))
848                                 goto next;
849
850                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0) ?: ret;
851                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
852                                 continue;
853                         if (ret)
854                                 break;
855 next:
856                         bch2_btree_iter_next_node(&iter);
857                 }
858                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
859                         goto retry;
860
861                 bch2_trans_iter_exit(&trans, &iter);
862
863                 if (kthread && kthread_should_stop())
864                         break;
865         }
866
867         bch2_trans_exit(&trans);
868
869         if (ret)
870                 bch_err(c, "error in %s(): %s", __func__, bch2_err_str(ret));
871
872         bch2_btree_interior_updates_flush(c);
873
874         progress_list_del(c, stats);
875         return ret;
876 }
877
878 static bool rereplicate_pred(struct bch_fs *c, void *arg,
879                              struct bkey_s_c k,
880                              struct bch_io_opts *io_opts,
881                              struct data_update_opts *data_opts)
882 {
883         unsigned nr_good = bch2_bkey_durability(c, k);
884         unsigned replicas = bkey_is_btree_ptr(k.k)
885                 ? c->opts.metadata_replicas
886                 : io_opts->data_replicas;
887
888         if (!nr_good || nr_good >= replicas)
889                 return false;
890
891         data_opts->target               = 0;
892         data_opts->extra_replicas       = replicas - nr_good;
893         data_opts->btree_insert_flags   = 0;
894         return true;
895 }
896
897 static bool migrate_pred(struct bch_fs *c, void *arg,
898                          struct bkey_s_c k,
899                          struct bch_io_opts *io_opts,
900                          struct data_update_opts *data_opts)
901 {
902         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
903         const struct bch_extent_ptr *ptr;
904         struct bch_ioctl_data *op = arg;
905         unsigned i = 0;
906
907         data_opts->rewrite_ptrs         = 0;
908         data_opts->target               = 0;
909         data_opts->extra_replicas       = 0;
910         data_opts->btree_insert_flags   = 0;
911
912         bkey_for_each_ptr(ptrs, ptr) {
913                 if (ptr->dev == op->migrate.dev)
914                         data_opts->rewrite_ptrs |= 1U << i;
915                 i++;
916         }
917
918         return data_opts->rewrite_ptrs != 0;
919 }
920
921 static bool rereplicate_btree_pred(struct bch_fs *c, void *arg,
922                                    struct btree *b,
923                                    struct bch_io_opts *io_opts,
924                                    struct data_update_opts *data_opts)
925 {
926         return rereplicate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
927 }
928
929 static bool migrate_btree_pred(struct bch_fs *c, void *arg,
930                                struct btree *b,
931                                struct bch_io_opts *io_opts,
932                                struct data_update_opts *data_opts)
933 {
934         return migrate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
935 }
936
937 static bool bformat_needs_redo(struct bkey_format *f)
938 {
939         unsigned i;
940
941         for (i = 0; i < f->nr_fields; i++) {
942                 unsigned unpacked_bits = bch2_bkey_format_current.bits_per_field[i];
943                 u64 unpacked_mask = ~((~0ULL << 1) << (unpacked_bits - 1));
944                 u64 field_offset = le64_to_cpu(f->field_offset[i]);
945
946                 if (f->bits_per_field[i] > unpacked_bits)
947                         return true;
948
949                 if ((f->bits_per_field[i] == unpacked_bits) && field_offset)
950                         return true;
951
952                 if (((field_offset + ((1ULL << f->bits_per_field[i]) - 1)) &
953                      unpacked_mask) <
954                     field_offset)
955                         return true;
956         }
957
958         return false;
959 }
960
961 static bool rewrite_old_nodes_pred(struct bch_fs *c, void *arg,
962                                    struct btree *b,
963                                    struct bch_io_opts *io_opts,
964                                    struct data_update_opts *data_opts)
965 {
966         if (b->version_ondisk != c->sb.version ||
967             btree_node_need_rewrite(b) ||
968             bformat_needs_redo(&b->format)) {
969                 data_opts->target               = 0;
970                 data_opts->extra_replicas       = 0;
971                 data_opts->btree_insert_flags   = 0;
972                 return true;
973         }
974
975         return false;
976 }
977
978 int bch2_scan_old_btree_nodes(struct bch_fs *c, struct bch_move_stats *stats)
979 {
980         int ret;
981
982         ret = bch2_move_btree(c,
983                               0,                POS_MIN,
984                               BTREE_ID_NR,      SPOS_MAX,
985                               rewrite_old_nodes_pred, c, stats);
986         if (!ret) {
987                 mutex_lock(&c->sb_lock);
988                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
989                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
990                 c->disk_sb.sb->version_min = c->disk_sb.sb->version;
991                 bch2_write_super(c);
992                 mutex_unlock(&c->sb_lock);
993         }
994
995         return ret;
996 }
997
998 int bch2_data_job(struct bch_fs *c,
999                   struct bch_move_stats *stats,
1000                   struct bch_ioctl_data op)
1001 {
1002         int ret = 0;
1003
1004         switch (op.op) {
1005         case BCH_DATA_OP_REREPLICATE:
1006                 bch2_move_stats_init(stats, "rereplicate");
1007                 stats->data_type = BCH_DATA_journal;
1008                 ret = bch2_journal_flush_device_pins(&c->journal, -1);
1009
1010                 ret = bch2_move_btree(c,
1011                                       op.start_btree,   op.start_pos,
1012                                       op.end_btree,     op.end_pos,
1013                                       rereplicate_btree_pred, c, stats) ?: ret;
1014                 ret = bch2_replicas_gc2(c) ?: ret;
1015
1016                 ret = bch2_move_data(c,
1017                                      op.start_btree,    op.start_pos,
1018                                      op.end_btree,      op.end_pos,
1019                                      NULL,
1020                                      stats,
1021                                      writepoint_hashed((unsigned long) current),
1022                                      true,
1023                                      rereplicate_pred, c) ?: ret;
1024                 ret = bch2_replicas_gc2(c) ?: ret;
1025                 break;
1026         case BCH_DATA_OP_MIGRATE:
1027                 if (op.migrate.dev >= c->sb.nr_devices)
1028                         return -EINVAL;
1029
1030                 bch2_move_stats_init(stats, "migrate");
1031                 stats->data_type = BCH_DATA_journal;
1032                 ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
1033
1034                 ret = bch2_move_btree(c,
1035                                       op.start_btree,   op.start_pos,
1036                                       op.end_btree,     op.end_pos,
1037                                       migrate_btree_pred, &op, stats) ?: ret;
1038                 ret = bch2_replicas_gc2(c) ?: ret;
1039
1040                 ret = bch2_move_data(c,
1041                                      op.start_btree,    op.start_pos,
1042                                      op.end_btree,      op.end_pos,
1043                                      NULL,
1044                                      stats,
1045                                      writepoint_hashed((unsigned long) current),
1046                                      true,
1047                                      migrate_pred, &op) ?: ret;
1048                 ret = bch2_replicas_gc2(c) ?: ret;
1049                 break;
1050         case BCH_DATA_OP_REWRITE_OLD_NODES:
1051                 bch2_move_stats_init(stats, "rewrite_old_nodes");
1052                 ret = bch2_scan_old_btree_nodes(c, stats);
1053                 break;
1054         default:
1055                 ret = -EINVAL;
1056         }
1057
1058         return ret;
1059 }