]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/move.c
Update bcachefs sources to 8fd009dd76 bcachefs: Rip out code for storing 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
64         if (io->b)
65                 atomic_dec(&io->b->count);
66
67         bch2_data_update_exit(&io->write);
68
69         mutex_lock(&ctxt->lock);
70         list_del(&io->io_list);
71         wake_up(&ctxt->wait);
72         mutex_unlock(&ctxt->lock);
73
74         kfree(io);
75 }
76
77 static void move_write_done(struct bch_write_op *op)
78 {
79         struct moving_io *io = container_of(op, struct moving_io, write.op);
80         struct moving_context *ctxt = io->write.ctxt;
81
82         if (io->write.op.error)
83                 ctxt->write_error = true;
84
85         atomic_sub(io->write_sectors, &io->write.ctxt->write_sectors);
86         atomic_dec(&io->write.ctxt->write_ios);
87         move_free(io);
88         closure_put(&ctxt->cl);
89 }
90
91 static void move_write(struct moving_io *io)
92 {
93         if (unlikely(io->rbio.bio.bi_status || io->rbio.hole)) {
94                 move_free(io);
95                 return;
96         }
97
98         closure_get(&io->write.ctxt->cl);
99         atomic_add(io->write_sectors, &io->write.ctxt->write_sectors);
100         atomic_inc(&io->write.ctxt->write_ios);
101
102         bch2_data_update_read_done(&io->write, io->rbio.pick.crc);
103 }
104
105 struct moving_io *bch2_moving_ctxt_next_pending_write(struct moving_context *ctxt)
106 {
107         struct moving_io *io =
108                 list_first_entry_or_null(&ctxt->reads, struct moving_io, read_list);
109
110         return io && io->read_completed ? io : NULL;
111 }
112
113 static void move_read_endio(struct bio *bio)
114 {
115         struct moving_io *io = container_of(bio, struct moving_io, rbio.bio);
116         struct moving_context *ctxt = io->write.ctxt;
117
118         atomic_sub(io->read_sectors, &ctxt->read_sectors);
119         atomic_dec(&ctxt->read_ios);
120         io->read_completed = true;
121
122         wake_up(&ctxt->wait);
123         closure_put(&ctxt->cl);
124 }
125
126 void bch2_moving_ctxt_do_pending_writes(struct moving_context *ctxt,
127                                         struct btree_trans *trans)
128 {
129         struct moving_io *io;
130
131         if (trans)
132                 bch2_trans_unlock(trans);
133
134         while ((io = bch2_moving_ctxt_next_pending_write(ctxt))) {
135                 list_del(&io->read_list);
136                 move_write(io);
137         }
138 }
139
140 static void bch2_move_ctxt_wait_for_io(struct moving_context *ctxt,
141                                        struct btree_trans *trans)
142 {
143         unsigned sectors_pending = atomic_read(&ctxt->write_sectors);
144
145         move_ctxt_wait_event(ctxt, trans,
146                 !atomic_read(&ctxt->write_sectors) ||
147                 atomic_read(&ctxt->write_sectors) != sectors_pending);
148 }
149
150 void bch2_moving_ctxt_exit(struct moving_context *ctxt)
151 {
152         struct bch_fs *c = ctxt->c;
153
154         move_ctxt_wait_event(ctxt, NULL, list_empty(&ctxt->reads));
155         closure_sync(&ctxt->cl);
156
157         EBUG_ON(atomic_read(&ctxt->write_sectors));
158         EBUG_ON(atomic_read(&ctxt->write_ios));
159         EBUG_ON(atomic_read(&ctxt->read_sectors));
160         EBUG_ON(atomic_read(&ctxt->read_ios));
161
162         if (ctxt->stats) {
163                 progress_list_del(c, ctxt->stats);
164                 trace_move_data(c,
165                                 atomic64_read(&ctxt->stats->sectors_moved),
166                                 atomic64_read(&ctxt->stats->keys_moved));
167         }
168
169         mutex_lock(&c->moving_context_lock);
170         list_del(&ctxt->list);
171         mutex_unlock(&c->moving_context_lock);
172 }
173
174 void bch2_moving_ctxt_init(struct moving_context *ctxt,
175                            struct bch_fs *c,
176                            struct bch_ratelimit *rate,
177                            struct bch_move_stats *stats,
178                            struct write_point_specifier wp,
179                            bool wait_on_copygc)
180 {
181         memset(ctxt, 0, sizeof(*ctxt));
182
183         ctxt->c         = c;
184         ctxt->fn        = (void *) _RET_IP_;
185         ctxt->rate      = rate;
186         ctxt->stats     = stats;
187         ctxt->wp        = wp;
188         ctxt->wait_on_copygc = wait_on_copygc;
189
190         closure_init_stack(&ctxt->cl);
191
192         mutex_init(&ctxt->lock);
193         INIT_LIST_HEAD(&ctxt->reads);
194         INIT_LIST_HEAD(&ctxt->ios);
195         init_waitqueue_head(&ctxt->wait);
196
197         mutex_lock(&c->moving_context_lock);
198         list_add(&ctxt->list, &c->moving_context_list);
199         mutex_unlock(&c->moving_context_lock);
200
201         if (stats) {
202                 progress_list_add(c, stats);
203                 stats->data_type = BCH_DATA_user;
204         }
205 }
206
207 void bch2_move_stats_init(struct bch_move_stats *stats, char *name)
208 {
209         memset(stats, 0, sizeof(*stats));
210         scnprintf(stats->name, sizeof(stats->name), "%s", name);
211 }
212
213 static int bch2_extent_drop_ptrs(struct btree_trans *trans,
214                                  struct btree_iter *iter,
215                                  struct bkey_s_c k,
216                                  struct data_update_opts data_opts)
217 {
218         struct bch_fs *c = trans->c;
219         struct bkey_i *n;
220         int ret;
221
222         n = bch2_bkey_make_mut(trans, k);
223         ret = PTR_ERR_OR_ZERO(n);
224         if (ret)
225                 return ret;
226
227         while (data_opts.kill_ptrs) {
228                 unsigned i = 0, drop = __fls(data_opts.kill_ptrs);
229                 struct bch_extent_ptr *ptr;
230
231                 bch2_bkey_drop_ptrs(bkey_i_to_s(n), ptr, i++ == drop);
232                 data_opts.kill_ptrs ^= 1U << drop;
233         }
234
235         /*
236          * If the new extent no longer has any pointers, bch2_extent_normalize()
237          * will do the appropriate thing with it (turning it into a
238          * KEY_TYPE_error key, or just a discard if it was a cached extent)
239          */
240         bch2_extent_normalize(c, bkey_i_to_s(n));
241
242         /*
243          * Since we're not inserting through an extent iterator
244          * (BTREE_ITER_ALL_SNAPSHOTS iterators aren't extent iterators),
245          * we aren't using the extent overwrite path to delete, we're
246          * just using the normal key deletion path:
247          */
248         if (bkey_deleted(&n->k))
249                 n->k.size = 0;
250
251         return bch2_trans_relock(trans) ?:
252                 bch2_trans_update(trans, iter, n, BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE) ?:
253                 bch2_trans_commit(trans, NULL, NULL, BTREE_INSERT_NOFAIL);
254 }
255
256 static int bch2_move_extent(struct btree_trans *trans,
257                             struct btree_iter *iter,
258                             struct moving_context *ctxt,
259                             struct move_bucket_in_flight *bucket_in_flight,
260                             struct bch_io_opts io_opts,
261                             enum btree_id btree_id,
262                             struct bkey_s_c k,
263                             struct data_update_opts data_opts)
264 {
265         struct bch_fs *c = trans->c;
266         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
267         struct moving_io *io;
268         const union bch_extent_entry *entry;
269         struct extent_ptr_decoded p;
270         unsigned sectors = k.k->size, pages;
271         int ret = -ENOMEM;
272
273         bch2_data_update_opts_normalize(k, &data_opts);
274
275         if (!data_opts.rewrite_ptrs &&
276             !data_opts.extra_replicas) {
277                 if (data_opts.kill_ptrs)
278                         return bch2_extent_drop_ptrs(trans, iter, k, data_opts);
279                 return 0;
280         }
281
282         /*
283          * Before memory allocations & taking nocow locks in
284          * bch2_data_update_init():
285          */
286         bch2_trans_unlock(trans);
287
288         /* write path might have to decompress data: */
289         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
290                 sectors = max_t(unsigned, sectors, p.crc.uncompressed_size);
291
292         pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
293         io = kzalloc(sizeof(struct moving_io) +
294                      sizeof(struct bio_vec) * pages, GFP_KERNEL);
295         if (!io)
296                 goto err;
297
298         INIT_LIST_HEAD(&io->io_list);
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         struct bpos bp_pos = POS_MIN;
631         unsigned nr_bps = 0;
632         int ret;
633
634         bch2_trans_begin(trans);
635
636         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
637                              bucket, BTREE_ITER_CACHED);
638 again:
639         ret = lockrestart_do(trans,
640                         bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
641
642         if (!ret && k.k->type == KEY_TYPE_alloc_v4) {
643                 struct bkey_s_c_alloc_v4 a = bkey_s_c_to_alloc_v4(k);
644
645                 if (a.v->gen == gen &&
646                     a.v->dirty_sectors) {
647                         if (a.v->data_type == BCH_DATA_btree) {
648                                 bch2_trans_unlock(trans);
649                                 if (bch2_btree_interior_updates_flush(c))
650                                         goto again;
651                                 goto failed_to_evacuate;
652                         }
653                 }
654         }
655
656         set_btree_iter_dontneed(&iter);
657         bch2_trans_iter_exit(trans, &iter);
658         return;
659 failed_to_evacuate:
660         bch2_trans_iter_exit(trans, &iter);
661
662         if (test_bit(BCH_FS_EMERGENCY_RO, &c->flags))
663                 return;
664
665         prt_printf(&buf, bch2_log_msg(c, "failed to evacuate bucket "));
666         bch2_bkey_val_to_text(&buf, c, k);
667
668         while (1) {
669                 bch2_trans_begin(trans);
670
671                 ret = bch2_get_next_backpointer(trans, bucket, gen,
672                                                 &bp_pos, &bp,
673                                                 BTREE_ITER_CACHED);
674                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
675                         continue;
676                 if (ret)
677                         break;
678                 if (bkey_eq(bp_pos, POS_MAX))
679                         break;
680
681                 k = bch2_backpointer_get_key(trans, &iter, bp_pos, bp, 0);
682                 ret = bkey_err(k);
683                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
684                         continue;
685                 if (ret)
686                         break;
687                 if (!k.k)
688                         continue;
689                 prt_newline(&buf);
690                 bch2_bkey_val_to_text(&buf, c, k);
691                 bch2_trans_iter_exit(trans, &iter);
692
693                 if (++nr_bps > 10)
694                         break;
695                 bp_pos = bpos_nosnap_successor(bp_pos);
696         }
697
698         bch2_print_string_as_lines(KERN_ERR, buf.buf);
699         printbuf_exit(&buf);
700 }
701
702 int __bch2_evacuate_bucket(struct btree_trans *trans,
703                            struct moving_context *ctxt,
704                            struct move_bucket_in_flight *bucket_in_flight,
705                            struct bpos bucket, int gen,
706                            struct data_update_opts _data_opts)
707 {
708         struct bch_fs *c = ctxt->c;
709         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
710         struct btree_iter iter;
711         struct bkey_buf sk;
712         struct bch_backpointer bp;
713         struct bch_alloc_v4 a_convert;
714         const struct bch_alloc_v4 *a;
715         struct bkey_s_c k;
716         struct data_update_opts data_opts;
717         unsigned dirty_sectors, bucket_size;
718         u64 fragmentation;
719         u64 cur_inum = U64_MAX;
720         struct bpos bp_pos = POS_MIN;
721         int ret = 0;
722
723         bch2_bkey_buf_init(&sk);
724
725         /*
726          * We're not run in a context that handles transaction restarts:
727          */
728         bch2_trans_begin(trans);
729
730         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
731                              bucket, BTREE_ITER_CACHED);
732         ret = lockrestart_do(trans,
733                         bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
734         bch2_trans_iter_exit(trans, &iter);
735
736         if (ret) {
737                 bch_err(c, "%s: error looking up alloc key: %s", __func__, bch2_err_str(ret));
738                 goto err;
739         }
740
741         a = bch2_alloc_to_v4(k, &a_convert);
742         dirty_sectors = a->dirty_sectors;
743         bucket_size = bch_dev_bkey_exists(c, bucket.inode)->mi.bucket_size;
744         fragmentation = a->fragmentation_lru;
745
746         ret = bch2_btree_write_buffer_flush(trans);
747         if (ret) {
748                 bch_err(c, "%s: error flushing btree write buffer: %s", __func__, bch2_err_str(ret));
749                 goto err;
750         }
751
752         while (!(ret = move_ratelimit(trans, ctxt))) {
753                 bch2_trans_begin(trans);
754
755                 ret = bch2_get_next_backpointer(trans, bucket, gen,
756                                                 &bp_pos, &bp,
757                                                 BTREE_ITER_CACHED);
758                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
759                         continue;
760                 if (ret)
761                         goto err;
762                 if (bkey_eq(bp_pos, POS_MAX))
763                         break;
764
765                 if (!bp.level) {
766                         const struct bch_extent_ptr *ptr;
767                         struct bkey_s_c k;
768                         unsigned i = 0;
769
770                         k = bch2_backpointer_get_key(trans, &iter, bp_pos, bp, 0);
771                         ret = bkey_err(k);
772                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
773                                 continue;
774                         if (ret)
775                                 goto err;
776                         if (!k.k)
777                                 goto next;
778
779                         bch2_bkey_buf_reassemble(&sk, c, k);
780                         k = bkey_i_to_s_c(sk.k);
781
782                         ret = move_get_io_opts(trans, &io_opts, k, &cur_inum);
783                         if (ret) {
784                                 bch2_trans_iter_exit(trans, &iter);
785                                 continue;
786                         }
787
788                         data_opts = _data_opts;
789                         data_opts.target        = io_opts.background_target;
790                         data_opts.rewrite_ptrs = 0;
791
792                         bkey_for_each_ptr(bch2_bkey_ptrs_c(k), ptr) {
793                                 if (ptr->dev == bucket.inode) {
794                                         data_opts.rewrite_ptrs |= 1U << i;
795                                         if (ptr->cached) {
796                                                 bch2_trans_iter_exit(trans, &iter);
797                                                 goto next;
798                                         }
799                                 }
800                                 i++;
801                         }
802
803                         ret = bch2_move_extent(trans, &iter, ctxt,
804                                         bucket_in_flight,
805                                         io_opts, bp.btree_id, k, data_opts);
806                         bch2_trans_iter_exit(trans, &iter);
807
808                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
809                                 continue;
810                         if (ret == -ENOMEM) {
811                                 /* memory allocation failure, wait for some IO to finish */
812                                 bch2_move_ctxt_wait_for_io(ctxt, trans);
813                                 continue;
814                         }
815                         if (ret)
816                                 goto err;
817
818                         if (ctxt->rate)
819                                 bch2_ratelimit_increment(ctxt->rate, k.k->size);
820                         if (ctxt->stats)
821                                 atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
822                 } else {
823                         struct btree *b;
824
825                         b = bch2_backpointer_get_node(trans, &iter, bp_pos, bp);
826                         ret = PTR_ERR_OR_ZERO(b);
827                         if (ret == -BCH_ERR_backpointer_to_overwritten_btree_node)
828                                 continue;
829                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
830                                 continue;
831                         if (ret)
832                                 goto err;
833                         if (!b)
834                                 goto next;
835
836                         ret = bch2_btree_node_rewrite(trans, &iter, b, 0);
837                         bch2_trans_iter_exit(trans, &iter);
838
839                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
840                                 continue;
841                         if (ret)
842                                 goto err;
843
844                         if (ctxt->rate)
845                                 bch2_ratelimit_increment(ctxt->rate,
846                                                          c->opts.btree_node_size >> 9);
847                         if (ctxt->stats) {
848                                 atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_seen);
849                                 atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_moved);
850                         }
851                 }
852 next:
853                 bp_pos = bpos_nosnap_successor(bp_pos);
854         }
855
856         trace_evacuate_bucket(c, &bucket, dirty_sectors, bucket_size, fragmentation, ret);
857 err:
858         bch2_bkey_buf_exit(&sk, c);
859         return ret;
860 }
861
862 int bch2_evacuate_bucket(struct bch_fs *c,
863                          struct bpos bucket, int gen,
864                          struct data_update_opts data_opts,
865                          struct bch_ratelimit *rate,
866                          struct bch_move_stats *stats,
867                          struct write_point_specifier wp,
868                          bool wait_on_copygc)
869 {
870         struct btree_trans trans;
871         struct moving_context ctxt;
872         int ret;
873
874         bch2_trans_init(&trans, c, 0, 0);
875         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
876         ret = __bch2_evacuate_bucket(&trans, &ctxt, NULL, bucket, gen, data_opts);
877         bch2_moving_ctxt_exit(&ctxt);
878         bch2_trans_exit(&trans);
879
880         return ret;
881 }
882
883 typedef bool (*move_btree_pred)(struct bch_fs *, void *,
884                                 struct btree *, struct bch_io_opts *,
885                                 struct data_update_opts *);
886
887 static int bch2_move_btree(struct bch_fs *c,
888                            enum btree_id start_btree_id, struct bpos start_pos,
889                            enum btree_id end_btree_id,   struct bpos end_pos,
890                            move_btree_pred pred, void *arg,
891                            struct bch_move_stats *stats)
892 {
893         bool kthread = (current->flags & PF_KTHREAD) != 0;
894         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
895         struct btree_trans trans;
896         struct btree_iter iter;
897         struct btree *b;
898         enum btree_id id;
899         struct data_update_opts data_opts;
900         int ret = 0;
901
902         bch2_trans_init(&trans, c, 0, 0);
903         progress_list_add(c, stats);
904
905         stats->data_type = BCH_DATA_btree;
906
907         for (id = start_btree_id;
908              id <= min_t(unsigned, end_btree_id, BTREE_ID_NR - 1);
909              id++) {
910                 stats->btree_id = id;
911
912                 bch2_trans_node_iter_init(&trans, &iter, id, POS_MIN, 0, 0,
913                                           BTREE_ITER_PREFETCH);
914 retry:
915                 ret = 0;
916                 while (bch2_trans_begin(&trans),
917                        (b = bch2_btree_iter_peek_node(&iter)) &&
918                        !(ret = PTR_ERR_OR_ZERO(b))) {
919                         if (kthread && kthread_should_stop())
920                                 break;
921
922                         if ((cmp_int(id, end_btree_id) ?:
923                              bpos_cmp(b->key.k.p, end_pos)) > 0)
924                                 break;
925
926                         stats->pos = iter.pos;
927
928                         if (!pred(c, arg, b, &io_opts, &data_opts))
929                                 goto next;
930
931                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0) ?: ret;
932                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
933                                 continue;
934                         if (ret)
935                                 break;
936 next:
937                         bch2_btree_iter_next_node(&iter);
938                 }
939                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
940                         goto retry;
941
942                 bch2_trans_iter_exit(&trans, &iter);
943
944                 if (kthread && kthread_should_stop())
945                         break;
946         }
947
948         bch2_trans_exit(&trans);
949
950         if (ret)
951                 bch_err(c, "error in %s(): %s", __func__, bch2_err_str(ret));
952
953         bch2_btree_interior_updates_flush(c);
954
955         progress_list_del(c, stats);
956         return ret;
957 }
958
959 static bool rereplicate_pred(struct bch_fs *c, void *arg,
960                              struct bkey_s_c k,
961                              struct bch_io_opts *io_opts,
962                              struct data_update_opts *data_opts)
963 {
964         unsigned nr_good = bch2_bkey_durability(c, k);
965         unsigned replicas = bkey_is_btree_ptr(k.k)
966                 ? c->opts.metadata_replicas
967                 : io_opts->data_replicas;
968
969         if (!nr_good || nr_good >= replicas)
970                 return false;
971
972         data_opts->target               = 0;
973         data_opts->extra_replicas       = replicas - nr_good;
974         data_opts->btree_insert_flags   = 0;
975         return true;
976 }
977
978 static bool migrate_pred(struct bch_fs *c, void *arg,
979                          struct bkey_s_c k,
980                          struct bch_io_opts *io_opts,
981                          struct data_update_opts *data_opts)
982 {
983         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
984         const struct bch_extent_ptr *ptr;
985         struct bch_ioctl_data *op = arg;
986         unsigned i = 0;
987
988         data_opts->rewrite_ptrs         = 0;
989         data_opts->target               = 0;
990         data_opts->extra_replicas       = 0;
991         data_opts->btree_insert_flags   = 0;
992
993         bkey_for_each_ptr(ptrs, ptr) {
994                 if (ptr->dev == op->migrate.dev)
995                         data_opts->rewrite_ptrs |= 1U << i;
996                 i++;
997         }
998
999         return data_opts->rewrite_ptrs != 0;
1000 }
1001
1002 static bool rereplicate_btree_pred(struct bch_fs *c, void *arg,
1003                                    struct btree *b,
1004                                    struct bch_io_opts *io_opts,
1005                                    struct data_update_opts *data_opts)
1006 {
1007         return rereplicate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
1008 }
1009
1010 static bool migrate_btree_pred(struct bch_fs *c, void *arg,
1011                                struct btree *b,
1012                                struct bch_io_opts *io_opts,
1013                                struct data_update_opts *data_opts)
1014 {
1015         return migrate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
1016 }
1017
1018 static bool bformat_needs_redo(struct bkey_format *f)
1019 {
1020         unsigned i;
1021
1022         for (i = 0; i < f->nr_fields; i++) {
1023                 unsigned unpacked_bits = bch2_bkey_format_current.bits_per_field[i];
1024                 u64 unpacked_mask = ~((~0ULL << 1) << (unpacked_bits - 1));
1025                 u64 field_offset = le64_to_cpu(f->field_offset[i]);
1026
1027                 if (f->bits_per_field[i] > unpacked_bits)
1028                         return true;
1029
1030                 if ((f->bits_per_field[i] == unpacked_bits) && field_offset)
1031                         return true;
1032
1033                 if (((field_offset + ((1ULL << f->bits_per_field[i]) - 1)) &
1034                      unpacked_mask) <
1035                     field_offset)
1036                         return true;
1037         }
1038
1039         return false;
1040 }
1041
1042 static bool rewrite_old_nodes_pred(struct bch_fs *c, void *arg,
1043                                    struct btree *b,
1044                                    struct bch_io_opts *io_opts,
1045                                    struct data_update_opts *data_opts)
1046 {
1047         if (b->version_ondisk != c->sb.version ||
1048             btree_node_need_rewrite(b) ||
1049             bformat_needs_redo(&b->format)) {
1050                 data_opts->target               = 0;
1051                 data_opts->extra_replicas       = 0;
1052                 data_opts->btree_insert_flags   = 0;
1053                 return true;
1054         }
1055
1056         return false;
1057 }
1058
1059 int bch2_scan_old_btree_nodes(struct bch_fs *c, struct bch_move_stats *stats)
1060 {
1061         int ret;
1062
1063         ret = bch2_move_btree(c,
1064                               0,                POS_MIN,
1065                               BTREE_ID_NR,      SPOS_MAX,
1066                               rewrite_old_nodes_pred, c, stats);
1067         if (!ret) {
1068                 mutex_lock(&c->sb_lock);
1069                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
1070                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
1071                 c->disk_sb.sb->version_min = c->disk_sb.sb->version;
1072                 bch2_write_super(c);
1073                 mutex_unlock(&c->sb_lock);
1074         }
1075
1076         return ret;
1077 }
1078
1079 int bch2_data_job(struct bch_fs *c,
1080                   struct bch_move_stats *stats,
1081                   struct bch_ioctl_data op)
1082 {
1083         int ret = 0;
1084
1085         switch (op.op) {
1086         case BCH_DATA_OP_REREPLICATE:
1087                 bch2_move_stats_init(stats, "rereplicate");
1088                 stats->data_type = BCH_DATA_journal;
1089                 ret = bch2_journal_flush_device_pins(&c->journal, -1);
1090
1091                 ret = bch2_move_btree(c,
1092                                       op.start_btree,   op.start_pos,
1093                                       op.end_btree,     op.end_pos,
1094                                       rereplicate_btree_pred, c, stats) ?: ret;
1095                 ret = bch2_replicas_gc2(c) ?: ret;
1096
1097                 ret = bch2_move_data(c,
1098                                      op.start_btree,    op.start_pos,
1099                                      op.end_btree,      op.end_pos,
1100                                      NULL,
1101                                      stats,
1102                                      writepoint_hashed((unsigned long) current),
1103                                      true,
1104                                      rereplicate_pred, c) ?: ret;
1105                 ret = bch2_replicas_gc2(c) ?: ret;
1106                 break;
1107         case BCH_DATA_OP_MIGRATE:
1108                 if (op.migrate.dev >= c->sb.nr_devices)
1109                         return -EINVAL;
1110
1111                 bch2_move_stats_init(stats, "migrate");
1112                 stats->data_type = BCH_DATA_journal;
1113                 ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
1114
1115                 ret = bch2_move_btree(c,
1116                                       op.start_btree,   op.start_pos,
1117                                       op.end_btree,     op.end_pos,
1118                                       migrate_btree_pred, &op, stats) ?: ret;
1119                 ret = bch2_replicas_gc2(c) ?: ret;
1120
1121                 ret = bch2_move_data(c,
1122                                      op.start_btree,    op.start_pos,
1123                                      op.end_btree,      op.end_pos,
1124                                      NULL,
1125                                      stats,
1126                                      writepoint_hashed((unsigned long) current),
1127                                      true,
1128                                      migrate_pred, &op) ?: ret;
1129                 ret = bch2_replicas_gc2(c) ?: ret;
1130                 break;
1131         case BCH_DATA_OP_REWRITE_OLD_NODES:
1132                 bch2_move_stats_init(stats, "rewrite_old_nodes");
1133                 ret = bch2_scan_old_btree_nodes(c, stats);
1134                 break;
1135         default:
1136                 ret = -EINVAL;
1137         }
1138
1139         return ret;
1140 }
1141
1142 void bch2_data_jobs_to_text(struct printbuf *out, struct bch_fs *c)
1143 {
1144         struct bch_move_stats *stats;
1145
1146         mutex_lock(&c->data_progress_lock);
1147         list_for_each_entry(stats, &c->data_progress_list, list) {
1148                 prt_printf(out, "%s: data type %s btree_id %s position: ",
1149                        stats->name,
1150                        bch2_data_types[stats->data_type],
1151                        bch2_btree_ids[stats->btree_id]);
1152                 bch2_bpos_to_text(out, stats->pos);
1153                 prt_printf(out, "%s", "\n");
1154         }
1155         mutex_unlock(&c->data_progress_lock);
1156 }
1157
1158 static void bch2_moving_ctxt_to_text(struct printbuf *out, struct moving_context *ctxt)
1159 {
1160         struct moving_io *io;
1161
1162         prt_printf(out, "%ps:", ctxt->fn);
1163         prt_newline(out);
1164         printbuf_indent_add(out, 2);
1165
1166         prt_printf(out, "reads: %u sectors %u",
1167                    atomic_read(&ctxt->read_ios),
1168                    atomic_read(&ctxt->read_sectors));
1169         prt_newline(out);
1170
1171         prt_printf(out, "writes: %u sectors %u",
1172                    atomic_read(&ctxt->write_ios),
1173                    atomic_read(&ctxt->write_sectors));
1174         prt_newline(out);
1175
1176         printbuf_indent_add(out, 2);
1177
1178         mutex_lock(&ctxt->lock);
1179         list_for_each_entry(io, &ctxt->ios, io_list) {
1180                 bch2_write_op_to_text(out, &io->write.op);
1181         }
1182         mutex_unlock(&ctxt->lock);
1183
1184         printbuf_indent_sub(out, 4);
1185 }
1186
1187 void bch2_fs_moving_ctxts_to_text(struct printbuf *out, struct bch_fs *c)
1188 {
1189         struct moving_context *ctxt;
1190
1191         mutex_lock(&c->moving_context_lock);
1192         list_for_each_entry(ctxt, &c->moving_context_list, list)
1193                 bch2_moving_ctxt_to_text(out, ctxt);
1194         mutex_unlock(&c->moving_context_lock);
1195 }
1196
1197 void bch2_fs_move_init(struct bch_fs *c)
1198 {
1199         INIT_LIST_HEAD(&c->moving_context_list);
1200         mutex_init(&c->moving_context_lock);
1201
1202         INIT_LIST_HEAD(&c->data_progress_list);
1203         mutex_init(&c->data_progress_lock);
1204 }