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
;
31 if (counter
->usage
> counter
->max_usage
)
32 counter
->max_usage
= counter
->usage
;
36 int res_counter_charge(struct res_counter
*counter
, unsigned long val
)
41 spin_lock_irqsave(&counter
->lock
, flags
);
42 ret
= res_counter_charge_locked(counter
, val
);
43 spin_unlock_irqrestore(&counter
->lock
, flags
);
47 void res_counter_uncharge_locked(struct res_counter
*counter
, unsigned long val
)
49 if (WARN_ON(counter
->usage
< val
))
52 counter
->usage
-= val
;
55 void res_counter_uncharge(struct res_counter
*counter
, unsigned long val
)
59 spin_lock_irqsave(&counter
->lock
, flags
);
60 res_counter_uncharge_locked(counter
, val
);
61 spin_unlock_irqrestore(&counter
->lock
, flags
);
65 static inline unsigned long long *
66 res_counter_member(struct res_counter
*counter
, int member
)
70 return &counter
->usage
;
72 return &counter
->max_usage
;
74 return &counter
->limit
;
76 return &counter
->failcnt
;
83 ssize_t
res_counter_read(struct res_counter
*counter
, int member
,
84 const char __user
*userbuf
, size_t nbytes
, loff_t
*pos
,
85 int (*read_strategy
)(unsigned long long val
, char *st_buf
))
87 unsigned long long *val
;
91 val
= res_counter_member(counter
, member
);
93 s
+= read_strategy(*val
, s
);
95 s
+= sprintf(s
, "%llu\n", *val
);
96 return simple_read_from_buffer((void __user
*)userbuf
, nbytes
,
100 u64
res_counter_read_u64(struct res_counter
*counter
, int member
)
102 return *res_counter_member(counter
, member
);
105 ssize_t
res_counter_write(struct res_counter
*counter
, int member
,
106 const char __user
*userbuf
, size_t nbytes
, loff_t
*pos
,
107 int (*write_strategy
)(char *st_buf
, unsigned long long *val
))
112 unsigned long long tmp
, *val
;
114 buf
= kmalloc(nbytes
+ 1, GFP_KERNEL
);
121 if (copy_from_user(buf
, userbuf
, nbytes
))
127 if (write_strategy
) {
128 if (write_strategy(buf
, &tmp
)) {
132 tmp
= simple_strtoull(buf
, &end
, 10);
136 spin_lock_irqsave(&counter
->lock
, flags
);
137 val
= res_counter_member(counter
, member
);
139 spin_unlock_irqrestore(&counter
->lock
, flags
);