]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_background.c
Update bcachefs sources to 17a344f265 bcachefs: Improve fsck for subvols/snapshots
[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(&trans, iter, BTREE_ID_alloc, POS_MIN,
1011                            BTREE_ITER_PREFETCH, k, ret) {
1012                 ret = commit_do(&trans, NULL, NULL,
1013                                       BTREE_INSERT_NOFAIL|
1014                                       BTREE_INSERT_LAZY_RW,
1015                         bch2_check_alloc_to_lru_ref(&trans, &iter));
1016                 if (ret)
1017                         break;
1018         }
1019         bch2_trans_iter_exit(&trans, &iter);
1020
1021         bch2_trans_exit(&trans);
1022         return ret < 0 ? ret : 0;
1023 }
1024
1025 static int bch2_clear_need_discard(struct btree_trans *trans, struct bpos pos,
1026                                    struct bch_dev *ca, bool *discard_done)
1027 {
1028         struct bch_fs *c = trans->c;
1029         struct btree_iter iter;
1030         struct bkey_s_c k;
1031         struct bkey_i_alloc_v4 *a;
1032         struct printbuf buf = PRINTBUF;
1033         int ret;
1034
1035         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, pos,
1036                              BTREE_ITER_CACHED);
1037         k = bch2_btree_iter_peek_slot(&iter);
1038         ret = bkey_err(k);
1039         if (ret)
1040                 goto out;
1041
1042         a = bch2_alloc_to_v4_mut(trans, k);
1043         ret = PTR_ERR_OR_ZERO(a);
1044         if (ret)
1045                 goto out;
1046
1047         if (BCH_ALLOC_V4_NEED_INC_GEN(&a->v)) {
1048                 a->v.gen++;
1049                 SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
1050                 goto write;
1051         }
1052
1053         if (bch2_trans_inconsistent_on(a->v.journal_seq > c->journal.flushed_seq_ondisk, trans,
1054                         "clearing need_discard but journal_seq %llu > flushed_seq %llu\n"
1055                         "%s",
1056                         a->v.journal_seq,
1057                         c->journal.flushed_seq_ondisk,
1058                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1059                 ret = -EIO;
1060                 goto out;
1061         }
1062
1063         if (bch2_trans_inconsistent_on(a->v.data_type != BCH_DATA_need_discard, trans,
1064                         "bucket incorrectly set in need_discard btree\n"
1065                         "%s",
1066                         (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1067                 ret = -EIO;
1068                 goto out;
1069         }
1070
1071         if (!*discard_done && ca->mi.discard && !c->opts.nochanges) {
1072                 /*
1073                  * This works without any other locks because this is the only
1074                  * thread that removes items from the need_discard tree
1075                  */
1076                 bch2_trans_unlock(trans);
1077                 blkdev_issue_discard(ca->disk_sb.bdev,
1078                                      k.k->p.offset * ca->mi.bucket_size,
1079                                      ca->mi.bucket_size,
1080                                      GFP_KERNEL, 0);
1081                 *discard_done = true;
1082
1083                 ret = bch2_trans_relock(trans) ? 0 : -EINTR;
1084                 if (ret)
1085                         goto out;
1086         }
1087
1088         SET_BCH_ALLOC_V4_NEED_DISCARD(&a->v, false);
1089         a->v.data_type = alloc_data_type(a->v, a->v.data_type);
1090 write:
1091         ret = bch2_trans_update(trans, &iter, &a->k_i, 0);
1092 out:
1093         bch2_trans_iter_exit(trans, &iter);
1094         printbuf_exit(&buf);
1095         return ret;
1096 }
1097
1098 static void bch2_do_discards_work(struct work_struct *work)
1099 {
1100         struct bch_fs *c = container_of(work, struct bch_fs, discard_work);
1101         struct bch_dev *ca = NULL;
1102         struct btree_trans trans;
1103         struct btree_iter iter;
1104         struct bkey_s_c k;
1105         u64 seen = 0, open = 0, need_journal_commit = 0, discarded = 0;
1106         int ret;
1107
1108         bch2_trans_init(&trans, c, 0, 0);
1109
1110         for_each_btree_key(&trans, iter, BTREE_ID_need_discard,
1111                            POS_MIN, 0, k, ret) {
1112                 bool discard_done = false;
1113
1114                 if (ca && k.k->p.inode != ca->dev_idx) {
1115                         percpu_ref_put(&ca->io_ref);
1116                         ca = NULL;
1117                 }
1118
1119                 if (!ca) {
1120                         ca = bch_dev_bkey_exists(c, k.k->p.inode);
1121                         if (!percpu_ref_tryget(&ca->io_ref)) {
1122                                 ca = NULL;
1123                                 bch2_btree_iter_set_pos(&iter, POS(k.k->p.inode + 1, 0));
1124                                 continue;
1125                         }
1126                 }
1127
1128                 seen++;
1129
1130                 if (bch2_bucket_is_open_safe(c, k.k->p.inode, k.k->p.offset)) {
1131                         open++;
1132                         continue;
1133                 }
1134
1135                 if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
1136                                 c->journal.flushed_seq_ondisk,
1137                                 k.k->p.inode, k.k->p.offset)) {
1138                         need_journal_commit++;
1139                         continue;
1140                 }
1141
1142                 ret = commit_do(&trans, NULL, NULL,
1143                                       BTREE_INSERT_USE_RESERVE|
1144                                       BTREE_INSERT_NOFAIL,
1145                                 bch2_clear_need_discard(&trans, k.k->p, ca, &discard_done));
1146                 if (ret)
1147                         break;
1148
1149                 this_cpu_inc(c->counters[BCH_COUNTER_bucket_discard]);
1150                 discarded++;
1151         }
1152         bch2_trans_iter_exit(&trans, &iter);
1153
1154         if (ca)
1155                 percpu_ref_put(&ca->io_ref);
1156
1157         bch2_trans_exit(&trans);
1158
1159         if (need_journal_commit * 2 > seen)
1160                 bch2_journal_flush_async(&c->journal, NULL);
1161
1162         percpu_ref_put(&c->writes);
1163
1164         trace_discard_buckets(c, seen, open, need_journal_commit, discarded, ret);
1165 }
1166
1167 void bch2_do_discards(struct bch_fs *c)
1168 {
1169         if (percpu_ref_tryget_live(&c->writes) &&
1170             !queue_work(system_long_wq, &c->discard_work))
1171                 percpu_ref_put(&c->writes);
1172 }
1173
1174 static int invalidate_one_bucket(struct btree_trans *trans, struct bch_dev *ca,
1175                                  struct bpos *bucket_pos, unsigned *cached_sectors)
1176 {
1177         struct bch_fs *c = trans->c;
1178         struct btree_iter lru_iter, alloc_iter = { NULL };
1179         struct bkey_s_c k;
1180         struct bkey_i_alloc_v4 *a;
1181         u64 bucket, idx;
1182         struct printbuf buf = PRINTBUF;
1183         int ret;
1184
1185         bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
1186                              POS(ca->dev_idx, 0), 0);
1187 next_lru:
1188         k = bch2_btree_iter_peek(&lru_iter);
1189         ret = bkey_err(k);
1190         if (ret)
1191                 goto out;
1192
1193         if (!k.k || k.k->p.inode != ca->dev_idx) {
1194                 ret = 1;
1195                 goto out;
1196         }
1197
1198         if (k.k->type != KEY_TYPE_lru) {
1199                 prt_printf(&buf, "non lru key in lru btree:\n  ");
1200                 bch2_bkey_val_to_text(&buf, c, k);
1201
1202                 if (!test_bit(BCH_FS_CHECK_LRUS_DONE, &c->flags)) {
1203                         bch_err(c, "%s", buf.buf);
1204                         bch2_btree_iter_advance(&lru_iter);
1205                         goto next_lru;
1206                 } else {
1207                         bch2_trans_inconsistent(trans, "%s", buf.buf);
1208                         ret = -EINVAL;
1209                         goto out;
1210                 }
1211         }
1212
1213         idx     = k.k->p.offset;
1214         bucket  = le64_to_cpu(bkey_s_c_to_lru(k).v->idx);
1215
1216         *bucket_pos = POS(ca->dev_idx, bucket);
1217
1218         a = bch2_trans_start_alloc_update(trans, &alloc_iter, *bucket_pos);
1219         ret = PTR_ERR_OR_ZERO(a);
1220         if (ret)
1221                 goto out;
1222
1223         if (idx != alloc_lru_idx(a->v)) {
1224                 prt_printf(&buf, "alloc key does not point back to lru entry when invalidating bucket:\n  ");
1225                 bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&a->k_i));
1226                 prt_printf(&buf, "\n  ");
1227                 bch2_bkey_val_to_text(&buf, c, k);
1228
1229                 if (!test_bit(BCH_FS_CHECK_LRUS_DONE, &c->flags)) {
1230                         bch_err(c, "%s", buf.buf);
1231                         bch2_btree_iter_advance(&lru_iter);
1232                         goto next_lru;
1233                 } else {
1234                         bch2_trans_inconsistent(trans, "%s", buf.buf);
1235                         ret = -EINVAL;
1236                         goto out;
1237                 }
1238         }
1239
1240         if (!a->v.cached_sectors)
1241                 bch_err(c, "invalidating empty bucket, confused");
1242
1243         *cached_sectors = a->v.cached_sectors;
1244
1245         SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
1246         a->v.gen++;
1247         a->v.data_type          = 0;
1248         a->v.dirty_sectors      = 0;
1249         a->v.cached_sectors     = 0;
1250         a->v.io_time[READ]      = atomic64_read(&c->io_clock[READ].now);
1251         a->v.io_time[WRITE]     = atomic64_read(&c->io_clock[WRITE].now);
1252
1253         ret = bch2_trans_update(trans, &alloc_iter, &a->k_i,
1254                                 BTREE_TRIGGER_BUCKET_INVALIDATE);
1255         if (ret)
1256                 goto out;
1257 out:
1258         bch2_trans_iter_exit(trans, &alloc_iter);
1259         bch2_trans_iter_exit(trans, &lru_iter);
1260         printbuf_exit(&buf);
1261         return ret;
1262 }
1263
1264 static void bch2_do_invalidates_work(struct work_struct *work)
1265 {
1266         struct bch_fs *c = container_of(work, struct bch_fs, invalidate_work);
1267         struct bch_dev *ca;
1268         struct btree_trans trans;
1269         struct bpos bucket;
1270         unsigned i, sectors;
1271         int ret = 0;
1272
1273         bch2_trans_init(&trans, c, 0, 0);
1274
1275         for_each_member_device(ca, c, i) {
1276                 s64 nr_to_invalidate =
1277                         should_invalidate_buckets(ca, bch2_dev_usage_read(ca));
1278
1279                 while (nr_to_invalidate-- >= 0) {
1280                         ret = commit_do(&trans, NULL, NULL,
1281                                               BTREE_INSERT_USE_RESERVE|
1282                                               BTREE_INSERT_NOFAIL,
1283                                         invalidate_one_bucket(&trans, ca, &bucket,
1284                                                               &sectors));
1285                         if (ret)
1286                                 break;
1287
1288                         trace_invalidate_bucket(c, bucket.inode, bucket.offset, sectors);
1289                         this_cpu_inc(c->counters[BCH_COUNTER_bucket_invalidate]);
1290                 }
1291         }
1292
1293         bch2_trans_exit(&trans);
1294         percpu_ref_put(&c->writes);
1295 }
1296
1297 void bch2_do_invalidates(struct bch_fs *c)
1298 {
1299         if (percpu_ref_tryget_live(&c->writes) &&
1300             !queue_work(system_long_wq, &c->invalidate_work))
1301                 percpu_ref_put(&c->writes);
1302 }
1303
1304 static int bucket_freespace_init(struct btree_trans *trans, struct btree_iter *iter)
1305 {
1306         struct bch_alloc_v4 a;
1307         struct bkey_s_c k;
1308         int ret;
1309
1310         k = bch2_btree_iter_peek_slot(iter);
1311         ret = bkey_err(k);
1312         if (ret)
1313                 return ret;
1314
1315         bch2_alloc_to_v4(k, &a);
1316         return bch2_bucket_do_index(trans, k, &a, true);
1317 }
1318
1319 static int bch2_dev_freespace_init(struct bch_fs *c, struct bch_dev *ca)
1320 {
1321         struct btree_trans trans;
1322         struct btree_iter iter;
1323         struct bkey_s_c k;
1324         struct bch_member *m;
1325         int ret;
1326
1327         bch2_trans_init(&trans, c, 0, 0);
1328
1329         for_each_btree_key(&trans, iter, BTREE_ID_alloc,
1330                            POS(ca->dev_idx, ca->mi.first_bucket),
1331                            BTREE_ITER_SLOTS|
1332                            BTREE_ITER_PREFETCH, k, ret) {
1333                 if (iter.pos.offset >= ca->mi.nbuckets)
1334                         break;
1335
1336                 ret = commit_do(&trans, NULL, NULL,
1337                                       BTREE_INSERT_LAZY_RW,
1338                                  bucket_freespace_init(&trans, &iter));
1339                 if (ret)
1340                         break;
1341         }
1342         bch2_trans_iter_exit(&trans, &iter);
1343
1344         bch2_trans_exit(&trans);
1345
1346         if (ret) {
1347                 bch_err(ca, "error initializing free space: %i", ret);
1348                 return ret;
1349         }
1350
1351         mutex_lock(&c->sb_lock);
1352         m = bch2_sb_get_members(c->disk_sb.sb)->members + ca->dev_idx;
1353         SET_BCH_MEMBER_FREESPACE_INITIALIZED(m, true);
1354         mutex_unlock(&c->sb_lock);
1355
1356         return ret;
1357 }
1358
1359 int bch2_fs_freespace_init(struct bch_fs *c)
1360 {
1361         struct bch_dev *ca;
1362         unsigned i;
1363         int ret = 0;
1364         bool doing_init = false;
1365
1366         /*
1367          * We can crash during the device add path, so we need to check this on
1368          * every mount:
1369          */
1370
1371         for_each_member_device(ca, c, i) {
1372                 if (ca->mi.freespace_initialized)
1373                         continue;
1374
1375                 if (!doing_init) {
1376                         bch_info(c, "initializing freespace");
1377                         doing_init = true;
1378                 }
1379
1380                 ret = bch2_dev_freespace_init(c, ca);
1381                 if (ret) {
1382                         percpu_ref_put(&ca->ref);
1383                         return ret;
1384                 }
1385         }
1386
1387         if (doing_init) {
1388                 mutex_lock(&c->sb_lock);
1389                 bch2_write_super(c);
1390                 mutex_unlock(&c->sb_lock);
1391
1392                 bch_verbose(c, "done initializing freespace");
1393         }
1394
1395         return ret;
1396 }
1397
1398 /* Bucket IO clocks: */
1399
1400 int bch2_bucket_io_time_reset(struct btree_trans *trans, unsigned dev,
1401                               size_t bucket_nr, int rw)
1402 {
1403         struct bch_fs *c = trans->c;
1404         struct btree_iter iter;
1405         struct bkey_i_alloc_v4 *a;
1406         u64 now;
1407         int ret = 0;
1408
1409         a = bch2_trans_start_alloc_update(trans, &iter,  POS(dev, bucket_nr));
1410         ret = PTR_ERR_OR_ZERO(a);
1411         if (ret)
1412                 return ret;
1413
1414         now = atomic64_read(&c->io_clock[rw].now);
1415         if (a->v.io_time[rw] == now)
1416                 goto out;
1417
1418         a->v.io_time[rw] = now;
1419
1420         ret   = bch2_trans_update(trans, &iter, &a->k_i, 0) ?:
1421                 bch2_trans_commit(trans, NULL, NULL, 0);
1422 out:
1423         bch2_trans_iter_exit(trans, &iter);
1424         return ret;
1425 }
1426
1427 /* Startup/shutdown (ro/rw): */
1428
1429 void bch2_recalc_capacity(struct bch_fs *c)
1430 {
1431         struct bch_dev *ca;
1432         u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1433         unsigned bucket_size_max = 0;
1434         unsigned long ra_pages = 0;
1435         unsigned i;
1436
1437         lockdep_assert_held(&c->state_lock);
1438
1439         for_each_online_member(ca, c, i) {
1440                 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_disk->bdi;
1441
1442                 ra_pages += bdi->ra_pages;
1443         }
1444
1445         bch2_set_ra_pages(c, ra_pages);
1446
1447         for_each_rw_member(ca, c, i) {
1448                 u64 dev_reserve = 0;
1449
1450                 /*
1451                  * We need to reserve buckets (from the number
1452                  * of currently available buckets) against
1453                  * foreground writes so that mainly copygc can
1454                  * make forward progress.
1455                  *
1456                  * We need enough to refill the various reserves
1457                  * from scratch - copygc will use its entire
1458                  * reserve all at once, then run against when
1459                  * its reserve is refilled (from the formerly
1460                  * available buckets).
1461                  *
1462                  * This reserve is just used when considering if
1463                  * allocations for foreground writes must wait -
1464                  * not -ENOSPC calculations.
1465                  */
1466
1467                 dev_reserve += ca->nr_btree_reserve * 2;
1468                 dev_reserve += ca->mi.nbuckets >> 6; /* copygc reserve */
1469
1470                 dev_reserve += 1;       /* btree write point */
1471                 dev_reserve += 1;       /* copygc write point */
1472                 dev_reserve += 1;       /* rebalance write point */
1473
1474                 dev_reserve *= ca->mi.bucket_size;
1475
1476                 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1477                                              ca->mi.first_bucket);
1478
1479                 reserved_sectors += dev_reserve * 2;
1480
1481                 bucket_size_max = max_t(unsigned, bucket_size_max,
1482                                         ca->mi.bucket_size);
1483         }
1484
1485         gc_reserve = c->opts.gc_reserve_bytes
1486                 ? c->opts.gc_reserve_bytes >> 9
1487                 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1488
1489         reserved_sectors = max(gc_reserve, reserved_sectors);
1490
1491         reserved_sectors = min(reserved_sectors, capacity);
1492
1493         c->capacity = capacity - reserved_sectors;
1494
1495         c->bucket_size_max = bucket_size_max;
1496
1497         /* Wake up case someone was waiting for buckets */
1498         closure_wake_up(&c->freelist_wait);
1499 }
1500
1501 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1502 {
1503         struct open_bucket *ob;
1504         bool ret = false;
1505
1506         for (ob = c->open_buckets;
1507              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1508              ob++) {
1509                 spin_lock(&ob->lock);
1510                 if (ob->valid && !ob->on_partial_list &&
1511                     ob->dev == ca->dev_idx)
1512                         ret = true;
1513                 spin_unlock(&ob->lock);
1514         }
1515
1516         return ret;
1517 }
1518
1519 /* device goes ro: */
1520 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1521 {
1522         unsigned i;
1523
1524         /* First, remove device from allocation groups: */
1525
1526         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1527                 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1528
1529         /*
1530          * Capacity is calculated based off of devices in allocation groups:
1531          */
1532         bch2_recalc_capacity(c);
1533
1534         /* Next, close write points that point to this device... */
1535         for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1536                 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1537
1538         bch2_writepoint_stop(c, ca, &c->copygc_write_point);
1539         bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1540         bch2_writepoint_stop(c, ca, &c->btree_write_point);
1541
1542         mutex_lock(&c->btree_reserve_cache_lock);
1543         while (c->btree_reserve_cache_nr) {
1544                 struct btree_alloc *a =
1545                         &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1546
1547                 bch2_open_buckets_put(c, &a->ob);
1548         }
1549         mutex_unlock(&c->btree_reserve_cache_lock);
1550
1551         while (1) {
1552                 struct open_bucket *ob;
1553
1554                 spin_lock(&c->freelist_lock);
1555                 if (!ca->open_buckets_partial_nr) {
1556                         spin_unlock(&c->freelist_lock);
1557                         break;
1558                 }
1559                 ob = c->open_buckets +
1560                         ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1561                 ob->on_partial_list = false;
1562                 spin_unlock(&c->freelist_lock);
1563
1564                 bch2_open_bucket_put(c, ob);
1565         }
1566
1567         bch2_ec_stop_dev(c, ca);
1568
1569         /*
1570          * Wake up threads that were blocked on allocation, so they can notice
1571          * the device can no longer be removed and the capacity has changed:
1572          */
1573         closure_wake_up(&c->freelist_wait);
1574
1575         /*
1576          * journal_res_get() can block waiting for free space in the journal -
1577          * it needs to notice there may not be devices to allocate from anymore:
1578          */
1579         wake_up(&c->journal.wait);
1580
1581         /* Now wait for any in flight writes: */
1582
1583         closure_wait_event(&c->open_buckets_wait,
1584                            !bch2_dev_has_open_write_point(c, ca));
1585 }
1586
1587 /* device goes rw: */
1588 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1589 {
1590         unsigned i;
1591
1592         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1593                 if (ca->mi.data_allowed & (1 << i))
1594                         set_bit(ca->dev_idx, c->rw_devs[i].d);
1595 }
1596
1597 void bch2_fs_allocator_background_init(struct bch_fs *c)
1598 {
1599         spin_lock_init(&c->freelist_lock);
1600         INIT_WORK(&c->discard_work, bch2_do_discards_work);
1601         INIT_WORK(&c->invalidate_work, bch2_do_invalidates_work);
1602 }