]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_foreground.c
Update bcachefs sources to d3422f9b18 bcachefs: Journal initialization fixes
[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 "btree_gc.h"
18 #include "buckets.h"
19 #include "clock.h"
20 #include "debug.h"
21 #include "disk_groups.h"
22 #include "ec.h"
23 #include "io.h"
24
25 #include <linux/math64.h>
26 #include <linux/rculist.h>
27 #include <linux/rcupdate.h>
28 #include <trace/events/bcachefs.h>
29
30 /*
31  * Open buckets represent a bucket that's currently being allocated from.  They
32  * serve two purposes:
33  *
34  *  - They track buckets that have been partially allocated, allowing for
35  *    sub-bucket sized allocations - they're used by the sector allocator below
36  *
37  *  - They provide a reference to the buckets they own that mark and sweep GC
38  *    can find, until the new allocation has a pointer to it inserted into the
39  *    btree
40  *
41  * When allocating some space with the sector allocator, the allocation comes
42  * with a reference to an open bucket - the caller is required to put that
43  * reference _after_ doing the index update that makes its allocation reachable.
44  */
45
46 void __bch2_open_bucket_put(struct bch_fs *c, struct open_bucket *ob)
47 {
48         struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
49
50         if (ob->ec) {
51                 bch2_ec_bucket_written(c, ob);
52                 return;
53         }
54
55         percpu_down_read(&c->mark_lock);
56         spin_lock(&ob->lock);
57
58         bch2_mark_alloc_bucket(c, ca, PTR_BUCKET_NR(ca, &ob->ptr), false);
59         ob->valid = false;
60         ob->type = 0;
61
62         spin_unlock(&ob->lock);
63         percpu_up_read(&c->mark_lock);
64
65         spin_lock(&c->freelist_lock);
66         ob->freelist = c->open_buckets_freelist;
67         c->open_buckets_freelist = ob - c->open_buckets;
68
69         c->open_buckets_nr_free++;
70         ca->nr_open_buckets--;
71         spin_unlock(&c->freelist_lock);
72
73         closure_wake_up(&c->open_buckets_wait);
74 }
75
76 void bch2_open_bucket_write_error(struct bch_fs *c,
77                                   struct open_buckets *obs,
78                                   unsigned dev)
79 {
80         struct open_bucket *ob;
81         unsigned i;
82
83         open_bucket_for_each(c, obs, ob, i)
84                 if (ob->ptr.dev == dev &&
85                     ob->ec)
86                         bch2_ec_bucket_cancel(c, ob);
87 }
88
89 static struct open_bucket *bch2_open_bucket_alloc(struct bch_fs *c)
90 {
91         struct open_bucket *ob;
92
93         BUG_ON(!c->open_buckets_freelist || !c->open_buckets_nr_free);
94
95         ob = c->open_buckets + c->open_buckets_freelist;
96         c->open_buckets_freelist = ob->freelist;
97         atomic_set(&ob->pin, 1);
98         ob->type = 0;
99
100         c->open_buckets_nr_free--;
101         return ob;
102 }
103
104 static void open_bucket_free_unused(struct bch_fs *c,
105                                     struct write_point *wp,
106                                     struct open_bucket *ob)
107 {
108         struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
109         bool may_realloc = wp->type == BCH_DATA_user;
110
111         BUG_ON(ca->open_buckets_partial_nr >
112                ARRAY_SIZE(ca->open_buckets_partial));
113
114         if (ca->open_buckets_partial_nr <
115             ARRAY_SIZE(ca->open_buckets_partial) &&
116             may_realloc) {
117                 spin_lock(&c->freelist_lock);
118                 ob->on_partial_list = true;
119                 ca->open_buckets_partial[ca->open_buckets_partial_nr++] =
120                         ob - c->open_buckets;
121                 spin_unlock(&c->freelist_lock);
122
123                 closure_wake_up(&c->open_buckets_wait);
124                 closure_wake_up(&c->freelist_wait);
125         } else {
126                 bch2_open_bucket_put(c, ob);
127         }
128 }
129
130 static void verify_not_stale(struct bch_fs *c, const struct open_buckets *obs)
131 {
132 #ifdef CONFIG_BCACHEFS_DEBUG
133         struct open_bucket *ob;
134         unsigned i;
135
136         open_bucket_for_each(c, obs, ob, i) {
137                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
138
139                 BUG_ON(ptr_stale(ca, &ob->ptr));
140         }
141 #endif
142 }
143
144 /* _only_ for allocating the journal on a new device: */
145 long bch2_bucket_alloc_new_fs(struct bch_dev *ca)
146 {
147         struct bucket_array *buckets;
148         ssize_t b;
149
150         rcu_read_lock();
151         buckets = bucket_array(ca);
152
153         for (b = buckets->first_bucket; b < buckets->nbuckets; b++)
154                 if (is_available_bucket(buckets->b[b].mark) &&
155                     (!ca->buckets_nouse || !test_bit(b, ca->buckets_nouse)) &&
156                     !buckets->b[b].mark.owned_by_allocator)
157                         goto success;
158         b = -1;
159 success:
160         rcu_read_unlock();
161         return b;
162 }
163
164 static inline unsigned open_buckets_reserved(enum alloc_reserve reserve)
165 {
166         switch (reserve) {
167         case RESERVE_BTREE:
168         case RESERVE_BTREE_MOVINGGC:
169                 return 0;
170         case RESERVE_MOVINGGC:
171                 return OPEN_BUCKETS_COUNT / 4;
172         default:
173                 return OPEN_BUCKETS_COUNT / 2;
174         }
175 }
176
177 /**
178  * bch_bucket_alloc - allocate a single bucket from a specific device
179  *
180  * Returns index of bucket on success, 0 on failure
181  * */
182 struct open_bucket *bch2_bucket_alloc(struct bch_fs *c, struct bch_dev *ca,
183                                       enum alloc_reserve reserve,
184                                       bool may_alloc_partial,
185                                       struct closure *cl)
186 {
187         struct open_bucket *ob;
188         long b = 0;
189
190         spin_lock(&c->freelist_lock);
191
192         if (may_alloc_partial) {
193                 int i;
194
195                 for (i = ca->open_buckets_partial_nr - 1; i >= 0; --i) {
196                         ob = c->open_buckets + ca->open_buckets_partial[i];
197
198                         if (reserve <= ob->alloc_reserve) {
199                                 array_remove_item(ca->open_buckets_partial,
200                                                   ca->open_buckets_partial_nr,
201                                                   i);
202                                 ob->on_partial_list = false;
203                                 ob->alloc_reserve = reserve;
204                                 spin_unlock(&c->freelist_lock);
205                                 return ob;
206                         }
207                 }
208         }
209
210         if (unlikely(c->open_buckets_nr_free <= open_buckets_reserved(reserve))) {
211                 if (cl)
212                         closure_wait(&c->open_buckets_wait, cl);
213
214                 if (!c->blocked_allocate_open_bucket)
215                         c->blocked_allocate_open_bucket = local_clock();
216
217                 spin_unlock(&c->freelist_lock);
218                 trace_open_bucket_alloc_fail(ca, reserve);
219                 return ERR_PTR(-OPEN_BUCKETS_EMPTY);
220         }
221
222         if (likely(fifo_pop(&ca->free[RESERVE_NONE], b)))
223                 goto out;
224
225         switch (reserve) {
226         case RESERVE_BTREE_MOVINGGC:
227         case RESERVE_MOVINGGC:
228                 if (fifo_pop(&ca->free[RESERVE_MOVINGGC], b))
229                         goto out;
230                 break;
231         default:
232                 break;
233         }
234
235         if (cl)
236                 closure_wait(&c->freelist_wait, cl);
237
238         if (!c->blocked_allocate)
239                 c->blocked_allocate = local_clock();
240
241         spin_unlock(&c->freelist_lock);
242
243         trace_bucket_alloc_fail(ca, reserve);
244         return ERR_PTR(-FREELIST_EMPTY);
245 out:
246         verify_not_on_freelist(c, ca, b);
247
248         ob = bch2_open_bucket_alloc(c);
249
250         spin_lock(&ob->lock);
251
252         ob->valid       = true;
253         ob->sectors_free = ca->mi.bucket_size;
254         ob->alloc_reserve = reserve;
255         ob->ptr         = (struct bch_extent_ptr) {
256                 .type   = 1 << BCH_EXTENT_ENTRY_ptr,
257                 .gen    = bucket(ca, b)->mark.gen,
258                 .offset = bucket_to_sector(ca, b),
259                 .dev    = ca->dev_idx,
260         };
261
262         spin_unlock(&ob->lock);
263
264         if (c->blocked_allocate_open_bucket) {
265                 bch2_time_stats_update(
266                         &c->times[BCH_TIME_blocked_allocate_open_bucket],
267                         c->blocked_allocate_open_bucket);
268                 c->blocked_allocate_open_bucket = 0;
269         }
270
271         if (c->blocked_allocate) {
272                 bch2_time_stats_update(
273                         &c->times[BCH_TIME_blocked_allocate],
274                         c->blocked_allocate);
275                 c->blocked_allocate = 0;
276         }
277
278         ca->nr_open_buckets++;
279         spin_unlock(&c->freelist_lock);
280
281         bch2_wake_allocator(ca);
282
283         trace_bucket_alloc(ca, reserve);
284         return ob;
285 }
286
287 static int __dev_stripe_cmp(struct dev_stripe_state *stripe,
288                             unsigned l, unsigned r)
289 {
290         return ((stripe->next_alloc[l] > stripe->next_alloc[r]) -
291                 (stripe->next_alloc[l] < stripe->next_alloc[r]));
292 }
293
294 #define dev_stripe_cmp(l, r) __dev_stripe_cmp(stripe, l, r)
295
296 struct dev_alloc_list bch2_dev_alloc_list(struct bch_fs *c,
297                                           struct dev_stripe_state *stripe,
298                                           struct bch_devs_mask *devs)
299 {
300         struct dev_alloc_list ret = { .nr = 0 };
301         unsigned i;
302
303         for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX)
304                 ret.devs[ret.nr++] = i;
305
306         bubble_sort(ret.devs, ret.nr, dev_stripe_cmp);
307         return ret;
308 }
309
310 void bch2_dev_stripe_increment(struct bch_dev *ca,
311                                struct dev_stripe_state *stripe)
312 {
313         u64 *v = stripe->next_alloc + ca->dev_idx;
314         u64 free_space = dev_buckets_available(ca);
315         u64 free_space_inv = free_space
316                 ? div64_u64(1ULL << 48, free_space)
317                 : 1ULL << 48;
318         u64 scale = *v / 4;
319
320         if (*v + free_space_inv >= *v)
321                 *v += free_space_inv;
322         else
323                 *v = U64_MAX;
324
325         for (v = stripe->next_alloc;
326              v < stripe->next_alloc + ARRAY_SIZE(stripe->next_alloc); v++)
327                 *v = *v < scale ? 0 : *v - scale;
328 }
329
330 #define BUCKET_MAY_ALLOC_PARTIAL        (1 << 0)
331 #define BUCKET_ALLOC_USE_DURABILITY     (1 << 1)
332
333 static void add_new_bucket(struct bch_fs *c,
334                            struct open_buckets *ptrs,
335                            struct bch_devs_mask *devs_may_alloc,
336                            unsigned *nr_effective,
337                            bool *have_cache,
338                            unsigned flags,
339                            struct open_bucket *ob)
340 {
341         unsigned durability =
342                 bch_dev_bkey_exists(c, ob->ptr.dev)->mi.durability;
343
344         __clear_bit(ob->ptr.dev, devs_may_alloc->d);
345         *nr_effective   += (flags & BUCKET_ALLOC_USE_DURABILITY)
346                 ? durability : 1;
347         *have_cache     |= !durability;
348
349         ob_push(c, ptrs, ob);
350 }
351
352 int bch2_bucket_alloc_set(struct bch_fs *c,
353                       struct open_buckets *ptrs,
354                       struct dev_stripe_state *stripe,
355                       struct bch_devs_mask *devs_may_alloc,
356                       unsigned nr_replicas,
357                       unsigned *nr_effective,
358                       bool *have_cache,
359                       enum alloc_reserve reserve,
360                       unsigned flags,
361                       struct closure *cl)
362 {
363         struct dev_alloc_list devs_sorted =
364                 bch2_dev_alloc_list(c, stripe, devs_may_alloc);
365         struct bch_dev *ca;
366         int ret = -INSUFFICIENT_DEVICES;
367         unsigned i;
368
369         BUG_ON(*nr_effective >= nr_replicas);
370
371         for (i = 0; i < devs_sorted.nr; i++) {
372                 struct open_bucket *ob;
373
374                 ca = rcu_dereference(c->devs[devs_sorted.devs[i]]);
375                 if (!ca)
376                         continue;
377
378                 if (!ca->mi.durability && *have_cache)
379                         continue;
380
381                 ob = bch2_bucket_alloc(c, ca, reserve,
382                                 flags & BUCKET_MAY_ALLOC_PARTIAL, cl);
383                 if (IS_ERR(ob)) {
384                         ret = PTR_ERR(ob);
385
386                         if (cl)
387                                 return ret;
388                         continue;
389                 }
390
391                 add_new_bucket(c, ptrs, devs_may_alloc,
392                                nr_effective, have_cache, flags, ob);
393
394                 bch2_dev_stripe_increment(ca, stripe);
395
396                 if (*nr_effective >= nr_replicas)
397                         return 0;
398         }
399
400         return ret;
401 }
402
403 /* Allocate from stripes: */
404
405 /*
406  * if we can't allocate a new stripe because there are already too many
407  * partially filled stripes, force allocating from an existing stripe even when
408  * it's to a device we don't want:
409  */
410
411 static int bucket_alloc_from_stripe(struct bch_fs *c,
412                          struct open_buckets *ptrs,
413                          struct write_point *wp,
414                          struct bch_devs_mask *devs_may_alloc,
415                          u16 target,
416                          unsigned erasure_code,
417                          unsigned nr_replicas,
418                          unsigned *nr_effective,
419                          bool *have_cache,
420                          unsigned flags,
421                          struct closure *cl)
422 {
423         struct dev_alloc_list devs_sorted;
424         struct ec_stripe_head *h;
425         struct open_bucket *ob;
426         struct bch_dev *ca;
427         unsigned i, ec_idx;
428
429         if (!erasure_code)
430                 return 0;
431
432         if (nr_replicas < 2)
433                 return 0;
434
435         if (ec_open_bucket(c, ptrs))
436                 return 0;
437
438         h = bch2_ec_stripe_head_get(c, target, 0, nr_replicas - 1,
439                                     wp == &c->copygc_write_point,
440                                     cl);
441         if (IS_ERR(h))
442                 return -PTR_ERR(h);
443         if (!h)
444                 return 0;
445
446         devs_sorted = bch2_dev_alloc_list(c, &wp->stripe, devs_may_alloc);
447
448         for (i = 0; i < devs_sorted.nr; i++)
449                 for (ec_idx = 0; ec_idx < h->s->nr_data; ec_idx++) {
450                         if (!h->s->blocks[ec_idx])
451                                 continue;
452
453                         ob = c->open_buckets + h->s->blocks[ec_idx];
454                         if (ob->ptr.dev == devs_sorted.devs[i] &&
455                             !test_and_set_bit(ec_idx, h->s->blocks_allocated))
456                                 goto got_bucket;
457                 }
458         goto out_put_head;
459 got_bucket:
460         ca = bch_dev_bkey_exists(c, ob->ptr.dev);
461
462         ob->ec_idx      = ec_idx;
463         ob->ec          = h->s;
464
465         add_new_bucket(c, ptrs, devs_may_alloc,
466                        nr_effective, have_cache, flags, ob);
467         atomic_inc(&h->s->pin);
468 out_put_head:
469         bch2_ec_stripe_head_put(c, h);
470         return 0;
471 }
472
473 /* Sector allocator */
474
475 static void get_buckets_from_writepoint(struct bch_fs *c,
476                                         struct open_buckets *ptrs,
477                                         struct write_point *wp,
478                                         struct bch_devs_mask *devs_may_alloc,
479                                         unsigned nr_replicas,
480                                         unsigned *nr_effective,
481                                         bool *have_cache,
482                                         unsigned flags,
483                                         bool need_ec)
484 {
485         struct open_buckets ptrs_skip = { .nr = 0 };
486         struct open_bucket *ob;
487         unsigned i;
488
489         open_bucket_for_each(c, &wp->ptrs, ob, i) {
490                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
491
492                 if (*nr_effective < nr_replicas &&
493                     test_bit(ob->ptr.dev, devs_may_alloc->d) &&
494                     (ca->mi.durability ||
495                      (wp->type == BCH_DATA_user && !*have_cache)) &&
496                     (ob->ec || !need_ec)) {
497                         add_new_bucket(c, ptrs, devs_may_alloc,
498                                        nr_effective, have_cache,
499                                        flags, ob);
500                 } else {
501                         ob_push(c, &ptrs_skip, ob);
502                 }
503         }
504         wp->ptrs = ptrs_skip;
505 }
506
507 static int open_bucket_add_buckets(struct bch_fs *c,
508                         struct open_buckets *ptrs,
509                         struct write_point *wp,
510                         struct bch_devs_list *devs_have,
511                         u16 target,
512                         unsigned erasure_code,
513                         unsigned nr_replicas,
514                         unsigned *nr_effective,
515                         bool *have_cache,
516                         enum alloc_reserve reserve,
517                         unsigned flags,
518                         struct closure *_cl)
519 {
520         struct bch_devs_mask devs;
521         struct open_bucket *ob;
522         struct closure *cl = NULL;
523         int ret;
524         unsigned i;
525
526         rcu_read_lock();
527         devs = target_rw_devs(c, wp->type, target);
528         rcu_read_unlock();
529
530         /* Don't allocate from devices we already have pointers to: */
531         for (i = 0; i < devs_have->nr; i++)
532                 __clear_bit(devs_have->devs[i], devs.d);
533
534         open_bucket_for_each(c, ptrs, ob, i)
535                 __clear_bit(ob->ptr.dev, devs.d);
536
537         if (erasure_code) {
538                 if (!ec_open_bucket(c, ptrs)) {
539                         get_buckets_from_writepoint(c, ptrs, wp, &devs,
540                                                     nr_replicas, nr_effective,
541                                                     have_cache, flags, true);
542                         if (*nr_effective >= nr_replicas)
543                                 return 0;
544                 }
545
546                 if (!ec_open_bucket(c, ptrs)) {
547                         ret = bucket_alloc_from_stripe(c, ptrs, wp, &devs,
548                                                  target, erasure_code,
549                                                  nr_replicas, nr_effective,
550                                                  have_cache, flags, _cl);
551                         if (ret == -FREELIST_EMPTY ||
552                             ret == -OPEN_BUCKETS_EMPTY)
553                                 return ret;
554                         if (*nr_effective >= nr_replicas)
555                                 return 0;
556                 }
557         }
558
559         get_buckets_from_writepoint(c, ptrs, wp, &devs,
560                                     nr_replicas, nr_effective,
561                                     have_cache, flags, false);
562         if (*nr_effective >= nr_replicas)
563                 return 0;
564
565         percpu_down_read(&c->mark_lock);
566         rcu_read_lock();
567
568 retry_blocking:
569         /*
570          * Try nonblocking first, so that if one device is full we'll try from
571          * other devices:
572          */
573         ret = bch2_bucket_alloc_set(c, ptrs, &wp->stripe, &devs,
574                                 nr_replicas, nr_effective, have_cache,
575                                 reserve, flags, cl);
576         if (ret && ret != -INSUFFICIENT_DEVICES && !cl && _cl) {
577                 cl = _cl;
578                 goto retry_blocking;
579         }
580
581         rcu_read_unlock();
582         percpu_up_read(&c->mark_lock);
583
584         return ret;
585 }
586
587 void bch2_open_buckets_stop_dev(struct bch_fs *c, struct bch_dev *ca,
588                                 struct open_buckets *obs)
589 {
590         struct open_buckets ptrs = { .nr = 0 };
591         struct open_bucket *ob, *ob2;
592         unsigned i, j;
593
594         open_bucket_for_each(c, obs, ob, i) {
595                 bool drop = !ca || ob->ptr.dev == ca->dev_idx;
596
597                 if (!drop && ob->ec) {
598                         mutex_lock(&ob->ec->lock);
599                         for (j = 0; j < ob->ec->new_stripe.key.v.nr_blocks; j++) {
600                                 if (!ob->ec->blocks[j])
601                                         continue;
602
603                                 ob2 = c->open_buckets + ob->ec->blocks[j];
604                                 drop |= ob2->ptr.dev == ca->dev_idx;
605                         }
606                         mutex_unlock(&ob->ec->lock);
607                 }
608
609                 if (drop)
610                         bch2_open_bucket_put(c, ob);
611                 else
612                         ob_push(c, &ptrs, ob);
613         }
614
615         *obs = ptrs;
616 }
617
618 void bch2_writepoint_stop(struct bch_fs *c, struct bch_dev *ca,
619                           struct write_point *wp)
620 {
621         mutex_lock(&wp->lock);
622         bch2_open_buckets_stop_dev(c, ca, &wp->ptrs);
623         mutex_unlock(&wp->lock);
624 }
625
626 static inline struct hlist_head *writepoint_hash(struct bch_fs *c,
627                                                  unsigned long write_point)
628 {
629         unsigned hash =
630                 hash_long(write_point, ilog2(ARRAY_SIZE(c->write_points_hash)));
631
632         return &c->write_points_hash[hash];
633 }
634
635 static struct write_point *__writepoint_find(struct hlist_head *head,
636                                              unsigned long write_point)
637 {
638         struct write_point *wp;
639
640         rcu_read_lock();
641         hlist_for_each_entry_rcu(wp, head, node)
642                 if (wp->write_point == write_point)
643                         goto out;
644         wp = NULL;
645 out:
646         rcu_read_unlock();
647         return wp;
648 }
649
650 static inline bool too_many_writepoints(struct bch_fs *c, unsigned factor)
651 {
652         u64 stranded    = c->write_points_nr * c->bucket_size_max;
653         u64 free        = bch2_fs_usage_read_short(c).free;
654
655         return stranded * factor > free;
656 }
657
658 static bool try_increase_writepoints(struct bch_fs *c)
659 {
660         struct write_point *wp;
661
662         if (c->write_points_nr == ARRAY_SIZE(c->write_points) ||
663             too_many_writepoints(c, 32))
664                 return false;
665
666         wp = c->write_points + c->write_points_nr++;
667         hlist_add_head_rcu(&wp->node, writepoint_hash(c, wp->write_point));
668         return true;
669 }
670
671 static bool try_decrease_writepoints(struct bch_fs *c,
672                                      unsigned old_nr)
673 {
674         struct write_point *wp;
675
676         mutex_lock(&c->write_points_hash_lock);
677         if (c->write_points_nr < old_nr) {
678                 mutex_unlock(&c->write_points_hash_lock);
679                 return true;
680         }
681
682         if (c->write_points_nr == 1 ||
683             !too_many_writepoints(c, 8)) {
684                 mutex_unlock(&c->write_points_hash_lock);
685                 return false;
686         }
687
688         wp = c->write_points + --c->write_points_nr;
689
690         hlist_del_rcu(&wp->node);
691         mutex_unlock(&c->write_points_hash_lock);
692
693         bch2_writepoint_stop(c, NULL, wp);
694         return true;
695 }
696
697 static struct write_point *writepoint_find(struct bch_fs *c,
698                                            unsigned long write_point)
699 {
700         struct write_point *wp, *oldest;
701         struct hlist_head *head;
702
703         if (!(write_point & 1UL)) {
704                 wp = (struct write_point *) write_point;
705                 mutex_lock(&wp->lock);
706                 return wp;
707         }
708
709         head = writepoint_hash(c, write_point);
710 restart_find:
711         wp = __writepoint_find(head, write_point);
712         if (wp) {
713 lock_wp:
714                 mutex_lock(&wp->lock);
715                 if (wp->write_point == write_point)
716                         goto out;
717                 mutex_unlock(&wp->lock);
718                 goto restart_find;
719         }
720 restart_find_oldest:
721         oldest = NULL;
722         for (wp = c->write_points;
723              wp < c->write_points + c->write_points_nr; wp++)
724                 if (!oldest || time_before64(wp->last_used, oldest->last_used))
725                         oldest = wp;
726
727         mutex_lock(&oldest->lock);
728         mutex_lock(&c->write_points_hash_lock);
729         if (oldest >= c->write_points + c->write_points_nr ||
730             try_increase_writepoints(c)) {
731                 mutex_unlock(&c->write_points_hash_lock);
732                 mutex_unlock(&oldest->lock);
733                 goto restart_find_oldest;
734         }
735
736         wp = __writepoint_find(head, write_point);
737         if (wp && wp != oldest) {
738                 mutex_unlock(&c->write_points_hash_lock);
739                 mutex_unlock(&oldest->lock);
740                 goto lock_wp;
741         }
742
743         wp = oldest;
744         hlist_del_rcu(&wp->node);
745         wp->write_point = write_point;
746         hlist_add_head_rcu(&wp->node, head);
747         mutex_unlock(&c->write_points_hash_lock);
748 out:
749         wp->last_used = sched_clock();
750         return wp;
751 }
752
753 /*
754  * Get us an open_bucket we can allocate from, return with it locked:
755  */
756 struct write_point *bch2_alloc_sectors_start(struct bch_fs *c,
757                                 unsigned target,
758                                 unsigned erasure_code,
759                                 struct write_point_specifier write_point,
760                                 struct bch_devs_list *devs_have,
761                                 unsigned nr_replicas,
762                                 unsigned nr_replicas_required,
763                                 enum alloc_reserve reserve,
764                                 unsigned flags,
765                                 struct closure *cl)
766 {
767         struct write_point *wp;
768         struct open_bucket *ob;
769         struct open_buckets ptrs;
770         unsigned nr_effective, write_points_nr;
771         unsigned ob_flags = 0;
772         bool have_cache;
773         int ret;
774         int i;
775
776         if (!(flags & BCH_WRITE_ONLY_SPECIFIED_DEVS))
777                 ob_flags |= BUCKET_ALLOC_USE_DURABILITY;
778
779         BUG_ON(!nr_replicas || !nr_replicas_required);
780 retry:
781         ptrs.nr         = 0;
782         nr_effective    = 0;
783         write_points_nr = c->write_points_nr;
784         have_cache      = false;
785
786         wp = writepoint_find(c, write_point.v);
787
788         if (wp->type == BCH_DATA_user)
789                 ob_flags |= BUCKET_MAY_ALLOC_PARTIAL;
790
791         /* metadata may not allocate on cache devices: */
792         if (wp->type != BCH_DATA_user)
793                 have_cache = true;
794
795         if (!target || (flags & BCH_WRITE_ONLY_SPECIFIED_DEVS)) {
796                 ret = open_bucket_add_buckets(c, &ptrs, wp, devs_have,
797                                               target, erasure_code,
798                                               nr_replicas, &nr_effective,
799                                               &have_cache, reserve,
800                                               ob_flags, cl);
801         } else {
802                 ret = open_bucket_add_buckets(c, &ptrs, wp, devs_have,
803                                               target, erasure_code,
804                                               nr_replicas, &nr_effective,
805                                               &have_cache, reserve,
806                                               ob_flags, NULL);
807                 if (!ret)
808                         goto alloc_done;
809
810                 ret = open_bucket_add_buckets(c, &ptrs, wp, devs_have,
811                                               0, erasure_code,
812                                               nr_replicas, &nr_effective,
813                                               &have_cache, reserve,
814                                               ob_flags, cl);
815         }
816 alloc_done:
817         BUG_ON(!ret && nr_effective < nr_replicas);
818
819         if (erasure_code && !ec_open_bucket(c, &ptrs))
820                 pr_debug("failed to get ec bucket: ret %u", ret);
821
822         if (ret == -INSUFFICIENT_DEVICES &&
823             nr_effective >= nr_replicas_required)
824                 ret = 0;
825
826         if (ret)
827                 goto err;
828
829         /* Free buckets we didn't use: */
830         open_bucket_for_each(c, &wp->ptrs, ob, i)
831                 open_bucket_free_unused(c, wp, ob);
832
833         wp->ptrs = ptrs;
834
835         wp->sectors_free = UINT_MAX;
836
837         open_bucket_for_each(c, &wp->ptrs, ob, i)
838                 wp->sectors_free = min(wp->sectors_free, ob->sectors_free);
839
840         BUG_ON(!wp->sectors_free || wp->sectors_free == UINT_MAX);
841
842         verify_not_stale(c, &wp->ptrs);
843
844         return wp;
845 err:
846         open_bucket_for_each(c, &wp->ptrs, ob, i)
847                 if (ptrs.nr < ARRAY_SIZE(ptrs.v))
848                         ob_push(c, &ptrs, ob);
849                 else
850                         open_bucket_free_unused(c, wp, ob);
851         wp->ptrs = ptrs;
852
853         mutex_unlock(&wp->lock);
854
855         if (ret == -FREELIST_EMPTY &&
856             try_decrease_writepoints(c, write_points_nr))
857                 goto retry;
858
859         switch (ret) {
860         case -OPEN_BUCKETS_EMPTY:
861         case -FREELIST_EMPTY:
862                 return cl ? ERR_PTR(-EAGAIN) : ERR_PTR(-ENOSPC);
863         case -INSUFFICIENT_DEVICES:
864                 return ERR_PTR(-EROFS);
865         default:
866                 BUG();
867         }
868 }
869
870 /*
871  * Append pointers to the space we just allocated to @k, and mark @sectors space
872  * as allocated out of @ob
873  */
874 void bch2_alloc_sectors_append_ptrs(struct bch_fs *c, struct write_point *wp,
875                                     struct bkey_i *k, unsigned sectors)
876
877 {
878         struct open_bucket *ob;
879         unsigned i;
880
881         BUG_ON(sectors > wp->sectors_free);
882         wp->sectors_free -= sectors;
883
884         open_bucket_for_each(c, &wp->ptrs, ob, i) {
885                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
886                 struct bch_extent_ptr tmp = ob->ptr;
887
888                 tmp.cached = !ca->mi.durability &&
889                         wp->type == BCH_DATA_user;
890
891                 tmp.offset += ca->mi.bucket_size - ob->sectors_free;
892                 bch2_bkey_append_ptr(k, tmp);
893
894                 BUG_ON(sectors > ob->sectors_free);
895                 ob->sectors_free -= sectors;
896         }
897 }
898
899 /*
900  * Append pointers to the space we just allocated to @k, and mark @sectors space
901  * as allocated out of @ob
902  */
903 void bch2_alloc_sectors_done(struct bch_fs *c, struct write_point *wp)
904 {
905         struct open_buckets ptrs = { .nr = 0 }, keep = { .nr = 0 };
906         struct open_bucket *ob;
907         unsigned i;
908
909         open_bucket_for_each(c, &wp->ptrs, ob, i)
910                 ob_push(c, !ob->sectors_free ? &ptrs : &keep, ob);
911         wp->ptrs = keep;
912
913         mutex_unlock(&wp->lock);
914
915         bch2_open_buckets_put(c, &ptrs);
916 }
917
918 static inline void writepoint_init(struct write_point *wp,
919                                    enum bch_data_type type)
920 {
921         mutex_init(&wp->lock);
922         wp->type = type;
923 }
924
925 void bch2_fs_allocator_foreground_init(struct bch_fs *c)
926 {
927         struct open_bucket *ob;
928         struct write_point *wp;
929
930         mutex_init(&c->write_points_hash_lock);
931         c->write_points_nr = ARRAY_SIZE(c->write_points);
932
933         /* open bucket 0 is a sentinal NULL: */
934         spin_lock_init(&c->open_buckets[0].lock);
935
936         for (ob = c->open_buckets + 1;
937              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets); ob++) {
938                 spin_lock_init(&ob->lock);
939                 c->open_buckets_nr_free++;
940
941                 ob->freelist = c->open_buckets_freelist;
942                 c->open_buckets_freelist = ob - c->open_buckets;
943         }
944
945         writepoint_init(&c->btree_write_point,          BCH_DATA_btree);
946         writepoint_init(&c->rebalance_write_point,      BCH_DATA_user);
947         writepoint_init(&c->copygc_write_point,         BCH_DATA_user);
948
949         for (wp = c->write_points;
950              wp < c->write_points + c->write_points_nr; wp++) {
951                 writepoint_init(wp, BCH_DATA_user);
952
953                 wp->last_used   = sched_clock();
954                 wp->write_point = (unsigned long) wp;
955                 hlist_add_head_rcu(&wp->node,
956                                    writepoint_hash(c, wp->write_point));
957         }
958 }