]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_foreground.c
Update bcachefs sources to f7670cba39 bcachefs: Fix for building in userspace
[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                 .gen    = buckets->b[bucket].mark.gen,
292                 .offset = bucket_to_sector(ca, bucket),
293                 .dev    = ca->dev_idx,
294         };
295
296         bucket_io_clock_reset(c, ca, bucket, READ);
297         bucket_io_clock_reset(c, ca, bucket, WRITE);
298         spin_unlock(&ob->lock);
299
300         spin_unlock(&c->freelist_lock);
301
302         bch2_wake_allocator(ca);
303
304         trace_bucket_alloc(ca, reserve);
305         return ob;
306 }
307
308 static int __dev_stripe_cmp(struct dev_stripe_state *stripe,
309                             unsigned l, unsigned r)
310 {
311         return ((stripe->next_alloc[l] > stripe->next_alloc[r]) -
312                 (stripe->next_alloc[l] < stripe->next_alloc[r]));
313 }
314
315 #define dev_stripe_cmp(l, r) __dev_stripe_cmp(stripe, l, r)
316
317 struct dev_alloc_list bch2_dev_alloc_list(struct bch_fs *c,
318                                           struct dev_stripe_state *stripe,
319                                           struct bch_devs_mask *devs)
320 {
321         struct dev_alloc_list ret = { .nr = 0 };
322         struct bch_dev *ca;
323         unsigned i;
324
325         for_each_member_device_rcu(ca, c, i, devs)
326                 ret.devs[ret.nr++] = i;
327
328         bubble_sort(ret.devs, ret.nr, dev_stripe_cmp);
329         return ret;
330 }
331
332 void bch2_dev_stripe_increment(struct bch_fs *c, struct bch_dev *ca,
333                                struct dev_stripe_state *stripe)
334 {
335         u64 *v = stripe->next_alloc + ca->dev_idx;
336         u64 free_space = dev_buckets_free(c, ca);
337         u64 free_space_inv = free_space
338                 ? div64_u64(1ULL << 48, free_space)
339                 : 1ULL << 48;
340         u64 scale = *v / 4;
341
342         if (*v + free_space_inv >= *v)
343                 *v += free_space_inv;
344         else
345                 *v = U64_MAX;
346
347         for (v = stripe->next_alloc;
348              v < stripe->next_alloc + ARRAY_SIZE(stripe->next_alloc); v++)
349                 *v = *v < scale ? 0 : *v - scale;
350 }
351
352 #define BUCKET_MAY_ALLOC_PARTIAL        (1 << 0)
353 #define BUCKET_ALLOC_USE_DURABILITY     (1 << 1)
354
355 static int bch2_bucket_alloc_set(struct bch_fs *c,
356                                  struct open_buckets *ptrs,
357                                  struct dev_stripe_state *stripe,
358                                  struct bch_devs_mask *devs_may_alloc,
359                                  unsigned nr_replicas,
360                                  unsigned *nr_effective,
361                                  bool *have_cache,
362                                  enum alloc_reserve reserve,
363                                  unsigned flags,
364                                  struct closure *cl)
365 {
366         struct dev_alloc_list devs_sorted =
367                 bch2_dev_alloc_list(c, stripe, devs_may_alloc);
368         struct bch_dev *ca;
369         bool alloc_failure = false;
370         unsigned i, durability;
371
372         BUG_ON(*nr_effective >= nr_replicas);
373
374         for (i = 0; i < devs_sorted.nr; i++) {
375                 struct open_bucket *ob;
376
377                 ca = rcu_dereference(c->devs[devs_sorted.devs[i]]);
378                 if (!ca)
379                         continue;
380
381                 if (!ca->mi.durability && *have_cache)
382                         continue;
383
384                 ob = bch2_bucket_alloc(c, ca, reserve,
385                                 flags & BUCKET_MAY_ALLOC_PARTIAL, cl);
386                 if (IS_ERR(ob)) {
387                         enum bucket_alloc_ret ret = -PTR_ERR(ob);
388
389                         WARN_ON(reserve == RESERVE_MOVINGGC &&
390                                 ret != OPEN_BUCKETS_EMPTY);
391
392                         if (cl)
393                                 return -EAGAIN;
394                         if (ret == OPEN_BUCKETS_EMPTY)
395                                 return -ENOSPC;
396                         alloc_failure = true;
397                         continue;
398                 }
399
400                 durability = (flags & BUCKET_ALLOC_USE_DURABILITY)
401                         ? ca->mi.durability : 1;
402
403                 __clear_bit(ca->dev_idx, devs_may_alloc->d);
404                 *nr_effective   += durability;
405                 *have_cache     |= !durability;
406
407                 ob_push(c, ptrs, ob);
408
409                 bch2_dev_stripe_increment(c, ca, stripe);
410
411                 if (*nr_effective >= nr_replicas)
412                         return 0;
413         }
414
415         return alloc_failure ? -ENOSPC : -EROFS;
416 }
417
418 /* Allocate from stripes: */
419
420 /*
421  * XXX: use a higher watermark for allocating open buckets here:
422  */
423 static int ec_stripe_alloc(struct bch_fs *c, struct ec_stripe_head *h)
424 {
425         struct bch_devs_mask devs;
426         struct open_bucket *ob;
427         unsigned i, nr_have = 0, nr_data =
428                 min_t(unsigned, h->nr_active_devs,
429                       EC_STRIPE_MAX) - h->redundancy;
430         bool have_cache = true;
431         int ret = 0;
432
433         BUG_ON(h->blocks.nr > nr_data);
434         BUG_ON(h->parity.nr > h->redundancy);
435
436         devs = h->devs;
437
438         open_bucket_for_each(c, &h->parity, ob, i)
439                 __clear_bit(ob->ptr.dev, devs.d);
440         open_bucket_for_each(c, &h->blocks, ob, i)
441                 __clear_bit(ob->ptr.dev, devs.d);
442
443         percpu_down_read_preempt_disable(&c->mark_lock);
444         rcu_read_lock();
445
446         if (h->parity.nr < h->redundancy) {
447                 nr_have = h->parity.nr;
448
449                 ret = bch2_bucket_alloc_set(c, &h->parity,
450                                             &h->parity_stripe,
451                                             &devs,
452                                             h->redundancy,
453                                             &nr_have,
454                                             &have_cache,
455                                             RESERVE_NONE,
456                                             0,
457                                             NULL);
458                 if (ret)
459                         goto err;
460         }
461
462         if (h->blocks.nr < nr_data) {
463                 nr_have = h->blocks.nr;
464
465                 ret = bch2_bucket_alloc_set(c, &h->blocks,
466                                             &h->block_stripe,
467                                             &devs,
468                                             nr_data,
469                                             &nr_have,
470                                             &have_cache,
471                                             RESERVE_NONE,
472                                             0,
473                                             NULL);
474                 if (ret)
475                         goto err;
476         }
477
478         rcu_read_unlock();
479         percpu_up_read_preempt_enable(&c->mark_lock);
480
481         return bch2_ec_stripe_new_alloc(c, h);
482 err:
483         rcu_read_unlock();
484         percpu_up_read_preempt_enable(&c->mark_lock);
485         return -1;
486 }
487
488 /*
489  * if we can't allocate a new stripe because there are already too many
490  * partially filled stripes, force allocating from an existing stripe even when
491  * it's to a device we don't want:
492  */
493
494 static void bucket_alloc_from_stripe(struct bch_fs *c,
495                                      struct open_buckets *ptrs,
496                                      struct write_point *wp,
497                                      struct bch_devs_mask *devs_may_alloc,
498                                      u16 target,
499                                      unsigned erasure_code,
500                                      unsigned nr_replicas,
501                                      unsigned *nr_effective,
502                                      bool *have_cache)
503 {
504         struct dev_alloc_list devs_sorted;
505         struct ec_stripe_head *h;
506         struct open_bucket *ob;
507         struct bch_dev *ca;
508         unsigned i, ec_idx;
509
510         if (!erasure_code)
511                 return;
512
513         if (nr_replicas < 2)
514                 return;
515
516         if (ec_open_bucket(c, ptrs))
517                 return;
518
519         h = bch2_ec_stripe_head_get(c, target, erasure_code, nr_replicas - 1);
520         if (!h)
521                 return;
522
523         if (!h->s && ec_stripe_alloc(c, h))
524                 goto out_put_head;
525
526         rcu_read_lock();
527         devs_sorted = bch2_dev_alloc_list(c, &wp->stripe, devs_may_alloc);
528         rcu_read_unlock();
529
530         for (i = 0; i < devs_sorted.nr; i++)
531                 open_bucket_for_each(c, &h->s->blocks, ob, ec_idx)
532                         if (ob->ptr.dev == devs_sorted.devs[i] &&
533                             !test_and_set_bit(ec_idx, h->s->blocks_allocated))
534                                 goto got_bucket;
535         goto out_put_head;
536 got_bucket:
537         ca = bch_dev_bkey_exists(c, ob->ptr.dev);
538
539         ob->ec_idx      = ec_idx;
540         ob->ec          = h->s;
541
542         __clear_bit(ob->ptr.dev, devs_may_alloc->d);
543         *nr_effective   += ca->mi.durability;
544         *have_cache     |= !ca->mi.durability;
545
546         ob_push(c, ptrs, ob);
547         atomic_inc(&h->s->pin);
548 out_put_head:
549         bch2_ec_stripe_head_put(h);
550 }
551
552 /* Sector allocator */
553
554 static void get_buckets_from_writepoint(struct bch_fs *c,
555                                         struct open_buckets *ptrs,
556                                         struct write_point *wp,
557                                         struct bch_devs_mask *devs_may_alloc,
558                                         unsigned nr_replicas,
559                                         unsigned *nr_effective,
560                                         bool *have_cache,
561                                         bool need_ec)
562 {
563         struct open_buckets ptrs_skip = { .nr = 0 };
564         struct open_bucket *ob;
565         unsigned i;
566
567         open_bucket_for_each(c, &wp->ptrs, ob, i) {
568                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
569
570                 if (*nr_effective < nr_replicas &&
571                     test_bit(ob->ptr.dev, devs_may_alloc->d) &&
572                     (ca->mi.durability ||
573                      (wp->type == BCH_DATA_USER && !*have_cache)) &&
574                     (ob->ec || !need_ec)) {
575                         __clear_bit(ob->ptr.dev, devs_may_alloc->d);
576                         *nr_effective   += ca->mi.durability;
577                         *have_cache     |= !ca->mi.durability;
578
579                         ob_push(c, ptrs, ob);
580                 } else {
581                         ob_push(c, &ptrs_skip, ob);
582                 }
583         }
584         wp->ptrs = ptrs_skip;
585 }
586
587 static int open_bucket_add_buckets(struct bch_fs *c,
588                                    struct open_buckets *ptrs,
589                                    struct write_point *wp,
590                                    struct bch_devs_list *devs_have,
591                                    u16 target,
592                                    unsigned erasure_code,
593                                    unsigned nr_replicas,
594                                    unsigned *nr_effective,
595                                    bool *have_cache,
596                                    enum alloc_reserve reserve,
597                                    struct closure *_cl)
598 {
599         struct bch_devs_mask devs;
600         struct open_bucket *ob;
601         struct closure *cl = NULL;
602         unsigned i, flags = BUCKET_ALLOC_USE_DURABILITY;
603         int ret;
604
605         if (wp->type == BCH_DATA_USER)
606                 flags |= BUCKET_MAY_ALLOC_PARTIAL;
607
608         rcu_read_lock();
609         devs = target_rw_devs(c, wp->type, target);
610         rcu_read_unlock();
611
612         /* Don't allocate from devices we already have pointers to: */
613         for (i = 0; i < devs_have->nr; i++)
614                 __clear_bit(devs_have->devs[i], devs.d);
615
616         open_bucket_for_each(c, ptrs, ob, i)
617                 __clear_bit(ob->ptr.dev, devs.d);
618
619         if (erasure_code) {
620                 get_buckets_from_writepoint(c, ptrs, wp, &devs,
621                                             nr_replicas, nr_effective,
622                                             have_cache, true);
623                 if (*nr_effective >= nr_replicas)
624                         return 0;
625
626                 bucket_alloc_from_stripe(c, ptrs, wp, &devs,
627                                          target, erasure_code,
628                                          nr_replicas, nr_effective,
629                                          have_cache);
630                 if (*nr_effective >= nr_replicas)
631                         return 0;
632         }
633
634         get_buckets_from_writepoint(c, ptrs, wp, &devs,
635                                     nr_replicas, nr_effective,
636                                     have_cache, false);
637         if (*nr_effective >= nr_replicas)
638                 return 0;
639
640         percpu_down_read_preempt_disable(&c->mark_lock);
641         rcu_read_lock();
642
643 retry_blocking:
644         /*
645          * Try nonblocking first, so that if one device is full we'll try from
646          * other devices:
647          */
648         ret = bch2_bucket_alloc_set(c, ptrs, &wp->stripe, &devs,
649                                 nr_replicas, nr_effective, have_cache,
650                                 reserve, flags, cl);
651         if (ret && ret != -EROFS && !cl && _cl) {
652                 cl = _cl;
653                 goto retry_blocking;
654         }
655
656         rcu_read_unlock();
657         percpu_up_read_preempt_enable(&c->mark_lock);
658
659         return ret;
660 }
661
662 void bch2_open_buckets_stop_dev(struct bch_fs *c, struct bch_dev *ca,
663                                 struct open_buckets *obs,
664                                 enum bch_data_type data_type)
665 {
666         struct open_buckets ptrs = { .nr = 0 };
667         struct open_bucket *ob, *ob2;
668         unsigned i, j;
669
670         open_bucket_for_each(c, obs, ob, i) {
671                 bool drop = !ca || ob->ptr.dev == ca->dev_idx;
672
673                 if (!drop && ob->ec) {
674                         mutex_lock(&ob->ec->lock);
675                         open_bucket_for_each(c, &ob->ec->blocks, ob2, j)
676                                 drop |= ob2->ptr.dev == ca->dev_idx;
677                         open_bucket_for_each(c, &ob->ec->parity, ob2, j)
678                                 drop |= ob2->ptr.dev == ca->dev_idx;
679                         mutex_unlock(&ob->ec->lock);
680                 }
681
682                 if (drop)
683                         bch2_open_bucket_put(c, ob);
684                 else
685                         ob_push(c, &ptrs, ob);
686         }
687
688         *obs = ptrs;
689 }
690
691 void bch2_writepoint_stop(struct bch_fs *c, struct bch_dev *ca,
692                           struct write_point *wp)
693 {
694         mutex_lock(&wp->lock);
695         bch2_open_buckets_stop_dev(c, ca, &wp->ptrs, wp->type);
696         mutex_unlock(&wp->lock);
697 }
698
699 static inline struct hlist_head *writepoint_hash(struct bch_fs *c,
700                                                  unsigned long write_point)
701 {
702         unsigned hash =
703                 hash_long(write_point, ilog2(ARRAY_SIZE(c->write_points_hash)));
704
705         return &c->write_points_hash[hash];
706 }
707
708 static struct write_point *__writepoint_find(struct hlist_head *head,
709                                              unsigned long write_point)
710 {
711         struct write_point *wp;
712
713         hlist_for_each_entry_rcu(wp, head, node)
714                 if (wp->write_point == write_point)
715                         return wp;
716
717         return NULL;
718 }
719
720 static inline bool too_many_writepoints(struct bch_fs *c, unsigned factor)
721 {
722         u64 stranded    = c->write_points_nr * c->bucket_size_max;
723         u64 free        = bch2_fs_sectors_free(c);
724
725         return stranded * factor > free;
726 }
727
728 static bool try_increase_writepoints(struct bch_fs *c)
729 {
730         struct write_point *wp;
731
732         if (c->write_points_nr == ARRAY_SIZE(c->write_points) ||
733             too_many_writepoints(c, 32))
734                 return false;
735
736         wp = c->write_points + c->write_points_nr++;
737         hlist_add_head_rcu(&wp->node, writepoint_hash(c, wp->write_point));
738         return true;
739 }
740
741 static bool try_decrease_writepoints(struct bch_fs *c,
742                                      unsigned old_nr)
743 {
744         struct write_point *wp;
745
746         mutex_lock(&c->write_points_hash_lock);
747         if (c->write_points_nr < old_nr) {
748                 mutex_unlock(&c->write_points_hash_lock);
749                 return true;
750         }
751
752         if (c->write_points_nr == 1 ||
753             !too_many_writepoints(c, 8)) {
754                 mutex_unlock(&c->write_points_hash_lock);
755                 return false;
756         }
757
758         wp = c->write_points + --c->write_points_nr;
759
760         hlist_del_rcu(&wp->node);
761         mutex_unlock(&c->write_points_hash_lock);
762
763         bch2_writepoint_stop(c, NULL, wp);
764         return true;
765 }
766
767 static struct write_point *writepoint_find(struct bch_fs *c,
768                                            unsigned long write_point)
769 {
770         struct write_point *wp, *oldest;
771         struct hlist_head *head;
772
773         if (!(write_point & 1UL)) {
774                 wp = (struct write_point *) write_point;
775                 mutex_lock(&wp->lock);
776                 return wp;
777         }
778
779         head = writepoint_hash(c, write_point);
780 restart_find:
781         wp = __writepoint_find(head, write_point);
782         if (wp) {
783 lock_wp:
784                 mutex_lock(&wp->lock);
785                 if (wp->write_point == write_point)
786                         goto out;
787                 mutex_unlock(&wp->lock);
788                 goto restart_find;
789         }
790 restart_find_oldest:
791         oldest = NULL;
792         for (wp = c->write_points;
793              wp < c->write_points + c->write_points_nr; wp++)
794                 if (!oldest || time_before64(wp->last_used, oldest->last_used))
795                         oldest = wp;
796
797         mutex_lock(&oldest->lock);
798         mutex_lock(&c->write_points_hash_lock);
799         if (oldest >= c->write_points + c->write_points_nr ||
800             try_increase_writepoints(c)) {
801                 mutex_unlock(&c->write_points_hash_lock);
802                 mutex_unlock(&oldest->lock);
803                 goto restart_find_oldest;
804         }
805
806         wp = __writepoint_find(head, write_point);
807         if (wp && wp != oldest) {
808                 mutex_unlock(&c->write_points_hash_lock);
809                 mutex_unlock(&oldest->lock);
810                 goto lock_wp;
811         }
812
813         wp = oldest;
814         hlist_del_rcu(&wp->node);
815         wp->write_point = write_point;
816         hlist_add_head_rcu(&wp->node, head);
817         mutex_unlock(&c->write_points_hash_lock);
818 out:
819         wp->last_used = sched_clock();
820         return wp;
821 }
822
823 /*
824  * Get us an open_bucket we can allocate from, return with it locked:
825  */
826 struct write_point *bch2_alloc_sectors_start(struct bch_fs *c,
827                                 unsigned target,
828                                 unsigned erasure_code,
829                                 struct write_point_specifier write_point,
830                                 struct bch_devs_list *devs_have,
831                                 unsigned nr_replicas,
832                                 unsigned nr_replicas_required,
833                                 enum alloc_reserve reserve,
834                                 unsigned flags,
835                                 struct closure *cl)
836 {
837         struct write_point *wp;
838         struct open_bucket *ob;
839         unsigned nr_effective = 0;
840         struct open_buckets ptrs = { .nr = 0 };
841         bool have_cache = false;
842         unsigned write_points_nr;
843         int ret = 0, i;
844
845         BUG_ON(!nr_replicas || !nr_replicas_required);
846 retry:
847         write_points_nr = c->write_points_nr;
848
849         wp = writepoint_find(c, write_point.v);
850
851         /* metadata may not allocate on cache devices: */
852         if (wp->type != BCH_DATA_USER)
853                 have_cache = true;
854
855         if (!target || (flags & BCH_WRITE_ONLY_SPECIFIED_DEVS)) {
856                 ret = open_bucket_add_buckets(c, &ptrs, wp, devs_have,
857                                               target, erasure_code,
858                                               nr_replicas, &nr_effective,
859                                               &have_cache, reserve, cl);
860         } else {
861                 ret = open_bucket_add_buckets(c, &ptrs, wp, devs_have,
862                                               target, erasure_code,
863                                               nr_replicas, &nr_effective,
864                                               &have_cache, reserve, NULL);
865                 if (!ret)
866                         goto alloc_done;
867
868                 ret = open_bucket_add_buckets(c, &ptrs, wp, devs_have,
869                                               0, erasure_code,
870                                               nr_replicas, &nr_effective,
871                                               &have_cache, reserve, cl);
872         }
873 alloc_done:
874         BUG_ON(!ret && nr_effective < nr_replicas);
875
876         if (erasure_code && !ec_open_bucket(c, &ptrs))
877                 pr_debug("failed to get ec bucket: ret %u", ret);
878
879         if (ret == -EROFS &&
880             nr_effective >= nr_replicas_required)
881                 ret = 0;
882
883         if (ret)
884                 goto err;
885
886         /* Free buckets we didn't use: */
887         open_bucket_for_each(c, &wp->ptrs, ob, i)
888                 open_bucket_free_unused(c, ob, wp->type == BCH_DATA_USER);
889
890         wp->ptrs = ptrs;
891
892         wp->sectors_free = UINT_MAX;
893
894         open_bucket_for_each(c, &wp->ptrs, ob, i)
895                 wp->sectors_free = min(wp->sectors_free, ob->sectors_free);
896
897         BUG_ON(!wp->sectors_free || wp->sectors_free == UINT_MAX);
898
899         verify_not_stale(c, &wp->ptrs);
900
901         return wp;
902 err:
903         open_bucket_for_each(c, &wp->ptrs, ob, i)
904                 if (ptrs.nr < ARRAY_SIZE(ptrs.v))
905                         ob_push(c, &ptrs, ob);
906                 else
907                         open_bucket_free_unused(c, ob,
908                                         wp->type == BCH_DATA_USER);
909         wp->ptrs = ptrs;
910
911         mutex_unlock(&wp->lock);
912
913         if (ret == -ENOSPC &&
914             try_decrease_writepoints(c, write_points_nr))
915                 goto retry;
916
917         return ERR_PTR(ret);
918 }
919
920 /*
921  * Append pointers to the space we just allocated to @k, and mark @sectors space
922  * as allocated out of @ob
923  */
924 void bch2_alloc_sectors_append_ptrs(struct bch_fs *c, struct write_point *wp,
925                                     struct bkey_i *k, unsigned sectors)
926
927 {
928         struct open_bucket *ob;
929         unsigned i;
930
931         BUG_ON(sectors > wp->sectors_free);
932         wp->sectors_free -= sectors;
933
934         open_bucket_for_each(c, &wp->ptrs, ob, i) {
935                 struct bch_dev *ca = bch_dev_bkey_exists(c, ob->ptr.dev);
936                 struct bch_extent_ptr tmp = ob->ptr;
937
938                 tmp.cached = !ca->mi.durability &&
939                         wp->type == BCH_DATA_USER;
940
941                 tmp.offset += ca->mi.bucket_size - ob->sectors_free;
942                 bch2_bkey_append_ptr(k, tmp);
943
944                 BUG_ON(sectors > ob->sectors_free);
945                 ob->sectors_free -= sectors;
946         }
947 }
948
949 /*
950  * Append pointers to the space we just allocated to @k, and mark @sectors space
951  * as allocated out of @ob
952  */
953 void bch2_alloc_sectors_done(struct bch_fs *c, struct write_point *wp)
954 {
955         struct open_buckets ptrs = { .nr = 0 }, keep = { .nr = 0 };
956         struct open_bucket *ob;
957         unsigned i;
958
959         open_bucket_for_each(c, &wp->ptrs, ob, i)
960                 ob_push(c, !ob->sectors_free ? &ptrs : &keep, ob);
961         wp->ptrs = keep;
962
963         mutex_unlock(&wp->lock);
964
965         bch2_open_buckets_put(c, &ptrs);
966 }
967
968 void bch2_fs_allocator_foreground_init(struct bch_fs *c)
969 {
970         struct open_bucket *ob;
971         struct write_point *wp;
972
973         mutex_init(&c->write_points_hash_lock);
974         c->write_points_nr = ARRAY_SIZE(c->write_points);
975
976         /* open bucket 0 is a sentinal NULL: */
977         spin_lock_init(&c->open_buckets[0].lock);
978
979         for (ob = c->open_buckets + 1;
980              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets); ob++) {
981                 spin_lock_init(&ob->lock);
982                 c->open_buckets_nr_free++;
983
984                 ob->freelist = c->open_buckets_freelist;
985                 c->open_buckets_freelist = ob - c->open_buckets;
986         }
987
988         writepoint_init(&c->btree_write_point, BCH_DATA_BTREE);
989         writepoint_init(&c->rebalance_write_point, BCH_DATA_USER);
990
991         for (wp = c->write_points;
992              wp < c->write_points + c->write_points_nr; wp++) {
993                 writepoint_init(wp, BCH_DATA_USER);
994
995                 wp->last_used   = sched_clock();
996                 wp->write_point = (unsigned long) wp;
997                 hlist_add_head_rcu(&wp->node,
998                                    writepoint_hash(c, wp->write_point));
999         }
1000 }