]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/move.c
Update bcachefs sources to 4b5917839c bcachefs: Fix a null ptr deref in check_xattr()
[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_alive(c) - 1);
636              id++) {
637                 stats->btree_id = id;
638
639                 if (id != BTREE_ID_extents &&
640                     id != BTREE_ID_reflink)
641                         continue;
642
643                 if (!bch2_btree_id_root(c, id)->b)
644                         continue;
645
646                 ret = __bch2_move_data(&ctxt,
647                                        id == start_btree_id ? start_pos : POS_MIN,
648                                        id == end_btree_id   ? end_pos   : POS_MAX,
649                                        pred, arg, id);
650                 if (ret)
651                         break;
652         }
653
654         bch2_moving_ctxt_exit(&ctxt);
655
656         return ret;
657 }
658
659 int __bch2_evacuate_bucket(struct btree_trans *trans,
660                            struct moving_context *ctxt,
661                            struct move_bucket_in_flight *bucket_in_flight,
662                            struct bpos bucket, int gen,
663                            struct data_update_opts _data_opts)
664 {
665         struct bch_fs *c = ctxt->c;
666         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
667         struct btree_iter iter;
668         struct bkey_buf sk;
669         struct bch_backpointer bp;
670         struct bch_alloc_v4 a_convert;
671         const struct bch_alloc_v4 *a;
672         struct bkey_s_c k;
673         struct data_update_opts data_opts;
674         unsigned dirty_sectors, bucket_size;
675         u64 fragmentation;
676         u64 cur_inum = U64_MAX;
677         struct bpos bp_pos = POS_MIN;
678         int ret = 0;
679
680         trace_bucket_evacuate(c, &bucket);
681
682         bch2_bkey_buf_init(&sk);
683
684         /*
685          * We're not run in a context that handles transaction restarts:
686          */
687         bch2_trans_begin(trans);
688
689         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc,
690                              bucket, BTREE_ITER_CACHED);
691         ret = lockrestart_do(trans,
692                         bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
693         bch2_trans_iter_exit(trans, &iter);
694
695         if (ret) {
696                 bch_err_msg(c, ret, "looking up alloc key");
697                 goto err;
698         }
699
700         a = bch2_alloc_to_v4(k, &a_convert);
701         dirty_sectors = a->dirty_sectors;
702         bucket_size = bch_dev_bkey_exists(c, bucket.inode)->mi.bucket_size;
703         fragmentation = a->fragmentation_lru;
704
705         ret = bch2_btree_write_buffer_flush(trans);
706         if (ret) {
707                 bch_err_msg(c, ret, "flushing btree write buffer");
708                 goto err;
709         }
710
711         while (!(ret = move_ratelimit(trans, ctxt))) {
712                 bch2_trans_begin(trans);
713
714                 ret = bch2_get_next_backpointer(trans, bucket, gen,
715                                                 &bp_pos, &bp,
716                                                 BTREE_ITER_CACHED);
717                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
718                         continue;
719                 if (ret)
720                         goto err;
721                 if (bkey_eq(bp_pos, POS_MAX))
722                         break;
723
724                 if (!bp.level) {
725                         const struct bch_extent_ptr *ptr;
726                         struct bkey_s_c k;
727                         unsigned i = 0;
728
729                         k = bch2_backpointer_get_key(trans, &iter, bp_pos, bp, 0);
730                         ret = bkey_err(k);
731                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
732                                 continue;
733                         if (ret)
734                                 goto err;
735                         if (!k.k)
736                                 goto next;
737
738                         bch2_bkey_buf_reassemble(&sk, c, k);
739                         k = bkey_i_to_s_c(sk.k);
740
741                         ret = move_get_io_opts(trans, &io_opts, k, &cur_inum);
742                         if (ret) {
743                                 bch2_trans_iter_exit(trans, &iter);
744                                 continue;
745                         }
746
747                         data_opts = _data_opts;
748                         data_opts.target        = io_opts.background_target;
749                         data_opts.rewrite_ptrs = 0;
750
751                         bkey_for_each_ptr(bch2_bkey_ptrs_c(k), ptr) {
752                                 if (ptr->dev == bucket.inode) {
753                                         data_opts.rewrite_ptrs |= 1U << i;
754                                         if (ptr->cached) {
755                                                 bch2_trans_iter_exit(trans, &iter);
756                                                 goto next;
757                                         }
758                                 }
759                                 i++;
760                         }
761
762                         ret = bch2_move_extent(trans, &iter, ctxt,
763                                         bucket_in_flight,
764                                         io_opts, bp.btree_id, k, data_opts);
765                         bch2_trans_iter_exit(trans, &iter);
766
767                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
768                                 continue;
769                         if (ret == -ENOMEM) {
770                                 /* memory allocation failure, wait for some IO to finish */
771                                 bch2_move_ctxt_wait_for_io(ctxt, trans);
772                                 continue;
773                         }
774                         if (ret)
775                                 goto err;
776
777                         if (ctxt->rate)
778                                 bch2_ratelimit_increment(ctxt->rate, k.k->size);
779                         if (ctxt->stats)
780                                 atomic64_add(k.k->size, &ctxt->stats->sectors_seen);
781                 } else {
782                         struct btree *b;
783
784                         b = bch2_backpointer_get_node(trans, &iter, bp_pos, bp);
785                         ret = PTR_ERR_OR_ZERO(b);
786                         if (ret == -BCH_ERR_backpointer_to_overwritten_btree_node)
787                                 continue;
788                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
789                                 continue;
790                         if (ret)
791                                 goto err;
792                         if (!b)
793                                 goto next;
794
795                         ret = bch2_btree_node_rewrite(trans, &iter, b, 0);
796                         bch2_trans_iter_exit(trans, &iter);
797
798                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
799                                 continue;
800                         if (ret)
801                                 goto err;
802
803                         if (ctxt->rate)
804                                 bch2_ratelimit_increment(ctxt->rate,
805                                                          c->opts.btree_node_size >> 9);
806                         if (ctxt->stats) {
807                                 atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_seen);
808                                 atomic64_add(c->opts.btree_node_size >> 9, &ctxt->stats->sectors_moved);
809                         }
810                 }
811 next:
812                 bp_pos = bpos_nosnap_successor(bp_pos);
813         }
814
815         trace_evacuate_bucket(c, &bucket, dirty_sectors, bucket_size, fragmentation, ret);
816 err:
817         bch2_bkey_buf_exit(&sk, c);
818         return ret;
819 }
820
821 int bch2_evacuate_bucket(struct bch_fs *c,
822                          struct bpos bucket, int gen,
823                          struct data_update_opts data_opts,
824                          struct bch_ratelimit *rate,
825                          struct bch_move_stats *stats,
826                          struct write_point_specifier wp,
827                          bool wait_on_copygc)
828 {
829         struct btree_trans trans;
830         struct moving_context ctxt;
831         int ret;
832
833         bch2_trans_init(&trans, c, 0, 0);
834         bch2_moving_ctxt_init(&ctxt, c, rate, stats, wp, wait_on_copygc);
835         ret = __bch2_evacuate_bucket(&trans, &ctxt, NULL, bucket, gen, data_opts);
836         bch2_moving_ctxt_exit(&ctxt);
837         bch2_trans_exit(&trans);
838
839         return ret;
840 }
841
842 typedef bool (*move_btree_pred)(struct bch_fs *, void *,
843                                 struct btree *, struct bch_io_opts *,
844                                 struct data_update_opts *);
845
846 static int bch2_move_btree(struct bch_fs *c,
847                            enum btree_id start_btree_id, struct bpos start_pos,
848                            enum btree_id end_btree_id,   struct bpos end_pos,
849                            move_btree_pred pred, void *arg,
850                            struct bch_move_stats *stats)
851 {
852         bool kthread = (current->flags & PF_KTHREAD) != 0;
853         struct bch_io_opts io_opts = bch2_opts_to_inode_opts(c->opts);
854         struct btree_trans trans;
855         struct btree_iter iter;
856         struct btree *b;
857         enum btree_id id;
858         struct data_update_opts data_opts;
859         int ret = 0;
860
861         bch2_trans_init(&trans, c, 0, 0);
862         progress_list_add(c, stats);
863
864         stats->data_type = BCH_DATA_btree;
865
866         for (id = start_btree_id;
867              id <= min_t(unsigned, end_btree_id, btree_id_nr_alive(c) - 1);
868              id++) {
869                 stats->btree_id = id;
870
871                 if (!bch2_btree_id_root(c, id)->b)
872                         continue;
873
874                 bch2_trans_node_iter_init(&trans, &iter, id, POS_MIN, 0, 0,
875                                           BTREE_ITER_PREFETCH);
876 retry:
877                 ret = 0;
878                 while (bch2_trans_begin(&trans),
879                        (b = bch2_btree_iter_peek_node(&iter)) &&
880                        !(ret = PTR_ERR_OR_ZERO(b))) {
881                         if (kthread && kthread_should_stop())
882                                 break;
883
884                         if ((cmp_int(id, end_btree_id) ?:
885                              bpos_cmp(b->key.k.p, end_pos)) > 0)
886                                 break;
887
888                         stats->pos = iter.pos;
889
890                         if (!pred(c, arg, b, &io_opts, &data_opts))
891                                 goto next;
892
893                         ret = bch2_btree_node_rewrite(&trans, &iter, b, 0) ?: ret;
894                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
895                                 continue;
896                         if (ret)
897                                 break;
898 next:
899                         bch2_btree_iter_next_node(&iter);
900                 }
901                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
902                         goto retry;
903
904                 bch2_trans_iter_exit(&trans, &iter);
905
906                 if (kthread && kthread_should_stop())
907                         break;
908         }
909
910         bch2_trans_exit(&trans);
911
912         if (ret)
913                 bch_err_fn(c, ret);
914
915         bch2_btree_interior_updates_flush(c);
916
917         progress_list_del(c, stats);
918         return ret;
919 }
920
921 static bool rereplicate_pred(struct bch_fs *c, void *arg,
922                              struct bkey_s_c k,
923                              struct bch_io_opts *io_opts,
924                              struct data_update_opts *data_opts)
925 {
926         unsigned nr_good = bch2_bkey_durability(c, k);
927         unsigned replicas = bkey_is_btree_ptr(k.k)
928                 ? c->opts.metadata_replicas
929                 : io_opts->data_replicas;
930
931         if (!nr_good || nr_good >= replicas)
932                 return false;
933
934         data_opts->target               = 0;
935         data_opts->extra_replicas       = replicas - nr_good;
936         data_opts->btree_insert_flags   = 0;
937         return true;
938 }
939
940 static bool migrate_pred(struct bch_fs *c, void *arg,
941                          struct bkey_s_c k,
942                          struct bch_io_opts *io_opts,
943                          struct data_update_opts *data_opts)
944 {
945         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
946         const struct bch_extent_ptr *ptr;
947         struct bch_ioctl_data *op = arg;
948         unsigned i = 0;
949
950         data_opts->rewrite_ptrs         = 0;
951         data_opts->target               = 0;
952         data_opts->extra_replicas       = 0;
953         data_opts->btree_insert_flags   = 0;
954
955         bkey_for_each_ptr(ptrs, ptr) {
956                 if (ptr->dev == op->migrate.dev)
957                         data_opts->rewrite_ptrs |= 1U << i;
958                 i++;
959         }
960
961         return data_opts->rewrite_ptrs != 0;
962 }
963
964 static bool rereplicate_btree_pred(struct bch_fs *c, void *arg,
965                                    struct btree *b,
966                                    struct bch_io_opts *io_opts,
967                                    struct data_update_opts *data_opts)
968 {
969         return rereplicate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
970 }
971
972 static bool migrate_btree_pred(struct bch_fs *c, void *arg,
973                                struct btree *b,
974                                struct bch_io_opts *io_opts,
975                                struct data_update_opts *data_opts)
976 {
977         return migrate_pred(c, arg, bkey_i_to_s_c(&b->key), io_opts, data_opts);
978 }
979
980 static bool bformat_needs_redo(struct bkey_format *f)
981 {
982         unsigned i;
983
984         for (i = 0; i < f->nr_fields; i++) {
985                 unsigned unpacked_bits = bch2_bkey_format_current.bits_per_field[i];
986                 u64 unpacked_mask = ~((~0ULL << 1) << (unpacked_bits - 1));
987                 u64 field_offset = le64_to_cpu(f->field_offset[i]);
988
989                 if (f->bits_per_field[i] > unpacked_bits)
990                         return true;
991
992                 if ((f->bits_per_field[i] == unpacked_bits) && field_offset)
993                         return true;
994
995                 if (((field_offset + ((1ULL << f->bits_per_field[i]) - 1)) &
996                      unpacked_mask) <
997                     field_offset)
998                         return true;
999         }
1000
1001         return false;
1002 }
1003
1004 static bool rewrite_old_nodes_pred(struct bch_fs *c, void *arg,
1005                                    struct btree *b,
1006                                    struct bch_io_opts *io_opts,
1007                                    struct data_update_opts *data_opts)
1008 {
1009         if (b->version_ondisk != c->sb.version ||
1010             btree_node_need_rewrite(b) ||
1011             bformat_needs_redo(&b->format)) {
1012                 data_opts->target               = 0;
1013                 data_opts->extra_replicas       = 0;
1014                 data_opts->btree_insert_flags   = 0;
1015                 return true;
1016         }
1017
1018         return false;
1019 }
1020
1021 int bch2_scan_old_btree_nodes(struct bch_fs *c, struct bch_move_stats *stats)
1022 {
1023         int ret;
1024
1025         ret = bch2_move_btree(c,
1026                               0,                POS_MIN,
1027                               BTREE_ID_NR,      SPOS_MAX,
1028                               rewrite_old_nodes_pred, c, stats);
1029         if (!ret) {
1030                 mutex_lock(&c->sb_lock);
1031                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_extents_above_btree_updates_done);
1032                 c->disk_sb.sb->compat[0] |= cpu_to_le64(1ULL << BCH_COMPAT_bformat_overflow_done);
1033                 c->disk_sb.sb->version_min = c->disk_sb.sb->version;
1034                 bch2_write_super(c);
1035                 mutex_unlock(&c->sb_lock);
1036         }
1037
1038         if (ret)
1039                 bch_err_fn(c, ret);
1040         return ret;
1041 }
1042
1043 int bch2_data_job(struct bch_fs *c,
1044                   struct bch_move_stats *stats,
1045                   struct bch_ioctl_data op)
1046 {
1047         int ret = 0;
1048
1049         switch (op.op) {
1050         case BCH_DATA_OP_REREPLICATE:
1051                 bch2_move_stats_init(stats, "rereplicate");
1052                 stats->data_type = BCH_DATA_journal;
1053                 ret = bch2_journal_flush_device_pins(&c->journal, -1);
1054
1055                 ret = bch2_move_btree(c,
1056                                       op.start_btree,   op.start_pos,
1057                                       op.end_btree,     op.end_pos,
1058                                       rereplicate_btree_pred, c, stats) ?: ret;
1059                 ret = bch2_replicas_gc2(c) ?: ret;
1060
1061                 ret = bch2_move_data(c,
1062                                      op.start_btree,    op.start_pos,
1063                                      op.end_btree,      op.end_pos,
1064                                      NULL,
1065                                      stats,
1066                                      writepoint_hashed((unsigned long) current),
1067                                      true,
1068                                      rereplicate_pred, c) ?: ret;
1069                 ret = bch2_replicas_gc2(c) ?: ret;
1070                 break;
1071         case BCH_DATA_OP_MIGRATE:
1072                 if (op.migrate.dev >= c->sb.nr_devices)
1073                         return -EINVAL;
1074
1075                 bch2_move_stats_init(stats, "migrate");
1076                 stats->data_type = BCH_DATA_journal;
1077                 ret = bch2_journal_flush_device_pins(&c->journal, op.migrate.dev);
1078
1079                 ret = bch2_move_btree(c,
1080                                       op.start_btree,   op.start_pos,
1081                                       op.end_btree,     op.end_pos,
1082                                       migrate_btree_pred, &op, stats) ?: ret;
1083                 ret = bch2_replicas_gc2(c) ?: ret;
1084
1085                 ret = bch2_move_data(c,
1086                                      op.start_btree,    op.start_pos,
1087                                      op.end_btree,      op.end_pos,
1088                                      NULL,
1089                                      stats,
1090                                      writepoint_hashed((unsigned long) current),
1091                                      true,
1092                                      migrate_pred, &op) ?: ret;
1093                 ret = bch2_replicas_gc2(c) ?: ret;
1094                 break;
1095         case BCH_DATA_OP_REWRITE_OLD_NODES:
1096                 bch2_move_stats_init(stats, "rewrite_old_nodes");
1097                 ret = bch2_scan_old_btree_nodes(c, stats);
1098                 break;
1099         default:
1100                 ret = -EINVAL;
1101         }
1102
1103         return ret;
1104 }
1105
1106 void bch2_data_jobs_to_text(struct printbuf *out, struct bch_fs *c)
1107 {
1108         struct bch_move_stats *stats;
1109
1110         mutex_lock(&c->data_progress_lock);
1111         list_for_each_entry(stats, &c->data_progress_list, list) {
1112                 prt_printf(out, "%s: data type %s btree_id %s position: ",
1113                        stats->name,
1114                        bch2_data_types[stats->data_type],
1115                        bch2_btree_ids[stats->btree_id]);
1116                 bch2_bpos_to_text(out, stats->pos);
1117                 prt_printf(out, "%s", "\n");
1118         }
1119         mutex_unlock(&c->data_progress_lock);
1120 }
1121
1122 static void bch2_moving_ctxt_to_text(struct printbuf *out, struct moving_context *ctxt)
1123 {
1124         struct moving_io *io;
1125
1126         prt_printf(out, "%ps:", ctxt->fn);
1127         prt_newline(out);
1128         printbuf_indent_add(out, 2);
1129
1130         prt_printf(out, "reads: %u sectors %u",
1131                    atomic_read(&ctxt->read_ios),
1132                    atomic_read(&ctxt->read_sectors));
1133         prt_newline(out);
1134
1135         prt_printf(out, "writes: %u sectors %u",
1136                    atomic_read(&ctxt->write_ios),
1137                    atomic_read(&ctxt->write_sectors));
1138         prt_newline(out);
1139
1140         printbuf_indent_add(out, 2);
1141
1142         mutex_lock(&ctxt->lock);
1143         list_for_each_entry(io, &ctxt->ios, io_list) {
1144                 bch2_write_op_to_text(out, &io->write.op);
1145         }
1146         mutex_unlock(&ctxt->lock);
1147
1148         printbuf_indent_sub(out, 4);
1149 }
1150
1151 void bch2_fs_moving_ctxts_to_text(struct printbuf *out, struct bch_fs *c)
1152 {
1153         struct moving_context *ctxt;
1154
1155         mutex_lock(&c->moving_context_lock);
1156         list_for_each_entry(ctxt, &c->moving_context_list, list)
1157                 bch2_moving_ctxt_to_text(out, ctxt);
1158         mutex_unlock(&c->moving_context_lock);
1159 }
1160
1161 void bch2_fs_move_init(struct bch_fs *c)
1162 {
1163         INIT_LIST_HEAD(&c->moving_context_list);
1164         mutex_init(&c->moving_context_lock);
1165
1166         INIT_LIST_HEAD(&c->data_progress_list);
1167         mutex_init(&c->data_progress_lock);
1168 }