09a39e73d54fde2a78d99bc43ed7f02bd57f5fad
[dragonfly.git] / sys / dev / netif / ath / rate_sample / sample.c
1 /*
2  * Copyright (c) 2005 John Bicket
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13  *    redistribution must be conditioned upon including a substantially
14  *    similar Disclaimer requirement for further binary redistribution.
15  * 3. Neither the names of the above-listed copyright holders nor the names
16  *    of any contributors may be used to endorse or promote products derived
17  *    from this software without specific prior written permission.
18  *
19  * Alternatively, this software may be distributed under the terms of the
20  * GNU General Public License ("GPL") version 2 as published by the Free
21  * Software Foundation.
22  *
23  * NO WARRANTY
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
27  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
28  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
29  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
32  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
34  * THE POSSIBILITY OF SUCH DAMAGES.
35  *
36  * $FreeBSD: src/sys/dev/ath/ath_rate/sample/sample.c,v 1.8.2.3 2006/03/14 23:22:27 sam Exp $
37  * $DragonFly: src/sys/dev/netif/ath/rate_sample/sample.c,v 1.1 2006/07/13 09:15:22 sephe Exp $
38  */
39
40 /*
41  * John Bicket's SampleRate control algorithm.
42  */
43
44 #include <sys/param.h>
45 #include <sys/systm.h> 
46 #include <sys/sysctl.h>
47 #include <sys/module.h>
48 #include <sys/kernel.h>
49 #include <sys/lock.h>
50 #include <sys/errno.h>
51
52 #include <machine/bus.h>
53 #include <machine/resource.h>
54 #include <sys/bus.h>
55
56 #include <sys/socket.h>
57  
58 #include <net/if.h>
59 #include <net/if_media.h>
60 #include <net/if_arp.h>
61
62 #include <netproto/802_11/ieee80211_var.h>
63
64 #include <net/bpf.h>
65
66 #include <dev/netif/ath/ath/if_athvar.h>
67 #include <dev/netif/ath/rate_sample/sample.h>
68 #include <contrib/dev/ath/ah_desc.h>
69
70 #define SAMPLE_DEBUG
71 #ifdef SAMPLE_DEBUG
72 enum {
73         ATH_DEBUG_RATE          = 0x00000010    /* rate control */
74 };
75 #define DPRINTF(sc, _fmt, ...) do {                             \
76         if (sc->sc_debug & ATH_DEBUG_RATE)                      \
77                 printf(_fmt, __VA_ARGS__);                      \
78 } while (0)
79 #else
80 #define DPRINTF(sc, _fmt, ...)
81 #endif
82
83 /*
84  * This file is an implementation of the SampleRate algorithm
85  * in "Bit-rate Selection in Wireless Networks"
86  * (http://www.pdos.lcs.mit.edu/papers/jbicket-ms.ps)
87  *
88  * SampleRate chooses the bit-rate it predicts will provide the most
89  * throughput based on estimates of the expected per-packet
90  * transmission time for each bit-rate.  SampleRate periodically sends
91  * packets at bit-rates other than the current one to estimate when
92  * another bit-rate will provide better performance. SampleRate
93  * switches to another bit-rate when its estimated per-packet
94  * transmission time becomes smaller than the current bit-rate's.
95  * SampleRate reduces the number of bit-rates it must sample by
96  * eliminating those that could not perform better than the one
97  * currently being used.  SampleRate also stops probing at a bit-rate
98  * if it experiences several successive losses.
99  *
100  * The difference between the algorithm in the thesis and the one in this
101  * file is that the one in this file uses a ewma instead of a window.
102  *
103  * Also, this implementation tracks the average transmission time for
104  * a few different packet sizes independently for each link.
105  */
106
107 #define STALE_FAILURE_TIMEOUT_MS 10000
108 #define MIN_SWITCH_MS 1000
109
110 static void     ath_rate_ctl_reset(struct ath_softc *, struct ieee80211_node *);
111
112 static __inline int
113 size_to_bin(int size) 
114 {
115         int x = 0;
116         for (x = 0; x < NUM_PACKET_SIZE_BINS; x++) {
117                 if (size <= packet_size_bins[x]) {
118                         return x;
119                 }
120         }
121         return NUM_PACKET_SIZE_BINS-1;
122 }
123 static __inline int
124 bin_to_size(int index) {
125         return packet_size_bins[index];
126 }
127
128 static __inline int
129 rate_to_ndx(struct sample_node *sn, int rate) {
130         int x = 0;
131         for (x = 0; x < sn->num_rates; x++) {
132                 if (sn->rates[x].rate == rate) {
133                         return x;
134                 }      
135         }
136         return -1;
137 }
138
139 void
140 ath_rate_node_init(struct ath_softc *sc, struct ath_node *an)
141 {
142         DPRINTF(sc, "%s:\n", __func__);
143         /* NB: assumed to be zero'd by caller */
144 }
145
146 void
147 ath_rate_node_cleanup(struct ath_softc *sc, struct ath_node *an)
148 {
149         DPRINTF(sc, "%s:\n", __func__);
150 }
151
152
153 /*
154  * returns the ndx with the lowest average_tx_time,
155  * or -1 if all the average_tx_times are 0.
156  */
157 static __inline int best_rate_ndx(struct sample_node *sn, int size_bin, 
158                                   int require_acked_before)
159 {
160         int x = 0;
161         int best_rate_ndx = 0;
162         int best_rate_tt = 0;
163         for (x = 0; x < sn->num_rates; x++) {
164                 int tt = sn->stats[size_bin][x].average_tx_time;
165                 if (tt <= 0 || (require_acked_before && 
166                                 !sn->stats[size_bin][x].packets_acked)) {
167                         continue;
168                 }
169
170                 /* 9 megabits never works better than 12 */
171                 if (sn->rates[x].rate == 18) 
172                         continue;
173
174                 /* don't use a bit-rate that has been failing */
175                 if (sn->stats[size_bin][x].successive_failures > 3)
176                         continue;
177
178                 if (!best_rate_tt || best_rate_tt > tt) {
179                         best_rate_tt = tt;
180                         best_rate_ndx = x;
181                 }
182         }
183         return (best_rate_tt) ? best_rate_ndx : -1;
184 }
185
186 /*
187  * pick a good "random" bit-rate to sample other than the current one
188  */
189 static __inline int
190 pick_sample_ndx(struct sample_node *sn, int size_bin) 
191 {
192         int x = 0;
193         int current_ndx = 0;
194         unsigned current_tt = 0;
195         
196         current_ndx = sn->current_rate[size_bin];
197         if (current_ndx < 0) {
198                 /* no successes yet, send at the lowest bit-rate */
199                 return 0;
200         }
201         
202         current_tt = sn->stats[size_bin][current_ndx].average_tx_time;
203         
204         for (x = 0; x < sn->num_rates; x++) {
205                 int ndx = (sn->last_sample_ndx[size_bin]+1+x) % sn->num_rates;
206
207                 /* don't sample the current bit-rate */
208                 if (ndx == current_ndx) 
209                         continue;
210
211                 /* this bit-rate is always worse than the current one */
212                 if (sn->stats[size_bin][ndx].perfect_tx_time > current_tt) 
213                         continue;
214
215                 /* rarely sample bit-rates that fail a lot */
216                 if (ticks - sn->stats[size_bin][ndx].last_tx < ((hz * STALE_FAILURE_TIMEOUT_MS)/1000) &&
217                     sn->stats[size_bin][ndx].successive_failures > 3)
218                         continue;
219
220                 /* don't sample more than 2 indexes higher 
221                  * for rates higher than 11 megabits
222                  */
223                 if (sn->rates[ndx].rate > 22 && ndx > current_ndx + 2)
224                         continue;
225
226                 /* 9 megabits never works better than 12 */
227                 if (sn->rates[ndx].rate == 18) 
228                         continue;
229
230                 /* if we're using 11 megabits, only sample up to 12 megabits
231                  */
232                 if (sn->rates[current_ndx].rate == 22 && ndx > current_ndx + 1) 
233                         continue;
234
235                 sn->last_sample_ndx[size_bin] = ndx;
236                 return ndx;
237         }
238         return current_ndx;
239 }
240
241 void
242 ath_rate_findrate(struct ath_softc *sc, struct ath_node *an,
243                   int shortPreamble, size_t frameLen,
244                   u_int8_t *rix, int *try0, u_int8_t *txrate)
245 {
246         struct sample_node *sn = ATH_NODE_SAMPLE(an);
247         struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
248         struct ieee80211com *ic = &sc->sc_ic;
249         int ndx, size_bin, mrr, best_ndx, change_rates;
250         unsigned average_tx_time;
251
252         mrr = sc->sc_mrretry && !(ic->ic_flags & IEEE80211_F_USEPROT);
253         size_bin = size_to_bin(frameLen);
254         best_ndx = best_rate_ndx(sn, size_bin, !mrr);
255
256         if (best_ndx >= 0) {
257                 average_tx_time = sn->stats[size_bin][best_ndx].average_tx_time;
258         } else {
259                 average_tx_time = 0;
260         }
261         
262         if (sn->static_rate_ndx != -1) {
263                 ndx = sn->static_rate_ndx;
264                 *try0 = ATH_TXMAXTRY;
265         } else {
266                 *try0 = mrr ? 2 : ATH_TXMAXTRY;
267                 
268                 if (sn->sample_tt[size_bin] < average_tx_time * (sn->packets_since_sample[size_bin]*ssc->ath_sample_rate/100)) {
269                         /*
270                          * we want to limit the time measuring the performance
271                          * of other bit-rates to ath_sample_rate% of the
272                          * total transmission time.
273                          */
274                         ndx = pick_sample_ndx(sn, size_bin);
275                         if (ndx != sn->current_rate[size_bin]) {
276                                 sn->current_sample_ndx[size_bin] = ndx;
277                         } else {
278                                 sn->current_sample_ndx[size_bin] = -1;
279                         }
280                         sn->packets_since_sample[size_bin] = 0;
281
282                 } else {
283                         change_rates = 0;
284                         if (!sn->packets_sent[size_bin] || best_ndx == -1) {
285                                 /* no packet has been sent successfully yet */
286                                 for (ndx = sn->num_rates-1; ndx > 0; ndx--) {
287                                         /* 
288                                          * pick the highest rate <= 36 Mbps
289                                          * that hasn't failed.
290                                          */
291                                         if (sn->rates[ndx].rate <= 72 && 
292                                             sn->stats[size_bin][ndx].successive_failures == 0) {
293                                                 break;
294                                         }
295                                 }
296                                 change_rates = 1;
297                                 best_ndx = ndx;
298                         } else if (sn->packets_sent[size_bin] < 20) {
299                                 /* let the bit-rate switch quickly during the first few packets */
300                                 change_rates = 1;
301                         } else if (ticks - ((hz*MIN_SWITCH_MS)/1000) > sn->ticks_since_switch[size_bin]) {
302                                 /* 2 seconds have gone by */
303                                 change_rates = 1;
304                         } else if (average_tx_time * 2 < sn->stats[size_bin][sn->current_rate[size_bin]].average_tx_time) {
305                                 /* the current bit-rate is twice as slow as the best one */
306                                 change_rates = 1;
307                         }
308
309                         sn->packets_since_sample[size_bin]++;
310                         
311                         if (change_rates) {
312                                 if (best_ndx != sn->current_rate[size_bin]) {
313                                         DPRINTF(sc, "%s: %6D size %d switch rate %d (%d/%d) -> %d (%d/%d) after %d packets mrr %d\n",
314                                                 __func__,
315                                                 an->an_node.ni_macaddr, ":",
316                                                 packet_size_bins[size_bin],
317                                                 sn->rates[sn->current_rate[size_bin]].rate,
318                                                 sn->stats[size_bin][sn->current_rate[size_bin]].average_tx_time,
319                                                 sn->stats[size_bin][sn->current_rate[size_bin]].perfect_tx_time,
320                                                 sn->rates[best_ndx].rate,
321                                                 sn->stats[size_bin][best_ndx].average_tx_time,
322                                                 sn->stats[size_bin][best_ndx].perfect_tx_time,
323                                                 sn->packets_since_switch[size_bin],
324                                                 mrr);
325                                 }
326                                 sn->packets_since_switch[size_bin] = 0;
327                                 sn->current_rate[size_bin] = best_ndx;
328                                 sn->ticks_since_switch[size_bin] = ticks;
329                         }
330                         ndx = sn->current_rate[size_bin];
331                         sn->packets_since_switch[size_bin]++;
332                         if (size_bin == 0) {
333                                 /* 
334                                  * set the visible txrate for this node
335                                  * to the rate of small packets
336                                  */
337                                 an->an_node.ni_txrate = ndx;
338                         }
339                 }
340         }
341
342         KASSERT(ndx >= 0 && ndx < sn->num_rates, ("ndx is %d", ndx));
343
344         *rix = sn->rates[ndx].rix;
345         if (shortPreamble) {
346                 *txrate = sn->rates[ndx].shortPreambleRateCode;
347         } else {
348                 *txrate = sn->rates[ndx].rateCode;
349         }
350         sn->packets_sent[size_bin]++;
351 }
352
353 void
354 ath_rate_setupxtxdesc(struct ath_softc *sc, struct ath_node *an,
355                       struct ath_desc *ds, int shortPreamble, u_int8_t rix)
356 {
357         struct sample_node *sn = ATH_NODE_SAMPLE(an);
358         int rateCode = -1;
359         int frame_size = 0;
360         int size_bin = 0;
361         int ndx = 0;
362
363         /* TODO: it's correct that frame_size alway 0 ? */
364         size_bin = size_to_bin(frame_size);
365         
366         ndx = sn->current_rate[size_bin]; /* retry at the current bit-rate */
367         
368         if (!sn->stats[size_bin][ndx].packets_acked) {
369                 ndx = 0;  /* use the lowest bit-rate */
370         }
371
372         if (shortPreamble) {
373                 rateCode = sn->rates[ndx].shortPreambleRateCode;
374         } else {
375                 rateCode = sn->rates[ndx].rateCode;
376         }
377         ath_hal_setupxtxdesc(sc->sc_ah, ds
378                              , rateCode, 3              /* series 1 */
379                              , sn->rates[0].rateCode, 3 /* series 2 */
380                              , 0, 0                     /* series 3 */
381                              );
382 }
383
384 static void
385 update_stats(struct ath_softc *sc, struct ath_node *an, 
386                   int frame_size,
387                   int ndx0, int tries0,
388                   int ndx1, int tries1,
389                   int ndx2, int tries2,
390                   int ndx3, int tries3,
391                   int short_tries, int tries, int status)
392 {
393         struct sample_node *sn = ATH_NODE_SAMPLE(an);
394         struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
395         int tt = 0;
396         int tries_so_far = 0;
397         int size_bin = 0;
398         int size = 0;
399         int rate = 0;
400
401         size_bin = size_to_bin(frame_size);
402         size = bin_to_size(size_bin);
403         rate = sn->rates[ndx0].rate;
404
405         tt += calc_usecs_unicast_packet(sc, size, sn->rates[ndx0].rix, 
406                                         short_tries-1, 
407                                         MIN(tries0, tries) - 1);
408         tries_so_far += tries0;
409         if (tries1 && tries0 < tries) {
410                 tt += calc_usecs_unicast_packet(sc, size, sn->rates[ndx1].rix, 
411                                                 short_tries-1, 
412                                                 MIN(tries1 + tries_so_far, tries) - tries_so_far - 1);
413         }
414         tries_so_far += tries1;
415
416         if (tries2 && tries0 + tries1 < tries) {
417                 tt += calc_usecs_unicast_packet(sc, size, sn->rates[ndx2].rix, 
418                                                short_tries-1, 
419                                                 MIN(tries2 + tries_so_far, tries) - tries_so_far - 1);
420         }
421
422         tries_so_far += tries2;
423
424         if (tries3 && tries0 + tries1 + tries2 < tries) {
425                 tt += calc_usecs_unicast_packet(sc, size, sn->rates[ndx3].rix, 
426                                                 short_tries-1, 
427                                                 MIN(tries3 + tries_so_far, tries) - tries_so_far - 1);
428         }
429         if (sn->stats[size_bin][ndx0].total_packets < (100 / (100 - ssc->ath_smoothing_rate))) {
430                 /* just average the first few packets */
431                 int avg_tx = sn->stats[size_bin][ndx0].average_tx_time;
432                 int packets = sn->stats[size_bin][ndx0].total_packets;
433                 sn->stats[size_bin][ndx0].average_tx_time = (tt+(avg_tx*packets))/(packets+1);
434         } else {
435                 /* use a ewma */
436                 sn->stats[size_bin][ndx0].average_tx_time = 
437                         ((sn->stats[size_bin][ndx0].average_tx_time * ssc->ath_smoothing_rate) + 
438                          (tt * (100 - ssc->ath_smoothing_rate))) / 100;
439         }
440         
441         if (status) {
442                 int y;
443                 sn->stats[size_bin][ndx0].successive_failures++;
444                 for (y = size_bin+1; y < NUM_PACKET_SIZE_BINS; y++) {
445                         /* also say larger packets failed since we
446                          * assume if a small packet fails at a lower
447                          * bit-rate then a larger one will also.
448                          */
449                         sn->stats[y][ndx0].successive_failures++;
450                         sn->stats[y][ndx0].last_tx = ticks;
451                         sn->stats[y][ndx0].tries += tries;
452                         sn->stats[y][ndx0].total_packets++;
453                 }
454         } else {
455                 sn->stats[size_bin][ndx0].packets_acked++;
456                 sn->stats[size_bin][ndx0].successive_failures = 0;
457         }
458         sn->stats[size_bin][ndx0].tries += tries;
459         sn->stats[size_bin][ndx0].last_tx = ticks;
460         sn->stats[size_bin][ndx0].total_packets++;
461
462
463         if (ndx0 == sn->current_sample_ndx[size_bin]) {
464                 DPRINTF(sc, "%s: %6D size %d sample rate %d tries (%d/%d) tt %d avg_tt (%d/%d) status %d\n", 
465                         __func__, an->an_node.ni_macaddr, ":",
466                         size, rate, short_tries, tries, tt,
467                         sn->stats[size_bin][ndx0].average_tx_time,
468                         sn->stats[size_bin][ndx0].perfect_tx_time,
469                         status);
470                 sn->sample_tt[size_bin] = tt;
471                 sn->current_sample_ndx[size_bin] = -1;
472         }
473 }
474
475 void
476 ath_rate_tx_complete(struct ath_softc *sc, struct ath_node *an,
477         const struct ath_desc *ds, const struct ath_desc *ds0)
478 {
479         struct ieee80211com *ic = &sc->sc_ic;
480         struct sample_node *sn = ATH_NODE_SAMPLE(an);
481         const struct ar5212_desc *ads = (const struct ar5212_desc *)&ds->ds_ctl0;
482         int final_rate, short_tries, long_tries, frame_size;
483         int ndx = -1;
484         int mrr;
485
486         final_rate = sc->sc_hwmap[ds->ds_txstat.ts_rate &~ HAL_TXSTAT_ALTRATE].ieeerate;
487         short_tries = ds->ds_txstat.ts_shortretry + 1;
488         long_tries = ds->ds_txstat.ts_longretry + 1;
489         frame_size = ds0->ds_ctl0 & 0x0fff; /* low-order 12 bits of ds_ctl0 */
490         if (frame_size == 0)                /* NB: should not happen */
491                 frame_size = 1500;
492
493         if (sn->num_rates <= 0) {
494                 DPRINTF(sc, "%s: %6D size %d status %d rate/try %d/%d "
495                         "no rates yet\n", 
496                         __func__, an->an_node.ni_macaddr, ":",
497                         bin_to_size(size_to_bin(frame_size)),
498                         ds->ds_txstat.ts_status,
499                         short_tries, long_tries);
500                 return;
501         }
502
503         mrr = sc->sc_mrretry && !(ic->ic_flags & IEEE80211_F_USEPROT);
504
505         if (sc->sc_mrretry && ds->ds_txstat.ts_status) {
506                 /* this packet failed */
507                 DPRINTF(sc, "%s: %6D size %d rate/try %d/%d %d/%d %d/%d %d/%d status %s retries (%d/%d)\n", 
508                         __func__,
509                         an->an_node.ni_macaddr, ":",
510                         bin_to_size(size_to_bin(frame_size)),
511                         sc->sc_hwmap[ads->xmit_rate0].ieeerate,
512                                 ads->xmit_tries0,
513                         sc->sc_hwmap[ads->xmit_rate1].ieeerate,
514                                 ads->xmit_tries1,
515                         sc->sc_hwmap[ads->xmit_rate2].ieeerate,
516                                 ads->xmit_tries2,
517                         sc->sc_hwmap[ads->xmit_rate3].ieeerate,
518                                 ads->xmit_tries3,
519                         ds->ds_txstat.ts_status ? "FAIL" : "OK",
520                         short_tries, 
521                         long_tries);
522         }
523
524         if (!mrr || !(ds->ds_txstat.ts_rate & HAL_TXSTAT_ALTRATE)) {
525                 /* only one rate was used */
526                 ndx = rate_to_ndx(sn, final_rate);
527                 DPRINTF(sc, "%s: %6D size %d status %d rate/try %d/%d/%d\n", 
528                         __func__, an->an_node.ni_macaddr, ":",
529                         bin_to_size(size_to_bin(frame_size)),
530                         ds->ds_txstat.ts_status,
531                         ndx, short_tries, long_tries);
532                 if (ndx >= 0 && ndx < sn->num_rates) {
533                         update_stats(sc, an, frame_size, 
534                                      ndx, long_tries,
535                                      0, 0,
536                                      0, 0,
537                                      0, 0,
538                                      short_tries, long_tries, ds->ds_txstat.ts_status);
539                 }
540         } else {
541                 int rate0, tries0, ndx0;
542                 int rate1, tries1, ndx1;
543                 int rate2, tries2, ndx2;
544                 int rate3, tries3, ndx3;
545                 int finalTSIdx = ads->final_ts_index;
546
547                 /*
548                  * Process intermediate rates that failed.
549                  */
550
551                 rate0 = sc->sc_hwmap[ads->xmit_rate0].ieeerate;
552                 tries0 = ads->xmit_tries0;
553                 ndx0 = rate_to_ndx(sn, rate0);
554                 
555                 rate1 = sc->sc_hwmap[ads->xmit_rate1].ieeerate;
556                 tries1 = ads->xmit_tries1;
557                 ndx1 = rate_to_ndx(sn, rate1);
558                 
559                 rate2 = sc->sc_hwmap[ads->xmit_rate2].ieeerate;
560                 tries2 = ads->xmit_tries2;
561                 ndx2 = rate_to_ndx(sn, rate2);
562                 
563                 rate3 = sc->sc_hwmap[ads->xmit_rate3].ieeerate;
564                 tries3 = ads->xmit_tries3;
565                 ndx3 = rate_to_ndx(sn, rate3);
566                 
567 #if 1
568                 DPRINTF(sc, "%s: %6D size %d finaltsidx %d tries %d status %d rate/try %d/%d %d/%d %d/%d %d/%d\n", 
569                         __func__, an->an_node.ni_macaddr, ":",
570                         bin_to_size(size_to_bin(frame_size)),
571                         finalTSIdx,
572                         long_tries, 
573                         ds->ds_txstat.ts_status,
574                         rate0, tries0,
575                         rate1, tries1,
576                         rate2, tries2,
577                         rate3, tries3);
578 #endif
579
580                 if (tries0) {
581                         update_stats(sc, an, frame_size, 
582                                      ndx0, tries0, 
583                                      ndx1, tries1, 
584                                      ndx2, tries2, 
585                                      ndx3, tries3, 
586                                      short_tries, ds->ds_txstat.ts_longretry + 1, 
587                                      long_tries > tries0);
588                 }
589                 
590                 if (tries1 && finalTSIdx > 0) {
591                         update_stats(sc, an, frame_size, 
592                                      ndx1, tries1, 
593                                      ndx2, tries2, 
594                                      ndx3, tries3, 
595                                      0, 0, 
596                                      short_tries, ds->ds_txstat.ts_longretry + 1 - tries0, 
597                                      ds->ds_txstat.ts_status);
598                 }
599
600                 if (tries2 && finalTSIdx > 1) {
601                         update_stats(sc, an, frame_size, 
602                                      ndx2, tries2, 
603                                      ndx3, tries3, 
604                                      0, 0,
605                                      0, 0,
606                                      short_tries, ds->ds_txstat.ts_longretry + 1 - tries0 - tries1, 
607                                      ds->ds_txstat.ts_status);
608                 }
609
610                 if (tries3 && finalTSIdx > 2) {
611                         update_stats(sc, an, frame_size, 
612                                      ndx3, tries3, 
613                                      0, 0,
614                                      0, 0,
615                                      0, 0,
616                                      short_tries, ds->ds_txstat.ts_longretry + 1 - tries0 - tries1 - tries2, 
617                                      ds->ds_txstat.ts_status);
618                 }
619         }
620 }
621
622 void
623 ath_rate_newassoc(struct ath_softc *sc, struct ath_node *an, int isnew)
624 {
625         DPRINTF(sc, "%s: %6D isnew %d\n", __func__,
626                 an->an_node.ni_macaddr, ":", isnew);
627         if (isnew)
628                 ath_rate_ctl_reset(sc, &an->an_node);
629 }
630
631 /*
632  * Initialize the tables for a node.
633  */
634 static void
635 ath_rate_ctl_reset(struct ath_softc *sc, struct ieee80211_node *ni)
636 {
637 #define RATE(_ix)       (ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
638         struct ieee80211com *ic = &sc->sc_ic;
639         struct ath_node *an = ATH_NODE(ni);
640         struct sample_node *sn = ATH_NODE_SAMPLE(an);
641         const HAL_RATE_TABLE *rt = sc->sc_currates;
642         int x, y, srate;
643
644         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
645         sn->static_rate_ndx = -1;
646         if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
647                 /*
648                  * A fixed rate is to be used; ic_fixed_rate is an
649                  * index into the supported rate set.  Convert this
650                  * to the index into the negotiated rate set for
651                  * the node.
652                  */
653                 const struct ieee80211_rateset *rs =
654                         &ic->ic_sup_rates[ic->ic_curmode];
655                 int r = rs->rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
656                 /* NB: the rate set is assumed sorted */
657                 srate = ni->ni_rates.rs_nrates - 1;
658                 for (; srate >= 0 && RATE(srate) != r; srate--)
659                         ;
660                 KASSERT(srate >= 0,
661                         ("fixed rate %d not in rate set", ic->ic_fixed_rate));
662                 sn->static_rate_ndx = srate;
663         }
664
665         DPRINTF(sc, "%s: %6D size 1600 rate/tt", __func__, ni->ni_macaddr, ":");
666
667         sn->num_rates = ni->ni_rates.rs_nrates;
668         for (x = 0; x < ni->ni_rates.rs_nrates; x++) {
669                 sn->rates[x].rate = ni->ni_rates.rs_rates[x] & IEEE80211_RATE_VAL;
670                 sn->rates[x].rix = sc->sc_rixmap[sn->rates[x].rate];
671                 if (sn->rates[x].rix == 0xff) {
672                         DPRINTF(sc, "%s: ignore bogus rix at %d\n",
673                                 __func__, x);
674                         continue;
675                 }
676                 sn->rates[x].rateCode = rt->info[sn->rates[x].rix].rateCode;
677                 sn->rates[x].shortPreambleRateCode = 
678                         rt->info[sn->rates[x].rix].rateCode | 
679                         rt->info[sn->rates[x].rix].shortPreamble;
680
681                 DPRINTF(sc, " %d/%d", sn->rates[x].rate,
682                         calc_usecs_unicast_packet(sc, 1600, sn->rates[x].rix, 
683                                                   0,0));
684         }
685         DPRINTF(sc, "%s\n", "");
686         
687         /* set the visible bit-rate to the lowest one available */
688         ni->ni_txrate = 0;
689         sn->num_rates = ni->ni_rates.rs_nrates;
690         
691         for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
692                 int size = bin_to_size(y);
693                 int ndx = 0;
694                 sn->packets_sent[y] = 0;
695                 sn->current_sample_ndx[y] = -1;
696                 sn->last_sample_ndx[y] = 0;
697                 
698                 for (x = 0; x < ni->ni_rates.rs_nrates; x++) {
699                         sn->stats[y][x].successive_failures = 0;
700                         sn->stats[y][x].tries = 0;
701                         sn->stats[y][x].total_packets = 0;
702                         sn->stats[y][x].packets_acked = 0;
703                         sn->stats[y][x].last_tx = 0;
704                         
705                         sn->stats[y][x].perfect_tx_time = 
706                                 calc_usecs_unicast_packet(sc, size, 
707                                                           sn->rates[x].rix,
708                                                           0, 0);
709                         sn->stats[y][x].average_tx_time = sn->stats[y][x].perfect_tx_time;
710                 }
711
712                 /* set the initial rate */
713                 for (ndx = sn->num_rates-1; ndx > 0; ndx--) {
714                         if (sn->rates[ndx].rate <= 72) {
715                                 break;
716                         }
717                 }
718                 sn->current_rate[y] = ndx;
719         }
720
721         DPRINTF(sc, "%s: %6D %d rates %d%sMbps (%dus)- %d%sMbps (%dus)\n",
722                 __func__, ni->ni_macaddr, ":",
723                 sn->num_rates,
724                 sn->rates[0].rate/2, sn->rates[0].rate % 0x1 ? ".5" : "",
725                 sn->stats[1][0].perfect_tx_time,
726                 sn->rates[sn->num_rates-1].rate/2,
727                         sn->rates[sn->num_rates-1].rate % 0x1 ? ".5" : "",
728                 sn->stats[1][sn->num_rates-1].perfect_tx_time
729         );
730
731         if (sn->static_rate_ndx != -1)
732                 ni->ni_txrate = sn->static_rate_ndx;
733         else
734                 ni->ni_txrate = sn->current_rate[0];
735 #undef RATE
736 }
737
738 static void
739 rate_cb(void *arg, struct ieee80211_node *ni)
740 {
741         struct ath_softc *sc = arg;
742
743         ath_rate_newassoc(sc, ATH_NODE(ni), 1);
744 }
745
746 /*
747  * Reset the rate control state for each 802.11 state transition.
748  */
749 void
750 ath_rate_newstate(struct ath_softc *sc, enum ieee80211_state state)
751 {
752         struct ieee80211com *ic = &sc->sc_ic;
753
754         ASSERT_SERIALIZED(ic->ic_if.if_serializer);
755
756         if (state == IEEE80211_S_RUN) {
757                 if (ic->ic_opmode != IEEE80211_M_STA) {
758                         /*
759                          * Sync rates for associated stations and neighbors.
760                          */
761                         ieee80211_iterate_nodes(&ic->ic_sta, rate_cb, sc);
762                 }
763                 ath_rate_newassoc(sc, ATH_NODE(ic->ic_bss), 1);
764         }
765 }
766
767 static void
768 ath_rate_sysctlattach(struct ath_softc *sc, struct sample_softc *osc)
769 {
770         struct sysctl_ctx_list *ctx = &sc->sc_sysctl_ctx;
771         struct sysctl_oid *tree = sc->sc_sysctl_tree;
772
773         /* XXX bounds check [0..100] */
774         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
775                 "smoothing_rate", CTLFLAG_RW, &osc->ath_smoothing_rate, 0,
776                 "rate control: retry threshold to credit rate raise (%%)");
777         /* XXX bounds check [2..100] */
778         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
779                 "sample_rate", CTLFLAG_RW, &osc->ath_sample_rate,0,
780                 "rate control: # good periods before raising rate");
781 }
782
783 struct ath_ratectrl *
784 ath_rate_attach(struct ath_softc *sc)
785 {
786         struct sample_softc *osc;
787         
788         DPRINTF(sc, "%s:\n", __func__);
789         osc = malloc(sizeof(struct sample_softc), M_DEVBUF, M_NOWAIT|M_ZERO);
790         if (osc == NULL)
791                 return NULL;
792         osc->arc.arc_space = sizeof(struct sample_node);
793         osc->ath_smoothing_rate = 95;   /* ewma percentage (out of 100) */
794         osc->ath_sample_rate = 10;      /* send a different bit-rate 1/X packets */
795         ath_rate_sysctlattach(sc, osc);
796         return &osc->arc;
797 }
798
799 void
800 ath_rate_detach(struct ath_ratectrl *arc)
801 {
802         struct sample_softc *osc = (struct sample_softc *) arc;
803         
804         free(osc, M_DEVBUF);
805 }
806
807 void
808 ath_rate_stop(struct ath_ratectrl *arc __unused)
809 {
810 }
811
812 /*
813  * Module glue.
814  */
815 static int
816 sample_modevent(module_t mod, int type, void *unused)
817 {
818         switch (type) {
819         case MOD_LOAD:
820                 if (bootverbose)
821                         printf("ath_rate: version 1.2 <SampleRate bit-rate selection algorithm>\n");
822                 return 0;
823         case MOD_UNLOAD:
824                 return 0;
825         }
826         return EINVAL;
827 }
828
829 static moduledata_t sample_mod = {
830         "ath_rate",
831         sample_modevent,
832         0
833 };
834 DECLARE_MODULE(ath_rate, sample_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
835 MODULE_VERSION(ath_rate, 1);
836 MODULE_DEPEND(ath_rate, ath_hal, 1, 1, 1);      /* Atheros HAL */
837 MODULE_DEPEND(ath_rate, wlan, 1, 1, 1);