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