]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/move.c
62dcac79ed068ab3ef7aeca4755bcef3af5f5a2f
[bcachefs-tools-debian] / libbcachefs / move.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "alloc_foreground.h"
5 #include "bkey_on_stack.h"
6 #include "btree_gc.h"
7 #include "btree_update.h"
8 #include "btree_update_interior.h"
9 #include "buckets.h"
10 #include "disk_groups.h"
11 #include "inode.h"
12 #include "io.h"
13 #include "journal_reclaim.h"
14 #include "move.h"
15 #include "replicas.h"
16 #include "super-io.h"
17 #include "keylist.h"
18
19 #include <linux/ioprio.h>
20 #include <linux/kthread.h>
21
22 #include <trace/events/bcachefs.h>
23
24 #define SECTORS_IN_FLIGHT_PER_DEVICE    2048
25
26 struct moving_io {
27         struct list_head        list;
28         struct closure          cl;
29         bool                    read_completed;
30
31         unsigned                read_sectors;
32         unsigned                write_sectors;
33
34         struct bch_read_bio     rbio;
35
36         struct migrate_write    write;
37         /* Must be last since it is variable size */
38         struct bio_vec          bi_inline_vecs[0];
39 };
40
41 struct moving_context {
42         /* Closure for waiting on all reads and writes to complete */
43         struct closure          cl;
44
45         struct bch_move_stats   *stats;
46
47         struct list_head        reads;
48
49         /* in flight sectors: */
50         atomic_t                read_sectors;
51         atomic_t                write_sectors;
52
53         wait_queue_head_t       wait;
54 };
55
56 static int bch2_migrate_index_update(struct bch_write_op *op)
57 {
58         struct bch_fs *c = op->c;
59         struct btree_trans trans;
60         struct btree_iter *iter;
61         struct migrate_write *m =
62                 container_of(op, struct migrate_write, op);
63         struct keylist *keys = &op->insert_keys;
64         int ret = 0;
65
66         bch2_trans_init(&trans, c, BTREE_ITER_MAX, 0);
67
68         iter = bch2_trans_get_iter(&trans, m->btree_id,
69                                    bkey_start_pos(&bch2_keylist_front(keys)->k),
70                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
71
72         while (1) {
73                 struct bkey_s_c k;
74                 struct bkey_i *insert;
75                 struct bkey_i_extent *new;
76                 BKEY_PADDED(k) _new, _insert;
77                 const union bch_extent_entry *entry;
78                 struct extent_ptr_decoded p;
79                 bool did_work = false;
80                 int nr;
81
82                 bch2_trans_reset(&trans, 0);
83
84                 k = bch2_btree_iter_peek_slot(iter);
85                 ret = bkey_err(k);
86                 if (ret) {
87                         if (ret == -EINTR)
88                                 continue;
89                         break;
90                 }
91
92                 new = bkey_i_to_extent(bch2_keylist_front(keys));
93
94                 if (bversion_cmp(k.k->version, new->k.version) ||
95                     !bch2_bkey_matches_ptr(c, k, m->ptr, m->offset))
96                         goto nomatch;
97
98                 bkey_reassemble(&_insert.k, k);
99                 insert = &_insert.k;
100
101                 bkey_copy(&_new.k, bch2_keylist_front(keys));
102                 new = bkey_i_to_extent(&_new.k);
103                 bch2_cut_front(iter->pos, &new->k_i);
104
105                 bch2_cut_front(iter->pos,       insert);
106                 bch2_cut_back(new->k.p,         insert);
107                 bch2_cut_back(insert->k.p,      &new->k_i);
108
109                 if (m->data_cmd == DATA_REWRITE) {
110                         struct bch_extent_ptr *new_ptr, *old_ptr = (void *)
111                                 bch2_bkey_has_device(bkey_i_to_s_c(insert),
112                                                      m->data_opts.rewrite_dev);
113                         if (!old_ptr)
114                                 goto nomatch;
115
116                         if (old_ptr->cached)
117                                 extent_for_each_ptr(extent_i_to_s(new), new_ptr)
118                                         new_ptr->cached = true;
119
120                         bch2_bkey_drop_ptr(bkey_i_to_s(insert), old_ptr);
121                 }
122
123                 extent_for_each_ptr_decode(extent_i_to_s(new), p, entry) {
124                         if (bch2_bkey_has_device(bkey_i_to_s_c(insert), p.ptr.dev)) {
125                                 /*
126                                  * raced with another move op? extent already
127                                  * has a pointer to the device we just wrote
128                                  * data to
129                                  */
130                                 continue;
131                         }
132
133                         bch2_extent_ptr_decoded_append(insert, &p);
134                         did_work = true;
135                 }
136
137                 if (!did_work)
138                         goto nomatch;
139
140                 bch2_bkey_narrow_crcs(insert,
141                                 (struct bch_extent_crc_unpacked) { 0 });
142                 bch2_extent_normalize(c, bkey_i_to_s(insert));
143                 bch2_bkey_mark_replicas_cached(c, bkey_i_to_s(insert),
144                                                op->opts.background_target,
145                                                op->opts.data_replicas);
146
147                 /*
148                  * If we're not fully overwriting @k, and it's compressed, we
149                  * need a reservation for all the pointers in @insert
150                  */
151                 nr = bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(insert)) -
152                          m->nr_ptrs_reserved;
153
154                 if (insert->k.size < k.k->size &&
155                     bch2_bkey_sectors_compressed(k) &&
156                     nr > 0) {
157                         ret = bch2_disk_reservation_add(c, &op->res,
158                                         keylist_sectors(keys) * nr, 0);
159                         if (ret)
160                                 goto out;
161
162                         m->nr_ptrs_reserved += nr;
163                         goto next;
164                 }
165
166                 bch2_trans_update(&trans, iter, insert, 0);
167
168                 ret = bch2_trans_commit(&trans, &op->res,
169                                 op_journal_seq(op),
170                                 BTREE_INSERT_NOFAIL|
171                                 BTREE_INSERT_USE_RESERVE|
172                                 m->data_opts.btree_insert_flags);
173                 if (!ret)
174                         atomic_long_inc(&c->extent_migrate_done);
175                 if (ret == -EINTR)
176                         ret = 0;
177                 if (ret)
178                         break;
179 next:
180                 while (bkey_cmp(iter->pos, bch2_keylist_front(keys)->k.p) >= 0) {
181                         bch2_keylist_pop_front(keys);
182                         if (bch2_keylist_empty(keys))
183                                 goto out;
184                 }
185                 continue;
186 nomatch:
187                 if (m->ctxt) {
188                         BUG_ON(k.k->p.offset <= iter->pos.offset);
189                         atomic64_inc(&m->ctxt->stats->keys_raced);
190                         atomic64_add(k.k->p.offset - iter->pos.offset,
191                                      &m->ctxt->stats->sectors_raced);
192                 }
193                 atomic_long_inc(&c->extent_migrate_raced);
194                 trace_move_race(&new->k);
195                 bch2_btree_iter_next_slot(iter);
196                 goto next;
197         }
198 out:
199         bch2_trans_exit(&trans);
200         BUG_ON(ret == -EINTR);
201         return ret;
202 }
203
204 void bch2_migrate_read_done(struct migrate_write *m, struct bch_read_bio *rbio)
205 {
206         /* write bio must own pages: */
207         BUG_ON(!m->op.wbio.bio.bi_vcnt);
208
209         m->ptr          = rbio->pick.ptr;
210         m->offset       = rbio->pos.offset - rbio->pick.crc.offset;
211         m->op.devs_have = rbio->devs_have;
212         m->op.pos       = rbio->pos;
213         m->op.version   = rbio->version;
214         m->op.crc       = rbio->pick.crc;
215         m->op.wbio.bio.bi_iter.bi_size = m->op.crc.compressed_size << 9;
216
217         if (bch2_csum_type_is_encryption(m->op.crc.csum_type)) {
218                 m->op.nonce     = m->op.crc.nonce + m->op.crc.offset;
219                 m->op.csum_type = m->op.crc.csum_type;
220         }
221
222         if (m->data_cmd == DATA_REWRITE)
223                 bch2_dev_list_drop_dev(&m->op.devs_have, m->data_opts.rewrite_dev);
224 }
225
226 int bch2_migrate_write_init(struct bch_fs *c, struct migrate_write *m,
227                             struct write_point_specifier wp,
228                             struct bch_io_opts io_opts,
229                             enum data_cmd data_cmd,
230                             struct data_opts data_opts,
231                             enum btree_id btree_id,
232                             struct bkey_s_c k)
233 {
234         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
235         const union bch_extent_entry *entry;
236         struct extent_ptr_decoded p;
237         int ret;
238
239         m->btree_id     = btree_id;
240         m->data_cmd     = data_cmd;
241         m->data_opts    = data_opts;
242         m->nr_ptrs_reserved = 0;
243
244         bch2_write_op_init(&m->op, c, io_opts);
245
246         if (!bch2_bkey_is_incompressible(k))
247                 m->op.compression_type =
248                         bch2_compression_opt_to_type[io_opts.background_compression ?:
249                                                      io_opts.compression];
250         else
251                 m->op.incompressible = true;
252
253         m->op.target    = data_opts.target,
254         m->op.write_point = wp;
255
256         if (m->data_opts.btree_insert_flags & BTREE_INSERT_USE_RESERVE) {
257                 m->op.alloc_reserve = RESERVE_MOVINGGC;
258                 m->op.flags |= BCH_WRITE_ALLOC_NOWAIT;
259         } else {
260                 /* XXX: this should probably be passed in */
261                 m->op.flags |= BCH_WRITE_ONLY_SPECIFIED_DEVS;
262         }
263
264         m->op.flags |= BCH_WRITE_PAGES_STABLE|
265                 BCH_WRITE_PAGES_OWNED|
266                 BCH_WRITE_DATA_ENCODED|
267                 BCH_WRITE_FROM_INTERNAL;
268
269         m->op.nr_replicas       = 1;
270         m->op.nr_replicas_required = 1;
271         m->op.index_update_fn   = bch2_migrate_index_update;
272
273         switch (data_cmd) {
274         case DATA_ADD_REPLICAS: {
275                 /*
276                  * DATA_ADD_REPLICAS is used for moving data to a different
277                  * device in the background, and due to compression the new copy
278                  * might take up more space than the old copy:
279                  */
280 #if 0
281                 int nr = (int) io_opts.data_replicas -
282                         bch2_bkey_nr_ptrs_allocated(k);
283 #endif
284                 int nr = (int) io_opts.data_replicas;
285
286                 if (nr > 0) {
287                         m->op.nr_replicas = m->nr_ptrs_reserved = nr;
288
289                         ret = bch2_disk_reservation_get(c, &m->op.res,
290                                         k.k->size, m->op.nr_replicas, 0);
291                         if (ret)
292                                 return ret;
293                 }
294                 break;
295         }
296         case DATA_REWRITE: {
297                 unsigned compressed_sectors = 0;
298
299                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
300                         if (p.ptr.dev == data_opts.rewrite_dev &&
301                             !p.ptr.cached &&
302                             crc_is_compressed(p.crc))
303                                 compressed_sectors += p.crc.compressed_size;
304
305                 if (compressed_sectors) {
306                         ret = bch2_disk_reservation_add(c, &m->op.res,
307                                         k.k->size * m->op.nr_replicas,
308                                         BCH_DISK_RESERVATION_NOFAIL);
309                         if (ret)
310                                 return ret;
311                 }
312                 break;
313         }
314         case DATA_PROMOTE:
315                 m->op.flags     |= BCH_WRITE_ALLOC_NOWAIT;
316                 m->op.flags     |= BCH_WRITE_CACHED;
317                 break;
318         default:
319                 BUG();
320         }
321
322         return 0;
323 }
324
325 static void move_free(struct closure *cl)
326 {
327         struct moving_io *io = container_of(cl, struct moving_io, cl);
328         struct moving_context *ctxt = io->write.ctxt;
329         struct bvec_iter_all iter;
330         struct bio_vec *bv;
331
332         bch2_disk_reservation_put(io->write.op.c, &io->write.op.res);
333
334         bio_for_each_segment_all(bv, &io->write.op.wbio.bio, iter)
335                 if (bv->bv_page)
336                         __free_page(bv->bv_page);
337
338         wake_up(&ctxt->wait);
339
340         kfree(io);
341 }
342
343 static void move_write_done(struct closure *cl)
344 {
345         struct moving_io *io = container_of(cl, struct moving_io, cl);
346
347         atomic_sub(io->write_sectors, &io->write.ctxt->write_sectors);
348         closure_return_with_destructor(cl, move_free);
349 }
350
351 static void move_write(struct closure *cl)
352 {
353         struct moving_io *io = container_of(cl, struct moving_io, cl);
354
355         if (unlikely(io->rbio.bio.bi_status || io->rbio.hole)) {
356                 closure_return_with_destructor(cl, move_free);
357                 return;
358         }
359
360         bch2_migrate_read_done(&io->write, &io->rbio);
361
362         atomic_add(io->write_sectors, &io->write.ctxt->write_sectors);
363         closure_call(&io->write.op.cl, bch2_write, NULL, cl);
364         continue_at(cl, move_write_done, NULL);
365 }
366
367 static inline struct moving_io *next_pending_write(struct moving_context *ctxt)
368 {
369         struct moving_io *io =
370                 list_first_entry_or_null(&ctxt->reads, struct moving_io, list);
371
372         return io && io->read_completed ? io : NULL;
373 }
374
375 static void move_read_endio(struct bio *bio)
376 {
377         struct moving_io *io = container_of(bio, struct moving_io, rbio.bio);
378         struct moving_context *ctxt = io->write.ctxt;
379
380         atomic_sub(io->read_sectors, &ctxt->read_sectors);
381         io->read_completed = true;
382
383         if (next_pending_write(ctxt))
384                 wake_up(&ctxt->wait);
385
386         closure_put(&ctxt->cl);
387 }
388
389 static void do_pending_writes(struct moving_context *ctxt)
390 {
391         struct moving_io *io;
392
393         while ((io = next_pending_write(ctxt))) {
394                 list_del(&io->list);
395                 closure_call(&io->cl, move_write, NULL, &ctxt->cl);
396         }
397 }
398
399 #define move_ctxt_wait_event(_ctxt, _cond)                      \
400 do {                                                            \
401         do_pending_writes(_ctxt);                               \
402                                                                 \
403         if (_cond)                                              \
404                 break;                                          \
405         __wait_event((_ctxt)->wait,                             \
406                      next_pending_write(_ctxt) || (_cond));     \
407 } while (1)
408
409 static void bch2_move_ctxt_wait_for_io(struct moving_context *ctxt)
410 {
411         unsigned sectors_pending = atomic_read(&ctxt->write_sectors);
412
413         move_ctxt_wait_event(ctxt,
414                 !atomic_read(&ctxt->write_sectors) ||
415                 atomic_read(&ctxt->write_sectors) != sectors_pending);
416 }
417
418 static int bch2_move_extent(struct btree_trans *trans,
419                             struct moving_context *ctxt,
420                             struct write_point_specifier wp,
421                             struct bch_io_opts io_opts,
422                             enum btree_id btree_id,
423                             struct bkey_s_c k,
424                             enum data_cmd data_cmd,
425                             struct data_opts data_opts)
426 {
427         struct bch_fs *c = trans->c;
428         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
429         struct moving_io *io;
430         const union bch_extent_entry *entry;
431         struct extent_ptr_decoded p;
432         unsigned sectors = k.k->size, pages;
433         int ret = -ENOMEM;
434
435         move_ctxt_wait_event(ctxt,
436                 atomic_read(&ctxt->write_sectors) <
437                 SECTORS_IN_FLIGHT_PER_DEVICE);
438
439         move_ctxt_wait_event(ctxt,
440                 atomic_read(&ctxt->read_sectors) <
441                 SECTORS_IN_FLIGHT_PER_DEVICE);
442
443         /* write path might have to decompress data: */
444         bkey_for_each_ptr_decode(k.k, ptrs, p, entry)
445                 sectors = max_t(unsigned, sectors, p.crc.uncompressed_size);
446
447         pages = DIV_ROUND_UP(sectors, PAGE_SECTORS);
448         io = kzalloc(sizeof(struct moving_io) +
449                      sizeof(struct bio_vec) * pages, GFP_KERNEL);
450         if (!io)
451                 goto err;
452
453         io->write.ctxt          = ctxt;
454         io->read_sectors        = k.k->size;
455         io->write_sectors       = k.k->size;
456
457         bio_init(&io->write.op.wbio.bio, io->bi_inline_vecs, pages);
458         bio_set_prio(&io->write.op.wbio.bio,
459                      IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
460
461         if (bch2_bio_alloc_pages(&io->write.op.wbio.bio, sectors << 9,
462                                  GFP_KERNEL))
463                 goto err_free;
464
465         io->rbio.c              = c;
466         io->rbio.opts           = io_opts;
467         bio_init(&io->rbio.bio, io->bi_inline_vecs, pages);
468         io->rbio.bio.bi_vcnt = pages;
469         bio_set_prio(&io->rbio.bio, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0));
470         io->rbio.bio.bi_iter.bi_size = sectors << 9;
471
472         bio_set_op_attrs(&io->rbio.bio, REQ_OP_READ, 0);
473         io->rbio.bio.bi_iter.bi_sector  = bkey_start_offset(k.k);
474         io->rbio.bio.bi_end_io          = move_read_endio;
475
476         ret = bch2_migrate_write_init(c, &io->write, wp, io_opts,
477                                       data_cmd, data_opts, btree_id, k);
478         if (ret)
479                 goto err_free_pages;
480
481         atomic64_inc(&ctxt->stats->keys_moved);
482         atomic64_add(k.k->size, &ctxt->stats->sectors_moved);
483
484         trace_move_extent(k.k);
485
486         atomic_add(io->read_sectors, &ctxt->read_sectors);
487         list_add_tail(&io->list, &ctxt->reads);
488
489         /*
490          * dropped by move_read_endio() - guards against use after free of
491          * ctxt when doing wakeup
492          */
493         closure_get(&ctxt->cl);
494         bch2_read_extent(trans, &io->rbio, k, 0,
495                          BCH_READ_NODECODE|
496                          BCH_READ_LAST_FRAGMENT);
497         return 0;
498 err_free_pages:
499         bio_free_pages(&io->write.op.wbio.bio);
500 err_free:
501         kfree(io);
502 err:
503         trace_move_alloc_fail(k.k);
504         return ret;
505 }
506
507 static int __bch2_move_data(struct bch_fs *c,
508                 struct moving_context *ctxt,
509                 struct bch_ratelimit *rate,
510                 struct write_point_specifier wp,
511                 struct bpos start,
512                 struct bpos end,
513                 move_pred_fn pred, void *arg,
514                 struct bch_move_stats *stats,
515                 enum btree_id btree_id)
516 {
517         bool kthread = (current->flags & PF_KTHREAD) != 0;
518         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
519         struct bkey_on_stack sk;
520         struct btree_trans trans;
521         struct btree_iter *iter;
522         struct bkey_s_c k;
523         struct data_opts data_opts;
524         enum data_cmd data_cmd;
525         u64 delay, cur_inum = U64_MAX;
526         int ret = 0, ret2;
527
528         bkey_on_stack_init(&sk);
529         bch2_trans_init(&trans, c, 0, 0);
530
531         stats->data_type = BCH_DATA_user;
532         stats->btree_id = btree_id;
533         stats->pos      = POS_MIN;
534
535         iter = bch2_trans_get_iter(&trans, btree_id, start,
536                                    BTREE_ITER_PREFETCH);
537
538         if (rate)
539                 bch2_ratelimit_reset(rate);
540
541         while (1) {
542                 do {
543                         delay = rate ? bch2_ratelimit_delay(rate) : 0;
544
545                         if (delay) {
546                                 bch2_trans_unlock(&trans);
547                                 set_current_state(TASK_INTERRUPTIBLE);
548                         }
549
550                         if (kthread && (ret = kthread_should_stop())) {
551                                 __set_current_state(TASK_RUNNING);
552                                 goto out;
553                         }
554
555                         if (delay)
556                                 schedule_timeout(delay);
557
558                         if (unlikely(freezing(current))) {
559                                 bch2_trans_unlock(&trans);
560                                 move_ctxt_wait_event(ctxt, list_empty(&ctxt->reads));
561                                 try_to_freeze();
562                         }
563                 } while (delay);
564 peek:
565                 k = bch2_btree_iter_peek(iter);
566
567                 stats->pos = iter->pos;
568
569                 if (!k.k)
570                         break;
571                 ret = bkey_err(k);
572                 if (ret)
573                         break;
574                 if (bkey_cmp(bkey_start_pos(k.k), end) >= 0)
575                         break;
576
577                 if (!bkey_extent_is_direct_data(k.k))
578                         goto next_nondata;
579
580                 if (btree_id == BTREE_ID_EXTENTS &&
581                     cur_inum != k.k->p.inode) {
582                         struct bch_inode_unpacked inode;
583
584                         /* don't hold btree locks while looking up inode: */
585                         bch2_trans_unlock(&trans);
586
587                         io_opts = bch2_opts_to_inode_opts(c->opts);
588                         if (!bch2_inode_find_by_inum(c, k.k->p.inode, &inode))
589                                 bch2_io_opts_apply(&io_opts, bch2_inode_opts_get(&inode));
590                         cur_inum = k.k->p.inode;
591                         goto peek;
592                 }
593
594                 switch ((data_cmd = pred(c, arg, k, &io_opts, &data_opts))) {
595                 case DATA_SKIP:
596                         goto next;
597                 case DATA_SCRUB:
598                         BUG();
599                 case DATA_ADD_REPLICAS:
600                 case DATA_REWRITE:
601                 case DATA_PROMOTE:
602                         break;
603                 default:
604                         BUG();
605                 }
606
607                 /* unlock before doing IO: */
608                 bkey_on_stack_reassemble(&sk, c, k);
609                 k = bkey_i_to_s_c(sk.k);
610                 bch2_trans_unlock(&trans);
611
612                 ret2 = bch2_move_extent(&trans, ctxt, wp, io_opts, btree_id, k,
613                                         data_cmd, data_opts);
614                 if (ret2) {
615                         if (ret2 == -ENOMEM) {
616                                 /* memory allocation failure, wait for some IO to finish */
617                                 bch2_move_ctxt_wait_for_io(ctxt);
618                                 continue;
619                         }
620
621                         /* XXX signal failure */
622                         goto next;
623                 }
624
625                 if (rate)
626                         bch2_ratelimit_increment(rate, k.k->size);
627 next:
628                 atomic64_add(k.k->size * bch2_bkey_nr_ptrs_allocated(k),
629                              &stats->sectors_seen);
630 next_nondata:
631                 bch2_btree_iter_next(iter);
632                 bch2_trans_cond_resched(&trans);
633         }
634 out:
635         ret = bch2_trans_exit(&trans) ?: ret;
636         bkey_on_stack_exit(&sk, c);
637
638         return ret;
639 }
640
641 int bch2_move_data(struct bch_fs *c,
642                    struct bch_ratelimit *rate,
643                    struct write_point_specifier wp,
644                    struct bpos start,
645                    struct bpos end,
646                    move_pred_fn pred, void *arg,
647                    struct bch_move_stats *stats)
648 {
649         struct moving_context ctxt = { .stats = stats };
650         int ret;
651
652         closure_init_stack(&ctxt.cl);
653         INIT_LIST_HEAD(&ctxt.reads);
654         init_waitqueue_head(&ctxt.wait);
655
656         stats->data_type = BCH_DATA_user;
657
658         ret =   __bch2_move_data(c, &ctxt, rate, wp, start, end,
659                                  pred, arg, stats, BTREE_ID_EXTENTS) ?:
660                 __bch2_move_data(c, &ctxt, rate, wp, start, end,
661                                  pred, arg, stats, BTREE_ID_REFLINK);
662
663         move_ctxt_wait_event(&ctxt, list_empty(&ctxt.reads));
664         closure_sync(&ctxt.cl);
665
666         EBUG_ON(atomic_read(&ctxt.write_sectors));
667
668         trace_move_data(c,
669                         atomic64_read(&stats->sectors_moved),
670                         atomic64_read(&stats->keys_moved));
671
672         return ret;
673 }
674
675 static int bch2_move_btree(struct bch_fs *c,
676                            move_pred_fn pred,
677                            void *arg,
678                            struct bch_move_stats *stats)
679 {
680         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
681         struct btree_trans trans;
682         struct btree_iter *iter;
683         struct btree *b;
684         unsigned id;
685         struct data_opts data_opts;
686         enum data_cmd cmd;
687         int ret = 0;
688
689         bch2_trans_init(&trans, c, 0, 0);
690
691         stats->data_type = BCH_DATA_btree;
692
693         for (id = 0; id < BTREE_ID_NR; id++) {
694                 stats->btree_id = id;
695
696                 for_each_btree_node(&trans, iter, id, POS_MIN,
697                                     BTREE_ITER_PREFETCH, b) {
698                         stats->pos = iter->pos;
699
700                         switch ((cmd = pred(c, arg,
701                                             bkey_i_to_s_c(&b->key),
702                                             &io_opts, &data_opts))) {
703                         case DATA_SKIP:
704                                 goto next;
705                         case DATA_SCRUB:
706                                 BUG();
707                         case DATA_ADD_REPLICAS:
708                         case DATA_REWRITE:
709                                 break;
710                         default:
711                                 BUG();
712                         }
713
714                         ret = bch2_btree_node_rewrite(c, iter,
715                                         b->data->keys.seq, 0) ?: ret;
716 next:
717                         bch2_trans_cond_resched(&trans);
718                 }
719
720                 ret = bch2_trans_iter_free(&trans, iter) ?: ret;
721         }
722
723         bch2_trans_exit(&trans);
724
725         return ret;
726 }
727
728 #if 0
729 static enum data_cmd scrub_pred(struct bch_fs *c, void *arg,
730                                 struct bkey_s_c k,
731                                 struct bch_io_opts *io_opts,
732                                 struct data_opts *data_opts)
733 {
734         return DATA_SCRUB;
735 }
736 #endif
737
738 static enum data_cmd rereplicate_pred(struct bch_fs *c, void *arg,
739                                       struct bkey_s_c k,
740                                       struct bch_io_opts *io_opts,
741                                       struct data_opts *data_opts)
742 {
743         unsigned nr_good = bch2_bkey_durability(c, k);
744         unsigned replicas = 0;
745
746         switch (k.k->type) {
747         case KEY_TYPE_btree_ptr:
748                 replicas = c->opts.metadata_replicas;
749                 break;
750         case KEY_TYPE_extent:
751                 replicas = io_opts->data_replicas;
752                 break;
753         }
754
755         if (!nr_good || nr_good >= replicas)
756                 return DATA_SKIP;
757
758         data_opts->target               = 0;
759         data_opts->btree_insert_flags   = 0;
760         return DATA_ADD_REPLICAS;
761 }
762
763 static enum data_cmd migrate_pred(struct bch_fs *c, void *arg,
764                                   struct bkey_s_c k,
765                                   struct bch_io_opts *io_opts,
766                                   struct data_opts *data_opts)
767 {
768         struct bch_ioctl_data *op = arg;
769
770         if (!bch2_bkey_has_device(k, op->migrate.dev))
771                 return DATA_SKIP;
772
773         data_opts->target               = 0;
774         data_opts->btree_insert_flags   = 0;
775         data_opts->rewrite_dev          = op->migrate.dev;
776         return DATA_REWRITE;
777 }
778
779 int bch2_data_job(struct bch_fs *c,
780                   struct bch_move_stats *stats,
781                   struct bch_ioctl_data op)
782 {
783         int ret = 0;
784
785         switch (op.op) {
786         case BCH_DATA_OP_REREPLICATE:
787                 stats->data_type = BCH_DATA_journal;
788                 ret = bch2_journal_flush_device_pins(&c->journal, -1);
789
790                 ret = bch2_move_btree(c, rereplicate_pred, c, stats) ?: ret;
791
792                 closure_wait_event(&c->btree_interior_update_wait,
793                                    !bch2_btree_interior_updates_nr_pending(c));
794
795                 ret = bch2_replicas_gc2(c) ?: ret;
796
797                 ret = bch2_move_data(c, NULL,
798                                      writepoint_hashed((unsigned long) current),
799                                      op.start,
800                                      op.end,
801                                      rereplicate_pred, c, stats) ?: ret;
802                 ret = bch2_replicas_gc2(c) ?: ret;
803                 break;
804         case BCH_DATA_OP_MIGRATE:
805                 if (op.migrate.dev >= c->sb.nr_devices)
806                         return -EINVAL;
807
808                 stats->data_type = BCH_DATA_journal;
809                 ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
810
811                 ret = bch2_move_btree(c, migrate_pred, &op, stats) ?: ret;
812                 ret = bch2_replicas_gc2(c) ?: ret;
813
814                 ret = bch2_move_data(c, NULL,
815                                      writepoint_hashed((unsigned long) current),
816                                      op.start,
817                                      op.end,
818                                      migrate_pred, &op, stats) ?: ret;
819                 ret = bch2_replicas_gc2(c) ?: ret;
820                 break;
821         default:
822                 ret = -EINVAL;
823         }
824
825         return ret;
826 }