]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_foreground.c
Update bcachefs sources to 61ebcb532a bcachefs: Fix for allocating before backpointer...
[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                                               struct bch_alloc_v4 *a,
198                                               u64 *skipped_open,
199                                               u64 *skipped_need_journal_commit,
200                                               u64 *skipped_nouse,
201                                               struct closure *cl)
202 {
203         struct open_bucket *ob;
204
205         if (unlikely(ca->buckets_nouse && test_bit(bucket, ca->buckets_nouse))) {
206                 (*skipped_nouse)++;
207                 return NULL;
208         }
209
210         if (bch2_bucket_is_open(c, ca->dev_idx, bucket)) {
211                 (*skipped_open)++;
212                 return NULL;
213         }
214
215         if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
216                         c->journal.flushed_seq_ondisk, ca->dev_idx, bucket)) {
217                 (*skipped_need_journal_commit)++;
218                 return NULL;
219         }
220
221         spin_lock(&c->freelist_lock);
222
223         if (unlikely(c->open_buckets_nr_free <= open_buckets_reserved(reserve))) {
224                 if (cl)
225                         closure_wait(&c->open_buckets_wait, cl);
226
227                 if (!c->blocked_allocate_open_bucket)
228                         c->blocked_allocate_open_bucket = local_clock();
229
230                 spin_unlock(&c->freelist_lock);
231                 return ERR_PTR(-BCH_ERR_open_buckets_empty);
232         }
233
234         /* Recheck under lock: */
235         if (bch2_bucket_is_open(c, ca->dev_idx, bucket)) {
236                 spin_unlock(&c->freelist_lock);
237                 (*skipped_open)++;
238                 return NULL;
239         }
240
241         ob = bch2_open_bucket_alloc(c);
242
243         spin_lock(&ob->lock);
244
245         ob->valid       = true;
246         ob->sectors_free = ca->mi.bucket_size;
247         ob->alloc_reserve = reserve;
248         ob->dev         = ca->dev_idx;
249         ob->gen         = a->gen;
250         ob->bucket      = bucket;
251         spin_unlock(&ob->lock);
252
253         ca->nr_open_buckets++;
254         bch2_open_bucket_hash_add(c, ob);
255
256         if (c->blocked_allocate_open_bucket) {
257                 bch2_time_stats_update(
258                         &c->times[BCH_TIME_blocked_allocate_open_bucket],
259                         c->blocked_allocate_open_bucket);
260                 c->blocked_allocate_open_bucket = 0;
261         }
262
263         if (c->blocked_allocate) {
264                 bch2_time_stats_update(
265                         &c->times[BCH_TIME_blocked_allocate],
266                         c->blocked_allocate);
267                 c->blocked_allocate = 0;
268         }
269
270         spin_unlock(&c->freelist_lock);
271
272         return ob;
273 }
274
275 static struct open_bucket *try_alloc_bucket(struct btree_trans *trans, struct bch_dev *ca,
276                                             enum alloc_reserve reserve, u64 free_entry,
277                                             u64 *skipped_open,
278                                             u64 *skipped_need_journal_commit,
279                                             u64 *skipped_nouse,
280                                             struct bkey_s_c freespace_k,
281                                             struct closure *cl)
282 {
283         struct bch_fs *c = trans->c;
284         struct btree_iter iter = { NULL };
285         struct bkey_s_c k;
286         struct open_bucket *ob;
287         struct bch_alloc_v4 a;
288         u64 b = free_entry & ~(~0ULL << 56);
289         unsigned genbits = free_entry >> 56;
290         struct printbuf buf = PRINTBUF;
291         int ret;
292
293         if (b < ca->mi.first_bucket || b >= ca->mi.nbuckets) {
294                 prt_printf(&buf, "freespace btree has bucket outside allowed range %u-%llu\n"
295                        "  freespace key ",
296                         ca->mi.first_bucket, ca->mi.nbuckets);
297                 bch2_bkey_val_to_text(&buf, c, freespace_k);
298                 bch2_trans_inconsistent(trans, "%s", buf.buf);
299                 ob = ERR_PTR(-EIO);
300                 goto err;
301         }
302
303         bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, POS(ca->dev_idx, b), BTREE_ITER_CACHED);
304         k = bch2_btree_iter_peek_slot(&iter);
305         ret = bkey_err(k);
306         if (ret) {
307                 ob = ERR_PTR(ret);
308                 goto err;
309         }
310
311         bch2_alloc_to_v4(k, &a);
312
313         if (genbits != (alloc_freespace_genbits(a) >> 56)) {
314                 prt_printf(&buf, "bucket in freespace btree with wrong genbits (got %u should be %llu)\n"
315                        "  freespace key ",
316                        genbits, alloc_freespace_genbits(a) >> 56);
317                 bch2_bkey_val_to_text(&buf, c, freespace_k);
318                 prt_printf(&buf, "\n  ");
319                 bch2_bkey_val_to_text(&buf, c, k);
320                 bch2_trans_inconsistent(trans, "%s", buf.buf);
321                 ob = ERR_PTR(-EIO);
322                 goto err;
323
324         }
325
326         if (a.data_type != BCH_DATA_free) {
327                 prt_printf(&buf, "non free bucket in freespace btree\n"
328                        "  freespace key ");
329                 bch2_bkey_val_to_text(&buf, c, freespace_k);
330                 prt_printf(&buf, "\n  ");
331                 bch2_bkey_val_to_text(&buf, c, k);
332                 bch2_trans_inconsistent(trans, "%s", buf.buf);
333                 ob = ERR_PTR(-EIO);
334                 goto err;
335         }
336
337         if (!test_bit(BCH_FS_CHECK_BACKPOINTERS_DONE, &c->flags)) {
338                 struct bch_backpointer bp;
339                 u64 bp_offset = 0;
340
341                 ret = bch2_get_next_backpointer(trans, POS(ca->dev_idx, b), -1,
342                                                 &bp_offset, &bp, 0);
343                 if (ret) {
344                         ob = ERR_PTR(ret);
345                         goto err;
346                 }
347
348                 if (bp_offset != U64_MAX) {
349                         /*
350                          * Bucket may have data in it - we don't call
351                          * bc2h_trans_inconnsistent() because fsck hasn't
352                          * finished yet
353                          */
354                         ob = NULL;
355                         goto err;
356                 }
357         }
358
359         ob = __try_alloc_bucket(c, ca, b, reserve, &a,
360                                 skipped_open,
361                                 skipped_need_journal_commit,
362                                 skipped_nouse,
363                                 cl);
364         if (!ob)
365                 iter.path->preserve = false;
366 err:
367         set_btree_iter_dontneed(&iter);
368         bch2_trans_iter_exit(trans, &iter);
369         printbuf_exit(&buf);
370         return ob;
371 }
372
373 static struct open_bucket *try_alloc_partial_bucket(struct bch_fs *c, struct bch_dev *ca,
374                                                     enum alloc_reserve reserve)
375 {
376         struct open_bucket *ob;
377         int i;
378
379         spin_lock(&c->freelist_lock);
380
381         for (i = ca->open_buckets_partial_nr - 1; i >= 0; --i) {
382                 ob = c->open_buckets + ca->open_buckets_partial[i];
383
384                 if (reserve <= ob->alloc_reserve) {
385                         array_remove_item(ca->open_buckets_partial,
386                                           ca->open_buckets_partial_nr,
387                                           i);
388                         ob->on_partial_list = false;
389                         ob->alloc_reserve = reserve;
390                         spin_unlock(&c->freelist_lock);
391                         return ob;
392                 }
393         }
394
395         spin_unlock(&c->freelist_lock);
396         return NULL;
397 }
398
399 /*
400  * This path is for before the freespace btree is initialized:
401  *
402  * If ca->new_fs_bucket_idx is nonzero, we haven't yet marked superblock &
403  * journal buckets - journal buckets will be < ca->new_fs_bucket_idx
404  */
405 static noinline struct open_bucket *
406 bch2_bucket_alloc_early(struct btree_trans *trans,
407                         struct bch_dev *ca,
408                         enum alloc_reserve reserve,
409                         u64 *cur_bucket,
410                         u64 *buckets_seen,
411                         u64 *skipped_open,
412                         u64 *skipped_need_journal_commit,
413                         u64 *skipped_nouse,
414                         struct closure *cl)
415 {
416         struct btree_iter iter;
417         struct bkey_s_c k;
418         struct open_bucket *ob = NULL;
419         int ret;
420
421         *cur_bucket = max_t(u64, *cur_bucket, ca->mi.first_bucket);
422         *cur_bucket = max_t(u64, *cur_bucket, ca->new_fs_bucket_idx);
423
424         for_each_btree_key_norestart(trans, iter, BTREE_ID_alloc, POS(ca->dev_idx, *cur_bucket),
425                            BTREE_ITER_SLOTS, k, ret) {
426                 struct bch_alloc_v4 a;
427
428                 if (bkey_cmp(k.k->p, POS(ca->dev_idx, ca->mi.nbuckets)) >= 0)
429                         break;
430
431                 if (ca->new_fs_bucket_idx &&
432                     is_superblock_bucket(ca, k.k->p.offset))
433                         continue;
434
435                 bch2_alloc_to_v4(k, &a);
436
437                 if (a.data_type != BCH_DATA_free)
438                         continue;
439
440                 (*buckets_seen)++;
441
442                 ob = __try_alloc_bucket(trans->c, ca, k.k->p.offset, reserve, &a,
443                                         skipped_open,
444                                         skipped_need_journal_commit,
445                                         skipped_nouse,
446                                         cl);
447                 if (ob)
448                         break;
449         }
450         bch2_trans_iter_exit(trans, &iter);
451
452         *cur_bucket = iter.pos.offset;
453
454         return ob ?: ERR_PTR(ret ?: -BCH_ERR_no_buckets_found);
455 }
456
457 static struct open_bucket *bch2_bucket_alloc_freelist(struct btree_trans *trans,
458                                                    struct bch_dev *ca,
459                                                    enum alloc_reserve reserve,
460                                                    u64 *cur_bucket,
461                                                    u64 *buckets_seen,
462                                                    u64 *skipped_open,
463                                                    u64 *skipped_need_journal_commit,
464                                                    u64 *skipped_nouse,
465                                                    struct closure *cl)
466 {
467         struct btree_iter iter;
468         struct bkey_s_c k;
469         struct open_bucket *ob = NULL;
470         int ret;
471
472         BUG_ON(ca->new_fs_bucket_idx);
473
474         /*
475          * XXX:
476          * On transaction restart, we'd like to restart from the bucket we were
477          * at previously
478          */
479         for_each_btree_key_norestart(trans, iter, BTREE_ID_freespace,
480                                      POS(ca->dev_idx, *cur_bucket), 0, k, ret) {
481                 if (k.k->p.inode != ca->dev_idx)
482                         break;
483
484                 for (*cur_bucket = max(*cur_bucket, bkey_start_offset(k.k));
485                      *cur_bucket < k.k->p.offset;
486                      (*cur_bucket)++) {
487                         ret = btree_trans_too_many_iters(trans);
488                         if (ret)
489                                 break;
490
491                         (*buckets_seen)++;
492
493                         ob = try_alloc_bucket(trans, ca, reserve,
494                                               *cur_bucket,
495                                               skipped_open,
496                                               skipped_need_journal_commit,
497                                               skipped_nouse,
498                                               k, cl);
499                         if (ob)
500                                 break;
501                 }
502
503                 if (ob || ret)
504                         break;
505         }
506         bch2_trans_iter_exit(trans, &iter);
507
508         return ob ?: ERR_PTR(ret);
509 }
510
511 /**
512  * bch_bucket_alloc - allocate a single bucket from a specific device
513  *
514  * Returns index of bucket on success, 0 on failure
515  */
516 static struct open_bucket *bch2_bucket_alloc_trans(struct btree_trans *trans,
517                                       struct bch_dev *ca,
518                                       enum alloc_reserve reserve,
519                                       bool may_alloc_partial,
520                                       struct closure *cl,
521                                       struct bch_dev_usage *usage)
522 {
523         struct bch_fs *c = trans->c;
524         struct open_bucket *ob = NULL;
525         bool freespace_initialized = READ_ONCE(ca->mi.freespace_initialized);
526         u64 start = freespace_initialized ? 0 : ca->bucket_alloc_trans_early_cursor;
527         u64 avail;
528         u64 cur_bucket = start;
529         u64 buckets_seen = 0;
530         u64 skipped_open = 0;
531         u64 skipped_need_journal_commit = 0;
532         u64 skipped_nouse = 0;
533         bool waiting = false;
534 again:
535         bch2_dev_usage_read_fast(ca, usage);
536         avail = dev_buckets_free(ca, *usage, reserve);
537
538         if (usage->d[BCH_DATA_need_discard].buckets > avail)
539                 bch2_do_discards(c);
540
541         if (usage->d[BCH_DATA_need_gc_gens].buckets > avail)
542                 bch2_do_gc_gens(c);
543
544         if (should_invalidate_buckets(ca, *usage))
545                 bch2_do_invalidates(c);
546
547         if (!avail) {
548                 if (cl && !waiting) {
549                         closure_wait(&c->freelist_wait, cl);
550                         waiting = true;
551                         goto again;
552                 }
553
554                 if (!c->blocked_allocate)
555                         c->blocked_allocate = local_clock();
556
557                 ob = ERR_PTR(-BCH_ERR_freelist_empty);
558                 goto err;
559         }
560
561         if (waiting)
562                 closure_wake_up(&c->freelist_wait);
563
564         if (may_alloc_partial) {
565                 ob = try_alloc_partial_bucket(c, ca, reserve);
566                 if (ob)
567                         return ob;
568         }
569
570         ob = likely(ca->mi.freespace_initialized)
571                 ? bch2_bucket_alloc_freelist(trans, ca, reserve,
572                                         &cur_bucket,
573                                         &buckets_seen,
574                                         &skipped_open,
575                                         &skipped_need_journal_commit,
576                                         &skipped_nouse,
577                                         cl)
578                 : bch2_bucket_alloc_early(trans, ca, reserve,
579                                         &cur_bucket,
580                                         &buckets_seen,
581                                         &skipped_open,
582                                         &skipped_need_journal_commit,
583                                         &skipped_nouse,
584                                         cl);
585
586         if (skipped_need_journal_commit * 2 > avail)
587                 bch2_journal_flush_async(&c->journal, NULL);
588
589         if (!ob && !freespace_initialized && start) {
590                 start = cur_bucket = 0;
591                 goto again;
592         }
593
594         if (!freespace_initialized)
595                 ca->bucket_alloc_trans_early_cursor = cur_bucket;
596 err:
597         if (!ob)
598                 ob = ERR_PTR(-BCH_ERR_no_buckets_found);
599
600         if (!IS_ERR(ob))
601                 trace_and_count(c, bucket_alloc, ca, bch2_alloc_reserves[reserve],
602                                 may_alloc_partial, ob->bucket);
603         else if (!bch2_err_matches(PTR_ERR(ob), BCH_ERR_transaction_restart))
604                 trace_and_count(c, bucket_alloc_fail,
605                                 ca, bch2_alloc_reserves[reserve],
606                                 usage->d[BCH_DATA_free].buckets,
607                                 avail,
608                                 bch2_copygc_wait_amount(c),
609                                 c->copygc_wait - atomic64_read(&c->io_clock[WRITE].now),
610                                 buckets_seen,
611                                 skipped_open,
612                                 skipped_need_journal_commit,
613                                 skipped_nouse,
614                                 cl == NULL,
615                                 bch2_err_str(PTR_ERR(ob)));
616
617         return ob;
618 }
619
620 struct open_bucket *bch2_bucket_alloc(struct bch_fs *c, struct bch_dev *ca,
621                                       enum alloc_reserve reserve,
622                                       bool may_alloc_partial,
623                                       struct closure *cl)
624 {
625         struct bch_dev_usage usage;
626         struct open_bucket *ob;
627
628         bch2_trans_do(c, NULL, NULL, 0,
629                       PTR_ERR_OR_ZERO(ob = bch2_bucket_alloc_trans(&trans, ca, reserve,
630                                                         may_alloc_partial, cl, &usage)));
631         return ob;
632 }
633
634 static int __dev_stripe_cmp(struct dev_stripe_state *stripe,
635                             unsigned l, unsigned r)
636 {
637         return ((stripe->next_alloc[l] > stripe->next_alloc[r]) -
638                 (stripe->next_alloc[l] < stripe->next_alloc[r]));
639 }
640
641 #define dev_stripe_cmp(l, r) __dev_stripe_cmp(stripe, l, r)
642
643 struct dev_alloc_list bch2_dev_alloc_list(struct bch_fs *c,
644                                           struct dev_stripe_state *stripe,
645                                           struct bch_devs_mask *devs)
646 {
647         struct dev_alloc_list ret = { .nr = 0 };
648         unsigned i;
649
650         for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX)
651                 ret.devs[ret.nr++] = i;
652
653         bubble_sort(ret.devs, ret.nr, dev_stripe_cmp);
654         return ret;
655 }
656
657 static inline void bch2_dev_stripe_increment_inlined(struct bch_dev *ca,
658                                struct dev_stripe_state *stripe,
659                                struct bch_dev_usage *usage)
660 {
661         u64 *v = stripe->next_alloc + ca->dev_idx;
662         u64 free_space = dev_buckets_available(ca, RESERVE_none);
663         u64 free_space_inv = free_space
664                 ? div64_u64(1ULL << 48, free_space)
665                 : 1ULL << 48;
666         u64 scale = *v / 4;
667
668         if (*v + free_space_inv >= *v)
669                 *v += free_space_inv;
670         else
671                 *v = U64_MAX;
672
673         for (v = stripe->next_alloc;
674              v < stripe->next_alloc + ARRAY_SIZE(stripe->next_alloc); v++)
675                 *v = *v < scale ? 0 : *v - scale;
676 }
677
678 void bch2_dev_stripe_increment(struct bch_dev *ca,
679                                struct dev_stripe_state *stripe)
680 {
681         struct bch_dev_usage usage;
682
683         bch2_dev_usage_read_fast(ca, &usage);
684         bch2_dev_stripe_increment_inlined(ca, stripe, &usage);
685 }
686
687 #define BUCKET_MAY_ALLOC_PARTIAL        (1 << 0)
688 #define BUCKET_ALLOC_USE_DURABILITY     (1 << 1)
689
690 static void add_new_bucket(struct bch_fs *c,
691                            struct open_buckets *ptrs,
692                            struct bch_devs_mask *devs_may_alloc,
693                            unsigned *nr_effective,
694                            bool *have_cache,
695                            unsigned flags,
696                            struct open_bucket *ob)
697 {
698         unsigned durability =
699                 bch_dev_bkey_exists(c, ob->dev)->mi.durability;
700
701         __clear_bit(ob->dev, devs_may_alloc->d);
702         *nr_effective   += (flags & BUCKET_ALLOC_USE_DURABILITY)
703                 ? durability : 1;
704         *have_cache     |= !durability;
705
706         ob_push(c, ptrs, ob);
707 }
708
709 static int bch2_bucket_alloc_set_trans(struct btree_trans *trans,
710                       struct open_buckets *ptrs,
711                       struct dev_stripe_state *stripe,
712                       struct bch_devs_mask *devs_may_alloc,
713                       unsigned nr_replicas,
714                       unsigned *nr_effective,
715                       bool *have_cache,
716                       enum alloc_reserve reserve,
717                       unsigned flags,
718                       struct closure *cl)
719 {
720         struct bch_fs *c = trans->c;
721         struct dev_alloc_list devs_sorted =
722                 bch2_dev_alloc_list(c, stripe, devs_may_alloc);
723         unsigned dev;
724         struct bch_dev *ca;
725         int ret = -BCH_ERR_insufficient_devices;
726         unsigned i;
727
728         BUG_ON(*nr_effective >= nr_replicas);
729
730         for (i = 0; i < devs_sorted.nr; i++) {
731                 struct bch_dev_usage usage;
732                 struct open_bucket *ob;
733
734                 dev = devs_sorted.devs[i];
735
736                 rcu_read_lock();
737                 ca = rcu_dereference(c->devs[dev]);
738                 if (ca)
739                         percpu_ref_get(&ca->ref);
740                 rcu_read_unlock();
741
742                 if (!ca)
743                         continue;
744
745                 if (!ca->mi.durability && *have_cache) {
746                         percpu_ref_put(&ca->ref);
747                         continue;
748                 }
749
750                 ob = bch2_bucket_alloc_trans(trans, ca, reserve,
751                                 flags & BUCKET_MAY_ALLOC_PARTIAL, cl, &usage);
752                 if (!IS_ERR(ob))
753                         bch2_dev_stripe_increment_inlined(ca, stripe, &usage);
754                 percpu_ref_put(&ca->ref);
755
756                 if (IS_ERR(ob)) {
757                         ret = PTR_ERR(ob);
758                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart) || cl)
759                                 break;
760                         continue;
761                 }
762
763                 add_new_bucket(c, ptrs, devs_may_alloc,
764                                nr_effective, have_cache, flags, ob);
765
766                 if (*nr_effective >= nr_replicas) {
767                         ret = 0;
768                         break;
769                 }
770         }
771
772         return ret;
773 }
774
775 int bch2_bucket_alloc_set(struct bch_fs *c,
776                       struct open_buckets *ptrs,
777                       struct dev_stripe_state *stripe,
778                       struct bch_devs_mask *devs_may_alloc,
779                       unsigned nr_replicas,
780                       unsigned *nr_effective,
781                       bool *have_cache,
782                       enum alloc_reserve reserve,
783                       unsigned flags,
784                       struct closure *cl)
785 {
786         return bch2_trans_do(c, NULL, NULL, 0,
787                       bch2_bucket_alloc_set_trans(&trans, ptrs, stripe,
788                                               devs_may_alloc, nr_replicas,
789                                               nr_effective, have_cache, reserve,
790                                               flags, cl));
791 }
792
793 /* Allocate from stripes: */
794
795 /*
796  * if we can't allocate a new stripe because there are already too many
797  * partially filled stripes, force allocating from an existing stripe even when
798  * it's to a device we don't want:
799  */
800
801 static int bucket_alloc_from_stripe(struct bch_fs *c,
802                          struct open_buckets *ptrs,
803                          struct write_point *wp,
804                          struct bch_devs_mask *devs_may_alloc,
805                          u16 target,
806                          unsigned erasure_code,
807                          unsigned nr_replicas,
808                          unsigned *nr_effective,
809                          bool *have_cache,
810                          unsigned flags,
811                          struct closure *cl)
812 {
813         struct dev_alloc_list devs_sorted;
814         struct ec_stripe_head *h;
815         struct open_bucket *ob;
816         struct bch_dev *ca;
817         unsigned i, ec_idx;
818
819         if (!erasure_code)
820                 return 0;
821
822         if (nr_replicas < 2)
823                 return 0;
824
825         if (ec_open_bucket(c, ptrs))
826                 return 0;
827
828         h = bch2_ec_stripe_head_get(c, target, 0, nr_replicas - 1,
829                                     wp == &c->copygc_write_point,
830                                     cl);
831         if (IS_ERR(h))
832                 return -PTR_ERR(h);
833         if (!h)
834                 return 0;
835
836         devs_sorted = bch2_dev_alloc_list(c, &wp->stripe, devs_may_alloc);
837
838         for (i = 0; i < devs_sorted.nr; i++)
839                 for (ec_idx = 0; ec_idx < h->s->nr_data; ec_idx++) {
840                         if (!h->s->blocks[ec_idx])
841                                 continue;
842
843                         ob = c->open_buckets + h->s->blocks[ec_idx];
844                         if (ob->dev == devs_sorted.devs[i] &&
845                             !test_and_set_bit(ec_idx, h->s->blocks_allocated))
846                                 goto got_bucket;
847                 }
848         goto out_put_head;
849 got_bucket:
850         ca = bch_dev_bkey_exists(c, ob->dev);
851
852         ob->ec_idx      = ec_idx;
853         ob->ec          = h->s;
854
855         add_new_bucket(c, ptrs, devs_may_alloc,
856                        nr_effective, have_cache, flags, ob);
857         atomic_inc(&h->s->pin);
858 out_put_head:
859         bch2_ec_stripe_head_put(c, h);
860         return 0;
861 }
862
863 /* Sector allocator */
864
865 static void get_buckets_from_writepoint(struct bch_fs *c,
866                                         struct open_buckets *ptrs,
867                                         struct write_point *wp,
868                                         struct bch_devs_mask *devs_may_alloc,
869                                         unsigned nr_replicas,
870                                         unsigned *nr_effective,
871                                         bool *have_cache,
872                                         unsigned flags,
873                                         bool need_ec)
874 {
875         struct open_buckets ptrs_skip = { .nr = 0 };
876         struct open_bucket *ob;
877         unsigned i;
878
879         open_bucket_for_each(c, &wp->ptrs, ob, i) {
880                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
881
882                 if (*nr_effective < nr_replicas &&
883                     test_bit(ob->dev, devs_may_alloc->d) &&
884                     (ca->mi.durability ||
885                      (wp->data_type == BCH_DATA_user && !*have_cache)) &&
886                     (ob->ec || !need_ec)) {
887                         add_new_bucket(c, ptrs, devs_may_alloc,
888                                        nr_effective, have_cache,
889                                        flags, ob);
890                 } else {
891                         ob_push(c, &ptrs_skip, ob);
892                 }
893         }
894         wp->ptrs = ptrs_skip;
895 }
896
897 static int open_bucket_add_buckets(struct btree_trans *trans,
898                         struct open_buckets *ptrs,
899                         struct write_point *wp,
900                         struct bch_devs_list *devs_have,
901                         u16 target,
902                         unsigned erasure_code,
903                         unsigned nr_replicas,
904                         unsigned *nr_effective,
905                         bool *have_cache,
906                         enum alloc_reserve reserve,
907                         unsigned flags,
908                         struct closure *_cl)
909 {
910         struct bch_fs *c = trans->c;
911         struct bch_devs_mask devs;
912         struct open_bucket *ob;
913         struct closure *cl = NULL;
914         int ret;
915         unsigned i;
916
917         rcu_read_lock();
918         devs = target_rw_devs(c, wp->data_type, target);
919         rcu_read_unlock();
920
921         /* Don't allocate from devices we already have pointers to: */
922         for (i = 0; i < devs_have->nr; i++)
923                 __clear_bit(devs_have->devs[i], devs.d);
924
925         open_bucket_for_each(c, ptrs, ob, i)
926                 __clear_bit(ob->dev, devs.d);
927
928         if (erasure_code) {
929                 if (!ec_open_bucket(c, ptrs)) {
930                         get_buckets_from_writepoint(c, ptrs, wp, &devs,
931                                                     nr_replicas, nr_effective,
932                                                     have_cache, flags, true);
933                         if (*nr_effective >= nr_replicas)
934                                 return 0;
935                 }
936
937                 if (!ec_open_bucket(c, ptrs)) {
938                         ret = bucket_alloc_from_stripe(c, ptrs, wp, &devs,
939                                                  target, erasure_code,
940                                                  nr_replicas, nr_effective,
941                                                  have_cache, flags, _cl);
942                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
943                             bch2_err_matches(ret, BCH_ERR_freelist_empty) ||
944                             bch2_err_matches(ret, BCH_ERR_open_buckets_empty))
945                                 return ret;
946                         if (*nr_effective >= nr_replicas)
947                                 return 0;
948                 }
949         }
950
951         get_buckets_from_writepoint(c, ptrs, wp, &devs,
952                                     nr_replicas, nr_effective,
953                                     have_cache, flags, false);
954         if (*nr_effective >= nr_replicas)
955                 return 0;
956
957 retry_blocking:
958         /*
959          * Try nonblocking first, so that if one device is full we'll try from
960          * other devices:
961          */
962         ret = bch2_bucket_alloc_set_trans(trans, ptrs, &wp->stripe, &devs,
963                                 nr_replicas, nr_effective, have_cache,
964                                 reserve, flags, cl);
965         if (ret &&
966             !bch2_err_matches(ret, BCH_ERR_transaction_restart) &&
967             !bch2_err_matches(ret, BCH_ERR_insufficient_devices) &&
968             !cl && _cl) {
969                 cl = _cl;
970                 goto retry_blocking;
971         }
972
973         return ret;
974 }
975
976 void bch2_open_buckets_stop_dev(struct bch_fs *c, struct bch_dev *ca,
977                                 struct open_buckets *obs)
978 {
979         struct open_buckets ptrs = { .nr = 0 };
980         struct open_bucket *ob, *ob2;
981         unsigned i, j;
982
983         open_bucket_for_each(c, obs, ob, i) {
984                 bool drop = !ca || ob->dev == ca->dev_idx;
985
986                 if (!drop && ob->ec) {
987                         mutex_lock(&ob->ec->lock);
988                         for (j = 0; j < ob->ec->new_stripe.key.v.nr_blocks; j++) {
989                                 if (!ob->ec->blocks[j])
990                                         continue;
991
992                                 ob2 = c->open_buckets + ob->ec->blocks[j];
993                                 drop |= ob2->dev == ca->dev_idx;
994                         }
995                         mutex_unlock(&ob->ec->lock);
996                 }
997
998                 if (drop)
999                         bch2_open_bucket_put(c, ob);
1000                 else
1001                         ob_push(c, &ptrs, ob);
1002         }
1003
1004         *obs = ptrs;
1005 }
1006
1007 void bch2_writepoint_stop(struct bch_fs *c, struct bch_dev *ca,
1008                           struct write_point *wp)
1009 {
1010         mutex_lock(&wp->lock);
1011         bch2_open_buckets_stop_dev(c, ca, &wp->ptrs);
1012         mutex_unlock(&wp->lock);
1013 }
1014
1015 static inline struct hlist_head *writepoint_hash(struct bch_fs *c,
1016                                                  unsigned long write_point)
1017 {
1018         unsigned hash =
1019                 hash_long(write_point, ilog2(ARRAY_SIZE(c->write_points_hash)));
1020
1021         return &c->write_points_hash[hash];
1022 }
1023
1024 static struct write_point *__writepoint_find(struct hlist_head *head,
1025                                              unsigned long write_point)
1026 {
1027         struct write_point *wp;
1028
1029         rcu_read_lock();
1030         hlist_for_each_entry_rcu(wp, head, node)
1031                 if (wp->write_point == write_point)
1032                         goto out;
1033         wp = NULL;
1034 out:
1035         rcu_read_unlock();
1036         return wp;
1037 }
1038
1039 static inline bool too_many_writepoints(struct bch_fs *c, unsigned factor)
1040 {
1041         u64 stranded    = c->write_points_nr * c->bucket_size_max;
1042         u64 free        = bch2_fs_usage_read_short(c).free;
1043
1044         return stranded * factor > free;
1045 }
1046
1047 static bool try_increase_writepoints(struct bch_fs *c)
1048 {
1049         struct write_point *wp;
1050
1051         if (c->write_points_nr == ARRAY_SIZE(c->write_points) ||
1052             too_many_writepoints(c, 32))
1053                 return false;
1054
1055         wp = c->write_points + c->write_points_nr++;
1056         hlist_add_head_rcu(&wp->node, writepoint_hash(c, wp->write_point));
1057         return true;
1058 }
1059
1060 static bool try_decrease_writepoints(struct bch_fs *c,
1061                                      unsigned old_nr)
1062 {
1063         struct write_point *wp;
1064
1065         mutex_lock(&c->write_points_hash_lock);
1066         if (c->write_points_nr < old_nr) {
1067                 mutex_unlock(&c->write_points_hash_lock);
1068                 return true;
1069         }
1070
1071         if (c->write_points_nr == 1 ||
1072             !too_many_writepoints(c, 8)) {
1073                 mutex_unlock(&c->write_points_hash_lock);
1074                 return false;
1075         }
1076
1077         wp = c->write_points + --c->write_points_nr;
1078
1079         hlist_del_rcu(&wp->node);
1080         mutex_unlock(&c->write_points_hash_lock);
1081
1082         bch2_writepoint_stop(c, NULL, wp);
1083         return true;
1084 }
1085
1086 static void bch2_trans_mutex_lock(struct btree_trans *trans,
1087                                   struct mutex *lock)
1088 {
1089         if (!mutex_trylock(lock)) {
1090                 bch2_trans_unlock(trans);
1091                 mutex_lock(lock);
1092         }
1093 }
1094
1095 static struct write_point *writepoint_find(struct btree_trans *trans,
1096                                            unsigned long write_point)
1097 {
1098         struct bch_fs *c = trans->c;
1099         struct write_point *wp, *oldest;
1100         struct hlist_head *head;
1101
1102         if (!(write_point & 1UL)) {
1103                 wp = (struct write_point *) write_point;
1104                 bch2_trans_mutex_lock(trans, &wp->lock);
1105                 return wp;
1106         }
1107
1108         head = writepoint_hash(c, write_point);
1109 restart_find:
1110         wp = __writepoint_find(head, write_point);
1111         if (wp) {
1112 lock_wp:
1113                 bch2_trans_mutex_lock(trans, &wp->lock);
1114                 if (wp->write_point == write_point)
1115                         goto out;
1116                 mutex_unlock(&wp->lock);
1117                 goto restart_find;
1118         }
1119 restart_find_oldest:
1120         oldest = NULL;
1121         for (wp = c->write_points;
1122              wp < c->write_points + c->write_points_nr; wp++)
1123                 if (!oldest || time_before64(wp->last_used, oldest->last_used))
1124                         oldest = wp;
1125
1126         bch2_trans_mutex_lock(trans, &oldest->lock);
1127         bch2_trans_mutex_lock(trans, &c->write_points_hash_lock);
1128         if (oldest >= c->write_points + c->write_points_nr ||
1129             try_increase_writepoints(c)) {
1130                 mutex_unlock(&c->write_points_hash_lock);
1131                 mutex_unlock(&oldest->lock);
1132                 goto restart_find_oldest;
1133         }
1134
1135         wp = __writepoint_find(head, write_point);
1136         if (wp && wp != oldest) {
1137                 mutex_unlock(&c->write_points_hash_lock);
1138                 mutex_unlock(&oldest->lock);
1139                 goto lock_wp;
1140         }
1141
1142         wp = oldest;
1143         hlist_del_rcu(&wp->node);
1144         wp->write_point = write_point;
1145         hlist_add_head_rcu(&wp->node, head);
1146         mutex_unlock(&c->write_points_hash_lock);
1147 out:
1148         wp->last_used = local_clock();
1149         return wp;
1150 }
1151
1152 /*
1153  * Get us an open_bucket we can allocate from, return with it locked:
1154  */
1155 struct write_point *bch2_alloc_sectors_start_trans(struct btree_trans *trans,
1156                                 unsigned target,
1157                                 unsigned erasure_code,
1158                                 struct write_point_specifier write_point,
1159                                 struct bch_devs_list *devs_have,
1160                                 unsigned nr_replicas,
1161                                 unsigned nr_replicas_required,
1162                                 enum alloc_reserve reserve,
1163                                 unsigned flags,
1164                                 struct closure *cl)
1165 {
1166         struct bch_fs *c = trans->c;
1167         struct write_point *wp;
1168         struct open_bucket *ob;
1169         struct open_buckets ptrs;
1170         unsigned nr_effective, write_points_nr;
1171         unsigned ob_flags = 0;
1172         bool have_cache;
1173         int ret;
1174         int i;
1175
1176         if (!(flags & BCH_WRITE_ONLY_SPECIFIED_DEVS))
1177                 ob_flags |= BUCKET_ALLOC_USE_DURABILITY;
1178
1179         BUG_ON(!nr_replicas || !nr_replicas_required);
1180 retry:
1181         ptrs.nr         = 0;
1182         nr_effective    = 0;
1183         write_points_nr = c->write_points_nr;
1184         have_cache      = false;
1185
1186         wp = writepoint_find(trans, write_point.v);
1187
1188         if (wp->data_type == BCH_DATA_user)
1189                 ob_flags |= BUCKET_MAY_ALLOC_PARTIAL;
1190
1191         /* metadata may not allocate on cache devices: */
1192         if (wp->data_type != BCH_DATA_user)
1193                 have_cache = true;
1194
1195         if (!target || (flags & BCH_WRITE_ONLY_SPECIFIED_DEVS)) {
1196                 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1197                                               target, erasure_code,
1198                                               nr_replicas, &nr_effective,
1199                                               &have_cache, reserve,
1200                                               ob_flags, cl);
1201         } else {
1202                 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1203                                               target, erasure_code,
1204                                               nr_replicas, &nr_effective,
1205                                               &have_cache, reserve,
1206                                               ob_flags, NULL);
1207                 if (!ret ||
1208                     bch2_err_matches(ret, BCH_ERR_transaction_restart))
1209                         goto alloc_done;
1210
1211                 ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1212                                               0, erasure_code,
1213                                               nr_replicas, &nr_effective,
1214                                               &have_cache, reserve,
1215                                               ob_flags, cl);
1216         }
1217 alloc_done:
1218         BUG_ON(!ret && nr_effective < nr_replicas);
1219
1220         if (erasure_code && !ec_open_bucket(c, &ptrs))
1221                 pr_debug("failed to get ec bucket: ret %u", ret);
1222
1223         if (ret == -BCH_ERR_insufficient_devices &&
1224             nr_effective >= nr_replicas_required)
1225                 ret = 0;
1226
1227         if (ret)
1228                 goto err;
1229
1230         /* Free buckets we didn't use: */
1231         open_bucket_for_each(c, &wp->ptrs, ob, i)
1232                 open_bucket_free_unused(c, wp, ob);
1233
1234         wp->ptrs = ptrs;
1235
1236         wp->sectors_free = UINT_MAX;
1237
1238         open_bucket_for_each(c, &wp->ptrs, ob, i)
1239                 wp->sectors_free = min(wp->sectors_free, ob->sectors_free);
1240
1241         BUG_ON(!wp->sectors_free || wp->sectors_free == UINT_MAX);
1242
1243         return wp;
1244 err:
1245         open_bucket_for_each(c, &wp->ptrs, ob, i)
1246                 if (ptrs.nr < ARRAY_SIZE(ptrs.v))
1247                         ob_push(c, &ptrs, ob);
1248                 else
1249                         open_bucket_free_unused(c, wp, ob);
1250         wp->ptrs = ptrs;
1251
1252         mutex_unlock(&wp->lock);
1253
1254         if (bch2_err_matches(ret, BCH_ERR_freelist_empty) &&
1255             try_decrease_writepoints(c, write_points_nr))
1256                 goto retry;
1257
1258         if (bch2_err_matches(ret, BCH_ERR_open_buckets_empty) ||
1259             bch2_err_matches(ret, BCH_ERR_freelist_empty))
1260                 return cl
1261                         ? ERR_PTR(-EAGAIN)
1262                         : ERR_PTR(-BCH_ERR_ENOSPC_bucket_alloc);
1263
1264         if (bch2_err_matches(ret, BCH_ERR_insufficient_devices))
1265                 return ERR_PTR(-EROFS);
1266
1267         return ERR_PTR(ret);
1268 }
1269
1270 struct write_point *bch2_alloc_sectors_start(struct bch_fs *c,
1271                                 unsigned target,
1272                                 unsigned erasure_code,
1273                                 struct write_point_specifier write_point,
1274                                 struct bch_devs_list *devs_have,
1275                                 unsigned nr_replicas,
1276                                 unsigned nr_replicas_required,
1277                                 enum alloc_reserve reserve,
1278                                 unsigned flags,
1279                                 struct closure *cl)
1280 {
1281         struct write_point *wp;
1282
1283         bch2_trans_do(c, NULL, NULL, 0,
1284                       PTR_ERR_OR_ZERO(wp = bch2_alloc_sectors_start_trans(&trans, target,
1285                                                         erasure_code,
1286                                                         write_point,
1287                                                         devs_have,
1288                                                         nr_replicas,
1289                                                         nr_replicas_required,
1290                                                         reserve,
1291                                                         flags, cl)));
1292         return wp;
1293
1294 }
1295
1296 struct bch_extent_ptr bch2_ob_ptr(struct bch_fs *c, struct open_bucket *ob)
1297 {
1298         struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
1299
1300         return (struct bch_extent_ptr) {
1301                 .type   = 1 << BCH_EXTENT_ENTRY_ptr,
1302                 .gen    = ob->gen,
1303                 .dev    = ob->dev,
1304                 .offset = bucket_to_sector(ca, ob->bucket) +
1305                         ca->mi.bucket_size -
1306                         ob->sectors_free,
1307         };
1308 }
1309
1310 /*
1311  * Append pointers to the space we just allocated to @k, and mark @sectors space
1312  * as allocated out of @ob
1313  */
1314 void bch2_alloc_sectors_append_ptrs(struct bch_fs *c, struct write_point *wp,
1315                                     struct bkey_i *k, unsigned sectors,
1316                                     bool cached)
1317
1318 {
1319         struct open_bucket *ob;
1320         unsigned i;
1321
1322         BUG_ON(sectors > wp->sectors_free);
1323         wp->sectors_free -= sectors;
1324
1325         open_bucket_for_each(c, &wp->ptrs, ob, i) {
1326                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->dev);
1327                 struct bch_extent_ptr ptr = bch2_ob_ptr(c, ob);
1328
1329                 ptr.cached = cached ||
1330                         (!ca->mi.durability &&
1331                          wp->data_type == BCH_DATA_user);
1332
1333                 bch2_bkey_append_ptr(k, ptr);
1334
1335                 BUG_ON(sectors > ob->sectors_free);
1336                 ob->sectors_free -= sectors;
1337         }
1338 }
1339
1340 /*
1341  * Append pointers to the space we just allocated to @k, and mark @sectors space
1342  * as allocated out of @ob
1343  */
1344 void bch2_alloc_sectors_done(struct bch_fs *c, struct write_point *wp)
1345 {
1346         struct open_buckets ptrs = { .nr = 0 }, keep = { .nr = 0 };
1347         struct open_bucket *ob;
1348         unsigned i;
1349
1350         open_bucket_for_each(c, &wp->ptrs, ob, i)
1351                 ob_push(c, !ob->sectors_free ? &ptrs : &keep, ob);
1352         wp->ptrs = keep;
1353
1354         mutex_unlock(&wp->lock);
1355
1356         bch2_open_buckets_put(c, &ptrs);
1357 }
1358
1359 static inline void writepoint_init(struct write_point *wp,
1360                                    enum bch_data_type type)
1361 {
1362         mutex_init(&wp->lock);
1363         wp->data_type = type;
1364 }
1365
1366 void bch2_fs_allocator_foreground_init(struct bch_fs *c)
1367 {
1368         struct open_bucket *ob;
1369         struct write_point *wp;
1370
1371         mutex_init(&c->write_points_hash_lock);
1372         c->write_points_nr = ARRAY_SIZE(c->write_points);
1373
1374         /* open bucket 0 is a sentinal NULL: */
1375         spin_lock_init(&c->open_buckets[0].lock);
1376
1377         for (ob = c->open_buckets + 1;
1378              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets); ob++) {
1379                 spin_lock_init(&ob->lock);
1380                 c->open_buckets_nr_free++;
1381
1382                 ob->freelist = c->open_buckets_freelist;
1383                 c->open_buckets_freelist = ob - c->open_buckets;
1384         }
1385
1386         writepoint_init(&c->btree_write_point,          BCH_DATA_btree);
1387         writepoint_init(&c->rebalance_write_point,      BCH_DATA_user);
1388         writepoint_init(&c->copygc_write_point,         BCH_DATA_user);
1389
1390         for (wp = c->write_points;
1391              wp < c->write_points + c->write_points_nr; wp++) {
1392                 writepoint_init(wp, BCH_DATA_user);
1393
1394                 wp->last_used   = local_clock();
1395                 wp->write_point = (unsigned long) wp;
1396                 hlist_add_head_rcu(&wp->node,
1397                                    writepoint_hash(c, wp->write_point));
1398         }
1399 }
1400
1401 void bch2_open_buckets_to_text(struct printbuf *out, struct bch_fs *c)
1402 {
1403         struct open_bucket *ob;
1404
1405         for (ob = c->open_buckets;
1406              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1407              ob++) {
1408                 spin_lock(&ob->lock);
1409                 if (ob->valid && !ob->on_partial_list) {
1410                         prt_printf(out, "%zu ref %u type %s %u:%llu:%u\n",
1411                                ob - c->open_buckets,
1412                                atomic_read(&ob->pin),
1413                                bch2_data_types[ob->data_type],
1414                                ob->dev, ob->bucket, ob->gen);
1415                 }
1416                 spin_unlock(&ob->lock);
1417         }
1418 }