xref: /linux/fs/bcachefs/disk_accounting.c (revision 566ab427f827b0256d3e8ce0235d088e6a9c28bd)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "bcachefs.h"
4 #include "bcachefs_ioctl.h"
5 #include "btree_cache.h"
6 #include "btree_journal_iter.h"
7 #include "btree_update.h"
8 #include "btree_write_buffer.h"
9 #include "buckets.h"
10 #include "compress.h"
11 #include "disk_accounting.h"
12 #include "error.h"
13 #include "journal_io.h"
14 #include "replicas.h"
15 
16 /*
17  * Notes on disk accounting:
18  *
19  * We have two parallel sets of counters to be concerned with, and both must be
20  * kept in sync.
21  *
22  *  - Persistent/on disk accounting, stored in the accounting btree and updated
23  *    via btree write buffer updates that treat new accounting keys as deltas to
24  *    apply to existing values. But reading from a write buffer btree is
25  *    expensive, so we also have
26  *
27  *  - In memory accounting, where accounting is stored as an array of percpu
28  *    counters, indexed by an eytzinger array of disk acounting keys/bpos (which
29  *    are the same thing, excepting byte swabbing on big endian).
30  *
31  *    Cheap to read, but non persistent.
32  *
33  * Disk accounting updates are generated by transactional triggers; these run as
34  * keys enter and leave the btree, and can compare old and new versions of keys;
35  * the output of these triggers are deltas to the various counters.
36  *
37  * Disk accounting updates are done as btree write buffer updates, where the
38  * counters in the disk accounting key are deltas that will be applied to the
39  * counter in the btree when the key is flushed by the write buffer (or journal
40  * replay).
41  *
42  * To do a disk accounting update:
43  * - initialize a disk_accounting_pos, to specify which counter is being update
44  * - initialize counter deltas, as an array of 1-3 s64s
45  * - call bch2_disk_accounting_mod()
46  *
47  * This queues up the accounting update to be done at transaction commit time.
48  * Underneath, it's a normal btree write buffer update.
49  *
50  * The transaction commit path is responsible for propagating updates to the in
51  * memory counters, with bch2_accounting_mem_mod().
52  *
53  * The commit path also assigns every disk accounting update a unique version
54  * number, based on the journal sequence number and offset within that journal
55  * buffer; this is used by journal replay to determine which updates have been
56  * done.
57  *
58  * The transaction commit path also ensures that replicas entry accounting
59  * updates are properly marked in the superblock (so that we know whether we can
60  * mount without data being unavailable); it will update the superblock if
61  * bch2_accounting_mem_mod() tells it to.
62  */
63 
64 static const char * const disk_accounting_type_strs[] = {
65 #define x(t, n, ...) [n] = #t,
66 	BCH_DISK_ACCOUNTING_TYPES()
67 #undef x
68 	NULL
69 };
70 
71 static inline void accounting_key_init(struct bkey_i *k, struct disk_accounting_pos *pos,
72 				       s64 *d, unsigned nr)
73 {
74 	struct bkey_i_accounting *acc = bkey_accounting_init(k);
75 
76 	acc->k.p = disk_accounting_pos_to_bpos(pos);
77 	set_bkey_val_u64s(&acc->k, sizeof(struct bch_accounting) / sizeof(u64) + nr);
78 
79 	memcpy_u64s_small(acc->v.d, d, nr);
80 }
81 
82 int bch2_disk_accounting_mod(struct btree_trans *trans,
83 			     struct disk_accounting_pos *k,
84 			     s64 *d, unsigned nr, bool gc)
85 {
86 	/* Normalize: */
87 	switch (k->type) {
88 	case BCH_DISK_ACCOUNTING_replicas:
89 		bubble_sort(k->replicas.devs, k->replicas.nr_devs, u8_cmp);
90 		break;
91 	}
92 
93 	BUG_ON(nr > BCH_ACCOUNTING_MAX_COUNTERS);
94 
95 	struct { __BKEY_PADDED(k, BCH_ACCOUNTING_MAX_COUNTERS); } k_i;
96 
97 	accounting_key_init(&k_i.k, k, d, nr);
98 
99 	return likely(!gc)
100 		? bch2_trans_update_buffered(trans, BTREE_ID_accounting, &k_i.k)
101 		: bch2_accounting_mem_add(trans, bkey_i_to_s_c_accounting(&k_i.k), true);
102 }
103 
104 int bch2_mod_dev_cached_sectors(struct btree_trans *trans,
105 				unsigned dev, s64 sectors,
106 				bool gc)
107 {
108 	struct disk_accounting_pos acc = {
109 		.type = BCH_DISK_ACCOUNTING_replicas,
110 	};
111 
112 	bch2_replicas_entry_cached(&acc.replicas, dev);
113 
114 	return bch2_disk_accounting_mod(trans, &acc, &sectors, 1, gc);
115 }
116 
117 static inline bool is_zero(char *start, char *end)
118 {
119 	BUG_ON(start > end);
120 
121 	for (; start < end; start++)
122 		if (*start)
123 			return false;
124 	return true;
125 }
126 
127 #define field_end(p, member)	(((void *) (&p.member)) + sizeof(p.member))
128 
129 int bch2_accounting_validate(struct bch_fs *c, struct bkey_s_c k,
130 			     enum bch_validate_flags flags)
131 {
132 	struct disk_accounting_pos acc_k;
133 	bpos_to_disk_accounting_pos(&acc_k, k.k->p);
134 	void *end = &acc_k + 1;
135 	int ret = 0;
136 
137 	bkey_fsck_err_on(bversion_zero(k.k->bversion),
138 			 c, accounting_key_version_0,
139 			 "accounting key with version=0");
140 
141 	switch (acc_k.type) {
142 	case BCH_DISK_ACCOUNTING_nr_inodes:
143 		end = field_end(acc_k, nr_inodes);
144 		break;
145 	case BCH_DISK_ACCOUNTING_persistent_reserved:
146 		end = field_end(acc_k, persistent_reserved);
147 		break;
148 	case BCH_DISK_ACCOUNTING_replicas:
149 		bkey_fsck_err_on(!acc_k.replicas.nr_devs,
150 				 c, accounting_key_replicas_nr_devs_0,
151 				 "accounting key replicas entry with nr_devs=0");
152 
153 		bkey_fsck_err_on(acc_k.replicas.nr_required > acc_k.replicas.nr_devs ||
154 				 (acc_k.replicas.nr_required > 1 &&
155 				  acc_k.replicas.nr_required == acc_k.replicas.nr_devs),
156 				 c, accounting_key_replicas_nr_required_bad,
157 				 "accounting key replicas entry with bad nr_required");
158 
159 		for (unsigned i = 0; i + 1 < acc_k.replicas.nr_devs; i++)
160 			bkey_fsck_err_on(acc_k.replicas.devs[i] >= acc_k.replicas.devs[i + 1],
161 					 c, accounting_key_replicas_devs_unsorted,
162 					 "accounting key replicas entry with unsorted devs");
163 
164 		end = (void *) &acc_k.replicas + replicas_entry_bytes(&acc_k.replicas);
165 		break;
166 	case BCH_DISK_ACCOUNTING_dev_data_type:
167 		end = field_end(acc_k, dev_data_type);
168 		break;
169 	case BCH_DISK_ACCOUNTING_compression:
170 		end = field_end(acc_k, compression);
171 		break;
172 	case BCH_DISK_ACCOUNTING_snapshot:
173 		end = field_end(acc_k, snapshot);
174 		break;
175 	case BCH_DISK_ACCOUNTING_btree:
176 		end = field_end(acc_k, btree);
177 		break;
178 	case BCH_DISK_ACCOUNTING_rebalance_work:
179 		end = field_end(acc_k, rebalance_work);
180 		break;
181 	}
182 
183 	bkey_fsck_err_on(!is_zero(end, (void *) (&acc_k + 1)),
184 			 c, accounting_key_junk_at_end,
185 			 "junk at end of accounting key");
186 fsck_err:
187 	return ret;
188 }
189 
190 void bch2_accounting_key_to_text(struct printbuf *out, struct disk_accounting_pos *k)
191 {
192 	if (k->type >= BCH_DISK_ACCOUNTING_TYPE_NR) {
193 		prt_printf(out, "unknown type %u", k->type);
194 		return;
195 	}
196 
197 	prt_str(out, disk_accounting_type_strs[k->type]);
198 	prt_str(out, " ");
199 
200 	switch (k->type) {
201 	case BCH_DISK_ACCOUNTING_nr_inodes:
202 		break;
203 	case BCH_DISK_ACCOUNTING_persistent_reserved:
204 		prt_printf(out, "replicas=%u", k->persistent_reserved.nr_replicas);
205 		break;
206 	case BCH_DISK_ACCOUNTING_replicas:
207 		bch2_replicas_entry_to_text(out, &k->replicas);
208 		break;
209 	case BCH_DISK_ACCOUNTING_dev_data_type:
210 		prt_printf(out, "dev=%u data_type=", k->dev_data_type.dev);
211 		bch2_prt_data_type(out, k->dev_data_type.data_type);
212 		break;
213 	case BCH_DISK_ACCOUNTING_compression:
214 		bch2_prt_compression_type(out, k->compression.type);
215 		break;
216 	case BCH_DISK_ACCOUNTING_snapshot:
217 		prt_printf(out, "id=%u", k->snapshot.id);
218 		break;
219 	case BCH_DISK_ACCOUNTING_btree:
220 		prt_printf(out, "btree=%s", bch2_btree_id_str(k->btree.id));
221 		break;
222 	}
223 }
224 
225 void bch2_accounting_to_text(struct printbuf *out, struct bch_fs *c, struct bkey_s_c k)
226 {
227 	struct bkey_s_c_accounting acc = bkey_s_c_to_accounting(k);
228 	struct disk_accounting_pos acc_k;
229 	bpos_to_disk_accounting_pos(&acc_k, k.k->p);
230 
231 	bch2_accounting_key_to_text(out, &acc_k);
232 
233 	for (unsigned i = 0; i < bch2_accounting_counters(k.k); i++)
234 		prt_printf(out, " %lli", acc.v->d[i]);
235 }
236 
237 void bch2_accounting_swab(struct bkey_s k)
238 {
239 	for (u64 *p = (u64 *) k.v;
240 	     p < (u64 *) bkey_val_end(k);
241 	     p++)
242 		*p = swab64(*p);
243 }
244 
245 static inline bool accounting_to_replicas(struct bch_replicas_entry_v1 *r, struct bpos p)
246 {
247 	struct disk_accounting_pos acc_k;
248 	bpos_to_disk_accounting_pos(&acc_k, p);
249 
250 	switch (acc_k.type) {
251 	case BCH_DISK_ACCOUNTING_replicas:
252 		unsafe_memcpy(r, &acc_k.replicas,
253 			      replicas_entry_bytes(&acc_k.replicas),
254 			      "variable length struct");
255 		return true;
256 	default:
257 		return false;
258 	}
259 }
260 
261 static int bch2_accounting_update_sb_one(struct bch_fs *c, struct bpos p)
262 {
263 	struct bch_replicas_padded r;
264 	return accounting_to_replicas(&r.e, p)
265 		? bch2_mark_replicas(c, &r.e)
266 		: 0;
267 }
268 
269 /*
270  * Ensure accounting keys being updated are present in the superblock, when
271  * applicable (i.e. replicas updates)
272  */
273 int bch2_accounting_update_sb(struct btree_trans *trans)
274 {
275 	for (struct jset_entry *i = trans->journal_entries;
276 	     i != (void *) ((u64 *) trans->journal_entries + trans->journal_entries_u64s);
277 	     i = vstruct_next(i))
278 		if (jset_entry_is_key(i) && i->start->k.type == KEY_TYPE_accounting) {
279 			int ret = bch2_accounting_update_sb_one(trans->c, i->start->k.p);
280 			if (ret)
281 				return ret;
282 		}
283 
284 	return 0;
285 }
286 
287 static int __bch2_accounting_mem_insert(struct bch_fs *c, struct bkey_s_c_accounting a)
288 {
289 	struct bch_accounting_mem *acc = &c->accounting;
290 
291 	/* raced with another insert, already present: */
292 	if (eytzinger0_find(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]),
293 			    accounting_pos_cmp, &a.k->p) < acc->k.nr)
294 		return 0;
295 
296 	struct accounting_mem_entry n = {
297 		.pos		= a.k->p,
298 		.bversion	= a.k->bversion,
299 		.nr_counters	= bch2_accounting_counters(a.k),
300 		.v[0]		= __alloc_percpu_gfp(n.nr_counters * sizeof(u64),
301 						     sizeof(u64), GFP_KERNEL),
302 	};
303 
304 	if (!n.v[0])
305 		goto err;
306 
307 	if (acc->gc_running) {
308 		n.v[1] = __alloc_percpu_gfp(n.nr_counters * sizeof(u64),
309 					    sizeof(u64), GFP_KERNEL);
310 		if (!n.v[1])
311 			goto err;
312 	}
313 
314 	if (darray_push(&acc->k, n))
315 		goto err;
316 
317 	eytzinger0_sort(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]),
318 			accounting_pos_cmp, NULL);
319 	return 0;
320 err:
321 	free_percpu(n.v[1]);
322 	free_percpu(n.v[0]);
323 	return -BCH_ERR_ENOMEM_disk_accounting;
324 }
325 
326 int bch2_accounting_mem_insert(struct bch_fs *c, struct bkey_s_c_accounting a,
327 			       enum bch_accounting_mode mode)
328 {
329 	struct bch_replicas_padded r;
330 
331 	if (mode != BCH_ACCOUNTING_read &&
332 	    accounting_to_replicas(&r.e, a.k->p) &&
333 	    !bch2_replicas_marked_locked(c, &r.e))
334 		return -BCH_ERR_btree_insert_need_mark_replicas;
335 
336 	percpu_up_read(&c->mark_lock);
337 	percpu_down_write(&c->mark_lock);
338 	int ret = __bch2_accounting_mem_insert(c, a);
339 	percpu_up_write(&c->mark_lock);
340 	percpu_down_read(&c->mark_lock);
341 	return ret;
342 }
343 
344 static bool accounting_mem_entry_is_zero(struct accounting_mem_entry *e)
345 {
346 	for (unsigned i = 0; i < e->nr_counters; i++)
347 		if (percpu_u64_get(e->v[0] + i) ||
348 		    (e->v[1] &&
349 		     percpu_u64_get(e->v[1] + i)))
350 			return false;
351 	return true;
352 }
353 
354 void bch2_accounting_mem_gc(struct bch_fs *c)
355 {
356 	struct bch_accounting_mem *acc = &c->accounting;
357 
358 	percpu_down_write(&c->mark_lock);
359 	struct accounting_mem_entry *dst = acc->k.data;
360 
361 	darray_for_each(acc->k, src) {
362 		if (accounting_mem_entry_is_zero(src)) {
363 			free_percpu(src->v[0]);
364 			free_percpu(src->v[1]);
365 		} else {
366 			*dst++ = *src;
367 		}
368 	}
369 
370 	acc->k.nr = dst - acc->k.data;
371 	eytzinger0_sort(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]),
372 			accounting_pos_cmp, NULL);
373 	percpu_up_write(&c->mark_lock);
374 }
375 
376 /*
377  * Read out accounting keys for replicas entries, as an array of
378  * bch_replicas_usage entries.
379  *
380  * Note: this may be deprecated/removed at smoe point in the future and replaced
381  * with something more general, it exists to support the ioctl used by the
382  * 'bcachefs fs usage' command.
383  */
384 int bch2_fs_replicas_usage_read(struct bch_fs *c, darray_char *usage)
385 {
386 	struct bch_accounting_mem *acc = &c->accounting;
387 	int ret = 0;
388 
389 	darray_init(usage);
390 
391 	percpu_down_read(&c->mark_lock);
392 	darray_for_each(acc->k, i) {
393 		struct {
394 			struct bch_replicas_usage r;
395 			u8 pad[BCH_BKEY_PTRS_MAX];
396 		} u;
397 
398 		if (!accounting_to_replicas(&u.r.r, i->pos))
399 			continue;
400 
401 		u64 sectors;
402 		bch2_accounting_mem_read_counters(acc, i - acc->k.data, &sectors, 1, false);
403 		u.r.sectors = sectors;
404 
405 		ret = darray_make_room(usage, replicas_usage_bytes(&u.r));
406 		if (ret)
407 			break;
408 
409 		memcpy(&darray_top(*usage), &u.r, replicas_usage_bytes(&u.r));
410 		usage->nr += replicas_usage_bytes(&u.r);
411 	}
412 	percpu_up_read(&c->mark_lock);
413 
414 	if (ret)
415 		darray_exit(usage);
416 	return ret;
417 }
418 
419 int bch2_fs_accounting_read(struct bch_fs *c, darray_char *out_buf, unsigned accounting_types_mask)
420 {
421 
422 	struct bch_accounting_mem *acc = &c->accounting;
423 	int ret = 0;
424 
425 	darray_init(out_buf);
426 
427 	percpu_down_read(&c->mark_lock);
428 	darray_for_each(acc->k, i) {
429 		struct disk_accounting_pos a_p;
430 		bpos_to_disk_accounting_pos(&a_p, i->pos);
431 
432 		if (!(accounting_types_mask & BIT(a_p.type)))
433 			continue;
434 
435 		ret = darray_make_room(out_buf, sizeof(struct bkey_i_accounting) +
436 				       sizeof(u64) * i->nr_counters);
437 		if (ret)
438 			break;
439 
440 		struct bkey_i_accounting *a_out =
441 			bkey_accounting_init((void *) &darray_top(*out_buf));
442 		set_bkey_val_u64s(&a_out->k, i->nr_counters);
443 		a_out->k.p = i->pos;
444 		bch2_accounting_mem_read_counters(acc, i - acc->k.data,
445 						  a_out->v.d, i->nr_counters, false);
446 
447 		if (!bch2_accounting_key_is_zero(accounting_i_to_s_c(a_out)))
448 			out_buf->nr += bkey_bytes(&a_out->k);
449 	}
450 
451 	percpu_up_read(&c->mark_lock);
452 
453 	if (ret)
454 		darray_exit(out_buf);
455 	return ret;
456 }
457 
458 void bch2_fs_accounting_to_text(struct printbuf *out, struct bch_fs *c)
459 {
460 	struct bch_accounting_mem *acc = &c->accounting;
461 
462 	percpu_down_read(&c->mark_lock);
463 	out->atomic++;
464 
465 	eytzinger0_for_each(i, acc->k.nr) {
466 		struct disk_accounting_pos acc_k;
467 		bpos_to_disk_accounting_pos(&acc_k, acc->k.data[i].pos);
468 
469 		bch2_accounting_key_to_text(out, &acc_k);
470 
471 		u64 v[BCH_ACCOUNTING_MAX_COUNTERS];
472 		bch2_accounting_mem_read_counters(acc, i, v, ARRAY_SIZE(v), false);
473 
474 		prt_str(out, ":");
475 		for (unsigned j = 0; j < acc->k.data[i].nr_counters; j++)
476 			prt_printf(out, " %llu", v[j]);
477 		prt_newline(out);
478 	}
479 
480 	--out->atomic;
481 	percpu_up_read(&c->mark_lock);
482 }
483 
484 static void bch2_accounting_free_counters(struct bch_accounting_mem *acc, bool gc)
485 {
486 	darray_for_each(acc->k, e) {
487 		free_percpu(e->v[gc]);
488 		e->v[gc] = NULL;
489 	}
490 }
491 
492 int bch2_gc_accounting_start(struct bch_fs *c)
493 {
494 	struct bch_accounting_mem *acc = &c->accounting;
495 	int ret = 0;
496 
497 	percpu_down_write(&c->mark_lock);
498 	darray_for_each(acc->k, e) {
499 		e->v[1] = __alloc_percpu_gfp(e->nr_counters * sizeof(u64),
500 					     sizeof(u64), GFP_KERNEL);
501 		if (!e->v[1]) {
502 			bch2_accounting_free_counters(acc, true);
503 			ret = -BCH_ERR_ENOMEM_disk_accounting;
504 			break;
505 		}
506 	}
507 
508 	acc->gc_running = !ret;
509 	percpu_up_write(&c->mark_lock);
510 
511 	return ret;
512 }
513 
514 int bch2_gc_accounting_done(struct bch_fs *c)
515 {
516 	struct bch_accounting_mem *acc = &c->accounting;
517 	struct btree_trans *trans = bch2_trans_get(c);
518 	struct printbuf buf = PRINTBUF;
519 	struct bpos pos = POS_MIN;
520 	int ret = 0;
521 
522 	percpu_down_write(&c->mark_lock);
523 	while (1) {
524 		unsigned idx = eytzinger0_find_ge(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]),
525 						  accounting_pos_cmp, &pos);
526 
527 		if (idx >= acc->k.nr)
528 			break;
529 
530 		struct accounting_mem_entry *e = acc->k.data + idx;
531 		pos = bpos_successor(e->pos);
532 
533 		struct disk_accounting_pos acc_k;
534 		bpos_to_disk_accounting_pos(&acc_k, e->pos);
535 
536 		if (acc_k.type >= BCH_DISK_ACCOUNTING_TYPE_NR)
537 			continue;
538 
539 		u64 src_v[BCH_ACCOUNTING_MAX_COUNTERS];
540 		u64 dst_v[BCH_ACCOUNTING_MAX_COUNTERS];
541 
542 		unsigned nr = e->nr_counters;
543 		bch2_accounting_mem_read_counters(acc, idx, dst_v, nr, false);
544 		bch2_accounting_mem_read_counters(acc, idx, src_v, nr, true);
545 
546 		if (memcmp(dst_v, src_v, nr * sizeof(u64))) {
547 			printbuf_reset(&buf);
548 			prt_str(&buf, "accounting mismatch for ");
549 			bch2_accounting_key_to_text(&buf, &acc_k);
550 
551 			prt_str(&buf, ": got");
552 			for (unsigned j = 0; j < nr; j++)
553 				prt_printf(&buf, " %llu", dst_v[j]);
554 
555 			prt_str(&buf, " should be");
556 			for (unsigned j = 0; j < nr; j++)
557 				prt_printf(&buf, " %llu", src_v[j]);
558 
559 			for (unsigned j = 0; j < nr; j++)
560 				src_v[j] -= dst_v[j];
561 
562 			if (fsck_err(trans, accounting_mismatch, "%s", buf.buf)) {
563 				percpu_up_write(&c->mark_lock);
564 				ret = commit_do(trans, NULL, NULL, 0,
565 						bch2_disk_accounting_mod(trans, &acc_k, src_v, nr, false));
566 				percpu_down_write(&c->mark_lock);
567 				if (ret)
568 					goto err;
569 
570 				if (!test_bit(BCH_FS_may_go_rw, &c->flags)) {
571 					memset(&trans->fs_usage_delta, 0, sizeof(trans->fs_usage_delta));
572 					struct { __BKEY_PADDED(k, BCH_ACCOUNTING_MAX_COUNTERS); } k_i;
573 
574 					accounting_key_init(&k_i.k, &acc_k, src_v, nr);
575 					bch2_accounting_mem_mod_locked(trans,
576 								bkey_i_to_s_c_accounting(&k_i.k),
577 								BCH_ACCOUNTING_normal);
578 
579 					preempt_disable();
580 					struct bch_fs_usage_base *dst = this_cpu_ptr(c->usage);
581 					struct bch_fs_usage_base *src = &trans->fs_usage_delta;
582 					acc_u64s((u64 *) dst, (u64 *) src, sizeof(*src) / sizeof(u64));
583 					preempt_enable();
584 				}
585 			}
586 		}
587 	}
588 err:
589 fsck_err:
590 	percpu_up_write(&c->mark_lock);
591 	printbuf_exit(&buf);
592 	bch2_trans_put(trans);
593 	bch_err_fn(c, ret);
594 	return ret;
595 }
596 
597 static int accounting_read_key(struct btree_trans *trans, struct bkey_s_c k)
598 {
599 	struct bch_fs *c = trans->c;
600 
601 	if (k.k->type != KEY_TYPE_accounting)
602 		return 0;
603 
604 	percpu_down_read(&c->mark_lock);
605 	int ret = bch2_accounting_mem_mod_locked(trans, bkey_s_c_to_accounting(k),
606 						 BCH_ACCOUNTING_read);
607 	percpu_up_read(&c->mark_lock);
608 	return ret;
609 }
610 
611 /*
612  * At startup time, initialize the in memory accounting from the btree (and
613  * journal)
614  */
615 int bch2_accounting_read(struct bch_fs *c)
616 {
617 	struct bch_accounting_mem *acc = &c->accounting;
618 	struct btree_trans *trans = bch2_trans_get(c);
619 	struct printbuf buf = PRINTBUF;
620 
621 	int ret = for_each_btree_key(trans, iter,
622 				BTREE_ID_accounting, POS_MIN,
623 				BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, ({
624 			struct bkey u;
625 			struct bkey_s_c k = bch2_btree_path_peek_slot_exact(btree_iter_path(trans, &iter), &u);
626 			accounting_read_key(trans, k);
627 		}));
628 	if (ret)
629 		goto err;
630 
631 	struct journal_keys *keys = &c->journal_keys;
632 	struct journal_key *dst = keys->data;
633 	move_gap(keys, keys->nr);
634 
635 	darray_for_each(*keys, i) {
636 		if (i->k->k.type == KEY_TYPE_accounting) {
637 			struct bkey_s_c k = bkey_i_to_s_c(i->k);
638 			unsigned idx = eytzinger0_find(acc->k.data, acc->k.nr,
639 						sizeof(acc->k.data[0]),
640 						accounting_pos_cmp, &k.k->p);
641 
642 			bool applied = idx < acc->k.nr &&
643 				bversion_cmp(acc->k.data[idx].bversion, k.k->bversion) >= 0;
644 
645 			if (applied)
646 				continue;
647 
648 			if (i + 1 < &darray_top(*keys) &&
649 			    i[1].k->k.type == KEY_TYPE_accounting &&
650 			    !journal_key_cmp(i, i + 1)) {
651 				WARN_ON(bversion_cmp(i[0].k->k.bversion, i[1].k->k.bversion) >= 0);
652 
653 				i[1].journal_seq = i[0].journal_seq;
654 
655 				bch2_accounting_accumulate(bkey_i_to_accounting(i[1].k),
656 							   bkey_s_c_to_accounting(k));
657 				continue;
658 			}
659 
660 			ret = accounting_read_key(trans, k);
661 			if (ret)
662 				goto err;
663 		}
664 
665 		*dst++ = *i;
666 	}
667 	keys->gap = keys->nr = dst - keys->data;
668 
669 	percpu_down_read(&c->mark_lock);
670 	for (unsigned i = 0; i < acc->k.nr; i++) {
671 		u64 v[BCH_ACCOUNTING_MAX_COUNTERS];
672 		bch2_accounting_mem_read_counters(acc, i, v, ARRAY_SIZE(v), false);
673 
674 		if (bch2_is_zero(v, sizeof(v[0]) * acc->k.data[i].nr_counters))
675 			continue;
676 
677 		struct bch_replicas_padded r;
678 		if (!accounting_to_replicas(&r.e, acc->k.data[i].pos))
679 			continue;
680 
681 		/*
682 		 * If the replicas entry is invalid it'll get cleaned up by
683 		 * check_allocations:
684 		 */
685 		if (bch2_replicas_entry_validate(&r.e, c, &buf))
686 			continue;
687 
688 		struct disk_accounting_pos k;
689 		bpos_to_disk_accounting_pos(&k, acc->k.data[i].pos);
690 
691 		if (fsck_err_on(!bch2_replicas_marked_locked(c, &r.e),
692 				trans, accounting_replicas_not_marked,
693 				"accounting not marked in superblock replicas\n  %s",
694 				(printbuf_reset(&buf),
695 				 bch2_accounting_key_to_text(&buf, &k),
696 				 buf.buf))) {
697 			/*
698 			 * We're not RW yet and still single threaded, dropping
699 			 * and retaking lock is ok:
700 			 */
701 			percpu_up_read(&c->mark_lock);
702 			ret = bch2_mark_replicas(c, &r.e);
703 			if (ret)
704 				goto fsck_err;
705 			percpu_down_read(&c->mark_lock);
706 		}
707 	}
708 
709 	preempt_disable();
710 	struct bch_fs_usage_base *usage = this_cpu_ptr(c->usage);
711 
712 	for (unsigned i = 0; i < acc->k.nr; i++) {
713 		struct disk_accounting_pos k;
714 		bpos_to_disk_accounting_pos(&k, acc->k.data[i].pos);
715 
716 		u64 v[BCH_ACCOUNTING_MAX_COUNTERS];
717 		bch2_accounting_mem_read_counters(acc, i, v, ARRAY_SIZE(v), false);
718 
719 		switch (k.type) {
720 		case BCH_DISK_ACCOUNTING_persistent_reserved:
721 			usage->reserved += v[0] * k.persistent_reserved.nr_replicas;
722 			break;
723 		case BCH_DISK_ACCOUNTING_replicas:
724 			fs_usage_data_type_to_base(usage, k.replicas.data_type, v[0]);
725 			break;
726 		case BCH_DISK_ACCOUNTING_dev_data_type:
727 			rcu_read_lock();
728 			struct bch_dev *ca = bch2_dev_rcu(c, k.dev_data_type.dev);
729 			if (ca) {
730 				struct bch_dev_usage_type __percpu *d = &ca->usage->d[k.dev_data_type.data_type];
731 				percpu_u64_set(&d->buckets,	v[0]);
732 				percpu_u64_set(&d->sectors,	v[1]);
733 				percpu_u64_set(&d->fragmented,	v[2]);
734 
735 				if (k.dev_data_type.data_type == BCH_DATA_sb ||
736 				    k.dev_data_type.data_type == BCH_DATA_journal)
737 					usage->hidden += v[0] * ca->mi.bucket_size;
738 			}
739 			rcu_read_unlock();
740 			break;
741 		}
742 	}
743 	preempt_enable();
744 fsck_err:
745 	percpu_up_read(&c->mark_lock);
746 err:
747 	printbuf_exit(&buf);
748 	bch2_trans_put(trans);
749 	bch_err_fn(c, ret);
750 	return ret;
751 }
752 
753 int bch2_dev_usage_remove(struct bch_fs *c, unsigned dev)
754 {
755 	return bch2_trans_run(c,
756 		bch2_btree_write_buffer_flush_sync(trans) ?:
757 		for_each_btree_key_commit(trans, iter, BTREE_ID_accounting, POS_MIN,
758 				BTREE_ITER_all_snapshots, k, NULL, NULL, 0, ({
759 			struct disk_accounting_pos acc;
760 			bpos_to_disk_accounting_pos(&acc, k.k->p);
761 
762 			acc.type == BCH_DISK_ACCOUNTING_dev_data_type &&
763 			acc.dev_data_type.dev == dev
764 				? bch2_btree_bit_mod_buffered(trans, BTREE_ID_accounting, k.k->p, 0)
765 				: 0;
766 		})) ?:
767 		bch2_btree_write_buffer_flush_sync(trans));
768 }
769 
770 int bch2_dev_usage_init(struct bch_dev *ca, bool gc)
771 {
772 	struct bch_fs *c = ca->fs;
773 	struct disk_accounting_pos acc = {
774 		.type = BCH_DISK_ACCOUNTING_dev_data_type,
775 		.dev_data_type.dev = ca->dev_idx,
776 		.dev_data_type.data_type = BCH_DATA_free,
777 	};
778 	u64 v[3] = { ca->mi.nbuckets - ca->mi.first_bucket, 0, 0 };
779 
780 	int ret = bch2_trans_do(c, NULL, NULL, 0,
781 			bch2_disk_accounting_mod(trans, &acc, v, ARRAY_SIZE(v), gc));
782 	bch_err_fn(c, ret);
783 	return ret;
784 }
785 
786 void bch2_verify_accounting_clean(struct bch_fs *c)
787 {
788 	bool mismatch = false;
789 	struct bch_fs_usage_base base = {}, base_inmem = {};
790 
791 	bch2_trans_run(c,
792 		for_each_btree_key(trans, iter,
793 				   BTREE_ID_accounting, POS_MIN,
794 				   BTREE_ITER_all_snapshots, k, ({
795 			u64 v[BCH_ACCOUNTING_MAX_COUNTERS];
796 			struct bkey_s_c_accounting a = bkey_s_c_to_accounting(k);
797 			unsigned nr = bch2_accounting_counters(k.k);
798 
799 			struct disk_accounting_pos acc_k;
800 			bpos_to_disk_accounting_pos(&acc_k, k.k->p);
801 
802 			if (acc_k.type >= BCH_DISK_ACCOUNTING_TYPE_NR)
803 				continue;
804 
805 			if (acc_k.type == BCH_DISK_ACCOUNTING_inum)
806 				continue;
807 
808 			bch2_accounting_mem_read(c, k.k->p, v, nr);
809 
810 			if (memcmp(a.v->d, v, nr * sizeof(u64))) {
811 				struct printbuf buf = PRINTBUF;
812 
813 				bch2_bkey_val_to_text(&buf, c, k);
814 				prt_str(&buf, " !=");
815 				for (unsigned j = 0; j < nr; j++)
816 					prt_printf(&buf, " %llu", v[j]);
817 
818 				pr_err("%s", buf.buf);
819 				printbuf_exit(&buf);
820 				mismatch = true;
821 			}
822 
823 			switch (acc_k.type) {
824 			case BCH_DISK_ACCOUNTING_persistent_reserved:
825 				base.reserved += acc_k.persistent_reserved.nr_replicas * a.v->d[0];
826 				break;
827 			case BCH_DISK_ACCOUNTING_replicas:
828 				fs_usage_data_type_to_base(&base, acc_k.replicas.data_type, a.v->d[0]);
829 				break;
830 			case BCH_DISK_ACCOUNTING_dev_data_type: {
831 				rcu_read_lock();
832 				struct bch_dev *ca = bch2_dev_rcu(c, acc_k.dev_data_type.dev);
833 				if (!ca) {
834 					rcu_read_unlock();
835 					continue;
836 				}
837 
838 				v[0] = percpu_u64_get(&ca->usage->d[acc_k.dev_data_type.data_type].buckets);
839 				v[1] = percpu_u64_get(&ca->usage->d[acc_k.dev_data_type.data_type].sectors);
840 				v[2] = percpu_u64_get(&ca->usage->d[acc_k.dev_data_type.data_type].fragmented);
841 				rcu_read_unlock();
842 
843 				if (memcmp(a.v->d, v, 3 * sizeof(u64))) {
844 					struct printbuf buf = PRINTBUF;
845 
846 					bch2_bkey_val_to_text(&buf, c, k);
847 					prt_str(&buf, " in mem");
848 					for (unsigned j = 0; j < nr; j++)
849 						prt_printf(&buf, " %llu", v[j]);
850 
851 					pr_err("dev accounting mismatch: %s", buf.buf);
852 					printbuf_exit(&buf);
853 					mismatch = true;
854 				}
855 			}
856 			}
857 
858 			0;
859 		})));
860 
861 	acc_u64s_percpu(&base_inmem.hidden, &c->usage->hidden, sizeof(base_inmem) / sizeof(u64));
862 
863 #define check(x)										\
864 	if (base.x != base_inmem.x) {								\
865 		pr_err("fs_usage_base.%s mismatch: %llu != %llu", #x, base.x, base_inmem.x);	\
866 		mismatch = true;								\
867 	}
868 
869 	//check(hidden);
870 	check(btree);
871 	check(data);
872 	check(cached);
873 	check(reserved);
874 	check(nr_inodes);
875 
876 	WARN_ON(mismatch);
877 }
878 
879 void bch2_accounting_gc_free(struct bch_fs *c)
880 {
881 	lockdep_assert_held(&c->mark_lock);
882 
883 	struct bch_accounting_mem *acc = &c->accounting;
884 
885 	bch2_accounting_free_counters(acc, true);
886 	acc->gc_running = false;
887 }
888 
889 void bch2_fs_accounting_exit(struct bch_fs *c)
890 {
891 	struct bch_accounting_mem *acc = &c->accounting;
892 
893 	bch2_accounting_free_counters(acc, false);
894 	darray_exit(&acc->k);
895 }
896