]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_foreground.c
46f215c8bced21fec6d3614ef69a6db1c411f483
[bcachefs-tools-debian] / libbcachefs / alloc_foreground.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2012 Google, Inc.
4  *
5  * Foreground allocator code: allocate buckets from freelist, and allocate in
6  * sector granularity from writepoints.
7  *
8  * bch2_bucket_alloc() allocates a single bucket from a specific device.
9  *
10  * bch2_bucket_alloc_set() allocates one or more buckets from different devices
11  * in a given filesystem.
12  */
13
14 #include "bcachefs.h"
15 #include "alloc_background.h"
16 #include "alloc_foreground.h"
17 #include "backpointers.h"
18 #include "btree_iter.h"
19 #include "btree_update.h"
20 #include "btree_gc.h"
21 #include "buckets.h"
22 #include "buckets_waiting_for_journal.h"
23 #include "clock.h"
24 #include "debug.h"
25 #include "disk_groups.h"
26 #include "ec.h"
27 #include "error.h"
28 #include "io.h"
29 #include "journal.h"
30 #include "movinggc.h"
31
32 #include <linux/math64.h>
33 #include <linux/rculist.h>
34 #include <linux/rcupdate.h>
35 #include <trace/events/bcachefs.h>
36
37 const char * const bch2_alloc_reserves[] = {
38 #define x(t) #t,
39         BCH_ALLOC_RESERVES()
40 #undef x
41         NULL
42 };
43
44 /*
45  * Open buckets represent a bucket that's currently being allocated from.  They
46  * serve two purposes:
47  *
48  *  - They track buckets that have been partially allocated, allowing for
49  *    sub-bucket sized allocations - they're used by the sector allocator below
50  *
51  *  - They provide a reference to the buckets they own that mark and sweep GC
52  *    can find, until the new allocation has a pointer to it inserted into the
53  *    btree
54  *
55  * When allocating some space with the sector allocator, the allocation comes
56  * with a reference to an open bucket - the caller is required to put that
57  * reference _after_ doing the index update that makes its allocation reachable.
58  */
59
60 static void bch2_open_bucket_hash_add(struct bch_fs *c, struct open_bucket *ob)
61 {
62         open_bucket_idx_t idx = ob - c->open_buckets;
63         open_bucket_idx_t *slot = open_bucket_hashslot(c, ob->dev, ob->bucket);
64
65         ob->hash = *slot;
66         *slot = idx;
67 }
68
69 static void bch2_open_bucket_hash_remove(struct bch_fs *c, struct open_bucket *ob)
70 {
71         open_bucket_idx_t idx = ob - c->open_buckets;
72         open_bucket_idx_t *slot = open_bucket_hashslot(c, ob->dev, ob->bucket);
73
74         while (*slot != idx) {
75                 BUG_ON(!*slot);
76                 slot = &c->open_buckets[*slot].hash;
77         }
78
79         *slot = ob->hash;
80         ob->hash = 0;
81 }
82
83 void __bch2_open_bucket_put(struct bch_fs *c, struct open_bucket *ob)
84 {
85         struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
86
87         if (ob->ec) {
88                 bch2_ec_bucket_written(c, ob);
89                 return;
90         }
91
92         percpu_down_read(&c->mark_lock);
93         spin_lock(&ob->lock);
94
95         ob->valid = false;
96         ob->data_type = 0;
97
98         spin_unlock(&ob->lock);
99         percpu_up_read(&c->mark_lock);
100
101         spin_lock(&c->freelist_lock);
102         bch2_open_bucket_hash_remove(c, ob);
103
104         ob->freelist = c->open_buckets_freelist;
105         c->open_buckets_freelist = ob - c->open_buckets;
106
107         c->open_buckets_nr_free++;
108         ca->nr_open_buckets--;
109         spin_unlock(&c->freelist_lock);
110
111         closure_wake_up(&c->open_buckets_wait);
112 }
113
114 void bch2_open_bucket_write_error(struct bch_fs *c,
115                                   struct open_buckets *obs,
116                                   unsigned dev)
117 {
118         struct open_bucket *ob;
119         unsigned i;
120
121         open_bucket_for_each(c, obs, ob, i)
122                 if (ob->dev == dev && ob->ec)
123                         bch2_ec_bucket_cancel(c, ob);
124 }
125
126 static struct open_bucket *bch2_open_bucket_alloc(struct bch_fs *c)
127 {
128         struct open_bucket *ob;
129
130         BUG_ON(!c->open_buckets_freelist || !c->open_buckets_nr_free);
131
132         ob = c->open_buckets + c->open_buckets_freelist;
133         c->open_buckets_freelist = ob->freelist;
134         atomic_set(&ob->pin, 1);
135         ob->data_type = 0;
136
137         c->open_buckets_nr_free--;
138         return ob;
139 }
140
141 static void open_bucket_free_unused(struct bch_fs *c,
142                                     struct write_point *wp,
143                                     struct open_bucket *ob)
144 {
145         struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
146         bool may_realloc = wp->data_type == BCH_DATA_user;
147
148         BUG_ON(ca->open_buckets_partial_nr >
149                ARRAY_SIZE(ca->open_buckets_partial));
150
151         if (ca->open_buckets_partial_nr <
152             ARRAY_SIZE(ca->open_buckets_partial) &&
153             may_realloc) {
154                 spin_lock(&c->freelist_lock);
155                 ob->on_partial_list = true;
156                 ca->open_buckets_partial[ca->open_buckets_partial_nr++] =
157                         ob - c->open_buckets;
158                 spin_unlock(&c->freelist_lock);
159
160                 closure_wake_up(&c->open_buckets_wait);
161                 closure_wake_up(&c->freelist_wait);
162         } else {
163                 bch2_open_bucket_put(c, ob);
164         }
165 }
166
167 /* _only_ for allocating the journal on a new device: */
168 long bch2_bucket_alloc_new_fs(struct bch_dev *ca)
169 {
170         while (ca->new_fs_bucket_idx < ca->mi.nbuckets) {
171                 u64 b = ca->new_fs_bucket_idx++;
172
173                 if (!is_superblock_bucket(ca, b) &&
174                     (!ca->buckets_nouse || !test_bit(b, ca->buckets_nouse)))
175                         return b;
176         }
177
178         return -1;
179 }
180
181 static inline unsigned open_buckets_reserved(enum alloc_reserve reserve)
182 {
183         switch (reserve) {
184         case RESERVE_btree:
185         case RESERVE_btree_movinggc:
186                 return 0;
187         case RESERVE_movinggc:
188                 return OPEN_BUCKETS_COUNT / 4;
189         default:
190                 return OPEN_BUCKETS_COUNT / 2;
191         }
192 }
193
194 static struct open_bucket *__try_alloc_bucket(struct bch_fs *c, struct bch_dev *ca,
195                                               u64 bucket,
196                                               enum alloc_reserve reserve,
197                                               const struct bch_alloc_v4 *a,
198                                               struct bucket_alloc_state *s,
199                                               struct closure *cl)
200 {
201         struct open_bucket *ob;
202
203         if (unlikely(ca->buckets_nouse && test_bit(bucket, ca->buckets_nouse))) {
204                 s->skipped_nouse++;
205                 return NULL;
206         }
207
208         if (bch2_bucket_is_open(c, ca->dev_idx, bucket)) {
209                 s->skipped_open++;
210                 return NULL;
211         }
212
213         if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
214                         c->journal.flushed_seq_ondisk, ca->dev_idx, bucket)) {
215                 s->skipped_need_journal_commit++;
216                 return NULL;
217         }
218
219         if (bch2_bucket_nocow_is_locked(&c->nocow_locks, POS(ca->dev_idx, bucket))) {
220                 s->skipped_nocow++;
221                 return NULL;
222         }
223
224         spin_lock(&c->freelist_lock);
225
226         if (unlikely(c->open_buckets_nr_free <= open_buckets_reserved(reserve))) {
227                 if (cl)
228                         closure_wait(&c->open_buckets_wait, cl);
229
230                 if (!c->blocked_allocate_open_bucket)
231                         c->blocked_allocate_open_bucket = local_clock();
232
233                 spin_unlock(&c->freelist_lock);
234                 return ERR_PTR(-BCH_ERR_open_buckets_empty);
235         }
236
237         /* Recheck under lock: */
238         if (bch2_bucket_is_open(c, ca->dev_idx, bucket)) {
239                 spin_unlock(&c->freelist_lock);
240                 s->skipped_open++;
241                 return NULL;
242         }
243
244         ob = bch2_open_bucket_alloc(c);
245
246         spin_lock(&ob->lock);
247
248         ob->valid       = true;
249         ob->sectors_free = ca->mi.bucket_size;
250         ob->alloc_reserve = reserve;
251         ob->dev         = ca->dev_idx;
252         ob->gen         = a->gen;
253         ob->bucket      = bucket;
254         spin_unlock(&ob->lock);
255
256         ca->nr_open_buckets++;
257         bch2_open_bucket_hash_add(c, ob);
258
259         if (c->blocked_allocate_open_bucket) {
260                 bch2_time_stats_update(
261                         &c->times[BCH_TIME_blocked_allocate_open_bucket],
262                         c->blocked_allocate_open_bucket);
263                 c->blocked_allocate_open_bucket = 0;
264         }
265
266         if (c->blocked_allocate) {
267                 bch2_time_stats_update(
268                         &c->times[BCH_TIME_blocked_allocate],
269                         c->blocked_allocate);
270                 c->blocked_allocate = 0;
271         }
272
273         spin_unlock(&c->freelist_lock);
274
275         return ob;
276 }
277
278 static struct open_bucket *try_alloc_bucket(struct btree_trans *trans, struct bch_dev *ca,
279                                             enum alloc_reserve reserve, u64 free_entry,
280                                             struct bucket_alloc_state *s,
281                                             struct bkey_s_c freespace_k,
282                                             struct closure *cl)
283 {
284         struct bch_fs *c = trans->c;
285         struct btree_iter iter = { NULL };
286         struct bkey_s_c k;
287         struct open_bucket *ob;
288         struct bch_alloc_v4 a_convert;
289         const struct bch_alloc_v4 *a;
290         u64 b = free_entry & ~(~0ULL << 56);
291         unsigned genbits = free_entry >> 56;
292         struct printbuf buf = PRINTBUF;
293         int ret;
294
295         if (b < ca->mi.first_bucket || b >= ca->mi.nbuckets) {
296                 prt_printf(&buf, "freespace btree has bucket outside allowed range %u-%llu\n"
297                        "  freespace key ",
298                         ca->mi.first_bucket, ca->mi.nbuckets);
299                 bch2_bkey_val_to_text(&buf, c, freespace_k);
300                 bch2_trans_inconsistent(trans, "%s", buf.buf);
301                 ob = ERR_PTR(-EIO);
302                 goto err;
303         }
304
305         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, POS(ca->dev_idx, b), BTREE_ITER_CACHED);
306         k = bch2_btree_iter_peek_slot(&iter);
307         ret = bkey_err(k);
308         if (ret) {
309                 ob = ERR_PTR(ret);
310                 goto err;
311         }
312
313         a = bch2_alloc_to_v4(k, &a_convert);
314
315         if (genbits != (alloc_freespace_genbits(*a) >> 56)) {
316                 prt_printf(&buf, "bucket in freespace btree with wrong genbits (got %u should be %llu)\n"
317                        "  freespace key ",
318                        genbits, alloc_freespace_genbits(*a) >> 56);
319                 bch2_bkey_val_to_text(&buf, c, freespace_k);
320                 prt_printf(&buf, "\n  ");
321                 bch2_bkey_val_to_text(&buf, c, k);
322                 bch2_trans_inconsistent(trans, "%s", buf.buf);
323                 ob = ERR_PTR(-EIO);
324                 goto err;
325
326         }
327
328         if (a->data_type != BCH_DATA_free) {
329                 prt_printf(&buf, "non free bucket in freespace btree\n"
330                        "  freespace key ");
331                 bch2_bkey_val_to_text(&buf, c, freespace_k);
332                 prt_printf(&buf, "\n  ");
333                 bch2_bkey_val_to_text(&buf, c, k);
334                 bch2_trans_inconsistent(trans, "%s", buf.buf);
335                 ob = ERR_PTR(-EIO);
336                 goto err;
337         }
338
339         if (!test_bit(BCH_FS_CHECK_BACKPOINTERS_DONE, &c->flags)) {
340                 struct bch_backpointer bp;
341                 u64 bp_offset = 0;
342
343                 ret = bch2_get_next_backpointer(trans, POS(ca->dev_idx, b), -1,
344                                                 &bp_offset, &bp,
345                                                 BTREE_ITER_NOPRESERVE);
346                 if (ret) {
347                         ob = ERR_PTR(ret);
348                         goto err;
349                 }
350
351                 if (bp_offset != U64_MAX) {
352                         /*
353                          * Bucket may have data in it - we don't call
354                          * bc2h_trans_inconnsistent() because fsck hasn't
355                          * finished yet
356                          */
357                         ob = NULL;
358                         goto err;
359                 }
360         }
361
362         ob = __try_alloc_bucket(c, ca, b, reserve, a, s, cl);
363         if (!ob)
364                 iter.path->preserve = false;
365 err:
366         set_btree_iter_dontneed(&iter);
367         bch2_trans_iter_exit(trans, &iter);
368         printbuf_exit(&buf);
369         return ob;
370 }
371
372 static struct open_bucket *try_alloc_partial_bucket(struct bch_fs *c, struct bch_dev *ca,
373                                                     enum alloc_reserve reserve)
374 {
375         struct open_bucket *ob;
376         int i;
377
378         spin_lock(&c->freelist_lock);
379
380         for (i = ca->open_buckets_partial_nr - 1; i >= 0; --i) {
381                 ob = c->open_buckets + ca->open_buckets_partial[i];
382
383                 if (reserve <= ob->alloc_reserve) {
384                         array_remove_item(ca->open_buckets_partial,
385                                           ca->open_buckets_partial_nr,
386                                           i);
387                         ob->on_partial_list = false;
388                         ob->alloc_reserve = reserve;
389                         spin_unlock(&c->freelist_lock);
390                         return ob;
391                 }
392         }
393
394         spin_unlock(&c->freelist_lock);
395         return NULL;
396 }
397
398 /*
399  * This path is for before the freespace btree is initialized:
400  *
401  * If ca->new_fs_bucket_idx is nonzero, we haven't yet marked superblock &
402  * journal buckets - journal buckets will be < ca->new_fs_bucket_idx
403  */
404 static noinline struct open_bucket *
405 bch2_bucket_alloc_early(struct btree_trans *trans,
406                         struct bch_dev *ca,
407                         enum alloc_reserve reserve,
408                         struct bucket_alloc_state *s,
409                         struct closure *cl)
410 {
411         struct btree_iter iter;
412         struct bkey_s_c k;
413         struct open_bucket *ob = NULL;
414         int ret;
415
416         s->cur_bucket = max_t(u64, s->cur_bucket, ca->mi.first_bucket);
417         s->cur_bucket = max_t(u64, s->cur_bucket, ca->new_fs_bucket_idx);
418
419         for_each_btree_key_norestart(trans, iter, BTREE_ID_alloc, POS(ca->dev_idx, s->cur_bucket),
420                            BTREE_ITER_SLOTS, k, ret) {
421                 struct bch_alloc_v4 a_convert;
422                 const struct bch_alloc_v4 *a;
423
424                 if (bkey_ge(k.k->p, POS(ca->dev_idx, ca->mi.nbuckets)))
425                         break;
426
427                 if (ca->new_fs_bucket_idx &&
428                     is_superblock_bucket(ca, k.k->p.offset))
429                         continue;
430
431                 a = bch2_alloc_to_v4(k, &a_convert);
432
433                 if (a->data_type != BCH_DATA_free)
434                         continue;
435
436                 s->buckets_seen++;
437
438                 ob = __try_alloc_bucket(trans->c, ca, k.k->p.offset, reserve, a, s, cl);
439                 if (ob)
440                         break;
441         }
442         bch2_trans_iter_exit(trans, &iter);
443
444         s->cur_bucket = iter.pos.offset;
445
446         return ob ?: ERR_PTR(ret ?: -BCH_ERR_no_buckets_found);
447 }
448
449 static struct open_bucket *bch2_bucket_alloc_freelist(struct btree_trans *trans,
450                                                    struct bch_dev *ca,
451                                                    enum alloc_reserve reserve,
452                                                    struct bucket_alloc_state *s,
453                                                    struct closure *cl)
454 {
455         struct btree_iter iter;
456         struct bkey_s_c k;
457         struct open_bucket *ob = NULL;
458         int ret;
459
460         BUG_ON(ca->new_fs_bucket_idx);
461
462         /*
463          * XXX:
464          * On transaction restart, we'd like to restart from the bucket we were
465          * at previously
466          */
467         for_each_btree_key_norestart(trans, iter, BTREE_ID_freespace,
468                                      POS(ca->dev_idx, s->cur_bucket), 0, k, ret) {
469                 if (k.k->p.inode != ca->dev_idx)
470                         break;
471
472                 for (s->cur_bucket = max(s->cur_bucket, bkey_start_offset(k.k));
473                      s->cur_bucket < k.k->p.offset;
474                      s->cur_bucket++) {
475                         ret = btree_trans_too_many_iters(trans);
476                         if (ret)
477                                 break;
478
479                         s->buckets_seen++;
480
481                         ob = try_alloc_bucket(trans, ca, reserve,
482                                               s->cur_bucket, s, k, cl);
483                         if (ob)
484                                 break;
485                 }
486
487                 if (ob || ret)
488                         break;
489         }
490         bch2_trans_iter_exit(trans, &iter);
491
492         return ob ?: ERR_PTR(ret);
493 }
494
495 /**
496  * bch_bucket_alloc - allocate a single bucket from a specific device
497  *
498  * Returns index of bucket on success, 0 on failure
499  */
500 static struct open_bucket *bch2_bucket_alloc_trans(struct btree_trans *trans,
501                                       struct bch_dev *ca,
502                                       enum alloc_reserve reserve,
503                                       bool may_alloc_partial,
504                                       struct closure *cl,
505                                       struct bch_dev_usage *usage)
506 {
507         struct bch_fs *c = trans->c;
508         struct open_bucket *ob = NULL;
509         bool freespace_initialized = READ_ONCE(ca->mi.freespace_initialized);
510         u64 start = freespace_initialized ? 0 : ca->bucket_alloc_trans_early_cursor;
511         u64 avail;
512         struct bucket_alloc_state s = { .cur_bucket = start };
513         bool waiting = false;
514 again:
515         bch2_dev_usage_read_fast(ca, usage);
516         avail = dev_buckets_free(ca, *usage, reserve);
517
518         if (usage->d[BCH_DATA_need_discard].buckets > avail)
519                 bch2_do_discards(c);
520
521         if (usage->d[BCH_DATA_need_gc_gens].buckets > avail)
522                 bch2_do_gc_gens(c);
523
524         if (should_invalidate_buckets(ca, *usage))
525                 bch2_do_invalidates(c);
526
527         if (!avail) {
528                 if (cl && !waiting) {
529                         closure_wait(&c->freelist_wait, cl);
530                         waiting = true;
531                         goto again;
532                 }
533
534                 if (!c->blocked_allocate)
535                         c->blocked_allocate = local_clock();
536
537                 ob = ERR_PTR(-BCH_ERR_freelist_empty);
538                 goto err;
539         }
540
541         if (waiting)
542                 closure_wake_up(&c->freelist_wait);
543
544         if (may_alloc_partial) {
545                 ob = try_alloc_partial_bucket(c, ca, reserve);
546                 if (ob)
547                         return ob;
548         }
549
550         ob = likely(ca->mi.freespace_initialized)
551                 ? bch2_bucket_alloc_freelist(trans, ca, reserve, &s, cl)
552                 : bch2_bucket_alloc_early(trans, ca, reserve, &s, cl);
553
554         if (s.skipped_need_journal_commit * 2 > avail)
555                 bch2_journal_flush_async(&c->journal, NULL);
556
557         if (!ob && !freespace_initialized && start) {
558                 start = s.cur_bucket = 0;
559                 goto again;
560         }
561
562         if (!freespace_initialized)
563                 ca->bucket_alloc_trans_early_cursor = s.cur_bucket;
564 err:
565         if (!ob)
566                 ob = ERR_PTR(-BCH_ERR_no_buckets_found);
567
568         if (!IS_ERR(ob))
569                 trace_and_count(c, bucket_alloc, ca, bch2_alloc_reserves[reserve],
570                                 may_alloc_partial, ob->bucket);
571         else if (!bch2_err_matches(PTR_ERR(ob), BCH_ERR_transaction_restart))
572                 trace_and_count(c, bucket_alloc_fail,
573                                 ca, bch2_alloc_reserves[reserve],
574                                 usage->d[BCH_DATA_free].buckets,
575                                 avail,
576                                 bch2_copygc_wait_amount(c),
577                                 c->copygc_wait - atomic64_read(&c->io_clock[WRITE].now),
578                                 &s,
579                                 cl == NULL,
580                                 bch2_err_str(PTR_ERR(ob)));
581
582         return ob;
583 }
584
585 struct open_bucket *bch2_bucket_alloc(struct bch_fs *c, struct bch_dev *ca,
586                                       enum alloc_reserve reserve,
587                                       bool may_alloc_partial,
588                                       struct closure *cl)
589 {
590         struct bch_dev_usage usage;
591         struct open_bucket *ob;
592
593         bch2_trans_do(c, NULL, NULL, 0,
594                       PTR_ERR_OR_ZERO(ob = bch2_bucket_alloc_trans(&trans, ca, reserve,
595                                                         may_alloc_partial, cl, &usage)));
596         return ob;
597 }
598
599 static int __dev_stripe_cmp(struct dev_stripe_state *stripe,
600                             unsigned l, unsigned r)
601 {
602         return ((stripe->next_alloc[l] > stripe->next_alloc[r]) -
603                 (stripe->next_alloc[l] < stripe->next_alloc[r]));
604 }
605
606 #define dev_stripe_cmp(l, r) __dev_stripe_cmp(stripe, l, r)
607
608 struct dev_alloc_list bch2_dev_alloc_list(struct bch_fs *c,
609                                           struct dev_stripe_state *stripe,
610                                           struct bch_devs_mask *devs)
611 {
612         struct dev_alloc_list ret = { .nr = 0 };
613         unsigned i;
614
615         for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX)
616                 ret.devs[ret.nr++] = i;
617
618         bubble_sort(ret.devs, ret.nr, dev_stripe_cmp);
619         return ret;
620 }
621
622 static inline void bch2_dev_stripe_increment_inlined(struct bch_dev *ca,
623                                struct dev_stripe_state *stripe,
624                                struct bch_dev_usage *usage)
625 {
626         u64 *v = stripe->next_alloc + ca->dev_idx;
627         u64 free_space = dev_buckets_available(ca, RESERVE_none);
628         u64 free_space_inv = free_space
629                 ? div64_u64(1ULL << 48, free_space)
630                 : 1ULL << 48;
631         u64 scale = *v / 4;
632
633         if (*v + free_space_inv >= *v)
634                 *v += free_space_inv;
635         else
636                 *v = U64_MAX;
637
638         for (v = stripe->next_alloc;
639              v < stripe->next_alloc + ARRAY_SIZE(stripe->next_alloc); v++)
640                 *v = *v < scale ? 0 : *v - scale;
641 }
642
643 void bch2_dev_stripe_increment(struct bch_dev *ca,
644                                struct dev_stripe_state *stripe)
645 {
646         struct bch_dev_usage usage;
647
648         bch2_dev_usage_read_fast(ca, &usage);
649         bch2_dev_stripe_increment_inlined(ca, stripe, &usage);
650 }
651
652 #define BUCKET_MAY_ALLOC_PARTIAL        (1 << 0)
653 #define BUCKET_ALLOC_USE_DURABILITY     (1 << 1)
654
655 static void add_new_bucket(struct bch_fs *c,
656                            struct open_buckets *ptrs,
657                            struct bch_devs_mask *devs_may_alloc,
658                            unsigned *nr_effective,
659                            bool *have_cache,
660                            unsigned flags,
661                            struct open_bucket *ob)
662 {
663         unsigned durability =
664                 bch_dev_bkey_exists(c, ob->dev)->mi.durability;
665
666         __clear_bit(ob->dev, devs_may_alloc->d);
667         *nr_effective   += (flags & BUCKET_ALLOC_USE_DURABILITY)
668                 ? durability : 1;
669         *have_cache     |= !durability;
670
671         ob_push(c, ptrs, ob);
672 }
673
674 static int bch2_bucket_alloc_set_trans(struct btree_trans *trans,
675                       struct open_buckets *ptrs,
676                       struct dev_stripe_state *stripe,
677                       struct bch_devs_mask *devs_may_alloc,
678                       unsigned nr_replicas,
679                       unsigned *nr_effective,
680                       bool *have_cache,
681                       enum alloc_reserve reserve,
682                       unsigned flags,
683                       struct closure *cl)
684 {
685         struct bch_fs *c = trans->c;
686         struct dev_alloc_list devs_sorted =
687                 bch2_dev_alloc_list(c, stripe, devs_may_alloc);
688         unsigned dev;
689         struct bch_dev *ca;
690         int ret = -BCH_ERR_insufficient_devices;
691         unsigned i;
692
693         BUG_ON(*nr_effective >= nr_replicas);
694
695         for (i = 0; i < devs_sorted.nr; i++) {
696                 struct bch_dev_usage usage;
697                 struct open_bucket *ob;
698
699                 dev = devs_sorted.devs[i];
700
701                 rcu_read_lock();
702                 ca = rcu_dereference(c->devs[dev]);
703                 if (ca)
704                         percpu_ref_get(&ca->ref);
705                 rcu_read_unlock();
706
707                 if (!ca)
708                         continue;
709
710                 if (!ca->mi.durability && *have_cache) {
711                         percpu_ref_put(&ca->ref);
712                         continue;
713                 }
714
715                 ob = bch2_bucket_alloc_trans(trans, ca, reserve,
716                                 flags & BUCKET_MAY_ALLOC_PARTIAL, cl, &usage);
717                 if (!IS_ERR(ob))
718                         bch2_dev_stripe_increment_inlined(ca, stripe, &usage);
719                 percpu_ref_put(&ca->ref);
720
721                 if (IS_ERR(ob)) {
722                         ret = PTR_ERR(ob);
723                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart) || cl)
724                                 break;
725                         continue;
726                 }
727
728                 add_new_bucket(c, ptrs, devs_may_alloc,
729                                nr_effective, have_cache, flags, ob);
730
731                 if (*nr_effective >= nr_replicas) {
732                         ret = 0;
733                         break;
734                 }
735         }
736
737         return ret;
738 }
739
740 int bch2_bucket_alloc_set(struct bch_fs *c,
741                       struct open_buckets *ptrs,
742                       struct dev_stripe_state *stripe,
743                       struct bch_devs_mask *devs_may_alloc,
744                       unsigned nr_replicas,
745                       unsigned *nr_effective,
746                       bool *have_cache,
747                       enum alloc_reserve reserve,
748                       unsigned flags,
749                       struct closure *cl)
750 {
751         return bch2_trans_do(c, NULL, NULL, 0,
752                       bch2_bucket_alloc_set_trans(&trans, ptrs, stripe,
753                                               devs_may_alloc, nr_replicas,
754                                               nr_effective, have_cache, reserve,
755                                               flags, cl));
756 }
757
758 /* Allocate from stripes: */
759
760 /*
761  * if we can't allocate a new stripe because there are already too many
762  * partially filled stripes, force allocating from an existing stripe even when
763  * it's to a device we don't want:
764  */
765
766 static int bucket_alloc_from_stripe(struct bch_fs *c,
767                          struct open_buckets *ptrs,
768                          struct write_point *wp,
769                          struct bch_devs_mask *devs_may_alloc,
770                          u16 target,
771                          unsigned erasure_code,
772                          unsigned nr_replicas,
773                          unsigned *nr_effective,
774                          bool *have_cache,
775                          unsigned flags,
776                          struct closure *cl)
777 {
778         struct dev_alloc_list devs_sorted;
779         struct ec_stripe_head *h;
780         struct open_bucket *ob;
781         struct bch_dev *ca;
782         unsigned i, ec_idx;
783
784         if (!erasure_code)
785                 return 0;
786
787         if (nr_replicas < 2)
788                 return 0;
789
790         if (ec_open_bucket(c, ptrs))
791                 return 0;
792
793         h = bch2_ec_stripe_head_get(c, target, 0, nr_replicas - 1,
794                                     wp == &c->copygc_write_point,
795                                     cl);
796         if (IS_ERR(h))
797                 return -PTR_ERR(h);
798         if (!h)
799                 return 0;
800
801         devs_sorted = bch2_dev_alloc_list(c, &wp->stripe, devs_may_alloc);
802
803         for (i = 0; i < devs_sorted.nr; i++)
804                 for (ec_idx = 0; ec_idx < h->s->nr_data; ec_idx++) {
805                         if (!h->s->blocks[ec_idx])
806                                 continue;
807
808                         ob = c->open_buckets + h->s->blocks[ec_idx];
809                         if (ob->dev == devs_sorted.devs[i] &&
810                             !test_and_set_bit(ec_idx, h->s->blocks_allocated))
811                                 goto got_bucket;
812                 }
813         goto out_put_head;
814 got_bucket:
815         ca = bch_dev_bkey_exists(c, ob->dev);
816
817         ob->ec_idx      = ec_idx;
818         ob->ec          = h->s;
819
820         add_new_bucket(c, ptrs, devs_may_alloc,
821                        nr_effective, have_cache, flags, ob);
822         atomic_inc(&h->s->pin);
823 out_put_head:
824         bch2_ec_stripe_head_put(c, h);
825         return 0;
826 }
827
828 /* Sector allocator */
829
830 static void get_buckets_from_writepoint(struct bch_fs *c,
831                                         struct open_buckets *ptrs,
832                                         struct write_point *wp,
833                                         struct bch_devs_mask *devs_may_alloc,
834                                         unsigned nr_replicas,
835                                         unsigned *nr_effective,
836                                         bool *have_cache,
837                                         unsigned flags,
838                                         bool need_ec)
839 {
840         struct open_buckets ptrs_skip = { .nr = 0 };
841         struct open_bucket *ob;
842         unsigned i;
843
844         open_bucket_for_each(c, &wp->ptrs, ob, i) {
845                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
846
847                 if (*nr_effective < nr_replicas &&
848                     test_bit(ob->dev, devs_may_alloc->d) &&
849                     (ca->mi.durability ||
850                      (wp->data_type == BCH_DATA_user && !*have_cache)) &&
851                     (ob->ec || !need_ec)) {
852                         add_new_bucket(c, ptrs, devs_may_alloc,
853                                        nr_effective, have_cache,
854                                        flags, ob);
855                 } else {
856                         ob_push(c, &ptrs_skip, ob);
857                 }
858         }
859         wp->ptrs = ptrs_skip;
860 }
861
862 static int open_bucket_add_buckets(struct btree_trans *trans,
863                         struct open_buckets *ptrs,
864                         struct write_point *wp,
865                         struct bch_devs_list *devs_have,
866                         u16 target,
867                         unsigned erasure_code,
868                         unsigned nr_replicas,
869                         unsigned *nr_effective,
870                         bool *have_cache,
871                         enum alloc_reserve reserve,
872                         unsigned flags,
873                         struct closure *_cl)
874 {
875         struct bch_fs *c = trans->c;
876         struct bch_devs_mask devs;
877         struct open_bucket *ob;
878         struct closure *cl = NULL;
879         int ret;
880         unsigned i;
881
882         rcu_read_lock();
883         devs = target_rw_devs(c, wp->data_type, target);
884         rcu_read_unlock();
885
886         /* Don't allocate from devices we already have pointers to: */
887         for (i = 0; i < devs_have->nr; i++)
888                 __clear_bit(devs_have->devs[i], devs.d);
889
890         open_bucket_for_each(c, ptrs, ob, i)
891                 __clear_bit(ob->dev, devs.d);
892
893         if (erasure_code) {
894                 if (!ec_open_bucket(c, ptrs)) {
895                         get_buckets_from_writepoint(c, ptrs, wp, &devs,
896                                                     nr_replicas, nr_effective,
897                                                     have_cache, flags, true);
898                         if (*nr_effective >= nr_replicas)
899                                 return 0;
900                 }
901
902                 if (!ec_open_bucket(c, ptrs)) {
903                         ret = bucket_alloc_from_stripe(c, ptrs, wp, &devs,
904                                                  target, erasure_code,
905                                                  nr_replicas, nr_effective,
906                                                  have_cache, flags, _cl);
907                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
908                             bch2_err_matches(ret, BCH_ERR_freelist_empty) ||
909                             bch2_err_matches(ret, BCH_ERR_open_buckets_empty))
910                                 return ret;
911                         if (*nr_effective >= nr_replicas)
912                                 return 0;
913                 }
914         }
915
916         get_buckets_from_writepoint(c, ptrs, wp, &devs,
917                                     nr_replicas, nr_effective,
918                                     have_cache, flags, false);
919         if (*nr_effective >= nr_replicas)
920                 return 0;
921
922 retry_blocking:
923         /*
924          * Try nonblocking first, so that if one device is full we'll try from
925          * other devices:
926          */
927         ret = bch2_bucket_alloc_set_trans(trans, ptrs, &wp->stripe, &devs,
928                                 nr_replicas, nr_effective, have_cache,
929                                 reserve, flags, cl);
930         if (ret &&
931             !bch2_err_matches(ret, BCH_ERR_transaction_restart) &&
932             !bch2_err_matches(ret, BCH_ERR_insufficient_devices) &&
933             !cl && _cl) {
934                 cl = _cl;
935                 goto retry_blocking;
936         }
937
938         return ret;
939 }
940
941 void bch2_open_buckets_stop_dev(struct bch_fs *c, struct bch_dev *ca,
942                                 struct open_buckets *obs)
943 {
944         struct open_buckets ptrs = { .nr = 0 };
945         struct open_bucket *ob, *ob2;
946         unsigned i, j;
947
948         open_bucket_for_each(c, obs, ob, i) {
949                 bool drop = !ca || ob->dev == ca->dev_idx;
950
951                 if (!drop && ob->ec) {
952                         mutex_lock(&ob->ec->lock);
953                         for (j = 0; j < ob->ec->new_stripe.key.v.nr_blocks; j++) {
954                                 if (!ob->ec->blocks[j])
955                                         continue;
956
957                                 ob2 = c->open_buckets + ob->ec->blocks[j];
958                                 drop |= ob2->dev == ca->dev_idx;
959                         }
960                         mutex_unlock(&ob->ec->lock);
961                 }
962
963                 if (drop)
964                         bch2_open_bucket_put(c, ob);
965                 else
966                         ob_push(c, &ptrs, ob);
967         }
968
969         *obs = ptrs;
970 }
971
972 void bch2_writepoint_stop(struct bch_fs *c, struct bch_dev *ca,
973                           struct write_point *wp)
974 {
975         mutex_lock(&wp->lock);
976         bch2_open_buckets_stop_dev(c, ca, &wp->ptrs);
977         mutex_unlock(&wp->lock);
978 }
979
980 static inline struct hlist_head *writepoint_hash(struct bch_fs *c,
981                                                  unsigned long write_point)
982 {
983         unsigned hash =
984                 hash_long(write_point, ilog2(ARRAY_SIZE(c->write_points_hash)));
985
986         return &c->write_points_hash[hash];
987 }
988
989 static struct write_point *__writepoint_find(struct hlist_head *head,
990                                              unsigned long write_point)
991 {
992         struct write_point *wp;
993
994         rcu_read_lock();
995         hlist_for_each_entry_rcu(wp, head, node)
996                 if (wp->write_point == write_point)
997                         goto out;
998         wp = NULL;
999 out:
1000         rcu_read_unlock();
1001         return wp;
1002 }
1003
1004 static inline bool too_many_writepoints(struct bch_fs *c, unsigned factor)
1005 {
1006         u64 stranded    = c->write_points_nr * c->bucket_size_max;
1007         u64 free        = bch2_fs_usage_read_short(c).free;
1008
1009         return stranded * factor > free;
1010 }
1011
1012 static bool try_increase_writepoints(struct bch_fs *c)
1013 {
1014         struct write_point *wp;
1015
1016         if (c->write_points_nr == ARRAY_SIZE(c->write_points) ||
1017             too_many_writepoints(c, 32))
1018                 return false;
1019
1020         wp = c->write_points + c->write_points_nr++;
1021         hlist_add_head_rcu(&wp->node, writepoint_hash(c, wp->write_point));
1022         return true;
1023 }
1024
1025 static bool try_decrease_writepoints(struct bch_fs *c,
1026                                      unsigned old_nr)
1027 {
1028         struct write_point *wp;
1029
1030         mutex_lock(&c->write_points_hash_lock);
1031         if (c->write_points_nr < old_nr) {
1032                 mutex_unlock(&c->write_points_hash_lock);
1033                 return true;
1034         }
1035
1036         if (c->write_points_nr == 1 ||
1037             !too_many_writepoints(c, 8)) {
1038                 mutex_unlock(&c->write_points_hash_lock);
1039                 return false;
1040         }
1041
1042         wp = c->write_points + --c->write_points_nr;
1043
1044         hlist_del_rcu(&wp->node);
1045         mutex_unlock(&c->write_points_hash_lock);
1046
1047         bch2_writepoint_stop(c, NULL, wp);
1048         return true;
1049 }
1050
1051 static void bch2_trans_mutex_lock(struct btree_trans *trans,
1052                                   struct mutex *lock)
1053 {
1054         if (!mutex_trylock(lock)) {
1055                 bch2_trans_unlock(trans);
1056                 mutex_lock(lock);
1057         }
1058 }
1059
1060 static struct write_point *writepoint_find(struct btree_trans *trans,
1061                                            unsigned long write_point)
1062 {
1063         struct bch_fs *c = trans->c;
1064         struct write_point *wp, *oldest;
1065         struct hlist_head *head;
1066
1067         if (!(write_point & 1UL)) {
1068                 wp = (struct write_point *) write_point;
1069                 bch2_trans_mutex_lock(trans, &wp->lock);
1070                 return wp;
1071         }
1072
1073         head = writepoint_hash(c, write_point);
1074 restart_find:
1075         wp = __writepoint_find(head, write_point);
1076         if (wp) {
1077 lock_wp:
1078                 bch2_trans_mutex_lock(trans, &wp->lock);
1079                 if (wp->write_point == write_point)
1080                         goto out;
1081                 mutex_unlock(&wp->lock);
1082                 goto restart_find;
1083         }
1084 restart_find_oldest:
1085         oldest = NULL;
1086         for (wp = c->write_points;
1087              wp < c->write_points + c->write_points_nr; wp++)
1088                 if (!oldest || time_before64(wp->last_used, oldest->last_used))
1089                         oldest = wp;
1090
1091         bch2_trans_mutex_lock(trans, &oldest->lock);
1092         bch2_trans_mutex_lock(trans, &c->write_points_hash_lock);
1093         if (oldest >= c->write_points + c->write_points_nr ||
1094             try_increase_writepoints(c)) {
1095                 mutex_unlock(&c->write_points_hash_lock);
1096                 mutex_unlock(&oldest->lock);
1097                 goto restart_find_oldest;
1098         }
1099
1100         wp = __writepoint_find(head, write_point);
1101         if (wp && wp != oldest) {
1102                 mutex_unlock(&c->write_points_hash_lock);
1103                 mutex_unlock(&oldest->lock);
1104                 goto lock_wp;
1105         }
1106
1107         wp = oldest;
1108         hlist_del_rcu(&wp->node);
1109         wp->write_point = write_point;
1110         hlist_add_head_rcu(&wp->node, head);
1111         mutex_unlock(&c->write_points_hash_lock);
1112 out:
1113         wp->last_used = local_clock();
1114         return wp;
1115 }
1116
1117 /*
1118  * Get us an open_bucket we can allocate from, return with it locked:
1119  */
1120 int bch2_alloc_sectors_start_trans(struct btree_trans *trans,
1121                                    unsigned target,
1122                                    unsigned erasure_code,
1123                                    struct write_point_specifier write_point,
1124                                    struct bch_devs_list *devs_have,
1125                                    unsigned nr_replicas,
1126                                    unsigned nr_replicas_required,
1127                                    enum alloc_reserve reserve,
1128                                    unsigned flags,
1129                                    struct closure *cl,
1130                                    struct write_point **wp_ret)
1131 {
1132         struct bch_fs *c = trans->c;
1133         struct write_point *wp;
1134         struct open_bucket *ob;
1135         struct open_buckets ptrs;
1136         unsigned nr_effective, write_points_nr;
1137         unsigned ob_flags = 0;
1138         bool have_cache;
1139         int ret;
1140         int i;
1141
1142         if (!(flags & BCH_WRITE_ONLY_SPECIFIED_DEVS))
1143                 ob_flags |= BUCKET_ALLOC_USE_DURABILITY;
1144
1145         BUG_ON(!nr_replicas || !nr_replicas_required);
1146 retry:
1147         ptrs.nr         = 0;
1148         nr_effective    = 0;
1149         write_points_nr = c->write_points_nr;
1150         have_cache      = false;
1151
1152         *wp_ret = wp = writepoint_find(trans, write_point.v);
1153
1154         if (wp->data_type == BCH_DATA_user)
1155                 ob_flags |= BUCKET_MAY_ALLOC_PARTIAL;
1156
1157         /* metadata may not allocate on cache devices: */
1158         if (wp->data_type != BCH_DATA_user)
1159                 have_cache = true;
1160
1161         if (!target || (flags & BCH_WRITE_ONLY_SPECIFIED_DEVS)) {
1162                 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1163                                               target, erasure_code,
1164                                               nr_replicas, &nr_effective,
1165                                               &have_cache, reserve,
1166                                               ob_flags, cl);
1167         } else {
1168                 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1169                                               target, erasure_code,
1170                                               nr_replicas, &nr_effective,
1171                                               &have_cache, reserve,
1172                                               ob_flags, NULL);
1173                 if (!ret ||
1174                     bch2_err_matches(ret, BCH_ERR_transaction_restart))
1175                         goto alloc_done;
1176
1177                 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1178                                               0, erasure_code,
1179                                               nr_replicas, &nr_effective,
1180                                               &have_cache, reserve,
1181                                               ob_flags, cl);
1182         }
1183 alloc_done:
1184         BUG_ON(!ret && nr_effective < nr_replicas);
1185
1186         if (erasure_code && !ec_open_bucket(c, &ptrs))
1187                 pr_debug("failed to get ec bucket: ret %u", ret);
1188
1189         if (ret == -BCH_ERR_insufficient_devices &&
1190             nr_effective >= nr_replicas_required)
1191                 ret = 0;
1192
1193         if (ret)
1194                 goto err;
1195
1196         /* Free buckets we didn't use: */
1197         open_bucket_for_each(c, &wp->ptrs, ob, i)
1198                 open_bucket_free_unused(c, wp, ob);
1199
1200         wp->ptrs = ptrs;
1201
1202         wp->sectors_free = UINT_MAX;
1203
1204         open_bucket_for_each(c, &wp->ptrs, ob, i)
1205                 wp->sectors_free = min(wp->sectors_free, ob->sectors_free);
1206
1207         BUG_ON(!wp->sectors_free || wp->sectors_free == UINT_MAX);
1208
1209         return 0;
1210 err:
1211         open_bucket_for_each(c, &wp->ptrs, ob, i)
1212                 if (ptrs.nr < ARRAY_SIZE(ptrs.v))
1213                         ob_push(c, &ptrs, ob);
1214                 else
1215                         open_bucket_free_unused(c, wp, ob);
1216         wp->ptrs = ptrs;
1217
1218         mutex_unlock(&wp->lock);
1219
1220         if (bch2_err_matches(ret, BCH_ERR_freelist_empty) &&
1221             try_decrease_writepoints(c, write_points_nr))
1222                 goto retry;
1223
1224         if (bch2_err_matches(ret, BCH_ERR_open_buckets_empty) ||
1225             bch2_err_matches(ret, BCH_ERR_freelist_empty))
1226                 return cl
1227                         ? -EAGAIN
1228                         : -BCH_ERR_ENOSPC_bucket_alloc;
1229
1230         if (bch2_err_matches(ret, BCH_ERR_insufficient_devices))
1231                 return -EROFS;
1232
1233         return ret;
1234 }
1235
1236 struct bch_extent_ptr bch2_ob_ptr(struct bch_fs *c, struct open_bucket *ob)
1237 {
1238         struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
1239
1240         return (struct bch_extent_ptr) {
1241                 .type   = 1 << BCH_EXTENT_ENTRY_ptr,
1242                 .gen    = ob->gen,
1243                 .dev    = ob->dev,
1244                 .offset = bucket_to_sector(ca, ob->bucket) +
1245                         ca->mi.bucket_size -
1246                         ob->sectors_free,
1247         };
1248 }
1249
1250 void bch2_alloc_sectors_append_ptrs(struct bch_fs *c, struct write_point *wp,
1251                                     struct bkey_i *k, unsigned sectors,
1252                                     bool cached)
1253 {
1254         bch2_alloc_sectors_append_ptrs_inlined(c, wp, k, sectors, cached);
1255 }
1256
1257 /*
1258  * Append pointers to the space we just allocated to @k, and mark @sectors space
1259  * as allocated out of @ob
1260  */
1261 void bch2_alloc_sectors_done(struct bch_fs *c, struct write_point *wp)
1262 {
1263         bch2_alloc_sectors_done_inlined(c, wp);
1264 }
1265
1266 static inline void writepoint_init(struct write_point *wp,
1267                                    enum bch_data_type type)
1268 {
1269         mutex_init(&wp->lock);
1270         wp->data_type = type;
1271
1272         INIT_WORK(&wp->index_update_work, bch2_write_point_do_index_updates);
1273         INIT_LIST_HEAD(&wp->writes);
1274         spin_lock_init(&wp->writes_lock);
1275 }
1276
1277 void bch2_fs_allocator_foreground_init(struct bch_fs *c)
1278 {
1279         struct open_bucket *ob;
1280         struct write_point *wp;
1281
1282         mutex_init(&c->write_points_hash_lock);
1283         c->write_points_nr = ARRAY_SIZE(c->write_points);
1284
1285         /* open bucket 0 is a sentinal NULL: */
1286         spin_lock_init(&c->open_buckets[0].lock);
1287
1288         for (ob = c->open_buckets + 1;
1289              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets); ob++) {
1290                 spin_lock_init(&ob->lock);
1291                 c->open_buckets_nr_free++;
1292
1293                 ob->freelist = c->open_buckets_freelist;
1294                 c->open_buckets_freelist = ob - c->open_buckets;
1295         }
1296
1297         writepoint_init(&c->btree_write_point,          BCH_DATA_btree);
1298         writepoint_init(&c->rebalance_write_point,      BCH_DATA_user);
1299         writepoint_init(&c->copygc_write_point,         BCH_DATA_user);
1300
1301         for (wp = c->write_points;
1302              wp < c->write_points + c->write_points_nr; wp++) {
1303                 writepoint_init(wp, BCH_DATA_user);
1304
1305                 wp->last_used   = local_clock();
1306                 wp->write_point = (unsigned long) wp;
1307                 hlist_add_head_rcu(&wp->node,
1308                                    writepoint_hash(c, wp->write_point));
1309         }
1310 }
1311
1312 void bch2_open_buckets_to_text(struct printbuf *out, struct bch_fs *c)
1313 {
1314         struct open_bucket *ob;
1315
1316         for (ob = c->open_buckets;
1317              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1318              ob++) {
1319                 spin_lock(&ob->lock);
1320                 if (ob->valid && !ob->on_partial_list) {
1321                         prt_printf(out, "%zu ref %u type %s %u:%llu:%u\n",
1322                                ob - c->open_buckets,
1323                                atomic_read(&ob->pin),
1324                                bch2_data_types[ob->data_type],
1325                                ob->dev, ob->bucket, ob->gen);
1326                 }
1327                 spin_unlock(&ob->lock);
1328         }
1329 }