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