]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/move.c
Update bcachefs sources to eb83f1f842bb mean and variance: Promote to lib/math
[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                 struct btree_iter iter;
376                 struct bkey_s_c k;
377
378                 io_opts->d.nr = 0;
379
380                 for_each_btree_key(trans, iter, BTREE_ID_inodes, POS(0, extent_k.k->p.inode),
381                                    BTREE_ITER_ALL_SNAPSHOTS, k, ret) {
382                         if (k.k->p.offset != extent_k.k->p.inode)
383                                 break;
384
385                         if (!bkey_is_inode(k.k))
386                                 continue;
387
388                         struct bch_inode_unpacked inode;
389                         BUG_ON(bch2_inode_unpack(k, &inode));
390
391                         struct snapshot_io_opts_entry e = { .snapshot = k.k->p.snapshot };
392                         bch2_inode_opts_get(&e.io_opts, trans->c, &inode);
393
394                         ret = darray_push(&io_opts->d, e);
395                         if (ret)
396                                 break;
397                 }
398                 bch2_trans_iter_exit(trans, &iter);
399                 io_opts->cur_inum = extent_k.k->p.inode;
400         }
401
402         ret = ret ?: trans_was_restarted(trans, restart_count);
403         if (ret)
404                 return ERR_PTR(ret);
405
406         if (extent_k.k->p.snapshot) {
407                 struct snapshot_io_opts_entry *i;
408                 darray_for_each(io_opts->d, i)
409                         if (bch2_snapshot_is_ancestor(c, extent_k.k->p.snapshot, i->snapshot))
410                                 return &i->io_opts;
411         }
412
413         return &io_opts->fs_io_opts;
414 }
415
416 int bch2_move_get_io_opts_one(struct btree_trans *trans,
417                               struct bch_io_opts *io_opts,
418                               struct bkey_s_c extent_k)
419 {
420         struct btree_iter iter;
421         struct bkey_s_c k;
422         int ret;
423
424         /* reflink btree? */
425         if (!extent_k.k->p.inode) {
426                 *io_opts = bch2_opts_to_inode_opts(trans->c->opts);
427                 return 0;
428         }
429
430         k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_inodes,
431                                SPOS(0, extent_k.k->p.inode, extent_k.k->p.snapshot),
432                                BTREE_ITER_CACHED);
433         ret = bkey_err(k);
434         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
435                 return ret;
436
437         if (!ret && bkey_is_inode(k.k)) {
438                 struct bch_inode_unpacked inode;
439                 bch2_inode_unpack(k, &inode);
440                 bch2_inode_opts_get(io_opts, trans->c, &inode);
441         } else {
442                 *io_opts = bch2_opts_to_inode_opts(trans->c->opts);
443         }
444
445         bch2_trans_iter_exit(trans, &iter);
446         return 0;
447 }
448
449 int bch2_move_ratelimit(struct moving_context *ctxt)
450 {
451         struct bch_fs *c = ctxt->trans->c;
452         u64 delay;
453
454         if (ctxt->wait_on_copygc && c->copygc_running) {
455                 bch2_moving_ctxt_flush_all(ctxt);
456                 wait_event_killable(c->copygc_running_wq,
457                                     !c->copygc_running ||
458                                     kthread_should_stop());
459         }
460
461         do {
462                 delay = ctxt->rate ? bch2_ratelimit_delay(ctxt->rate) : 0;
463
464                 if (kthread_should_stop())
465                         return 1;
466
467                 if (delay)
468                         move_ctxt_wait_event_timeout(ctxt,
469                                         freezing(current) ||
470                                         kthread_should_stop(),
471                                         delay);
472
473                 if (unlikely(freezing(current))) {
474                         bch2_moving_ctxt_flush_all(ctxt);
475                         try_to_freeze();
476                 }
477         } while (delay);
478
479         /*
480          * XXX: these limits really ought to be per device, SSDs and hard drives
481          * will want different limits
482          */
483         move_ctxt_wait_event(ctxt,
484                 atomic_read(&ctxt->write_sectors) < c->opts.move_bytes_in_flight >> 9 &&
485                 atomic_read(&ctxt->read_sectors) < c->opts.move_bytes_in_flight >> 9 &&
486                 atomic_read(&ctxt->write_ios) < c->opts.move_ios_in_flight &&
487                 atomic_read(&ctxt->read_ios) < c->opts.move_ios_in_flight);
488
489         return 0;
490 }
491
492 static int bch2_move_data_btree(struct moving_context *ctxt,
493                                 struct bpos start,
494                                 struct bpos end,
495                                 move_pred_fn pred, void *arg,
496                                 enum btree_id btree_id)
497 {
498         struct btree_trans *trans = ctxt->trans;
499         struct bch_fs *c = trans->c;
500         struct per_snapshot_io_opts snapshot_io_opts;
501         struct bch_io_opts *io_opts;
502         struct bkey_buf sk;
503         struct btree_iter iter;
504         struct bkey_s_c k;
505         struct data_update_opts data_opts;
506         int ret = 0, ret2;
507
508         per_snapshot_io_opts_init(&snapshot_io_opts, c);
509         bch2_bkey_buf_init(&sk);
510
511         if (ctxt->stats) {
512                 ctxt->stats->data_type  = BCH_DATA_user;
513                 ctxt->stats->pos        = BBPOS(btree_id, start);
514         }
515
516         bch2_trans_iter_init(trans, &iter, btree_id, start,
517                              BTREE_ITER_PREFETCH|
518                              BTREE_ITER_ALL_SNAPSHOTS);
519
520         if (ctxt->rate)
521                 bch2_ratelimit_reset(ctxt->rate);
522
523         while (!bch2_move_ratelimit(ctxt)) {
524                 bch2_trans_begin(trans);
525
526                 k = bch2_btree_iter_peek(&iter);
527                 if (!k.k)
528                         break;
529
530                 ret = bkey_err(k);
531                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
532                         continue;
533                 if (ret)
534                         break;
535
536                 if (bkey_ge(bkey_start_pos(k.k), end))
537                         break;
538
539                 if (ctxt->stats)
540                         ctxt->stats->pos = BBPOS(iter.btree_id, iter.pos);
541
542                 if (!bkey_extent_is_direct_data(k.k))
543                         goto next_nondata;
544
545                 io_opts = bch2_move_get_io_opts(trans, &snapshot_io_opts, k);
546                 ret = PTR_ERR_OR_ZERO(io_opts);
547                 if (ret)
548                         continue;
549
550                 memset(&data_opts, 0, sizeof(data_opts));
551                 if (!pred(c, arg, k, io_opts, &data_opts))
552                         goto next;
553
554                 /*
555                  * The iterator gets unlocked by __bch2_read_extent - need to
556                  * save a copy of @k elsewhere:
557                  */
558                 bch2_bkey_buf_reassemble(&sk, c, k);
559                 k = bkey_i_to_s_c(sk.k);
560
561                 ret2 = bch2_move_extent(ctxt, NULL, &iter, k, *io_opts, data_opts);
562                 if (ret2) {
563                         if (bch2_err_matches(ret2, BCH_ERR_transaction_restart))
564                                 continue;
565
566                         if (ret2 == -ENOMEM) {
567                                 /* memory allocation failure, wait for some IO to finish */
568                                 bch2_move_ctxt_wait_for_io(ctxt);
569                                 continue;
570                         }
571
572                         /* XXX signal failure */
573                         goto next;
574                 }
575 next:
576                 if (ctxt->stats)
577                         atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
578 next_nondata:
579                 bch2_btree_iter_advance(&iter);
580         }
581
582         bch2_trans_iter_exit(trans, &iter);
583         bch2_bkey_buf_exit(&sk, c);
584         per_snapshot_io_opts_exit(&snapshot_io_opts);
585
586         return ret;
587 }
588
589 int __bch2_move_data(struct moving_context *ctxt,
590                      struct bbpos start,
591                      struct bbpos end,
592                      move_pred_fn pred, void *arg)
593 {
594         struct bch_fs *c = ctxt->trans->c;
595         enum btree_id id;
596         int ret = 0;
597
598         for (id = start.btree;
599              id <= min_t(unsigned, end.btree, btree_id_nr_alive(c) - 1);
600              id++) {
601                 ctxt->stats->pos = BBPOS(id, POS_MIN);
602
603                 if (!btree_type_has_ptrs(id) ||
604                     !bch2_btree_id_root(c, id)->b)
605                         continue;
606
607                 ret = bch2_move_data_btree(ctxt,
608                                        id == start.btree ? start.pos : POS_MIN,
609                                        id == end.btree   ? end.pos   : POS_MAX,
610                                        pred, arg, id);
611                 if (ret)
612                         break;
613         }
614
615         return ret;
616 }
617
618 int bch2_move_data(struct bch_fs *c,
619                    struct bbpos start,
620                    struct bbpos end,
621                    struct bch_ratelimit *rate,
622                    struct bch_move_stats *stats,
623                    struct write_point_specifier wp,
624                    bool wait_on_copygc,
625                    move_pred_fn pred, void *arg)
626 {
627
628         struct moving_context ctxt;
629         int ret;
630
631         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
632         ret = __bch2_move_data(&ctxt, start, end, pred, arg);
633         bch2_moving_ctxt_exit(&ctxt);
634
635         return ret;
636 }
637
638 int bch2_evacuate_bucket(struct moving_context *ctxt,
639                            struct move_bucket_in_flight *bucket_in_flight,
640                            struct bpos bucket, int gen,
641                            struct data_update_opts _data_opts)
642 {
643         struct btree_trans *trans = ctxt->trans;
644         struct bch_fs *c = trans->c;
645         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
646         struct btree_iter iter;
647         struct bkey_buf sk;
648         struct bch_backpointer bp;
649         struct bch_alloc_v4 a_convert;
650         const struct bch_alloc_v4 *a;
651         struct bkey_s_c k;
652         struct data_update_opts data_opts;
653         unsigned dirty_sectors, bucket_size;
654         u64 fragmentation;
655         struct bpos bp_pos = POS_MIN;
656         int ret = 0;
657
658         trace_bucket_evacuate(c, &bucket);
659
660         bch2_bkey_buf_init(&sk);
661
662         /*
663          * We're not run in a context that handles transaction restarts:
664          */
665         bch2_trans_begin(trans);
666
667         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
668                              bucket, BTREE_ITER_CACHED);
669         ret = lockrestart_do(trans,
670                         bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
671         bch2_trans_iter_exit(trans, &iter);
672
673         if (ret) {
674                 bch_err_msg(c, ret, "looking up alloc key");
675                 goto err;
676         }
677
678         a = bch2_alloc_to_v4(k, &a_convert);
679         dirty_sectors = bch2_bucket_sectors_dirty(*a);
680         bucket_size = bch_dev_bkey_exists(c, bucket.inode)->mi.bucket_size;
681         fragmentation = a->fragmentation_lru;
682
683         ret = bch2_btree_write_buffer_tryflush(trans);
684         bch_err_msg(c, ret, "flushing btree write buffer");
685         if (ret)
686                 goto err;
687
688         while (!(ret = bch2_move_ratelimit(ctxt))) {
689                 if (kthread_should_stop())
690                         break;
691
692                 bch2_trans_begin(trans);
693
694                 ret = bch2_get_next_backpointer(trans, bucket, gen,
695                                                 &bp_pos, &bp,
696                                                 BTREE_ITER_CACHED);
697                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
698                         continue;
699                 if (ret)
700                         goto err;
701                 if (bkey_eq(bp_pos, POS_MAX))
702                         break;
703
704                 if (!bp.level) {
705                         const struct bch_extent_ptr *ptr;
706                         unsigned i = 0;
707
708                         k = bch2_backpointer_get_key(trans, &iter, bp_pos, bp, 0);
709                         ret = bkey_err(k);
710                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
711                                 continue;
712                         if (ret)
713                                 goto err;
714                         if (!k.k)
715                                 goto next;
716
717                         bch2_bkey_buf_reassemble(&sk, c, k);
718                         k = bkey_i_to_s_c(sk.k);
719
720                         ret = bch2_move_get_io_opts_one(trans, &io_opts, k);
721                         if (ret) {
722                                 bch2_trans_iter_exit(trans, &iter);
723                                 continue;
724                         }
725
726                         data_opts = _data_opts;
727                         data_opts.target        = io_opts.background_target;
728                         data_opts.rewrite_ptrs = 0;
729
730                         bkey_for_each_ptr(bch2_bkey_ptrs_c(k), ptr) {
731                                 if (ptr->dev == bucket.inode) {
732                                         data_opts.rewrite_ptrs |= 1U << i;
733                                         if (ptr->cached) {
734                                                 bch2_trans_iter_exit(trans, &iter);
735                                                 goto next;
736                                         }
737                                 }
738                                 i++;
739                         }
740
741                         ret = bch2_move_extent(ctxt, bucket_in_flight,
742                                                &iter, k, io_opts, data_opts);
743                         bch2_trans_iter_exit(trans, &iter);
744
745                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
746                                 continue;
747                         if (ret == -ENOMEM) {
748                                 /* memory allocation failure, wait for some IO to finish */
749                                 bch2_move_ctxt_wait_for_io(ctxt);
750                                 continue;
751                         }
752                         if (ret)
753                                 goto err;
754
755                         if (ctxt->stats)
756                                 atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
757                 } else {
758                         struct btree *b;
759
760                         b = bch2_backpointer_get_node(trans, &iter, bp_pos, bp);
761                         ret = PTR_ERR_OR_ZERO(b);
762                         if (ret == -BCH_ERR_backpointer_to_overwritten_btree_node)
763                                 continue;
764                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
765                                 continue;
766                         if (ret)
767                                 goto err;
768                         if (!b)
769                                 goto next;
770
771                         ret = bch2_btree_node_rewrite(trans, &iter, b, 0);
772                         bch2_trans_iter_exit(trans, &iter);
773
774                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
775                                 continue;
776                         if (ret)
777                                 goto err;
778
779                         if (ctxt->rate)
780                                 bch2_ratelimit_increment(ctxt->rate,
781                                                          c->opts.btree_node_size >> 9);
782                         if (ctxt->stats) {
783                                 atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_seen);
784                                 atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_moved);
785                         }
786                 }
787 next:
788                 bp_pos = bpos_nosnap_successor(bp_pos);
789         }
790
791         trace_evacuate_bucket(c, &bucket, dirty_sectors, bucket_size, fragmentation, ret);
792 err:
793         bch2_bkey_buf_exit(&sk, c);
794         return ret;
795 }
796
797 typedef bool (*move_btree_pred)(struct bch_fs *, void *,
798                                 struct btree *, struct bch_io_opts *,
799                                 struct data_update_opts *);
800
801 static int bch2_move_btree(struct bch_fs *c,
802                            struct bbpos start,
803                            struct bbpos end,
804                            move_btree_pred pred, void *arg,
805                            struct bch_move_stats *stats)
806 {
807         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
808         struct moving_context ctxt;
809         struct btree_trans *trans;
810         struct btree_iter iter;
811         struct btree *b;
812         enum btree_id btree;
813         struct data_update_opts data_opts;
814         int ret = 0;
815
816         bch2_moving_ctxt_init(&ctxt, c, NULL, stats,
817                               writepoint_ptr(&c->btree_write_point),
818                               true);
819         trans = ctxt.trans;
820
821         stats->data_type = BCH_DATA_btree;
822
823         for (btree = start.btree;
824              btree <= min_t(unsigned, end.btree, btree_id_nr_alive(c) - 1);
825              btree ++) {
826                 stats->pos = BBPOS(btree, POS_MIN);
827
828                 if (!bch2_btree_id_root(c, btree)->b)
829                         continue;
830
831                 bch2_trans_node_iter_init(trans, &iter, btree, 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_should_stop())
839                                 break;
840
841                         if ((cmp_int(btree, end.btree) ?:
842                              bpos_cmp(b->key.k.p, end.pos)) > 0)
843                                 break;
844
845                         stats->pos = BBPOS(iter.btree_id, 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_should_stop())
864                         break;
865         }
866
867         bch_err_fn(c, ret);
868         bch2_moving_ctxt_exit(&ctxt);
869         bch2_btree_interior_updates_flush(c);
870
871         return ret;
872 }
873
874 static bool rereplicate_pred(struct bch_fs *c, void *arg,
875                              struct bkey_s_c k,
876                              struct bch_io_opts *io_opts,
877                              struct data_update_opts *data_opts)
878 {
879         unsigned nr_good = bch2_bkey_durability(c, k);
880         unsigned replicas = bkey_is_btree_ptr(k.k)
881                 ? c->opts.metadata_replicas
882                 : io_opts->data_replicas;
883
884         if (!nr_good || nr_good >= replicas)
885                 return false;
886
887         data_opts->target               = 0;
888         data_opts->extra_replicas       = replicas - nr_good;
889         data_opts->btree_insert_flags   = 0;
890         return true;
891 }
892
893 static bool migrate_pred(struct bch_fs *c, void *arg,
894                          struct bkey_s_c k,
895                          struct bch_io_opts *io_opts,
896                          struct data_update_opts *data_opts)
897 {
898         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
899         const struct bch_extent_ptr *ptr;
900         struct bch_ioctl_data *op = arg;
901         unsigned i = 0;
902
903         data_opts->rewrite_ptrs         = 0;
904         data_opts->target               = 0;
905         data_opts->extra_replicas       = 0;
906         data_opts->btree_insert_flags   = 0;
907
908         bkey_for_each_ptr(ptrs, ptr) {
909                 if (ptr->dev == op->migrate.dev)
910                         data_opts->rewrite_ptrs |= 1U << i;
911                 i++;
912         }
913
914         return data_opts->rewrite_ptrs != 0;
915 }
916
917 static bool rereplicate_btree_pred(struct bch_fs *c, void *arg,
918                                    struct btree *b,
919                                    struct bch_io_opts *io_opts,
920                                    struct data_update_opts *data_opts)
921 {
922         return rereplicate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
923 }
924
925 static bool migrate_btree_pred(struct bch_fs *c, void *arg,
926                                struct btree *b,
927                                struct bch_io_opts *io_opts,
928                                struct data_update_opts *data_opts)
929 {
930         return migrate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
931 }
932
933 static bool bformat_needs_redo(struct bkey_format *f)
934 {
935         unsigned i;
936
937         for (i = 0; i < f->nr_fields; i++) {
938                 unsigned unpacked_bits = bch2_bkey_format_current.bits_per_field[i];
939                 u64 unpacked_mask = ~((~0ULL << 1) << (unpacked_bits - 1));
940                 u64 field_offset = le64_to_cpu(f->field_offset[i]);
941
942                 if (f->bits_per_field[i] > unpacked_bits)
943                         return true;
944
945                 if ((f->bits_per_field[i] == unpacked_bits) && field_offset)
946                         return true;
947
948                 if (((field_offset + ((1ULL << f->bits_per_field[i]) - 1)) &
949                      unpacked_mask) <
950                     field_offset)
951                         return true;
952         }
953
954         return false;
955 }
956
957 static bool rewrite_old_nodes_pred(struct bch_fs *c, void *arg,
958                                    struct btree *b,
959                                    struct bch_io_opts *io_opts,
960                                    struct data_update_opts *data_opts)
961 {
962         if (b->version_ondisk != c->sb.version ||
963             btree_node_need_rewrite(b) ||
964             bformat_needs_redo(&b->format)) {
965                 data_opts->target               = 0;
966                 data_opts->extra_replicas       = 0;
967                 data_opts->btree_insert_flags   = 0;
968                 return true;
969         }
970
971         return false;
972 }
973
974 int bch2_scan_old_btree_nodes(struct bch_fs *c, struct bch_move_stats *stats)
975 {
976         int ret;
977
978         ret = bch2_move_btree(c,
979                               BBPOS_MIN,
980                               BBPOS_MAX,
981                               rewrite_old_nodes_pred, c, stats);
982         if (!ret) {
983                 mutex_lock(&c->sb_lock);
984                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
985                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
986                 c->disk_sb.sb->version_min = c->disk_sb.sb->version;
987                 bch2_write_super(c);
988                 mutex_unlock(&c->sb_lock);
989         }
990
991         bch_err_fn(c, ret);
992         return ret;
993 }
994
995 static bool drop_extra_replicas_pred(struct bch_fs *c, void *arg,
996                              struct bkey_s_c k,
997                              struct bch_io_opts *io_opts,
998                              struct data_update_opts *data_opts)
999 {
1000         unsigned durability = bch2_bkey_durability(c, k);
1001         unsigned replicas = bkey_is_btree_ptr(k.k)
1002                 ? c->opts.metadata_replicas
1003                 : io_opts->data_replicas;
1004         const union bch_extent_entry *entry;
1005         struct extent_ptr_decoded p;
1006         unsigned i = 0;
1007
1008         bkey_for_each_ptr_decode(k.k, bch2_bkey_ptrs_c(k), p, entry) {
1009                 unsigned d = bch2_extent_ptr_durability(c, &p);
1010
1011                 if (d && durability - d >= replicas) {
1012                         data_opts->kill_ptrs |= BIT(i);
1013                         durability -= d;
1014                 }
1015
1016                 i++;
1017         }
1018
1019         return data_opts->kill_ptrs != 0;
1020 }
1021
1022 static bool drop_extra_replicas_btree_pred(struct bch_fs *c, void *arg,
1023                                    struct btree *b,
1024                                    struct bch_io_opts *io_opts,
1025                                    struct data_update_opts *data_opts)
1026 {
1027         return drop_extra_replicas_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
1028 }
1029
1030 int bch2_data_job(struct bch_fs *c,
1031                   struct bch_move_stats *stats,
1032                   struct bch_ioctl_data op)
1033 {
1034         struct bbpos start      = BBPOS(op.start_btree, op.start_pos);
1035         struct bbpos end        = BBPOS(op.end_btree, op.end_pos);
1036         int ret = 0;
1037
1038         if (op.op >= BCH_DATA_OP_NR)
1039                 return -EINVAL;
1040
1041         bch2_move_stats_init(stats, bch2_data_ops_strs[op.op]);
1042
1043         switch (op.op) {
1044         case BCH_DATA_OP_rereplicate:
1045                 stats->data_type = BCH_DATA_journal;
1046                 ret = bch2_journal_flush_device_pins(&c->journal, -1);
1047                 ret = bch2_move_btree(c, start, end,
1048                                       rereplicate_btree_pred, c, stats) ?: ret;
1049                 ret = bch2_move_data(c, start, end,
1050                                      NULL,
1051                                      stats,
1052                                      writepoint_hashed((unsigned long) current),
1053                                      true,
1054                                      rereplicate_pred, c) ?: ret;
1055                 ret = bch2_replicas_gc2(c) ?: ret;
1056                 break;
1057         case BCH_DATA_OP_migrate:
1058                 if (op.migrate.dev >= c->sb.nr_devices)
1059                         return -EINVAL;
1060
1061                 stats->data_type = BCH_DATA_journal;
1062                 ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
1063                 ret = bch2_move_btree(c, start, end,
1064                                       migrate_btree_pred, &op, stats) ?: ret;
1065                 ret = bch2_move_data(c, start, end,
1066                                      NULL,
1067                                      stats,
1068                                      writepoint_hashed((unsigned long) current),
1069                                      true,
1070                                      migrate_pred, &op) ?: ret;
1071                 ret = bch2_replicas_gc2(c) ?: ret;
1072                 break;
1073         case BCH_DATA_OP_rewrite_old_nodes:
1074                 ret = bch2_scan_old_btree_nodes(c, stats);
1075                 break;
1076         case BCH_DATA_OP_drop_extra_replicas:
1077                 ret = bch2_move_btree(c, start, end,
1078                                 drop_extra_replicas_btree_pred, c, stats) ?: ret;
1079                 ret = bch2_move_data(c, start, end, NULL, stats,
1080                                 writepoint_hashed((unsigned long) current),
1081                                 true,
1082                                 drop_extra_replicas_pred, c) ?: ret;
1083                 ret = bch2_replicas_gc2(c) ?: ret;
1084                 break;
1085         default:
1086                 ret = -EINVAL;
1087         }
1088
1089         bch2_move_stats_exit(stats, c);
1090         return ret;
1091 }
1092
1093 void bch2_move_stats_to_text(struct printbuf *out, struct bch_move_stats *stats)
1094 {
1095         prt_printf(out, "%s: data type=%s pos=",
1096                    stats->name,
1097                    bch2_data_types[stats->data_type]);
1098         bch2_bbpos_to_text(out, stats->pos);
1099         prt_newline(out);
1100         printbuf_indent_add(out, 2);
1101
1102         prt_str(out, "keys moved:  ");
1103         prt_u64(out, atomic64_read(&stats->keys_moved));
1104         prt_newline(out);
1105
1106         prt_str(out, "keys raced:  ");
1107         prt_u64(out, atomic64_read(&stats->keys_raced));
1108         prt_newline(out);
1109
1110         prt_str(out, "bytes seen:  ");
1111         prt_human_readable_u64(out, atomic64_read(&stats->sectors_seen) << 9);
1112         prt_newline(out);
1113
1114         prt_str(out, "bytes moved: ");
1115         prt_human_readable_u64(out, atomic64_read(&stats->sectors_moved) << 9);
1116         prt_newline(out);
1117
1118         prt_str(out, "bytes raced: ");
1119         prt_human_readable_u64(out, atomic64_read(&stats->sectors_raced) << 9);
1120         prt_newline(out);
1121
1122         printbuf_indent_sub(out, 2);
1123 }
1124
1125 static void bch2_moving_ctxt_to_text(struct printbuf *out, struct bch_fs *c, struct moving_context *ctxt)
1126 {
1127         struct moving_io *io;
1128
1129         bch2_move_stats_to_text(out, ctxt->stats);
1130         printbuf_indent_add(out, 2);
1131
1132         prt_printf(out, "reads: ios %u/%u sectors %u/%u",
1133                    atomic_read(&ctxt->read_ios),
1134                    c->opts.move_ios_in_flight,
1135                    atomic_read(&ctxt->read_sectors),
1136                    c->opts.move_bytes_in_flight >> 9);
1137         prt_newline(out);
1138
1139         prt_printf(out, "writes: ios %u/%u sectors %u/%u",
1140                    atomic_read(&ctxt->write_ios),
1141                    c->opts.move_ios_in_flight,
1142                    atomic_read(&ctxt->write_sectors),
1143                    c->opts.move_bytes_in_flight >> 9);
1144         prt_newline(out);
1145
1146         printbuf_indent_add(out, 2);
1147
1148         mutex_lock(&ctxt->lock);
1149         list_for_each_entry(io, &ctxt->ios, io_list)
1150                 bch2_write_op_to_text(out, &io->write.op);
1151         mutex_unlock(&ctxt->lock);
1152
1153         printbuf_indent_sub(out, 4);
1154 }
1155
1156 void bch2_fs_moving_ctxts_to_text(struct printbuf *out, struct bch_fs *c)
1157 {
1158         struct moving_context *ctxt;
1159
1160         mutex_lock(&c->moving_context_lock);
1161         list_for_each_entry(ctxt, &c->moving_context_list, list)
1162                 bch2_moving_ctxt_to_text(out, c, ctxt);
1163         mutex_unlock(&c->moving_context_lock);
1164 }
1165
1166 void bch2_fs_move_init(struct bch_fs *c)
1167 {
1168         INIT_LIST_HEAD(&c->moving_context_list);
1169         mutex_init(&c->moving_context_lock);
1170 }