2012-09-24 09:17:00 +00:00
|
|
|
// (c) 2012 Thomas Schoebel-Theuer / 1&1 Internet AG
|
|
|
|
|
|
|
|
#include "lib_limiter.h"
|
|
|
|
|
|
|
|
#include <linux/kernel.h>
|
|
|
|
#include <linux/module.h>
|
|
|
|
|
|
|
|
int mars_limit(struct mars_limiter *lim, int amount)
|
|
|
|
{
|
2012-09-24 09:49:29 +00:00
|
|
|
int delay = 0;
|
2012-12-06 13:14:59 +00:00
|
|
|
long long now;
|
2012-09-24 09:17:00 +00:00
|
|
|
|
|
|
|
now = cpu_clock(raw_smp_processor_id());
|
|
|
|
|
2012-09-24 09:49:29 +00:00
|
|
|
/* Compute the maximum delay along the path
|
|
|
|
* down to the root of the hierarchy tree.
|
|
|
|
*/
|
|
|
|
while (lim != NULL) {
|
|
|
|
if (likely(lim->lim_stamp)) {
|
|
|
|
long long elapsed = now - lim->lim_stamp;
|
|
|
|
int rate;
|
|
|
|
|
|
|
|
/* Races are possible, but taken into account.
|
|
|
|
* There is no real harm from rarely lost updates.
|
|
|
|
*/
|
2012-12-11 14:34:51 +00:00
|
|
|
if (likely(amount > 0))
|
2012-12-06 13:14:59 +00:00
|
|
|
lim->lim_accu += amount;
|
2012-09-24 09:49:29 +00:00
|
|
|
|
|
|
|
rate = (long long)lim->lim_accu * LIMITER_TIME_RESOLUTION / elapsed;
|
|
|
|
lim->lim_rate = rate;
|
|
|
|
|
|
|
|
// limit exceeded?
|
|
|
|
if (lim->lim_max_rate > 0 && rate > lim->lim_max_rate) {
|
2012-12-11 14:34:51 +00:00
|
|
|
int this_delay = 1000 - (long long)lim->lim_max_rate * 1000 / rate;
|
2012-09-24 09:49:29 +00:00
|
|
|
// compute maximum
|
2012-12-11 14:34:51 +00:00
|
|
|
if (this_delay > delay)
|
2012-09-24 09:49:29 +00:00
|
|
|
delay = this_delay;
|
|
|
|
}
|
|
|
|
|
|
|
|
elapsed -= LIMITER_TIME_RESOLUTION * 2;
|
|
|
|
if (elapsed > LIMITER_TIME_RESOLUTION) {
|
|
|
|
lim->lim_stamp += elapsed;
|
|
|
|
if (lim->lim_accu > 0) {
|
|
|
|
lim->lim_accu -= (long long)lim->lim_max_rate * elapsed / LIMITER_TIME_RESOLUTION;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2012-12-06 13:14:59 +00:00
|
|
|
if (unlikely(amount < 0))
|
|
|
|
amount = 0;
|
2012-09-24 09:49:29 +00:00
|
|
|
lim->lim_accu = amount;
|
|
|
|
lim->lim_stamp = now;
|
|
|
|
lim->lim_rate = 0;
|
2012-09-24 09:17:00 +00:00
|
|
|
}
|
2012-09-24 09:49:29 +00:00
|
|
|
lim = lim->lim_father;
|
2012-09-24 09:17:00 +00:00
|
|
|
}
|
2012-09-24 09:49:29 +00:00
|
|
|
return delay;
|
2012-09-24 09:17:00 +00:00
|
|
|
}
|
|
|
|
EXPORT_SYMBOL_GPL(mars_limit);
|