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