]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_background.c
7be4829790b621c47a67297a85ede2a400947110
[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                                 pr_buf(err, "cached bucket with read_time == 0");
387                                 return -EINVAL;
388                         }
389                         break;
390                 case BCH_DATA_stripe:
391                         if (!a.v->stripe) {
392                                 pr_buf(err, "data_type %s but stripe==0",
393                                        bch2_data_types[a.v->data_type]);
394                                 return -EINVAL;
395                         }
396                         break;
397                 }
398         }
399
400         return 0;
401 }
402
403 void bch2_alloc_v4_swab(struct bkey_s k)
404 {
405         struct bch_alloc_v4 *a = bkey_s_to_alloc_v4(k).v;
406
407         a->journal_seq          = swab64(a->journal_seq);
408         a->flags                = swab32(a->flags);
409         a->dirty_sectors        = swab32(a->dirty_sectors);
410         a->cached_sectors       = swab32(a->cached_sectors);
411         a->io_time[0]           = swab64(a->io_time[0]);
412         a->io_time[1]           = swab64(a->io_time[1]);
413         a->stripe               = swab32(a->stripe);
414         a->nr_external_backpointers = swab32(a->nr_external_backpointers);
415 }
416
417 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c, struct bkey_s_c k)
418 {
419         struct bch_alloc_v4 a;
420
421         bch2_alloc_to_v4(k, &a);
422
423         pr_buf(out, "gen %u oldest_gen %u data_type %s journal_seq %llu need_discard %llu need_inc_gen %llu",
424                a.gen, a.oldest_gen, bch2_data_types[a.data_type],
425                a.journal_seq,
426                BCH_ALLOC_V4_NEED_DISCARD(&a),
427                BCH_ALLOC_V4_NEED_INC_GEN(&a));
428         pr_buf(out, " dirty_sectors %u",        a.dirty_sectors);
429         pr_buf(out, " cached_sectors %u",       a.cached_sectors);
430         pr_buf(out, " stripe %u",               a.stripe);
431         pr_buf(out, " stripe_redundancy %u",    a.stripe_redundancy);
432         pr_buf(out, " read_time %llu",          a.io_time[READ]);
433         pr_buf(out, " write_time %llu",         a.io_time[WRITE]);
434 }
435
436 int bch2_alloc_read(struct bch_fs *c)
437 {
438         struct btree_trans trans;
439         struct btree_iter iter;
440         struct bkey_s_c k;
441         struct bch_alloc_v4 a;
442         struct bch_dev *ca;
443         int ret;
444
445         bch2_trans_init(&trans, c, 0, 0);
446
447         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
448                            BTREE_ITER_PREFETCH, k, ret) {
449                 /*
450                  * Not a fsck error because this is checked/repaired by
451                  * bch2_check_alloc_key() which runs later:
452                  */
453                 if (!bch2_dev_bucket_exists(c, k.k->p))
454                         continue;
455
456                 ca = bch_dev_bkey_exists(c, k.k->p.inode);
457                 bch2_alloc_to_v4(k, &a);
458
459                 *bucket_gen(ca, k.k->p.offset) = a.gen;
460         }
461         bch2_trans_iter_exit(&trans, &iter);
462
463         bch2_trans_exit(&trans);
464
465         if (ret)
466                 bch_err(c, "error reading alloc info: %i", ret);
467
468         return ret;
469 }
470
471 /* Free space/discard btree: */
472
473 static int bch2_bucket_do_index(struct btree_trans *trans,
474                                 struct bkey_s_c alloc_k,
475                                 const struct bch_alloc_v4 *a,
476                                 bool set)
477 {
478         struct bch_fs *c = trans->c;
479         struct bch_dev *ca = bch_dev_bkey_exists(c, alloc_k.k->p.inode);
480         struct btree_iter iter;
481         struct bkey_s_c old;
482         struct bkey_i *k;
483         enum btree_id btree;
484         enum bch_bkey_type old_type = !set ? KEY_TYPE_set : KEY_TYPE_deleted;
485         enum bch_bkey_type new_type =  set ? KEY_TYPE_set : KEY_TYPE_deleted;
486         struct printbuf buf = PRINTBUF;
487         int ret;
488
489         if (a->data_type != BCH_DATA_free &&
490             a->data_type != BCH_DATA_need_discard)
491                 return 0;
492
493         k = bch2_trans_kmalloc(trans, sizeof(*k));
494         if (IS_ERR(k))
495                 return PTR_ERR(k);
496
497         bkey_init(&k->k);
498         k->k.type = new_type;
499
500         switch (a->data_type) {
501         case BCH_DATA_free:
502                 btree = BTREE_ID_freespace;
503                 k->k.p = alloc_freespace_pos(alloc_k.k->p, *a);
504                 bch2_key_resize(&k->k, 1);
505                 break;
506         case BCH_DATA_need_discard:
507                 btree = BTREE_ID_need_discard;
508                 k->k.p = alloc_k.k->p;
509                 break;
510         default:
511                 return 0;
512         }
513
514         bch2_trans_iter_init(trans, &iter, btree,
515                              bkey_start_pos(&k->k),
516                              BTREE_ITER_INTENT);
517         old = bch2_btree_iter_peek_slot(&iter);
518         ret = bkey_err(old);
519         if (ret)
520                 goto err;
521
522         if (ca->mi.freespace_initialized &&
523             bch2_trans_inconsistent_on(old.k->type != old_type, trans,
524                         "incorrect key when %s %s btree (got %s should be %s)\n"
525                         "  for %s",
526                         set ? "setting" : "clearing",
527                         bch2_btree_ids[btree],
528                         bch2_bkey_types[old.k->type],
529                         bch2_bkey_types[old_type],
530                         (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
531                 ret = -EIO;
532                 goto err;
533         }
534
535         ret = bch2_trans_update(trans, &iter, k, 0);
536 err:
537         bch2_trans_iter_exit(trans, &iter);
538         printbuf_exit(&buf);
539         return ret;
540 }
541
542 int bch2_trans_mark_alloc(struct btree_trans *trans,
543                           struct bkey_s_c old, struct bkey_i *new,
544                           unsigned flags)
545 {
546         struct bch_fs *c = trans->c;
547         struct bch_alloc_v4 old_a, *new_a;
548         u64 old_lru, new_lru;
549         int ret = 0;
550
551         /*
552          * Deletion only happens in the device removal path, with
553          * BTREE_TRIGGER_NORUN:
554          */
555         BUG_ON(new->k.type != KEY_TYPE_alloc_v4);
556
557         bch2_alloc_to_v4(old, &old_a);
558         new_a = &bkey_i_to_alloc_v4(new)->v;
559
560         new_a->data_type = alloc_data_type(*new_a, new_a->data_type);
561
562         if (new_a->dirty_sectors > old_a.dirty_sectors ||
563             new_a->cached_sectors > old_a.cached_sectors) {
564                 new_a->io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
565                 new_a->io_time[WRITE]= max_t(u64, 1, atomic64_read(&c->io_clock[WRITE].now));
566                 SET_BCH_ALLOC_V4_NEED_INC_GEN(new_a, true);
567                 SET_BCH_ALLOC_V4_NEED_DISCARD(new_a, true);
568         }
569
570         if (data_type_is_empty(new_a->data_type) &&
571             BCH_ALLOC_V4_NEED_INC_GEN(new_a) &&
572             !bch2_bucket_is_open_safe(c, new->k.p.inode, new->k.p.offset)) {
573                 new_a->gen++;
574                 SET_BCH_ALLOC_V4_NEED_INC_GEN(new_a, false);
575         }
576
577         if (old_a.data_type != new_a->data_type ||
578             (new_a->data_type == BCH_DATA_free &&
579              alloc_freespace_genbits(old_a) != alloc_freespace_genbits(*new_a))) {
580                 ret =   bch2_bucket_do_index(trans, old, &old_a, false) ?:
581                         bch2_bucket_do_index(trans, bkey_i_to_s_c(new), new_a, true);
582                 if (ret)
583                         return ret;
584         }
585
586         if (new_a->data_type == BCH_DATA_cached &&
587             !new_a->io_time[READ])
588                 new_a->io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
589
590
591         old_lru = alloc_lru_idx(old_a);
592         new_lru = alloc_lru_idx(*new_a);
593
594         if (old_lru != new_lru) {
595                 ret = bch2_lru_change(trans, new->k.p.inode, new->k.p.offset,
596                                       old_lru, &new_lru, old);
597                 if (ret)
598                         return ret;
599
600                 if (new_a->data_type == BCH_DATA_cached)
601                         new_a->io_time[READ] = new_lru;
602         }
603
604         return 0;
605 }
606
607 static int bch2_check_alloc_key(struct btree_trans *trans,
608                                 struct btree_iter *alloc_iter)
609 {
610         struct bch_fs *c = trans->c;
611         struct bch_dev *ca;
612         struct btree_iter discard_iter, freespace_iter;
613         struct bch_alloc_v4 a;
614         unsigned discard_key_type, freespace_key_type;
615         struct bkey_s_c alloc_k, k;
616         struct printbuf buf = PRINTBUF;
617         struct printbuf buf2 = PRINTBUF;
618         int ret;
619
620         alloc_k = bch2_btree_iter_peek(alloc_iter);
621         if (!alloc_k.k)
622                 return 0;
623
624         ret = bkey_err(alloc_k);
625         if (ret)
626                 return ret;
627
628         if (fsck_err_on(!bch2_dev_bucket_exists(c, alloc_k.k->p), c,
629                         "alloc key for invalid device:bucket %llu:%llu",
630                         alloc_k.k->p.inode, alloc_k.k->p.offset))
631                 return bch2_btree_delete_at(trans, alloc_iter, 0);
632
633         ca = bch_dev_bkey_exists(c, alloc_k.k->p.inode);
634         if (!ca->mi.freespace_initialized)
635                 return 0;
636
637         bch2_alloc_to_v4(alloc_k, &a);
638
639         discard_key_type = a.data_type == BCH_DATA_need_discard
640                 ? KEY_TYPE_set : 0;
641         freespace_key_type = a.data_type == BCH_DATA_free
642                 ? KEY_TYPE_set : 0;
643
644         bch2_trans_iter_init(trans, &discard_iter, BTREE_ID_need_discard,
645                              alloc_k.k->p, 0);
646         bch2_trans_iter_init(trans, &freespace_iter, BTREE_ID_freespace,
647                              alloc_freespace_pos(alloc_k.k->p, a), 0);
648
649         k = bch2_btree_iter_peek_slot(&discard_iter);
650         ret = bkey_err(k);
651         if (ret)
652                 goto err;
653
654         if (fsck_err_on(k.k->type != discard_key_type, c,
655                         "incorrect key in need_discard btree (got %s should be %s)\n"
656                         "  %s",
657                         bch2_bkey_types[k.k->type],
658                         bch2_bkey_types[discard_key_type],
659                         (bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
660                 struct bkey_i *update =
661                         bch2_trans_kmalloc(trans, sizeof(*update));
662
663                 ret = PTR_ERR_OR_ZERO(update);
664                 if (ret)
665                         goto err;
666
667                 bkey_init(&update->k);
668                 update->k.type  = discard_key_type;
669                 update->k.p     = discard_iter.pos;
670
671                 ret = bch2_trans_update(trans, &discard_iter, update, 0);
672                 if (ret)
673                         goto err;
674         }
675
676         k = bch2_btree_iter_peek_slot(&freespace_iter);
677         ret = bkey_err(k);
678         if (ret)
679                 goto err;
680
681         if (fsck_err_on(k.k->type != freespace_key_type, c,
682                         "incorrect key in freespace btree (got %s should be %s)\n"
683                         "  %s",
684                         bch2_bkey_types[k.k->type],
685                         bch2_bkey_types[freespace_key_type],
686                         (printbuf_reset(&buf),
687                          bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
688                 struct bkey_i *update =
689                         bch2_trans_kmalloc(trans, sizeof(*update));
690
691                 ret = PTR_ERR_OR_ZERO(update);
692                 if (ret)
693                         goto err;
694
695                 bkey_init(&update->k);
696                 update->k.type  = freespace_key_type;
697                 update->k.p     = freespace_iter.pos;
698                 bch2_key_resize(&update->k, 1);
699
700                 ret = bch2_trans_update(trans, &freespace_iter, update, 0);
701                 if (ret)
702                         goto err;
703         }
704 err:
705 fsck_err:
706         bch2_trans_iter_exit(trans, &freespace_iter);
707         bch2_trans_iter_exit(trans, &discard_iter);
708         printbuf_exit(&buf2);
709         printbuf_exit(&buf);
710         return ret;
711 }
712
713 static int bch2_check_discard_freespace_key(struct btree_trans *trans,
714                                             struct btree_iter *iter)
715 {
716         struct bch_fs *c = trans->c;
717         struct btree_iter alloc_iter;
718         struct bkey_s_c k, freespace_k;
719         struct bch_alloc_v4 a;
720         u64 genbits;
721         struct bpos pos;
722         enum bch_data_type state = iter->btree_id == BTREE_ID_need_discard
723                 ? BCH_DATA_need_discard
724                 : BCH_DATA_free;
725         struct printbuf buf = PRINTBUF;
726         int ret;
727
728         freespace_k = bch2_btree_iter_peek(iter);
729         if (!freespace_k.k)
730                 return 1;
731
732         ret = bkey_err(freespace_k);
733         if (ret)
734                 return ret;
735
736         pos = iter->pos;
737         pos.offset &= ~(~0ULL << 56);
738         genbits = iter->pos.offset & (~0ULL << 56);
739
740         bch2_trans_iter_init(trans, &alloc_iter, BTREE_ID_alloc, pos, 0);
741
742         if (fsck_err_on(!bch2_dev_bucket_exists(c, pos), c,
743                         "entry in %s btree for nonexistant dev:bucket %llu:%llu",
744                         bch2_btree_ids[iter->btree_id], pos.inode, pos.offset))
745                 goto delete;
746
747         k = bch2_btree_iter_peek_slot(&alloc_iter);
748         ret = bkey_err(k);
749         if (ret)
750                 goto err;
751
752         bch2_alloc_to_v4(k, &a);
753
754         if (fsck_err_on(a.data_type != state ||
755                         (state == BCH_DATA_free &&
756                          genbits != alloc_freespace_genbits(a)), c,
757                         "%s\n  incorrectly set in %s index (free %u, genbits %llu should be %llu)",
758                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf),
759                         bch2_btree_ids[iter->btree_id],
760                         a.data_type == state,
761                         genbits >> 56, alloc_freespace_genbits(a) >> 56))
762                 goto delete;
763 out:
764 err:
765 fsck_err:
766         bch2_trans_iter_exit(trans, &alloc_iter);
767         printbuf_exit(&buf);
768         return ret;
769 delete:
770         ret = bch2_btree_delete_extent_at(trans, iter,
771                         iter->btree_id == BTREE_ID_freespace ? 1 : 0, 0);
772         goto out;
773 }
774
775 int bch2_check_alloc_info(struct bch_fs *c)
776 {
777         struct btree_trans trans;
778         struct btree_iter iter;
779         struct bkey_s_c k;
780         int ret = 0;
781
782         bch2_trans_init(&trans, c, 0, 0);
783
784         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
785                            BTREE_ITER_PREFETCH, k, ret) {
786                 ret = __bch2_trans_do(&trans, NULL, NULL, 0,
787                         bch2_check_alloc_key(&trans, &iter));
788                 if (ret)
789                         break;
790         }
791         bch2_trans_iter_exit(&trans, &iter);
792
793         if (ret)
794                 goto err;
795
796         bch2_trans_iter_init(&trans, &iter, BTREE_ID_need_discard, POS_MIN,
797                              BTREE_ITER_PREFETCH);
798         while (1) {
799                 ret = __bch2_trans_do(&trans, NULL, NULL, 0,
800                         bch2_check_discard_freespace_key(&trans, &iter));
801                 if (ret)
802                         break;
803
804                 bch2_btree_iter_set_pos(&iter, bpos_nosnap_successor(iter.pos));
805         }
806         bch2_trans_iter_exit(&trans, &iter);
807
808         if (ret)
809                 goto err;
810
811         bch2_trans_iter_init(&trans, &iter, BTREE_ID_freespace, POS_MIN,
812                              BTREE_ITER_PREFETCH);
813         while (1) {
814                 ret = __bch2_trans_do(&trans, NULL, NULL, 0,
815                         bch2_check_discard_freespace_key(&trans, &iter));
816                 if (ret)
817                         break;
818
819                 bch2_btree_iter_set_pos(&iter, bpos_nosnap_successor(iter.pos));
820         }
821         bch2_trans_iter_exit(&trans, &iter);
822 err:
823         bch2_trans_exit(&trans);
824         return ret < 0 ? ret : 0;
825 }
826
827 static int bch2_check_alloc_to_lru_ref(struct btree_trans *trans,
828                                        struct btree_iter *alloc_iter)
829 {
830         struct bch_fs *c = trans->c;
831         struct btree_iter lru_iter;
832         struct bch_alloc_v4 a;
833         struct bkey_s_c alloc_k, k;
834         struct printbuf buf = PRINTBUF;
835         struct printbuf buf2 = PRINTBUF;
836         int ret;
837
838         alloc_k = bch2_btree_iter_peek(alloc_iter);
839         if (!alloc_k.k)
840                 return 0;
841
842         ret = bkey_err(alloc_k);
843         if (ret)
844                 return ret;
845
846         bch2_alloc_to_v4(alloc_k, &a);
847
848         if (a.data_type != BCH_DATA_cached)
849                 return 0;
850
851         bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
852                              POS(alloc_k.k->p.inode, a.io_time[READ]), 0);
853
854         k = bch2_btree_iter_peek_slot(&lru_iter);
855         ret = bkey_err(k);
856         if (ret)
857                 goto err;
858
859         if (fsck_err_on(!a.io_time[READ], c,
860                         "cached bucket with read_time 0\n"
861                         "  %s",
862                 (printbuf_reset(&buf),
863                  bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf)) ||
864             fsck_err_on(k.k->type != KEY_TYPE_lru ||
865                         le64_to_cpu(bkey_s_c_to_lru(k).v->idx) != alloc_k.k->p.offset, c,
866                         "incorrect/missing lru entry\n"
867                         "  %s\n"
868                         "  %s",
869                         (printbuf_reset(&buf),
870                          bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf),
871                         (bch2_bkey_val_to_text(&buf2, c, k), buf2.buf))) {
872                 u64 read_time = a.io_time[READ];
873
874                 if (!a.io_time[READ])
875                         a.io_time[READ] = atomic64_read(&c->io_clock[READ].now);
876
877                 ret = bch2_lru_set(trans,
878                                    alloc_k.k->p.inode,
879                                    alloc_k.k->p.offset,
880                                    &a.io_time[READ]);
881                 if (ret)
882                         goto err;
883
884                 if (a.io_time[READ] != read_time) {
885                         struct bkey_i_alloc_v4 *a_mut =
886                                 bch2_alloc_to_v4_mut(trans, alloc_k);
887                         ret = PTR_ERR_OR_ZERO(a_mut);
888                         if (ret)
889                                 goto err;
890
891                         a_mut->v.io_time[READ] = a.io_time[READ];
892                         ret = bch2_trans_update(trans, alloc_iter,
893                                                 &a_mut->k_i, BTREE_TRIGGER_NORUN);
894                         if (ret)
895                                 goto err;
896                 }
897         }
898 err:
899 fsck_err:
900         bch2_trans_iter_exit(trans, &lru_iter);
901         printbuf_exit(&buf2);
902         printbuf_exit(&buf);
903         return ret;
904 }
905
906 int bch2_check_alloc_to_lru_refs(struct bch_fs *c)
907 {
908         struct btree_trans trans;
909         struct btree_iter iter;
910         struct bkey_s_c k;
911         int ret = 0;
912
913         bch2_trans_init(&trans, c, 0, 0);
914
915         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
916                            BTREE_ITER_PREFETCH, k, ret) {
917                 ret = __bch2_trans_do(&trans, NULL, NULL,
918                                       BTREE_INSERT_NOFAIL|
919                                       BTREE_INSERT_LAZY_RW,
920                         bch2_check_alloc_to_lru_ref(&trans, &iter));
921                 if (ret)
922                         break;
923         }
924         bch2_trans_iter_exit(&trans, &iter);
925
926         bch2_trans_exit(&trans);
927         return ret < 0 ? ret : 0;
928 }
929
930 static int bch2_clear_need_discard(struct btree_trans *trans, struct bpos pos,
931                                    struct bch_dev *ca, bool *discard_done)
932 {
933         struct bch_fs *c = trans->c;
934         struct btree_iter iter;
935         struct bkey_s_c k;
936         struct bkey_i_alloc_v4 *a;
937         struct printbuf buf = PRINTBUF;
938         int ret;
939
940         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, pos,
941                              BTREE_ITER_CACHED);
942         k = bch2_btree_iter_peek_slot(&iter);
943         ret = bkey_err(k);
944         if (ret)
945                 goto out;
946
947         a = bch2_alloc_to_v4_mut(trans, k);
948         ret = PTR_ERR_OR_ZERO(a);
949         if (ret)
950                 goto out;
951
952         if (BCH_ALLOC_V4_NEED_INC_GEN(&a->v)) {
953                 a->v.gen++;
954                 SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
955                 goto write;
956         }
957
958         if (bch2_trans_inconsistent_on(a->v.journal_seq > c->journal.flushed_seq_ondisk, trans,
959                         "clearing need_discard but journal_seq %llu > flushed_seq %llu\n"
960                         "%s",
961                         a->v.journal_seq,
962                         c->journal.flushed_seq_ondisk,
963                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
964                 ret = -EIO;
965                 goto out;
966         }
967
968         if (bch2_trans_inconsistent_on(a->v.data_type != BCH_DATA_need_discard, trans,
969                         "bucket incorrectly set in need_discard btree\n"
970                         "%s",
971                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
972                 ret = -EIO;
973                 goto out;
974         }
975
976         if (!*discard_done && ca->mi.discard && !c->opts.nochanges) {
977                 /*
978                  * This works without any other locks because this is the only
979                  * thread that removes items from the need_discard tree
980                  */
981                 bch2_trans_unlock(trans);
982                 blkdev_issue_discard(ca->disk_sb.bdev,
983                                      k.k->p.offset * ca->mi.bucket_size,
984                                      ca->mi.bucket_size,
985                                      GFP_KERNEL, 0);
986                 *discard_done = true;
987
988                 ret = bch2_trans_relock(trans) ? 0 : -EINTR;
989                 if (ret)
990                         goto out;
991         }
992
993         SET_BCH_ALLOC_V4_NEED_DISCARD(&a->v, false);
994         a->v.data_type = alloc_data_type(a->v, a->v.data_type);
995 write:
996         ret = bch2_trans_update(trans, &iter, &a->k_i, 0);
997 out:
998         bch2_trans_iter_exit(trans, &iter);
999         printbuf_exit(&buf);
1000         return ret;
1001 }
1002
1003 static void bch2_do_discards_work(struct work_struct *work)
1004 {
1005         struct bch_fs *c = container_of(work, struct bch_fs, discard_work);
1006         struct bch_dev *ca = NULL;
1007         struct btree_trans trans;
1008         struct btree_iter iter;
1009         struct bkey_s_c k;
1010         u64 seen = 0, open = 0, need_journal_commit = 0, discarded = 0;
1011         int ret;
1012
1013         bch2_trans_init(&trans, c, 0, 0);
1014
1015         for_each_btree_key(&trans, iter, BTREE_ID_need_discard,
1016                            POS_MIN, 0, k, ret) {
1017                 bool discard_done = false;
1018
1019                 if (ca && k.k->p.inode != ca->dev_idx) {
1020                         percpu_ref_put(&ca->io_ref);
1021                         ca = NULL;
1022                 }
1023
1024                 if (!ca) {
1025                         ca = bch_dev_bkey_exists(c, k.k->p.inode);
1026                         if (!percpu_ref_tryget(&ca->io_ref)) {
1027                                 ca = NULL;
1028                                 bch2_btree_iter_set_pos(&iter, POS(k.k->p.inode + 1, 0));
1029                                 continue;
1030                         }
1031                 }
1032
1033                 seen++;
1034
1035                 if (bch2_bucket_is_open_safe(c, k.k->p.inode, k.k->p.offset)) {
1036                         open++;
1037                         continue;
1038                 }
1039
1040                 if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
1041                                 c->journal.flushed_seq_ondisk,
1042                                 k.k->p.inode, k.k->p.offset)) {
1043                         need_journal_commit++;
1044                         continue;
1045                 }
1046
1047                 ret = __bch2_trans_do(&trans, NULL, NULL,
1048                                       BTREE_INSERT_USE_RESERVE|
1049                                       BTREE_INSERT_NOFAIL,
1050                                 bch2_clear_need_discard(&trans, k.k->p, ca, &discard_done));
1051                 if (ret)
1052                         break;
1053
1054                 discarded++;
1055         }
1056         bch2_trans_iter_exit(&trans, &iter);
1057
1058         if (ca)
1059                 percpu_ref_put(&ca->io_ref);
1060
1061         bch2_trans_exit(&trans);
1062
1063         if (need_journal_commit * 2 > seen)
1064                 bch2_journal_flush_async(&c->journal, NULL);
1065
1066         percpu_ref_put(&c->writes);
1067
1068         trace_do_discards(c, seen, open, need_journal_commit, discarded, ret);
1069 }
1070
1071 void bch2_do_discards(struct bch_fs *c)
1072 {
1073         if (percpu_ref_tryget(&c->writes) &&
1074             !queue_work(system_long_wq, &c->discard_work))
1075                 percpu_ref_put(&c->writes);
1076 }
1077
1078 static int invalidate_one_bucket(struct btree_trans *trans, struct bch_dev *ca)
1079 {
1080         struct bch_fs *c = trans->c;
1081         struct btree_iter lru_iter, alloc_iter = { NULL };
1082         struct bkey_s_c k;
1083         struct bkey_i_alloc_v4 *a;
1084         u64 bucket, idx;
1085         struct printbuf buf = PRINTBUF;
1086         int ret;
1087
1088         bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
1089                              POS(ca->dev_idx, 0), 0);
1090         k = bch2_btree_iter_peek(&lru_iter);
1091         ret = bkey_err(k);
1092         if (ret)
1093                 goto out;
1094
1095         if (!k.k || k.k->p.inode != ca->dev_idx)
1096                 goto out;
1097
1098         if (bch2_trans_inconsistent_on(k.k->type != KEY_TYPE_lru, trans,
1099                                        "non lru key in lru btree"))
1100                 goto out;
1101
1102         idx     = k.k->p.offset;
1103         bucket  = le64_to_cpu(bkey_s_c_to_lru(k).v->idx);
1104
1105         a = bch2_trans_start_alloc_update(trans, &alloc_iter,
1106                                           POS(ca->dev_idx, bucket));
1107         ret = PTR_ERR_OR_ZERO(a);
1108         if (ret)
1109                 goto out;
1110
1111         if (idx != alloc_lru_idx(a->v)) {
1112                 pr_buf(&buf, "alloc key does not point back to lru entry when invalidating bucket:\n  ");
1113
1114                 bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&a->k_i));
1115                 pr_buf(&buf, "\n  ");
1116                 bch2_bkey_val_to_text(&buf, c, k);
1117                 bch2_trans_inconsistent(trans, "%s", buf.buf);
1118                 ret = -EINVAL;
1119                 goto out;
1120         }
1121
1122         SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
1123         a->v.gen++;
1124         a->v.data_type          = 0;
1125         a->v.dirty_sectors      = 0;
1126         a->v.cached_sectors     = 0;
1127         a->v.io_time[READ]      = atomic64_read(&c->io_clock[READ].now);
1128         a->v.io_time[WRITE]     = atomic64_read(&c->io_clock[WRITE].now);
1129
1130         ret = bch2_trans_update(trans, &alloc_iter, &a->k_i,
1131                                 BTREE_TRIGGER_BUCKET_INVALIDATE);
1132 out:
1133         bch2_trans_iter_exit(trans, &alloc_iter);
1134         bch2_trans_iter_exit(trans, &lru_iter);
1135         printbuf_exit(&buf);
1136         return ret;
1137 }
1138
1139 static void bch2_do_invalidates_work(struct work_struct *work)
1140 {
1141         struct bch_fs *c = container_of(work, struct bch_fs, invalidate_work);
1142         struct bch_dev *ca;
1143         struct btree_trans trans;
1144         unsigned i;
1145         int ret = 0;
1146
1147         bch2_trans_init(&trans, c, 0, 0);
1148
1149         for_each_member_device(ca, c, i) {
1150                 s64 nr_to_invalidate =
1151                         should_invalidate_buckets(ca, bch2_dev_usage_read(ca));
1152
1153                 while (!ret && nr_to_invalidate-- >= 0)
1154                         ret = __bch2_trans_do(&trans, NULL, NULL,
1155                                               BTREE_INSERT_USE_RESERVE|
1156                                               BTREE_INSERT_NOFAIL,
1157                                         invalidate_one_bucket(&trans, ca));
1158         }
1159
1160         bch2_trans_exit(&trans);
1161         percpu_ref_put(&c->writes);
1162 }
1163
1164 void bch2_do_invalidates(struct bch_fs *c)
1165 {
1166         if (percpu_ref_tryget(&c->writes))
1167                 queue_work(system_long_wq, &c->invalidate_work);
1168 }
1169
1170 static int bch2_dev_freespace_init(struct bch_fs *c, struct bch_dev *ca)
1171 {
1172         struct btree_trans trans;
1173         struct btree_iter iter;
1174         struct bkey_s_c k;
1175         struct bch_alloc_v4 a;
1176         struct bch_member *m;
1177         int ret;
1178
1179         bch2_trans_init(&trans, c, 0, 0);
1180
1181         for_each_btree_key(&trans, iter, BTREE_ID_alloc,
1182                            POS(ca->dev_idx, ca->mi.first_bucket),
1183                            BTREE_ITER_SLOTS|
1184                            BTREE_ITER_PREFETCH, k, ret) {
1185                 if (iter.pos.offset >= ca->mi.nbuckets)
1186                         break;
1187
1188                 bch2_alloc_to_v4(k, &a);
1189                 ret = __bch2_trans_do(&trans, NULL, NULL,
1190                                       BTREE_INSERT_LAZY_RW,
1191                                  bch2_bucket_do_index(&trans, k, &a, true));
1192                 if (ret)
1193                         break;
1194         }
1195         bch2_trans_iter_exit(&trans, &iter);
1196
1197         bch2_trans_exit(&trans);
1198
1199         if (ret) {
1200                 bch_err(ca, "error initializing free space: %i", ret);
1201                 return ret;
1202         }
1203
1204         mutex_lock(&c->sb_lock);
1205         m = bch2_sb_get_members(c->disk_sb.sb)->members + ca->dev_idx;
1206         SET_BCH_MEMBER_FREESPACE_INITIALIZED(m, true);
1207         mutex_unlock(&c->sb_lock);
1208
1209         return ret;
1210 }
1211
1212 int bch2_fs_freespace_init(struct bch_fs *c)
1213 {
1214         struct bch_dev *ca;
1215         unsigned i;
1216         int ret = 0;
1217         bool doing_init = false;
1218
1219         /*
1220          * We can crash during the device add path, so we need to check this on
1221          * every mount:
1222          */
1223
1224         for_each_member_device(ca, c, i) {
1225                 if (ca->mi.freespace_initialized)
1226                         continue;
1227
1228                 if (!doing_init) {
1229                         bch_info(c, "initializing freespace");
1230                         doing_init = true;
1231                 }
1232
1233                 ret = bch2_dev_freespace_init(c, ca);
1234                 if (ret) {
1235                         percpu_ref_put(&ca->ref);
1236                         return ret;
1237                 }
1238         }
1239
1240         if (doing_init) {
1241                 mutex_lock(&c->sb_lock);
1242                 bch2_write_super(c);
1243                 mutex_unlock(&c->sb_lock);
1244
1245                 bch_verbose(c, "done initializing freespace");
1246         }
1247
1248         return ret;
1249 }
1250
1251 /* Bucket IO clocks: */
1252
1253 int bch2_bucket_io_time_reset(struct btree_trans *trans, unsigned dev,
1254                               size_t bucket_nr, int rw)
1255 {
1256         struct bch_fs *c = trans->c;
1257         struct btree_iter iter;
1258         struct bkey_i_alloc_v4 *a;
1259         u64 now;
1260         int ret = 0;
1261
1262         a = bch2_trans_start_alloc_update(trans, &iter,  POS(dev, bucket_nr));
1263         ret = PTR_ERR_OR_ZERO(a);
1264         if (ret)
1265                 return ret;
1266
1267         now = atomic64_read(&c->io_clock[rw].now);
1268         if (a->v.io_time[rw] == now)
1269                 goto out;
1270
1271         a->v.io_time[rw] = now;
1272
1273         ret   = bch2_trans_update(trans, &iter, &a->k_i, 0) ?:
1274                 bch2_trans_commit(trans, NULL, NULL, 0);
1275 out:
1276         bch2_trans_iter_exit(trans, &iter);
1277         return ret;
1278 }
1279
1280 /* Startup/shutdown (ro/rw): */
1281
1282 void bch2_recalc_capacity(struct bch_fs *c)
1283 {
1284         struct bch_dev *ca;
1285         u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1286         unsigned bucket_size_max = 0;
1287         unsigned long ra_pages = 0;
1288         unsigned i;
1289
1290         lockdep_assert_held(&c->state_lock);
1291
1292         for_each_online_member(ca, c, i) {
1293                 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_disk->bdi;
1294
1295                 ra_pages += bdi->ra_pages;
1296         }
1297
1298         bch2_set_ra_pages(c, ra_pages);
1299
1300         for_each_rw_member(ca, c, i) {
1301                 u64 dev_reserve = 0;
1302
1303                 /*
1304                  * We need to reserve buckets (from the number
1305                  * of currently available buckets) against
1306                  * foreground writes so that mainly copygc can
1307                  * make forward progress.
1308                  *
1309                  * We need enough to refill the various reserves
1310                  * from scratch - copygc will use its entire
1311                  * reserve all at once, then run against when
1312                  * its reserve is refilled (from the formerly
1313                  * available buckets).
1314                  *
1315                  * This reserve is just used when considering if
1316                  * allocations for foreground writes must wait -
1317                  * not -ENOSPC calculations.
1318                  */
1319
1320                 dev_reserve += ca->nr_btree_reserve * 2;
1321                 dev_reserve += ca->mi.nbuckets >> 6; /* copygc reserve */
1322
1323                 dev_reserve += 1;       /* btree write point */
1324                 dev_reserve += 1;       /* copygc write point */
1325                 dev_reserve += 1;       /* rebalance write point */
1326
1327                 dev_reserve *= ca->mi.bucket_size;
1328
1329                 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1330                                              ca->mi.first_bucket);
1331
1332                 reserved_sectors += dev_reserve * 2;
1333
1334                 bucket_size_max = max_t(unsigned, bucket_size_max,
1335                                         ca->mi.bucket_size);
1336         }
1337
1338         gc_reserve = c->opts.gc_reserve_bytes
1339                 ? c->opts.gc_reserve_bytes >> 9
1340                 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1341
1342         reserved_sectors = max(gc_reserve, reserved_sectors);
1343
1344         reserved_sectors = min(reserved_sectors, capacity);
1345
1346         c->capacity = capacity - reserved_sectors;
1347
1348         c->bucket_size_max = bucket_size_max;
1349
1350         /* Wake up case someone was waiting for buckets */
1351         closure_wake_up(&c->freelist_wait);
1352 }
1353
1354 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1355 {
1356         struct open_bucket *ob;
1357         bool ret = false;
1358
1359         for (ob = c->open_buckets;
1360              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1361              ob++) {
1362                 spin_lock(&ob->lock);
1363                 if (ob->valid && !ob->on_partial_list &&
1364                     ob->dev == ca->dev_idx)
1365                         ret = true;
1366                 spin_unlock(&ob->lock);
1367         }
1368
1369         return ret;
1370 }
1371
1372 /* device goes ro: */
1373 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1374 {
1375         unsigned i;
1376
1377         /* First, remove device from allocation groups: */
1378
1379         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1380                 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1381
1382         /*
1383          * Capacity is calculated based off of devices in allocation groups:
1384          */
1385         bch2_recalc_capacity(c);
1386
1387         /* Next, close write points that point to this device... */
1388         for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1389                 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1390
1391         bch2_writepoint_stop(c, ca, &c->copygc_write_point);
1392         bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1393         bch2_writepoint_stop(c, ca, &c->btree_write_point);
1394
1395         mutex_lock(&c->btree_reserve_cache_lock);
1396         while (c->btree_reserve_cache_nr) {
1397                 struct btree_alloc *a =
1398                         &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1399
1400                 bch2_open_buckets_put(c, &a->ob);
1401         }
1402         mutex_unlock(&c->btree_reserve_cache_lock);
1403
1404         while (1) {
1405                 struct open_bucket *ob;
1406
1407                 spin_lock(&c->freelist_lock);
1408                 if (!ca->open_buckets_partial_nr) {
1409                         spin_unlock(&c->freelist_lock);
1410                         break;
1411                 }
1412                 ob = c->open_buckets +
1413                         ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1414                 ob->on_partial_list = false;
1415                 spin_unlock(&c->freelist_lock);
1416
1417                 bch2_open_bucket_put(c, ob);
1418         }
1419
1420         bch2_ec_stop_dev(c, ca);
1421
1422         /*
1423          * Wake up threads that were blocked on allocation, so they can notice
1424          * the device can no longer be removed and the capacity has changed:
1425          */
1426         closure_wake_up(&c->freelist_wait);
1427
1428         /*
1429          * journal_res_get() can block waiting for free space in the journal -
1430          * it needs to notice there may not be devices to allocate from anymore:
1431          */
1432         wake_up(&c->journal.wait);
1433
1434         /* Now wait for any in flight writes: */
1435
1436         closure_wait_event(&c->open_buckets_wait,
1437                            !bch2_dev_has_open_write_point(c, ca));
1438 }
1439
1440 /* device goes rw: */
1441 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1442 {
1443         unsigned i;
1444
1445         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1446                 if (ca->mi.data_allowed & (1 << i))
1447                         set_bit(ca->dev_idx, c->rw_devs[i].d);
1448 }
1449
1450 void bch2_fs_allocator_background_init(struct bch_fs *c)
1451 {
1452         spin_lock_init(&c->freelist_lock);
1453         INIT_WORK(&c->discard_work, bch2_do_discards_work);
1454         INIT_WORK(&c->invalidate_work, bch2_do_invalidates_work);
1455 }