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