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