xref: /linux/fs/bcachefs/alloc_foreground.c (revision 566ab427f827b0256d3e8ce0235d088e6a9c28bd)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2012 Google, Inc.
4  *
5  * Foreground allocator code: allocate buckets from freelist, and allocate in
6  * sector granularity from writepoints.
7  *
8  * bch2_bucket_alloc() allocates a single bucket from a specific device.
9  *
10  * bch2_bucket_alloc_set() allocates one or more buckets from different devices
11  * in a given filesystem.
12  */
13 
14 #include "bcachefs.h"
15 #include "alloc_background.h"
16 #include "alloc_foreground.h"
17 #include "backpointers.h"
18 #include "btree_iter.h"
19 #include "btree_update.h"
20 #include "btree_gc.h"
21 #include "buckets.h"
22 #include "buckets_waiting_for_journal.h"
23 #include "clock.h"
24 #include "debug.h"
25 #include "disk_groups.h"
26 #include "ec.h"
27 #include "error.h"
28 #include "io_write.h"
29 #include "journal.h"
30 #include "movinggc.h"
31 #include "nocow_locking.h"
32 #include "trace.h"
33 
34 #include <linux/math64.h>
35 #include <linux/rculist.h>
36 #include <linux/rcupdate.h>
37 
38 static void bch2_trans_mutex_lock_norelock(struct btree_trans *trans,
39 					   struct mutex *lock)
40 {
41 	if (!mutex_trylock(lock)) {
42 		bch2_trans_unlock(trans);
43 		mutex_lock(lock);
44 	}
45 }
46 
47 const char * const bch2_watermarks[] = {
48 #define x(t) #t,
49 	BCH_WATERMARKS()
50 #undef x
51 	NULL
52 };
53 
54 /*
55  * Open buckets represent a bucket that's currently being allocated from.  They
56  * serve two purposes:
57  *
58  *  - They track buckets that have been partially allocated, allowing for
59  *    sub-bucket sized allocations - they're used by the sector allocator below
60  *
61  *  - They provide a reference to the buckets they own that mark and sweep GC
62  *    can find, until the new allocation has a pointer to it inserted into the
63  *    btree
64  *
65  * When allocating some space with the sector allocator, the allocation comes
66  * with a reference to an open bucket - the caller is required to put that
67  * reference _after_ doing the index update that makes its allocation reachable.
68  */
69 
70 void bch2_reset_alloc_cursors(struct bch_fs *c)
71 {
72 	rcu_read_lock();
73 	for_each_member_device_rcu(c, ca, NULL)
74 		memset(ca->alloc_cursor, 0, sizeof(ca->alloc_cursor));
75 	rcu_read_unlock();
76 }
77 
78 static void bch2_open_bucket_hash_add(struct bch_fs *c, struct open_bucket *ob)
79 {
80 	open_bucket_idx_t idx = ob - c->open_buckets;
81 	open_bucket_idx_t *slot = open_bucket_hashslot(c, ob->dev, ob->bucket);
82 
83 	ob->hash = *slot;
84 	*slot = idx;
85 }
86 
87 static void bch2_open_bucket_hash_remove(struct bch_fs *c, struct open_bucket *ob)
88 {
89 	open_bucket_idx_t idx = ob - c->open_buckets;
90 	open_bucket_idx_t *slot = open_bucket_hashslot(c, ob->dev, ob->bucket);
91 
92 	while (*slot != idx) {
93 		BUG_ON(!*slot);
94 		slot = &c->open_buckets[*slot].hash;
95 	}
96 
97 	*slot = ob->hash;
98 	ob->hash = 0;
99 }
100 
101 void __bch2_open_bucket_put(struct bch_fs *c, struct open_bucket *ob)
102 {
103 	struct bch_dev *ca = ob_dev(c, ob);
104 
105 	if (ob->ec) {
106 		ec_stripe_new_put(c, ob->ec, STRIPE_REF_io);
107 		return;
108 	}
109 
110 	percpu_down_read(&c->mark_lock);
111 	spin_lock(&ob->lock);
112 
113 	ob->valid = false;
114 	ob->data_type = 0;
115 
116 	spin_unlock(&ob->lock);
117 	percpu_up_read(&c->mark_lock);
118 
119 	spin_lock(&c->freelist_lock);
120 	bch2_open_bucket_hash_remove(c, ob);
121 
122 	ob->freelist = c->open_buckets_freelist;
123 	c->open_buckets_freelist = ob - c->open_buckets;
124 
125 	c->open_buckets_nr_free++;
126 	ca->nr_open_buckets--;
127 	spin_unlock(&c->freelist_lock);
128 
129 	closure_wake_up(&c->open_buckets_wait);
130 }
131 
132 void bch2_open_bucket_write_error(struct bch_fs *c,
133 				  struct open_buckets *obs,
134 				  unsigned dev)
135 {
136 	struct open_bucket *ob;
137 	unsigned i;
138 
139 	open_bucket_for_each(c, obs, ob, i)
140 		if (ob->dev == dev && ob->ec)
141 			bch2_ec_bucket_cancel(c, ob);
142 }
143 
144 static struct open_bucket *bch2_open_bucket_alloc(struct bch_fs *c)
145 {
146 	struct open_bucket *ob;
147 
148 	BUG_ON(!c->open_buckets_freelist || !c->open_buckets_nr_free);
149 
150 	ob = c->open_buckets + c->open_buckets_freelist;
151 	c->open_buckets_freelist = ob->freelist;
152 	atomic_set(&ob->pin, 1);
153 	ob->data_type = 0;
154 
155 	c->open_buckets_nr_free--;
156 	return ob;
157 }
158 
159 static void open_bucket_free_unused(struct bch_fs *c, struct open_bucket *ob)
160 {
161 	BUG_ON(c->open_buckets_partial_nr >=
162 	       ARRAY_SIZE(c->open_buckets_partial));
163 
164 	spin_lock(&c->freelist_lock);
165 	ob->on_partial_list = true;
166 	c->open_buckets_partial[c->open_buckets_partial_nr++] =
167 		ob - c->open_buckets;
168 	spin_unlock(&c->freelist_lock);
169 
170 	closure_wake_up(&c->open_buckets_wait);
171 	closure_wake_up(&c->freelist_wait);
172 }
173 
174 /* _only_ for allocating the journal on a new device: */
175 long bch2_bucket_alloc_new_fs(struct bch_dev *ca)
176 {
177 	while (ca->new_fs_bucket_idx < ca->mi.nbuckets) {
178 		u64 b = ca->new_fs_bucket_idx++;
179 
180 		if (!is_superblock_bucket(ca, b) &&
181 		    (!ca->buckets_nouse || !test_bit(b, ca->buckets_nouse)))
182 			return b;
183 	}
184 
185 	return -1;
186 }
187 
188 static inline unsigned open_buckets_reserved(enum bch_watermark watermark)
189 {
190 	switch (watermark) {
191 	case BCH_WATERMARK_interior_updates:
192 		return 0;
193 	case BCH_WATERMARK_reclaim:
194 		return OPEN_BUCKETS_COUNT / 6;
195 	case BCH_WATERMARK_btree:
196 	case BCH_WATERMARK_btree_copygc:
197 		return OPEN_BUCKETS_COUNT / 4;
198 	case BCH_WATERMARK_copygc:
199 		return OPEN_BUCKETS_COUNT / 3;
200 	default:
201 		return OPEN_BUCKETS_COUNT / 2;
202 	}
203 }
204 
205 static struct open_bucket *__try_alloc_bucket(struct bch_fs *c, struct bch_dev *ca,
206 					      u64 bucket,
207 					      enum bch_watermark watermark,
208 					      const struct bch_alloc_v4 *a,
209 					      struct bucket_alloc_state *s,
210 					      struct closure *cl)
211 {
212 	struct open_bucket *ob;
213 
214 	if (unlikely(ca->buckets_nouse && test_bit(bucket, ca->buckets_nouse))) {
215 		s->skipped_nouse++;
216 		return NULL;
217 	}
218 
219 	if (bch2_bucket_is_open(c, ca->dev_idx, bucket)) {
220 		s->skipped_open++;
221 		return NULL;
222 	}
223 
224 	if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
225 			c->journal.flushed_seq_ondisk, ca->dev_idx, bucket)) {
226 		s->skipped_need_journal_commit++;
227 		return NULL;
228 	}
229 
230 	if (bch2_bucket_nocow_is_locked(&c->nocow_locks, POS(ca->dev_idx, bucket))) {
231 		s->skipped_nocow++;
232 		return NULL;
233 	}
234 
235 	spin_lock(&c->freelist_lock);
236 
237 	if (unlikely(c->open_buckets_nr_free <= open_buckets_reserved(watermark))) {
238 		if (cl)
239 			closure_wait(&c->open_buckets_wait, cl);
240 
241 		track_event_change(&c->times[BCH_TIME_blocked_allocate_open_bucket], true);
242 		spin_unlock(&c->freelist_lock);
243 		return ERR_PTR(-BCH_ERR_open_buckets_empty);
244 	}
245 
246 	/* Recheck under lock: */
247 	if (bch2_bucket_is_open(c, ca->dev_idx, bucket)) {
248 		spin_unlock(&c->freelist_lock);
249 		s->skipped_open++;
250 		return NULL;
251 	}
252 
253 	ob = bch2_open_bucket_alloc(c);
254 
255 	spin_lock(&ob->lock);
256 
257 	ob->valid	= true;
258 	ob->sectors_free = ca->mi.bucket_size;
259 	ob->dev		= ca->dev_idx;
260 	ob->gen		= a->gen;
261 	ob->bucket	= bucket;
262 	spin_unlock(&ob->lock);
263 
264 	ca->nr_open_buckets++;
265 	bch2_open_bucket_hash_add(c, ob);
266 
267 	track_event_change(&c->times[BCH_TIME_blocked_allocate_open_bucket], false);
268 	track_event_change(&c->times[BCH_TIME_blocked_allocate], false);
269 
270 	spin_unlock(&c->freelist_lock);
271 	return ob;
272 }
273 
274 static struct open_bucket *try_alloc_bucket(struct btree_trans *trans, struct bch_dev *ca,
275 					    enum bch_watermark watermark, u64 free_entry,
276 					    struct bucket_alloc_state *s,
277 					    struct bkey_s_c freespace_k,
278 					    struct closure *cl)
279 {
280 	struct bch_fs *c = trans->c;
281 	struct btree_iter iter = { NULL };
282 	struct bkey_s_c k;
283 	struct open_bucket *ob;
284 	struct bch_alloc_v4 a_convert;
285 	const struct bch_alloc_v4 *a;
286 	u64 b = free_entry & ~(~0ULL << 56);
287 	unsigned genbits = free_entry >> 56;
288 	struct printbuf buf = PRINTBUF;
289 	int ret;
290 
291 	if (b < ca->mi.first_bucket || b >= ca->mi.nbuckets) {
292 		prt_printf(&buf, "freespace btree has bucket outside allowed range %u-%llu\n"
293 		       "  freespace key ",
294 			ca->mi.first_bucket, ca->mi.nbuckets);
295 		bch2_bkey_val_to_text(&buf, c, freespace_k);
296 		bch2_trans_inconsistent(trans, "%s", buf.buf);
297 		ob = ERR_PTR(-EIO);
298 		goto err;
299 	}
300 
301 	k = bch2_bkey_get_iter(trans, &iter,
302 			       BTREE_ID_alloc, POS(ca->dev_idx, b),
303 			       BTREE_ITER_cached);
304 	ret = bkey_err(k);
305 	if (ret) {
306 		ob = ERR_PTR(ret);
307 		goto err;
308 	}
309 
310 	a = bch2_alloc_to_v4(k, &a_convert);
311 
312 	if (a->data_type != BCH_DATA_free) {
313 		if (c->curr_recovery_pass <= BCH_RECOVERY_PASS_check_alloc_info) {
314 			ob = NULL;
315 			goto err;
316 		}
317 
318 		prt_printf(&buf, "non free bucket in freespace btree\n"
319 		       "  freespace key ");
320 		bch2_bkey_val_to_text(&buf, c, freespace_k);
321 		prt_printf(&buf, "\n  ");
322 		bch2_bkey_val_to_text(&buf, c, k);
323 		bch2_trans_inconsistent(trans, "%s", buf.buf);
324 		ob = ERR_PTR(-EIO);
325 		goto err;
326 	}
327 
328 	if (genbits != (alloc_freespace_genbits(*a) >> 56) &&
329 	    c->curr_recovery_pass > BCH_RECOVERY_PASS_check_alloc_info) {
330 		prt_printf(&buf, "bucket in freespace btree with wrong genbits (got %u should be %llu)\n"
331 		       "  freespace key ",
332 		       genbits, alloc_freespace_genbits(*a) >> 56);
333 		bch2_bkey_val_to_text(&buf, c, freespace_k);
334 		prt_printf(&buf, "\n  ");
335 		bch2_bkey_val_to_text(&buf, c, k);
336 		bch2_trans_inconsistent(trans, "%s", buf.buf);
337 		ob = ERR_PTR(-EIO);
338 		goto err;
339 	}
340 
341 	if (c->curr_recovery_pass <= BCH_RECOVERY_PASS_check_extents_to_backpointers) {
342 		struct bch_backpointer bp;
343 		struct bpos bp_pos = POS_MIN;
344 
345 		ret = bch2_get_next_backpointer(trans, ca, POS(ca->dev_idx, b), -1,
346 						&bp_pos, &bp,
347 						BTREE_ITER_nopreserve);
348 		if (ret) {
349 			ob = ERR_PTR(ret);
350 			goto err;
351 		}
352 
353 		if (!bkey_eq(bp_pos, POS_MAX)) {
354 			/*
355 			 * Bucket may have data in it - we don't call
356 			 * bc2h_trans_inconnsistent() because fsck hasn't
357 			 * finished yet
358 			 */
359 			ob = NULL;
360 			goto err;
361 		}
362 	}
363 
364 	ob = __try_alloc_bucket(c, ca, b, watermark, a, s, cl);
365 	if (!ob)
366 		bch2_set_btree_iter_dontneed(&iter);
367 err:
368 	if (iter.path)
369 		bch2_set_btree_iter_dontneed(&iter);
370 	bch2_trans_iter_exit(trans, &iter);
371 	printbuf_exit(&buf);
372 	return ob;
373 }
374 
375 /*
376  * This path is for before the freespace btree is initialized:
377  *
378  * If ca->new_fs_bucket_idx is nonzero, we haven't yet marked superblock &
379  * journal buckets - journal buckets will be < ca->new_fs_bucket_idx
380  */
381 static noinline struct open_bucket *
382 bch2_bucket_alloc_early(struct btree_trans *trans,
383 			struct bch_dev *ca,
384 			enum bch_watermark watermark,
385 			struct bucket_alloc_state *s,
386 			struct closure *cl)
387 {
388 	struct btree_iter iter, citer;
389 	struct bkey_s_c k, ck;
390 	struct open_bucket *ob = NULL;
391 	u64 first_bucket = max_t(u64, ca->mi.first_bucket, ca->new_fs_bucket_idx);
392 	u64 *dev_alloc_cursor = &ca->alloc_cursor[s->btree_bitmap];
393 	u64 alloc_start = max(first_bucket, *dev_alloc_cursor);
394 	u64 alloc_cursor = alloc_start;
395 	int ret;
396 
397 	/*
398 	 * Scan with an uncached iterator to avoid polluting the key cache. An
399 	 * uncached iter will return a cached key if one exists, but if not
400 	 * there is no other underlying protection for the associated key cache
401 	 * slot. To avoid racing bucket allocations, look up the cached key slot
402 	 * of any likely allocation candidate before attempting to proceed with
403 	 * the allocation. This provides proper exclusion on the associated
404 	 * bucket.
405 	 */
406 again:
407 	for_each_btree_key_norestart(trans, iter, BTREE_ID_alloc, POS(ca->dev_idx, alloc_cursor),
408 			   BTREE_ITER_slots, k, ret) {
409 		u64 bucket = k.k->p.offset;
410 
411 		if (bkey_ge(k.k->p, POS(ca->dev_idx, ca->mi.nbuckets)))
412 			break;
413 
414 		if (ca->new_fs_bucket_idx &&
415 		    is_superblock_bucket(ca, k.k->p.offset))
416 			continue;
417 
418 		if (s->btree_bitmap != BTREE_BITMAP_ANY &&
419 		    s->btree_bitmap != bch2_dev_btree_bitmap_marked_sectors(ca,
420 				bucket_to_sector(ca, bucket), ca->mi.bucket_size)) {
421 			if (s->btree_bitmap == BTREE_BITMAP_YES &&
422 			    bucket_to_sector(ca, bucket) > 64ULL << ca->mi.btree_bitmap_shift)
423 				break;
424 
425 			bucket = sector_to_bucket(ca,
426 					round_up(bucket_to_sector(ca, bucket) + 1,
427 						 1ULL << ca->mi.btree_bitmap_shift));
428 			bch2_btree_iter_set_pos(&iter, POS(ca->dev_idx, bucket));
429 			s->buckets_seen++;
430 			s->skipped_mi_btree_bitmap++;
431 			continue;
432 		}
433 
434 		struct bch_alloc_v4 a_convert;
435 		const struct bch_alloc_v4 *a = bch2_alloc_to_v4(k, &a_convert);
436 		if (a->data_type != BCH_DATA_free)
437 			continue;
438 
439 		/* now check the cached key to serialize concurrent allocs of the bucket */
440 		ck = bch2_bkey_get_iter(trans, &citer, BTREE_ID_alloc, k.k->p, BTREE_ITER_cached);
441 		ret = bkey_err(ck);
442 		if (ret)
443 			break;
444 
445 		a = bch2_alloc_to_v4(ck, &a_convert);
446 		if (a->data_type != BCH_DATA_free)
447 			goto next;
448 
449 		s->buckets_seen++;
450 
451 		ob = __try_alloc_bucket(trans->c, ca, k.k->p.offset, watermark, a, s, cl);
452 next:
453 		bch2_set_btree_iter_dontneed(&citer);
454 		bch2_trans_iter_exit(trans, &citer);
455 		if (ob)
456 			break;
457 	}
458 	bch2_trans_iter_exit(trans, &iter);
459 
460 	alloc_cursor = iter.pos.offset;
461 
462 	if (!ob && ret)
463 		ob = ERR_PTR(ret);
464 
465 	if (!ob && alloc_start > first_bucket) {
466 		alloc_cursor = alloc_start = first_bucket;
467 		goto again;
468 	}
469 
470 	*dev_alloc_cursor = alloc_cursor;
471 
472 	return ob;
473 }
474 
475 static struct open_bucket *bch2_bucket_alloc_freelist(struct btree_trans *trans,
476 						   struct bch_dev *ca,
477 						   enum bch_watermark watermark,
478 						   struct bucket_alloc_state *s,
479 						   struct closure *cl)
480 {
481 	struct btree_iter iter;
482 	struct bkey_s_c k;
483 	struct open_bucket *ob = NULL;
484 	u64 *dev_alloc_cursor = &ca->alloc_cursor[s->btree_bitmap];
485 	u64 alloc_start = max_t(u64, ca->mi.first_bucket, READ_ONCE(*dev_alloc_cursor));
486 	u64 alloc_cursor = alloc_start;
487 	int ret;
488 
489 	BUG_ON(ca->new_fs_bucket_idx);
490 again:
491 	for_each_btree_key_norestart(trans, iter, BTREE_ID_freespace,
492 				     POS(ca->dev_idx, alloc_cursor), 0, k, ret) {
493 		if (k.k->p.inode != ca->dev_idx)
494 			break;
495 
496 		for (alloc_cursor = max(alloc_cursor, bkey_start_offset(k.k));
497 		     alloc_cursor < k.k->p.offset;
498 		     alloc_cursor++) {
499 			s->buckets_seen++;
500 
501 			u64 bucket = alloc_cursor & ~(~0ULL << 56);
502 			if (s->btree_bitmap != BTREE_BITMAP_ANY &&
503 			    s->btree_bitmap != bch2_dev_btree_bitmap_marked_sectors(ca,
504 					bucket_to_sector(ca, bucket), ca->mi.bucket_size)) {
505 				if (s->btree_bitmap == BTREE_BITMAP_YES &&
506 				    bucket_to_sector(ca, bucket) > 64ULL << ca->mi.btree_bitmap_shift)
507 					goto fail;
508 
509 				bucket = sector_to_bucket(ca,
510 						round_up(bucket_to_sector(ca, bucket) + 1,
511 							 1ULL << ca->mi.btree_bitmap_shift));
512 				u64 genbits = alloc_cursor >> 56;
513 				alloc_cursor = bucket | (genbits << 56);
514 
515 				if (alloc_cursor > k.k->p.offset)
516 					bch2_btree_iter_set_pos(&iter, POS(ca->dev_idx, alloc_cursor));
517 				s->skipped_mi_btree_bitmap++;
518 				continue;
519 			}
520 
521 			ob = try_alloc_bucket(trans, ca, watermark,
522 					      alloc_cursor, s, k, cl);
523 			if (ob) {
524 				bch2_set_btree_iter_dontneed(&iter);
525 				break;
526 			}
527 		}
528 
529 		if (ob || ret)
530 			break;
531 	}
532 fail:
533 	bch2_trans_iter_exit(trans, &iter);
534 
535 	if (!ob && ret)
536 		ob = ERR_PTR(ret);
537 
538 	if (!ob && alloc_start > ca->mi.first_bucket) {
539 		alloc_cursor = alloc_start = ca->mi.first_bucket;
540 		goto again;
541 	}
542 
543 	*dev_alloc_cursor = alloc_cursor;
544 
545 	return ob;
546 }
547 
548 static noinline void trace_bucket_alloc2(struct bch_fs *c, struct bch_dev *ca,
549 					 enum bch_watermark watermark,
550 					 enum bch_data_type data_type,
551 					 struct closure *cl,
552 					 struct bch_dev_usage *usage,
553 					 struct bucket_alloc_state *s,
554 					 struct open_bucket *ob)
555 {
556 	struct printbuf buf = PRINTBUF;
557 
558 	printbuf_tabstop_push(&buf, 24);
559 
560 	prt_printf(&buf, "dev\t%s (%u)\n",	ca->name, ca->dev_idx);
561 	prt_printf(&buf, "watermark\t%s\n",	bch2_watermarks[watermark]);
562 	prt_printf(&buf, "data type\t%s\n",	__bch2_data_types[data_type]);
563 	prt_printf(&buf, "blocking\t%u\n",	cl != NULL);
564 	prt_printf(&buf, "free\t%llu\n",	usage->d[BCH_DATA_free].buckets);
565 	prt_printf(&buf, "avail\t%llu\n",	dev_buckets_free(ca, *usage, watermark));
566 	prt_printf(&buf, "copygc_wait\t%lu/%lli\n",
567 		   bch2_copygc_wait_amount(c),
568 		   c->copygc_wait - atomic64_read(&c->io_clock[WRITE].now));
569 	prt_printf(&buf, "seen\t%llu\n",	s->buckets_seen);
570 	prt_printf(&buf, "open\t%llu\n",	s->skipped_open);
571 	prt_printf(&buf, "need journal commit\t%llu\n", s->skipped_need_journal_commit);
572 	prt_printf(&buf, "nocow\t%llu\n",	s->skipped_nocow);
573 	prt_printf(&buf, "nouse\t%llu\n",	s->skipped_nouse);
574 	prt_printf(&buf, "mi_btree_bitmap\t%llu\n", s->skipped_mi_btree_bitmap);
575 
576 	if (!IS_ERR(ob)) {
577 		prt_printf(&buf, "allocated\t%llu\n", ob->bucket);
578 		trace_bucket_alloc(c, buf.buf);
579 	} else {
580 		prt_printf(&buf, "err\t%s\n", bch2_err_str(PTR_ERR(ob)));
581 		trace_bucket_alloc_fail(c, buf.buf);
582 	}
583 
584 	printbuf_exit(&buf);
585 }
586 
587 /**
588  * bch2_bucket_alloc_trans - allocate a single bucket from a specific device
589  * @trans:	transaction object
590  * @ca:		device to allocate from
591  * @watermark:	how important is this allocation?
592  * @data_type:	BCH_DATA_journal, btree, user...
593  * @cl:		if not NULL, closure to be used to wait if buckets not available
594  * @usage:	for secondarily also returning the current device usage
595  *
596  * Returns:	an open_bucket on success, or an ERR_PTR() on failure.
597  */
598 static struct open_bucket *bch2_bucket_alloc_trans(struct btree_trans *trans,
599 				      struct bch_dev *ca,
600 				      enum bch_watermark watermark,
601 				      enum bch_data_type data_type,
602 				      struct closure *cl,
603 				      bool nowait,
604 				      struct bch_dev_usage *usage)
605 {
606 	struct bch_fs *c = trans->c;
607 	struct open_bucket *ob = NULL;
608 	bool freespace = READ_ONCE(ca->mi.freespace_initialized);
609 	u64 avail;
610 	struct bucket_alloc_state s = {
611 		.btree_bitmap = data_type == BCH_DATA_btree,
612 	};
613 	bool waiting = nowait;
614 again:
615 	bch2_dev_usage_read_fast(ca, usage);
616 	avail = dev_buckets_free(ca, *usage, watermark);
617 
618 	if (usage->d[BCH_DATA_need_discard].buckets > avail)
619 		bch2_dev_do_discards(ca);
620 
621 	if (usage->d[BCH_DATA_need_gc_gens].buckets > avail)
622 		bch2_gc_gens_async(c);
623 
624 	if (should_invalidate_buckets(ca, *usage))
625 		bch2_dev_do_invalidates(ca);
626 
627 	if (!avail) {
628 		if (cl && !waiting) {
629 			closure_wait(&c->freelist_wait, cl);
630 			waiting = true;
631 			goto again;
632 		}
633 
634 		track_event_change(&c->times[BCH_TIME_blocked_allocate], true);
635 
636 		ob = ERR_PTR(-BCH_ERR_freelist_empty);
637 		goto err;
638 	}
639 
640 	if (waiting)
641 		closure_wake_up(&c->freelist_wait);
642 alloc:
643 	ob = likely(freespace)
644 		? bch2_bucket_alloc_freelist(trans, ca, watermark, &s, cl)
645 		: bch2_bucket_alloc_early(trans, ca, watermark, &s, cl);
646 
647 	if (s.skipped_need_journal_commit * 2 > avail)
648 		bch2_journal_flush_async(&c->journal, NULL);
649 
650 	if (!ob && s.btree_bitmap != BTREE_BITMAP_ANY) {
651 		s.btree_bitmap = BTREE_BITMAP_ANY;
652 		goto alloc;
653 	}
654 
655 	if (!ob && freespace && c->curr_recovery_pass <= BCH_RECOVERY_PASS_check_alloc_info) {
656 		freespace = false;
657 		goto alloc;
658 	}
659 err:
660 	if (!ob)
661 		ob = ERR_PTR(-BCH_ERR_no_buckets_found);
662 
663 	if (!IS_ERR(ob))
664 		ob->data_type = data_type;
665 
666 	if (!IS_ERR(ob))
667 		count_event(c, bucket_alloc);
668 	else if (!bch2_err_matches(PTR_ERR(ob), BCH_ERR_transaction_restart))
669 		count_event(c, bucket_alloc_fail);
670 
671 	if (!IS_ERR(ob)
672 	    ? trace_bucket_alloc_enabled()
673 	    : trace_bucket_alloc_fail_enabled())
674 		trace_bucket_alloc2(c, ca, watermark, data_type, cl, usage, &s, ob);
675 
676 	return ob;
677 }
678 
679 struct open_bucket *bch2_bucket_alloc(struct bch_fs *c, struct bch_dev *ca,
680 				      enum bch_watermark watermark,
681 				      enum bch_data_type data_type,
682 				      struct closure *cl)
683 {
684 	struct bch_dev_usage usage;
685 	struct open_bucket *ob;
686 
687 	bch2_trans_do(c, NULL, NULL, 0,
688 		      PTR_ERR_OR_ZERO(ob = bch2_bucket_alloc_trans(trans, ca, watermark,
689 							data_type, cl, false, &usage)));
690 	return ob;
691 }
692 
693 static int __dev_stripe_cmp(struct dev_stripe_state *stripe,
694 			    unsigned l, unsigned r)
695 {
696 	return ((stripe->next_alloc[l] > stripe->next_alloc[r]) -
697 		(stripe->next_alloc[l] < stripe->next_alloc[r]));
698 }
699 
700 #define dev_stripe_cmp(l, r) __dev_stripe_cmp(stripe, l, r)
701 
702 struct dev_alloc_list bch2_dev_alloc_list(struct bch_fs *c,
703 					  struct dev_stripe_state *stripe,
704 					  struct bch_devs_mask *devs)
705 {
706 	struct dev_alloc_list ret = { .nr = 0 };
707 	unsigned i;
708 
709 	for_each_set_bit(i, devs->d, BCH_SB_MEMBERS_MAX)
710 		ret.devs[ret.nr++] = i;
711 
712 	bubble_sort(ret.devs, ret.nr, dev_stripe_cmp);
713 	return ret;
714 }
715 
716 static inline void bch2_dev_stripe_increment_inlined(struct bch_dev *ca,
717 			       struct dev_stripe_state *stripe,
718 			       struct bch_dev_usage *usage)
719 {
720 	u64 *v = stripe->next_alloc + ca->dev_idx;
721 	u64 free_space = dev_buckets_available(ca, BCH_WATERMARK_normal);
722 	u64 free_space_inv = free_space
723 		? div64_u64(1ULL << 48, free_space)
724 		: 1ULL << 48;
725 	u64 scale = *v / 4;
726 
727 	if (*v + free_space_inv >= *v)
728 		*v += free_space_inv;
729 	else
730 		*v = U64_MAX;
731 
732 	for (v = stripe->next_alloc;
733 	     v < stripe->next_alloc + ARRAY_SIZE(stripe->next_alloc); v++)
734 		*v = *v < scale ? 0 : *v - scale;
735 }
736 
737 void bch2_dev_stripe_increment(struct bch_dev *ca,
738 			       struct dev_stripe_state *stripe)
739 {
740 	struct bch_dev_usage usage;
741 
742 	bch2_dev_usage_read_fast(ca, &usage);
743 	bch2_dev_stripe_increment_inlined(ca, stripe, &usage);
744 }
745 
746 static int add_new_bucket(struct bch_fs *c,
747 			   struct open_buckets *ptrs,
748 			   struct bch_devs_mask *devs_may_alloc,
749 			   unsigned nr_replicas,
750 			   unsigned *nr_effective,
751 			   bool *have_cache,
752 			   struct open_bucket *ob)
753 {
754 	unsigned durability = ob_dev(c, ob)->mi.durability;
755 
756 	BUG_ON(*nr_effective >= nr_replicas);
757 
758 	__clear_bit(ob->dev, devs_may_alloc->d);
759 	*nr_effective	+= durability;
760 	*have_cache	|= !durability;
761 
762 	ob_push(c, ptrs, ob);
763 
764 	if (*nr_effective >= nr_replicas)
765 		return 1;
766 	if (ob->ec)
767 		return 1;
768 	return 0;
769 }
770 
771 int bch2_bucket_alloc_set_trans(struct btree_trans *trans,
772 		      struct open_buckets *ptrs,
773 		      struct dev_stripe_state *stripe,
774 		      struct bch_devs_mask *devs_may_alloc,
775 		      unsigned nr_replicas,
776 		      unsigned *nr_effective,
777 		      bool *have_cache,
778 		      enum bch_write_flags flags,
779 		      enum bch_data_type data_type,
780 		      enum bch_watermark watermark,
781 		      struct closure *cl)
782 {
783 	struct bch_fs *c = trans->c;
784 	struct dev_alloc_list devs_sorted =
785 		bch2_dev_alloc_list(c, stripe, devs_may_alloc);
786 	int ret = -BCH_ERR_insufficient_devices;
787 
788 	BUG_ON(*nr_effective >= nr_replicas);
789 
790 	for (unsigned i = 0; i < devs_sorted.nr; i++) {
791 		struct bch_dev_usage usage;
792 		struct open_bucket *ob;
793 
794 		unsigned dev = devs_sorted.devs[i];
795 		struct bch_dev *ca = bch2_dev_tryget_noerror(c, dev);
796 		if (!ca)
797 			continue;
798 
799 		if (!ca->mi.durability && *have_cache) {
800 			bch2_dev_put(ca);
801 			continue;
802 		}
803 
804 		ob = bch2_bucket_alloc_trans(trans, ca, watermark, data_type,
805 					     cl, flags & BCH_WRITE_ALLOC_NOWAIT, &usage);
806 		if (!IS_ERR(ob))
807 			bch2_dev_stripe_increment_inlined(ca, stripe, &usage);
808 		bch2_dev_put(ca);
809 
810 		if (IS_ERR(ob)) {
811 			ret = PTR_ERR(ob);
812 			if (bch2_err_matches(ret, BCH_ERR_transaction_restart) || cl)
813 				break;
814 			continue;
815 		}
816 
817 		if (add_new_bucket(c, ptrs, devs_may_alloc,
818 				   nr_replicas, nr_effective,
819 				   have_cache, ob)) {
820 			ret = 0;
821 			break;
822 		}
823 	}
824 
825 	return ret;
826 }
827 
828 /* Allocate from stripes: */
829 
830 /*
831  * if we can't allocate a new stripe because there are already too many
832  * partially filled stripes, force allocating from an existing stripe even when
833  * it's to a device we don't want:
834  */
835 
836 static int bucket_alloc_from_stripe(struct btree_trans *trans,
837 			 struct open_buckets *ptrs,
838 			 struct write_point *wp,
839 			 struct bch_devs_mask *devs_may_alloc,
840 			 u16 target,
841 			 unsigned nr_replicas,
842 			 unsigned *nr_effective,
843 			 bool *have_cache,
844 			 enum bch_watermark watermark,
845 			 enum bch_write_flags flags,
846 			 struct closure *cl)
847 {
848 	struct bch_fs *c = trans->c;
849 	struct dev_alloc_list devs_sorted;
850 	struct ec_stripe_head *h;
851 	struct open_bucket *ob;
852 	unsigned i, ec_idx;
853 	int ret = 0;
854 
855 	if (nr_replicas < 2)
856 		return 0;
857 
858 	if (ec_open_bucket(c, ptrs))
859 		return 0;
860 
861 	h = bch2_ec_stripe_head_get(trans, target, 0, nr_replicas - 1, watermark, cl);
862 	if (IS_ERR(h))
863 		return PTR_ERR(h);
864 	if (!h)
865 		return 0;
866 
867 	devs_sorted = bch2_dev_alloc_list(c, &wp->stripe, devs_may_alloc);
868 
869 	for (i = 0; i < devs_sorted.nr; i++)
870 		for (ec_idx = 0; ec_idx < h->s->nr_data; ec_idx++) {
871 			if (!h->s->blocks[ec_idx])
872 				continue;
873 
874 			ob = c->open_buckets + h->s->blocks[ec_idx];
875 			if (ob->dev == devs_sorted.devs[i] &&
876 			    !test_and_set_bit(ec_idx, h->s->blocks_allocated))
877 				goto got_bucket;
878 		}
879 	goto out_put_head;
880 got_bucket:
881 	ob->ec_idx	= ec_idx;
882 	ob->ec		= h->s;
883 	ec_stripe_new_get(h->s, STRIPE_REF_io);
884 
885 	ret = add_new_bucket(c, ptrs, devs_may_alloc,
886 			     nr_replicas, nr_effective,
887 			     have_cache, ob);
888 out_put_head:
889 	bch2_ec_stripe_head_put(c, h);
890 	return ret;
891 }
892 
893 /* Sector allocator */
894 
895 static bool want_bucket(struct bch_fs *c,
896 			struct write_point *wp,
897 			struct bch_devs_mask *devs_may_alloc,
898 			bool *have_cache, bool ec,
899 			struct open_bucket *ob)
900 {
901 	struct bch_dev *ca = ob_dev(c, ob);
902 
903 	if (!test_bit(ob->dev, devs_may_alloc->d))
904 		return false;
905 
906 	if (ob->data_type != wp->data_type)
907 		return false;
908 
909 	if (!ca->mi.durability &&
910 	    (wp->data_type == BCH_DATA_btree || ec || *have_cache))
911 		return false;
912 
913 	if (ec != (ob->ec != NULL))
914 		return false;
915 
916 	return true;
917 }
918 
919 static int bucket_alloc_set_writepoint(struct bch_fs *c,
920 				       struct open_buckets *ptrs,
921 				       struct write_point *wp,
922 				       struct bch_devs_mask *devs_may_alloc,
923 				       unsigned nr_replicas,
924 				       unsigned *nr_effective,
925 				       bool *have_cache,
926 				       bool ec)
927 {
928 	struct open_buckets ptrs_skip = { .nr = 0 };
929 	struct open_bucket *ob;
930 	unsigned i;
931 	int ret = 0;
932 
933 	open_bucket_for_each(c, &wp->ptrs, ob, i) {
934 		if (!ret && want_bucket(c, wp, devs_may_alloc,
935 					have_cache, ec, ob))
936 			ret = add_new_bucket(c, ptrs, devs_may_alloc,
937 				       nr_replicas, nr_effective,
938 				       have_cache, ob);
939 		else
940 			ob_push(c, &ptrs_skip, ob);
941 	}
942 	wp->ptrs = ptrs_skip;
943 
944 	return ret;
945 }
946 
947 static int bucket_alloc_set_partial(struct bch_fs *c,
948 				    struct open_buckets *ptrs,
949 				    struct write_point *wp,
950 				    struct bch_devs_mask *devs_may_alloc,
951 				    unsigned nr_replicas,
952 				    unsigned *nr_effective,
953 				    bool *have_cache, bool ec,
954 				    enum bch_watermark watermark)
955 {
956 	int i, ret = 0;
957 
958 	if (!c->open_buckets_partial_nr)
959 		return 0;
960 
961 	spin_lock(&c->freelist_lock);
962 
963 	if (!c->open_buckets_partial_nr)
964 		goto unlock;
965 
966 	for (i = c->open_buckets_partial_nr - 1; i >= 0; --i) {
967 		struct open_bucket *ob = c->open_buckets + c->open_buckets_partial[i];
968 
969 		if (want_bucket(c, wp, devs_may_alloc, have_cache, ec, ob)) {
970 			struct bch_dev *ca = ob_dev(c, ob);
971 			struct bch_dev_usage usage;
972 			u64 avail;
973 
974 			bch2_dev_usage_read_fast(ca, &usage);
975 			avail = dev_buckets_free(ca, usage, watermark);
976 			if (!avail)
977 				continue;
978 
979 			array_remove_item(c->open_buckets_partial,
980 					  c->open_buckets_partial_nr,
981 					  i);
982 			ob->on_partial_list = false;
983 
984 			ret = add_new_bucket(c, ptrs, devs_may_alloc,
985 					     nr_replicas, nr_effective,
986 					     have_cache, ob);
987 			if (ret)
988 				break;
989 		}
990 	}
991 unlock:
992 	spin_unlock(&c->freelist_lock);
993 	return ret;
994 }
995 
996 static int __open_bucket_add_buckets(struct btree_trans *trans,
997 			struct open_buckets *ptrs,
998 			struct write_point *wp,
999 			struct bch_devs_list *devs_have,
1000 			u16 target,
1001 			bool erasure_code,
1002 			unsigned nr_replicas,
1003 			unsigned *nr_effective,
1004 			bool *have_cache,
1005 			enum bch_watermark watermark,
1006 			enum bch_write_flags flags,
1007 			struct closure *_cl)
1008 {
1009 	struct bch_fs *c = trans->c;
1010 	struct bch_devs_mask devs;
1011 	struct open_bucket *ob;
1012 	struct closure *cl = NULL;
1013 	unsigned i;
1014 	int ret;
1015 
1016 	devs = target_rw_devs(c, wp->data_type, target);
1017 
1018 	/* Don't allocate from devices we already have pointers to: */
1019 	darray_for_each(*devs_have, i)
1020 		__clear_bit(*i, devs.d);
1021 
1022 	open_bucket_for_each(c, ptrs, ob, i)
1023 		__clear_bit(ob->dev, devs.d);
1024 
1025 	ret = bucket_alloc_set_writepoint(c, ptrs, wp, &devs,
1026 				 nr_replicas, nr_effective,
1027 				 have_cache, erasure_code);
1028 	if (ret)
1029 		return ret;
1030 
1031 	ret = bucket_alloc_set_partial(c, ptrs, wp, &devs,
1032 				 nr_replicas, nr_effective,
1033 				 have_cache, erasure_code, watermark);
1034 	if (ret)
1035 		return ret;
1036 
1037 	if (erasure_code) {
1038 		ret = bucket_alloc_from_stripe(trans, ptrs, wp, &devs,
1039 					 target,
1040 					 nr_replicas, nr_effective,
1041 					 have_cache,
1042 					 watermark, flags, _cl);
1043 	} else {
1044 retry_blocking:
1045 		/*
1046 		 * Try nonblocking first, so that if one device is full we'll try from
1047 		 * other devices:
1048 		 */
1049 		ret = bch2_bucket_alloc_set_trans(trans, ptrs, &wp->stripe, &devs,
1050 					nr_replicas, nr_effective, have_cache,
1051 					flags, wp->data_type, watermark, cl);
1052 		if (ret &&
1053 		    !bch2_err_matches(ret, BCH_ERR_transaction_restart) &&
1054 		    !bch2_err_matches(ret, BCH_ERR_insufficient_devices) &&
1055 		    !cl && _cl) {
1056 			cl = _cl;
1057 			goto retry_blocking;
1058 		}
1059 	}
1060 
1061 	return ret;
1062 }
1063 
1064 static int open_bucket_add_buckets(struct btree_trans *trans,
1065 			struct open_buckets *ptrs,
1066 			struct write_point *wp,
1067 			struct bch_devs_list *devs_have,
1068 			u16 target,
1069 			unsigned erasure_code,
1070 			unsigned nr_replicas,
1071 			unsigned *nr_effective,
1072 			bool *have_cache,
1073 			enum bch_watermark watermark,
1074 			enum bch_write_flags flags,
1075 			struct closure *cl)
1076 {
1077 	int ret;
1078 
1079 	if (erasure_code && !ec_open_bucket(trans->c, ptrs)) {
1080 		ret = __open_bucket_add_buckets(trans, ptrs, wp,
1081 				devs_have, target, erasure_code,
1082 				nr_replicas, nr_effective, have_cache,
1083 				watermark, flags, cl);
1084 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart) ||
1085 		    bch2_err_matches(ret, BCH_ERR_operation_blocked) ||
1086 		    bch2_err_matches(ret, BCH_ERR_freelist_empty) ||
1087 		    bch2_err_matches(ret, BCH_ERR_open_buckets_empty))
1088 			return ret;
1089 		if (*nr_effective >= nr_replicas)
1090 			return 0;
1091 	}
1092 
1093 	ret = __open_bucket_add_buckets(trans, ptrs, wp,
1094 			devs_have, target, false,
1095 			nr_replicas, nr_effective, have_cache,
1096 			watermark, flags, cl);
1097 	return ret < 0 ? ret : 0;
1098 }
1099 
1100 /**
1101  * should_drop_bucket - check if this is open_bucket should go away
1102  * @ob:		open_bucket to predicate on
1103  * @c:		filesystem handle
1104  * @ca:		if set, we're killing buckets for a particular device
1105  * @ec:		if true, we're shutting down erasure coding and killing all ec
1106  *		open_buckets
1107  *		otherwise, return true
1108  * Returns: true if we should kill this open_bucket
1109  *
1110  * We're killing open_buckets because we're shutting down a device, erasure
1111  * coding, or the entire filesystem - check if this open_bucket matches:
1112  */
1113 static bool should_drop_bucket(struct open_bucket *ob, struct bch_fs *c,
1114 			       struct bch_dev *ca, bool ec)
1115 {
1116 	if (ec) {
1117 		return ob->ec != NULL;
1118 	} else if (ca) {
1119 		bool drop = ob->dev == ca->dev_idx;
1120 		struct open_bucket *ob2;
1121 		unsigned i;
1122 
1123 		if (!drop && ob->ec) {
1124 			unsigned nr_blocks;
1125 
1126 			mutex_lock(&ob->ec->lock);
1127 			nr_blocks = bkey_i_to_stripe(&ob->ec->new_stripe.key)->v.nr_blocks;
1128 
1129 			for (i = 0; i < nr_blocks; i++) {
1130 				if (!ob->ec->blocks[i])
1131 					continue;
1132 
1133 				ob2 = c->open_buckets + ob->ec->blocks[i];
1134 				drop |= ob2->dev == ca->dev_idx;
1135 			}
1136 			mutex_unlock(&ob->ec->lock);
1137 		}
1138 
1139 		return drop;
1140 	} else {
1141 		return true;
1142 	}
1143 }
1144 
1145 static void bch2_writepoint_stop(struct bch_fs *c, struct bch_dev *ca,
1146 				 bool ec, struct write_point *wp)
1147 {
1148 	struct open_buckets ptrs = { .nr = 0 };
1149 	struct open_bucket *ob;
1150 	unsigned i;
1151 
1152 	mutex_lock(&wp->lock);
1153 	open_bucket_for_each(c, &wp->ptrs, ob, i)
1154 		if (should_drop_bucket(ob, c, ca, ec))
1155 			bch2_open_bucket_put(c, ob);
1156 		else
1157 			ob_push(c, &ptrs, ob);
1158 	wp->ptrs = ptrs;
1159 	mutex_unlock(&wp->lock);
1160 }
1161 
1162 void bch2_open_buckets_stop(struct bch_fs *c, struct bch_dev *ca,
1163 			    bool ec)
1164 {
1165 	unsigned i;
1166 
1167 	/* Next, close write points that point to this device... */
1168 	for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1169 		bch2_writepoint_stop(c, ca, ec, &c->write_points[i]);
1170 
1171 	bch2_writepoint_stop(c, ca, ec, &c->copygc_write_point);
1172 	bch2_writepoint_stop(c, ca, ec, &c->rebalance_write_point);
1173 	bch2_writepoint_stop(c, ca, ec, &c->btree_write_point);
1174 
1175 	mutex_lock(&c->btree_reserve_cache_lock);
1176 	while (c->btree_reserve_cache_nr) {
1177 		struct btree_alloc *a =
1178 			&c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1179 
1180 		bch2_open_buckets_put(c, &a->ob);
1181 	}
1182 	mutex_unlock(&c->btree_reserve_cache_lock);
1183 
1184 	spin_lock(&c->freelist_lock);
1185 	i = 0;
1186 	while (i < c->open_buckets_partial_nr) {
1187 		struct open_bucket *ob =
1188 			c->open_buckets + c->open_buckets_partial[i];
1189 
1190 		if (should_drop_bucket(ob, c, ca, ec)) {
1191 			--c->open_buckets_partial_nr;
1192 			swap(c->open_buckets_partial[i],
1193 			     c->open_buckets_partial[c->open_buckets_partial_nr]);
1194 			ob->on_partial_list = false;
1195 			spin_unlock(&c->freelist_lock);
1196 			bch2_open_bucket_put(c, ob);
1197 			spin_lock(&c->freelist_lock);
1198 		} else {
1199 			i++;
1200 		}
1201 	}
1202 	spin_unlock(&c->freelist_lock);
1203 
1204 	bch2_ec_stop_dev(c, ca);
1205 }
1206 
1207 static inline struct hlist_head *writepoint_hash(struct bch_fs *c,
1208 						 unsigned long write_point)
1209 {
1210 	unsigned hash =
1211 		hash_long(write_point, ilog2(ARRAY_SIZE(c->write_points_hash)));
1212 
1213 	return &c->write_points_hash[hash];
1214 }
1215 
1216 static struct write_point *__writepoint_find(struct hlist_head *head,
1217 					     unsigned long write_point)
1218 {
1219 	struct write_point *wp;
1220 
1221 	rcu_read_lock();
1222 	hlist_for_each_entry_rcu(wp, head, node)
1223 		if (wp->write_point == write_point)
1224 			goto out;
1225 	wp = NULL;
1226 out:
1227 	rcu_read_unlock();
1228 	return wp;
1229 }
1230 
1231 static inline bool too_many_writepoints(struct bch_fs *c, unsigned factor)
1232 {
1233 	u64 stranded	= c->write_points_nr * c->bucket_size_max;
1234 	u64 free	= bch2_fs_usage_read_short(c).free;
1235 
1236 	return stranded * factor > free;
1237 }
1238 
1239 static bool try_increase_writepoints(struct bch_fs *c)
1240 {
1241 	struct write_point *wp;
1242 
1243 	if (c->write_points_nr == ARRAY_SIZE(c->write_points) ||
1244 	    too_many_writepoints(c, 32))
1245 		return false;
1246 
1247 	wp = c->write_points + c->write_points_nr++;
1248 	hlist_add_head_rcu(&wp->node, writepoint_hash(c, wp->write_point));
1249 	return true;
1250 }
1251 
1252 static bool try_decrease_writepoints(struct btree_trans *trans, unsigned old_nr)
1253 {
1254 	struct bch_fs *c = trans->c;
1255 	struct write_point *wp;
1256 	struct open_bucket *ob;
1257 	unsigned i;
1258 
1259 	mutex_lock(&c->write_points_hash_lock);
1260 	if (c->write_points_nr < old_nr) {
1261 		mutex_unlock(&c->write_points_hash_lock);
1262 		return true;
1263 	}
1264 
1265 	if (c->write_points_nr == 1 ||
1266 	    !too_many_writepoints(c, 8)) {
1267 		mutex_unlock(&c->write_points_hash_lock);
1268 		return false;
1269 	}
1270 
1271 	wp = c->write_points + --c->write_points_nr;
1272 
1273 	hlist_del_rcu(&wp->node);
1274 	mutex_unlock(&c->write_points_hash_lock);
1275 
1276 	bch2_trans_mutex_lock_norelock(trans, &wp->lock);
1277 	open_bucket_for_each(c, &wp->ptrs, ob, i)
1278 		open_bucket_free_unused(c, ob);
1279 	wp->ptrs.nr = 0;
1280 	mutex_unlock(&wp->lock);
1281 	return true;
1282 }
1283 
1284 static struct write_point *writepoint_find(struct btree_trans *trans,
1285 					   unsigned long write_point)
1286 {
1287 	struct bch_fs *c = trans->c;
1288 	struct write_point *wp, *oldest;
1289 	struct hlist_head *head;
1290 
1291 	if (!(write_point & 1UL)) {
1292 		wp = (struct write_point *) write_point;
1293 		bch2_trans_mutex_lock_norelock(trans, &wp->lock);
1294 		return wp;
1295 	}
1296 
1297 	head = writepoint_hash(c, write_point);
1298 restart_find:
1299 	wp = __writepoint_find(head, write_point);
1300 	if (wp) {
1301 lock_wp:
1302 		bch2_trans_mutex_lock_norelock(trans, &wp->lock);
1303 		if (wp->write_point == write_point)
1304 			goto out;
1305 		mutex_unlock(&wp->lock);
1306 		goto restart_find;
1307 	}
1308 restart_find_oldest:
1309 	oldest = NULL;
1310 	for (wp = c->write_points;
1311 	     wp < c->write_points + c->write_points_nr; wp++)
1312 		if (!oldest || time_before64(wp->last_used, oldest->last_used))
1313 			oldest = wp;
1314 
1315 	bch2_trans_mutex_lock_norelock(trans, &oldest->lock);
1316 	bch2_trans_mutex_lock_norelock(trans, &c->write_points_hash_lock);
1317 	if (oldest >= c->write_points + c->write_points_nr ||
1318 	    try_increase_writepoints(c)) {
1319 		mutex_unlock(&c->write_points_hash_lock);
1320 		mutex_unlock(&oldest->lock);
1321 		goto restart_find_oldest;
1322 	}
1323 
1324 	wp = __writepoint_find(head, write_point);
1325 	if (wp && wp != oldest) {
1326 		mutex_unlock(&c->write_points_hash_lock);
1327 		mutex_unlock(&oldest->lock);
1328 		goto lock_wp;
1329 	}
1330 
1331 	wp = oldest;
1332 	hlist_del_rcu(&wp->node);
1333 	wp->write_point = write_point;
1334 	hlist_add_head_rcu(&wp->node, head);
1335 	mutex_unlock(&c->write_points_hash_lock);
1336 out:
1337 	wp->last_used = local_clock();
1338 	return wp;
1339 }
1340 
1341 static noinline void
1342 deallocate_extra_replicas(struct bch_fs *c,
1343 			  struct open_buckets *ptrs,
1344 			  struct open_buckets *ptrs_no_use,
1345 			  unsigned extra_replicas)
1346 {
1347 	struct open_buckets ptrs2 = { 0 };
1348 	struct open_bucket *ob;
1349 	unsigned i;
1350 
1351 	open_bucket_for_each(c, ptrs, ob, i) {
1352 		unsigned d = ob_dev(c, ob)->mi.durability;
1353 
1354 		if (d && d <= extra_replicas) {
1355 			extra_replicas -= d;
1356 			ob_push(c, ptrs_no_use, ob);
1357 		} else {
1358 			ob_push(c, &ptrs2, ob);
1359 		}
1360 	}
1361 
1362 	*ptrs = ptrs2;
1363 }
1364 
1365 /*
1366  * Get us an open_bucket we can allocate from, return with it locked:
1367  */
1368 int bch2_alloc_sectors_start_trans(struct btree_trans *trans,
1369 			     unsigned target,
1370 			     unsigned erasure_code,
1371 			     struct write_point_specifier write_point,
1372 			     struct bch_devs_list *devs_have,
1373 			     unsigned nr_replicas,
1374 			     unsigned nr_replicas_required,
1375 			     enum bch_watermark watermark,
1376 			     enum bch_write_flags flags,
1377 			     struct closure *cl,
1378 			     struct write_point **wp_ret)
1379 {
1380 	struct bch_fs *c = trans->c;
1381 	struct write_point *wp;
1382 	struct open_bucket *ob;
1383 	struct open_buckets ptrs;
1384 	unsigned nr_effective, write_points_nr;
1385 	bool have_cache;
1386 	int ret;
1387 	int i;
1388 
1389 	if (!IS_ENABLED(CONFIG_BCACHEFS_ERASURE_CODING))
1390 		erasure_code = false;
1391 
1392 	BUG_ON(!nr_replicas || !nr_replicas_required);
1393 retry:
1394 	ptrs.nr		= 0;
1395 	nr_effective	= 0;
1396 	write_points_nr = c->write_points_nr;
1397 	have_cache	= false;
1398 
1399 	*wp_ret = wp = writepoint_find(trans, write_point.v);
1400 
1401 	ret = bch2_trans_relock(trans);
1402 	if (ret)
1403 		goto err;
1404 
1405 	/* metadata may not allocate on cache devices: */
1406 	if (wp->data_type != BCH_DATA_user)
1407 		have_cache = true;
1408 
1409 	if (target && !(flags & BCH_WRITE_ONLY_SPECIFIED_DEVS)) {
1410 		ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1411 					      target, erasure_code,
1412 					      nr_replicas, &nr_effective,
1413 					      &have_cache, watermark,
1414 					      flags, NULL);
1415 		if (!ret ||
1416 		    bch2_err_matches(ret, BCH_ERR_transaction_restart))
1417 			goto alloc_done;
1418 
1419 		/* Don't retry from all devices if we're out of open buckets: */
1420 		if (bch2_err_matches(ret, BCH_ERR_open_buckets_empty)) {
1421 			int ret2 = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1422 					      target, erasure_code,
1423 					      nr_replicas, &nr_effective,
1424 					      &have_cache, watermark,
1425 					      flags, cl);
1426 			if (!ret2 ||
1427 			    bch2_err_matches(ret2, BCH_ERR_transaction_restart) ||
1428 			    bch2_err_matches(ret2, BCH_ERR_open_buckets_empty)) {
1429 				ret = ret2;
1430 				goto alloc_done;
1431 			}
1432 		}
1433 
1434 		/*
1435 		 * Only try to allocate cache (durability = 0 devices) from the
1436 		 * specified target:
1437 		 */
1438 		have_cache = true;
1439 
1440 		ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1441 					      0, erasure_code,
1442 					      nr_replicas, &nr_effective,
1443 					      &have_cache, watermark,
1444 					      flags, cl);
1445 	} else {
1446 		ret = open_bucket_add_buckets(trans, &ptrs, wp, devs_have,
1447 					      target, erasure_code,
1448 					      nr_replicas, &nr_effective,
1449 					      &have_cache, watermark,
1450 					      flags, cl);
1451 	}
1452 alloc_done:
1453 	BUG_ON(!ret && nr_effective < nr_replicas);
1454 
1455 	if (erasure_code && !ec_open_bucket(c, &ptrs))
1456 		pr_debug("failed to get ec bucket: ret %u", ret);
1457 
1458 	if (ret == -BCH_ERR_insufficient_devices &&
1459 	    nr_effective >= nr_replicas_required)
1460 		ret = 0;
1461 
1462 	if (ret)
1463 		goto err;
1464 
1465 	if (nr_effective > nr_replicas)
1466 		deallocate_extra_replicas(c, &ptrs, &wp->ptrs, nr_effective - nr_replicas);
1467 
1468 	/* Free buckets we didn't use: */
1469 	open_bucket_for_each(c, &wp->ptrs, ob, i)
1470 		open_bucket_free_unused(c, ob);
1471 
1472 	wp->ptrs = ptrs;
1473 
1474 	wp->sectors_free = UINT_MAX;
1475 
1476 	open_bucket_for_each(c, &wp->ptrs, ob, i)
1477 		wp->sectors_free = min(wp->sectors_free, ob->sectors_free);
1478 
1479 	BUG_ON(!wp->sectors_free || wp->sectors_free == UINT_MAX);
1480 
1481 	return 0;
1482 err:
1483 	open_bucket_for_each(c, &wp->ptrs, ob, i)
1484 		if (ptrs.nr < ARRAY_SIZE(ptrs.v))
1485 			ob_push(c, &ptrs, ob);
1486 		else
1487 			open_bucket_free_unused(c, ob);
1488 	wp->ptrs = ptrs;
1489 
1490 	mutex_unlock(&wp->lock);
1491 
1492 	if (bch2_err_matches(ret, BCH_ERR_freelist_empty) &&
1493 	    try_decrease_writepoints(trans, write_points_nr))
1494 		goto retry;
1495 
1496 	if (cl && bch2_err_matches(ret, BCH_ERR_open_buckets_empty))
1497 		ret = -BCH_ERR_bucket_alloc_blocked;
1498 
1499 	if (cl && !(flags & BCH_WRITE_ALLOC_NOWAIT) &&
1500 	    bch2_err_matches(ret, BCH_ERR_freelist_empty))
1501 		ret = -BCH_ERR_bucket_alloc_blocked;
1502 
1503 	return ret;
1504 }
1505 
1506 struct bch_extent_ptr bch2_ob_ptr(struct bch_fs *c, struct open_bucket *ob)
1507 {
1508 	struct bch_dev *ca = ob_dev(c, ob);
1509 
1510 	return (struct bch_extent_ptr) {
1511 		.type	= 1 << BCH_EXTENT_ENTRY_ptr,
1512 		.gen	= ob->gen,
1513 		.dev	= ob->dev,
1514 		.offset	= bucket_to_sector(ca, ob->bucket) +
1515 			ca->mi.bucket_size -
1516 			ob->sectors_free,
1517 	};
1518 }
1519 
1520 void bch2_alloc_sectors_append_ptrs(struct bch_fs *c, struct write_point *wp,
1521 				    struct bkey_i *k, unsigned sectors,
1522 				    bool cached)
1523 {
1524 	bch2_alloc_sectors_append_ptrs_inlined(c, wp, k, sectors, cached);
1525 }
1526 
1527 /*
1528  * Append pointers to the space we just allocated to @k, and mark @sectors space
1529  * as allocated out of @ob
1530  */
1531 void bch2_alloc_sectors_done(struct bch_fs *c, struct write_point *wp)
1532 {
1533 	bch2_alloc_sectors_done_inlined(c, wp);
1534 }
1535 
1536 static inline void writepoint_init(struct write_point *wp,
1537 				   enum bch_data_type type)
1538 {
1539 	mutex_init(&wp->lock);
1540 	wp->data_type = type;
1541 
1542 	INIT_WORK(&wp->index_update_work, bch2_write_point_do_index_updates);
1543 	INIT_LIST_HEAD(&wp->writes);
1544 	spin_lock_init(&wp->writes_lock);
1545 }
1546 
1547 void bch2_fs_allocator_foreground_init(struct bch_fs *c)
1548 {
1549 	struct open_bucket *ob;
1550 	struct write_point *wp;
1551 
1552 	mutex_init(&c->write_points_hash_lock);
1553 	c->write_points_nr = ARRAY_SIZE(c->write_points);
1554 
1555 	/* open bucket 0 is a sentinal NULL: */
1556 	spin_lock_init(&c->open_buckets[0].lock);
1557 
1558 	for (ob = c->open_buckets + 1;
1559 	     ob < c->open_buckets + ARRAY_SIZE(c->open_buckets); ob++) {
1560 		spin_lock_init(&ob->lock);
1561 		c->open_buckets_nr_free++;
1562 
1563 		ob->freelist = c->open_buckets_freelist;
1564 		c->open_buckets_freelist = ob - c->open_buckets;
1565 	}
1566 
1567 	writepoint_init(&c->btree_write_point,		BCH_DATA_btree);
1568 	writepoint_init(&c->rebalance_write_point,	BCH_DATA_user);
1569 	writepoint_init(&c->copygc_write_point,		BCH_DATA_user);
1570 
1571 	for (wp = c->write_points;
1572 	     wp < c->write_points + c->write_points_nr; wp++) {
1573 		writepoint_init(wp, BCH_DATA_user);
1574 
1575 		wp->last_used	= local_clock();
1576 		wp->write_point	= (unsigned long) wp;
1577 		hlist_add_head_rcu(&wp->node,
1578 				   writepoint_hash(c, wp->write_point));
1579 	}
1580 }
1581 
1582 void bch2_open_bucket_to_text(struct printbuf *out, struct bch_fs *c, struct open_bucket *ob)
1583 {
1584 	struct bch_dev *ca = ob_dev(c, ob);
1585 	unsigned data_type = ob->data_type;
1586 	barrier(); /* READ_ONCE() doesn't work on bitfields */
1587 
1588 	prt_printf(out, "%zu ref %u ",
1589 		   ob - c->open_buckets,
1590 		   atomic_read(&ob->pin));
1591 	bch2_prt_data_type(out, data_type);
1592 	prt_printf(out, " %u:%llu gen %u allocated %u/%u",
1593 		   ob->dev, ob->bucket, ob->gen,
1594 		   ca->mi.bucket_size - ob->sectors_free, ca->mi.bucket_size);
1595 	if (ob->ec)
1596 		prt_printf(out, " ec idx %llu", ob->ec->idx);
1597 	if (ob->on_partial_list)
1598 		prt_str(out, " partial");
1599 	prt_newline(out);
1600 }
1601 
1602 void bch2_open_buckets_to_text(struct printbuf *out, struct bch_fs *c,
1603 			       struct bch_dev *ca)
1604 {
1605 	struct open_bucket *ob;
1606 
1607 	out->atomic++;
1608 
1609 	for (ob = c->open_buckets;
1610 	     ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1611 	     ob++) {
1612 		spin_lock(&ob->lock);
1613 		if (ob->valid && !ob->on_partial_list &&
1614 		    (!ca || ob->dev == ca->dev_idx))
1615 			bch2_open_bucket_to_text(out, c, ob);
1616 		spin_unlock(&ob->lock);
1617 	}
1618 
1619 	--out->atomic;
1620 }
1621 
1622 void bch2_open_buckets_partial_to_text(struct printbuf *out, struct bch_fs *c)
1623 {
1624 	unsigned i;
1625 
1626 	out->atomic++;
1627 	spin_lock(&c->freelist_lock);
1628 
1629 	for (i = 0; i < c->open_buckets_partial_nr; i++)
1630 		bch2_open_bucket_to_text(out, c,
1631 				c->open_buckets + c->open_buckets_partial[i]);
1632 
1633 	spin_unlock(&c->freelist_lock);
1634 	--out->atomic;
1635 }
1636 
1637 static const char * const bch2_write_point_states[] = {
1638 #define x(n)	#n,
1639 	WRITE_POINT_STATES()
1640 #undef x
1641 	NULL
1642 };
1643 
1644 static void bch2_write_point_to_text(struct printbuf *out, struct bch_fs *c,
1645 				     struct write_point *wp)
1646 {
1647 	struct open_bucket *ob;
1648 	unsigned i;
1649 
1650 	prt_printf(out, "%lu: ", wp->write_point);
1651 	prt_human_readable_u64(out, wp->sectors_allocated);
1652 
1653 	prt_printf(out, " last wrote: ");
1654 	bch2_pr_time_units(out, sched_clock() - wp->last_used);
1655 
1656 	for (i = 0; i < WRITE_POINT_STATE_NR; i++) {
1657 		prt_printf(out, " %s: ", bch2_write_point_states[i]);
1658 		bch2_pr_time_units(out, wp->time[i]);
1659 	}
1660 
1661 	prt_newline(out);
1662 
1663 	printbuf_indent_add(out, 2);
1664 	open_bucket_for_each(c, &wp->ptrs, ob, i)
1665 		bch2_open_bucket_to_text(out, c, ob);
1666 	printbuf_indent_sub(out, 2);
1667 }
1668 
1669 void bch2_write_points_to_text(struct printbuf *out, struct bch_fs *c)
1670 {
1671 	struct write_point *wp;
1672 
1673 	prt_str(out, "Foreground write points\n");
1674 	for (wp = c->write_points;
1675 	     wp < c->write_points + ARRAY_SIZE(c->write_points);
1676 	     wp++)
1677 		bch2_write_point_to_text(out, c, wp);
1678 
1679 	prt_str(out, "Copygc write point\n");
1680 	bch2_write_point_to_text(out, c, &c->copygc_write_point);
1681 
1682 	prt_str(out, "Rebalance write point\n");
1683 	bch2_write_point_to_text(out, c, &c->rebalance_write_point);
1684 
1685 	prt_str(out, "Btree write point\n");
1686 	bch2_write_point_to_text(out, c, &c->btree_write_point);
1687 }
1688 
1689 void bch2_fs_alloc_debug_to_text(struct printbuf *out, struct bch_fs *c)
1690 {
1691 	unsigned nr[BCH_DATA_NR];
1692 
1693 	memset(nr, 0, sizeof(nr));
1694 
1695 	for (unsigned i = 0; i < ARRAY_SIZE(c->open_buckets); i++)
1696 		nr[c->open_buckets[i].data_type]++;
1697 
1698 	printbuf_tabstops_reset(out);
1699 	printbuf_tabstop_push(out, 24);
1700 
1701 	prt_printf(out, "capacity\t%llu\n",		c->capacity);
1702 	prt_printf(out, "reserved\t%llu\n",		c->reserved);
1703 	prt_printf(out, "hidden\t%llu\n",		percpu_u64_get(&c->usage->hidden));
1704 	prt_printf(out, "btree\t%llu\n",		percpu_u64_get(&c->usage->btree));
1705 	prt_printf(out, "data\t%llu\n",			percpu_u64_get(&c->usage->data));
1706 	prt_printf(out, "cached\t%llu\n",		percpu_u64_get(&c->usage->cached));
1707 	prt_printf(out, "reserved\t%llu\n",		percpu_u64_get(&c->usage->reserved));
1708 	prt_printf(out, "online_reserved\t%llu\n",	percpu_u64_get(c->online_reserved));
1709 	prt_printf(out, "nr_inodes\t%llu\n",		percpu_u64_get(&c->usage->nr_inodes));
1710 
1711 	prt_newline(out);
1712 	prt_printf(out, "freelist_wait\t%s\n",			c->freelist_wait.list.first ? "waiting" : "empty");
1713 	prt_printf(out, "open buckets allocated\t%i\n",		OPEN_BUCKETS_COUNT - c->open_buckets_nr_free);
1714 	prt_printf(out, "open buckets total\t%u\n",		OPEN_BUCKETS_COUNT);
1715 	prt_printf(out, "open_buckets_wait\t%s\n",		c->open_buckets_wait.list.first ? "waiting" : "empty");
1716 	prt_printf(out, "open_buckets_btree\t%u\n",		nr[BCH_DATA_btree]);
1717 	prt_printf(out, "open_buckets_user\t%u\n",		nr[BCH_DATA_user]);
1718 	prt_printf(out, "btree reserve cache\t%u\n",		c->btree_reserve_cache_nr);
1719 }
1720 
1721 void bch2_dev_alloc_debug_to_text(struct printbuf *out, struct bch_dev *ca)
1722 {
1723 	struct bch_fs *c = ca->fs;
1724 	struct bch_dev_usage stats = bch2_dev_usage_read(ca);
1725 	unsigned nr[BCH_DATA_NR];
1726 
1727 	memset(nr, 0, sizeof(nr));
1728 
1729 	for (unsigned i = 0; i < ARRAY_SIZE(c->open_buckets); i++)
1730 		nr[c->open_buckets[i].data_type]++;
1731 
1732 	bch2_dev_usage_to_text(out, ca, &stats);
1733 
1734 	prt_newline(out);
1735 
1736 	prt_printf(out, "reserves:\n");
1737 	for (unsigned i = 0; i < BCH_WATERMARK_NR; i++)
1738 		prt_printf(out, "%s\t%llu\r\n", bch2_watermarks[i], bch2_dev_buckets_reserved(ca, i));
1739 
1740 	prt_newline(out);
1741 
1742 	printbuf_tabstops_reset(out);
1743 	printbuf_tabstop_push(out, 12);
1744 	printbuf_tabstop_push(out, 16);
1745 
1746 	prt_printf(out, "open buckets\t%i\r\n",	ca->nr_open_buckets);
1747 	prt_printf(out, "buckets to invalidate\t%llu\r\n",	should_invalidate_buckets(ca, stats));
1748 }
1749 
1750 static noinline void bch2_print_allocator_stuck(struct bch_fs *c)
1751 {
1752 	struct printbuf buf = PRINTBUF;
1753 
1754 	prt_printf(&buf, "Allocator stuck? Waited for %u seconds\n",
1755 		   c->opts.allocator_stuck_timeout);
1756 
1757 	prt_printf(&buf, "Allocator debug:\n");
1758 	printbuf_indent_add(&buf, 2);
1759 	bch2_fs_alloc_debug_to_text(&buf, c);
1760 	printbuf_indent_sub(&buf, 2);
1761 	prt_newline(&buf);
1762 
1763 	for_each_online_member(c, ca) {
1764 		prt_printf(&buf, "Dev %u:\n", ca->dev_idx);
1765 		printbuf_indent_add(&buf, 2);
1766 		bch2_dev_alloc_debug_to_text(&buf, ca);
1767 		printbuf_indent_sub(&buf, 2);
1768 		prt_newline(&buf);
1769 	}
1770 
1771 	prt_printf(&buf, "Copygc debug:\n");
1772 	printbuf_indent_add(&buf, 2);
1773 	bch2_copygc_wait_to_text(&buf, c);
1774 	printbuf_indent_sub(&buf, 2);
1775 	prt_newline(&buf);
1776 
1777 	prt_printf(&buf, "Journal debug:\n");
1778 	printbuf_indent_add(&buf, 2);
1779 	bch2_journal_debug_to_text(&buf, &c->journal);
1780 	printbuf_indent_sub(&buf, 2);
1781 
1782 	bch2_print_string_as_lines(KERN_ERR, buf.buf);
1783 	printbuf_exit(&buf);
1784 }
1785 
1786 static inline unsigned allocator_wait_timeout(struct bch_fs *c)
1787 {
1788 	if (c->allocator_last_stuck &&
1789 	    time_after(c->allocator_last_stuck + HZ * 60 * 2, jiffies))
1790 		return 0;
1791 
1792 	return c->opts.allocator_stuck_timeout * HZ;
1793 }
1794 
1795 void __bch2_wait_on_allocator(struct bch_fs *c, struct closure *cl)
1796 {
1797 	unsigned t = allocator_wait_timeout(c);
1798 
1799 	if (t && closure_sync_timeout(cl, t)) {
1800 		c->allocator_last_stuck = jiffies;
1801 		bch2_print_allocator_stuck(c);
1802 	}
1803 
1804 	closure_sync(cl);
1805 }
1806