rc80211-pid: simplify and fix shift_adjust
[safe/jmp/linux-2.6] / net / mac80211 / rc80211_pid_algo.c
1 /*
2  * Copyright 2002-2005, Instant802 Networks, Inc.
3  * Copyright 2005, Devicescape Software, Inc.
4  * Copyright 2007, Mattias Nissler <mattias.nissler@gmx.de>
5  * Copyright 2007, Stefano Brivio <stefano.brivio@polimi.it>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11
12 #include <linux/netdevice.h>
13 #include <linux/types.h>
14 #include <linux/skbuff.h>
15
16 #include <net/mac80211.h>
17 #include "ieee80211_rate.h"
18
19 #include "rc80211_pid.h"
20
21
22 /* This is an implementation of a TX rate control algorithm that uses a PID
23  * controller. Given a target failed frames rate, the controller decides about
24  * TX rate changes to meet the target failed frames rate.
25  *
26  * The controller basically computes the following:
27  *
28  * adj = CP * err + CI * err_avg + CD * (err - last_err) * (1 + sharpening)
29  *
30  * where
31  *      adj     adjustment value that is used to switch TX rate (see below)
32  *      err     current error: target vs. current failed frames percentage
33  *      last_err        last error
34  *      err_avg average (i.e. poor man's integral) of recent errors
35  *      sharpening      non-zero when fast response is needed (i.e. right after
36  *                      association or no frames sent for a long time), heading
37  *                      to zero over time
38  *      CP      Proportional coefficient
39  *      CI      Integral coefficient
40  *      CD      Derivative coefficient
41  *
42  * CP, CI, CD are subject to careful tuning.
43  *
44  * The integral component uses a exponential moving average approach instead of
45  * an actual sliding window. The advantage is that we don't need to keep an
46  * array of the last N error values and computation is easier.
47  *
48  * Once we have the adj value, we map it to a rate by means of a learning
49  * algorithm. This algorithm keeps the state of the percentual failed frames
50  * difference between rates. The behaviour of the lowest available rate is kept
51  * as a reference value, and every time we switch between two rates, we compute
52  * the difference between the failed frames each rate exhibited. By doing so,
53  * we compare behaviours which different rates exhibited in adjacent timeslices,
54  * thus the comparison is minimally affected by external conditions. This
55  * difference gets propagated to the whole set of measurements, so that the
56  * reference is always the same. Periodically, we normalize this set so that
57  * recent events weigh the most. By comparing the adj value with this set, we
58  * avoid pejorative switches to lower rates and allow for switches to higher
59  * rates if they behaved well.
60  *
61  * Note that for the computations we use a fixed-point representation to avoid
62  * floating point arithmetic. Hence, all values are shifted left by
63  * RC_PID_ARITH_SHIFT.
64  */
65
66
67 /* Shift the adjustment so that we won't switch to a lower rate if it exhibited
68  * a worse failed frames behaviour and we'll choose the highest rate whose
69  * failed frames behaviour is not worse than the one of the original rate
70  * target. While at it, check that the adjustment is within the ranges. Then,
71  * provide the new rate index. */
72 static int rate_control_pid_shift_adjust(struct rc_pid_rateinfo *r,
73                                          int adj, int cur, int l)
74 {
75         int i, j, k, tmp;
76
77         j = r[cur].rev_index;
78         i = j + adj;
79
80         if (i < 0)
81                 return r[0].index;
82         if (i >= l - 1)
83                 return r[l - 1].index;
84
85         tmp = i;
86
87         if (adj < 0) {
88                 for (k = j; k >= i; k--)
89                         if (r[k].diff <= r[j].diff)
90                                 tmp = k;
91         } else {
92                 for (k = i + 1; k + i < l; k++)
93                         if (r[k].diff <= r[i].diff)
94                                 tmp = k;
95         }
96
97         return r[tmp].index;
98 }
99
100 static void rate_control_pid_adjust_rate(struct ieee80211_local *local,
101                                          struct sta_info *sta, int adj,
102                                          struct rc_pid_rateinfo *rinfo)
103 {
104         struct ieee80211_sub_if_data *sdata;
105         struct ieee80211_hw_mode *mode;
106         int newidx;
107         int maxrate;
108         int back = (adj > 0) ? 1 : -1;
109
110         sdata = IEEE80211_DEV_TO_SUB_IF(sta->dev);
111         if (sdata->bss && sdata->bss->force_unicast_rateidx > -1) {
112                 /* forced unicast rate - do not change STA rate */
113                 return;
114         }
115
116         mode = local->oper_hw_mode;
117         maxrate = sdata->bss ? sdata->bss->max_ratectrl_rateidx : -1;
118
119         newidx = rate_control_pid_shift_adjust(rinfo, adj, sta->txrate,
120                                                mode->num_rates);
121
122         while (newidx != sta->txrate) {
123                 if (rate_supported(sta, mode, newidx) &&
124                     (maxrate < 0 || newidx <= maxrate)) {
125                         sta->txrate = newidx;
126                         break;
127                 }
128
129                 newidx += back;
130         }
131
132 #ifdef CONFIG_MAC80211_DEBUGFS
133         rate_control_pid_event_rate_change(
134                 &((struct rc_pid_sta_info *)sta->rate_ctrl_priv)->events,
135                 newidx, mode->rates[newidx].rate);
136 #endif
137 }
138
139 /* Normalize the failed frames per-rate differences. */
140 static void rate_control_pid_normalize(struct rc_pid_info *pinfo, int l)
141 {
142         int i, norm_offset = pinfo->norm_offset;
143         struct rc_pid_rateinfo *r = pinfo->rinfo;
144
145         if (r[0].diff > norm_offset)
146                 r[0].diff -= norm_offset;
147         else if (r[0].diff < -norm_offset)
148                 r[0].diff += norm_offset;
149         for (i = 0; i < l - 1; i++)
150                 if (r[i + 1].diff > r[i].diff + norm_offset)
151                         r[i + 1].diff -= norm_offset;
152                 else if (r[i + 1].diff <= r[i].diff)
153                         r[i + 1].diff += norm_offset;
154 }
155
156 static void rate_control_pid_sample(struct rc_pid_info *pinfo,
157                                     struct ieee80211_local *local,
158                                     struct sta_info *sta)
159 {
160         struct rc_pid_sta_info *spinfo = sta->rate_ctrl_priv;
161         struct rc_pid_rateinfo *rinfo = pinfo->rinfo;
162         struct ieee80211_hw_mode *mode;
163         u32 pf;
164         s32 err_avg;
165         u32 err_prop;
166         u32 err_int;
167         u32 err_der;
168         int adj, i, j, tmp;
169         unsigned long period;
170
171         mode = local->oper_hw_mode;
172         spinfo = sta->rate_ctrl_priv;
173
174         /* In case nothing happened during the previous control interval, turn
175          * the sharpening factor on. */
176         period = (HZ * pinfo->sampling_period + 500) / 1000;
177         if (!period)
178                 period = 1;
179         if (jiffies - spinfo->last_sample > 2 * period)
180                 spinfo->sharp_cnt = pinfo->sharpen_duration;
181
182         spinfo->last_sample = jiffies;
183
184         /* This should never happen, but in case, we assume the old sample is
185          * still a good measurement and copy it. */
186         if (unlikely(spinfo->tx_num_xmit == 0))
187                 pf = spinfo->last_pf;
188         else {
189                 pf = spinfo->tx_num_failed * 100 / spinfo->tx_num_xmit;
190                 pf <<= RC_PID_ARITH_SHIFT;
191         }
192
193         spinfo->tx_num_xmit = 0;
194         spinfo->tx_num_failed = 0;
195
196         /* If we just switched rate, update the rate behaviour info. */
197         if (pinfo->oldrate != sta->txrate) {
198
199                 i = rinfo[pinfo->oldrate].rev_index;
200                 j = rinfo[sta->txrate].rev_index;
201
202                 tmp = (pf - spinfo->last_pf);
203                 tmp = RC_PID_DO_ARITH_RIGHT_SHIFT(tmp, RC_PID_ARITH_SHIFT);
204
205                 rinfo[j].diff = rinfo[i].diff + tmp;
206                 pinfo->oldrate = sta->txrate;
207         }
208         rate_control_pid_normalize(pinfo, mode->num_rates);
209
210         /* Compute the proportional, integral and derivative errors. */
211         err_prop = (pinfo->target << RC_PID_ARITH_SHIFT) - pf;
212
213         err_avg = spinfo->err_avg_sc >> pinfo->smoothing_shift;
214         spinfo->err_avg_sc = spinfo->err_avg_sc - err_avg + err_prop;
215         err_int = spinfo->err_avg_sc >> pinfo->smoothing_shift;
216
217         err_der = (pf - spinfo->last_pf) *
218                   (1 + pinfo->sharpen_factor * spinfo->sharp_cnt);
219         spinfo->last_pf = pf;
220         if (spinfo->sharp_cnt)
221                         spinfo->sharp_cnt--;
222
223 #ifdef CONFIG_MAC80211_DEBUGFS
224         rate_control_pid_event_pf_sample(&spinfo->events, pf, err_prop, err_int,
225                                          err_der);
226 #endif
227
228         /* Compute the controller output. */
229         adj = (err_prop * pinfo->coeff_p + err_int * pinfo->coeff_i
230               + err_der * pinfo->coeff_d);
231         adj = RC_PID_DO_ARITH_RIGHT_SHIFT(adj, 2 * RC_PID_ARITH_SHIFT);
232
233         /* Change rate. */
234         if (adj)
235                 rate_control_pid_adjust_rate(local, sta, adj, rinfo);
236 }
237
238 static void rate_control_pid_tx_status(void *priv, struct net_device *dev,
239                                        struct sk_buff *skb,
240                                        struct ieee80211_tx_status *status)
241 {
242         struct ieee80211_local *local = wdev_priv(dev->ieee80211_ptr);
243         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
244         struct rc_pid_info *pinfo = priv;
245         struct sta_info *sta;
246         struct rc_pid_sta_info *spinfo;
247         unsigned long period;
248
249         sta = sta_info_get(local, hdr->addr1);
250
251         if (!sta)
252                 return;
253
254         /* Ignore all frames that were sent with a different rate than the rate
255          * we currently advise mac80211 to use. */
256         if (status->control.rate != &local->oper_hw_mode->rates[sta->txrate])
257                 return;
258
259         spinfo = sta->rate_ctrl_priv;
260         spinfo->tx_num_xmit++;
261
262 #ifdef CONFIG_MAC80211_DEBUGFS
263         rate_control_pid_event_tx_status(&spinfo->events, status);
264 #endif
265
266         /* We count frames that totally failed to be transmitted as two bad
267          * frames, those that made it out but had some retries as one good and
268          * one bad frame. */
269         if (status->excessive_retries) {
270                 spinfo->tx_num_failed += 2;
271                 spinfo->tx_num_xmit++;
272         } else if (status->retry_count) {
273                 spinfo->tx_num_failed++;
274                 spinfo->tx_num_xmit++;
275         }
276
277         if (status->excessive_retries) {
278                 sta->tx_retry_failed++;
279                 sta->tx_num_consecutive_failures++;
280                 sta->tx_num_mpdu_fail++;
281         } else {
282                 sta->last_ack_rssi[0] = sta->last_ack_rssi[1];
283                 sta->last_ack_rssi[1] = sta->last_ack_rssi[2];
284                 sta->last_ack_rssi[2] = status->ack_signal;
285                 sta->tx_num_consecutive_failures = 0;
286                 sta->tx_num_mpdu_ok++;
287         }
288         sta->tx_retry_count += status->retry_count;
289         sta->tx_num_mpdu_fail += status->retry_count;
290
291         /* Update PID controller state. */
292         period = (HZ * pinfo->sampling_period + 500) / 1000;
293         if (!period)
294                 period = 1;
295         if (time_after(jiffies, spinfo->last_sample + period))
296                 rate_control_pid_sample(pinfo, local, sta);
297
298         sta_info_put(sta);
299 }
300
301 static void rate_control_pid_get_rate(void *priv, struct net_device *dev,
302                                       struct ieee80211_hw_mode *mode,
303                                       struct sk_buff *skb,
304                                       struct rate_selection *sel)
305 {
306         struct ieee80211_local *local = wdev_priv(dev->ieee80211_ptr);
307         struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
308         struct sta_info *sta;
309         int rateidx;
310
311         sta = sta_info_get(local, hdr->addr1);
312
313         if (!sta) {
314                 sel->rate = rate_lowest(local, mode, NULL);
315                 sta_info_put(sta);
316                 return;
317         }
318
319         rateidx = sta->txrate;
320
321         if (rateidx >= mode->num_rates)
322                 rateidx = mode->num_rates - 1;
323
324         sta_info_put(sta);
325
326         sel->rate = &mode->rates[rateidx];
327
328 #ifdef CONFIG_MAC80211_DEBUGFS
329         rate_control_pid_event_tx_rate(
330                 &((struct rc_pid_sta_info *) sta->rate_ctrl_priv)->events,
331                 rateidx, mode->rates[rateidx].rate);
332 #endif
333 }
334
335 static void rate_control_pid_rate_init(void *priv, void *priv_sta,
336                                           struct ieee80211_local *local,
337                                           struct sta_info *sta)
338 {
339         /* TODO: This routine should consider using RSSI from previous packets
340          * as we need to have IEEE 802.1X auth succeed immediately after assoc..
341          * Until that method is implemented, we will use the lowest supported
342          * rate as a workaround. */
343         sta->txrate = rate_lowest_index(local, local->oper_hw_mode, sta);
344 }
345
346 static void *rate_control_pid_alloc(struct ieee80211_local *local)
347 {
348         struct rc_pid_info *pinfo;
349         struct rc_pid_rateinfo *rinfo;
350         struct ieee80211_hw_mode *mode;
351         int i, j, tmp;
352         bool s;
353 #ifdef CONFIG_MAC80211_DEBUGFS
354         struct rc_pid_debugfs_entries *de;
355 #endif
356
357         pinfo = kmalloc(sizeof(*pinfo), GFP_ATOMIC);
358         if (!pinfo)
359                 return NULL;
360
361         /* We can safely assume that oper_hw_mode won't change unless we get
362          * reinitialized. */
363         mode = local->oper_hw_mode;
364         rinfo = kmalloc(sizeof(*rinfo) * mode->num_rates, GFP_ATOMIC);
365         if (!rinfo) {
366                 kfree(pinfo);
367                 return NULL;
368         }
369
370         /* Sort the rates. This is optimized for the most common case (i.e.
371          * almost-sorted CCK+OFDM rates). Kind of bubble-sort with reversed
372          * mapping too. */
373         for (i = 0; i < mode->num_rates; i++) {
374                 rinfo[i].index = i;
375                 rinfo[i].rev_index = i;
376                 if (pinfo->fast_start)
377                         rinfo[i].diff = 0;
378                 else
379                         rinfo[i].diff = i * pinfo->norm_offset;
380         }
381         for (i = 1; i < mode->num_rates; i++) {
382                 s = 0;
383                 for (j = 0; j < mode->num_rates - i; j++)
384                         if (unlikely(mode->rates[rinfo[j].index].rate >
385                                      mode->rates[rinfo[j + 1].index].rate)) {
386                                 tmp = rinfo[j].index;
387                                 rinfo[j].index = rinfo[j + 1].index;
388                                 rinfo[j + 1].index = tmp;
389                                 rinfo[rinfo[j].index].rev_index = j;
390                                 rinfo[rinfo[j + 1].index].rev_index = j + 1;
391                                 s = 1;
392                         }
393                 if (!s)
394                         break;
395         }
396
397         pinfo->target = RC_PID_TARGET_PF;
398         pinfo->sampling_period = RC_PID_INTERVAL;
399         pinfo->coeff_p = RC_PID_COEFF_P;
400         pinfo->coeff_i = RC_PID_COEFF_I;
401         pinfo->coeff_d = RC_PID_COEFF_D;
402         pinfo->smoothing_shift = RC_PID_SMOOTHING_SHIFT;
403         pinfo->sharpen_factor = RC_PID_SHARPENING_FACTOR;
404         pinfo->sharpen_duration = RC_PID_SHARPENING_DURATION;
405         pinfo->norm_offset = RC_PID_NORM_OFFSET;
406         pinfo->fast_start = RC_PID_FAST_START;
407         pinfo->rinfo = rinfo;
408         pinfo->oldrate = 0;
409
410 #ifdef CONFIG_MAC80211_DEBUGFS
411         de = &pinfo->dentries;
412         de->dir = debugfs_create_dir("rc80211_pid",
413                                      local->hw.wiphy->debugfsdir);
414         de->target = debugfs_create_u32("target_pf", S_IRUSR | S_IWUSR,
415                                         de->dir, &pinfo->target);
416         de->sampling_period = debugfs_create_u32("sampling_period",
417                                                  S_IRUSR | S_IWUSR, de->dir,
418                                                  &pinfo->sampling_period);
419         de->coeff_p = debugfs_create_u32("coeff_p", S_IRUSR | S_IWUSR,
420                                          de->dir, &pinfo->coeff_p);
421         de->coeff_i = debugfs_create_u32("coeff_i", S_IRUSR | S_IWUSR,
422                                          de->dir, &pinfo->coeff_i);
423         de->coeff_d = debugfs_create_u32("coeff_d", S_IRUSR | S_IWUSR,
424                                          de->dir, &pinfo->coeff_d);
425         de->smoothing_shift = debugfs_create_u32("smoothing_shift",
426                                                  S_IRUSR | S_IWUSR, de->dir,
427                                                  &pinfo->smoothing_shift);
428         de->sharpen_factor = debugfs_create_u32("sharpen_factor",
429                                                S_IRUSR | S_IWUSR, de->dir,
430                                                &pinfo->sharpen_factor);
431         de->sharpen_duration = debugfs_create_u32("sharpen_duration",
432                                                   S_IRUSR | S_IWUSR, de->dir,
433                                                   &pinfo->sharpen_duration);
434         de->norm_offset = debugfs_create_u32("norm_offset",
435                                              S_IRUSR | S_IWUSR, de->dir,
436                                              &pinfo->norm_offset);
437         de->fast_start = debugfs_create_bool("fast_start",
438                                              S_IRUSR | S_IWUSR, de->dir,
439                                              &pinfo->fast_start);
440 #endif
441
442         return pinfo;
443 }
444
445 static void rate_control_pid_free(void *priv)
446 {
447         struct rc_pid_info *pinfo = priv;
448 #ifdef CONFIG_MAC80211_DEBUGFS
449         struct rc_pid_debugfs_entries *de = &pinfo->dentries;
450
451         debugfs_remove(de->fast_start);
452         debugfs_remove(de->norm_offset);
453         debugfs_remove(de->sharpen_duration);
454         debugfs_remove(de->sharpen_factor);
455         debugfs_remove(de->smoothing_shift);
456         debugfs_remove(de->coeff_d);
457         debugfs_remove(de->coeff_i);
458         debugfs_remove(de->coeff_p);
459         debugfs_remove(de->sampling_period);
460         debugfs_remove(de->target);
461         debugfs_remove(de->dir);
462 #endif
463
464         kfree(pinfo->rinfo);
465         kfree(pinfo);
466 }
467
468 static void rate_control_pid_clear(void *priv)
469 {
470 }
471
472 static void *rate_control_pid_alloc_sta(void *priv, gfp_t gfp)
473 {
474         struct rc_pid_sta_info *spinfo;
475
476         spinfo = kzalloc(sizeof(*spinfo), gfp);
477         if (spinfo == NULL)
478                 return NULL;
479
480 #ifdef CONFIG_MAC80211_DEBUGFS
481         spin_lock_init(&spinfo->events.lock);
482         init_waitqueue_head(&spinfo->events.waitqueue);
483 #endif
484
485         return spinfo;
486 }
487
488 static void rate_control_pid_free_sta(void *priv, void *priv_sta)
489 {
490         struct rc_pid_sta_info *spinfo = priv_sta;
491         kfree(spinfo);
492 }
493
494 struct rate_control_ops mac80211_rcpid = {
495         .name = "pid",
496         .tx_status = rate_control_pid_tx_status,
497         .get_rate = rate_control_pid_get_rate,
498         .rate_init = rate_control_pid_rate_init,
499         .clear = rate_control_pid_clear,
500         .alloc = rate_control_pid_alloc,
501         .free = rate_control_pid_free,
502         .alloc_sta = rate_control_pid_alloc_sta,
503         .free_sta = rate_control_pid_free_sta,
504 #ifdef CONFIG_MAC80211_DEBUGFS
505         .add_sta_debugfs = rate_control_pid_add_sta_debugfs,
506         .remove_sta_debugfs = rate_control_pid_remove_sta_debugfs,
507 #endif
508 };