a48916d9050281420c1e6b5046622567d0a25e64
[dragonfly.git] / sys / dev / netif / ath / 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  */
37
38 #include <sys/cdefs.h>
39
40 /*
41  * John Bicket's SampleRate control algorithm.
42  */
43 #include "opt_ath.h"
44 #include "opt_inet.h"
45 #include "opt_wlan.h"
46 #include "opt_ah.h"
47
48 #include <sys/param.h>
49 #include <sys/systm.h> 
50 #include <sys/sysctl.h>
51 #include <sys/kernel.h>
52 #include <sys/lock.h>
53 #include <sys/malloc.h>
54 #include <sys/mutex.h>
55 #include <sys/errno.h>
56
57 #include <machine/bus.h>
58 #include <machine/resource.h>
59 #include <sys/bus.h>
60
61 #include <sys/socket.h>
62  
63 #include <net/if.h>
64 #include <net/if_var.h>
65 #include <net/if_media.h>
66 #include <net/if_arp.h>
67 #include <net/ethernet.h>               /* XXX for ether_sprintf */
68
69 #include <net80211/ieee80211_var.h>
70
71 #include <net/bpf.h>
72
73 #ifdef INET
74 #include <netinet/in.h> 
75 #include <netinet/if_ether.h>
76 #endif
77
78 #include <dev/ath/if_athvar.h>
79 #include <dev/ath/ath_rate/sample/sample.h>
80 #include <dev/ath/ath_hal/ah_desc.h>
81 #include <dev/ath/ath_rate/sample/tx_schedules.h>
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 static void     ath_rate_ctl_reset(struct ath_softc *, struct ieee80211_node *);
108
109 static __inline int
110 size_to_bin(int size) 
111 {
112 #if NUM_PACKET_SIZE_BINS > 1
113         if (size <= packet_size_bins[0])
114                 return 0;
115 #endif
116 #if NUM_PACKET_SIZE_BINS > 2
117         if (size <= packet_size_bins[1])
118                 return 1;
119 #endif
120 #if NUM_PACKET_SIZE_BINS > 3
121         if (size <= packet_size_bins[2])
122                 return 2;
123 #endif
124 #if NUM_PACKET_SIZE_BINS > 4
125 #error "add support for more packet sizes"
126 #endif
127         return NUM_PACKET_SIZE_BINS-1;
128 }
129
130 void
131 ath_rate_node_init(struct ath_softc *sc, struct ath_node *an)
132 {
133         /* NB: assumed to be zero'd by caller */
134 }
135
136 void
137 ath_rate_node_cleanup(struct ath_softc *sc, struct ath_node *an)
138 {
139 }
140
141 static int
142 dot11rate(const HAL_RATE_TABLE *rt, int rix)
143 {
144         if (rix < 0)
145                 return -1;
146         return rt->info[rix].phy == IEEE80211_T_HT ?
147             rt->info[rix].dot11Rate : (rt->info[rix].dot11Rate & IEEE80211_RATE_VAL) / 2;
148 }
149
150 static const char *
151 dot11rate_label(const HAL_RATE_TABLE *rt, int rix)
152 {
153         if (rix < 0)
154                 return "";
155         return rt->info[rix].phy == IEEE80211_T_HT ? "MCS" : "Mb ";
156 }
157
158 /*
159  * Return the rix with the lowest average_tx_time,
160  * or -1 if all the average_tx_times are 0.
161  */
162 static __inline int
163 pick_best_rate(struct ath_node *an, const HAL_RATE_TABLE *rt,
164     int size_bin, int require_acked_before)
165 {
166         struct sample_node *sn = ATH_NODE_SAMPLE(an);
167         int best_rate_rix, best_rate_tt, best_rate_pct;
168         uint64_t mask;
169         int rix, tt, pct;
170
171         best_rate_rix = 0;
172         best_rate_tt = 0;
173         best_rate_pct = 0;
174         for (mask = sn->ratemask, rix = 0; mask != 0; mask >>= 1, rix++) {
175                 if ((mask & 1) == 0)            /* not a supported rate */
176                         continue;
177
178                 /* Don't pick a non-HT rate for a HT node */
179                 if ((an->an_node.ni_flags & IEEE80211_NODE_HT) &&
180                     (rt->info[rix].phy != IEEE80211_T_HT)) {
181                         continue;
182                 }
183
184                 tt = sn->stats[size_bin][rix].average_tx_time;
185                 if (tt <= 0 ||
186                     (require_acked_before &&
187                      !sn->stats[size_bin][rix].packets_acked))
188                         continue;
189
190                 /* Calculate percentage if possible */
191                 if (sn->stats[size_bin][rix].total_packets > 0) {
192                         pct = sn->stats[size_bin][rix].ewma_pct;
193                 } else {
194                         /* XXX for now, assume 95% ok */
195                         pct = 95;
196                 }
197
198                 /* don't use a bit-rate that has been failing */
199                 if (sn->stats[size_bin][rix].successive_failures > 3)
200                         continue;
201
202                 /*
203                  * For HT, Don't use a bit rate that is much more
204                  * lossy than the best.
205                  *
206                  * XXX this isn't optimal; it's just designed to
207                  * eliminate rates that are going to be obviously
208                  * worse.
209                  */
210                 if (an->an_node.ni_flags & IEEE80211_NODE_HT) {
211                         if (best_rate_pct > (pct + 50))
212                                 continue;
213                 }
214
215                 /*
216                  * For non-MCS rates, use the current average txtime for
217                  * comparison.
218                  */
219                 if (! (an->an_node.ni_flags & IEEE80211_NODE_HT)) {
220                         if (best_rate_tt == 0 || tt <= best_rate_tt) {
221                                 best_rate_tt = tt;
222                                 best_rate_rix = rix;
223                                 best_rate_pct = pct;
224                         }
225                 }
226
227                 /*
228                  * Since 2 stream rates have slightly higher TX times,
229                  * allow a little bit of leeway. This should later
230                  * be abstracted out and properly handled.
231                  */
232                 if (an->an_node.ni_flags & IEEE80211_NODE_HT) {
233                         if (best_rate_tt == 0 || (tt * 8 <= best_rate_tt * 10)) {
234                                 best_rate_tt = tt;
235                                 best_rate_rix = rix;
236                                 best_rate_pct = pct;
237                         }
238                 }
239         }
240         return (best_rate_tt ? best_rate_rix : -1);
241 }
242
243 /*
244  * Pick a good "random" bit-rate to sample other than the current one.
245  */
246 static __inline int
247 pick_sample_rate(struct sample_softc *ssc , struct ath_node *an,
248     const HAL_RATE_TABLE *rt, int size_bin)
249 {
250 #define DOT11RATE(ix)   (rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
251 #define MCS(ix)         (rt->info[ix].dot11Rate | IEEE80211_RATE_MCS)
252         struct sample_node *sn = ATH_NODE_SAMPLE(an);
253         int current_rix, rix;
254         unsigned current_tt;
255         uint64_t mask;
256         
257         current_rix = sn->current_rix[size_bin];
258         if (current_rix < 0) {
259                 /* no successes yet, send at the lowest bit-rate */
260                 /* XXX should return MCS0 if HT */
261                 return 0;
262         }
263
264         current_tt = sn->stats[size_bin][current_rix].average_tx_time;
265
266         rix = sn->last_sample_rix[size_bin]+1;  /* next sample rate */
267         mask = sn->ratemask &~ ((uint64_t) 1<<current_rix);/* don't sample current rate */
268         while (mask != 0) {
269                 if ((mask & ((uint64_t) 1<<rix)) == 0) {        /* not a supported rate */
270         nextrate:
271                         if (++rix >= rt->rateCount)
272                                 rix = 0;
273                         continue;
274                 }
275
276                 /*
277                  * The following code stops trying to sample
278                  * non-MCS rates when speaking to an MCS node.
279                  * However, at least for CCK rates in 2.4GHz mode,
280                  * the non-MCS rates MAY actually provide better
281                  * PER at the very far edge of reception.
282                  *
283                  * However! Until ath_rate_form_aggr() grows
284                  * some logic to not form aggregates if the
285                  * selected rate is non-MCS, this won't work.
286                  *
287                  * So don't disable this code until you've taught
288                  * ath_rate_form_aggr() to drop out if any of
289                  * the selected rates are non-MCS.
290                  */
291 #if 1
292                 /* if the node is HT and the rate isn't HT, don't bother sample */
293                 if ((an->an_node.ni_flags & IEEE80211_NODE_HT) &&
294                     (rt->info[rix].phy != IEEE80211_T_HT)) {
295                         mask &= ~((uint64_t) 1<<rix);
296                         goto nextrate;
297                 }
298 #endif
299
300                 /* this bit-rate is always worse than the current one */
301                 if (sn->stats[size_bin][rix].perfect_tx_time > current_tt) {
302                         mask &= ~((uint64_t) 1<<rix);
303                         goto nextrate;
304                 }
305
306                 /* rarely sample bit-rates that fail a lot */
307                 if (sn->stats[size_bin][rix].successive_failures > ssc->max_successive_failures &&
308                     ticks - sn->stats[size_bin][rix].last_tx < ssc->stale_failure_timeout) {
309                         mask &= ~((uint64_t) 1<<rix);
310                         goto nextrate;
311                 }
312
313                 /*
314                  * For HT, only sample a few rates on either side of the
315                  * current rix; there's quite likely a lot of them.
316                  */
317                 if (an->an_node.ni_flags & IEEE80211_NODE_HT) {
318                         if (rix < (current_rix - 3) ||
319                             rix > (current_rix + 3)) {
320                                 mask &= ~((uint64_t) 1<<rix);
321                                 goto nextrate;
322                         }
323                 }
324
325                 /* Don't sample more than 2 rates higher for rates > 11M for non-HT rates */
326                 if (! (an->an_node.ni_flags & IEEE80211_NODE_HT)) {
327                         if (DOT11RATE(rix) > 2*11 && rix > current_rix + 2) {
328                                 mask &= ~((uint64_t) 1<<rix);
329                                 goto nextrate;
330                         }
331                 }
332
333                 sn->last_sample_rix[size_bin] = rix;
334                 return rix;
335         }
336         return current_rix;
337 #undef DOT11RATE
338 #undef  MCS
339 }
340
341 static int
342 ath_rate_get_static_rix(struct ath_softc *sc, const struct ieee80211_node *ni)
343 {
344 #define RATE(_ix)       (ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
345 #define DOT11RATE(_ix)  (rt->info[(_ix)].dot11Rate & IEEE80211_RATE_VAL)
346 #define MCS(_ix)        (ni->ni_htrates.rs_rates[_ix] | IEEE80211_RATE_MCS)
347         const struct ieee80211_txparam *tp = ni->ni_txparms;
348         int srate;
349
350         /* Check MCS rates */
351         for (srate = ni->ni_htrates.rs_nrates - 1; srate >= 0; srate--) {
352                 if (MCS(srate) == tp->ucastrate)
353                         return sc->sc_rixmap[tp->ucastrate];
354         }
355
356         /* Check legacy rates */
357         for (srate = ni->ni_rates.rs_nrates - 1; srate >= 0; srate--) {
358                 if (RATE(srate) == tp->ucastrate)
359                         return sc->sc_rixmap[tp->ucastrate];
360         }
361         return -1;
362 #undef  RATE
363 #undef  DOT11RATE
364 #undef  MCS
365 }
366
367 static void
368 ath_rate_update_static_rix(struct ath_softc *sc, struct ieee80211_node *ni)
369 {
370         struct ath_node *an = ATH_NODE(ni);
371         const struct ieee80211_txparam *tp = ni->ni_txparms;
372         struct sample_node *sn = ATH_NODE_SAMPLE(an);
373
374         if (tp != NULL && tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
375                 /*
376                  * A fixed rate is to be used; ucastrate is the IEEE code
377                  * for this rate (sans basic bit).  Check this against the
378                  * negotiated rate set for the node.  Note the fixed rate
379                  * may not be available for various reasons so we only
380                  * setup the static rate index if the lookup is successful.
381                  */
382                 sn->static_rix = ath_rate_get_static_rix(sc, ni);
383         } else {
384                 sn->static_rix = -1;
385         }
386 }
387
388 /*
389  * Pick a non-HT rate to begin using.
390  */
391 static int
392 ath_rate_pick_seed_rate_legacy(struct ath_softc *sc, struct ath_node *an,
393     int frameLen)
394 {
395 #define DOT11RATE(ix)   (rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
396 #define MCS(ix)         (rt->info[ix].dot11Rate | IEEE80211_RATE_MCS)
397 #define RATE(ix)        (DOT11RATE(ix) / 2)
398         int rix = -1;
399         const HAL_RATE_TABLE *rt = sc->sc_currates;
400         struct sample_node *sn = ATH_NODE_SAMPLE(an);
401         const int size_bin = size_to_bin(frameLen);
402
403         /* no packet has been sent successfully yet */
404         for (rix = rt->rateCount-1; rix > 0; rix--) {
405                 if ((sn->ratemask & ((uint64_t) 1<<rix)) == 0)
406                         continue;
407
408                 /* Skip HT rates */
409                 if (rt->info[rix].phy == IEEE80211_T_HT)
410                         continue;
411
412                 /*
413                  * Pick the highest rate <= 36 Mbps
414                  * that hasn't failed.
415                  */
416                 if (DOT11RATE(rix) <= 72 &&
417                     sn->stats[size_bin][rix].successive_failures == 0) {
418                         break;
419                 }
420         }
421         return rix;
422 #undef  RATE
423 #undef  MCS
424 #undef  DOT11RATE
425 }
426
427 /*
428  * Pick a HT rate to begin using.
429  *
430  * Don't use any non-HT rates; only consider HT rates.
431  */
432 static int
433 ath_rate_pick_seed_rate_ht(struct ath_softc *sc, struct ath_node *an,
434     int frameLen)
435 {
436 #define DOT11RATE(ix)   (rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
437 #define MCS(ix)         (rt->info[ix].dot11Rate | IEEE80211_RATE_MCS)
438 #define RATE(ix)        (DOT11RATE(ix) / 2)
439         int rix = -1, ht_rix = -1;
440         const HAL_RATE_TABLE *rt = sc->sc_currates;
441         struct sample_node *sn = ATH_NODE_SAMPLE(an);
442         const int size_bin = size_to_bin(frameLen);
443
444         /* no packet has been sent successfully yet */
445         for (rix = rt->rateCount-1; rix > 0; rix--) {
446                 /* Skip rates we can't use */
447                 if ((sn->ratemask & ((uint64_t) 1<<rix)) == 0)
448                         continue;
449
450                 /* Keep a copy of the last seen HT rate index */
451                 if (rt->info[rix].phy == IEEE80211_T_HT)
452                         ht_rix = rix;
453
454                 /* Skip non-HT rates */
455                 if (rt->info[rix].phy != IEEE80211_T_HT)
456                         continue;
457
458                 /*
459                  * Pick a medium-speed rate regardless of stream count
460                  * which has not seen any failures. Higher rates may fail;
461                  * we'll try them later.
462                  */
463                 if (((MCS(rix) & 0x7) <= 4) &&
464                     sn->stats[size_bin][rix].successive_failures == 0) {
465                         break;
466                 }
467         }
468
469         /*
470          * If all the MCS rates have successive failures, rix should be
471          * > 0; otherwise use the lowest MCS rix (hopefully MCS 0.)
472          */
473         return MAX(rix, ht_rix);
474 #undef  RATE
475 #undef  MCS
476 #undef  DOT11RATE
477 }
478
479
480 void
481 ath_rate_findrate(struct ath_softc *sc, struct ath_node *an,
482                   int shortPreamble, size_t frameLen,
483                   u_int8_t *rix0, int *try0, u_int8_t *txrate)
484 {
485 #define DOT11RATE(ix)   (rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
486 #define MCS(ix)         (rt->info[ix].dot11Rate | IEEE80211_RATE_MCS)
487 #define RATE(ix)        (DOT11RATE(ix) / 2)
488         struct sample_node *sn = ATH_NODE_SAMPLE(an);
489         struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
490         struct ifnet *ifp = sc->sc_ifp;
491         struct ieee80211com *ic = ifp->if_l2com;
492         const HAL_RATE_TABLE *rt = sc->sc_currates;
493         const int size_bin = size_to_bin(frameLen);
494         int rix, mrr, best_rix, change_rates;
495         unsigned average_tx_time;
496
497         ath_rate_update_static_rix(sc, &an->an_node);
498
499         if (sn->currates != sc->sc_currates) {
500                 device_printf(sc->sc_dev, "%s: currates != sc_currates!\n",
501                     __func__);
502                 rix = 0;
503                 *try0 = ATH_TXMAXTRY;
504                 goto done;
505         }
506
507         if (sn->static_rix != -1) {
508                 rix = sn->static_rix;
509                 *try0 = ATH_TXMAXTRY;
510                 goto done;
511         }
512
513         mrr = sc->sc_mrretry;
514         /* XXX check HT protmode too */
515         if (mrr && (ic->ic_flags & IEEE80211_F_USEPROT && !sc->sc_mrrprot))
516                 mrr = 0;
517
518         best_rix = pick_best_rate(an, rt, size_bin, !mrr);
519         if (best_rix >= 0) {
520                 average_tx_time = sn->stats[size_bin][best_rix].average_tx_time;
521         } else {
522                 average_tx_time = 0;
523         }
524         /*
525          * Limit the time measuring the performance of other tx
526          * rates to sample_rate% of the total transmission time.
527          */
528         if (sn->sample_tt[size_bin] < average_tx_time * (sn->packets_since_sample[size_bin]*ssc->sample_rate/100)) {
529                 rix = pick_sample_rate(ssc, an, rt, size_bin);
530                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
531                      &an->an_node, "att %d sample_tt %d size %u sample rate %d %s current rate %d %s",
532                      average_tx_time,
533                      sn->sample_tt[size_bin],
534                      bin_to_size(size_bin),
535                      dot11rate(rt, rix),
536                      dot11rate_label(rt, rix),
537                      dot11rate(rt, sn->current_rix[size_bin]),
538                      dot11rate_label(rt, sn->current_rix[size_bin]));
539                 if (rix != sn->current_rix[size_bin]) {
540                         sn->current_sample_rix[size_bin] = rix;
541                 } else {
542                         sn->current_sample_rix[size_bin] = -1;
543                 }
544                 sn->packets_since_sample[size_bin] = 0;
545         } else {
546                 change_rates = 0;
547                 if (!sn->packets_sent[size_bin] || best_rix == -1) {
548                         /* no packet has been sent successfully yet */
549                         change_rates = 1;
550                         if (an->an_node.ni_flags & IEEE80211_NODE_HT)
551                                 best_rix =
552                                     ath_rate_pick_seed_rate_ht(sc, an, frameLen);
553                         else
554                                 best_rix =
555                                     ath_rate_pick_seed_rate_legacy(sc, an, frameLen);
556                 } else if (sn->packets_sent[size_bin] < 20) {
557                         /* let the bit-rate switch quickly during the first few packets */
558                         IEEE80211_NOTE(an->an_node.ni_vap,
559                             IEEE80211_MSG_RATECTL, &an->an_node,
560                             "%s: switching quickly..", __func__);
561                         change_rates = 1;
562                 } else if (ticks - ssc->min_switch > sn->ticks_since_switch[size_bin]) {
563                         /* min_switch seconds have gone by */
564                         IEEE80211_NOTE(an->an_node.ni_vap,
565                             IEEE80211_MSG_RATECTL, &an->an_node,
566                             "%s: min_switch %d > ticks_since_switch %d..",
567                             __func__, ticks - ssc->min_switch, sn->ticks_since_switch[size_bin]);
568                         change_rates = 1;
569                 } else if ((! (an->an_node.ni_flags & IEEE80211_NODE_HT)) &&
570                     (2*average_tx_time < sn->stats[size_bin][sn->current_rix[size_bin]].average_tx_time)) {
571                         /* the current bit-rate is twice as slow as the best one */
572                         IEEE80211_NOTE(an->an_node.ni_vap,
573                             IEEE80211_MSG_RATECTL, &an->an_node,
574                             "%s: 2x att (= %d) < cur_rix att %d",
575                             __func__,
576                             2 * average_tx_time, sn->stats[size_bin][sn->current_rix[size_bin]].average_tx_time);
577                         change_rates = 1;
578                 } else if ((an->an_node.ni_flags & IEEE80211_NODE_HT)) {
579                         int cur_rix = sn->current_rix[size_bin];
580                         int cur_att = sn->stats[size_bin][cur_rix].average_tx_time;
581                         /*
582                          * If the node is HT, upgrade it if the MCS rate is
583                          * higher and the average tx time is within 20% of
584                          * the current rate. It can fail a little.
585                          *
586                          * This is likely not optimal!
587                          */
588 #if 0
589                         printf("cur rix/att %x/%d, best rix/att %x/%d\n",
590                             MCS(cur_rix), cur_att, MCS(best_rix), average_tx_time);
591 #endif
592                         if ((MCS(best_rix) > MCS(cur_rix)) &&
593                             (average_tx_time * 8) <= (cur_att * 10)) {
594                                 IEEE80211_NOTE(an->an_node.ni_vap,
595                                     IEEE80211_MSG_RATECTL, &an->an_node,
596                                     "%s: HT: best_rix 0x%d > cur_rix 0x%x, average_tx_time %d, cur_att %d",
597                                     __func__,
598                                     MCS(best_rix), MCS(cur_rix), average_tx_time, cur_att);
599                                 change_rates = 1;
600                         }
601                 }
602
603                 sn->packets_since_sample[size_bin]++;
604                 
605                 if (change_rates) {
606                         if (best_rix != sn->current_rix[size_bin]) {
607                                 IEEE80211_NOTE(an->an_node.ni_vap,
608                                     IEEE80211_MSG_RATECTL,
609                                     &an->an_node,
610 "%s: size %d switch rate %d (%d/%d) -> %d (%d/%d) after %d packets mrr %d",
611                                     __func__,
612                                     bin_to_size(size_bin),
613                                     RATE(sn->current_rix[size_bin]),
614                                     sn->stats[size_bin][sn->current_rix[size_bin]].average_tx_time,
615                                     sn->stats[size_bin][sn->current_rix[size_bin]].perfect_tx_time,
616                                     RATE(best_rix),
617                                     sn->stats[size_bin][best_rix].average_tx_time,
618                                     sn->stats[size_bin][best_rix].perfect_tx_time,
619                                     sn->packets_since_switch[size_bin],
620                                     mrr);
621                         }
622                         sn->packets_since_switch[size_bin] = 0;
623                         sn->current_rix[size_bin] = best_rix;
624                         sn->ticks_since_switch[size_bin] = ticks;
625                         /* 
626                          * Set the visible txrate for this node.
627                          */
628                         an->an_node.ni_txrate = (rt->info[best_rix].phy == IEEE80211_T_HT) ?  MCS(best_rix) : DOT11RATE(best_rix);
629                 }
630                 rix = sn->current_rix[size_bin];
631                 sn->packets_since_switch[size_bin]++;
632         }
633         *try0 = mrr ? sn->sched[rix].t0 : ATH_TXMAXTRY;
634 done:
635
636         /*
637          * This bug totally sucks and should be fixed.
638          *
639          * For now though, let's not panic, so we can start to figure
640          * out how to better reproduce it.
641          */
642         if (rix < 0 || rix >= rt->rateCount) {
643                 printf("%s: ERROR: rix %d out of bounds (rateCount=%d)\n",
644                     __func__,
645                     rix,
646                     rt->rateCount);
647                     rix = 0;    /* XXX just default for now */
648         }
649         KASSERT(rix >= 0 && rix < rt->rateCount, ("rix is %d", rix));
650
651         *rix0 = rix;
652         *txrate = rt->info[rix].rateCode
653                 | (shortPreamble ? rt->info[rix].shortPreamble : 0);
654         sn->packets_sent[size_bin]++;
655 #undef DOT11RATE
656 #undef MCS
657 #undef RATE
658 }
659
660 /*
661  * Get the TX rates. Don't fiddle with short preamble flags for them;
662  * the caller can do that.
663  */
664 void
665 ath_rate_getxtxrates(struct ath_softc *sc, struct ath_node *an,
666     uint8_t rix0, struct ath_rc_series *rc)
667 {
668         struct sample_node *sn = ATH_NODE_SAMPLE(an);
669         const struct txschedule *sched = &sn->sched[rix0];
670
671         KASSERT(rix0 == sched->r0, ("rix0 (%x) != sched->r0 (%x)!\n",
672             rix0, sched->r0));
673
674         rc[0].flags = rc[1].flags = rc[2].flags = rc[3].flags = 0;
675
676         rc[0].rix = sched->r0;
677         rc[1].rix = sched->r1;
678         rc[2].rix = sched->r2;
679         rc[3].rix = sched->r3;
680
681         rc[0].tries = sched->t0;
682         rc[1].tries = sched->t1;
683         rc[2].tries = sched->t2;
684         rc[3].tries = sched->t3;
685 }
686
687 void
688 ath_rate_setupxtxdesc(struct ath_softc *sc, struct ath_node *an,
689                       struct ath_desc *ds, int shortPreamble, u_int8_t rix)
690 {
691         struct sample_node *sn = ATH_NODE_SAMPLE(an);
692         const struct txschedule *sched = &sn->sched[rix];
693         const HAL_RATE_TABLE *rt = sc->sc_currates;
694         uint8_t rix1, s1code, rix2, s2code, rix3, s3code;
695
696         /* XXX precalculate short preamble tables */
697         rix1 = sched->r1;
698         s1code = rt->info[rix1].rateCode
699                | (shortPreamble ? rt->info[rix1].shortPreamble : 0);
700         rix2 = sched->r2;
701         s2code = rt->info[rix2].rateCode
702                | (shortPreamble ? rt->info[rix2].shortPreamble : 0);
703         rix3 = sched->r3;
704         s3code = rt->info[rix3].rateCode
705                | (shortPreamble ? rt->info[rix3].shortPreamble : 0);
706         ath_hal_setupxtxdesc(sc->sc_ah, ds,
707             s1code, sched->t1,          /* series 1 */
708             s2code, sched->t2,          /* series 2 */
709             s3code, sched->t3);         /* series 3 */
710 }
711
712 static void
713 update_stats(struct ath_softc *sc, struct ath_node *an, 
714                   int frame_size,
715                   int rix0, int tries0,
716                   int rix1, int tries1,
717                   int rix2, int tries2,
718                   int rix3, int tries3,
719                   int short_tries, int tries, int status,
720                   int nframes, int nbad)
721 {
722         struct sample_node *sn = ATH_NODE_SAMPLE(an);
723         struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
724 #ifdef IEEE80211_DEBUG
725         const HAL_RATE_TABLE *rt = sc->sc_currates;
726 #endif
727         const int size_bin = size_to_bin(frame_size);
728         const int size = bin_to_size(size_bin);
729         int tt, tries_so_far;
730         int is_ht40 = (an->an_node.ni_chw == 40);
731         int pct;
732
733         if (!IS_RATE_DEFINED(sn, rix0))
734                 return;
735         tt = calc_usecs_unicast_packet(sc, size, rix0, short_tries,
736                 MIN(tries0, tries) - 1, is_ht40);
737         tries_so_far = tries0;
738
739         if (tries1 && tries_so_far < tries) {
740                 if (!IS_RATE_DEFINED(sn, rix1))
741                         return;
742                 tt += calc_usecs_unicast_packet(sc, size, rix1, short_tries,
743                         MIN(tries1 + tries_so_far, tries) - tries_so_far - 1, is_ht40);
744                 tries_so_far += tries1;
745         }
746
747         if (tries2 && tries_so_far < tries) {
748                 if (!IS_RATE_DEFINED(sn, rix2))
749                         return;
750                 tt += calc_usecs_unicast_packet(sc, size, rix2, short_tries,
751                         MIN(tries2 + tries_so_far, tries) - tries_so_far - 1, is_ht40);
752                 tries_so_far += tries2;
753         }
754
755         if (tries3 && tries_so_far < tries) {
756                 if (!IS_RATE_DEFINED(sn, rix3))
757                         return;
758                 tt += calc_usecs_unicast_packet(sc, size, rix3, short_tries,
759                         MIN(tries3 + tries_so_far, tries) - tries_so_far - 1, is_ht40);
760         }
761
762         if (sn->stats[size_bin][rix0].total_packets < ssc->smoothing_minpackets) {
763                 /* just average the first few packets */
764                 int avg_tx = sn->stats[size_bin][rix0].average_tx_time;
765                 int packets = sn->stats[size_bin][rix0].total_packets;
766                 sn->stats[size_bin][rix0].average_tx_time = (tt+(avg_tx*packets))/(packets+nframes);
767         } else {
768                 /* use a ewma */
769                 sn->stats[size_bin][rix0].average_tx_time = 
770                         ((sn->stats[size_bin][rix0].average_tx_time * ssc->smoothing_rate) + 
771                          (tt * (100 - ssc->smoothing_rate))) / 100;
772         }
773         
774         /*
775          * XXX Don't mark the higher bit rates as also having failed; as this
776          * unfortunately stops those rates from being tasted when trying to
777          * TX. This happens with 11n aggregation.
778          */
779         if (nframes == nbad) {
780 #if 0
781                 int y;
782 #endif
783                 sn->stats[size_bin][rix0].successive_failures += nbad;
784 #if 0
785                 for (y = size_bin+1; y < NUM_PACKET_SIZE_BINS; y++) {
786                         /*
787                          * Also say larger packets failed since we
788                          * assume if a small packet fails at a
789                          * bit-rate then a larger one will also.
790                          */
791                         sn->stats[y][rix0].successive_failures += nbad;
792                         sn->stats[y][rix0].last_tx = ticks;
793                         sn->stats[y][rix0].tries += tries;
794                         sn->stats[y][rix0].total_packets += nframes;
795                 }
796 #endif
797         } else {
798                 sn->stats[size_bin][rix0].packets_acked += (nframes - nbad);
799                 sn->stats[size_bin][rix0].successive_failures = 0;
800         }
801         sn->stats[size_bin][rix0].tries += tries;
802         sn->stats[size_bin][rix0].last_tx = ticks;
803         sn->stats[size_bin][rix0].total_packets += nframes;
804
805         /* update EWMA for this rix */
806
807         /* Calculate percentage based on current rate */
808         if (nframes == 0)
809                 nframes = nbad = 1;
810         pct = ((nframes - nbad) * 1000) / nframes;
811
812         if (sn->stats[size_bin][rix0].total_packets <
813             ssc->smoothing_minpackets) {
814                 /* just average the first few packets */
815                 int a_pct = (sn->stats[size_bin][rix0].packets_acked * 1000) /
816                     (sn->stats[size_bin][rix0].total_packets);
817                 sn->stats[size_bin][rix0].ewma_pct = a_pct;
818         } else {
819                 /* use a ewma */
820                 sn->stats[size_bin][rix0].ewma_pct =
821                         ((sn->stats[size_bin][rix0].ewma_pct * ssc->smoothing_rate) +
822                          (pct * (100 - ssc->smoothing_rate))) / 100;
823         }
824
825
826         if (rix0 == sn->current_sample_rix[size_bin]) {
827                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
828                    &an->an_node,
829 "%s: size %d %s sample rate %d %s tries (%d/%d) tt %d avg_tt (%d/%d) nfrm %d nbad %d", 
830                     __func__, 
831                     size,
832                     status ? "FAIL" : "OK",
833                     dot11rate(rt, rix0),
834                     dot11rate_label(rt, rix0),
835                     short_tries, tries, tt, 
836                     sn->stats[size_bin][rix0].average_tx_time,
837                     sn->stats[size_bin][rix0].perfect_tx_time,
838                     nframes, nbad);
839                 sn->sample_tt[size_bin] = tt;
840                 sn->current_sample_rix[size_bin] = -1;
841         }
842 }
843
844 static void
845 badrate(struct ifnet *ifp, int series, int hwrate, int tries, int status)
846 {
847         if_printf(ifp, "bad series%d hwrate 0x%x, tries %u ts_status 0x%x\n",
848             series, hwrate, tries, status);
849 }
850
851 void
852 ath_rate_tx_complete(struct ath_softc *sc, struct ath_node *an,
853         const struct ath_rc_series *rc, const struct ath_tx_status *ts,
854         int frame_size, int nframes, int nbad)
855 {
856         struct ifnet *ifp = sc->sc_ifp;
857         struct ieee80211com *ic = ifp->if_l2com;
858         struct sample_node *sn = ATH_NODE_SAMPLE(an);
859         int final_rix, short_tries, long_tries;
860         const HAL_RATE_TABLE *rt = sc->sc_currates;
861         int status = ts->ts_status;
862         int mrr;
863
864         final_rix = rt->rateCodeToIndex[ts->ts_rate];
865         short_tries = ts->ts_shortretry;
866         long_tries = ts->ts_longretry + 1;
867
868         if (nframes == 0) {
869                 device_printf(sc->sc_dev, "%s: nframes=0?\n", __func__);
870                 return;
871         }
872
873         if (frame_size == 0)                /* NB: should not happen */
874                 frame_size = 1500;
875
876         if (sn->ratemask == 0) {
877                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
878                     &an->an_node,
879                     "%s: size %d %s rate/try %d/%d no rates yet", 
880                     __func__,
881                     bin_to_size(size_to_bin(frame_size)),
882                     status ? "FAIL" : "OK",
883                     short_tries, long_tries);
884                 return;
885         }
886         mrr = sc->sc_mrretry;
887         /* XXX check HT protmode too */
888         if (mrr && (ic->ic_flags & IEEE80211_F_USEPROT && !sc->sc_mrrprot))
889                 mrr = 0;
890
891         if (!mrr || ts->ts_finaltsi == 0) {
892                 if (!IS_RATE_DEFINED(sn, final_rix)) {
893                         device_printf(sc->sc_dev, "%s: ts_rate=%d ts_finaltsi=%d\n",
894                             __func__, ts->ts_rate, ts->ts_finaltsi);
895                         badrate(ifp, 0, ts->ts_rate, long_tries, status);
896                         return;
897                 }
898                 /*
899                  * Only one rate was used; optimize work.
900                  */
901                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
902                      &an->an_node, "%s: size %d (%d bytes) %s rate/short/long %d %s/%d/%d nframes/nbad [%d/%d]",
903                      __func__,
904                      bin_to_size(size_to_bin(frame_size)),
905                      frame_size,
906                      status ? "FAIL" : "OK",
907                      dot11rate(rt, final_rix), dot11rate_label(rt, final_rix),
908                      short_tries, long_tries, nframes, nbad);
909                 update_stats(sc, an, frame_size, 
910                              final_rix, long_tries,
911                              0, 0,
912                              0, 0,
913                              0, 0,
914                              short_tries, long_tries, status,
915                              nframes, nbad);
916
917         } else {
918                 int finalTSIdx = ts->ts_finaltsi;
919                 int i;
920
921                 /*
922                  * Process intermediate rates that failed.
923                  */
924
925                 IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
926                     &an->an_node,
927 "%s: size %d (%d bytes) finaltsidx %d short %d long %d %s rate/try [%d %s/%d %d %s/%d %d %s/%d %d %s/%d] nframes/nbad [%d/%d]", 
928                      __func__,
929                      bin_to_size(size_to_bin(frame_size)),
930                      frame_size,
931                      finalTSIdx,
932                      short_tries,
933                      long_tries,
934                      status ? "FAIL" : "OK",
935                      dot11rate(rt, rc[0].rix),
936                       dot11rate_label(rt, rc[0].rix), rc[0].tries,
937                      dot11rate(rt, rc[1].rix),
938                       dot11rate_label(rt, rc[1].rix), rc[1].tries,
939                      dot11rate(rt, rc[2].rix),
940                       dot11rate_label(rt, rc[2].rix), rc[2].tries,
941                      dot11rate(rt, rc[3].rix),
942                       dot11rate_label(rt, rc[3].rix), rc[3].tries,
943                      nframes, nbad);
944
945                 for (i = 0; i < 4; i++) {
946                         if (rc[i].tries && !IS_RATE_DEFINED(sn, rc[i].rix))
947                                 badrate(ifp, 0, rc[i].ratecode, rc[i].tries,
948                                     status);
949                 }
950
951                 /*
952                  * NB: series > 0 are not penalized for failure
953                  * based on the try counts under the assumption
954                  * that losses are often bursty and since we
955                  * sample higher rates 1 try at a time doing so
956                  * may unfairly penalize them.
957                  */
958                 if (rc[0].tries) {
959                         update_stats(sc, an, frame_size,
960                                      rc[0].rix, rc[0].tries,
961                                      rc[1].rix, rc[1].tries,
962                                      rc[2].rix, rc[2].tries,
963                                      rc[3].rix, rc[3].tries,
964                                      short_tries, long_tries,
965                                      long_tries > rc[0].tries,
966                                      nframes, nbad);
967                         long_tries -= rc[0].tries;
968                 }
969                 
970                 if (rc[1].tries && finalTSIdx > 0) {
971                         update_stats(sc, an, frame_size,
972                                      rc[1].rix, rc[1].tries,
973                                      rc[2].rix, rc[2].tries,
974                                      rc[3].rix, rc[3].tries,
975                                      0, 0,
976                                      short_tries, long_tries,
977                                      status,
978                                      nframes, nbad);
979                         long_tries -= rc[1].tries;
980                 }
981
982                 if (rc[2].tries && finalTSIdx > 1) {
983                         update_stats(sc, an, frame_size,
984                                      rc[2].rix, rc[2].tries,
985                                      rc[3].rix, rc[3].tries,
986                                      0, 0,
987                                      0, 0,
988                                      short_tries, long_tries,
989                                      status,
990                                      nframes, nbad);
991                         long_tries -= rc[2].tries;
992                 }
993
994                 if (rc[3].tries && finalTSIdx > 2) {
995                         update_stats(sc, an, frame_size,
996                                      rc[3].rix, rc[3].tries,
997                                      0, 0,
998                                      0, 0,
999                                      0, 0,
1000                                      short_tries, long_tries,
1001                                      status,
1002                                      nframes, nbad);
1003                 }
1004         }
1005 }
1006
1007 void
1008 ath_rate_newassoc(struct ath_softc *sc, struct ath_node *an, int isnew)
1009 {
1010         if (isnew)
1011                 ath_rate_ctl_reset(sc, &an->an_node);
1012 }
1013
1014 static const struct txschedule *mrr_schedules[IEEE80211_MODE_MAX+2] = {
1015         NULL,           /* IEEE80211_MODE_AUTO */
1016         series_11a,     /* IEEE80211_MODE_11A */
1017         series_11g,     /* IEEE80211_MODE_11B */
1018         series_11g,     /* IEEE80211_MODE_11G */
1019         NULL,           /* IEEE80211_MODE_FH */
1020         series_11a,     /* IEEE80211_MODE_TURBO_A */
1021         series_11g,     /* IEEE80211_MODE_TURBO_G */
1022         series_11a,     /* IEEE80211_MODE_STURBO_A */
1023         series_11na,    /* IEEE80211_MODE_11NA */
1024         series_11ng,    /* IEEE80211_MODE_11NG */
1025         series_half,    /* IEEE80211_MODE_HALF */
1026         series_quarter, /* IEEE80211_MODE_QUARTER */
1027 };
1028
1029 /*
1030  * Initialize the tables for a node.
1031  */
1032 static void
1033 ath_rate_ctl_reset(struct ath_softc *sc, struct ieee80211_node *ni)
1034 {
1035 #define RATE(_ix)       (ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
1036 #define DOT11RATE(_ix)  (rt->info[(_ix)].dot11Rate & IEEE80211_RATE_VAL)
1037 #define MCS(_ix)        (ni->ni_htrates.rs_rates[_ix] | IEEE80211_RATE_MCS)
1038         struct ath_node *an = ATH_NODE(ni);
1039         struct sample_node *sn = ATH_NODE_SAMPLE(an);
1040         const HAL_RATE_TABLE *rt = sc->sc_currates;
1041         int x, y, rix;
1042
1043         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
1044
1045         KASSERT(sc->sc_curmode < IEEE80211_MODE_MAX+2,
1046             ("curmode %u", sc->sc_curmode));
1047
1048         sn->sched = mrr_schedules[sc->sc_curmode];
1049         KASSERT(sn->sched != NULL,
1050             ("no mrr schedule for mode %u", sc->sc_curmode));
1051
1052         sn->static_rix = -1;
1053         ath_rate_update_static_rix(sc, ni);
1054
1055         sn->currates = sc->sc_currates;
1056
1057         /*
1058          * Construct a bitmask of usable rates.  This has all
1059          * negotiated rates minus those marked by the hal as
1060          * to be ignored for doing rate control.
1061          */
1062         sn->ratemask = 0;
1063         /* MCS rates */
1064         if (ni->ni_flags & IEEE80211_NODE_HT) {
1065                 for (x = 0; x < ni->ni_htrates.rs_nrates; x++) {
1066                         rix = sc->sc_rixmap[MCS(x)];
1067                         if (rix == 0xff)
1068                                 continue;
1069                         /* skip rates marked broken by hal */
1070                         if (!rt->info[rix].valid)
1071                                 continue;
1072                         KASSERT(rix < SAMPLE_MAXRATES,
1073                             ("mcs %u has rix %d", MCS(x), rix));
1074                         sn->ratemask |= (uint64_t) 1<<rix;
1075                 }
1076         }
1077
1078         /* Legacy rates */
1079         for (x = 0; x < ni->ni_rates.rs_nrates; x++) {
1080                 rix = sc->sc_rixmap[RATE(x)];
1081                 if (rix == 0xff)
1082                         continue;
1083                 /* skip rates marked broken by hal */
1084                 if (!rt->info[rix].valid)
1085                         continue;
1086                 KASSERT(rix < SAMPLE_MAXRATES,
1087                     ("rate %u has rix %d", RATE(x), rix));
1088                 sn->ratemask |= (uint64_t) 1<<rix;
1089         }
1090 #ifdef IEEE80211_DEBUG
1091         if (ieee80211_msg(ni->ni_vap, IEEE80211_MSG_RATECTL)) {
1092                 uint64_t mask;
1093
1094                 ieee80211_note(ni->ni_vap, "[%6D] %s: size 1600 rate/tt",
1095                     ni->ni_macaddr, ":", __func__);
1096                 for (mask = sn->ratemask, rix = 0; mask != 0; mask >>= 1, rix++) {
1097                         if ((mask & 1) == 0)
1098                                 continue;
1099                         printf(" %d %s/%d", dot11rate(rt, rix), dot11rate_label(rt, rix),
1100                             calc_usecs_unicast_packet(sc, 1600, rix, 0,0,
1101                                 (ni->ni_chw == 40)));
1102                 }
1103                 printf("\n");
1104         }
1105 #endif
1106         for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
1107                 int size = bin_to_size(y);
1108                 uint64_t mask;
1109
1110                 sn->packets_sent[y] = 0;
1111                 sn->current_sample_rix[y] = -1;
1112                 sn->last_sample_rix[y] = 0;
1113                 /* XXX start with first valid rate */
1114                 sn->current_rix[y] = ffs(sn->ratemask)-1;
1115                 
1116                 /*
1117                  * Initialize the statistics buckets; these are
1118                  * indexed by the rate code index.
1119                  */
1120                 for (rix = 0, mask = sn->ratemask; mask != 0; rix++, mask >>= 1) {
1121                         if ((mask & 1) == 0)            /* not a valid rate */
1122                                 continue;
1123                         sn->stats[y][rix].successive_failures = 0;
1124                         sn->stats[y][rix].tries = 0;
1125                         sn->stats[y][rix].total_packets = 0;
1126                         sn->stats[y][rix].packets_acked = 0;
1127                         sn->stats[y][rix].last_tx = 0;
1128                         sn->stats[y][rix].ewma_pct = 0;
1129                         
1130                         sn->stats[y][rix].perfect_tx_time =
1131                             calc_usecs_unicast_packet(sc, size, rix, 0, 0,
1132                             (ni->ni_chw == 40));
1133                         sn->stats[y][rix].average_tx_time =
1134                             sn->stats[y][rix].perfect_tx_time;
1135                 }
1136         }
1137 #if 0
1138         /* XXX 0, num_rates-1 are wrong */
1139         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_RATECTL, ni,
1140             "%s: %d rates %d%sMbps (%dus)- %d%sMbps (%dus)", __func__, 
1141             sn->num_rates,
1142             DOT11RATE(0)/2, DOT11RATE(0) % 1 ? ".5" : "",
1143             sn->stats[1][0].perfect_tx_time,
1144             DOT11RATE(sn->num_rates-1)/2, DOT11RATE(sn->num_rates-1) % 1 ? ".5" : "",
1145             sn->stats[1][sn->num_rates-1].perfect_tx_time
1146         );
1147 #endif
1148         /* set the visible bit-rate */
1149         if (sn->static_rix != -1)
1150                 ni->ni_txrate = DOT11RATE(sn->static_rix);
1151         else
1152                 ni->ni_txrate = RATE(0);
1153 #undef RATE
1154 #undef DOT11RATE
1155 }
1156
1157 /*
1158  * Fetch the statistics for the given node.
1159  *
1160  * The ieee80211 node must be referenced and unlocked, however the ath_node
1161  * must be locked.
1162  *
1163  * The main difference here is that we convert the rate indexes
1164  * to 802.11 rates, or the userland output won't make much sense
1165  * as it has no access to the rix table.
1166  */
1167 int
1168 ath_rate_fetch_node_stats(struct ath_softc *sc, struct ath_node *an,
1169     struct ath_rateioctl *rs)
1170 {
1171         struct sample_node *sn = ATH_NODE_SAMPLE(an);
1172         const HAL_RATE_TABLE *rt = sc->sc_currates;
1173         struct ath_rateioctl_tlv av;
1174         struct ath_rateioctl_rt *tv;
1175         int y;
1176         int o = 0;
1177
1178         ATH_NODE_LOCK_ASSERT(an);
1179
1180         /*
1181          * Ensure there's enough space for the statistics.
1182          */
1183         if (rs->len <
1184             sizeof(struct ath_rateioctl_tlv) +
1185             sizeof(struct ath_rateioctl_rt) +
1186             sizeof(struct ath_rateioctl_tlv) +
1187             sizeof(struct sample_node)) {
1188                 device_printf(sc->sc_dev, "%s: len=%d, too short\n",
1189                     __func__,
1190                     rs->len);
1191                 return (EINVAL);
1192         }
1193
1194         /*
1195          * Take a temporary copy of the sample node state so we can
1196          * modify it before we copy it.
1197          */
1198         tv = malloc(sizeof(struct ath_rateioctl_rt), M_TEMP,
1199             M_NOWAIT | M_ZERO);
1200         if (tv == NULL) {
1201                 return (ENOMEM);
1202         }
1203
1204         /*
1205          * Populate the rate table mapping TLV.
1206          */
1207         tv->nentries = rt->rateCount;
1208         for (y = 0; y < rt->rateCount; y++) {
1209                 tv->ratecode[y] = rt->info[y].dot11Rate & IEEE80211_RATE_VAL;
1210                 if (rt->info[y].phy == IEEE80211_T_HT)
1211                         tv->ratecode[y] |= IEEE80211_RATE_MCS;
1212         }
1213
1214         o = 0;
1215         /*
1216          * First TLV - rate code mapping
1217          */
1218         av.tlv_id = ATH_RATE_TLV_RATETABLE;
1219         av.tlv_len = sizeof(struct ath_rateioctl_rt);
1220         copyout(&av, rs->buf + o, sizeof(struct ath_rateioctl_tlv));
1221         o += sizeof(struct ath_rateioctl_tlv);
1222         copyout(tv, rs->buf + o, sizeof(struct ath_rateioctl_rt));
1223         o += sizeof(struct ath_rateioctl_rt);
1224
1225         /*
1226          * Second TLV - sample node statistics
1227          */
1228         av.tlv_id = ATH_RATE_TLV_SAMPLENODE;
1229         av.tlv_len = sizeof(struct sample_node);
1230         copyout(&av, rs->buf + o, sizeof(struct ath_rateioctl_tlv));
1231         o += sizeof(struct ath_rateioctl_tlv);
1232
1233         /*
1234          * Copy the statistics over to the provided buffer.
1235          */
1236         copyout(sn, rs->buf + o, sizeof(struct sample_node));
1237         o += sizeof(struct sample_node);
1238
1239         free(tv, M_TEMP);
1240
1241         return (0);
1242 }
1243
1244 static void
1245 sample_stats(void *arg, struct ieee80211_node *ni)
1246 {
1247         struct ath_softc *sc = arg;
1248         const HAL_RATE_TABLE *rt = sc->sc_currates;
1249         struct sample_node *sn = ATH_NODE_SAMPLE(ATH_NODE(ni));
1250         uint64_t mask;
1251         int rix, y;
1252
1253         printf("\n[%s] refcnt %d static_rix (%d %s) ratemask 0x%jx\n",
1254             ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni),
1255             dot11rate(rt, sn->static_rix),
1256             dot11rate_label(rt, sn->static_rix),
1257             (uintmax_t)sn->ratemask);
1258         for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
1259                 printf("[%4u] cur rix %d (%d %s) since switch: packets %d ticks %u\n",
1260                     bin_to_size(y), sn->current_rix[y],
1261                     dot11rate(rt, sn->current_rix[y]),
1262                     dot11rate_label(rt, sn->current_rix[y]),
1263                     sn->packets_since_switch[y], sn->ticks_since_switch[y]);
1264                 printf("[%4u] last sample (%d %s) cur sample (%d %s) packets sent %d\n",
1265                     bin_to_size(y),
1266                     dot11rate(rt, sn->last_sample_rix[y]),
1267                     dot11rate_label(rt, sn->last_sample_rix[y]),
1268                     dot11rate(rt, sn->current_sample_rix[y]),
1269                     dot11rate_label(rt, sn->current_sample_rix[y]),
1270                     sn->packets_sent[y]);
1271                 printf("[%4u] packets since sample %d sample tt %u\n",
1272                     bin_to_size(y), sn->packets_since_sample[y],
1273                     sn->sample_tt[y]);
1274         }
1275         for (mask = sn->ratemask, rix = 0; mask != 0; mask >>= 1, rix++) {
1276                 if ((mask & 1) == 0)
1277                                 continue;
1278                 for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
1279                         if (sn->stats[y][rix].total_packets == 0)
1280                                 continue;
1281                         printf("[%2u %s:%4u] %8ju:%-8ju (%3d%%) (EWMA %3d.%1d%%) T %8ju F %4d avg %5u last %u\n",
1282                             dot11rate(rt, rix), dot11rate_label(rt, rix),
1283                             bin_to_size(y),
1284                             (uintmax_t) sn->stats[y][rix].total_packets,
1285                             (uintmax_t) sn->stats[y][rix].packets_acked,
1286                             (int) ((sn->stats[y][rix].packets_acked * 100ULL) /
1287                              sn->stats[y][rix].total_packets),
1288                             sn->stats[y][rix].ewma_pct / 10,
1289                             sn->stats[y][rix].ewma_pct % 10,
1290                             (uintmax_t) sn->stats[y][rix].tries,
1291                             sn->stats[y][rix].successive_failures,
1292                             sn->stats[y][rix].average_tx_time,
1293                             ticks - sn->stats[y][rix].last_tx);
1294                 }
1295         }
1296 }
1297
1298 static int
1299 ath_rate_sysctl_stats(SYSCTL_HANDLER_ARGS)
1300 {
1301         struct ath_softc *sc = arg1;
1302         struct ifnet *ifp = sc->sc_ifp;
1303         struct ieee80211com *ic = ifp->if_l2com;
1304         int error, v;
1305
1306         v = 0;
1307         error = sysctl_handle_int(oidp, &v, 0, req);
1308         if (error || !req->newptr)
1309                 return error;
1310         ieee80211_iterate_nodes(&ic->ic_sta, sample_stats, sc);
1311         return 0;
1312 }
1313
1314 static int
1315 ath_rate_sysctl_smoothing_rate(SYSCTL_HANDLER_ARGS)
1316 {
1317         struct sample_softc *ssc = arg1;
1318         int rate, error;
1319
1320         rate = ssc->smoothing_rate;
1321         error = sysctl_handle_int(oidp, &rate, 0, req);
1322         if (error || !req->newptr)
1323                 return error;
1324         if (!(0 <= rate && rate < 100))
1325                 return EINVAL;
1326         ssc->smoothing_rate = rate;
1327         ssc->smoothing_minpackets = 100 / (100 - rate);
1328         return 0;
1329 }
1330
1331 static int
1332 ath_rate_sysctl_sample_rate(SYSCTL_HANDLER_ARGS)
1333 {
1334         struct sample_softc *ssc = arg1;
1335         int rate, error;
1336
1337         rate = ssc->sample_rate;
1338         error = sysctl_handle_int(oidp, &rate, 0, req);
1339         if (error || !req->newptr)
1340                 return error;
1341         if (!(2 <= rate && rate <= 100))
1342                 return EINVAL;
1343         ssc->sample_rate = rate;
1344         return 0;
1345 }
1346
1347 static void
1348 ath_rate_sysctlattach(struct ath_softc *sc, struct sample_softc *ssc)
1349 {
1350         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
1351         struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
1352
1353         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
1354             "smoothing_rate", CTLTYPE_INT | CTLFLAG_RW, ssc, 0,
1355             ath_rate_sysctl_smoothing_rate, "I",
1356             "sample: smoothing rate for avg tx time (%%)");
1357         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
1358             "sample_rate", CTLTYPE_INT | CTLFLAG_RW, ssc, 0,
1359             ath_rate_sysctl_sample_rate, "I",
1360             "sample: percent air time devoted to sampling new rates (%%)");
1361         /* XXX max_successive_failures, stale_failure_timeout, min_switch */
1362         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
1363             "sample_stats", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
1364             ath_rate_sysctl_stats, "I", "sample: print statistics");
1365 }
1366
1367 struct ath_ratectrl *
1368 ath_rate_attach(struct ath_softc *sc)
1369 {
1370         struct sample_softc *ssc;
1371         
1372         ssc = malloc(sizeof(struct sample_softc), M_DEVBUF, M_NOWAIT|M_ZERO);
1373         if (ssc == NULL)
1374                 return NULL;
1375         ssc->arc.arc_space = sizeof(struct sample_node);
1376         ssc->smoothing_rate = 75;               /* ewma percentage ([0..99]) */
1377         ssc->smoothing_minpackets = 100 / (100 - ssc->smoothing_rate);
1378         ssc->sample_rate = 10;                  /* %time to try diff tx rates */
1379         ssc->max_successive_failures = 3;       /* threshold for rate sampling*/
1380         ssc->stale_failure_timeout = 10 * hz;   /* 10 seconds */
1381         ssc->min_switch = hz;                   /* 1 second */
1382         ath_rate_sysctlattach(sc, ssc);
1383         return &ssc->arc;
1384 }
1385
1386 void
1387 ath_rate_detach(struct ath_ratectrl *arc)
1388 {
1389         struct sample_softc *ssc = (struct sample_softc *) arc;
1390         
1391         free(ssc, M_DEVBUF);
1392 }