xref: /linux/fs/bcachefs/disk_accounting.c (revision 1a5efc9e13f357abc396dbf445b25d08914c8060)
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_invalid(struct bch_fs *c, struct bkey_s_c k,
130 			    enum bch_validate_flags flags,
131 			    struct printbuf *err)
132 {
133 	struct disk_accounting_pos acc_k;
134 	bpos_to_disk_accounting_pos(&acc_k, k.k->p);
135 	void *end = &acc_k + 1;
136 	int ret = 0;
137 
138 	switch (acc_k.type) {
139 	case BCH_DISK_ACCOUNTING_nr_inodes:
140 		end = field_end(acc_k, nr_inodes);
141 		break;
142 	case BCH_DISK_ACCOUNTING_persistent_reserved:
143 		end = field_end(acc_k, persistent_reserved);
144 		break;
145 	case BCH_DISK_ACCOUNTING_replicas:
146 		bkey_fsck_err_on(!acc_k.replicas.nr_devs,
147 				 c, err, accounting_key_replicas_nr_devs_0,
148 				 "accounting key replicas entry with nr_devs=0");
149 
150 		bkey_fsck_err_on(acc_k.replicas.nr_required > acc_k.replicas.nr_devs ||
151 				 (acc_k.replicas.nr_required > 1 &&
152 				  acc_k.replicas.nr_required == acc_k.replicas.nr_devs),
153 				 c, err, accounting_key_replicas_nr_required_bad,
154 				 "accounting key replicas entry with bad nr_required");
155 
156 		for (unsigned i = 0; i + 1 < acc_k.replicas.nr_devs; i++)
157 			bkey_fsck_err_on(acc_k.replicas.devs[i] > acc_k.replicas.devs[i + 1],
158 					 c, err, accounting_key_replicas_devs_unsorted,
159 					 "accounting key replicas entry with unsorted devs");
160 
161 		end = (void *) &acc_k.replicas + replicas_entry_bytes(&acc_k.replicas);
162 		break;
163 	case BCH_DISK_ACCOUNTING_dev_data_type:
164 		end = field_end(acc_k, dev_data_type);
165 		break;
166 	case BCH_DISK_ACCOUNTING_compression:
167 		end = field_end(acc_k, compression);
168 		break;
169 	case BCH_DISK_ACCOUNTING_snapshot:
170 		end = field_end(acc_k, snapshot);
171 		break;
172 	case BCH_DISK_ACCOUNTING_btree:
173 		end = field_end(acc_k, btree);
174 		break;
175 	case BCH_DISK_ACCOUNTING_rebalance_work:
176 		end = field_end(acc_k, rebalance_work);
177 		break;
178 	}
179 
180 	bkey_fsck_err_on(!is_zero(end, (void *) (&acc_k + 1)),
181 			 c, err, accounting_key_junk_at_end,
182 			 "junk at end of accounting key");
183 fsck_err:
184 	return ret;
185 }
186 
187 void bch2_accounting_key_to_text(struct printbuf *out, struct disk_accounting_pos *k)
188 {
189 	if (k->type >= BCH_DISK_ACCOUNTING_TYPE_NR) {
190 		prt_printf(out, "unknown type %u", k->type);
191 		return;
192 	}
193 
194 	prt_str(out, disk_accounting_type_strs[k->type]);
195 	prt_str(out, " ");
196 
197 	switch (k->type) {
198 	case BCH_DISK_ACCOUNTING_nr_inodes:
199 		break;
200 	case BCH_DISK_ACCOUNTING_persistent_reserved:
201 		prt_printf(out, "replicas=%u", k->persistent_reserved.nr_replicas);
202 		break;
203 	case BCH_DISK_ACCOUNTING_replicas:
204 		bch2_replicas_entry_to_text(out, &k->replicas);
205 		break;
206 	case BCH_DISK_ACCOUNTING_dev_data_type:
207 		prt_printf(out, "dev=%u data_type=", k->dev_data_type.dev);
208 		bch2_prt_data_type(out, k->dev_data_type.data_type);
209 		break;
210 	case BCH_DISK_ACCOUNTING_compression:
211 		bch2_prt_compression_type(out, k->compression.type);
212 		break;
213 	case BCH_DISK_ACCOUNTING_snapshot:
214 		prt_printf(out, "id=%u", k->snapshot.id);
215 		break;
216 	case BCH_DISK_ACCOUNTING_btree:
217 		prt_printf(out, "btree=%s", bch2_btree_id_str(k->btree.id));
218 		break;
219 	}
220 }
221 
222 void bch2_accounting_to_text(struct printbuf *out, struct bch_fs *c, struct bkey_s_c k)
223 {
224 	struct bkey_s_c_accounting acc = bkey_s_c_to_accounting(k);
225 	struct disk_accounting_pos acc_k;
226 	bpos_to_disk_accounting_pos(&acc_k, k.k->p);
227 
228 	bch2_accounting_key_to_text(out, &acc_k);
229 
230 	for (unsigned i = 0; i < bch2_accounting_counters(k.k); i++)
231 		prt_printf(out, " %lli", acc.v->d[i]);
232 }
233 
234 void bch2_accounting_swab(struct bkey_s k)
235 {
236 	for (u64 *p = (u64 *) k.v;
237 	     p < (u64 *) bkey_val_end(k);
238 	     p++)
239 		*p = swab64(*p);
240 }
241 
242 static inline bool accounting_to_replicas(struct bch_replicas_entry_v1 *r, struct bpos p)
243 {
244 	struct disk_accounting_pos acc_k;
245 	bpos_to_disk_accounting_pos(&acc_k, p);
246 
247 	switch (acc_k.type) {
248 	case BCH_DISK_ACCOUNTING_replicas:
249 		unsafe_memcpy(r, &acc_k.replicas,
250 			      replicas_entry_bytes(&acc_k.replicas),
251 			      "variable length struct");
252 		return true;
253 	default:
254 		return false;
255 	}
256 }
257 
258 static int bch2_accounting_update_sb_one(struct bch_fs *c, struct bpos p)
259 {
260 	struct bch_replicas_padded r;
261 	return accounting_to_replicas(&r.e, p)
262 		? bch2_mark_replicas(c, &r.e)
263 		: 0;
264 }
265 
266 /*
267  * Ensure accounting keys being updated are present in the superblock, when
268  * applicable (i.e. replicas updates)
269  */
270 int bch2_accounting_update_sb(struct btree_trans *trans)
271 {
272 	for (struct jset_entry *i = trans->journal_entries;
273 	     i != (void *) ((u64 *) trans->journal_entries + trans->journal_entries_u64s);
274 	     i = vstruct_next(i))
275 		if (jset_entry_is_key(i) && i->start->k.type == KEY_TYPE_accounting) {
276 			int ret = bch2_accounting_update_sb_one(trans->c, i->start->k.p);
277 			if (ret)
278 				return ret;
279 		}
280 
281 	return 0;
282 }
283 
284 static int __bch2_accounting_mem_insert(struct bch_fs *c, struct bkey_s_c_accounting a)
285 {
286 	struct bch_accounting_mem *acc = &c->accounting;
287 
288 	/* raced with another insert, already present: */
289 	if (eytzinger0_find(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]),
290 			    accounting_pos_cmp, &a.k->p) < acc->k.nr)
291 		return 0;
292 
293 	struct accounting_mem_entry n = {
294 		.pos		= a.k->p,
295 		.version	= a.k->version,
296 		.nr_counters	= bch2_accounting_counters(a.k),
297 		.v[0]		= __alloc_percpu_gfp(n.nr_counters * sizeof(u64),
298 						     sizeof(u64), GFP_KERNEL),
299 	};
300 
301 	if (!n.v[0])
302 		goto err;
303 
304 	if (acc->gc_running) {
305 		n.v[1] = __alloc_percpu_gfp(n.nr_counters * sizeof(u64),
306 					    sizeof(u64), GFP_KERNEL);
307 		if (!n.v[1])
308 			goto err;
309 	}
310 
311 	if (darray_push(&acc->k, n))
312 		goto err;
313 
314 	eytzinger0_sort(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]),
315 			accounting_pos_cmp, NULL);
316 	return 0;
317 err:
318 	free_percpu(n.v[1]);
319 	free_percpu(n.v[0]);
320 	return -BCH_ERR_ENOMEM_disk_accounting;
321 }
322 
323 int bch2_accounting_mem_insert(struct bch_fs *c, struct bkey_s_c_accounting a, bool gc)
324 {
325 	struct bch_replicas_padded r;
326 
327 	if (accounting_to_replicas(&r.e, a.k->p) &&
328 	    !bch2_replicas_marked_locked(c, &r.e))
329 		return -BCH_ERR_btree_insert_need_mark_replicas;
330 
331 	percpu_up_read(&c->mark_lock);
332 	percpu_down_write(&c->mark_lock);
333 	int ret = __bch2_accounting_mem_insert(c, a);
334 	percpu_up_write(&c->mark_lock);
335 	percpu_down_read(&c->mark_lock);
336 	return ret;
337 }
338 
339 static bool accounting_mem_entry_is_zero(struct accounting_mem_entry *e)
340 {
341 	for (unsigned i = 0; i < e->nr_counters; i++)
342 		if (percpu_u64_get(e->v[0] + i) ||
343 		    (e->v[1] &&
344 		     percpu_u64_get(e->v[1] + i)))
345 			return false;
346 	return true;
347 }
348 
349 void bch2_accounting_mem_gc(struct bch_fs *c)
350 {
351 	struct bch_accounting_mem *acc = &c->accounting;
352 
353 	percpu_down_write(&c->mark_lock);
354 	struct accounting_mem_entry *dst = acc->k.data;
355 
356 	darray_for_each(acc->k, src) {
357 		if (accounting_mem_entry_is_zero(src)) {
358 			free_percpu(src->v[0]);
359 			free_percpu(src->v[1]);
360 		} else {
361 			*dst++ = *src;
362 		}
363 	}
364 
365 	acc->k.nr = dst - acc->k.data;
366 	eytzinger0_sort(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]),
367 			accounting_pos_cmp, NULL);
368 	percpu_up_write(&c->mark_lock);
369 }
370 
371 /*
372  * Read out accounting keys for replicas entries, as an array of
373  * bch_replicas_usage entries.
374  *
375  * Note: this may be deprecated/removed at smoe point in the future and replaced
376  * with something more general, it exists to support the ioctl used by the
377  * 'bcachefs fs usage' command.
378  */
379 int bch2_fs_replicas_usage_read(struct bch_fs *c, darray_char *usage)
380 {
381 	struct bch_accounting_mem *acc = &c->accounting;
382 	int ret = 0;
383 
384 	darray_init(usage);
385 
386 	percpu_down_read(&c->mark_lock);
387 	darray_for_each(acc->k, i) {
388 		struct {
389 			struct bch_replicas_usage r;
390 			u8 pad[BCH_BKEY_PTRS_MAX];
391 		} u;
392 
393 		if (!accounting_to_replicas(&u.r.r, i->pos))
394 			continue;
395 
396 		u64 sectors;
397 		bch2_accounting_mem_read_counters(acc, i - acc->k.data, &sectors, 1, false);
398 		u.r.sectors = sectors;
399 
400 		ret = darray_make_room(usage, replicas_usage_bytes(&u.r));
401 		if (ret)
402 			break;
403 
404 		memcpy(&darray_top(*usage), &u.r, replicas_usage_bytes(&u.r));
405 		usage->nr += replicas_usage_bytes(&u.r);
406 	}
407 	percpu_up_read(&c->mark_lock);
408 
409 	if (ret)
410 		darray_exit(usage);
411 	return ret;
412 }
413 
414 int bch2_fs_accounting_read(struct bch_fs *c, darray_char *out_buf, unsigned accounting_types_mask)
415 {
416 
417 	struct bch_accounting_mem *acc = &c->accounting;
418 	int ret = 0;
419 
420 	darray_init(out_buf);
421 
422 	percpu_down_read(&c->mark_lock);
423 	darray_for_each(acc->k, i) {
424 		struct disk_accounting_pos a_p;
425 		bpos_to_disk_accounting_pos(&a_p, i->pos);
426 
427 		if (!(accounting_types_mask & BIT(a_p.type)))
428 			continue;
429 
430 		ret = darray_make_room(out_buf, sizeof(struct bkey_i_accounting) +
431 				       sizeof(u64) * i->nr_counters);
432 		if (ret)
433 			break;
434 
435 		struct bkey_i_accounting *a_out =
436 			bkey_accounting_init((void *) &darray_top(*out_buf));
437 		set_bkey_val_u64s(&a_out->k, i->nr_counters);
438 		a_out->k.p = i->pos;
439 		bch2_accounting_mem_read_counters(acc, i - acc->k.data,
440 						  a_out->v.d, i->nr_counters, false);
441 
442 		if (!bch2_accounting_key_is_zero(accounting_i_to_s_c(a_out)))
443 			out_buf->nr += bkey_bytes(&a_out->k);
444 	}
445 
446 	percpu_up_read(&c->mark_lock);
447 
448 	if (ret)
449 		darray_exit(out_buf);
450 	return ret;
451 }
452 
453 void bch2_fs_accounting_to_text(struct printbuf *out, struct bch_fs *c)
454 {
455 	struct bch_accounting_mem *acc = &c->accounting;
456 
457 	percpu_down_read(&c->mark_lock);
458 	out->atomic++;
459 
460 	eytzinger0_for_each(i, acc->k.nr) {
461 		struct disk_accounting_pos acc_k;
462 		bpos_to_disk_accounting_pos(&acc_k, acc->k.data[i].pos);
463 
464 		bch2_accounting_key_to_text(out, &acc_k);
465 
466 		u64 v[BCH_ACCOUNTING_MAX_COUNTERS];
467 		bch2_accounting_mem_read_counters(acc, i, v, ARRAY_SIZE(v), false);
468 
469 		prt_str(out, ":");
470 		for (unsigned j = 0; j < acc->k.data[i].nr_counters; j++)
471 			prt_printf(out, " %llu", v[j]);
472 		prt_newline(out);
473 	}
474 
475 	--out->atomic;
476 	percpu_up_read(&c->mark_lock);
477 }
478 
479 static void bch2_accounting_free_counters(struct bch_accounting_mem *acc, bool gc)
480 {
481 	darray_for_each(acc->k, e) {
482 		free_percpu(e->v[gc]);
483 		e->v[gc] = NULL;
484 	}
485 }
486 
487 int bch2_gc_accounting_start(struct bch_fs *c)
488 {
489 	struct bch_accounting_mem *acc = &c->accounting;
490 	int ret = 0;
491 
492 	percpu_down_write(&c->mark_lock);
493 	darray_for_each(acc->k, e) {
494 		e->v[1] = __alloc_percpu_gfp(e->nr_counters * sizeof(u64),
495 					     sizeof(u64), GFP_KERNEL);
496 		if (!e->v[1]) {
497 			bch2_accounting_free_counters(acc, true);
498 			ret = -BCH_ERR_ENOMEM_disk_accounting;
499 			break;
500 		}
501 	}
502 
503 	acc->gc_running = !ret;
504 	percpu_up_write(&c->mark_lock);
505 
506 	return ret;
507 }
508 
509 int bch2_gc_accounting_done(struct bch_fs *c)
510 {
511 	struct bch_accounting_mem *acc = &c->accounting;
512 	struct btree_trans *trans = bch2_trans_get(c);
513 	struct printbuf buf = PRINTBUF;
514 	struct bpos pos = POS_MIN;
515 	int ret = 0;
516 
517 	percpu_down_write(&c->mark_lock);
518 	while (1) {
519 		unsigned idx = eytzinger0_find_ge(acc->k.data, acc->k.nr, sizeof(acc->k.data[0]),
520 						  accounting_pos_cmp, &pos);
521 
522 		if (idx >= acc->k.nr)
523 			break;
524 
525 		struct accounting_mem_entry *e = acc->k.data + idx;
526 		pos = bpos_successor(e->pos);
527 
528 		struct disk_accounting_pos acc_k;
529 		bpos_to_disk_accounting_pos(&acc_k, e->pos);
530 
531 		u64 src_v[BCH_ACCOUNTING_MAX_COUNTERS];
532 		u64 dst_v[BCH_ACCOUNTING_MAX_COUNTERS];
533 
534 		unsigned nr = e->nr_counters;
535 		bch2_accounting_mem_read_counters(acc, idx, dst_v, nr, false);
536 		bch2_accounting_mem_read_counters(acc, idx, src_v, nr, true);
537 
538 		if (memcmp(dst_v, src_v, nr * sizeof(u64))) {
539 			printbuf_reset(&buf);
540 			prt_str(&buf, "accounting mismatch for ");
541 			bch2_accounting_key_to_text(&buf, &acc_k);
542 
543 			prt_str(&buf, ": got");
544 			for (unsigned j = 0; j < nr; j++)
545 				prt_printf(&buf, " %llu", dst_v[j]);
546 
547 			prt_str(&buf, " should be");
548 			for (unsigned j = 0; j < nr; j++)
549 				prt_printf(&buf, " %llu", src_v[j]);
550 
551 			for (unsigned j = 0; j < nr; j++)
552 				src_v[j] -= dst_v[j];
553 
554 			if (fsck_err(trans, accounting_mismatch, "%s", buf.buf)) {
555 				percpu_up_write(&c->mark_lock);
556 				ret = commit_do(trans, NULL, NULL, 0,
557 						bch2_disk_accounting_mod(trans, &acc_k, src_v, nr, false));
558 				percpu_down_write(&c->mark_lock);
559 				if (ret)
560 					goto err;
561 
562 				if (!test_bit(BCH_FS_may_go_rw, &c->flags)) {
563 					memset(&trans->fs_usage_delta, 0, sizeof(trans->fs_usage_delta));
564 					struct { __BKEY_PADDED(k, BCH_ACCOUNTING_MAX_COUNTERS); } k_i;
565 
566 					accounting_key_init(&k_i.k, &acc_k, src_v, nr);
567 					bch2_accounting_mem_mod_locked(trans, bkey_i_to_s_c_accounting(&k_i.k), false);
568 
569 					preempt_disable();
570 					struct bch_fs_usage_base *dst = this_cpu_ptr(c->usage);
571 					struct bch_fs_usage_base *src = &trans->fs_usage_delta;
572 					acc_u64s((u64 *) dst, (u64 *) src, sizeof(*src) / sizeof(u64));
573 					preempt_enable();
574 				}
575 			}
576 		}
577 	}
578 err:
579 fsck_err:
580 	percpu_up_write(&c->mark_lock);
581 	printbuf_exit(&buf);
582 	bch2_trans_put(trans);
583 	bch_err_fn(c, ret);
584 	return ret;
585 }
586 
587 static int accounting_read_key(struct btree_trans *trans, struct bkey_s_c k)
588 {
589 	struct bch_fs *c = trans->c;
590 	struct printbuf buf = PRINTBUF;
591 
592 	if (k.k->type != KEY_TYPE_accounting)
593 		return 0;
594 
595 	percpu_down_read(&c->mark_lock);
596 	int ret = __bch2_accounting_mem_mod(c, bkey_s_c_to_accounting(k), false);
597 	percpu_up_read(&c->mark_lock);
598 
599 	if (bch2_accounting_key_is_zero(bkey_s_c_to_accounting(k)) &&
600 	    ret == -BCH_ERR_btree_insert_need_mark_replicas)
601 		ret = 0;
602 
603 	struct disk_accounting_pos acc;
604 	bpos_to_disk_accounting_pos(&acc, k.k->p);
605 
606 	if (fsck_err_on(ret == -BCH_ERR_btree_insert_need_mark_replicas,
607 			trans, accounting_replicas_not_marked,
608 			"accounting not marked in superblock replicas\n  %s",
609 			(bch2_accounting_key_to_text(&buf, &acc),
610 			 buf.buf)))
611 		ret = bch2_accounting_update_sb_one(c, k.k->p);
612 fsck_err:
613 	printbuf_exit(&buf);
614 	return ret;
615 }
616 
617 /*
618  * At startup time, initialize the in memory accounting from the btree (and
619  * journal)
620  */
621 int bch2_accounting_read(struct bch_fs *c)
622 {
623 	struct bch_accounting_mem *acc = &c->accounting;
624 	struct btree_trans *trans = bch2_trans_get(c);
625 
626 	int ret = for_each_btree_key(trans, iter,
627 				BTREE_ID_accounting, POS_MIN,
628 				BTREE_ITER_prefetch|BTREE_ITER_all_snapshots, k, ({
629 			struct bkey u;
630 			struct bkey_s_c k = bch2_btree_path_peek_slot_exact(btree_iter_path(trans, &iter), &u);
631 			accounting_read_key(trans, k);
632 		}));
633 	if (ret)
634 		goto err;
635 
636 	struct journal_keys *keys = &c->journal_keys;
637 	struct journal_key *dst = keys->data;
638 	move_gap(keys, keys->nr);
639 
640 	darray_for_each(*keys, i) {
641 		if (i->k->k.type == KEY_TYPE_accounting) {
642 			struct bkey_s_c k = bkey_i_to_s_c(i->k);
643 			unsigned idx = eytzinger0_find(acc->k.data, acc->k.nr,
644 						sizeof(acc->k.data[0]),
645 						accounting_pos_cmp, &k.k->p);
646 
647 			bool applied = idx < acc->k.nr &&
648 				bversion_cmp(acc->k.data[idx].version, k.k->version) >= 0;
649 
650 			if (applied)
651 				continue;
652 
653 			if (i + 1 < &darray_top(*keys) &&
654 			    i[1].k->k.type == KEY_TYPE_accounting &&
655 			    !journal_key_cmp(i, i + 1)) {
656 				BUG_ON(bversion_cmp(i[0].k->k.version, i[1].k->k.version) >= 0);
657 
658 				i[1].journal_seq = i[0].journal_seq;
659 
660 				bch2_accounting_accumulate(bkey_i_to_accounting(i[1].k),
661 							   bkey_s_c_to_accounting(k));
662 				continue;
663 			}
664 
665 			ret = accounting_read_key(trans, k);
666 			if (ret)
667 				goto err;
668 		}
669 
670 		*dst++ = *i;
671 	}
672 	keys->gap = keys->nr = dst - keys->data;
673 
674 	percpu_down_read(&c->mark_lock);
675 	preempt_disable();
676 	struct bch_fs_usage_base *usage = this_cpu_ptr(c->usage);
677 
678 	for (unsigned i = 0; i < acc->k.nr; i++) {
679 		struct disk_accounting_pos k;
680 		bpos_to_disk_accounting_pos(&k, acc->k.data[i].pos);
681 
682 		u64 v[BCH_ACCOUNTING_MAX_COUNTERS];
683 		bch2_accounting_mem_read_counters(acc, i, v, ARRAY_SIZE(v), false);
684 
685 		switch (k.type) {
686 		case BCH_DISK_ACCOUNTING_persistent_reserved:
687 			usage->reserved += v[0] * k.persistent_reserved.nr_replicas;
688 			break;
689 		case BCH_DISK_ACCOUNTING_replicas:
690 			fs_usage_data_type_to_base(usage, k.replicas.data_type, v[0]);
691 			break;
692 		case BCH_DISK_ACCOUNTING_dev_data_type:
693 			rcu_read_lock();
694 			struct bch_dev *ca = bch2_dev_rcu(c, k.dev_data_type.dev);
695 			if (ca) {
696 				struct bch_dev_usage_type __percpu *d = &ca->usage->d[k.dev_data_type.data_type];
697 				percpu_u64_set(&d->buckets,	v[0]);
698 				percpu_u64_set(&d->sectors,	v[1]);
699 				percpu_u64_set(&d->fragmented,	v[2]);
700 
701 				if (k.dev_data_type.data_type == BCH_DATA_sb ||
702 				    k.dev_data_type.data_type == BCH_DATA_journal)
703 					usage->hidden += v[0] * ca->mi.bucket_size;
704 			}
705 			rcu_read_unlock();
706 			break;
707 		}
708 	}
709 	preempt_enable();
710 	percpu_up_read(&c->mark_lock);
711 err:
712 	bch2_trans_put(trans);
713 	bch_err_fn(c, ret);
714 	return ret;
715 }
716 
717 int bch2_dev_usage_remove(struct bch_fs *c, unsigned dev)
718 {
719 	return bch2_trans_run(c,
720 		bch2_btree_write_buffer_flush_sync(trans) ?:
721 		for_each_btree_key_commit(trans, iter, BTREE_ID_accounting, POS_MIN,
722 				BTREE_ITER_all_snapshots, k, NULL, NULL, 0, ({
723 			struct disk_accounting_pos acc;
724 			bpos_to_disk_accounting_pos(&acc, k.k->p);
725 
726 			acc.type == BCH_DISK_ACCOUNTING_dev_data_type &&
727 			acc.dev_data_type.dev == dev
728 				? bch2_btree_bit_mod_buffered(trans, BTREE_ID_accounting, k.k->p, 0)
729 				: 0;
730 		})) ?:
731 		bch2_btree_write_buffer_flush_sync(trans));
732 }
733 
734 int bch2_dev_usage_init(struct bch_dev *ca, bool gc)
735 {
736 	struct bch_fs *c = ca->fs;
737 	struct disk_accounting_pos acc = {
738 		.type = BCH_DISK_ACCOUNTING_dev_data_type,
739 		.dev_data_type.dev = ca->dev_idx,
740 		.dev_data_type.data_type = BCH_DATA_free,
741 	};
742 	u64 v[3] = { ca->mi.nbuckets - ca->mi.first_bucket, 0, 0 };
743 
744 	int ret = bch2_trans_do(c, NULL, NULL, 0,
745 			bch2_disk_accounting_mod(trans, &acc, v, ARRAY_SIZE(v), gc));
746 	bch_err_fn(c, ret);
747 	return ret;
748 }
749 
750 void bch2_verify_accounting_clean(struct bch_fs *c)
751 {
752 	bool mismatch = false;
753 	struct bch_fs_usage_base base = {}, base_inmem = {};
754 
755 	bch2_trans_run(c,
756 		for_each_btree_key(trans, iter,
757 				   BTREE_ID_accounting, POS_MIN,
758 				   BTREE_ITER_all_snapshots, k, ({
759 			u64 v[BCH_ACCOUNTING_MAX_COUNTERS];
760 			struct bkey_s_c_accounting a = bkey_s_c_to_accounting(k);
761 			unsigned nr = bch2_accounting_counters(k.k);
762 
763 			bch2_accounting_mem_read(c, k.k->p, v, nr);
764 
765 			if (memcmp(a.v->d, v, nr * sizeof(u64))) {
766 				struct printbuf buf = PRINTBUF;
767 
768 				bch2_bkey_val_to_text(&buf, c, k);
769 				prt_str(&buf, " !=");
770 				for (unsigned j = 0; j < nr; j++)
771 					prt_printf(&buf, " %llu", v[j]);
772 
773 				pr_err("%s", buf.buf);
774 				printbuf_exit(&buf);
775 				mismatch = true;
776 			}
777 
778 			struct disk_accounting_pos acc_k;
779 			bpos_to_disk_accounting_pos(&acc_k, a.k->p);
780 
781 			switch (acc_k.type) {
782 			case BCH_DISK_ACCOUNTING_persistent_reserved:
783 				base.reserved += acc_k.persistent_reserved.nr_replicas * a.v->d[0];
784 				break;
785 			case BCH_DISK_ACCOUNTING_replicas:
786 				fs_usage_data_type_to_base(&base, acc_k.replicas.data_type, a.v->d[0]);
787 				break;
788 			case BCH_DISK_ACCOUNTING_dev_data_type: {
789 				rcu_read_lock();
790 				struct bch_dev *ca = bch2_dev_rcu(c, acc_k.dev_data_type.dev);
791 				if (!ca) {
792 					rcu_read_unlock();
793 					continue;
794 				}
795 
796 				v[0] = percpu_u64_get(&ca->usage->d[acc_k.dev_data_type.data_type].buckets);
797 				v[1] = percpu_u64_get(&ca->usage->d[acc_k.dev_data_type.data_type].sectors);
798 				v[2] = percpu_u64_get(&ca->usage->d[acc_k.dev_data_type.data_type].fragmented);
799 				rcu_read_unlock();
800 
801 				if (memcmp(a.v->d, v, 3 * sizeof(u64))) {
802 					struct printbuf buf = PRINTBUF;
803 
804 					bch2_bkey_val_to_text(&buf, c, k);
805 					prt_str(&buf, " in mem");
806 					for (unsigned j = 0; j < nr; j++)
807 						prt_printf(&buf, " %llu", v[j]);
808 
809 					pr_err("dev accounting mismatch: %s", buf.buf);
810 					printbuf_exit(&buf);
811 					mismatch = true;
812 				}
813 			}
814 			}
815 
816 			0;
817 		})));
818 
819 	acc_u64s_percpu(&base_inmem.hidden, &c->usage->hidden, sizeof(base_inmem) / sizeof(u64));
820 
821 #define check(x)										\
822 	if (base.x != base_inmem.x) {								\
823 		pr_err("fs_usage_base.%s mismatch: %llu != %llu", #x, base.x, base_inmem.x);	\
824 		mismatch = true;								\
825 	}
826 
827 	//check(hidden);
828 	check(btree);
829 	check(data);
830 	check(cached);
831 	check(reserved);
832 	check(nr_inodes);
833 
834 	WARN_ON(mismatch);
835 }
836 
837 void bch2_accounting_gc_free(struct bch_fs *c)
838 {
839 	lockdep_assert_held(&c->mark_lock);
840 
841 	struct bch_accounting_mem *acc = &c->accounting;
842 
843 	bch2_accounting_free_counters(acc, true);
844 	acc->gc_running = false;
845 }
846 
847 void bch2_fs_accounting_exit(struct bch_fs *c)
848 {
849 	struct bch_accounting_mem *acc = &c->accounting;
850 
851 	bch2_accounting_free_counters(acc, false);
852 	darray_exit(&acc->k);
853 }
854