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