aboutsummaryrefslogtreecommitdiffstats
path: root/lib/percpu_counter.c
blob: 7a87003f8e8fa6bdd88b291c9a052f0f040eb0b1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
 * Fast batching percpu counters.
 */

#include <linux/percpu_counter.h>
#include <linux/module.h>

void percpu_counter_mod(struct percpu_counter *fbc, long amount)
{
	long count;
	long *pcount;
	int cpu = get_cpu();

	pcount = per_cpu_ptr(fbc->counters, cpu);
	count = *pcount + amount;
	if (count >= FBC_BATCH || count <= -FBC_BATCH) {
		spin_lock(&fbc->lock);
		fbc->count += count;
		*pcount = 0;
		spin_unlock(&fbc->lock);
	} else {
		*pcount = count;
	}
	put_cpu();
}
EXPORT_SYMBOL(percpu_counter_mod);

/*
 * Add up all the per-cpu counts, return the result.  This is a more accurate
 * but much slower version of percpu_counter_read_positive()
 */
long percpu_counter_sum(struct percpu_counter *fbc)
{
	long ret;
	int cpu;

	spin_lock(&fbc->lock);
	ret = fbc->count;
	for_each_possible_cpu(cpu) {
		long *pcount = per_cpu_ptr(fbc->counters, cpu);
		ret += *pcount;
	}
	spin_unlock(&fbc->lock);
	return ret < 0 ? 0 : ret;
}
EXPORT_SYMBOL(percpu_counter_sum);