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