]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_background.c
Update bcachefs sources to bdf6d7c135 fixup! bcachefs: Kill journal buf bloom filter
[bcachefs-tools-debian] / libbcachefs / alloc_background.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include "bcachefs.h"
3 #include "alloc_background.h"
4 #include "alloc_foreground.h"
5 #include "btree_cache.h"
6 #include "btree_io.h"
7 #include "btree_key_cache.h"
8 #include "btree_update.h"
9 #include "btree_update_interior.h"
10 #include "btree_gc.h"
11 #include "buckets.h"
12 #include "buckets_waiting_for_journal.h"
13 #include "clock.h"
14 #include "debug.h"
15 #include "ec.h"
16 #include "error.h"
17 #include "lru.h"
18 #include "recovery.h"
19 #include "varint.h"
20
21 #include <linux/kthread.h>
22 #include <linux/math64.h>
23 #include <linux/random.h>
24 #include <linux/rculist.h>
25 #include <linux/rcupdate.h>
26 #include <linux/sched/task.h>
27 #include <linux/sort.h>
28 #include <trace/events/bcachefs.h>
29
30 /* Persistent alloc info: */
31
32 static const unsigned BCH_ALLOC_V1_FIELD_BYTES[] = {
33 #define x(name, bits) [BCH_ALLOC_FIELD_V1_##name] = bits / 8,
34         BCH_ALLOC_FIELDS_V1()
35 #undef x
36 };
37
38 struct bkey_alloc_unpacked {
39         u64             journal_seq;
40         u64             bucket;
41         u8              dev;
42         u8              gen;
43         u8              oldest_gen;
44         u8              data_type;
45         bool            need_discard:1;
46         bool            need_inc_gen:1;
47 #define x(_name, _bits) u##_bits _name;
48         BCH_ALLOC_FIELDS_V2()
49 #undef  x
50 };
51
52 static inline u64 alloc_field_v1_get(const struct bch_alloc *a,
53                                      const void **p, unsigned field)
54 {
55         unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
56         u64 v;
57
58         if (!(a->fields & (1 << field)))
59                 return 0;
60
61         switch (bytes) {
62         case 1:
63                 v = *((const u8 *) *p);
64                 break;
65         case 2:
66                 v = le16_to_cpup(*p);
67                 break;
68         case 4:
69                 v = le32_to_cpup(*p);
70                 break;
71         case 8:
72                 v = le64_to_cpup(*p);
73                 break;
74         default:
75                 BUG();
76         }
77
78         *p += bytes;
79         return v;
80 }
81
82 static inline void alloc_field_v1_put(struct bkey_i_alloc *a, void **p,
83                                       unsigned field, u64 v)
84 {
85         unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
86
87         if (!v)
88                 return;
89
90         a->v.fields |= 1 << field;
91
92         switch (bytes) {
93         case 1:
94                 *((u8 *) *p) = v;
95                 break;
96         case 2:
97                 *((__le16 *) *p) = cpu_to_le16(v);
98                 break;
99         case 4:
100                 *((__le32 *) *p) = cpu_to_le32(v);
101                 break;
102         case 8:
103                 *((__le64 *) *p) = cpu_to_le64(v);
104                 break;
105         default:
106                 BUG();
107         }
108
109         *p += bytes;
110 }
111
112 static void bch2_alloc_unpack_v1(struct bkey_alloc_unpacked *out,
113                                  struct bkey_s_c k)
114 {
115         const struct bch_alloc *in = bkey_s_c_to_alloc(k).v;
116         const void *d = in->data;
117         unsigned idx = 0;
118
119         out->gen = in->gen;
120
121 #define x(_name, _bits) out->_name = alloc_field_v1_get(in, &d, idx++);
122         BCH_ALLOC_FIELDS_V1()
123 #undef  x
124 }
125
126 static int bch2_alloc_unpack_v2(struct bkey_alloc_unpacked *out,
127                                 struct bkey_s_c k)
128 {
129         struct bkey_s_c_alloc_v2 a = bkey_s_c_to_alloc_v2(k);
130         const u8 *in = a.v->data;
131         const u8 *end = bkey_val_end(a);
132         unsigned fieldnr = 0;
133         int ret;
134         u64 v;
135
136         out->gen        = a.v->gen;
137         out->oldest_gen = a.v->oldest_gen;
138         out->data_type  = a.v->data_type;
139
140 #define x(_name, _bits)                                                 \
141         if (fieldnr < a.v->nr_fields) {                                 \
142                 ret = bch2_varint_decode_fast(in, end, &v);             \
143                 if (ret < 0)                                            \
144                         return ret;                                     \
145                 in += ret;                                              \
146         } else {                                                        \
147                 v = 0;                                                  \
148         }                                                               \
149         out->_name = v;                                                 \
150         if (v != out->_name)                                            \
151                 return -1;                                              \
152         fieldnr++;
153
154         BCH_ALLOC_FIELDS_V2()
155 #undef  x
156         return 0;
157 }
158
159 static int bch2_alloc_unpack_v3(struct bkey_alloc_unpacked *out,
160                                 struct bkey_s_c k)
161 {
162         struct bkey_s_c_alloc_v3 a = bkey_s_c_to_alloc_v3(k);
163         const u8 *in = a.v->data;
164         const u8 *end = bkey_val_end(a);
165         unsigned fieldnr = 0;
166         int ret;
167         u64 v;
168
169         out->gen        = a.v->gen;
170         out->oldest_gen = a.v->oldest_gen;
171         out->data_type  = a.v->data_type;
172         out->need_discard = BCH_ALLOC_V3_NEED_DISCARD(a.v);
173         out->need_inc_gen = BCH_ALLOC_V3_NEED_INC_GEN(a.v);
174         out->journal_seq = le64_to_cpu(a.v->journal_seq);
175
176 #define x(_name, _bits)                                                 \
177         if (fieldnr < a.v->nr_fields) {                                 \
178                 ret = bch2_varint_decode_fast(in, end, &v);             \
179                 if (ret < 0)                                            \
180                         return ret;                                     \
181                 in += ret;                                              \
182         } else {                                                        \
183                 v = 0;                                                  \
184         }                                                               \
185         out->_name = v;                                                 \
186         if (v != out->_name)                                            \
187                 return -1;                                              \
188         fieldnr++;
189
190         BCH_ALLOC_FIELDS_V2()
191 #undef  x
192         return 0;
193 }
194
195 static struct bkey_alloc_unpacked bch2_alloc_unpack(struct bkey_s_c k)
196 {
197         struct bkey_alloc_unpacked ret = {
198                 .dev    = k.k->p.inode,
199                 .bucket = k.k->p.offset,
200                 .gen    = 0,
201         };
202
203         switch (k.k->type) {
204         case KEY_TYPE_alloc:
205                 bch2_alloc_unpack_v1(&ret, k);
206                 break;
207         case KEY_TYPE_alloc_v2:
208                 bch2_alloc_unpack_v2(&ret, k);
209                 break;
210         case KEY_TYPE_alloc_v3:
211                 bch2_alloc_unpack_v3(&ret, k);
212                 break;
213         }
214
215         return ret;
216 }
217
218 void bch2_alloc_to_v4(struct bkey_s_c k, struct bch_alloc_v4 *out)
219 {
220         if (k.k->type == KEY_TYPE_alloc_v4) {
221                 *out = *bkey_s_c_to_alloc_v4(k).v;
222         } else {
223                 struct bkey_alloc_unpacked u = bch2_alloc_unpack(k);
224
225                 *out = (struct bch_alloc_v4) {
226                         .journal_seq            = u.journal_seq,
227                         .flags                  = u.need_discard,
228                         .gen                    = u.gen,
229                         .oldest_gen             = u.oldest_gen,
230                         .data_type              = u.data_type,
231                         .stripe_redundancy      = u.stripe_redundancy,
232                         .dirty_sectors          = u.dirty_sectors,
233                         .cached_sectors         = u.cached_sectors,
234                         .io_time[READ]          = u.read_time,
235                         .io_time[WRITE]         = u.write_time,
236                         .stripe                 = u.stripe,
237                 };
238         }
239 }
240
241 struct bkey_i_alloc_v4 *bch2_alloc_to_v4_mut(struct btree_trans *trans, struct bkey_s_c k)
242 {
243         struct bkey_i_alloc_v4 *ret;
244
245         if (k.k->type == KEY_TYPE_alloc_v4) {
246                 ret = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
247                 if (!IS_ERR(ret))
248                         bkey_reassemble(&ret->k_i, k);
249         } else {
250                 ret = bch2_trans_kmalloc(trans, sizeof(*ret));
251                 if (!IS_ERR(ret)) {
252                         bkey_alloc_v4_init(&ret->k_i);
253                         ret->k.p = k.k->p;
254                         bch2_alloc_to_v4(k, &ret->v);
255                 }
256         }
257         return ret;
258 }
259
260 struct bkey_i_alloc_v4 *
261 bch2_trans_start_alloc_update(struct btree_trans *trans, struct btree_iter *iter,
262                               struct bpos pos)
263 {
264         struct bkey_s_c k;
265         struct bkey_i_alloc_v4 *a;
266         int ret;
267
268         bch2_trans_iter_init(trans, iter, BTREE_ID_alloc, pos,
269                              BTREE_ITER_WITH_UPDATES|
270                              BTREE_ITER_CACHED|
271                              BTREE_ITER_INTENT);
272         k = bch2_btree_iter_peek_slot(iter);
273         ret = bkey_err(k);
274         if (ret) {
275                 bch2_trans_iter_exit(trans, iter);
276                 return ERR_PTR(ret);
277         }
278
279         a = bch2_alloc_to_v4_mut(trans, k);
280         if (IS_ERR(a))
281                 bch2_trans_iter_exit(trans, iter);
282         return a;
283 }
284
285 static unsigned bch_alloc_v1_val_u64s(const struct bch_alloc *a)
286 {
287         unsigned i, bytes = offsetof(struct bch_alloc, data);
288
289         for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_V1_FIELD_BYTES); i++)
290                 if (a->fields & (1 << i))
291                         bytes += BCH_ALLOC_V1_FIELD_BYTES[i];
292
293         return DIV_ROUND_UP(bytes, sizeof(u64));
294 }
295
296 int bch2_alloc_v1_invalid(const struct bch_fs *c, struct bkey_s_c k,
297                           int rw, struct printbuf *err)
298 {
299         struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
300
301         /* allow for unknown fields */
302         if (bkey_val_u64s(a.k) < bch_alloc_v1_val_u64s(a.v)) {
303                 pr_buf(err, "incorrect value size (%zu < %u)",
304                        bkey_val_u64s(a.k), bch_alloc_v1_val_u64s(a.v));
305                 return -EINVAL;
306         }
307
308         return 0;
309 }
310
311 int bch2_alloc_v2_invalid(const struct bch_fs *c, struct bkey_s_c k,
312                           int rw, struct printbuf *err)
313 {
314         struct bkey_alloc_unpacked u;
315
316         if (bch2_alloc_unpack_v2(&u, k)) {
317                 pr_buf(err, "unpack error");
318                 return -EINVAL;
319         }
320
321         return 0;
322 }
323
324 int bch2_alloc_v3_invalid(const struct bch_fs *c, struct bkey_s_c k,
325                           int rw, struct printbuf *err)
326 {
327         struct bkey_alloc_unpacked u;
328
329         if (bch2_alloc_unpack_v3(&u, k)) {
330                 pr_buf(err, "unpack error");
331                 return -EINVAL;
332         }
333
334         return 0;
335 }
336
337 int bch2_alloc_v4_invalid(const struct bch_fs *c, struct bkey_s_c k,
338                           int rw, struct printbuf *err)
339 {
340         struct bkey_s_c_alloc_v4 a = bkey_s_c_to_alloc_v4(k);
341
342         if (bkey_val_bytes(k.k) != sizeof(struct bch_alloc_v4)) {
343                 pr_buf(err, "bad val size (%zu != %zu)",
344                        bkey_val_bytes(k.k), sizeof(struct bch_alloc_v4));
345                 return -EINVAL;
346         }
347
348         if (rw == WRITE) {
349                 if (alloc_data_type(*a.v, a.v->data_type) != a.v->data_type) {
350                         pr_buf(err, "invalid data type (got %u should be %u)",
351                                a.v->data_type, alloc_data_type(*a.v, a.v->data_type));
352                         return -EINVAL;
353                 }
354
355                 switch (a.v->data_type) {
356                 case BCH_DATA_free:
357                 case BCH_DATA_need_gc_gens:
358                 case BCH_DATA_need_discard:
359                         if (a.v->dirty_sectors ||
360                             a.v->cached_sectors ||
361                             a.v->stripe) {
362                                 pr_buf(err, "empty data type free but have data");
363                                 return -EINVAL;
364                         }
365                         break;
366                 case BCH_DATA_sb:
367                 case BCH_DATA_journal:
368                 case BCH_DATA_btree:
369                 case BCH_DATA_user:
370                 case BCH_DATA_parity:
371                         if (!a.v->dirty_sectors) {
372                                 pr_buf(err, "data_type %s but dirty_sectors==0",
373                                        bch2_data_types[a.v->data_type]);
374                                 return -EINVAL;
375                         }
376                         break;
377                 case BCH_DATA_cached:
378                         if (!a.v->cached_sectors ||
379                             a.v->dirty_sectors ||
380                             a.v->stripe) {
381                                 pr_buf(err, "data type inconsistency");
382                                 return -EINVAL;
383                         }
384
385                         if (!a.v->io_time[READ] &&
386                             test_bit(BCH_FS_CHECK_ALLOC_TO_LRU_REFS_DONE, &c->flags)) {
387                                 pr_buf(err, "cached bucket with read_time == 0");
388                                 return -EINVAL;
389                         }
390                         break;
391                 case BCH_DATA_stripe:
392                         if (!a.v->stripe) {
393                                 pr_buf(err, "data_type %s but stripe==0",
394                                        bch2_data_types[a.v->data_type]);
395                                 return -EINVAL;
396                         }
397                         break;
398                 }
399         }
400
401         return 0;
402 }
403
404 void bch2_alloc_v4_swab(struct bkey_s k)
405 {
406         struct bch_alloc_v4 *a = bkey_s_to_alloc_v4(k).v;
407
408         a->journal_seq          = swab64(a->journal_seq);
409         a->flags                = swab32(a->flags);
410         a->dirty_sectors        = swab32(a->dirty_sectors);
411         a->cached_sectors       = swab32(a->cached_sectors);
412         a->io_time[0]           = swab64(a->io_time[0]);
413         a->io_time[1]           = swab64(a->io_time[1]);
414         a->stripe               = swab32(a->stripe);
415         a->nr_external_backpointers = swab32(a->nr_external_backpointers);
416 }
417
418 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c, struct bkey_s_c k)
419 {
420         struct bch_alloc_v4 a;
421
422         bch2_alloc_to_v4(k, &a);
423
424         pr_buf(out, "gen %u oldest_gen %u data_type %s journal_seq %llu need_discard %llu need_inc_gen %llu",
425                a.gen, a.oldest_gen, bch2_data_types[a.data_type],
426                a.journal_seq,
427                BCH_ALLOC_V4_NEED_DISCARD(&a),
428                BCH_ALLOC_V4_NEED_INC_GEN(&a));
429         pr_buf(out, " dirty_sectors %u",        a.dirty_sectors);
430         pr_buf(out, " cached_sectors %u",       a.cached_sectors);
431         pr_buf(out, " stripe %u",               a.stripe);
432         pr_buf(out, " stripe_redundancy %u",    a.stripe_redundancy);
433         pr_buf(out, " read_time %llu",          a.io_time[READ]);
434         pr_buf(out, " write_time %llu",         a.io_time[WRITE]);
435 }
436
437 int bch2_alloc_read(struct bch_fs *c)
438 {
439         struct btree_trans trans;
440         struct btree_iter iter;
441         struct bkey_s_c k;
442         struct bch_alloc_v4 a;
443         struct bch_dev *ca;
444         int ret;
445
446         bch2_trans_init(&trans, c, 0, 0);
447
448         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
449                            BTREE_ITER_PREFETCH, k, ret) {
450                 /*
451                  * Not a fsck error because this is checked/repaired by
452                  * bch2_check_alloc_key() which runs later:
453                  */
454                 if (!bch2_dev_bucket_exists(c, k.k->p))
455                         continue;
456
457                 ca = bch_dev_bkey_exists(c, k.k->p.inode);
458                 bch2_alloc_to_v4(k, &a);
459
460                 *bucket_gen(ca, k.k->p.offset) = a.gen;
461         }
462         bch2_trans_iter_exit(&trans, &iter);
463
464         bch2_trans_exit(&trans);
465
466         if (ret)
467                 bch_err(c, "error reading alloc info: %i", ret);
468
469         return ret;
470 }
471
472 /* Free space/discard btree: */
473
474 static int bch2_bucket_do_index(struct btree_trans *trans,
475                                 struct bkey_s_c alloc_k,
476                                 const struct bch_alloc_v4 *a,
477                                 bool set)
478 {
479         struct bch_fs *c = trans->c;
480         struct bch_dev *ca = bch_dev_bkey_exists(c, alloc_k.k->p.inode);
481         struct btree_iter iter;
482         struct bkey_s_c old;
483         struct bkey_i *k;
484         enum btree_id btree;
485         enum bch_bkey_type old_type = !set ? KEY_TYPE_set : KEY_TYPE_deleted;
486         enum bch_bkey_type new_type =  set ? KEY_TYPE_set : KEY_TYPE_deleted;
487         struct printbuf buf = PRINTBUF;
488         int ret;
489
490         if (a->data_type != BCH_DATA_free &&
491             a->data_type != BCH_DATA_need_discard)
492                 return 0;
493
494         k = bch2_trans_kmalloc(trans, sizeof(*k));
495         if (IS_ERR(k))
496                 return PTR_ERR(k);
497
498         bkey_init(&k->k);
499         k->k.type = new_type;
500
501         switch (a->data_type) {
502         case BCH_DATA_free:
503                 btree = BTREE_ID_freespace;
504                 k->k.p = alloc_freespace_pos(alloc_k.k->p, *a);
505                 bch2_key_resize(&k->k, 1);
506                 break;
507         case BCH_DATA_need_discard:
508                 btree = BTREE_ID_need_discard;
509                 k->k.p = alloc_k.k->p;
510                 break;
511         default:
512                 return 0;
513         }
514
515         bch2_trans_iter_init(trans, &iter, btree,
516                              bkey_start_pos(&k->k),
517                              BTREE_ITER_INTENT);
518         old = bch2_btree_iter_peek_slot(&iter);
519         ret = bkey_err(old);
520         if (ret)
521                 goto err;
522
523         if (ca->mi.freespace_initialized &&
524             bch2_trans_inconsistent_on(old.k->type != old_type, trans,
525                         "incorrect key when %s %s btree (got %s should be %s)\n"
526                         "  for %s",
527                         set ? "setting" : "clearing",
528                         bch2_btree_ids[btree],
529                         bch2_bkey_types[old.k->type],
530                         bch2_bkey_types[old_type],
531                         (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
532                 ret = -EIO;
533                 goto err;
534         }
535
536         ret = bch2_trans_update(trans, &iter, k, 0);
537 err:
538         bch2_trans_iter_exit(trans, &iter);
539         printbuf_exit(&buf);
540         return ret;
541 }
542
543 int bch2_trans_mark_alloc(struct btree_trans *trans,
544                           enum btree_id btree_id, unsigned level,
545                           struct bkey_s_c old, struct bkey_i *new,
546                           unsigned flags)
547 {
548         struct bch_fs *c = trans->c;
549         struct bch_alloc_v4 old_a, *new_a;
550         u64 old_lru, new_lru;
551         int ret = 0;
552
553         /*
554          * Deletion only happens in the device removal path, with
555          * BTREE_TRIGGER_NORUN:
556          */
557         BUG_ON(new->k.type != KEY_TYPE_alloc_v4);
558
559         bch2_alloc_to_v4(old, &old_a);
560         new_a = &bkey_i_to_alloc_v4(new)->v;
561
562         new_a->data_type = alloc_data_type(*new_a, new_a->data_type);
563
564         if (new_a->dirty_sectors > old_a.dirty_sectors ||
565             new_a->cached_sectors > old_a.cached_sectors) {
566                 new_a->io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
567                 new_a->io_time[WRITE]= max_t(u64, 1, atomic64_read(&c->io_clock[WRITE].now));
568                 SET_BCH_ALLOC_V4_NEED_INC_GEN(new_a, true);
569                 SET_BCH_ALLOC_V4_NEED_DISCARD(new_a, true);
570         }
571
572         if (data_type_is_empty(new_a->data_type) &&
573             BCH_ALLOC_V4_NEED_INC_GEN(new_a) &&
574             !bch2_bucket_is_open_safe(c, new->k.p.inode, new->k.p.offset)) {
575                 new_a->gen++;
576                 SET_BCH_ALLOC_V4_NEED_INC_GEN(new_a, false);
577         }
578
579         if (old_a.data_type != new_a->data_type ||
580             (new_a->data_type == BCH_DATA_free &&
581              alloc_freespace_genbits(old_a) != alloc_freespace_genbits(*new_a))) {
582                 ret =   bch2_bucket_do_index(trans, old, &old_a, false) ?:
583                         bch2_bucket_do_index(trans, bkey_i_to_s_c(new), new_a, true);
584                 if (ret)
585                         return ret;
586         }
587
588         if (new_a->data_type == BCH_DATA_cached &&
589             !new_a->io_time[READ])
590                 new_a->io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
591
592         old_lru = alloc_lru_idx(old_a);
593         new_lru = alloc_lru_idx(*new_a);
594
595         if (old_lru != new_lru) {
596                 ret = bch2_lru_change(trans, new->k.p.inode, new->k.p.offset,
597                                       old_lru, &new_lru, old);
598                 if (ret)
599                         return ret;
600
601                 if (new_a->data_type == BCH_DATA_cached)
602                         new_a->io_time[READ] = new_lru;
603         }
604
605         return 0;
606 }
607
608 static int bch2_check_alloc_key(struct btree_trans *trans,
609                                 struct btree_iter *alloc_iter)
610 {
611         struct bch_fs *c = trans->c;
612         struct bch_dev *ca;
613         struct btree_iter discard_iter, freespace_iter;
614         struct bch_alloc_v4 a;
615         unsigned discard_key_type, freespace_key_type;
616         struct bkey_s_c alloc_k, k;
617         struct printbuf buf = PRINTBUF;
618         struct printbuf buf2 = PRINTBUF;
619         int ret;
620
621         alloc_k = bch2_btree_iter_peek(alloc_iter);
622         if (!alloc_k.k)
623                 return 0;
624
625         ret = bkey_err(alloc_k);
626         if (ret)
627                 return ret;
628
629         if (fsck_err_on(!bch2_dev_bucket_exists(c, alloc_k.k->p), c,
630                         "alloc key for invalid device:bucket %llu:%llu",
631                         alloc_k.k->p.inode, alloc_k.k->p.offset))
632                 return bch2_btree_delete_at(trans, alloc_iter, 0);
633
634         ca = bch_dev_bkey_exists(c, alloc_k.k->p.inode);
635         if (!ca->mi.freespace_initialized)
636                 return 0;
637
638         bch2_alloc_to_v4(alloc_k, &a);
639
640         discard_key_type = a.data_type == BCH_DATA_need_discard
641                 ? KEY_TYPE_set : 0;
642         freespace_key_type = a.data_type == BCH_DATA_free
643                 ? KEY_TYPE_set : 0;
644
645         bch2_trans_iter_init(trans, &discard_iter, BTREE_ID_need_discard,
646                              alloc_k.k->p, 0);
647         bch2_trans_iter_init(trans, &freespace_iter, BTREE_ID_freespace,
648                              alloc_freespace_pos(alloc_k.k->p, a), 0);
649
650         k = bch2_btree_iter_peek_slot(&discard_iter);
651         ret = bkey_err(k);
652         if (ret)
653                 goto err;
654
655         if (fsck_err_on(k.k->type != discard_key_type, c,
656                         "incorrect key in need_discard btree (got %s should be %s)\n"
657                         "  %s",
658                         bch2_bkey_types[k.k->type],
659                         bch2_bkey_types[discard_key_type],
660                         (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
661                 struct bkey_i *update =
662                         bch2_trans_kmalloc(trans, sizeof(*update));
663
664                 ret = PTR_ERR_OR_ZERO(update);
665                 if (ret)
666                         goto err;
667
668                 bkey_init(&update->k);
669                 update->k.type  = discard_key_type;
670                 update->k.p     = discard_iter.pos;
671
672                 ret = bch2_trans_update(trans, &discard_iter, update, 0);
673                 if (ret)
674                         goto err;
675         }
676
677         k = bch2_btree_iter_peek_slot(&freespace_iter);
678         ret = bkey_err(k);
679         if (ret)
680                 goto err;
681
682         if (fsck_err_on(k.k->type != freespace_key_type, c,
683                         "incorrect key in freespace btree (got %s should be %s)\n"
684                         "  %s",
685                         bch2_bkey_types[k.k->type],
686                         bch2_bkey_types[freespace_key_type],
687                         (printbuf_reset(&buf),
688                          bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
689                 struct bkey_i *update =
690                         bch2_trans_kmalloc(trans, sizeof(*update));
691
692                 ret = PTR_ERR_OR_ZERO(update);
693                 if (ret)
694                         goto err;
695
696                 bkey_init(&update->k);
697                 update->k.type  = freespace_key_type;
698                 update->k.p     = freespace_iter.pos;
699                 bch2_key_resize(&update->k, 1);
700
701                 ret = bch2_trans_update(trans, &freespace_iter, update, 0);
702                 if (ret)
703                         goto err;
704         }
705 err:
706 fsck_err:
707         bch2_trans_iter_exit(trans, &freespace_iter);
708         bch2_trans_iter_exit(trans, &discard_iter);
709         printbuf_exit(&buf2);
710         printbuf_exit(&buf);
711         return ret;
712 }
713
714 static int bch2_check_discard_freespace_key(struct btree_trans *trans,
715                                             struct btree_iter *iter)
716 {
717         struct bch_fs *c = trans->c;
718         struct btree_iter alloc_iter;
719         struct bkey_s_c k, freespace_k;
720         struct bch_alloc_v4 a;
721         u64 genbits;
722         struct bpos pos;
723         enum bch_data_type state = iter->btree_id == BTREE_ID_need_discard
724                 ? BCH_DATA_need_discard
725                 : BCH_DATA_free;
726         struct printbuf buf = PRINTBUF;
727         int ret;
728
729         freespace_k = bch2_btree_iter_peek(iter);
730         if (!freespace_k.k)
731                 return 1;
732
733         ret = bkey_err(freespace_k);
734         if (ret)
735                 return ret;
736
737         pos = iter->pos;
738         pos.offset &= ~(~0ULL << 56);
739         genbits = iter->pos.offset & (~0ULL << 56);
740
741         bch2_trans_iter_init(trans, &alloc_iter, BTREE_ID_alloc, pos, 0);
742
743         if (fsck_err_on(!bch2_dev_bucket_exists(c, pos), c,
744                         "entry in %s btree for nonexistant dev:bucket %llu:%llu",
745                         bch2_btree_ids[iter->btree_id], pos.inode, pos.offset))
746                 goto delete;
747
748         k = bch2_btree_iter_peek_slot(&alloc_iter);
749         ret = bkey_err(k);
750         if (ret)
751                 goto err;
752
753         bch2_alloc_to_v4(k, &a);
754
755         if (fsck_err_on(a.data_type != state ||
756                         (state == BCH_DATA_free &&
757                          genbits != alloc_freespace_genbits(a)), c,
758                         "%s\n  incorrectly set in %s index (free %u, genbits %llu should be %llu)",
759                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf),
760                         bch2_btree_ids[iter->btree_id],
761                         a.data_type == state,
762                         genbits >> 56, alloc_freespace_genbits(a) >> 56))
763                 goto delete;
764 out:
765 err:
766 fsck_err:
767         bch2_trans_iter_exit(trans, &alloc_iter);
768         printbuf_exit(&buf);
769         return ret;
770 delete:
771         ret = bch2_btree_delete_extent_at(trans, iter,
772                         iter->btree_id == BTREE_ID_freespace ? 1 : 0, 0);
773         goto out;
774 }
775
776 int bch2_check_alloc_info(struct bch_fs *c)
777 {
778         struct btree_trans trans;
779         struct btree_iter iter;
780         struct bkey_s_c k;
781         int ret = 0;
782
783         bch2_trans_init(&trans, c, 0, 0);
784
785         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
786                            BTREE_ITER_PREFETCH, k, ret) {
787                 ret = __bch2_trans_do(&trans, NULL, NULL, 0,
788                         bch2_check_alloc_key(&trans, &iter));
789                 if (ret)
790                         break;
791         }
792         bch2_trans_iter_exit(&trans, &iter);
793
794         if (ret)
795                 goto err;
796
797         bch2_trans_iter_init(&trans, &iter, BTREE_ID_need_discard, POS_MIN,
798                              BTREE_ITER_PREFETCH);
799         while (1) {
800                 ret = __bch2_trans_do(&trans, NULL, NULL, 0,
801                         bch2_check_discard_freespace_key(&trans, &iter));
802                 if (ret)
803                         break;
804
805                 bch2_btree_iter_set_pos(&iter, bpos_nosnap_successor(iter.pos));
806         }
807         bch2_trans_iter_exit(&trans, &iter);
808
809         if (ret)
810                 goto err;
811
812         bch2_trans_iter_init(&trans, &iter, BTREE_ID_freespace, POS_MIN,
813                              BTREE_ITER_PREFETCH);
814         while (1) {
815                 ret = __bch2_trans_do(&trans, NULL, NULL, 0,
816                         bch2_check_discard_freespace_key(&trans, &iter));
817                 if (ret)
818                         break;
819
820                 bch2_btree_iter_set_pos(&iter, bpos_nosnap_successor(iter.pos));
821         }
822         bch2_trans_iter_exit(&trans, &iter);
823 err:
824         bch2_trans_exit(&trans);
825         return ret < 0 ? ret : 0;
826 }
827
828 static int bch2_check_alloc_to_lru_ref(struct btree_trans *trans,
829                                        struct btree_iter *alloc_iter)
830 {
831         struct bch_fs *c = trans->c;
832         struct btree_iter lru_iter;
833         struct bch_alloc_v4 a;
834         struct bkey_s_c alloc_k, k;
835         struct printbuf buf = PRINTBUF;
836         struct printbuf buf2 = PRINTBUF;
837         int ret;
838
839         alloc_k = bch2_btree_iter_peek(alloc_iter);
840         if (!alloc_k.k)
841                 return 0;
842
843         ret = bkey_err(alloc_k);
844         if (ret)
845                 return ret;
846
847         bch2_alloc_to_v4(alloc_k, &a);
848
849         if (a.data_type != BCH_DATA_cached)
850                 return 0;
851
852         bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
853                              POS(alloc_k.k->p.inode, a.io_time[READ]), 0);
854
855         k = bch2_btree_iter_peek_slot(&lru_iter);
856         ret = bkey_err(k);
857         if (ret)
858                 goto err;
859
860         if (fsck_err_on(!a.io_time[READ], c,
861                         "cached bucket with read_time 0\n"
862                         "  %s",
863                 (printbuf_reset(&buf),
864                  bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf)) ||
865             fsck_err_on(k.k->type != KEY_TYPE_lru ||
866                         le64_to_cpu(bkey_s_c_to_lru(k).v->idx) != alloc_k.k->p.offset, c,
867                         "incorrect/missing lru entry\n"
868                         "  %s\n"
869                         "  %s",
870                         (printbuf_reset(&buf),
871                          bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf),
872                         (bch2_bkey_val_to_text(&buf2, c, k), buf2.buf))) {
873                 u64 read_time = a.io_time[READ];
874
875                 if (!a.io_time[READ])
876                         a.io_time[READ] = atomic64_read(&c->io_clock[READ].now);
877
878                 ret = bch2_lru_set(trans,
879                                    alloc_k.k->p.inode,
880                                    alloc_k.k->p.offset,
881                                    &a.io_time[READ]);
882                 if (ret)
883                         goto err;
884
885                 if (a.io_time[READ] != read_time) {
886                         struct bkey_i_alloc_v4 *a_mut =
887                                 bch2_alloc_to_v4_mut(trans, alloc_k);
888                         ret = PTR_ERR_OR_ZERO(a_mut);
889                         if (ret)
890                                 goto err;
891
892                         a_mut->v.io_time[READ] = a.io_time[READ];
893                         ret = bch2_trans_update(trans, alloc_iter,
894                                                 &a_mut->k_i, BTREE_TRIGGER_NORUN);
895                         if (ret)
896                                 goto err;
897                 }
898         }
899 err:
900 fsck_err:
901         bch2_trans_iter_exit(trans, &lru_iter);
902         printbuf_exit(&buf2);
903         printbuf_exit(&buf);
904         return ret;
905 }
906
907 int bch2_check_alloc_to_lru_refs(struct bch_fs *c)
908 {
909         struct btree_trans trans;
910         struct btree_iter iter;
911         struct bkey_s_c k;
912         int ret = 0;
913
914         bch2_trans_init(&trans, c, 0, 0);
915
916         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
917                            BTREE_ITER_PREFETCH, k, ret) {
918                 ret = __bch2_trans_do(&trans, NULL, NULL,
919                                       BTREE_INSERT_NOFAIL|
920                                       BTREE_INSERT_LAZY_RW,
921                         bch2_check_alloc_to_lru_ref(&trans, &iter));
922                 if (ret)
923                         break;
924         }
925         bch2_trans_iter_exit(&trans, &iter);
926
927         bch2_trans_exit(&trans);
928         return ret < 0 ? ret : 0;
929 }
930
931 static int bch2_clear_need_discard(struct btree_trans *trans, struct bpos pos,
932                                    struct bch_dev *ca, bool *discard_done)
933 {
934         struct bch_fs *c = trans->c;
935         struct btree_iter iter;
936         struct bkey_s_c k;
937         struct bkey_i_alloc_v4 *a;
938         struct printbuf buf = PRINTBUF;
939         int ret;
940
941         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, pos,
942                              BTREE_ITER_CACHED);
943         k = bch2_btree_iter_peek_slot(&iter);
944         ret = bkey_err(k);
945         if (ret)
946                 goto out;
947
948         a = bch2_alloc_to_v4_mut(trans, k);
949         ret = PTR_ERR_OR_ZERO(a);
950         if (ret)
951                 goto out;
952
953         if (BCH_ALLOC_V4_NEED_INC_GEN(&a->v)) {
954                 a->v.gen++;
955                 SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
956                 goto write;
957         }
958
959         if (bch2_trans_inconsistent_on(a->v.journal_seq > c->journal.flushed_seq_ondisk, trans,
960                         "clearing need_discard but journal_seq %llu > flushed_seq %llu\n"
961                         "%s",
962                         a->v.journal_seq,
963                         c->journal.flushed_seq_ondisk,
964                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
965                 ret = -EIO;
966                 goto out;
967         }
968
969         if (bch2_trans_inconsistent_on(a->v.data_type != BCH_DATA_need_discard, trans,
970                         "bucket incorrectly set in need_discard btree\n"
971                         "%s",
972                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
973                 ret = -EIO;
974                 goto out;
975         }
976
977         if (!*discard_done && ca->mi.discard && !c->opts.nochanges) {
978                 /*
979                  * This works without any other locks because this is the only
980                  * thread that removes items from the need_discard tree
981                  */
982                 bch2_trans_unlock(trans);
983                 blkdev_issue_discard(ca->disk_sb.bdev,
984                                      k.k->p.offset * ca->mi.bucket_size,
985                                      ca->mi.bucket_size,
986                                      GFP_KERNEL, 0);
987                 *discard_done = true;
988
989                 ret = bch2_trans_relock(trans) ? 0 : -EINTR;
990                 if (ret)
991                         goto out;
992         }
993
994         SET_BCH_ALLOC_V4_NEED_DISCARD(&a->v, false);
995         a->v.data_type = alloc_data_type(a->v, a->v.data_type);
996 write:
997         ret = bch2_trans_update(trans, &iter, &a->k_i, 0);
998 out:
999         bch2_trans_iter_exit(trans, &iter);
1000         printbuf_exit(&buf);
1001         return ret;
1002 }
1003
1004 static void bch2_do_discards_work(struct work_struct *work)
1005 {
1006         struct bch_fs *c = container_of(work, struct bch_fs, discard_work);
1007         struct bch_dev *ca = NULL;
1008         struct btree_trans trans;
1009         struct btree_iter iter;
1010         struct bkey_s_c k;
1011         u64 seen = 0, open = 0, need_journal_commit = 0, discarded = 0;
1012         int ret;
1013
1014         bch2_trans_init(&trans, c, 0, 0);
1015
1016         for_each_btree_key(&trans, iter, BTREE_ID_need_discard,
1017                            POS_MIN, 0, k, ret) {
1018                 bool discard_done = false;
1019
1020                 if (ca && k.k->p.inode != ca->dev_idx) {
1021                         percpu_ref_put(&ca->io_ref);
1022                         ca = NULL;
1023                 }
1024
1025                 if (!ca) {
1026                         ca = bch_dev_bkey_exists(c, k.k->p.inode);
1027                         if (!percpu_ref_tryget(&ca->io_ref)) {
1028                                 ca = NULL;
1029                                 bch2_btree_iter_set_pos(&iter, POS(k.k->p.inode + 1, 0));
1030                                 continue;
1031                         }
1032                 }
1033
1034                 seen++;
1035
1036                 if (bch2_bucket_is_open_safe(c, k.k->p.inode, k.k->p.offset)) {
1037                         open++;
1038                         continue;
1039                 }
1040
1041                 if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
1042                                 c->journal.flushed_seq_ondisk,
1043                                 k.k->p.inode, k.k->p.offset)) {
1044                         need_journal_commit++;
1045                         continue;
1046                 }
1047
1048                 ret = __bch2_trans_do(&trans, NULL, NULL,
1049                                       BTREE_INSERT_USE_RESERVE|
1050                                       BTREE_INSERT_NOFAIL,
1051                                 bch2_clear_need_discard(&trans, k.k->p, ca, &discard_done));
1052                 if (ret)
1053                         break;
1054
1055                 discarded++;
1056         }
1057         bch2_trans_iter_exit(&trans, &iter);
1058
1059         if (ca)
1060                 percpu_ref_put(&ca->io_ref);
1061
1062         bch2_trans_exit(&trans);
1063
1064         if (need_journal_commit * 2 > seen)
1065                 bch2_journal_flush_async(&c->journal, NULL);
1066
1067         percpu_ref_put(&c->writes);
1068
1069         trace_discard_buckets(c, seen, open, need_journal_commit, discarded, ret);
1070 }
1071
1072 void bch2_do_discards(struct bch_fs *c)
1073 {
1074         if (percpu_ref_tryget(&c->writes) &&
1075             !queue_work(system_long_wq, &c->discard_work))
1076                 percpu_ref_put(&c->writes);
1077 }
1078
1079 static int invalidate_one_bucket(struct btree_trans *trans, struct bch_dev *ca)
1080 {
1081         struct bch_fs *c = trans->c;
1082         struct btree_iter lru_iter, alloc_iter = { NULL };
1083         struct bkey_s_c k;
1084         struct bkey_i_alloc_v4 *a;
1085         u64 bucket, idx;
1086         struct printbuf buf = PRINTBUF;
1087         int ret;
1088
1089         bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
1090                              POS(ca->dev_idx, 0), 0);
1091 next_lru:
1092         k = bch2_btree_iter_peek(&lru_iter);
1093         ret = bkey_err(k);
1094         if (ret)
1095                 goto out;
1096
1097         if (!k.k || k.k->p.inode != ca->dev_idx)
1098                 goto out;
1099
1100         if (k.k->type != KEY_TYPE_lru) {
1101                 pr_buf(&buf, "non lru key in lru btree:\n  ");
1102                 bch2_bkey_val_to_text(&buf, c, k);
1103
1104                 if (!test_bit(BCH_FS_CHECK_LRUS_DONE, &c->flags)) {
1105                         bch_err(c, "%s", buf.buf);
1106                         bch2_btree_iter_advance(&lru_iter);
1107                         goto next_lru;
1108                 } else {
1109                         bch2_trans_inconsistent(trans, "%s", buf.buf);
1110                         ret = -EINVAL;
1111                         goto out;
1112                 }
1113         }
1114
1115         idx     = k.k->p.offset;
1116         bucket  = le64_to_cpu(bkey_s_c_to_lru(k).v->idx);
1117
1118         a = bch2_trans_start_alloc_update(trans, &alloc_iter,
1119                                           POS(ca->dev_idx, bucket));
1120         ret = PTR_ERR_OR_ZERO(a);
1121         if (ret)
1122                 goto out;
1123
1124         if (idx != alloc_lru_idx(a->v)) {
1125                 pr_buf(&buf, "alloc key does not point back to lru entry when invalidating bucket:\n  ");
1126                 bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&a->k_i));
1127                 pr_buf(&buf, "\n  ");
1128                 bch2_bkey_val_to_text(&buf, c, k);
1129
1130                 if (!test_bit(BCH_FS_CHECK_LRUS_DONE, &c->flags)) {
1131                         bch_err(c, "%s", buf.buf);
1132                         bch2_btree_iter_advance(&lru_iter);
1133                         goto next_lru;
1134                 } else {
1135                         bch2_trans_inconsistent(trans, "%s", buf.buf);
1136                         ret = -EINVAL;
1137                         goto out;
1138                 }
1139         }
1140
1141         SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
1142         a->v.gen++;
1143         a->v.data_type          = 0;
1144         a->v.dirty_sectors      = 0;
1145         a->v.cached_sectors     = 0;
1146         a->v.io_time[READ]      = atomic64_read(&c->io_clock[READ].now);
1147         a->v.io_time[WRITE]     = atomic64_read(&c->io_clock[WRITE].now);
1148
1149         ret = bch2_trans_update(trans, &alloc_iter, &a->k_i,
1150                                 BTREE_TRIGGER_BUCKET_INVALIDATE);
1151         if (ret)
1152                 goto out;
1153
1154         trace_invalidate_bucket(c, a->k.p.inode, a->k.p.offset);
1155 out:
1156         bch2_trans_iter_exit(trans, &alloc_iter);
1157         bch2_trans_iter_exit(trans, &lru_iter);
1158         printbuf_exit(&buf);
1159         return ret;
1160 }
1161
1162 static void bch2_do_invalidates_work(struct work_struct *work)
1163 {
1164         struct bch_fs *c = container_of(work, struct bch_fs, invalidate_work);
1165         struct bch_dev *ca;
1166         struct btree_trans trans;
1167         unsigned i;
1168         int ret = 0;
1169
1170         bch2_trans_init(&trans, c, 0, 0);
1171
1172         for_each_member_device(ca, c, i) {
1173                 s64 nr_to_invalidate =
1174                         should_invalidate_buckets(ca, bch2_dev_usage_read(ca));
1175
1176                 while (!ret && nr_to_invalidate-- >= 0)
1177                         ret = __bch2_trans_do(&trans, NULL, NULL,
1178                                               BTREE_INSERT_USE_RESERVE|
1179                                               BTREE_INSERT_NOFAIL,
1180                                         invalidate_one_bucket(&trans, ca));
1181         }
1182
1183         bch2_trans_exit(&trans);
1184         percpu_ref_put(&c->writes);
1185 }
1186
1187 void bch2_do_invalidates(struct bch_fs *c)
1188 {
1189         if (percpu_ref_tryget(&c->writes))
1190                 queue_work(system_long_wq, &c->invalidate_work);
1191 }
1192
1193 static int bch2_dev_freespace_init(struct bch_fs *c, struct bch_dev *ca)
1194 {
1195         struct btree_trans trans;
1196         struct btree_iter iter;
1197         struct bkey_s_c k;
1198         struct bch_alloc_v4 a;
1199         struct bch_member *m;
1200         int ret;
1201
1202         bch2_trans_init(&trans, c, 0, 0);
1203
1204         for_each_btree_key(&trans, iter, BTREE_ID_alloc,
1205                            POS(ca->dev_idx, ca->mi.first_bucket),
1206                            BTREE_ITER_SLOTS|
1207                            BTREE_ITER_PREFETCH, k, ret) {
1208                 if (iter.pos.offset >= ca->mi.nbuckets)
1209                         break;
1210
1211                 bch2_alloc_to_v4(k, &a);
1212                 ret = __bch2_trans_do(&trans, NULL, NULL,
1213                                       BTREE_INSERT_LAZY_RW,
1214                                  bch2_bucket_do_index(&trans, k, &a, true));
1215                 if (ret)
1216                         break;
1217         }
1218         bch2_trans_iter_exit(&trans, &iter);
1219
1220         bch2_trans_exit(&trans);
1221
1222         if (ret) {
1223                 bch_err(ca, "error initializing free space: %i", ret);
1224                 return ret;
1225         }
1226
1227         mutex_lock(&c->sb_lock);
1228         m = bch2_sb_get_members(c->disk_sb.sb)->members + ca->dev_idx;
1229         SET_BCH_MEMBER_FREESPACE_INITIALIZED(m, true);
1230         mutex_unlock(&c->sb_lock);
1231
1232         return ret;
1233 }
1234
1235 int bch2_fs_freespace_init(struct bch_fs *c)
1236 {
1237         struct bch_dev *ca;
1238         unsigned i;
1239         int ret = 0;
1240         bool doing_init = false;
1241
1242         /*
1243          * We can crash during the device add path, so we need to check this on
1244          * every mount:
1245          */
1246
1247         for_each_member_device(ca, c, i) {
1248                 if (ca->mi.freespace_initialized)
1249                         continue;
1250
1251                 if (!doing_init) {
1252                         bch_info(c, "initializing freespace");
1253                         doing_init = true;
1254                 }
1255
1256                 ret = bch2_dev_freespace_init(c, ca);
1257                 if (ret) {
1258                         percpu_ref_put(&ca->ref);
1259                         return ret;
1260                 }
1261         }
1262
1263         if (doing_init) {
1264                 mutex_lock(&c->sb_lock);
1265                 bch2_write_super(c);
1266                 mutex_unlock(&c->sb_lock);
1267
1268                 bch_verbose(c, "done initializing freespace");
1269         }
1270
1271         return ret;
1272 }
1273
1274 /* Bucket IO clocks: */
1275
1276 int bch2_bucket_io_time_reset(struct btree_trans *trans, unsigned dev,
1277                               size_t bucket_nr, int rw)
1278 {
1279         struct bch_fs *c = trans->c;
1280         struct btree_iter iter;
1281         struct bkey_i_alloc_v4 *a;
1282         u64 now;
1283         int ret = 0;
1284
1285         a = bch2_trans_start_alloc_update(trans, &iter,  POS(dev, bucket_nr));
1286         ret = PTR_ERR_OR_ZERO(a);
1287         if (ret)
1288                 return ret;
1289
1290         now = atomic64_read(&c->io_clock[rw].now);
1291         if (a->v.io_time[rw] == now)
1292                 goto out;
1293
1294         a->v.io_time[rw] = now;
1295
1296         ret   = bch2_trans_update(trans, &iter, &a->k_i, 0) ?:
1297                 bch2_trans_commit(trans, NULL, NULL, 0);
1298 out:
1299         bch2_trans_iter_exit(trans, &iter);
1300         return ret;
1301 }
1302
1303 /* Startup/shutdown (ro/rw): */
1304
1305 void bch2_recalc_capacity(struct bch_fs *c)
1306 {
1307         struct bch_dev *ca;
1308         u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1309         unsigned bucket_size_max = 0;
1310         unsigned long ra_pages = 0;
1311         unsigned i;
1312
1313         lockdep_assert_held(&c->state_lock);
1314
1315         for_each_online_member(ca, c, i) {
1316                 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_disk->bdi;
1317
1318                 ra_pages += bdi->ra_pages;
1319         }
1320
1321         bch2_set_ra_pages(c, ra_pages);
1322
1323         for_each_rw_member(ca, c, i) {
1324                 u64 dev_reserve = 0;
1325
1326                 /*
1327                  * We need to reserve buckets (from the number
1328                  * of currently available buckets) against
1329                  * foreground writes so that mainly copygc can
1330                  * make forward progress.
1331                  *
1332                  * We need enough to refill the various reserves
1333                  * from scratch - copygc will use its entire
1334                  * reserve all at once, then run against when
1335                  * its reserve is refilled (from the formerly
1336                  * available buckets).
1337                  *
1338                  * This reserve is just used when considering if
1339                  * allocations for foreground writes must wait -
1340                  * not -ENOSPC calculations.
1341                  */
1342
1343                 dev_reserve += ca->nr_btree_reserve * 2;
1344                 dev_reserve += ca->mi.nbuckets >> 6; /* copygc reserve */
1345
1346                 dev_reserve += 1;       /* btree write point */
1347                 dev_reserve += 1;       /* copygc write point */
1348                 dev_reserve += 1;       /* rebalance write point */
1349
1350                 dev_reserve *= ca->mi.bucket_size;
1351
1352                 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1353                                              ca->mi.first_bucket);
1354
1355                 reserved_sectors += dev_reserve * 2;
1356
1357                 bucket_size_max = max_t(unsigned, bucket_size_max,
1358                                         ca->mi.bucket_size);
1359         }
1360
1361         gc_reserve = c->opts.gc_reserve_bytes
1362                 ? c->opts.gc_reserve_bytes >> 9
1363                 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1364
1365         reserved_sectors = max(gc_reserve, reserved_sectors);
1366
1367         reserved_sectors = min(reserved_sectors, capacity);
1368
1369         c->capacity = capacity - reserved_sectors;
1370
1371         c->bucket_size_max = bucket_size_max;
1372
1373         /* Wake up case someone was waiting for buckets */
1374         closure_wake_up(&c->freelist_wait);
1375 }
1376
1377 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1378 {
1379         struct open_bucket *ob;
1380         bool ret = false;
1381
1382         for (ob = c->open_buckets;
1383              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1384              ob++) {
1385                 spin_lock(&ob->lock);
1386                 if (ob->valid && !ob->on_partial_list &&
1387                     ob->dev == ca->dev_idx)
1388                         ret = true;
1389                 spin_unlock(&ob->lock);
1390         }
1391
1392         return ret;
1393 }
1394
1395 /* device goes ro: */
1396 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1397 {
1398         unsigned i;
1399
1400         /* First, remove device from allocation groups: */
1401
1402         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1403                 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1404
1405         /*
1406          * Capacity is calculated based off of devices in allocation groups:
1407          */
1408         bch2_recalc_capacity(c);
1409
1410         /* Next, close write points that point to this device... */
1411         for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1412                 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1413
1414         bch2_writepoint_stop(c, ca, &c->copygc_write_point);
1415         bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1416         bch2_writepoint_stop(c, ca, &c->btree_write_point);
1417
1418         mutex_lock(&c->btree_reserve_cache_lock);
1419         while (c->btree_reserve_cache_nr) {
1420                 struct btree_alloc *a =
1421                         &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1422
1423                 bch2_open_buckets_put(c, &a->ob);
1424         }
1425         mutex_unlock(&c->btree_reserve_cache_lock);
1426
1427         while (1) {
1428                 struct open_bucket *ob;
1429
1430                 spin_lock(&c->freelist_lock);
1431                 if (!ca->open_buckets_partial_nr) {
1432                         spin_unlock(&c->freelist_lock);
1433                         break;
1434                 }
1435                 ob = c->open_buckets +
1436                         ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1437                 ob->on_partial_list = false;
1438                 spin_unlock(&c->freelist_lock);
1439
1440                 bch2_open_bucket_put(c, ob);
1441         }
1442
1443         bch2_ec_stop_dev(c, ca);
1444
1445         /*
1446          * Wake up threads that were blocked on allocation, so they can notice
1447          * the device can no longer be removed and the capacity has changed:
1448          */
1449         closure_wake_up(&c->freelist_wait);
1450
1451         /*
1452          * journal_res_get() can block waiting for free space in the journal -
1453          * it needs to notice there may not be devices to allocate from anymore:
1454          */
1455         wake_up(&c->journal.wait);
1456
1457         /* Now wait for any in flight writes: */
1458
1459         closure_wait_event(&c->open_buckets_wait,
1460                            !bch2_dev_has_open_write_point(c, ca));
1461 }
1462
1463 /* device goes rw: */
1464 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1465 {
1466         unsigned i;
1467
1468         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1469                 if (ca->mi.data_allowed & (1 << i))
1470                         set_bit(ca->dev_idx, c->rw_devs[i].d);
1471 }
1472
1473 void bch2_fs_allocator_background_init(struct bch_fs *c)
1474 {
1475         spin_lock_init(&c->freelist_lock);
1476         INIT_WORK(&c->discard_work, bch2_do_discards_work);
1477         INIT_WORK(&c->invalidate_work, bch2_do_invalidates_work);
1478 }