xref: /linux-6.15/fs/bcachefs/io_write.c (revision ee705fa2)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2010, 2011 Kent Overstreet <[email protected]>
4  * Copyright 2012 Google, Inc.
5  */
6 
7 #include "bcachefs.h"
8 #include "alloc_foreground.h"
9 #include "bkey_buf.h"
10 #include "bset.h"
11 #include "btree_update.h"
12 #include "buckets.h"
13 #include "checksum.h"
14 #include "clock.h"
15 #include "compress.h"
16 #include "debug.h"
17 #include "ec.h"
18 #include "error.h"
19 #include "extent_update.h"
20 #include "inode.h"
21 #include "io_write.h"
22 #include "journal.h"
23 #include "keylist.h"
24 #include "move.h"
25 #include "nocow_locking.h"
26 #include "rebalance.h"
27 #include "subvolume.h"
28 #include "super.h"
29 #include "super-io.h"
30 #include "trace.h"
31 
32 #include <linux/blkdev.h>
33 #include <linux/prefetch.h>
34 #include <linux/random.h>
35 #include <linux/sched/mm.h>
36 
37 #ifdef CONFIG_BCACHEFS_DEBUG
38 static unsigned bch2_write_corrupt_ratio;
39 module_param_named(write_corrupt_ratio, bch2_write_corrupt_ratio, uint, 0644);
40 MODULE_PARM_DESC(write_corrupt_ratio, "");
41 #endif
42 
43 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
44 
45 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
46 				       u64 now, int rw)
47 {
48 	u64 latency_capable =
49 		ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
50 	/* ideally we'd be taking into account the device's variance here: */
51 	u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
52 	s64 latency_over = io_latency - latency_threshold;
53 
54 	if (latency_threshold && latency_over > 0) {
55 		/*
56 		 * bump up congested by approximately latency_over * 4 /
57 		 * latency_threshold - we don't need much accuracy here so don't
58 		 * bother with the divide:
59 		 */
60 		if (atomic_read(&ca->congested) < CONGESTED_MAX)
61 			atomic_add(latency_over >>
62 				   max_t(int, ilog2(latency_threshold) - 2, 0),
63 				   &ca->congested);
64 
65 		ca->congested_last = now;
66 	} else if (atomic_read(&ca->congested) > 0) {
67 		atomic_dec(&ca->congested);
68 	}
69 }
70 
71 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
72 {
73 	atomic64_t *latency = &ca->cur_latency[rw];
74 	u64 now = local_clock();
75 	u64 io_latency = time_after64(now, submit_time)
76 		? now - submit_time
77 		: 0;
78 	u64 old, new;
79 
80 	old = atomic64_read(latency);
81 	do {
82 		/*
83 		 * If the io latency was reasonably close to the current
84 		 * latency, skip doing the update and atomic operation - most of
85 		 * the time:
86 		 */
87 		if (abs((int) (old - io_latency)) < (old >> 1) &&
88 		    now & ~(~0U << 5))
89 			break;
90 
91 		new = ewma_add(old, io_latency, 5);
92 	} while (!atomic64_try_cmpxchg(latency, &old, new));
93 
94 	bch2_congested_acct(ca, io_latency, now, rw);
95 
96 	__bch2_time_stats_update(&ca->io_latency[rw].stats, submit_time, now);
97 }
98 
99 #endif
100 
101 /* Allocate, free from mempool: */
102 
103 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
104 {
105 	struct bvec_iter_all iter;
106 	struct bio_vec *bv;
107 
108 	bio_for_each_segment_all(bv, bio, iter)
109 		if (bv->bv_page != ZERO_PAGE(0))
110 			mempool_free(bv->bv_page, &c->bio_bounce_pages);
111 	bio->bi_vcnt = 0;
112 }
113 
114 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
115 {
116 	struct page *page;
117 
118 	if (likely(!*using_mempool)) {
119 		page = alloc_page(GFP_NOFS);
120 		if (unlikely(!page)) {
121 			mutex_lock(&c->bio_bounce_pages_lock);
122 			*using_mempool = true;
123 			goto pool_alloc;
124 
125 		}
126 	} else {
127 pool_alloc:
128 		page = mempool_alloc(&c->bio_bounce_pages, GFP_NOFS);
129 	}
130 
131 	return page;
132 }
133 
134 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
135 			       size_t size)
136 {
137 	bool using_mempool = false;
138 
139 	while (size) {
140 		struct page *page = __bio_alloc_page_pool(c, &using_mempool);
141 		unsigned len = min_t(size_t, PAGE_SIZE, size);
142 
143 		BUG_ON(!bio_add_page(bio, page, len, 0));
144 		size -= len;
145 	}
146 
147 	if (using_mempool)
148 		mutex_unlock(&c->bio_bounce_pages_lock);
149 }
150 
151 /* Extent update path: */
152 
153 int bch2_sum_sector_overwrites(struct btree_trans *trans,
154 			       struct btree_iter *extent_iter,
155 			       struct bkey_i *new,
156 			       bool *usage_increasing,
157 			       s64 *i_sectors_delta,
158 			       s64 *disk_sectors_delta)
159 {
160 	struct bch_fs *c = trans->c;
161 	struct btree_iter iter;
162 	struct bkey_s_c old;
163 	unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new));
164 	bool new_compressed = bch2_bkey_sectors_compressed(bkey_i_to_s_c(new));
165 	int ret = 0;
166 
167 	*usage_increasing	= false;
168 	*i_sectors_delta	= 0;
169 	*disk_sectors_delta	= 0;
170 
171 	bch2_trans_copy_iter(&iter, extent_iter);
172 
173 	for_each_btree_key_max_continue_norestart(iter,
174 				new->k.p, BTREE_ITER_slots, old, ret) {
175 		s64 sectors = min(new->k.p.offset, old.k->p.offset) -
176 			max(bkey_start_offset(&new->k),
177 			    bkey_start_offset(old.k));
178 
179 		*i_sectors_delta += sectors *
180 			(bkey_extent_is_allocation(&new->k) -
181 			 bkey_extent_is_allocation(old.k));
182 
183 		*disk_sectors_delta += sectors * bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new));
184 		*disk_sectors_delta -= new->k.p.snapshot == old.k->p.snapshot
185 			? sectors * bch2_bkey_nr_ptrs_fully_allocated(old)
186 			: 0;
187 
188 		if (!*usage_increasing &&
189 		    (new->k.p.snapshot != old.k->p.snapshot ||
190 		     new_replicas > bch2_bkey_replicas(c, old) ||
191 		     (!new_compressed && bch2_bkey_sectors_compressed(old))))
192 			*usage_increasing = true;
193 
194 		if (bkey_ge(old.k->p, new->k.p))
195 			break;
196 	}
197 
198 	bch2_trans_iter_exit(trans, &iter);
199 	return ret;
200 }
201 
202 static inline int bch2_extent_update_i_size_sectors(struct btree_trans *trans,
203 						    struct btree_iter *extent_iter,
204 						    u64 new_i_size,
205 						    s64 i_sectors_delta)
206 {
207 	/*
208 	 * Crazy performance optimization:
209 	 * Every extent update needs to also update the inode: the inode trigger
210 	 * will set bi->journal_seq to the journal sequence number of this
211 	 * transaction - for fsync.
212 	 *
213 	 * But if that's the only reason we're updating the inode (we're not
214 	 * updating bi_size or bi_sectors), then we don't need the inode update
215 	 * to be journalled - if we crash, the bi_journal_seq update will be
216 	 * lost, but that's fine.
217 	 */
218 	unsigned inode_update_flags = BTREE_UPDATE_nojournal;
219 
220 	struct btree_iter iter;
221 	struct bkey_s_c k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_inodes,
222 			      SPOS(0,
223 				   extent_iter->pos.inode,
224 				   extent_iter->snapshot),
225 			      BTREE_ITER_intent|
226 			      BTREE_ITER_cached);
227 	int ret = bkey_err(k);
228 	if (unlikely(ret))
229 		return ret;
230 
231 	/*
232 	 * varint_decode_fast(), in the inode .invalid method, reads up to 7
233 	 * bytes past the end of the buffer:
234 	 */
235 	struct bkey_i *k_mut = bch2_trans_kmalloc_nomemzero(trans, bkey_bytes(k.k) + 8);
236 	ret = PTR_ERR_OR_ZERO(k_mut);
237 	if (unlikely(ret))
238 		goto err;
239 
240 	bkey_reassemble(k_mut, k);
241 
242 	if (unlikely(k_mut->k.type != KEY_TYPE_inode_v3)) {
243 		k_mut = bch2_inode_to_v3(trans, k_mut);
244 		ret = PTR_ERR_OR_ZERO(k_mut);
245 		if (unlikely(ret))
246 			goto err;
247 	}
248 
249 	struct bkey_i_inode_v3 *inode = bkey_i_to_inode_v3(k_mut);
250 
251 	if (!(le64_to_cpu(inode->v.bi_flags) & BCH_INODE_i_size_dirty) &&
252 	    new_i_size > le64_to_cpu(inode->v.bi_size)) {
253 		inode->v.bi_size = cpu_to_le64(new_i_size);
254 		inode_update_flags = 0;
255 	}
256 
257 	if (i_sectors_delta) {
258 		le64_add_cpu(&inode->v.bi_sectors, i_sectors_delta);
259 		inode_update_flags = 0;
260 	}
261 
262 	if (inode->k.p.snapshot != iter.snapshot) {
263 		inode->k.p.snapshot = iter.snapshot;
264 		inode_update_flags = 0;
265 	}
266 
267 	ret = bch2_trans_update(trans, &iter, &inode->k_i,
268 				BTREE_UPDATE_internal_snapshot_node|
269 				inode_update_flags);
270 err:
271 	bch2_trans_iter_exit(trans, &iter);
272 	return ret;
273 }
274 
275 int bch2_extent_update(struct btree_trans *trans,
276 		       subvol_inum inum,
277 		       struct btree_iter *iter,
278 		       struct bkey_i *k,
279 		       struct disk_reservation *disk_res,
280 		       u64 new_i_size,
281 		       s64 *i_sectors_delta_total,
282 		       bool check_enospc)
283 {
284 	struct bpos next_pos;
285 	bool usage_increasing;
286 	s64 i_sectors_delta = 0, disk_sectors_delta = 0;
287 	int ret;
288 
289 	/*
290 	 * This traverses us the iterator without changing iter->path->pos to
291 	 * search_key() (which is pos + 1 for extents): we want there to be a
292 	 * path already traversed at iter->pos because
293 	 * bch2_trans_extent_update() will use it to attempt extent merging
294 	 */
295 	ret = __bch2_btree_iter_traverse(iter);
296 	if (ret)
297 		return ret;
298 
299 	ret = bch2_extent_trim_atomic(trans, iter, k);
300 	if (ret)
301 		return ret;
302 
303 	next_pos = k->k.p;
304 
305 	ret = bch2_sum_sector_overwrites(trans, iter, k,
306 			&usage_increasing,
307 			&i_sectors_delta,
308 			&disk_sectors_delta);
309 	if (ret)
310 		return ret;
311 
312 	if (disk_res &&
313 	    disk_sectors_delta > (s64) disk_res->sectors) {
314 		ret = bch2_disk_reservation_add(trans->c, disk_res,
315 					disk_sectors_delta - disk_res->sectors,
316 					!check_enospc || !usage_increasing
317 					? BCH_DISK_RESERVATION_NOFAIL : 0);
318 		if (ret)
319 			return ret;
320 	}
321 
322 	/*
323 	 * Note:
324 	 * We always have to do an inode update - even when i_size/i_sectors
325 	 * aren't changing - for fsync to work properly; fsync relies on
326 	 * inode->bi_journal_seq which is updated by the trigger code:
327 	 */
328 	ret =   bch2_extent_update_i_size_sectors(trans, iter,
329 						  min(k->k.p.offset << 9, new_i_size),
330 						  i_sectors_delta) ?:
331 		bch2_trans_update(trans, iter, k, 0) ?:
332 		bch2_trans_commit(trans, disk_res, NULL,
333 				BCH_TRANS_COMMIT_no_check_rw|
334 				BCH_TRANS_COMMIT_no_enospc);
335 	if (unlikely(ret))
336 		return ret;
337 
338 	if (i_sectors_delta_total)
339 		*i_sectors_delta_total += i_sectors_delta;
340 	bch2_btree_iter_set_pos(iter, next_pos);
341 	return 0;
342 }
343 
344 static int bch2_write_index_default(struct bch_write_op *op)
345 {
346 	struct bch_fs *c = op->c;
347 	struct bkey_buf sk;
348 	struct keylist *keys = &op->insert_keys;
349 	struct bkey_i *k = bch2_keylist_front(keys);
350 	struct btree_trans *trans = bch2_trans_get(c);
351 	struct btree_iter iter;
352 	subvol_inum inum = {
353 		.subvol = op->subvol,
354 		.inum	= k->k.p.inode,
355 	};
356 	int ret;
357 
358 	BUG_ON(!inum.subvol);
359 
360 	bch2_bkey_buf_init(&sk);
361 
362 	do {
363 		bch2_trans_begin(trans);
364 
365 		k = bch2_keylist_front(keys);
366 		bch2_bkey_buf_copy(&sk, c, k);
367 
368 		ret = bch2_subvolume_get_snapshot(trans, inum.subvol,
369 						  &sk.k->k.p.snapshot);
370 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
371 			continue;
372 		if (ret)
373 			break;
374 
375 		bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
376 				     bkey_start_pos(&sk.k->k),
377 				     BTREE_ITER_slots|BTREE_ITER_intent);
378 
379 		ret =   bch2_bkey_set_needs_rebalance(c, &op->opts, sk.k) ?:
380 			bch2_extent_update(trans, inum, &iter, sk.k,
381 					&op->res,
382 					op->new_i_size, &op->i_sectors_delta,
383 					op->flags & BCH_WRITE_check_enospc);
384 		bch2_trans_iter_exit(trans, &iter);
385 
386 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
387 			continue;
388 		if (ret)
389 			break;
390 
391 		if (bkey_ge(iter.pos, k->k.p))
392 			bch2_keylist_pop_front(&op->insert_keys);
393 		else
394 			bch2_cut_front(iter.pos, k);
395 	} while (!bch2_keylist_empty(keys));
396 
397 	bch2_trans_put(trans);
398 	bch2_bkey_buf_exit(&sk, c);
399 
400 	return ret;
401 }
402 
403 /* Writes */
404 
405 void bch2_write_op_error(struct bch_write_op *op, u64 offset, const char *fmt, ...)
406 {
407 	struct printbuf buf = PRINTBUF;
408 
409 	if (op->subvol) {
410 		bch2_inum_offset_err_msg(op->c, &buf,
411 					 (subvol_inum) { op->subvol, op->pos.inode, },
412 					 offset << 9);
413 	} else {
414 		struct bpos pos = op->pos;
415 		pos.offset = offset;
416 		bch2_inum_snap_offset_err_msg(op->c, &buf, pos);
417 	}
418 
419 	prt_str(&buf, "write error: ");
420 
421 	va_list args;
422 	va_start(args, fmt);
423 	prt_vprintf(&buf, fmt, args);
424 	va_end(args);
425 
426 	if (op->flags & BCH_WRITE_move) {
427 		struct data_update *u = container_of(op, struct data_update, op);
428 
429 		prt_printf(&buf, "\n  from internal move ");
430 		bch2_bkey_val_to_text(&buf, op->c, bkey_i_to_s_c(u->k.k));
431 	}
432 
433 	bch_err_ratelimited(op->c, "%s", buf.buf);
434 	printbuf_exit(&buf);
435 }
436 
437 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
438 			       enum bch_data_type type,
439 			       const struct bkey_i *k,
440 			       bool nocow)
441 {
442 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
443 	struct bch_write_bio *n;
444 
445 	BUG_ON(c->opts.nochanges);
446 
447 	bkey_for_each_ptr(ptrs, ptr) {
448 		struct bch_dev *ca = nocow
449 			? bch2_dev_have_ref(c, ptr->dev)
450 			: bch2_dev_get_ioref(c, ptr->dev, type == BCH_DATA_btree ? READ : WRITE);
451 
452 		if (to_entry(ptr + 1) < ptrs.end) {
453 			n = to_wbio(bio_alloc_clone(NULL, &wbio->bio, GFP_NOFS, &c->replica_set));
454 
455 			n->bio.bi_end_io	= wbio->bio.bi_end_io;
456 			n->bio.bi_private	= wbio->bio.bi_private;
457 			n->parent		= wbio;
458 			n->split		= true;
459 			n->bounce		= false;
460 			n->put_bio		= true;
461 			n->bio.bi_opf		= wbio->bio.bi_opf;
462 			bio_inc_remaining(&wbio->bio);
463 		} else {
464 			n = wbio;
465 			n->split		= false;
466 		}
467 
468 		n->c			= c;
469 		n->dev			= ptr->dev;
470 		n->have_ioref		= ca != NULL;
471 		n->nocow		= nocow;
472 		n->submit_time		= local_clock();
473 		n->inode_offset		= bkey_start_offset(&k->k);
474 		if (nocow)
475 			n->nocow_bucket	= PTR_BUCKET_NR(ca, ptr);
476 		n->bio.bi_iter.bi_sector = ptr->offset;
477 
478 		if (likely(n->have_ioref)) {
479 			this_cpu_add(ca->io_done->sectors[WRITE][type],
480 				     bio_sectors(&n->bio));
481 
482 			bio_set_dev(&n->bio, ca->disk_sb.bdev);
483 
484 			if (type != BCH_DATA_btree && unlikely(c->opts.no_data_io)) {
485 				bio_endio(&n->bio);
486 				continue;
487 			}
488 
489 			submit_bio(&n->bio);
490 		} else {
491 			n->bio.bi_status	= BLK_STS_REMOVED;
492 			bio_endio(&n->bio);
493 		}
494 	}
495 }
496 
497 static void __bch2_write(struct bch_write_op *);
498 
499 static void bch2_write_done(struct closure *cl)
500 {
501 	struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
502 	struct bch_fs *c = op->c;
503 
504 	EBUG_ON(op->open_buckets.nr);
505 
506 	bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
507 	bch2_disk_reservation_put(c, &op->res);
508 
509 	if (!(op->flags & BCH_WRITE_move))
510 		bch2_write_ref_put(c, BCH_WRITE_REF_write);
511 	bch2_keylist_free(&op->insert_keys, op->inline_keys);
512 
513 	EBUG_ON(cl->parent);
514 	closure_debug_destroy(cl);
515 	if (op->end_io)
516 		op->end_io(op);
517 }
518 
519 static noinline int bch2_write_drop_io_error_ptrs(struct bch_write_op *op)
520 {
521 	struct keylist *keys = &op->insert_keys;
522 	struct bkey_i *src, *dst = keys->keys, *n;
523 
524 	for (src = keys->keys; src != keys->top; src = n) {
525 		n = bkey_next(src);
526 
527 		if (bkey_extent_is_direct_data(&src->k)) {
528 			bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
529 					    test_bit(ptr->dev, op->failed.d));
530 
531 			if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src)))
532 				return -BCH_ERR_data_write_io;
533 		}
534 
535 		if (dst != src)
536 			memmove_u64s_down(dst, src, src->k.u64s);
537 		dst = bkey_next(dst);
538 	}
539 
540 	keys->top = dst;
541 	return 0;
542 }
543 
544 /**
545  * __bch2_write_index - after a write, update index to point to new data
546  * @op:		bch_write_op to process
547  */
548 static void __bch2_write_index(struct bch_write_op *op)
549 {
550 	struct bch_fs *c = op->c;
551 	struct keylist *keys = &op->insert_keys;
552 	unsigned dev;
553 	int ret = 0;
554 
555 	if (unlikely(op->flags & BCH_WRITE_io_error)) {
556 		ret = bch2_write_drop_io_error_ptrs(op);
557 		if (ret)
558 			goto err;
559 	}
560 
561 	if (!bch2_keylist_empty(keys)) {
562 		u64 sectors_start = keylist_sectors(keys);
563 
564 		ret = !(op->flags & BCH_WRITE_move)
565 			? bch2_write_index_default(op)
566 			: bch2_data_update_index_update(op);
567 
568 		BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart));
569 		BUG_ON(keylist_sectors(keys) && !ret);
570 
571 		op->written += sectors_start - keylist_sectors(keys);
572 
573 		if (unlikely(ret && !bch2_err_matches(ret, EROFS))) {
574 			struct bkey_i *insert = bch2_keylist_front(&op->insert_keys);
575 
576 			bch2_write_op_error(op, bkey_start_offset(&insert->k),
577 					    "btree update error: %s", bch2_err_str(ret));
578 		}
579 
580 		if (ret)
581 			goto err;
582 	}
583 out:
584 	/* If some a bucket wasn't written, we can't erasure code it: */
585 	for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
586 		bch2_open_bucket_write_error(c, &op->open_buckets, dev, -BCH_ERR_data_write_io);
587 
588 	bch2_open_buckets_put(c, &op->open_buckets);
589 	return;
590 err:
591 	keys->top = keys->keys;
592 	op->error = ret;
593 	op->flags |= BCH_WRITE_submitted;
594 	goto out;
595 }
596 
597 static inline void __wp_update_state(struct write_point *wp, enum write_point_state state)
598 {
599 	if (state != wp->state) {
600 		struct task_struct *p = current;
601 		u64 now = ktime_get_ns();
602 		u64 runtime = p->se.sum_exec_runtime +
603 			(now - p->se.exec_start);
604 
605 		if (state == WRITE_POINT_runnable)
606 			wp->last_runtime = runtime;
607 		else if (wp->state == WRITE_POINT_runnable)
608 			wp->time[WRITE_POINT_running] += runtime - wp->last_runtime;
609 
610 		if (wp->last_state_change &&
611 		    time_after64(now, wp->last_state_change))
612 			wp->time[wp->state] += now - wp->last_state_change;
613 		wp->state = state;
614 		wp->last_state_change = now;
615 	}
616 }
617 
618 static inline void wp_update_state(struct write_point *wp, bool running)
619 {
620 	enum write_point_state state;
621 
622 	state = running			 ? WRITE_POINT_runnable:
623 		!list_empty(&wp->writes) ? WRITE_POINT_waiting_io
624 					 : WRITE_POINT_stopped;
625 
626 	__wp_update_state(wp, state);
627 }
628 
629 static CLOSURE_CALLBACK(bch2_write_index)
630 {
631 	closure_type(op, struct bch_write_op, cl);
632 	struct write_point *wp = op->wp;
633 	struct workqueue_struct *wq = index_update_wq(op);
634 	unsigned long flags;
635 
636 	if ((op->flags & BCH_WRITE_submitted) &&
637 	    (op->flags & BCH_WRITE_move))
638 		bch2_bio_free_pages_pool(op->c, &op->wbio.bio);
639 
640 	spin_lock_irqsave(&wp->writes_lock, flags);
641 	if (wp->state == WRITE_POINT_waiting_io)
642 		__wp_update_state(wp, WRITE_POINT_waiting_work);
643 	list_add_tail(&op->wp_list, &wp->writes);
644 	spin_unlock_irqrestore (&wp->writes_lock, flags);
645 
646 	queue_work(wq, &wp->index_update_work);
647 }
648 
649 static inline void bch2_write_queue(struct bch_write_op *op, struct write_point *wp)
650 {
651 	op->wp = wp;
652 
653 	if (wp->state == WRITE_POINT_stopped) {
654 		spin_lock_irq(&wp->writes_lock);
655 		__wp_update_state(wp, WRITE_POINT_waiting_io);
656 		spin_unlock_irq(&wp->writes_lock);
657 	}
658 }
659 
660 void bch2_write_point_do_index_updates(struct work_struct *work)
661 {
662 	struct write_point *wp =
663 		container_of(work, struct write_point, index_update_work);
664 	struct bch_write_op *op;
665 
666 	while (1) {
667 		spin_lock_irq(&wp->writes_lock);
668 		op = list_pop_entry(&wp->writes, struct bch_write_op, wp_list);
669 		wp_update_state(wp, op != NULL);
670 		spin_unlock_irq(&wp->writes_lock);
671 
672 		if (!op)
673 			break;
674 
675 		op->flags |= BCH_WRITE_in_worker;
676 
677 		__bch2_write_index(op);
678 
679 		if (!(op->flags & BCH_WRITE_submitted))
680 			__bch2_write(op);
681 		else
682 			bch2_write_done(&op->cl);
683 	}
684 }
685 
686 static void bch2_write_endio(struct bio *bio)
687 {
688 	struct closure *cl		= bio->bi_private;
689 	struct bch_write_op *op		= container_of(cl, struct bch_write_op, cl);
690 	struct bch_write_bio *wbio	= to_wbio(bio);
691 	struct bch_write_bio *parent	= wbio->split ? wbio->parent : NULL;
692 	struct bch_fs *c		= wbio->c;
693 	struct bch_dev *ca		= wbio->have_ioref
694 		? bch2_dev_have_ref(c, wbio->dev)
695 		: NULL;
696 
697 	bch2_account_io_completion(ca, BCH_MEMBER_ERROR_write,
698 				   wbio->submit_time, !bio->bi_status);
699 
700 	if (bio->bi_status) {
701 		bch_err_inum_offset_ratelimited(ca,
702 				    op->pos.inode,
703 				    wbio->inode_offset << 9,
704 				    "data write error: %s",
705 				    bch2_blk_status_to_str(bio->bi_status));
706 		set_bit(wbio->dev, op->failed.d);
707 		op->flags |= BCH_WRITE_io_error;
708 	}
709 
710 	if (wbio->nocow) {
711 		bch2_bucket_nocow_unlock(&c->nocow_locks,
712 					 POS(ca->dev_idx, wbio->nocow_bucket),
713 					 BUCKET_NOCOW_LOCK_UPDATE);
714 		set_bit(wbio->dev, op->devs_need_flush->d);
715 	}
716 
717 	if (wbio->have_ioref)
718 		percpu_ref_put(&ca->io_ref);
719 
720 	if (wbio->bounce)
721 		bch2_bio_free_pages_pool(c, bio);
722 
723 	if (wbio->put_bio)
724 		bio_put(bio);
725 
726 	if (parent)
727 		bio_endio(&parent->bio);
728 	else
729 		closure_put(cl);
730 }
731 
732 static void init_append_extent(struct bch_write_op *op,
733 			       struct write_point *wp,
734 			       struct bversion version,
735 			       struct bch_extent_crc_unpacked crc)
736 {
737 	struct bkey_i_extent *e;
738 
739 	op->pos.offset += crc.uncompressed_size;
740 
741 	e = bkey_extent_init(op->insert_keys.top);
742 	e->k.p		= op->pos;
743 	e->k.size	= crc.uncompressed_size;
744 	e->k.bversion	= version;
745 
746 	if (crc.csum_type ||
747 	    crc.compression_type ||
748 	    crc.nonce)
749 		bch2_extent_crc_append(&e->k_i, crc);
750 
751 	bch2_alloc_sectors_append_ptrs_inlined(op->c, wp, &e->k_i, crc.compressed_size,
752 				       op->flags & BCH_WRITE_cached);
753 
754 	bch2_keylist_push(&op->insert_keys);
755 }
756 
757 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
758 					struct write_point *wp,
759 					struct bio *src,
760 					bool *page_alloc_failed,
761 					void *buf)
762 {
763 	struct bch_write_bio *wbio;
764 	struct bio *bio;
765 	unsigned output_available =
766 		min(wp->sectors_free << 9, src->bi_iter.bi_size);
767 	unsigned pages = DIV_ROUND_UP(output_available +
768 				      (buf
769 				       ? ((unsigned long) buf & (PAGE_SIZE - 1))
770 				       : 0), PAGE_SIZE);
771 
772 	pages = min(pages, BIO_MAX_VECS);
773 
774 	bio = bio_alloc_bioset(NULL, pages, 0,
775 			       GFP_NOFS, &c->bio_write);
776 	wbio			= wbio_init(bio);
777 	wbio->put_bio		= true;
778 	/* copy WRITE_SYNC flag */
779 	wbio->bio.bi_opf	= src->bi_opf;
780 
781 	if (buf) {
782 		bch2_bio_map(bio, buf, output_available);
783 		return bio;
784 	}
785 
786 	wbio->bounce		= true;
787 
788 	/*
789 	 * We can't use mempool for more than c->sb.encoded_extent_max
790 	 * worth of pages, but we'd like to allocate more if we can:
791 	 */
792 	bch2_bio_alloc_pages_pool(c, bio,
793 				  min_t(unsigned, output_available,
794 					c->opts.encoded_extent_max));
795 
796 	if (bio->bi_iter.bi_size < output_available)
797 		*page_alloc_failed =
798 			bch2_bio_alloc_pages(bio,
799 					     output_available -
800 					     bio->bi_iter.bi_size,
801 					     GFP_NOFS) != 0;
802 
803 	return bio;
804 }
805 
806 static int bch2_write_rechecksum(struct bch_fs *c,
807 				 struct bch_write_op *op,
808 				 unsigned new_csum_type)
809 {
810 	struct bio *bio = &op->wbio.bio;
811 	struct bch_extent_crc_unpacked new_crc;
812 
813 	/* bch2_rechecksum_bio() can't encrypt or decrypt data: */
814 
815 	if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
816 	    bch2_csum_type_is_encryption(new_csum_type))
817 		new_csum_type = op->crc.csum_type;
818 
819 	int ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
820 				      NULL, &new_crc,
821 				      op->crc.offset, op->crc.live_size,
822 				      new_csum_type);
823 	if (ret)
824 		return ret;
825 
826 	bio_advance(bio, op->crc.offset << 9);
827 	bio->bi_iter.bi_size = op->crc.live_size << 9;
828 	op->crc = new_crc;
829 	return 0;
830 }
831 
832 static noinline int bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
833 {
834 	struct bch_fs *c = op->c;
835 	struct bio *bio = &op->wbio.bio;
836 	struct bch_csum csum;
837 	int ret = 0;
838 
839 	BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
840 
841 	/* Can we just write the entire extent as is? */
842 	if (op->crc.uncompressed_size == op->crc.live_size &&
843 	    op->crc.uncompressed_size <= c->opts.encoded_extent_max >> 9 &&
844 	    op->crc.compressed_size <= wp->sectors_free &&
845 	    (op->crc.compression_type == bch2_compression_opt_to_type(op->compression_opt) ||
846 	     op->incompressible)) {
847 		if (!crc_is_compressed(op->crc) &&
848 		    op->csum_type != op->crc.csum_type) {
849 			ret = bch2_write_rechecksum(c, op, op->csum_type);
850 			if (ret)
851 				return ret;
852 		}
853 
854 		return 1;
855 	}
856 
857 	/*
858 	 * If the data is compressed and we couldn't write the entire extent as
859 	 * is, we have to decompress it:
860 	 */
861 	if (crc_is_compressed(op->crc)) {
862 		/* Last point we can still verify checksum: */
863 		struct nonce nonce = extent_nonce(op->version, op->crc);
864 		csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, bio);
865 		if (bch2_crc_cmp(op->crc.csum, csum) && !c->opts.no_data_io)
866 			goto csum_err;
867 
868 		if (bch2_csum_type_is_encryption(op->crc.csum_type)) {
869 			ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, bio);
870 			if (ret)
871 				return ret;
872 
873 			op->crc.csum_type = 0;
874 			op->crc.csum = (struct bch_csum) { 0, 0 };
875 		}
876 
877 		ret = bch2_bio_uncompress_inplace(op, bio);
878 		if (ret)
879 			return ret;
880 	}
881 
882 	/*
883 	 * No longer have compressed data after this point - data might be
884 	 * encrypted:
885 	 */
886 
887 	/*
888 	 * If the data is checksummed and we're only writing a subset,
889 	 * rechecksum and adjust bio to point to currently live data:
890 	 */
891 	if (op->crc.live_size != op->crc.uncompressed_size ||
892 	    op->crc.csum_type != op->csum_type) {
893 		ret = bch2_write_rechecksum(c, op, op->csum_type);
894 		if (ret)
895 			return ret;
896 	}
897 
898 	/*
899 	 * If we want to compress the data, it has to be decrypted:
900 	 */
901 	if (bch2_csum_type_is_encryption(op->crc.csum_type) &&
902 	    (op->compression_opt || op->crc.csum_type != op->csum_type)) {
903 		struct nonce nonce = extent_nonce(op->version, op->crc);
904 		csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, bio);
905 		if (bch2_crc_cmp(op->crc.csum, csum) && !c->opts.no_data_io)
906 			goto csum_err;
907 
908 		ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, bio);
909 		if (ret)
910 			return ret;
911 
912 		op->crc.csum_type = 0;
913 		op->crc.csum = (struct bch_csum) { 0, 0 };
914 	}
915 
916 	return 0;
917 csum_err:
918 	bch2_write_op_error(op, op->pos.offset,
919 		"error verifying existing checksum while moving existing data (memory corruption?)\n"
920 		"  expected %0llx:%0llx got %0llx:%0llx type %s",
921 		op->crc.csum.hi,
922 		op->crc.csum.lo,
923 		csum.hi,
924 		csum.lo,
925 		op->crc.csum_type < BCH_CSUM_NR
926 		? __bch2_csum_types[op->crc.csum_type]
927 		: "(unknown)");
928 	return -BCH_ERR_data_write_csum;
929 }
930 
931 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
932 			     struct bio **_dst)
933 {
934 	struct bch_fs *c = op->c;
935 	struct bio *src = &op->wbio.bio, *dst = src;
936 	struct bvec_iter saved_iter;
937 	void *ec_buf;
938 	unsigned total_output = 0, total_input = 0;
939 	bool bounce = false;
940 	bool page_alloc_failed = false;
941 	int ret, more = 0;
942 
943 	if (op->incompressible)
944 		op->compression_opt = 0;
945 
946 	BUG_ON(!bio_sectors(src));
947 
948 	ec_buf = bch2_writepoint_ec_buf(c, wp);
949 
950 	if (unlikely(op->flags & BCH_WRITE_data_encoded)) {
951 		ret = bch2_write_prep_encoded_data(op, wp);
952 		if (ret < 0)
953 			goto err;
954 		if (ret) {
955 			if (ec_buf) {
956 				dst = bch2_write_bio_alloc(c, wp, src,
957 							   &page_alloc_failed,
958 							   ec_buf);
959 				bio_copy_data(dst, src);
960 				bounce = true;
961 			}
962 			init_append_extent(op, wp, op->version, op->crc);
963 			goto do_write;
964 		}
965 	}
966 
967 	if (ec_buf ||
968 	    op->compression_opt ||
969 	    (op->csum_type &&
970 	     !(op->flags & BCH_WRITE_pages_stable)) ||
971 	    (bch2_csum_type_is_encryption(op->csum_type) &&
972 	     !(op->flags & BCH_WRITE_pages_owned))) {
973 		dst = bch2_write_bio_alloc(c, wp, src,
974 					   &page_alloc_failed,
975 					   ec_buf);
976 		bounce = true;
977 	}
978 
979 #ifdef CONFIG_BCACHEFS_DEBUG
980 	unsigned write_corrupt_ratio = READ_ONCE(bch2_write_corrupt_ratio);
981 	if (!bounce && write_corrupt_ratio) {
982 		dst = bch2_write_bio_alloc(c, wp, src,
983 					   &page_alloc_failed,
984 					   ec_buf);
985 		bounce = true;
986 	}
987 #endif
988 	saved_iter = dst->bi_iter;
989 
990 	do {
991 		struct bch_extent_crc_unpacked crc = { 0 };
992 		struct bversion version = op->version;
993 		size_t dst_len = 0, src_len = 0;
994 
995 		if (page_alloc_failed &&
996 		    dst->bi_iter.bi_size  < (wp->sectors_free << 9) &&
997 		    dst->bi_iter.bi_size < c->opts.encoded_extent_max)
998 			break;
999 
1000 		BUG_ON(op->compression_opt &&
1001 		       (op->flags & BCH_WRITE_data_encoded) &&
1002 		       bch2_csum_type_is_encryption(op->crc.csum_type));
1003 		BUG_ON(op->compression_opt && !bounce);
1004 
1005 		crc.compression_type = op->incompressible
1006 			? BCH_COMPRESSION_TYPE_incompressible
1007 			: op->compression_opt
1008 			? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
1009 					    op->compression_opt)
1010 			: 0;
1011 		if (!crc_is_compressed(crc)) {
1012 			dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
1013 			dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
1014 
1015 			if (op->csum_type)
1016 				dst_len = min_t(unsigned, dst_len,
1017 						c->opts.encoded_extent_max);
1018 
1019 			if (bounce) {
1020 				swap(dst->bi_iter.bi_size, dst_len);
1021 				bio_copy_data(dst, src);
1022 				swap(dst->bi_iter.bi_size, dst_len);
1023 			}
1024 
1025 			src_len = dst_len;
1026 		}
1027 
1028 		BUG_ON(!src_len || !dst_len);
1029 
1030 		if (bch2_csum_type_is_encryption(op->csum_type)) {
1031 			if (bversion_zero(version)) {
1032 				version.lo = atomic64_inc_return(&c->key_version);
1033 			} else {
1034 				crc.nonce = op->nonce;
1035 				op->nonce += src_len >> 9;
1036 			}
1037 		}
1038 
1039 		if ((op->flags & BCH_WRITE_data_encoded) &&
1040 		    !crc_is_compressed(crc) &&
1041 		    bch2_csum_type_is_encryption(op->crc.csum_type) ==
1042 		    bch2_csum_type_is_encryption(op->csum_type)) {
1043 			u8 compression_type = crc.compression_type;
1044 			u16 nonce = crc.nonce;
1045 			/*
1046 			 * Note: when we're using rechecksum(), we need to be
1047 			 * checksumming @src because it has all the data our
1048 			 * existing checksum covers - if we bounced (because we
1049 			 * were trying to compress), @dst will only have the
1050 			 * part of the data the new checksum will cover.
1051 			 *
1052 			 * But normally we want to be checksumming post bounce,
1053 			 * because part of the reason for bouncing is so the
1054 			 * data can't be modified (by userspace) while it's in
1055 			 * flight.
1056 			 */
1057 			ret = bch2_rechecksum_bio(c, src, version, op->crc,
1058 					&crc, &op->crc,
1059 					src_len >> 9,
1060 					bio_sectors(src) - (src_len >> 9),
1061 					op->csum_type);
1062 			if (ret)
1063 				goto err;
1064 			/*
1065 			 * rchecksum_bio sets compression_type on crc from op->crc,
1066 			 * this isn't always correct as sometimes we're changing
1067 			 * an extent from uncompressed to incompressible.
1068 			 */
1069 			crc.compression_type = compression_type;
1070 			crc.nonce = nonce;
1071 		} else {
1072 			if ((op->flags & BCH_WRITE_data_encoded) &&
1073 			    (ret = bch2_rechecksum_bio(c, src, version, op->crc,
1074 					NULL, &op->crc,
1075 					src_len >> 9,
1076 					bio_sectors(src) - (src_len >> 9),
1077 					op->crc.csum_type)))
1078 				goto err;
1079 
1080 			crc.compressed_size	= dst_len >> 9;
1081 			crc.uncompressed_size	= src_len >> 9;
1082 			crc.live_size		= src_len >> 9;
1083 
1084 			swap(dst->bi_iter.bi_size, dst_len);
1085 			ret = bch2_encrypt_bio(c, op->csum_type,
1086 					       extent_nonce(version, crc), dst);
1087 			if (ret)
1088 				goto err;
1089 
1090 			crc.csum = bch2_checksum_bio(c, op->csum_type,
1091 					 extent_nonce(version, crc), dst);
1092 			crc.csum_type = op->csum_type;
1093 			swap(dst->bi_iter.bi_size, dst_len);
1094 		}
1095 
1096 		init_append_extent(op, wp, version, crc);
1097 
1098 #ifdef CONFIG_BCACHEFS_DEBUG
1099 		if (write_corrupt_ratio) {
1100 			swap(dst->bi_iter.bi_size, dst_len);
1101 			bch2_maybe_corrupt_bio(dst, write_corrupt_ratio);
1102 			swap(dst->bi_iter.bi_size, dst_len);
1103 		}
1104 #endif
1105 
1106 		if (dst != src)
1107 			bio_advance(dst, dst_len);
1108 		bio_advance(src, src_len);
1109 		total_output	+= dst_len;
1110 		total_input	+= src_len;
1111 	} while (dst->bi_iter.bi_size &&
1112 		 src->bi_iter.bi_size &&
1113 		 wp->sectors_free &&
1114 		 !bch2_keylist_realloc(&op->insert_keys,
1115 				      op->inline_keys,
1116 				      ARRAY_SIZE(op->inline_keys),
1117 				      BKEY_EXTENT_U64s_MAX));
1118 
1119 	more = src->bi_iter.bi_size != 0;
1120 
1121 	dst->bi_iter = saved_iter;
1122 
1123 	if (dst == src && more) {
1124 		BUG_ON(total_output != total_input);
1125 
1126 		dst = bio_split(src, total_input >> 9,
1127 				GFP_NOFS, &c->bio_write);
1128 		wbio_init(dst)->put_bio	= true;
1129 		/* copy WRITE_SYNC flag */
1130 		dst->bi_opf		= src->bi_opf;
1131 	}
1132 
1133 	dst->bi_iter.bi_size = total_output;
1134 do_write:
1135 	*_dst = dst;
1136 	return more;
1137 err:
1138 	if (to_wbio(dst)->bounce)
1139 		bch2_bio_free_pages_pool(c, dst);
1140 	if (to_wbio(dst)->put_bio)
1141 		bio_put(dst);
1142 
1143 	return ret;
1144 }
1145 
1146 static bool bch2_extent_is_writeable(struct bch_write_op *op,
1147 				     struct bkey_s_c k)
1148 {
1149 	struct bch_fs *c = op->c;
1150 	struct bkey_s_c_extent e;
1151 	struct extent_ptr_decoded p;
1152 	const union bch_extent_entry *entry;
1153 	unsigned replicas = 0;
1154 
1155 	if (k.k->type != KEY_TYPE_extent)
1156 		return false;
1157 
1158 	e = bkey_s_c_to_extent(k);
1159 
1160 	rcu_read_lock();
1161 	extent_for_each_ptr_decode(e, p, entry) {
1162 		if (crc_is_encoded(p.crc) || p.has_ec) {
1163 			rcu_read_unlock();
1164 			return false;
1165 		}
1166 
1167 		replicas += bch2_extent_ptr_durability(c, &p);
1168 	}
1169 	rcu_read_unlock();
1170 
1171 	return replicas >= op->opts.data_replicas;
1172 }
1173 
1174 static int bch2_nocow_write_convert_one_unwritten(struct btree_trans *trans,
1175 						  struct btree_iter *iter,
1176 						  struct bkey_i *orig,
1177 						  struct bkey_s_c k,
1178 						  u64 new_i_size)
1179 {
1180 	if (!bch2_extents_match(bkey_i_to_s_c(orig), k)) {
1181 		/* trace this */
1182 		return 0;
1183 	}
1184 
1185 	struct bkey_i *new = bch2_bkey_make_mut_noupdate(trans, k);
1186 	int ret = PTR_ERR_OR_ZERO(new);
1187 	if (ret)
1188 		return ret;
1189 
1190 	bch2_cut_front(bkey_start_pos(&orig->k), new);
1191 	bch2_cut_back(orig->k.p, new);
1192 
1193 	struct bkey_ptrs ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
1194 	bkey_for_each_ptr(ptrs, ptr)
1195 		ptr->unwritten = 0;
1196 
1197 	/*
1198 	 * Note that we're not calling bch2_subvol_get_snapshot() in this path -
1199 	 * that was done when we kicked off the write, and here it's important
1200 	 * that we update the extent that we wrote to - even if a snapshot has
1201 	 * since been created. The write is still outstanding, so we're ok
1202 	 * w.r.t. snapshot atomicity:
1203 	 */
1204 	return  bch2_extent_update_i_size_sectors(trans, iter,
1205 					min(new->k.p.offset << 9, new_i_size), 0) ?:
1206 		bch2_trans_update(trans, iter, new,
1207 				  BTREE_UPDATE_internal_snapshot_node);
1208 }
1209 
1210 static void bch2_nocow_write_convert_unwritten(struct bch_write_op *op)
1211 {
1212 	struct bch_fs *c = op->c;
1213 	struct btree_trans *trans = bch2_trans_get(c);
1214 	int ret = 0;
1215 
1216 	for_each_keylist_key(&op->insert_keys, orig) {
1217 		ret = for_each_btree_key_max_commit(trans, iter, BTREE_ID_extents,
1218 				     bkey_start_pos(&orig->k), orig->k.p,
1219 				     BTREE_ITER_intent, k,
1220 				     NULL, NULL, BCH_TRANS_COMMIT_no_enospc, ({
1221 			bch2_nocow_write_convert_one_unwritten(trans, &iter, orig, k, op->new_i_size);
1222 		}));
1223 		if (ret)
1224 			break;
1225 	}
1226 
1227 	bch2_trans_put(trans);
1228 
1229 	if (ret && !bch2_err_matches(ret, EROFS)) {
1230 		struct bkey_i *insert = bch2_keylist_front(&op->insert_keys);
1231 		bch2_write_op_error(op, bkey_start_offset(&insert->k),
1232 				    "btree update error: %s", bch2_err_str(ret));
1233 	}
1234 
1235 	if (ret)
1236 		op->error = ret;
1237 }
1238 
1239 static void __bch2_nocow_write_done(struct bch_write_op *op)
1240 {
1241 	if (unlikely(op->flags & BCH_WRITE_io_error)) {
1242 		op->error = -BCH_ERR_data_write_io;
1243 	} else if (unlikely(op->flags & BCH_WRITE_convert_unwritten))
1244 		bch2_nocow_write_convert_unwritten(op);
1245 }
1246 
1247 static CLOSURE_CALLBACK(bch2_nocow_write_done)
1248 {
1249 	closure_type(op, struct bch_write_op, cl);
1250 
1251 	__bch2_nocow_write_done(op);
1252 	bch2_write_done(cl);
1253 }
1254 
1255 struct bucket_to_lock {
1256 	struct bpos		b;
1257 	unsigned		gen;
1258 	struct nocow_lock_bucket *l;
1259 };
1260 
1261 static void bch2_nocow_write(struct bch_write_op *op)
1262 {
1263 	struct bch_fs *c = op->c;
1264 	struct btree_trans *trans;
1265 	struct btree_iter iter;
1266 	struct bkey_s_c k;
1267 	DARRAY_PREALLOCATED(struct bucket_to_lock, 3) buckets;
1268 	u32 snapshot;
1269 	struct bucket_to_lock *stale_at;
1270 	int stale, ret;
1271 
1272 	if (op->flags & BCH_WRITE_move)
1273 		return;
1274 
1275 	darray_init(&buckets);
1276 	trans = bch2_trans_get(c);
1277 retry:
1278 	bch2_trans_begin(trans);
1279 
1280 	ret = bch2_subvolume_get_snapshot(trans, op->subvol, &snapshot);
1281 	if (unlikely(ret))
1282 		goto err;
1283 
1284 	bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
1285 			     SPOS(op->pos.inode, op->pos.offset, snapshot),
1286 			     BTREE_ITER_slots);
1287 	while (1) {
1288 		struct bio *bio = &op->wbio.bio;
1289 
1290 		buckets.nr = 0;
1291 
1292 		ret = bch2_trans_relock(trans);
1293 		if (ret)
1294 			break;
1295 
1296 		k = bch2_btree_iter_peek_slot(&iter);
1297 		ret = bkey_err(k);
1298 		if (ret)
1299 			break;
1300 
1301 		/* fall back to normal cow write path? */
1302 		if (unlikely(k.k->p.snapshot != snapshot ||
1303 			     !bch2_extent_is_writeable(op, k)))
1304 			break;
1305 
1306 		if (bch2_keylist_realloc(&op->insert_keys,
1307 					 op->inline_keys,
1308 					 ARRAY_SIZE(op->inline_keys),
1309 					 k.k->u64s))
1310 			break;
1311 
1312 		/* Get iorefs before dropping btree locks: */
1313 		struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
1314 		bkey_for_each_ptr(ptrs, ptr) {
1315 			struct bch_dev *ca = bch2_dev_get_ioref(c, ptr->dev, WRITE);
1316 			if (unlikely(!ca))
1317 				goto err_get_ioref;
1318 
1319 			struct bpos b = PTR_BUCKET_POS(ca, ptr);
1320 			struct nocow_lock_bucket *l =
1321 				bucket_nocow_lock(&c->nocow_locks, bucket_to_u64(b));
1322 			prefetch(l);
1323 
1324 			/* XXX allocating memory with btree locks held - rare */
1325 			darray_push_gfp(&buckets, ((struct bucket_to_lock) {
1326 						   .b = b, .gen = ptr->gen, .l = l,
1327 						   }), GFP_KERNEL|__GFP_NOFAIL);
1328 
1329 			if (ptr->unwritten)
1330 				op->flags |= BCH_WRITE_convert_unwritten;
1331 		}
1332 
1333 		/* Unlock before taking nocow locks, doing IO: */
1334 		bkey_reassemble(op->insert_keys.top, k);
1335 		bch2_trans_unlock(trans);
1336 
1337 		bch2_cut_front(op->pos, op->insert_keys.top);
1338 		if (op->flags & BCH_WRITE_convert_unwritten)
1339 			bch2_cut_back(POS(op->pos.inode, op->pos.offset + bio_sectors(bio)), op->insert_keys.top);
1340 
1341 		darray_for_each(buckets, i) {
1342 			struct bch_dev *ca = bch2_dev_have_ref(c, i->b.inode);
1343 
1344 			__bch2_bucket_nocow_lock(&c->nocow_locks, i->l,
1345 						 bucket_to_u64(i->b),
1346 						 BUCKET_NOCOW_LOCK_UPDATE);
1347 
1348 			int gen = bucket_gen_get(ca, i->b.offset);
1349 			stale = gen < 0 ? gen : gen_after(gen, i->gen);
1350 			if (unlikely(stale)) {
1351 				stale_at = i;
1352 				goto err_bucket_stale;
1353 			}
1354 		}
1355 
1356 		bio = &op->wbio.bio;
1357 		if (k.k->p.offset < op->pos.offset + bio_sectors(bio)) {
1358 			bio = bio_split(bio, k.k->p.offset - op->pos.offset,
1359 					GFP_KERNEL, &c->bio_write);
1360 			wbio_init(bio)->put_bio = true;
1361 			bio->bi_opf = op->wbio.bio.bi_opf;
1362 		} else {
1363 			op->flags |= BCH_WRITE_submitted;
1364 		}
1365 
1366 		op->pos.offset += bio_sectors(bio);
1367 		op->written += bio_sectors(bio);
1368 
1369 		bio->bi_end_io	= bch2_write_endio;
1370 		bio->bi_private	= &op->cl;
1371 		bio->bi_opf |= REQ_OP_WRITE;
1372 		closure_get(&op->cl);
1373 
1374 		bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1375 					  op->insert_keys.top, true);
1376 
1377 		bch2_keylist_push(&op->insert_keys);
1378 		if (op->flags & BCH_WRITE_submitted)
1379 			break;
1380 		bch2_btree_iter_advance(&iter);
1381 	}
1382 out:
1383 	bch2_trans_iter_exit(trans, &iter);
1384 err:
1385 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1386 		goto retry;
1387 
1388 	bch2_trans_put(trans);
1389 	darray_exit(&buckets);
1390 
1391 	if (ret) {
1392 		bch2_write_op_error(op, op->pos.offset,
1393 				    "%s(): btree lookup error: %s", __func__, bch2_err_str(ret));
1394 		op->error = ret;
1395 		op->flags |= BCH_WRITE_submitted;
1396 	}
1397 
1398 	/* fallback to cow write path? */
1399 	if (!(op->flags & BCH_WRITE_submitted)) {
1400 		closure_sync(&op->cl);
1401 		__bch2_nocow_write_done(op);
1402 		op->insert_keys.top = op->insert_keys.keys;
1403 	} else if (op->flags & BCH_WRITE_sync) {
1404 		closure_sync(&op->cl);
1405 		bch2_nocow_write_done(&op->cl.work);
1406 	} else {
1407 		/*
1408 		 * XXX
1409 		 * needs to run out of process context because ei_quota_lock is
1410 		 * a mutex
1411 		 */
1412 		continue_at(&op->cl, bch2_nocow_write_done, index_update_wq(op));
1413 	}
1414 	return;
1415 err_get_ioref:
1416 	darray_for_each(buckets, i)
1417 		percpu_ref_put(&bch2_dev_have_ref(c, i->b.inode)->io_ref);
1418 
1419 	/* Fall back to COW path: */
1420 	goto out;
1421 err_bucket_stale:
1422 	darray_for_each(buckets, i) {
1423 		bch2_bucket_nocow_unlock(&c->nocow_locks, i->b, BUCKET_NOCOW_LOCK_UPDATE);
1424 		if (i == stale_at)
1425 			break;
1426 	}
1427 
1428 	struct printbuf buf = PRINTBUF;
1429 	if (bch2_fs_inconsistent_on(stale < 0, c,
1430 				    "pointer to invalid bucket in nocow path on device %llu\n  %s",
1431 				    stale_at->b.inode,
1432 				    (bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
1433 		ret = -BCH_ERR_data_write_invalid_ptr;
1434 	} else {
1435 		/* We can retry this: */
1436 		ret = -BCH_ERR_transaction_restart;
1437 	}
1438 	printbuf_exit(&buf);
1439 
1440 	goto err_get_ioref;
1441 }
1442 
1443 static void __bch2_write(struct bch_write_op *op)
1444 {
1445 	struct bch_fs *c = op->c;
1446 	struct write_point *wp = NULL;
1447 	struct bio *bio = NULL;
1448 	unsigned nofs_flags;
1449 	int ret;
1450 
1451 	nofs_flags = memalloc_nofs_save();
1452 
1453 	if (unlikely(op->opts.nocow && c->opts.nocow_enabled)) {
1454 		bch2_nocow_write(op);
1455 		if (op->flags & BCH_WRITE_submitted)
1456 			goto out_nofs_restore;
1457 	}
1458 again:
1459 	memset(&op->failed, 0, sizeof(op->failed));
1460 
1461 	do {
1462 		struct bkey_i *key_to_write;
1463 		unsigned key_to_write_offset = op->insert_keys.top_p -
1464 			op->insert_keys.keys_p;
1465 
1466 		/* +1 for possible cache device: */
1467 		if (op->open_buckets.nr + op->nr_replicas + 1 >
1468 		    ARRAY_SIZE(op->open_buckets.v))
1469 			break;
1470 
1471 		if (bch2_keylist_realloc(&op->insert_keys,
1472 					op->inline_keys,
1473 					ARRAY_SIZE(op->inline_keys),
1474 					BKEY_EXTENT_U64s_MAX))
1475 			break;
1476 
1477 		/*
1478 		 * The copygc thread is now global, which means it's no longer
1479 		 * freeing up space on specific disks, which means that
1480 		 * allocations for specific disks may hang arbitrarily long:
1481 		 */
1482 		ret = bch2_trans_run(c, lockrestart_do(trans,
1483 			bch2_alloc_sectors_start_trans(trans,
1484 				op->target,
1485 				op->opts.erasure_code && !(op->flags & BCH_WRITE_cached),
1486 				op->write_point,
1487 				&op->devs_have,
1488 				op->nr_replicas,
1489 				op->nr_replicas_required,
1490 				op->watermark,
1491 				op->flags,
1492 				&op->cl, &wp)));
1493 		if (unlikely(ret)) {
1494 			if (bch2_err_matches(ret, BCH_ERR_operation_blocked))
1495 				break;
1496 
1497 			goto err;
1498 		}
1499 
1500 		EBUG_ON(!wp);
1501 
1502 		bch2_open_bucket_get(c, wp, &op->open_buckets);
1503 		ret = bch2_write_extent(op, wp, &bio);
1504 
1505 		bch2_alloc_sectors_done_inlined(c, wp);
1506 err:
1507 		if (ret <= 0) {
1508 			op->flags |= BCH_WRITE_submitted;
1509 
1510 			if (unlikely(ret < 0)) {
1511 				if (!(op->flags & BCH_WRITE_alloc_nowait))
1512 					bch2_write_op_error(op, op->pos.offset,
1513 							    "%s(): %s", __func__, bch2_err_str(ret));
1514 				op->error = ret;
1515 				break;
1516 			}
1517 		}
1518 
1519 		bio->bi_end_io	= bch2_write_endio;
1520 		bio->bi_private	= &op->cl;
1521 		bio->bi_opf |= REQ_OP_WRITE;
1522 
1523 		closure_get(bio->bi_private);
1524 
1525 		key_to_write = (void *) (op->insert_keys.keys_p +
1526 					 key_to_write_offset);
1527 
1528 		bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1529 					  key_to_write, false);
1530 	} while (ret);
1531 
1532 	/*
1533 	 * Sync or no?
1534 	 *
1535 	 * If we're running asynchronously, wne may still want to block
1536 	 * synchronously here if we weren't able to submit all of the IO at
1537 	 * once, as that signals backpressure to the caller.
1538 	 */
1539 	if ((op->flags & BCH_WRITE_sync) ||
1540 	    (!(op->flags & BCH_WRITE_submitted) &&
1541 	     !(op->flags & BCH_WRITE_in_worker))) {
1542 		bch2_wait_on_allocator(c, &op->cl);
1543 
1544 		__bch2_write_index(op);
1545 
1546 		if (!(op->flags & BCH_WRITE_submitted))
1547 			goto again;
1548 		bch2_write_done(&op->cl);
1549 	} else {
1550 		bch2_write_queue(op, wp);
1551 		continue_at(&op->cl, bch2_write_index, NULL);
1552 	}
1553 out_nofs_restore:
1554 	memalloc_nofs_restore(nofs_flags);
1555 }
1556 
1557 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1558 {
1559 	struct bio *bio = &op->wbio.bio;
1560 	struct bvec_iter iter;
1561 	struct bkey_i_inline_data *id;
1562 	unsigned sectors;
1563 	int ret;
1564 
1565 	memset(&op->failed, 0, sizeof(op->failed));
1566 
1567 	op->flags |= BCH_WRITE_wrote_data_inline;
1568 	op->flags |= BCH_WRITE_submitted;
1569 
1570 	bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1571 
1572 	ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1573 				   ARRAY_SIZE(op->inline_keys),
1574 				   BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1575 	if (ret) {
1576 		op->error = ret;
1577 		goto err;
1578 	}
1579 
1580 	sectors = bio_sectors(bio);
1581 	op->pos.offset += sectors;
1582 
1583 	id = bkey_inline_data_init(op->insert_keys.top);
1584 	id->k.p		= op->pos;
1585 	id->k.bversion	= op->version;
1586 	id->k.size	= sectors;
1587 
1588 	iter = bio->bi_iter;
1589 	iter.bi_size = data_len;
1590 	memcpy_from_bio(id->v.data, bio, iter);
1591 
1592 	while (data_len & 7)
1593 		id->v.data[data_len++] = '\0';
1594 	set_bkey_val_bytes(&id->k, data_len);
1595 	bch2_keylist_push(&op->insert_keys);
1596 
1597 	__bch2_write_index(op);
1598 err:
1599 	bch2_write_done(&op->cl);
1600 }
1601 
1602 /**
1603  * bch2_write() - handle a write to a cache device or flash only volume
1604  * @cl:		&bch_write_op->cl
1605  *
1606  * This is the starting point for any data to end up in a cache device; it could
1607  * be from a normal write, or a writeback write, or a write to a flash only
1608  * volume - it's also used by the moving garbage collector to compact data in
1609  * mostly empty buckets.
1610  *
1611  * It first writes the data to the cache, creating a list of keys to be inserted
1612  * (if the data won't fit in a single open bucket, there will be multiple keys);
1613  * after the data is written it calls bch_journal, and after the keys have been
1614  * added to the next journal write they're inserted into the btree.
1615  *
1616  * If op->discard is true, instead of inserting the data it invalidates the
1617  * region of the cache represented by op->bio and op->inode.
1618  */
1619 CLOSURE_CALLBACK(bch2_write)
1620 {
1621 	closure_type(op, struct bch_write_op, cl);
1622 	struct bio *bio = &op->wbio.bio;
1623 	struct bch_fs *c = op->c;
1624 	unsigned data_len;
1625 
1626 	EBUG_ON(op->cl.parent);
1627 	BUG_ON(!op->nr_replicas);
1628 	BUG_ON(!op->write_point.v);
1629 	BUG_ON(bkey_eq(op->pos, POS_MAX));
1630 
1631 	if (op->flags & BCH_WRITE_only_specified_devs)
1632 		op->flags |= BCH_WRITE_alloc_nowait;
1633 
1634 	op->nr_replicas_required = min_t(unsigned, op->nr_replicas_required, op->nr_replicas);
1635 	op->start_time = local_clock();
1636 	bch2_keylist_init(&op->insert_keys, op->inline_keys);
1637 	wbio_init(bio)->put_bio = false;
1638 
1639 	if (unlikely(bio->bi_iter.bi_size & (c->opts.block_size - 1))) {
1640 		bch2_write_op_error(op, op->pos.offset, "misaligned write");
1641 		op->error = -BCH_ERR_data_write_misaligned;
1642 		goto err;
1643 	}
1644 
1645 	if (c->opts.nochanges) {
1646 		op->error = -BCH_ERR_erofs_no_writes;
1647 		goto err;
1648 	}
1649 
1650 	if (!(op->flags & BCH_WRITE_move) &&
1651 	    !bch2_write_ref_tryget(c, BCH_WRITE_REF_write)) {
1652 		op->error = -BCH_ERR_erofs_no_writes;
1653 		goto err;
1654 	}
1655 
1656 	if (!(op->flags & BCH_WRITE_move))
1657 		this_cpu_add(c->counters[BCH_COUNTER_io_write], bio_sectors(bio));
1658 	bch2_increment_clock(c, bio_sectors(bio), WRITE);
1659 
1660 	data_len = min_t(u64, bio->bi_iter.bi_size,
1661 			 op->new_i_size - (op->pos.offset << 9));
1662 
1663 	if (c->opts.inline_data &&
1664 	    data_len <= min(block_bytes(c) / 2, 1024U)) {
1665 		bch2_write_data_inline(op, data_len);
1666 		return;
1667 	}
1668 
1669 	__bch2_write(op);
1670 	return;
1671 err:
1672 	bch2_disk_reservation_put(c, &op->res);
1673 
1674 	closure_debug_destroy(&op->cl);
1675 	if (op->end_io)
1676 		op->end_io(op);
1677 }
1678 
1679 static const char * const bch2_write_flags[] = {
1680 #define x(f)	#f,
1681 	BCH_WRITE_FLAGS()
1682 #undef x
1683 	NULL
1684 };
1685 
1686 void bch2_write_op_to_text(struct printbuf *out, struct bch_write_op *op)
1687 {
1688 	if (!out->nr_tabstops)
1689 		printbuf_tabstop_push(out, 32);
1690 
1691 	prt_printf(out, "pos:\t");
1692 	bch2_bpos_to_text(out, op->pos);
1693 	prt_newline(out);
1694 	printbuf_indent_add(out, 2);
1695 
1696 	prt_printf(out, "started:\t");
1697 	bch2_pr_time_units(out, local_clock() - op->start_time);
1698 	prt_newline(out);
1699 
1700 	prt_printf(out, "flags:\t");
1701 	prt_bitflags(out, bch2_write_flags, op->flags);
1702 	prt_newline(out);
1703 
1704 	prt_printf(out, "nr_replicas:\t%u\n", op->nr_replicas);
1705 	prt_printf(out, "nr_replicas_required:\t%u\n", op->nr_replicas_required);
1706 
1707 	prt_printf(out, "ref:\t%u\n", closure_nr_remaining(&op->cl));
1708 
1709 	printbuf_indent_sub(out, 2);
1710 }
1711 
1712 void bch2_fs_io_write_exit(struct bch_fs *c)
1713 {
1714 	mempool_exit(&c->bio_bounce_pages);
1715 	bioset_exit(&c->replica_set);
1716 	bioset_exit(&c->bio_write);
1717 }
1718 
1719 int bch2_fs_io_write_init(struct bch_fs *c)
1720 {
1721 	if (bioset_init(&c->bio_write,   1, offsetof(struct bch_write_bio, bio), BIOSET_NEED_BVECS) ||
1722 	    bioset_init(&c->replica_set, 4, offsetof(struct bch_write_bio, bio), 0))
1723 		return -BCH_ERR_ENOMEM_bio_write_init;
1724 
1725 	if (mempool_init_page_pool(&c->bio_bounce_pages,
1726 				   max_t(unsigned,
1727 					 c->opts.btree_node_size,
1728 					 c->opts.encoded_extent_max) /
1729 				   PAGE_SIZE, 0))
1730 		return -BCH_ERR_ENOMEM_bio_bounce_pages_init;
1731 
1732 	return 0;
1733 }
1734