xref: /linux/fs/bcachefs/data_update.c (revision 06a130e42a5bfc84795464bff023bff4c16f58c5)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "alloc_foreground.h"
5 #include "bkey_buf.h"
6 #include "btree_update.h"
7 #include "buckets.h"
8 #include "compress.h"
9 #include "data_update.h"
10 #include "disk_groups.h"
11 #include "ec.h"
12 #include "error.h"
13 #include "extents.h"
14 #include "io_write.h"
15 #include "keylist.h"
16 #include "move.h"
17 #include "nocow_locking.h"
18 #include "rebalance.h"
19 #include "snapshot.h"
20 #include "subvolume.h"
21 #include "trace.h"
22 
23 static void bkey_put_dev_refs(struct bch_fs *c, struct bkey_s_c k)
24 {
25 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
26 
27 	bkey_for_each_ptr(ptrs, ptr)
28 		bch2_dev_put(bch2_dev_have_ref(c, ptr->dev));
29 }
30 
31 static bool bkey_get_dev_refs(struct bch_fs *c, struct bkey_s_c k)
32 {
33 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
34 
35 	bkey_for_each_ptr(ptrs, ptr) {
36 		if (!bch2_dev_tryget(c, ptr->dev)) {
37 			bkey_for_each_ptr(ptrs, ptr2) {
38 				if (ptr2 == ptr)
39 					break;
40 				bch2_dev_put(bch2_dev_have_ref(c, ptr2->dev));
41 			}
42 			return false;
43 		}
44 	}
45 	return true;
46 }
47 
48 static void bkey_nocow_unlock(struct bch_fs *c, struct bkey_s_c k)
49 {
50 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
51 
52 	bkey_for_each_ptr(ptrs, ptr) {
53 		struct bch_dev *ca = bch2_dev_have_ref(c, ptr->dev);
54 		struct bpos bucket = PTR_BUCKET_POS(ca, ptr);
55 
56 		bch2_bucket_nocow_unlock(&c->nocow_locks, bucket, 0);
57 	}
58 }
59 
60 static bool bkey_nocow_lock(struct bch_fs *c, struct moving_context *ctxt, struct bkey_s_c k)
61 {
62 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
63 
64 	bkey_for_each_ptr(ptrs, ptr) {
65 		struct bch_dev *ca = bch2_dev_have_ref(c, ptr->dev);
66 		struct bpos bucket = PTR_BUCKET_POS(ca, ptr);
67 
68 		if (ctxt) {
69 			bool locked;
70 
71 			move_ctxt_wait_event(ctxt,
72 				(locked = bch2_bucket_nocow_trylock(&c->nocow_locks, bucket, 0)) ||
73 				list_empty(&ctxt->ios));
74 
75 			if (!locked)
76 				bch2_bucket_nocow_lock(&c->nocow_locks, bucket, 0);
77 		} else {
78 			if (!bch2_bucket_nocow_trylock(&c->nocow_locks, bucket, 0)) {
79 				bkey_for_each_ptr(ptrs, ptr2) {
80 					if (ptr2 == ptr)
81 						break;
82 
83 					ca = bch2_dev_have_ref(c, ptr2->dev);
84 					bucket = PTR_BUCKET_POS(ca, ptr2);
85 					bch2_bucket_nocow_unlock(&c->nocow_locks, bucket, 0);
86 				}
87 				return false;
88 			}
89 		}
90 	}
91 	return true;
92 }
93 
94 static void trace_move_extent_finish2(struct bch_fs *c, struct bkey_s_c k)
95 {
96 	if (trace_move_extent_finish_enabled()) {
97 		struct printbuf buf = PRINTBUF;
98 
99 		bch2_bkey_val_to_text(&buf, c, k);
100 		trace_move_extent_finish(c, buf.buf);
101 		printbuf_exit(&buf);
102 	}
103 }
104 
105 static void trace_move_extent_fail2(struct data_update *m,
106 			 struct bkey_s_c new,
107 			 struct bkey_s_c wrote,
108 			 struct bkey_i *insert,
109 			 const char *msg)
110 {
111 	struct bch_fs *c = m->op.c;
112 	struct bkey_s_c old = bkey_i_to_s_c(m->k.k);
113 	const union bch_extent_entry *entry;
114 	struct bch_extent_ptr *ptr;
115 	struct extent_ptr_decoded p;
116 	struct printbuf buf = PRINTBUF;
117 	unsigned i, rewrites_found = 0;
118 
119 	if (!trace_move_extent_fail_enabled())
120 		return;
121 
122 	prt_str(&buf, msg);
123 
124 	if (insert) {
125 		i = 0;
126 		bkey_for_each_ptr_decode(old.k, bch2_bkey_ptrs_c(old), p, entry) {
127 			if (((1U << i) & m->data_opts.rewrite_ptrs) &&
128 			    (ptr = bch2_extent_has_ptr(old, p, bkey_i_to_s(insert))) &&
129 			    !ptr->cached)
130 				rewrites_found |= 1U << i;
131 			i++;
132 		}
133 	}
134 
135 	prt_printf(&buf, "\nrewrite ptrs:   %u%u%u%u",
136 		   (m->data_opts.rewrite_ptrs & (1 << 0)) != 0,
137 		   (m->data_opts.rewrite_ptrs & (1 << 1)) != 0,
138 		   (m->data_opts.rewrite_ptrs & (1 << 2)) != 0,
139 		   (m->data_opts.rewrite_ptrs & (1 << 3)) != 0);
140 
141 	prt_printf(&buf, "\nrewrites found: %u%u%u%u",
142 		   (rewrites_found & (1 << 0)) != 0,
143 		   (rewrites_found & (1 << 1)) != 0,
144 		   (rewrites_found & (1 << 2)) != 0,
145 		   (rewrites_found & (1 << 3)) != 0);
146 
147 	prt_str(&buf, "\nold:    ");
148 	bch2_bkey_val_to_text(&buf, c, old);
149 
150 	prt_str(&buf, "\nnew:    ");
151 	bch2_bkey_val_to_text(&buf, c, new);
152 
153 	prt_str(&buf, "\nwrote:  ");
154 	bch2_bkey_val_to_text(&buf, c, wrote);
155 
156 	if (insert) {
157 		prt_str(&buf, "\ninsert: ");
158 		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(insert));
159 	}
160 
161 	trace_move_extent_fail(c, buf.buf);
162 	printbuf_exit(&buf);
163 }
164 
165 static int __bch2_data_update_index_update(struct btree_trans *trans,
166 					   struct bch_write_op *op)
167 {
168 	struct bch_fs *c = op->c;
169 	struct btree_iter iter;
170 	struct data_update *m =
171 		container_of(op, struct data_update, op);
172 	struct keylist *keys = &op->insert_keys;
173 	struct bkey_buf _new, _insert;
174 	int ret = 0;
175 
176 	bch2_bkey_buf_init(&_new);
177 	bch2_bkey_buf_init(&_insert);
178 	bch2_bkey_buf_realloc(&_insert, c, U8_MAX);
179 
180 	bch2_trans_iter_init(trans, &iter, m->btree_id,
181 			     bkey_start_pos(&bch2_keylist_front(keys)->k),
182 			     BTREE_ITER_slots|BTREE_ITER_intent);
183 
184 	while (1) {
185 		struct bkey_s_c k;
186 		struct bkey_s_c old = bkey_i_to_s_c(m->k.k);
187 		struct bkey_i *insert = NULL;
188 		struct bkey_i_extent *new;
189 		const union bch_extent_entry *entry_c;
190 		union bch_extent_entry *entry;
191 		struct extent_ptr_decoded p;
192 		struct bch_extent_ptr *ptr;
193 		const struct bch_extent_ptr *ptr_c;
194 		struct bpos next_pos;
195 		bool should_check_enospc;
196 		s64 i_sectors_delta = 0, disk_sectors_delta = 0;
197 		unsigned rewrites_found = 0, durability, i;
198 
199 		bch2_trans_begin(trans);
200 
201 		k = bch2_btree_iter_peek_slot(&iter);
202 		ret = bkey_err(k);
203 		if (ret)
204 			goto err;
205 
206 		new = bkey_i_to_extent(bch2_keylist_front(keys));
207 
208 		if (!bch2_extents_match(k, old)) {
209 			trace_move_extent_fail2(m, k, bkey_i_to_s_c(&new->k_i),
210 						NULL, "no match:");
211 			goto nowork;
212 		}
213 
214 		bkey_reassemble(_insert.k, k);
215 		insert = _insert.k;
216 
217 		bch2_bkey_buf_copy(&_new, c, bch2_keylist_front(keys));
218 		new = bkey_i_to_extent(_new.k);
219 		bch2_cut_front(iter.pos, &new->k_i);
220 
221 		bch2_cut_front(iter.pos,	insert);
222 		bch2_cut_back(new->k.p,		insert);
223 		bch2_cut_back(insert->k.p,	&new->k_i);
224 
225 		/*
226 		 * @old: extent that we read from
227 		 * @insert: key that we're going to update, initialized from
228 		 * extent currently in btree - same as @old unless we raced with
229 		 * other updates
230 		 * @new: extent with new pointers that we'll be adding to @insert
231 		 *
232 		 * Fist, drop rewrite_ptrs from @new:
233 		 */
234 		i = 0;
235 		bkey_for_each_ptr_decode(old.k, bch2_bkey_ptrs_c(old), p, entry_c) {
236 			if (((1U << i) & m->data_opts.rewrite_ptrs) &&
237 			    (ptr = bch2_extent_has_ptr(old, p, bkey_i_to_s(insert))) &&
238 			    !ptr->cached) {
239 				bch2_extent_ptr_set_cached(bkey_i_to_s(insert), ptr);
240 				rewrites_found |= 1U << i;
241 			}
242 			i++;
243 		}
244 
245 		if (m->data_opts.rewrite_ptrs &&
246 		    !rewrites_found &&
247 		    bch2_bkey_durability(c, k) >= m->op.opts.data_replicas) {
248 			trace_move_extent_fail2(m, k, bkey_i_to_s_c(&new->k_i), insert, "no rewrites found:");
249 			goto nowork;
250 		}
251 
252 		/*
253 		 * A replica that we just wrote might conflict with a replica
254 		 * that we want to keep, due to racing with another move:
255 		 */
256 restart_drop_conflicting_replicas:
257 		extent_for_each_ptr(extent_i_to_s(new), ptr)
258 			if ((ptr_c = bch2_bkey_has_device_c(bkey_i_to_s_c(insert), ptr->dev)) &&
259 			    !ptr_c->cached) {
260 				bch2_bkey_drop_ptr_noerror(bkey_i_to_s(&new->k_i), ptr);
261 				goto restart_drop_conflicting_replicas;
262 			}
263 
264 		if (!bkey_val_u64s(&new->k)) {
265 			trace_move_extent_fail2(m, k, bkey_i_to_s_c(&new->k_i), insert, "new replicas conflicted:");
266 			goto nowork;
267 		}
268 
269 		/* Now, drop pointers that conflict with what we just wrote: */
270 		extent_for_each_ptr_decode(extent_i_to_s(new), p, entry)
271 			if ((ptr = bch2_bkey_has_device(bkey_i_to_s(insert), p.ptr.dev)))
272 				bch2_bkey_drop_ptr_noerror(bkey_i_to_s(insert), ptr);
273 
274 		durability = bch2_bkey_durability(c, bkey_i_to_s_c(insert)) +
275 			bch2_bkey_durability(c, bkey_i_to_s_c(&new->k_i));
276 
277 		/* Now, drop excess replicas: */
278 		rcu_read_lock();
279 restart_drop_extra_replicas:
280 		bkey_for_each_ptr_decode(old.k, bch2_bkey_ptrs(bkey_i_to_s(insert)), p, entry) {
281 			unsigned ptr_durability = bch2_extent_ptr_durability(c, &p);
282 
283 			if (!p.ptr.cached &&
284 			    durability - ptr_durability >= m->op.opts.data_replicas) {
285 				durability -= ptr_durability;
286 
287 				bch2_extent_ptr_set_cached(bkey_i_to_s(insert), &entry->ptr);
288 				goto restart_drop_extra_replicas;
289 			}
290 		}
291 		rcu_read_unlock();
292 
293 		/* Finally, add the pointers we just wrote: */
294 		extent_for_each_ptr_decode(extent_i_to_s(new), p, entry)
295 			bch2_extent_ptr_decoded_append(insert, &p);
296 
297 		bch2_bkey_narrow_crcs(insert, (struct bch_extent_crc_unpacked) { 0 });
298 		bch2_extent_normalize(c, bkey_i_to_s(insert));
299 
300 		ret = bch2_sum_sector_overwrites(trans, &iter, insert,
301 						 &should_check_enospc,
302 						 &i_sectors_delta,
303 						 &disk_sectors_delta);
304 		if (ret)
305 			goto err;
306 
307 		if (disk_sectors_delta > (s64) op->res.sectors) {
308 			ret = bch2_disk_reservation_add(c, &op->res,
309 						disk_sectors_delta - op->res.sectors,
310 						!should_check_enospc
311 						? BCH_DISK_RESERVATION_NOFAIL : 0);
312 			if (ret)
313 				goto out;
314 		}
315 
316 		next_pos = insert->k.p;
317 
318 		/*
319 		 * Check for nonce offset inconsistency:
320 		 * This is debug code - we've been seeing this bug rarely, and
321 		 * it's been hard to reproduce, so this should give us some more
322 		 * information when it does occur:
323 		 */
324 		int invalid = bch2_bkey_validate(c, bkey_i_to_s_c(insert), __btree_node_type(0, m->btree_id),
325 						 BCH_VALIDATE_commit);
326 		if (invalid) {
327 			struct printbuf buf = PRINTBUF;
328 
329 			prt_str(&buf, "about to insert invalid key in data update path");
330 			prt_str(&buf, "\nold: ");
331 			bch2_bkey_val_to_text(&buf, c, old);
332 			prt_str(&buf, "\nk:   ");
333 			bch2_bkey_val_to_text(&buf, c, k);
334 			prt_str(&buf, "\nnew: ");
335 			bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(insert));
336 
337 			bch2_print_string_as_lines(KERN_ERR, buf.buf);
338 			printbuf_exit(&buf);
339 
340 			bch2_fatal_error(c);
341 			ret = -EIO;
342 			goto out;
343 		}
344 
345 		if (trace_data_update_enabled()) {
346 			struct printbuf buf = PRINTBUF;
347 
348 			prt_str(&buf, "\nold: ");
349 			bch2_bkey_val_to_text(&buf, c, old);
350 			prt_str(&buf, "\nk:   ");
351 			bch2_bkey_val_to_text(&buf, c, k);
352 			prt_str(&buf, "\nnew: ");
353 			bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(insert));
354 
355 			trace_data_update(c, buf.buf);
356 			printbuf_exit(&buf);
357 		}
358 
359 		ret =   bch2_insert_snapshot_whiteouts(trans, m->btree_id,
360 						k.k->p, bkey_start_pos(&insert->k)) ?:
361 			bch2_insert_snapshot_whiteouts(trans, m->btree_id,
362 						k.k->p, insert->k.p) ?:
363 			bch2_bkey_set_needs_rebalance(c, insert, &op->opts) ?:
364 			bch2_trans_update(trans, &iter, insert,
365 				BTREE_UPDATE_internal_snapshot_node) ?:
366 			bch2_trans_commit(trans, &op->res,
367 				NULL,
368 				BCH_TRANS_COMMIT_no_check_rw|
369 				BCH_TRANS_COMMIT_no_enospc|
370 				m->data_opts.btree_insert_flags);
371 		if (!ret) {
372 			bch2_btree_iter_set_pos(&iter, next_pos);
373 
374 			this_cpu_add(c->counters[BCH_COUNTER_move_extent_finish], new->k.size);
375 			trace_move_extent_finish2(c, bkey_i_to_s_c(&new->k_i));
376 		}
377 err:
378 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
379 			ret = 0;
380 		if (ret)
381 			break;
382 next:
383 		while (bkey_ge(iter.pos, bch2_keylist_front(keys)->k.p)) {
384 			bch2_keylist_pop_front(keys);
385 			if (bch2_keylist_empty(keys))
386 				goto out;
387 		}
388 		continue;
389 nowork:
390 		if (m->stats) {
391 			BUG_ON(k.k->p.offset <= iter.pos.offset);
392 			atomic64_inc(&m->stats->keys_raced);
393 			atomic64_add(k.k->p.offset - iter.pos.offset,
394 				     &m->stats->sectors_raced);
395 		}
396 
397 		count_event(c, move_extent_fail);
398 
399 		bch2_btree_iter_advance(&iter);
400 		goto next;
401 	}
402 out:
403 	bch2_trans_iter_exit(trans, &iter);
404 	bch2_bkey_buf_exit(&_insert, c);
405 	bch2_bkey_buf_exit(&_new, c);
406 	BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart));
407 	return ret;
408 }
409 
410 int bch2_data_update_index_update(struct bch_write_op *op)
411 {
412 	return bch2_trans_run(op->c, __bch2_data_update_index_update(trans, op));
413 }
414 
415 void bch2_data_update_read_done(struct data_update *m,
416 				struct bch_extent_crc_unpacked crc)
417 {
418 	/* write bio must own pages: */
419 	BUG_ON(!m->op.wbio.bio.bi_vcnt);
420 
421 	m->op.crc = crc;
422 	m->op.wbio.bio.bi_iter.bi_size = crc.compressed_size << 9;
423 
424 	closure_call(&m->op.cl, bch2_write, NULL, NULL);
425 }
426 
427 void bch2_data_update_exit(struct data_update *update)
428 {
429 	struct bch_fs *c = update->op.c;
430 	struct bkey_s_c k = bkey_i_to_s_c(update->k.k);
431 
432 	if (c->opts.nocow_enabled)
433 		bkey_nocow_unlock(c, k);
434 	bkey_put_dev_refs(c, k);
435 	bch2_bkey_buf_exit(&update->k, c);
436 	bch2_disk_reservation_put(c, &update->op.res);
437 	bch2_bio_free_pages_pool(c, &update->op.wbio.bio);
438 }
439 
440 static void bch2_update_unwritten_extent(struct btree_trans *trans,
441 				  struct data_update *update)
442 {
443 	struct bch_fs *c = update->op.c;
444 	struct bio *bio = &update->op.wbio.bio;
445 	struct bkey_i_extent *e;
446 	struct write_point *wp;
447 	struct closure cl;
448 	struct btree_iter iter;
449 	struct bkey_s_c k;
450 	int ret;
451 
452 	closure_init_stack(&cl);
453 	bch2_keylist_init(&update->op.insert_keys, update->op.inline_keys);
454 
455 	while (bio_sectors(bio)) {
456 		unsigned sectors = bio_sectors(bio);
457 
458 		bch2_trans_begin(trans);
459 
460 		bch2_trans_iter_init(trans, &iter, update->btree_id, update->op.pos,
461 				     BTREE_ITER_slots);
462 		ret = lockrestart_do(trans, ({
463 			k = bch2_btree_iter_peek_slot(&iter);
464 			bkey_err(k);
465 		}));
466 		bch2_trans_iter_exit(trans, &iter);
467 
468 		if (ret || !bch2_extents_match(k, bkey_i_to_s_c(update->k.k)))
469 			break;
470 
471 		e = bkey_extent_init(update->op.insert_keys.top);
472 		e->k.p = update->op.pos;
473 
474 		ret = bch2_alloc_sectors_start_trans(trans,
475 				update->op.target,
476 				false,
477 				update->op.write_point,
478 				&update->op.devs_have,
479 				update->op.nr_replicas,
480 				update->op.nr_replicas,
481 				update->op.watermark,
482 				0, &cl, &wp);
483 		if (bch2_err_matches(ret, BCH_ERR_operation_blocked)) {
484 			bch2_trans_unlock(trans);
485 			closure_sync(&cl);
486 			continue;
487 		}
488 
489 		bch_err_fn_ratelimited(c, ret);
490 
491 		if (ret)
492 			return;
493 
494 		sectors = min(sectors, wp->sectors_free);
495 
496 		bch2_key_resize(&e->k, sectors);
497 
498 		bch2_open_bucket_get(c, wp, &update->op.open_buckets);
499 		bch2_alloc_sectors_append_ptrs(c, wp, &e->k_i, sectors, false);
500 		bch2_alloc_sectors_done(c, wp);
501 
502 		bio_advance(bio, sectors << 9);
503 		update->op.pos.offset += sectors;
504 
505 		extent_for_each_ptr(extent_i_to_s(e), ptr)
506 			ptr->unwritten = true;
507 		bch2_keylist_push(&update->op.insert_keys);
508 
509 		ret = __bch2_data_update_index_update(trans, &update->op);
510 
511 		bch2_open_buckets_put(c, &update->op.open_buckets);
512 
513 		if (ret)
514 			break;
515 	}
516 
517 	if (closure_nr_remaining(&cl) != 1) {
518 		bch2_trans_unlock(trans);
519 		closure_sync(&cl);
520 	}
521 }
522 
523 void bch2_data_update_opts_to_text(struct printbuf *out, struct bch_fs *c,
524 				   struct bch_io_opts *io_opts,
525 				   struct data_update_opts *data_opts)
526 {
527 	printbuf_tabstop_push(out, 20);
528 	prt_str(out, "rewrite ptrs:\t");
529 	bch2_prt_u64_base2(out, data_opts->rewrite_ptrs);
530 	prt_newline(out);
531 
532 	prt_str(out, "kill ptrs:\t");
533 	bch2_prt_u64_base2(out, data_opts->kill_ptrs);
534 	prt_newline(out);
535 
536 	prt_str(out, "target:\t");
537 	bch2_target_to_text(out, c, data_opts->target);
538 	prt_newline(out);
539 
540 	prt_str(out, "compression:\t");
541 	bch2_compression_opt_to_text(out, background_compression(*io_opts));
542 	prt_newline(out);
543 
544 	prt_str(out, "opts.replicas:\t");
545 	prt_u64(out, io_opts->data_replicas);
546 
547 	prt_str(out, "extra replicas:\t");
548 	prt_u64(out, data_opts->extra_replicas);
549 }
550 
551 void bch2_data_update_to_text(struct printbuf *out, struct data_update *m)
552 {
553 	bch2_bkey_val_to_text(out, m->op.c, bkey_i_to_s_c(m->k.k));
554 	prt_newline(out);
555 	bch2_data_update_opts_to_text(out, m->op.c, &m->op.opts, &m->data_opts);
556 }
557 
558 int bch2_extent_drop_ptrs(struct btree_trans *trans,
559 			  struct btree_iter *iter,
560 			  struct bkey_s_c k,
561 			  struct data_update_opts data_opts)
562 {
563 	struct bch_fs *c = trans->c;
564 	struct bkey_i *n;
565 	int ret;
566 
567 	n = bch2_bkey_make_mut_noupdate(trans, k);
568 	ret = PTR_ERR_OR_ZERO(n);
569 	if (ret)
570 		return ret;
571 
572 	while (data_opts.kill_ptrs) {
573 		unsigned i = 0, drop = __fls(data_opts.kill_ptrs);
574 
575 		bch2_bkey_drop_ptrs_noerror(bkey_i_to_s(n), ptr, i++ == drop);
576 		data_opts.kill_ptrs ^= 1U << drop;
577 	}
578 
579 	/*
580 	 * If the new extent no longer has any pointers, bch2_extent_normalize()
581 	 * will do the appropriate thing with it (turning it into a
582 	 * KEY_TYPE_error key, or just a discard if it was a cached extent)
583 	 */
584 	bch2_extent_normalize(c, bkey_i_to_s(n));
585 
586 	/*
587 	 * Since we're not inserting through an extent iterator
588 	 * (BTREE_ITER_all_snapshots iterators aren't extent iterators),
589 	 * we aren't using the extent overwrite path to delete, we're
590 	 * just using the normal key deletion path:
591 	 */
592 	if (bkey_deleted(&n->k) && !(iter->flags & BTREE_ITER_is_extents))
593 		n->k.size = 0;
594 
595 	return bch2_trans_relock(trans) ?:
596 		bch2_trans_update(trans, iter, n, BTREE_UPDATE_internal_snapshot_node) ?:
597 		bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc);
598 }
599 
600 int bch2_data_update_init(struct btree_trans *trans,
601 			  struct btree_iter *iter,
602 			  struct moving_context *ctxt,
603 			  struct data_update *m,
604 			  struct write_point_specifier wp,
605 			  struct bch_io_opts io_opts,
606 			  struct data_update_opts data_opts,
607 			  enum btree_id btree_id,
608 			  struct bkey_s_c k)
609 {
610 	struct bch_fs *c = trans->c;
611 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
612 	const union bch_extent_entry *entry;
613 	struct extent_ptr_decoded p;
614 	unsigned i, reserve_sectors = k.k->size * data_opts.extra_replicas;
615 	int ret = 0;
616 
617 	/*
618 	 * fs is corrupt  we have a key for a snapshot node that doesn't exist,
619 	 * and we have to check for this because we go rw before repairing the
620 	 * snapshots table - just skip it, we can move it later.
621 	 */
622 	if (unlikely(k.k->p.snapshot && !bch2_snapshot_equiv(c, k.k->p.snapshot)))
623 		return -BCH_ERR_data_update_done;
624 
625 	if (!bkey_get_dev_refs(c, k))
626 		return -BCH_ERR_data_update_done;
627 
628 	if (c->opts.nocow_enabled &&
629 	    !bkey_nocow_lock(c, ctxt, k)) {
630 		bkey_put_dev_refs(c, k);
631 		return -BCH_ERR_nocow_lock_blocked;
632 	}
633 
634 	bch2_bkey_buf_init(&m->k);
635 	bch2_bkey_buf_reassemble(&m->k, c, k);
636 	m->btree_id	= btree_id;
637 	m->data_opts	= data_opts;
638 	m->ctxt		= ctxt;
639 	m->stats	= ctxt ? ctxt->stats : NULL;
640 
641 	bch2_write_op_init(&m->op, c, io_opts);
642 	m->op.pos	= bkey_start_pos(k.k);
643 	m->op.version	= k.k->bversion;
644 	m->op.target	= data_opts.target;
645 	m->op.write_point = wp;
646 	m->op.nr_replicas = 0;
647 	m->op.flags	|= BCH_WRITE_PAGES_STABLE|
648 		BCH_WRITE_PAGES_OWNED|
649 		BCH_WRITE_DATA_ENCODED|
650 		BCH_WRITE_MOVE|
651 		m->data_opts.write_flags;
652 	m->op.compression_opt	= background_compression(io_opts);
653 	m->op.watermark		= m->data_opts.btree_insert_flags & BCH_WATERMARK_MASK;
654 
655 	unsigned durability_have = 0, durability_removing = 0;
656 
657 	i = 0;
658 	bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
659 		if (!p.ptr.cached) {
660 			rcu_read_lock();
661 			if (BIT(i) & m->data_opts.rewrite_ptrs) {
662 				if (crc_is_compressed(p.crc))
663 					reserve_sectors += k.k->size;
664 
665 				m->op.nr_replicas += bch2_extent_ptr_desired_durability(c, &p);
666 				durability_removing += bch2_extent_ptr_desired_durability(c, &p);
667 			} else if (!(BIT(i) & m->data_opts.kill_ptrs)) {
668 				bch2_dev_list_add_dev(&m->op.devs_have, p.ptr.dev);
669 				durability_have += bch2_extent_ptr_durability(c, &p);
670 			}
671 			rcu_read_unlock();
672 		}
673 
674 		/*
675 		 * op->csum_type is normally initialized from the fs/file's
676 		 * current options - but if an extent is encrypted, we require
677 		 * that it stays encrypted:
678 		 */
679 		if (bch2_csum_type_is_encryption(p.crc.csum_type)) {
680 			m->op.nonce	= p.crc.nonce + p.crc.offset;
681 			m->op.csum_type = p.crc.csum_type;
682 		}
683 
684 		if (p.crc.compression_type == BCH_COMPRESSION_TYPE_incompressible)
685 			m->op.incompressible = true;
686 
687 		i++;
688 	}
689 
690 	unsigned durability_required = max(0, (int) (io_opts.data_replicas - durability_have));
691 
692 	/*
693 	 * If current extent durability is less than io_opts.data_replicas,
694 	 * we're not trying to rereplicate the extent up to data_replicas here -
695 	 * unless extra_replicas was specified
696 	 *
697 	 * Increasing replication is an explicit operation triggered by
698 	 * rereplicate, currently, so that users don't get an unexpected -ENOSPC
699 	 */
700 	m->op.nr_replicas = min(durability_removing, durability_required) +
701 		m->data_opts.extra_replicas;
702 
703 	/*
704 	 * If device(s) were set to durability=0 after data was written to them
705 	 * we can end up with a duribilty=0 extent, and the normal algorithm
706 	 * that tries not to increase durability doesn't work:
707 	 */
708 	if (!(durability_have + durability_removing))
709 		m->op.nr_replicas = max((unsigned) m->op.nr_replicas, 1);
710 
711 	m->op.nr_replicas_required = m->op.nr_replicas;
712 
713 	/*
714 	 * It might turn out that we don't need any new replicas, if the
715 	 * replicas or durability settings have been changed since the extent
716 	 * was written:
717 	 */
718 	if (!m->op.nr_replicas) {
719 		m->data_opts.kill_ptrs |= m->data_opts.rewrite_ptrs;
720 		m->data_opts.rewrite_ptrs = 0;
721 		/* if iter == NULL, it's just a promote */
722 		if (iter)
723 			ret = bch2_extent_drop_ptrs(trans, iter, k, m->data_opts);
724 		goto out;
725 	}
726 
727 	if (reserve_sectors) {
728 		ret = bch2_disk_reservation_add(c, &m->op.res, reserve_sectors,
729 				m->data_opts.extra_replicas
730 				? 0
731 				: BCH_DISK_RESERVATION_NOFAIL);
732 		if (ret)
733 			goto out;
734 	}
735 
736 	if (bkey_extent_is_unwritten(k)) {
737 		bch2_update_unwritten_extent(trans, m);
738 		goto out;
739 	}
740 
741 	return 0;
742 out:
743 	bch2_data_update_exit(m);
744 	return ret ?: -BCH_ERR_data_update_done;
745 }
746 
747 void bch2_data_update_opts_normalize(struct bkey_s_c k, struct data_update_opts *opts)
748 {
749 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
750 	unsigned i = 0;
751 
752 	bkey_for_each_ptr(ptrs, ptr) {
753 		if ((opts->rewrite_ptrs & (1U << i)) && ptr->cached) {
754 			opts->kill_ptrs |= 1U << i;
755 			opts->rewrite_ptrs ^= 1U << i;
756 		}
757 
758 		i++;
759 	}
760 }
761