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