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/res_counter.h>
14 #include <linux/uaccess.h>
16 void res_counter_init(struct res_counter *counter)
18 spin_lock_init(&counter->lock);
19 counter->limit = (unsigned long long)LLONG_MAX;
22 int res_counter_charge_locked(struct res_counter *counter, unsigned long val)
24 if (counter->usage + val > counter->limit) {
29 counter->usage += val;
33 int res_counter_charge(struct res_counter *counter, unsigned long val)
38 spin_lock_irqsave(&counter->lock, flags);
39 ret = res_counter_charge_locked(counter, val);
40 spin_unlock_irqrestore(&counter->lock, flags);
44 void res_counter_uncharge_locked(struct res_counter *counter, unsigned long val)
46 if (WARN_ON(counter->usage < val))
49 counter->usage -= val;
52 void res_counter_uncharge(struct res_counter *counter, unsigned long val)
56 spin_lock_irqsave(&counter->lock, flags);
57 res_counter_uncharge_locked(counter, val);
58 spin_unlock_irqrestore(&counter->lock, flags);
62 static inline unsigned long long *
63 res_counter_member(struct res_counter *counter, int member)
67 return &counter->usage;
69 return &counter->limit;
71 return &counter->failcnt;
78 ssize_t res_counter_read(struct res_counter *counter, int member,
79 const char __user *userbuf, size_t nbytes, loff_t *pos,
80 int (*read_strategy)(unsigned long long val, char *st_buf))
82 unsigned long long *val;
86 val = res_counter_member(counter, member);
88 s += read_strategy(*val, s);
90 s += sprintf(s, "%llu\n", *val);
91 return simple_read_from_buffer((void __user *)userbuf, nbytes,
95 ssize_t res_counter_write(struct res_counter *counter, int member,
96 const char __user *userbuf, size_t nbytes, loff_t *pos,
97 int (*write_strategy)(char *st_buf, unsigned long long *val))
102 unsigned long long tmp, *val;
104 buf = kmalloc(nbytes + 1, GFP_KERNEL);
111 if (copy_from_user(buf, userbuf, nbytes))
117 if (write_strategy) {
118 if (write_strategy(buf, &tmp)) {
122 tmp = simple_strtoull(buf, &end, 10);
126 spin_lock_irqsave(&counter->lock, flags);
127 val = res_counter_member(counter, member);
129 spin_unlock_irqrestore(&counter->lock, flags);