/*1* lib/average.c2*3* This source code is licensed under the GNU General Public License,4* Version 2. See the file COPYING for more details.5*/67#include <linux/module.h>8#include <linux/average.h>9#include <linux/bug.h>10#include <linux/log2.h>1112/**13* DOC: Exponentially Weighted Moving Average (EWMA)14*15* These are generic functions for calculating Exponentially Weighted Moving16* Averages (EWMA). We keep a structure with the EWMA parameters and a scaled17* up internal representation of the average value to prevent rounding errors.18* The factor for scaling up and the exponential weight (or decay rate) have to19* be specified thru the init fuction. The structure should not be accessed20* directly but only thru the helper functions.21*/2223/**24* ewma_init() - Initialize EWMA parameters25* @avg: Average structure26* @factor: Factor to use for the scaled up internal value. The maximum value27* of averages can be ULONG_MAX/(factor*weight). For performance reasons28* factor has to be a power of 2.29* @weight: Exponential weight, or decay rate. This defines how fast the30* influence of older values decreases. For performance reasons weight has31* to be a power of 2.32*33* Initialize the EWMA parameters for a given struct ewma @avg.34*/35void ewma_init(struct ewma *avg, unsigned long factor, unsigned long weight)36{37WARN_ON(!is_power_of_2(weight) || !is_power_of_2(factor));3839avg->weight = ilog2(weight);40avg->factor = ilog2(factor);41avg->internal = 0;42}43EXPORT_SYMBOL(ewma_init);4445/**46* ewma_add() - Exponentially weighted moving average (EWMA)47* @avg: Average structure48* @val: Current value49*50* Add a sample to the average.51*/52struct ewma *ewma_add(struct ewma *avg, unsigned long val)53{54avg->internal = avg->internal ?55(((avg->internal << avg->weight) - avg->internal) +56(val << avg->factor)) >> avg->weight :57(val << avg->factor);58return avg;59}60EXPORT_SYMBOL(ewma_add);616263