4 * Copyright 2007 OpenVZ SWsoft Inc
6 * Author: Pavel Emelianov <xemul@openvz.org>
10 #include <linux/types.h>
11 #include <linux/parser.h>
13 #include <linux/slab.h>
14 #include <linux/res_counter.h>
15 #include <linux/uaccess.h>
17 void res_counter_init(struct res_counter *counter)
19 spin_lock_init(&counter->lock);
20 counter->limit = (unsigned long long)LLONG_MAX;
23 int res_counter_charge_locked(struct res_counter *counter, unsigned long val)
25 if (counter->usage + val > counter->limit) {
30 counter->usage += val;
34 int res_counter_charge(struct res_counter *counter, unsigned long val)
39 spin_lock_irqsave(&counter->lock, flags);
40 ret = res_counter_charge_locked(counter, val);
41 spin_unlock_irqrestore(&counter->lock, flags);
45 void res_counter_uncharge_locked(struct res_counter *counter, unsigned long val)
47 if (WARN_ON(counter->usage < val))
50 counter->usage -= val;
53 void res_counter_uncharge(struct res_counter *counter, unsigned long val)
57 spin_lock_irqsave(&counter->lock, flags);
58 res_counter_uncharge_locked(counter, val);
59 spin_unlock_irqrestore(&counter->lock, flags);
63 static inline unsigned long long *
64 res_counter_member(struct res_counter *counter, int member)
68 return &counter->usage;
70 return &counter->limit;
72 return &counter->failcnt;
79 ssize_t res_counter_read(struct res_counter *counter, int member,
80 const char __user *userbuf, size_t nbytes, loff_t *pos,
81 int (*read_strategy)(unsigned long long val, char *st_buf))
83 unsigned long long *val;
87 val = res_counter_member(counter, member);
89 s += read_strategy(*val, s);
91 s += sprintf(s, "%llu\n", *val);
92 return simple_read_from_buffer((void __user *)userbuf, nbytes,
96 ssize_t res_counter_write(struct res_counter *counter, int member,
97 const char __user *userbuf, size_t nbytes, loff_t *pos,
98 int (*write_strategy)(char *st_buf, unsigned long long *val))
103 unsigned long long tmp, *val;
105 buf = kmalloc(nbytes + 1, GFP_KERNEL);
112 if (copy_from_user(buf, userbuf, nbytes))
118 if (write_strategy) {
119 if (write_strategy(buf, &tmp)) {
123 tmp = simple_strtoull(buf, &end, 10);
127 spin_lock_irqsave(&counter->lock, flags);
128 val = res_counter_member(counter, member);
130 spin_unlock_irqrestore(&counter->lock, flags);