netmap: d_poll -> d_kqfilter
[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: head/sys/dev/ath/ath_rate/sample/sample.c 194135 2009-06-13 23:36:54Z sam $
37  */
38
39 /*
40  * John Bicket's SampleRate control algorithm.
41  */
42 #include "opt_inet.h"
43 #include "opt_wlan.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h> 
47 #include <sys/sysctl.h>
48 #include <sys/kernel.h>
49 #include <sys/lock.h>
50 #include <sys/mutex.h>
51 #include <sys/errno.h>
52
53 #include <sys/bus.h>
54
55 #include <sys/socket.h>
56  
57 #include <net/if.h>
58 #include <net/if_media.h>
59 #include <net/if_arp.h>
60
61 #include <netproto/802_11/ieee80211_var.h>
62
63 #include <net/bpf.h>
64
65 #ifdef INET
66 #include <netinet/in.h> 
67 #include <netinet/if_ether.h>
68 #endif
69
70 #include <dev/netif/ath/ath/if_athvar.h>
71 #include <dev/netif/ath/rate_sample/sample.h>
72 #include <dev/netif/ath/hal/ath_hal/ah_desc.h>
73
74 /*
75  * This file is an implementation of the SampleRate algorithm
76  * in "Bit-rate Selection in Wireless Networks"
77  * (http://www.pdos.lcs.mit.edu/papers/jbicket-ms.ps)
78  *
79  * SampleRate chooses the bit-rate it predicts will provide the most
80  * throughput based on estimates of the expected per-packet
81  * transmission time for each bit-rate.  SampleRate periodically sends
82  * packets at bit-rates other than the current one to estimate when
83  * another bit-rate will provide better performance. SampleRate
84  * switches to another bit-rate when its estimated per-packet
85  * transmission time becomes smaller than the current bit-rate's.
86  * SampleRate reduces the number of bit-rates it must sample by
87  * eliminating those that could not perform better than the one
88  * currently being used.  SampleRate also stops probing at a bit-rate
89  * if it experiences several successive losses.
90  *
91  * The difference between the algorithm in the thesis and the one in this
92  * file is that the one in this file uses a ewma instead of a window.
93  *
94  * Also, this implementation tracks the average transmission time for
95  * a few different packet sizes independently for each link.
96  */
97
98 static void     ath_rate_ctl_reset(struct ath_softc *, struct ieee80211_node *);
99
100 static const int packet_size_bins[NUM_PACKET_SIZE_BINS] = { 250, 1600 };
101
102 static __inline int
103 size_to_bin(int size) 
104 {
105 #if NUM_PACKET_SIZE_BINS > 1
106         if (size <= packet_size_bins[0])
107                 return 0;
108 #endif
109 #if NUM_PACKET_SIZE_BINS > 2
110         if (size <= packet_size_bins[1])
111                 return 1;
112 #endif
113 #if NUM_PACKET_SIZE_BINS > 3
114         if (size <= packet_size_bins[2])
115                 return 2;
116 #endif
117 #if NUM_PACKET_SIZE_BINS > 4
118 #error "add support for more packet sizes"
119 #endif
120         return NUM_PACKET_SIZE_BINS-1;
121 }
122
123 static __inline int
124 bin_to_size(int index)
125 {
126         return packet_size_bins[index];
127 }
128
129 void
130 ath_rate_node_init(struct ath_softc *sc, struct ath_node *an)
131 {
132         /* NB: assumed to be zero'd by caller */
133 }
134
135 void
136 ath_rate_node_cleanup(struct ath_softc *sc, struct ath_node *an)
137 {
138 }
139
140 /*
141  * Return the rix with the lowest average_tx_time,
142  * or -1 if all the average_tx_times are 0.
143  */
144 static __inline int
145 pick_best_rate(struct sample_node *sn, const HAL_RATE_TABLE *rt,
146     int size_bin, int require_acked_before)
147 {
148         int best_rate_rix, best_rate_tt;
149         uint32_t mask;
150         int rix, tt;
151
152         best_rate_rix = 0;
153         best_rate_tt = 0;
154         for (mask = sn->ratemask, rix = 0; mask != 0; mask >>= 1, rix++) {
155                 if ((mask & 1) == 0)            /* not a supported rate */
156                         continue;
157
158                 tt = sn->stats[size_bin][rix].average_tx_time;
159                 if (tt <= 0 ||
160                     (require_acked_before &&
161                      !sn->stats[size_bin][rix].packets_acked))
162                         continue;
163
164                 /* don't use a bit-rate that has been failing */
165                 if (sn->stats[size_bin][rix].successive_failures > 3)
166                         continue;
167
168                 if (best_rate_tt == 0 || tt < best_rate_tt) {
169                         best_rate_tt = tt;
170                         best_rate_rix = rix;
171                 }
172         }
173         return (best_rate_tt ? best_rate_rix : -1);
174 }
175
176 /*
177  * Pick a good "random" bit-rate to sample other than the current one.
178  */
179 static __inline int
180 pick_sample_rate(struct sample_softc *ssc , struct sample_node *sn,
181     const HAL_RATE_TABLE *rt, int size_bin)
182 {
183 #define DOT11RATE(ix)   (rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
184         int current_rix, rix;
185         unsigned current_tt;
186         uint32_t mask;
187         
188         current_rix = sn->current_rix[size_bin];
189         if (current_rix < 0) {
190                 /* no successes yet, send at the lowest bit-rate */
191                 return 0;
192         }
193
194         current_tt = sn->stats[size_bin][current_rix].average_tx_time;
195
196         rix = sn->last_sample_rix[size_bin]+1;  /* next sample rate */
197         mask = sn->ratemask &~ (1<<current_rix);/* don't sample current rate */
198         while (mask != 0) {
199                 if ((mask & (1<<rix)) == 0) {   /* not a supported rate */
200         nextrate:
201                         if (++rix >= rt->rateCount)
202                                 rix = 0;
203                         continue;
204                 }
205
206                 /* this bit-rate is always worse than the current one */
207                 if (sn->stats[size_bin][rix].perfect_tx_time > current_tt) {
208                         mask &= ~(1<<rix);
209                         goto nextrate;
210                 }
211
212                 /* rarely sample bit-rates that fail a lot */
213                 if (sn->stats[size_bin][rix].successive_failures > ssc->max_successive_failures &&
214                     ticks - sn->stats[size_bin][rix].last_tx < ssc->stale_failure_timeout) {
215                         mask &= ~(1<<rix);
216                         goto nextrate;
217                 }
218
219                 /* don't sample more than 2 rates higher for rates > 11M */
220                 if (DOT11RATE(rix) > 2*11 && rix > current_rix + 2) {
221                         mask &= ~(1<<rix);
222                         goto nextrate;
223                 }
224
225                 sn->last_sample_rix[size_bin] = rix;
226                 return rix;
227         }
228         return current_rix;
229 #undef DOT11RATE
230 }
231
232 void
233 ath_rate_findrate(struct ath_softc *sc, struct ath_node *an,
234                   int shortPreamble, size_t frameLen,
235                   u_int8_t *rix0, int *try0, u_int8_t *txrate)
236 {
237 #define DOT11RATE(ix)   (rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
238 #define RATE(ix)        (DOT11RATE(ix) / 2)
239         struct sample_node *sn = ATH_NODE_SAMPLE(an);
240         struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
241         struct ifnet *ifp = sc->sc_ifp;
242         struct ieee80211com *ic = ifp->if_l2com;
243         const HAL_RATE_TABLE *rt = sc->sc_currates;
244         const int size_bin = size_to_bin(frameLen);
245         int rix, mrr, best_rix, change_rates;
246         unsigned average_tx_time;
247
248         if (sn->static_rix != -1) {
249                 rix = sn->static_rix;
250                 *try0 = ATH_TXMAXTRY;
251                 goto done;
252         }
253
254         mrr = sc->sc_mrretry && !(ic->ic_flags & IEEE80211_F_USEPROT);
255
256         best_rix = pick_best_rate(sn, rt, size_bin, !mrr);
257         if (best_rix >= 0) {
258                 average_tx_time = sn->stats[size_bin][best_rix].average_tx_time;
259         } else {
260                 average_tx_time = 0;
261         }
262         /*
263          * Limit the time measuring the performance of other tx
264          * rates to sample_rate% of the total transmission time.
265          */
266         if (sn->sample_tt[size_bin] < average_tx_time * (sn->packets_since_sample[size_bin]*ssc->sample_rate/100)) {
267                 rix = pick_sample_rate(ssc, sn, rt, size_bin);
268                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
269                      &an->an_node, "size %u sample rate %d current rate %d",
270                      bin_to_size(size_bin), RATE(rix),
271                      RATE(sn->current_rix[size_bin]));
272                 if (rix != sn->current_rix[size_bin]) {
273                         sn->current_sample_rix[size_bin] = rix;
274                 } else {
275                         sn->current_sample_rix[size_bin] = -1;
276                 }
277                 sn->packets_since_sample[size_bin] = 0;
278         } else {
279                 change_rates = 0;
280                 if (!sn->packets_sent[size_bin] || best_rix == -1) {
281                         /* no packet has been sent successfully yet */
282                         for (rix = rt->rateCount-1; rix > 0; rix--) {
283                                 if ((sn->ratemask & (1<<rix)) == 0)
284                                         continue;
285                                 /* 
286                                  * Pick the highest rate <= 36 Mbps
287                                  * that hasn't failed.
288                                  */
289                                 if (DOT11RATE(rix) <= 72 && 
290                                     sn->stats[size_bin][rix].successive_failures == 0) {
291                                         break;
292                                 }
293                         }
294                         change_rates = 1;
295                         best_rix = rix;
296                 } else if (sn->packets_sent[size_bin] < 20) {
297                         /* let the bit-rate switch quickly during the first few packets */
298                         change_rates = 1;
299                 } else if (ticks - ssc->min_switch > sn->ticks_since_switch[size_bin]) {
300                         /* min_switch seconds have gone by */
301                         change_rates = 1;
302                 } else if (2*average_tx_time < sn->stats[size_bin][sn->current_rix[size_bin]].average_tx_time) {
303                         /* the current bit-rate is twice as slow as the best one */
304                         change_rates = 1;
305                 }
306
307                 sn->packets_since_sample[size_bin]++;
308                 
309                 if (change_rates) {
310                         if (best_rix != sn->current_rix[size_bin]) {
311                                 IEEE80211_NOTE(an->an_node.ni_vap,
312                                     IEEE80211_MSG_RATECTL,
313                                     &an->an_node,
314 "%s: size %d switch rate %d (%d/%d) -> %d (%d/%d) after %d packets mrr %d",
315                                     __func__,
316                                     bin_to_size(size_bin),
317                                     RATE(sn->current_rix[size_bin]),
318                                     sn->stats[size_bin][sn->current_rix[size_bin]].average_tx_time,
319                                     sn->stats[size_bin][sn->current_rix[size_bin]].perfect_tx_time,
320                                     RATE(best_rix),
321                                     sn->stats[size_bin][best_rix].average_tx_time,
322                                     sn->stats[size_bin][best_rix].perfect_tx_time,
323                                     sn->packets_since_switch[size_bin],
324                                     mrr);
325                         }
326                         sn->packets_since_switch[size_bin] = 0;
327                         sn->current_rix[size_bin] = best_rix;
328                         sn->ticks_since_switch[size_bin] = ticks;
329                         /* 
330                          * Set the visible txrate for this node.
331                          */
332                         an->an_node.ni_txrate = DOT11RATE(best_rix);
333                 }
334                 rix = sn->current_rix[size_bin];
335                 sn->packets_since_switch[size_bin]++;
336         }
337         *try0 = mrr ? sn->sched[rix].t0 : ATH_TXMAXTRY;
338 done:
339         KASSERT(rix >= 0 && rix < rt->rateCount, ("rix is %d", rix));
340
341         *rix0 = rix;
342         *txrate = rt->info[rix].rateCode
343                 | (shortPreamble ? rt->info[rix].shortPreamble : 0);
344         sn->packets_sent[size_bin]++;
345 #undef DOT11RATE
346 #undef RATE
347 }
348
349 #define A(_r) \
350     (((_r) == 6)   ? 0 : (((_r) == 9)   ? 1 : (((_r) == 12)  ? 2 : \
351     (((_r) == 18)  ? 3 : (((_r) == 24)  ? 4 : (((_r) == 36)  ? 5 : \
352     (((_r) == 48)  ? 6 : (((_r) == 54)  ? 7 : 0))))))))
353 static const struct txschedule series_11a[] = {
354         { 3,A( 6), 3,A(  6), 0,A(  6), 0,A( 6) },       /*   6Mb/s */
355         { 4,A( 9), 3,A(  6), 4,A(  6), 0,A( 6) },       /*   9Mb/s */
356         { 4,A(12), 3,A(  6), 4,A(  6), 0,A( 6) },       /*  12Mb/s */
357         { 4,A(18), 3,A( 12), 4,A(  6), 2,A( 6) },       /*  18Mb/s */
358         { 4,A(24), 3,A( 18), 4,A( 12), 2,A( 6) },       /*  24Mb/s */
359         { 4,A(36), 3,A( 24), 4,A( 18), 2,A( 6) },       /*  36Mb/s */
360         { 4,A(48), 3,A( 36), 4,A( 24), 2,A(12) },       /*  48Mb/s */
361         { 4,A(54), 3,A( 48), 4,A( 36), 2,A(24) }        /*  54Mb/s */
362 };
363 #undef A
364
365 #define G(_r) \
366     (((_r) == 1)   ? 0 : (((_r) == 2)   ? 1 : (((_r) == 5.5) ? 2 : \
367     (((_r) == 11)  ? 3 : (((_r) == 6)   ? 4 : (((_r) == 9)   ? 5 : \
368     (((_r) == 12)  ? 6 : (((_r) == 18)  ? 7 : (((_r) == 24)  ? 8 : \
369     (((_r) == 36)  ? 9 : (((_r) == 48)  ? 10 : (((_r) == 54)  ? 11 : 0))))))))))))
370 static const struct txschedule series_11g[] = {
371         { 3,G( 1), 3,G(  1), 0,G(  1), 0,G( 1) },       /*   1Mb/s */
372         { 4,G( 2), 3,G(  1), 4,G(  1), 0,G( 1) },       /*   2Mb/s */
373         { 4,G(5.5),3,G(  2), 4,G(  1), 2,G( 1) },       /* 5.5Mb/s */
374         { 4,G(11), 3,G(5.5), 4,G(  2), 2,G( 1) },       /*  11Mb/s */
375         { 4,G( 6), 3,G(5.5), 4,G(  2), 2,G( 1) },       /*   6Mb/s */
376         { 4,G( 9), 3,G(  6), 4,G(5.5), 2,G( 1) },       /*   9Mb/s */
377         { 4,G(12), 3,G( 11), 4,G(5.5), 2,G( 1) },       /*  12Mb/s */
378         { 4,G(18), 3,G( 12), 4,G( 11), 2,G( 1) },       /*  18Mb/s */
379         { 4,G(24), 3,G( 18), 4,G( 12), 2,G( 1) },       /*  24Mb/s */
380         { 4,G(36), 3,G( 24), 4,G( 18), 2,G( 1) },       /*  36Mb/s */
381         { 4,G(48), 3,G( 36), 4,G( 24), 2,G( 1) },       /*  48Mb/s */
382         { 4,G(54), 3,G( 48), 4,G( 36), 2,G( 1) }        /*  54Mb/s */
383 };
384 #undef G
385
386 #define H(_r) \
387     (((_r) == 3)   ? 0 : (((_r) == 4.5) ? 1 : (((_r) == 6)  ? 2 : \
388     (((_r) == 9)   ? 3 : (((_r) == 12)  ? 4 : (((_r) == 18) ? 5 : \
389     (((_r) == 24)  ? 6 : (((_r) == 27)  ? 7 : 0))))))))
390 static const struct txschedule series_half[] = {
391         { 3,H( 3), 3,H(  3), 0,H(  3), 0,H( 3) },       /*   3Mb/s */
392         { 4,H(4.5),3,H(  3), 4,H(  3), 0,H( 3) },       /* 4.5Mb/s */
393         { 4,H( 6), 3,H(  3), 4,H(  3), 0,H( 3) },       /*   6Mb/s */
394         { 4,H( 9), 3,H(  6), 4,H(  3), 2,H( 3) },       /*   9Mb/s */
395         { 4,H(12), 3,H(  9), 4,H(  6), 2,H( 3) },       /*  12Mb/s */
396         { 4,H(18), 3,H( 12), 4,H(  9), 2,H( 3) },       /*  18Mb/s */
397         { 4,H(24), 3,H( 18), 4,H( 12), 2,H( 6) },       /*  24Mb/s */
398         { 4,H(27), 3,H( 24), 4,H( 18), 2,H(12) }        /*  27Mb/s */
399 };
400 #undef H
401
402 #ifdef Q
403 #undef Q                /* sun4v bogosity */
404 #endif
405 #define Q(_r) \
406     (((_r) == 1.5) ? 0 : (((_r) ==2.25) ? 1 : (((_r) == 3)  ? 2 : \
407     (((_r) == 4.5) ? 3 : (((_r) ==  6)  ? 4 : (((_r) == 9)  ? 5 : \
408     (((_r) == 12)  ? 6 : (((_r) == 13.5)? 7 : 0))))))))
409 static const struct txschedule series_quarter[] = {
410         { 3,Q( 1.5),3,Q(1.5), 0,Q(1.5), 0,Q(1.5) },     /* 1.5Mb/s */
411         { 4,Q(2.25),3,Q(1.5), 4,Q(1.5), 0,Q(1.5) },     /*2.25Mb/s */
412         { 4,Q(   3),3,Q(1.5), 4,Q(1.5), 0,Q(1.5) },     /*   3Mb/s */
413         { 4,Q( 4.5),3,Q(  3), 4,Q(1.5), 2,Q(1.5) },     /* 4.5Mb/s */
414         { 4,Q(   6),3,Q(4.5), 4,Q(  3), 2,Q(1.5) },     /*   6Mb/s */
415         { 4,Q(   9),3,Q(  6), 4,Q(4.5), 2,Q(1.5) },     /*   9Mb/s */
416         { 4,Q(  12),3,Q(  9), 4,Q(  6), 2,Q(  3) },     /*  12Mb/s */
417         { 4,Q(13.5),3,Q( 12), 4,Q(  9), 2,Q(  6) }      /*13.5Mb/s */
418 };
419 #undef Q
420
421 void
422 ath_rate_setupxtxdesc(struct ath_softc *sc, struct ath_node *an,
423                       struct ath_desc *ds, int shortPreamble, u_int8_t rix)
424 {
425         struct sample_node *sn = ATH_NODE_SAMPLE(an);
426         const struct txschedule *sched = &sn->sched[rix];
427         const HAL_RATE_TABLE *rt = sc->sc_currates;
428         uint8_t rix1, s1code, rix2, s2code, rix3, s3code;
429
430         /* XXX precalculate short preamble tables */
431         rix1 = sched->r1;
432         s1code = rt->info[rix1].rateCode
433                | (shortPreamble ? rt->info[rix1].shortPreamble : 0);
434         rix2 = sched->r2;
435         s2code = rt->info[rix2].rateCode
436                | (shortPreamble ? rt->info[rix2].shortPreamble : 0);
437         rix3 = sched->r3;
438         s3code = rt->info[rix3].rateCode
439                | (shortPreamble ? rt->info[rix3].shortPreamble : 0);
440         ath_hal_setupxtxdesc(sc->sc_ah, ds,
441             s1code, sched->t1,          /* series 1 */
442             s2code, sched->t2,          /* series 2 */
443             s3code, sched->t3);         /* series 3 */
444 }
445
446 static void
447 update_stats(struct ath_softc *sc, struct ath_node *an, 
448                   int frame_size,
449                   int rix0, int tries0,
450                   int rix1, int tries1,
451                   int rix2, int tries2,
452                   int rix3, int tries3,
453                   int short_tries, int tries, int status)
454 {
455         struct sample_node *sn = ATH_NODE_SAMPLE(an);
456         struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
457         const int size_bin = size_to_bin(frame_size);
458         const int size = bin_to_size(size_bin);
459         int tt, tries_so_far;
460
461         if (!IS_RATE_DEFINED(sn, rix0))
462                 return;
463         tt = calc_usecs_unicast_packet(sc, size, rix0, short_tries,
464                 MIN(tries0, tries) - 1);
465         tries_so_far = tries0;
466
467         if (tries1 && tries_so_far < tries) {
468                 if (!IS_RATE_DEFINED(sn, rix1))
469                         return;
470                 tt += calc_usecs_unicast_packet(sc, size, rix1, short_tries,
471                         MIN(tries1 + tries_so_far, tries) - tries_so_far - 1);
472                 tries_so_far += tries1;
473         }
474
475         if (tries2 && tries_so_far < tries) {
476                 if (!IS_RATE_DEFINED(sn, rix2))
477                         return;
478                 tt += calc_usecs_unicast_packet(sc, size, rix2, short_tries,
479                         MIN(tries2 + tries_so_far, tries) - tries_so_far - 1);
480                 tries_so_far += tries2;
481         }
482
483         if (tries3 && tries_so_far < tries) {
484                 if (!IS_RATE_DEFINED(sn, rix3))
485                         return;
486                 tt += calc_usecs_unicast_packet(sc, size, rix3, short_tries,
487                         MIN(tries3 + tries_so_far, tries) - tries_so_far - 1);
488         }
489
490         if (sn->stats[size_bin][rix0].total_packets < ssc->smoothing_minpackets) {
491                 /* just average the first few packets */
492                 int avg_tx = sn->stats[size_bin][rix0].average_tx_time;
493                 int packets = sn->stats[size_bin][rix0].total_packets;
494                 sn->stats[size_bin][rix0].average_tx_time = (tt+(avg_tx*packets))/(packets+1);
495         } else {
496                 /* use a ewma */
497                 sn->stats[size_bin][rix0].average_tx_time = 
498                         ((sn->stats[size_bin][rix0].average_tx_time * ssc->smoothing_rate) + 
499                          (tt * (100 - ssc->smoothing_rate))) / 100;
500         }
501         
502         if (status != 0) {
503                 int y;
504                 sn->stats[size_bin][rix0].successive_failures++;
505                 for (y = size_bin+1; y < NUM_PACKET_SIZE_BINS; y++) {
506                         /*
507                          * Also say larger packets failed since we
508                          * assume if a small packet fails at a
509                          * bit-rate then a larger one will also.
510                          */
511                         sn->stats[y][rix0].successive_failures++;
512                         sn->stats[y][rix0].last_tx = ticks;
513                         sn->stats[y][rix0].tries += tries;
514                         sn->stats[y][rix0].total_packets++;
515                 }
516         } else {
517                 sn->stats[size_bin][rix0].packets_acked++;
518                 sn->stats[size_bin][rix0].successive_failures = 0;
519         }
520         sn->stats[size_bin][rix0].tries += tries;
521         sn->stats[size_bin][rix0].last_tx = ticks;
522         sn->stats[size_bin][rix0].total_packets++;
523
524         if (rix0 == sn->current_sample_rix[size_bin]) {
525                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
526                    &an->an_node,
527 "%s: size %d %s sample rate %d tries (%d/%d) tt %d avg_tt (%d/%d)", 
528                     __func__, 
529                     size,
530                     status ? "FAIL" : "OK",
531                     rix0, short_tries, tries, tt, 
532                     sn->stats[size_bin][rix0].average_tx_time,
533                     sn->stats[size_bin][rix0].perfect_tx_time);
534                 sn->sample_tt[size_bin] = tt;
535                 sn->current_sample_rix[size_bin] = -1;
536         }
537 }
538
539 static void
540 badrate(struct ifnet *ifp, int series, int hwrate, int tries, int status)
541 {
542         if_printf(ifp, "bad series%d hwrate 0x%x, tries %u ts_status 0x%x\n",
543             series, hwrate, tries, status);
544 }
545
546 void
547 ath_rate_tx_complete(struct ath_softc *sc, struct ath_node *an,
548         const struct ath_buf *bf)
549 {
550         struct ifnet *ifp = sc->sc_ifp;
551         struct ieee80211com *ic = ifp->if_l2com;
552         struct sample_node *sn = ATH_NODE_SAMPLE(an);
553         const struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
554         const struct ath_desc *ds0 = &bf->bf_desc[0];
555         int final_rix, short_tries, long_tries, frame_size;
556         const HAL_RATE_TABLE *rt = sc->sc_currates;
557         int mrr;
558
559         final_rix = rt->rateCodeToIndex[ts->ts_rate];
560         short_tries = ts->ts_shortretry;
561         long_tries = ts->ts_longretry + 1;
562         frame_size = ds0->ds_ctl0 & 0x0fff; /* low-order 12 bits of ds_ctl0 */
563         if (frame_size == 0)                /* NB: should not happen */
564                 frame_size = 1500;
565
566         if (sn->ratemask == 0) {
567                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
568                     &an->an_node,
569                     "%s: size %d %s rate/try %d/%d no rates yet", 
570                     __func__,
571                     bin_to_size(size_to_bin(frame_size)),
572                     ts->ts_status ? "FAIL" : "OK",
573                     short_tries, long_tries);
574                 return;
575         }
576         mrr = sc->sc_mrretry && !(ic->ic_flags & IEEE80211_F_USEPROT);
577         if (!mrr || ts->ts_finaltsi == 0) {
578                 if (!IS_RATE_DEFINED(sn, final_rix)) {
579                         badrate(ifp, 0, ts->ts_rate, long_tries, ts->ts_status);
580                         return;
581                 }
582                 /*
583                  * Only one rate was used; optimize work.
584                  */
585                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
586                      &an->an_node, "%s: size %d %s rate/try %d/%d/%d",
587                      __func__,
588                      bin_to_size(size_to_bin(frame_size)),
589                      ts->ts_status ? "FAIL" : "OK",
590                      final_rix, short_tries, long_tries);
591                 update_stats(sc, an, frame_size, 
592                              final_rix, long_tries,
593                              0, 0,
594                              0, 0,
595                              0, 0,
596                              short_tries, long_tries, ts->ts_status);
597         } else {
598                 int hwrate0, rix0, tries0;
599                 int hwrate1, rix1, tries1;
600                 int hwrate2, rix2, tries2;
601                 int hwrate3, rix3, tries3;
602                 int finalTSIdx = ts->ts_finaltsi;
603
604                 /*
605                  * Process intermediate rates that failed.
606                  */
607                 if (sc->sc_ah->ah_magic != 0x20065416) {
608                         hwrate0 = MS(ds0->ds_ctl3, AR_XmitRate0);
609                         hwrate1 = MS(ds0->ds_ctl3, AR_XmitRate1);
610                         hwrate2 = MS(ds0->ds_ctl3, AR_XmitRate2);
611                         hwrate3 = MS(ds0->ds_ctl3, AR_XmitRate3);
612                 } else {
613                         hwrate0 = MS(ds0->ds_ctl3, AR5416_XmitRate0);
614                         hwrate1 = MS(ds0->ds_ctl3, AR5416_XmitRate1);
615                         hwrate2 = MS(ds0->ds_ctl3, AR5416_XmitRate2);
616                         hwrate3 = MS(ds0->ds_ctl3, AR5416_XmitRate3);
617                 }
618
619                 rix0 = rt->rateCodeToIndex[hwrate0];
620                 tries0 = MS(ds0->ds_ctl2, AR_XmitDataTries0);
621
622                 rix1 = rt->rateCodeToIndex[hwrate1];
623                 tries1 = MS(ds0->ds_ctl2, AR_XmitDataTries1);
624
625                 rix2 = rt->rateCodeToIndex[hwrate2];
626                 tries2 = MS(ds0->ds_ctl2, AR_XmitDataTries2);
627
628                 rix3 = rt->rateCodeToIndex[hwrate3];
629                 tries3 = MS(ds0->ds_ctl2, AR_XmitDataTries3);
630
631                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
632                     &an->an_node,
633 "%s: size %d finaltsidx %d tries %d %s rate/try [%d/%d %d/%d %d/%d %d/%d]", 
634                      __func__,
635                      bin_to_size(size_to_bin(frame_size)),
636                      finalTSIdx,
637                      long_tries, 
638                      ts->ts_status ? "FAIL" : "OK",
639                      rix0, tries0,
640                      rix1, tries1,
641                      rix2, tries2,
642                      rix3, tries3);
643
644                 if (tries0 && !IS_RATE_DEFINED(sn, rix0))
645                         badrate(ifp, 0, hwrate0, tries0, ts->ts_status);
646                 if (tries1 && !IS_RATE_DEFINED(sn, rix1))
647                         badrate(ifp, 1, hwrate1, tries1, ts->ts_status);
648                 if (tries2 && !IS_RATE_DEFINED(sn, rix2))
649                         badrate(ifp, 2, hwrate2, tries2, ts->ts_status);
650                 if (tries3 && !IS_RATE_DEFINED(sn, rix3))
651                         badrate(ifp, 3, hwrate3, tries3, ts->ts_status);
652
653                 /*
654                  * NB: series > 0 are not penalized for failure
655                  * based on the try counts under the assumption
656                  * that losses are often bursty and since we
657                  * sample higher rates 1 try at a time doing so
658                  * may unfairly penalize them.
659                  */
660                 if (tries0) {
661                         update_stats(sc, an, frame_size, 
662                                      rix0, tries0, 
663                                      rix1, tries1, 
664                                      rix2, tries2, 
665                                      rix3, tries3, 
666                                      short_tries, long_tries, 
667                                      long_tries > tries0);
668                         long_tries -= tries0;
669                 }
670                 
671                 if (tries1 && finalTSIdx > 0) {
672                         update_stats(sc, an, frame_size, 
673                                      rix1, tries1, 
674                                      rix2, tries2, 
675                                      rix3, tries3, 
676                                      0, 0, 
677                                      short_tries, long_tries, 
678                                      ts->ts_status);
679                         long_tries -= tries1;
680                 }
681
682                 if (tries2 && finalTSIdx > 1) {
683                         update_stats(sc, an, frame_size, 
684                                      rix2, tries2, 
685                                      rix3, tries3, 
686                                      0, 0,
687                                      0, 0,
688                                      short_tries, long_tries, 
689                                      ts->ts_status);
690                         long_tries -= tries2;
691                 }
692
693                 if (tries3 && finalTSIdx > 2) {
694                         update_stats(sc, an, frame_size, 
695                                      rix3, tries3, 
696                                      0, 0,
697                                      0, 0,
698                                      0, 0,
699                                      short_tries, long_tries, 
700                                      ts->ts_status);
701                 }
702         }
703 }
704
705 void
706 ath_rate_newassoc(struct ath_softc *sc, struct ath_node *an, int isnew)
707 {
708         if (isnew)
709                 ath_rate_ctl_reset(sc, &an->an_node);
710 }
711
712 static const struct txschedule *mrr_schedules[IEEE80211_MODE_MAX+2] = {
713         NULL,           /* IEEE80211_MODE_AUTO */
714         series_11a,     /* IEEE80211_MODE_11A */
715         series_11g,     /* IEEE80211_MODE_11B */
716         series_11g,     /* IEEE80211_MODE_11G */
717         NULL,           /* IEEE80211_MODE_FH */
718         series_11a,     /* IEEE80211_MODE_TURBO_A */
719         series_11g,     /* IEEE80211_MODE_TURBO_G */
720         series_11a,     /* IEEE80211_MODE_STURBO_A */
721         series_11a,     /* IEEE80211_MODE_11NA */
722         series_11g,     /* IEEE80211_MODE_11NG */
723         series_half,    /* IEEE80211_MODE_HALF */
724         series_quarter, /* IEEE80211_MODE_QUARTER */
725 };
726
727 /*
728  * Initialize the tables for a node.
729  */
730 static void
731 ath_rate_ctl_reset(struct ath_softc *sc, struct ieee80211_node *ni)
732 {
733 #define RATE(_ix)       (ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
734 #define DOT11RATE(_ix)  (rt->info[(_ix)].dot11Rate & IEEE80211_RATE_VAL)
735         struct ath_node *an = ATH_NODE(ni);
736         const struct ieee80211_txparam *tp = ni->ni_txparms;
737         struct sample_node *sn = ATH_NODE_SAMPLE(an);
738         const HAL_RATE_TABLE *rt = sc->sc_currates;
739 #ifdef IEEE80211_DEBUG
740         char ethstr[ETHER_ADDRSTRLEN + 1];
741 #endif
742         int x, y, srate, rix;
743
744         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
745
746         KASSERT(sc->sc_curmode < IEEE80211_MODE_MAX+2,
747             ("curmode %u", sc->sc_curmode));
748         sn->sched = mrr_schedules[sc->sc_curmode];
749         KASSERT(sn->sched != NULL,
750             ("no mrr schedule for mode %u", sc->sc_curmode));
751
752         sn->static_rix = -1;
753         if (tp != NULL && tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
754                 /*
755                  * A fixed rate is to be used; ucastrate is the IEEE code
756                  * for this rate (sans basic bit).  Check this against the
757                  * negotiated rate set for the node.  Note the fixed rate
758                  * may not be available for various reasons so we only
759                  * setup the static rate index if the lookup is successful.
760                  * XXX handle MCS
761                  */
762                 for (srate = ni->ni_rates.rs_nrates - 1; srate >= 0; srate--)
763                         if (RATE(srate) == tp->ucastrate) {
764                                 sn->static_rix = sc->sc_rixmap[tp->ucastrate];
765                                 break;
766                         }
767 #ifdef IEEE80211_DEBUG
768                         if (sn->static_rix == -1) {
769                                 IEEE80211_NOTE(ni->ni_vap,
770                                     IEEE80211_MSG_RATECTL, ni,
771                                     "%s: ucastrate %u not found, nrates %u",
772                                     __func__, tp->ucastrate,
773                                     ni->ni_rates.rs_nrates);
774                         }
775 #endif
776         }
777
778         /*
779          * Construct a bitmask of usable rates.  This has all
780          * negotiated rates minus those marked by the hal as
781          * to be ignored for doing rate control.
782          */
783         sn->ratemask = 0;
784         for (x = 0; x < ni->ni_rates.rs_nrates; x++) {
785                 rix = sc->sc_rixmap[RATE(x)];
786                 if (rix == 0xff)
787                         continue;
788                 /* skip rates marked broken by hal */
789                 if (!rt->info[rix].valid)
790                         continue;
791                 KASSERT(rix < SAMPLE_MAXRATES,
792                     ("rate %u has rix %d", RATE(x), rix));
793                 sn->ratemask |= 1<<rix;
794         }
795 #ifdef IEEE80211_DEBUG
796         if (ieee80211_msg(ni->ni_vap, IEEE80211_MSG_RATECTL)) {
797                 uint32_t mask;
798
799                 ieee80211_note(ni->ni_vap, "[%s] %s: size 1600 rate/tt",
800                     kether_ntoa(ni->ni_macaddr, ethstr), __func__);
801                 for (mask = sn->ratemask, rix = 0; mask != 0; mask >>= 1, rix++) {
802                         if ((mask & 1) == 0)
803                                 continue;
804                         kprintf(" %d/%d", DOT11RATE(rix) / 2,
805                             calc_usecs_unicast_packet(sc, 1600, rix, 0,0));
806                 }
807                 kprintf("\n");
808         }
809 #endif
810         for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
811                 int size = bin_to_size(y);
812                 uint32_t mask;
813
814                 sn->packets_sent[y] = 0;
815                 sn->current_sample_rix[y] = -1;
816                 sn->last_sample_rix[y] = 0;
817                 /* XXX start with first valid rate */
818                 sn->current_rix[y] = ffs(sn->ratemask)-1;
819                 
820                 /*
821                  * Initialize the statistics buckets; these are
822                  * indexed by the rate code index.
823                  */
824                 for (rix = 0, mask = sn->ratemask; mask != 0; rix++, mask >>= 1) {
825                         if ((mask & 1) == 0)            /* not a valid rate */
826                                 continue;
827                         sn->stats[y][rix].successive_failures = 0;
828                         sn->stats[y][rix].tries = 0;
829                         sn->stats[y][rix].total_packets = 0;
830                         sn->stats[y][rix].packets_acked = 0;
831                         sn->stats[y][rix].last_tx = 0;
832                         
833                         sn->stats[y][rix].perfect_tx_time =
834                             calc_usecs_unicast_packet(sc, size, rix, 0, 0);
835                         sn->stats[y][rix].average_tx_time =
836                             sn->stats[y][rix].perfect_tx_time;
837                 }
838         }
839 #if 0
840         /* XXX 0, num_rates-1 are wrong */
841         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_RATECTL, ni,
842             "%s: %d rates %d%sMbps (%dus)- %d%sMbps (%dus)", __func__, 
843             sn->num_rates,
844             DOT11RATE(0)/2, DOT11RATE(0) % 1 ? ".5" : "",
845             sn->stats[1][0].perfect_tx_time,
846             DOT11RATE(sn->num_rates-1)/2, DOT11RATE(sn->num_rates-1) % 1 ? ".5" : "",
847             sn->stats[1][sn->num_rates-1].perfect_tx_time
848         );
849 #endif
850         /* set the visible bit-rate */
851         if (sn->static_rix != -1)
852                 ni->ni_txrate = DOT11RATE(sn->static_rix);
853         else
854                 ni->ni_txrate = RATE(0);
855 #undef RATE
856 #undef DOT11RATE
857 }
858
859 static void
860 sample_stats(void *arg, struct ieee80211_node *ni)
861 {
862         struct ath_softc *sc = arg;
863         const HAL_RATE_TABLE *rt = sc->sc_currates;
864         struct sample_node *sn = ATH_NODE_SAMPLE(ATH_NODE(ni));
865         char ethstr[ETHER_ADDRSTRLEN + 1];
866         uint32_t mask;
867         int rix, y;
868
869         kprintf("\n[%s] refcnt %d static_rix %d ratemask 0x%x\n",
870             kether_ntoa(ni->ni_macaddr, ethstr), ieee80211_node_refcnt(ni),
871             sn->static_rix, sn->ratemask);
872         for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
873                 kprintf("[%4u] cur rix %d since switch: packets %d ticks %u\n",
874                     bin_to_size(y), sn->current_rix[y],
875                     sn->packets_since_switch[y], sn->ticks_since_switch[y]);
876                 kprintf("[%4u] last sample %d cur sample %d packets sent %d\n",
877                     bin_to_size(y), sn->last_sample_rix[y],
878                     sn->current_sample_rix[y], sn->packets_sent[y]);
879                 kprintf("[%4u] packets since sample %d sample tt %u\n",
880                     bin_to_size(y), sn->packets_since_sample[y],
881                     sn->sample_tt[y]);
882         }
883         for (mask = sn->ratemask, rix = 0; mask != 0; mask >>= 1, rix++) {
884                 if ((mask & 1) == 0)
885                                 continue;
886                 for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
887                         if (sn->stats[y][rix].total_packets == 0)
888                                 continue;
889                         kprintf("[%2u:%4u] %8d:%-8d (%3d%%) T %8d F %4d avg %5u last %u\n",
890                             (rt->info[rix].dot11Rate & IEEE80211_RATE_VAL)/2,
891                             bin_to_size(y),
892                             sn->stats[y][rix].total_packets,
893                             sn->stats[y][rix].packets_acked,
894                             (100*sn->stats[y][rix].packets_acked)/sn->stats[y][rix].total_packets,
895                             sn->stats[y][rix].tries,
896                             sn->stats[y][rix].successive_failures,
897                             sn->stats[y][rix].average_tx_time,
898                             ticks - sn->stats[y][rix].last_tx);
899                 }
900         }
901 }
902
903 static int
904 ath_rate_sysctl_stats(SYSCTL_HANDLER_ARGS)
905 {
906         struct ath_softc *sc = arg1;
907         struct ifnet *ifp;
908         struct ieee80211com *ic;
909         int error, v;
910
911         wlan_serialize_enter();
912         v = 0;
913         ifp = sc->sc_ifp;
914         ic = ifp->if_l2com;
915         error = sysctl_handle_int(oidp, &v, 0, req);
916         if (error == 0 && req->newptr)
917                 ieee80211_iterate_nodes(&ic->ic_sta, sample_stats, sc);
918         wlan_serialize_exit();
919         return error;
920 }
921
922 static int
923 ath_rate_sysctl_smoothing_rate(SYSCTL_HANDLER_ARGS)
924 {
925         struct sample_softc *ssc = arg1;
926         int rate, error;
927
928         wlan_serialize_enter();
929         rate = ssc->smoothing_rate;
930         error = sysctl_handle_int(oidp, &rate, 0, req);
931         if (error == 0 && req->newptr) {
932                 if (!(0 <= rate && rate < 100)) {
933                         error = EINVAL;
934                 } else {
935                         ssc->smoothing_rate = rate;
936                         ssc->smoothing_minpackets = 100 / (100 - rate);
937                 }
938         }
939         wlan_serialize_exit();
940         return error;
941 }
942
943 static int
944 ath_rate_sysctl_sample_rate(SYSCTL_HANDLER_ARGS)
945 {
946         struct sample_softc *ssc = arg1;
947         int rate, error;
948
949         wlan_serialize_enter();
950         rate = ssc->sample_rate;
951         error = sysctl_handle_int(oidp, &rate, 0, req);
952         if (error == 0 && req->newptr) {
953                 if (!(2 <= rate && rate <= 100))
954                         error = EINVAL;
955                 else
956                         ssc->sample_rate = rate;
957         }
958         wlan_serialize_exit();
959         return error;
960 }
961
962 static void
963 ath_rate_sysctlattach(struct ath_softc *sc, struct sample_softc *ssc)
964 {
965         struct sysctl_ctx_list *ctx;
966         struct sysctl_oid *tree;
967
968         ctx = &sc->sc_sysctl_ctx;
969         tree = sc->sc_sysctl_tree;
970         if (tree == NULL) {
971                 device_printf(sc->sc_dev, "can't add sysctl node\n");
972                 return;
973         }
974         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
975             "smoothing_rate", CTLTYPE_INT | CTLFLAG_RW, ssc, 0,
976             ath_rate_sysctl_smoothing_rate, "I",
977             "sample: smoothing rate for avg tx time (%%)");
978         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
979             "sample_rate", CTLTYPE_INT | CTLFLAG_RW, ssc, 0,
980             ath_rate_sysctl_sample_rate, "I",
981             "sample: percent air time devoted to sampling new rates (%%)");
982         /* XXX max_successive_failures, stale_failure_timeout, min_switch */
983         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
984             "sample_stats", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
985             ath_rate_sysctl_stats, "I", "sample: print statistics");
986 }
987
988 struct ath_ratectrl *
989 ath_rate_attach(struct ath_softc *sc)
990 {
991         struct sample_softc *ssc;
992         
993         ssc = kmalloc(sizeof(struct sample_softc), M_DEVBUF, M_NOWAIT|M_ZERO);
994         if (ssc == NULL)
995                 return NULL;
996         ssc->arc.arc_space = sizeof(struct sample_node);
997         ssc->smoothing_rate = 95;               /* ewma percentage ([0..99]) */
998         ssc->smoothing_minpackets = 100 / (100 - ssc->smoothing_rate);
999         ssc->sample_rate = 10;                  /* %time to try diff tx rates */
1000         ssc->max_successive_failures = 3;       /* threshold for rate sampling*/
1001         ssc->stale_failure_timeout = 10 * hz;   /* 10 seconds */
1002         ssc->min_switch = hz;                   /* 1 second */
1003         ath_rate_sysctlattach(sc, ssc);
1004         return &ssc->arc;
1005 }
1006
1007 void
1008 ath_rate_detach(struct ath_ratectrl *arc)
1009 {
1010         struct sample_softc *ssc = (struct sample_softc *) arc;
1011         
1012         kfree(ssc, M_DEVBUF);
1013 }
1014
1015 /*
1016  * Module glue.
1017  */
1018 static int
1019 sample_modevent(module_t mod, int type, void *unused)
1020 {
1021         int error;
1022
1023         wlan_serialize_enter();
1024
1025         switch (type) {
1026         case MOD_LOAD:
1027                 if (bootverbose) {
1028                         kprintf("ath_rate: <SampleRate bit-rate "
1029                                 "selection algorithm>\n");
1030                 }
1031                 error = 0;
1032                 break;
1033         case MOD_UNLOAD:
1034                 error = 0;
1035                 break;
1036         default:
1037                 error = EINVAL;
1038                 break;
1039         }
1040         wlan_serialize_exit();
1041
1042         return error;
1043 }
1044
1045 static moduledata_t sample_mod = {
1046         "ath_rate",
1047         sample_modevent,
1048         0
1049 };
1050 DECLARE_MODULE(ath_rate, sample_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
1051 MODULE_VERSION(ath_rate, 1);
1052 MODULE_DEPEND(ath_rate, ath_hal, 1, 1, 1);      /* Atheros HAL */
1053 MODULE_DEPEND(ath_rate, wlan, 1, 1, 1);