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