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