update Intel copyright years to 2014
[dpdk.git] / lib / librte_sched / rte_red.h
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  * 
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  * 
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  * 
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #ifndef __RTE_RED_H_INCLUDED__
35 #define __RTE_RED_H_INCLUDED__
36
37 #ifdef __cplusplus
38 extern "C" {
39 #endif
40
41 /**
42  * @file
43  * RTE Random Early Detection (RED)
44  *
45  *
46  ***/
47
48 #include <stdint.h>
49 #include <limits.h>
50 #include <rte_common.h>
51 #include <rte_debug.h>
52 #include <rte_cycles.h>
53 #include <rte_branch_prediction.h>
54
55 #define RTE_RED_SCALING                     10         /**< Fraction size for fixed-point */
56 #define RTE_RED_S                           (1 << 22)  /**< Packet size multiplied by number of leaf queues */
57 #define RTE_RED_MAX_TH_MAX                  1023       /**< Max threshold limit in fixed point format */
58 #define RTE_RED_WQ_LOG2_MIN                 1          /**< Min inverse filter weight value */
59 #define RTE_RED_WQ_LOG2_MAX                 12         /**< Max inverse filter weight value */
60 #define RTE_RED_MAXP_INV_MIN                1          /**< Min inverse mark probability value */
61 #define RTE_RED_MAXP_INV_MAX                255        /**< Max inverse mark probability value */
62 #define RTE_RED_2POW16                      (1<<16)    /**< 2 power 16 */
63 #define RTE_RED_INT16_NBITS                 (sizeof(uint16_t) * CHAR_BIT)
64 #define RTE_RED_WQ_LOG2_NUM                 (RTE_RED_WQ_LOG2_MAX - RTE_RED_WQ_LOG2_MIN + 1)
65
66 #ifdef RTE_RED_DEBUG
67
68 #define RTE_RED_ASSERT(exp)                                      \
69 if (!(exp)) {                                                    \
70         rte_panic("line%d\tassert \"" #exp "\" failed\n", __LINE__); \
71 }
72
73 #else
74
75 #define RTE_RED_ASSERT(exp)                 do { } while(0)
76
77 #endif /* RTE_RED_DEBUG */
78
79 /**
80  * Externs
81  * 
82  */
83 extern uint32_t rte_red_rand_val;
84 extern uint32_t rte_red_rand_seed;
85 extern uint16_t rte_red_log2_1_minus_Wq[RTE_RED_WQ_LOG2_NUM];
86 extern uint16_t rte_red_pow2_frac_inv[16];
87
88 /**
89  * RED configuration parameters passed by user
90  * 
91  */
92 struct rte_red_params {
93         uint16_t min_th;   /**< Minimum threshold for queue (max_th) */
94         uint16_t max_th;   /**< Maximum threshold for queue (max_th) */
95         uint16_t maxp_inv; /**< Inverse of packet marking probability maximum value (maxp = 1 / maxp_inv) */
96         uint16_t wq_log2;  /**< Negated log2 of queue weight (wq = 1 / (2 ^ wq_log2)) */
97 };
98
99 /**
100  * RED configuration parameters
101  */
102 struct rte_red_config {
103         uint32_t min_th;   /**< min_th scaled in fixed-point format */
104         uint32_t max_th;   /**< max_th scaled in fixed-point format */
105         uint32_t pa_const; /**< Precomputed constant value used for pa calculation (scaled in fixed-point format) */
106         uint8_t maxp_inv;  /**< maxp_inv */
107         uint8_t wq_log2;   /**< wq_log2 */
108 };
109
110 /**
111  * RED run-time data
112  */
113 struct rte_red {
114         uint32_t avg;      /**< Average queue size (avg), scaled in fixed-point format */
115         uint32_t count;    /**< Number of packets since last marked packet (count) */
116         uint64_t q_time;   /**< Start of the queue idle time (q_time) */
117 };
118
119 /** 
120  * @brief Initialises run-time data
121  *  
122  * @param [in,out] data pointer to RED runtime data
123  *
124  * @return Operation status
125  * @retval 0 success
126  * @retval !0 error
127  */
128 int
129 rte_red_rt_data_init(struct rte_red *red);
130
131 /** 
132  * @brief Configures a single RED configuration parameter structure.
133  * 
134  * @param [in,out] config pointer to a RED configuration parameter structure
135  * @param [in] wq_log2 log2 of the filter weight, valid range is:
136  *             RTE_RED_WQ_LOG2_MIN <= wq_log2 <= RTE_RED_WQ_LOG2_MAX
137  * @param [in] min_th queue minimum threshold in number of packets
138  * @param [in] max_th queue maximum threshold in number of packets
139  * @param [in] maxp_inv inverse maximum mark probability
140  * 
141  * @return Operation status
142  * @retval 0 success
143  * @retval !0 error
144  */
145 int
146 rte_red_config_init(struct rte_red_config *red_cfg,
147         const uint16_t wq_log2,
148         const uint16_t min_th,
149         const uint16_t max_th,
150         const uint16_t maxp_inv);
151
152 /**
153  * @brief Generate random number for RED
154  *
155  * Implemenetation based on:
156  * http://software.intel.com/en-us/articles/fast-random-number-generator-on-the-intel-pentiumr-4-processor/
157  *
158  * 10 bit shift has been found through empirical tests (was 16).
159  *
160  * @return Random number between 0 and (2^22 - 1)
161  */
162 static inline uint32_t
163 rte_fast_rand(void)
164 {
165         rte_red_rand_seed = (214013 * rte_red_rand_seed) + 2531011;
166         return (rte_red_rand_seed >> 10);
167 }
168
169 /**
170  * @brief calculate factor to scale average queue size when queue
171  *        becomes empty
172  *
173  * @param [in] wq_log2, where EWMA filter weight wq = 1/(2 ^ wq_log2)
174  * @param [in] m exponent in the computed value (1 - wq) ^ m
175  *
176  * @return computed value
177  * @retval ((1 - wq) ^ m) scaled in fixed-point format
178  */
179 static inline uint16_t
180 __rte_red_calc_qempty_factor(uint8_t wq_log2, uint16_t m)
181 {
182         uint32_t n = 0;
183         uint32_t f = 0;
184
185         /**
186          * Basic math tells us that:
187          *   a^b = 2^(b * log2(a) )
188          *
189          * in our case:
190          *   a = (1-Wq)
191          *   b = m
192          *  Wq = 1/ (2^log2n)
193          *
194          * So we are computing this equation:
195          *   factor = 2 ^ ( m * log2(1-Wq))
196          *
197          * First we are computing:
198          *    n = m * log2(1-Wq)
199          *
200          * To avoid dealing with signed numbers log2 values are positive
201          * but they should be negative because (1-Wq) is always < 1.
202          * Contents of log2 table values are also scaled for precision.
203          */
204
205         n = m * rte_red_log2_1_minus_Wq[wq_log2 - RTE_RED_WQ_LOG2_MIN];
206
207         /**
208          * The tricky part is computing 2^n, for this I split n into
209          * integer part and fraction part.
210          *   f - is fraction part of n
211          *   n - is integer part of original n
212          *
213          * Now using basic math we compute 2^n:
214          *   2^(f+n) = 2^f * 2^n
215          *   2^f - we use lookup table
216          *   2^n - can be replaced with bit shift right oeprations
217          */
218
219         f = (n >> 6) & 0xf;
220         n >>= 10;
221
222         if (n < RTE_RED_SCALING)
223                 return (uint16_t) ((rte_red_pow2_frac_inv[f] + (1 << (n - 1))) >> n);
224
225         return 0;
226 }
227
228 /** 
229  * @brief Updates queue average in condition when queue is empty
230  *
231  * Note: packet is never dropped in this particular case.
232  *
233  * @param [in] config pointer to a RED configuration parameter structure
234  * @param [in,out] data pointer to RED runtime data
235  * @param [in] time current time stamp
236  * 
237  * @return Operation status
238  * @retval 0 enqueue the packet
239  * @retval 1 drop the packet based on max threshold criterion
240  * @retval 2 drop the packet based on mark probability criterion
241  */
242 static inline int
243 rte_red_enqueue_empty(const struct rte_red_config *red_cfg,
244         struct rte_red *red,
245         const uint64_t time)
246 {
247         uint64_t time_diff = 0, m = 0;
248         
249         RTE_RED_ASSERT(red_cfg != NULL);
250         RTE_RED_ASSERT(red != NULL);
251
252         red->count ++;
253
254         /**
255          * We compute avg but we don't compare avg against
256          *  min_th or max_th, nor calculate drop probability
257          */
258         time_diff = time - red->q_time;
259
260         /**
261          * m is the number of packets that might have arrived while the queue was empty.
262          * In this case we have time stamps provided by scheduler in byte units (bytes 
263          * transmitted on network port). Such time stamp translates into time units as
264          * port speed is fixed but such approach simplifies the code.
265          */
266         m = time_diff / RTE_RED_S;
267
268         /**
269          * Check that m will fit into 16-bit unsigned integer
270          */
271         if (m >= RTE_RED_2POW16) {
272                 red->avg = 0;
273         } else {
274                 red->avg = (red->avg >> RTE_RED_SCALING) * __rte_red_calc_qempty_factor(red_cfg->wq_log2, (uint16_t) m);
275         }
276
277         return 0;
278 }
279
280 /**
281  *  Drop probability (Sally Floyd and Van Jacobson):
282  *
283  *     pb = (1 / maxp_inv) * (avg - min_th) / (max_th - min_th)
284  *     pa = pb / (2 - count * pb)
285  *
286  *
287  *                 (1 / maxp_inv) * (avg - min_th)
288  *                ---------------------------------
289  *                         max_th - min_th
290  *     pa = -----------------------------------------------
291  *                count * (1 / maxp_inv) * (avg - min_th)
292  *           2 - -----------------------------------------
293  *                          max_th - min_th
294  *
295  *
296  *                                  avg - min_th
297  *     pa = -----------------------------------------------------------
298  *           2 * (max_th - min_th) * maxp_inv - count * (avg - min_th)
299  *
300  *
301  *  We define pa_const as: pa_const =  2 * (max_th - min_th) * maxp_inv. Then:
302  *
303  *
304  *                     avg - min_th
305  *     pa = -----------------------------------
306  *           pa_const - count * (avg - min_th)
307  */
308
309 /**
310  * @brief make a decision to drop or enqueue a packet based on mark probability
311  *        criteria
312  *
313  * @param [in] config pointer to structure defining RED parameters
314  * @param [in,out] data pointer to RED runtime data
315  *
316  * @return operation status
317  * @retval 0 enqueue the packet
318  * @retval 1 drop the packet
319  */
320 static inline int
321 __rte_red_drop(const struct rte_red_config *red_cfg, struct rte_red *red)
322 {
323         uint32_t pa_num = 0;    /* numerator of drop-probability */
324         uint32_t pa_den = 0;    /* denominator of drop-probability */
325         uint32_t pa_num_count = 0;
326
327         pa_num = (red->avg - red_cfg->min_th) >> (red_cfg->wq_log2);
328
329         pa_num_count = red->count * pa_num;
330
331         if (red_cfg->pa_const <= pa_num_count)
332                 return 1;
333
334         pa_den = red_cfg->pa_const - pa_num_count;
335
336         /* If drop, generate and save random number to be used next time */
337         if (unlikely((rte_red_rand_val % pa_den) < pa_num)) {
338                 rte_red_rand_val = rte_fast_rand();
339                 
340                 return 1;
341         }
342         
343         /* No drop */
344         return 0;
345 }
346
347 /** 
348  * @brief Decides if new packet should be enqeued or dropped in queue non-empty case
349  *
350  * @param [in] config pointer to a RED configuration parameter structure
351  * @param [in,out] data pointer to RED runtime data
352  * @param [in] q current queue size (measured in packets)
353  * 
354  * @return Operation status
355  * @retval 0 enqueue the packet
356  * @retval 1 drop the packet based on max threshold criterion
357  * @retval 2 drop the packet based on mark probability criterion
358  */
359 static inline int
360 rte_red_enqueue_nonempty(const struct rte_red_config *red_cfg,
361         struct rte_red *red,
362         const unsigned q)
363 {
364         RTE_RED_ASSERT(red_cfg != NULL);
365         RTE_RED_ASSERT(red != NULL);
366
367         /**
368         * EWMA filter (Sally Floyd and Van Jacobson):
369         *    avg = (1 - wq) * avg + wq * q
370         *    avg = avg + q * wq - avg * wq
371         *
372         * We select: wq = 2^(-n). Let scaled version of avg be: avg_s = avg * 2^(N+n). We get:
373         *    avg_s = avg_s + q * 2^N - avg_s * 2^(-n)
374         *
375         * By using shift left/right operations, we get:
376         *    avg_s = avg_s + (q << N) - (avg_s >> n)
377         *    avg_s += (q << N) - (avg_s >> n)
378         */
379         
380         /* avg update */
381         red->avg += (q << RTE_RED_SCALING) - (red->avg >> red_cfg->wq_log2);
382
383         /* avg < min_th: do not mark the packet  */
384         if (red->avg < red_cfg->min_th) {
385                 red->count ++;
386                 return 0;
387         }
388
389         /* min_th <= avg < max_th: mark the packet with pa probability */
390         if (red->avg < red_cfg->max_th) {
391                 if (!__rte_red_drop(red_cfg, red)) {
392                         red->count ++;
393                         return 0;
394                 }
395
396                 red->count = 0;
397                 return 2;
398         }
399         
400         /* max_th <= avg: always mark the packet */
401         red->count = 0;
402         return 1;
403 }
404
405 /** 
406  * @brief Decides if new packet should be enqeued or dropped
407  * Updates run time data based on new queue size value.
408  * Based on new queue average and RED configuration parameters
409  * gives verdict whether to enqueue or drop the packet. 
410  *
411  * @param [in] config pointer to a RED configuration parameter structure
412  * @param [in,out] data pointer to RED runtime data
413  * @param [in] q updated queue size in packets
414  * @param [in] time current time stamp
415  * 
416  * @return Operation status
417  * @retval 0 enqueue the packet
418  * @retval 1 drop the packet based on max threshold criteria
419  * @retval 2 drop the packet based on mark probability criteria
420  */
421 static inline int
422 rte_red_enqueue(const struct rte_red_config *red_cfg,
423         struct rte_red *red,
424         const unsigned q,
425         const uint64_t time)
426 {
427         RTE_RED_ASSERT(red_cfg != NULL);
428         RTE_RED_ASSERT(red != NULL);
429
430         if (q != 0) {
431                 return rte_red_enqueue_nonempty(red_cfg, red, q);
432         } else {
433                 return rte_red_enqueue_empty(red_cfg, red, time);
434         }
435 }
436
437 /** 
438  * @brief Callback to records time that queue became empty
439  *
440  * @param [in,out] data pointer to RED runtime data
441  * @param [in] time current time stamp
442  */
443 static inline void
444 rte_red_mark_queue_empty(struct rte_red *red, const uint64_t time)
445 {
446         red->q_time = time;
447 }
448
449 #ifdef __cplusplus
450 }
451 #endif
452
453 #endif /* __RTE_RED_H_INCLUDED__ */