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