sample.c revision 238638
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: head/sys/dev/ath/ath_rate/sample/sample.c 238638 2012-07-20 02:17:48Z adrian $");
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
106static void	ath_rate_ctl_reset(struct ath_softc *, struct ieee80211_node *);
107
108static __inline int
109size_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
129void
130ath_rate_node_init(struct ath_softc *sc, struct ath_node *an)
131{
132	/* NB: assumed to be zero'd by caller */
133}
134
135void
136ath_rate_node_cleanup(struct ath_softc *sc, struct ath_node *an)
137{
138}
139
140static int
141dot11rate(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
149static const char *
150dot11rate_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 */
161static __inline int
162pick_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	uint32_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 */
245static __inline int
246pick_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	uint32_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 &~ (1<<current_rix);/* don't sample current rate */
267	while (mask != 0) {
268		if ((mask & (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 &= ~(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 &= ~(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 &= ~(1<<rix);
292			goto nextrate;
293		}
294
295		/*
296		 * When doing aggregation, successive failures don't happen
297		 * as often, as sometimes some of the sub-frames get through.
298		 *
299		 * If the sample rix average tx time is greater than the
300		 * average tx time of the current rix, don't immediately use
301		 * the rate for sampling.
302		 */
303		if (an->an_node.ni_flags & IEEE80211_NODE_HT) {
304			if ((sn->stats[size_bin][rix].average_tx_time * 10 >
305			    sn->stats[size_bin][current_rix].average_tx_time * 9) &&
306			    (ticks - sn->stats[size_bin][rix].last_tx < ssc->stale_failure_timeout)) {
307				mask &= ~(1<<rix);
308				goto nextrate;
309			}
310		}
311
312		/*
313		 * XXX TODO
314		 * For HT, limit sample somehow?
315		 */
316
317		/* Don't sample more than 2 rates higher for rates > 11M for non-HT rates */
318		if (! (an->an_node.ni_flags & IEEE80211_NODE_HT)) {
319			if (DOT11RATE(rix) > 2*11 && rix > current_rix + 2) {
320				mask &= ~(1<<rix);
321				goto nextrate;
322			}
323		}
324
325		sn->last_sample_rix[size_bin] = rix;
326		return rix;
327	}
328	return current_rix;
329#undef DOT11RATE
330#undef	MCS
331}
332
333static int
334ath_rate_get_static_rix(struct ath_softc *sc, const struct ieee80211_node *ni)
335{
336#define	RATE(_ix)	(ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
337#define	DOT11RATE(_ix)	(rt->info[(_ix)].dot11Rate & IEEE80211_RATE_VAL)
338#define	MCS(_ix)	(ni->ni_htrates.rs_rates[_ix] | IEEE80211_RATE_MCS)
339	const struct ieee80211_txparam *tp = ni->ni_txparms;
340	int srate;
341
342	/* Check MCS rates */
343	for (srate = ni->ni_htrates.rs_nrates - 1; srate >= 0; srate--) {
344		if (MCS(srate) == tp->ucastrate)
345			return sc->sc_rixmap[tp->ucastrate];
346	}
347
348	/* Check legacy rates */
349	for (srate = ni->ni_rates.rs_nrates - 1; srate >= 0; srate--) {
350		if (RATE(srate) == tp->ucastrate)
351			return sc->sc_rixmap[tp->ucastrate];
352	}
353	return -1;
354#undef	RATE
355#undef	DOT11RATE
356#undef	MCS
357}
358
359static void
360ath_rate_update_static_rix(struct ath_softc *sc, struct ieee80211_node *ni)
361{
362	struct ath_node *an = ATH_NODE(ni);
363	const struct ieee80211_txparam *tp = ni->ni_txparms;
364	struct sample_node *sn = ATH_NODE_SAMPLE(an);
365
366	if (tp != NULL && tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
367		/*
368		 * A fixed rate is to be used; ucastrate is the IEEE code
369		 * for this rate (sans basic bit).  Check this against the
370		 * negotiated rate set for the node.  Note the fixed rate
371		 * may not be available for various reasons so we only
372		 * setup the static rate index if the lookup is successful.
373		 */
374		sn->static_rix = ath_rate_get_static_rix(sc, ni);
375	} else {
376		sn->static_rix = -1;
377	}
378}
379
380/*
381 * Pick a non-HT rate to begin using.
382 */
383static int
384ath_rate_pick_seed_rate_legacy(struct ath_softc *sc, struct ath_node *an,
385    int frameLen)
386{
387#define	DOT11RATE(ix)	(rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
388#define	MCS(ix)		(rt->info[ix].dot11Rate | IEEE80211_RATE_MCS)
389#define	RATE(ix)	(DOT11RATE(ix) / 2)
390	int rix = -1;
391	const HAL_RATE_TABLE *rt = sc->sc_currates;
392	struct sample_node *sn = ATH_NODE_SAMPLE(an);
393	const int size_bin = size_to_bin(frameLen);
394
395	/* no packet has been sent successfully yet */
396	for (rix = rt->rateCount-1; rix > 0; rix--) {
397		if ((sn->ratemask & (1<<rix)) == 0)
398			continue;
399
400		/* Skip HT rates */
401		if (rt->info[rix].phy == IEEE80211_T_HT)
402			continue;
403
404		/*
405		 * Pick the highest rate <= 36 Mbps
406		 * that hasn't failed.
407		 */
408		if (DOT11RATE(rix) <= 72 &&
409		    sn->stats[size_bin][rix].successive_failures == 0) {
410			break;
411		}
412	}
413	return rix;
414#undef	RATE
415#undef	MCS
416#undef	DOT11RATE
417}
418
419/*
420 * Pick a HT rate to begin using.
421 *
422 * Don't use any non-HT rates; only consider HT rates.
423 */
424static int
425ath_rate_pick_seed_rate_ht(struct ath_softc *sc, struct ath_node *an,
426    int frameLen)
427{
428#define	DOT11RATE(ix)	(rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
429#define	MCS(ix)		(rt->info[ix].dot11Rate | IEEE80211_RATE_MCS)
430#define	RATE(ix)	(DOT11RATE(ix) / 2)
431	int rix = -1, ht_rix = -1;
432	const HAL_RATE_TABLE *rt = sc->sc_currates;
433	struct sample_node *sn = ATH_NODE_SAMPLE(an);
434	const int size_bin = size_to_bin(frameLen);
435
436	/* no packet has been sent successfully yet */
437	for (rix = rt->rateCount-1; rix > 0; rix--) {
438		/* Skip rates we can't use */
439		if ((sn->ratemask & (1<<rix)) == 0)
440			continue;
441
442		/* Keep a copy of the last seen HT rate index */
443		if (rt->info[rix].phy == IEEE80211_T_HT)
444			ht_rix = rix;
445
446		/* Skip non-HT rates */
447		if (rt->info[rix].phy != IEEE80211_T_HT)
448			continue;
449
450		/*
451		 * Pick a medium-speed rate regardless of stream count
452		 * which has not seen any failures. Higher rates may fail;
453		 * we'll try them later.
454		 */
455		if (((MCS(rix) & 0x7) <= 4) &&
456		    sn->stats[size_bin][rix].successive_failures == 0) {
457			break;
458		}
459	}
460
461	/*
462	 * If all the MCS rates have successive failures, rix should be
463	 * > 0; otherwise use the lowest MCS rix (hopefully MCS 0.)
464	 */
465	return MAX(rix, ht_rix);
466#undef	RATE
467#undef	MCS
468#undef	DOT11RATE
469}
470
471
472void
473ath_rate_findrate(struct ath_softc *sc, struct ath_node *an,
474		  int shortPreamble, size_t frameLen,
475		  u_int8_t *rix0, int *try0, u_int8_t *txrate)
476{
477#define	DOT11RATE(ix)	(rt->info[ix].dot11Rate & IEEE80211_RATE_VAL)
478#define	MCS(ix)		(rt->info[ix].dot11Rate | IEEE80211_RATE_MCS)
479#define	RATE(ix)	(DOT11RATE(ix) / 2)
480	struct sample_node *sn = ATH_NODE_SAMPLE(an);
481	struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
482	struct ifnet *ifp = sc->sc_ifp;
483	struct ieee80211com *ic = ifp->if_l2com;
484	const HAL_RATE_TABLE *rt = sc->sc_currates;
485	const int size_bin = size_to_bin(frameLen);
486	int rix, mrr, best_rix, change_rates;
487	unsigned average_tx_time;
488
489	ath_rate_update_static_rix(sc, &an->an_node);
490
491	if (sn->currates != sc->sc_currates) {
492		device_printf(sc->sc_dev, "%s: currates != sc_currates!\n",
493		    __func__);
494		rix = 0;
495		*try0 = ATH_TXMAXTRY;
496		goto done;
497	}
498
499	if (sn->static_rix != -1) {
500		rix = sn->static_rix;
501		*try0 = ATH_TXMAXTRY;
502		goto done;
503	}
504
505	/* XXX TODO: this doesn't know about 11gn vs 11g protection; teach it */
506	mrr = sc->sc_mrretry && !(ic->ic_flags & IEEE80211_F_USEPROT);
507
508	best_rix = pick_best_rate(an, rt, size_bin, !mrr);
509	if (best_rix >= 0) {
510		average_tx_time = sn->stats[size_bin][best_rix].average_tx_time;
511	} else {
512		average_tx_time = 0;
513	}
514	/*
515	 * Limit the time measuring the performance of other tx
516	 * rates to sample_rate% of the total transmission time.
517	 */
518	if (sn->sample_tt[size_bin] < average_tx_time * (sn->packets_since_sample[size_bin]*ssc->sample_rate/100)) {
519		rix = pick_sample_rate(ssc, an, rt, size_bin);
520		IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
521		     &an->an_node, "att %d sample_tt %d size %u sample rate %d %s current rate %d %s",
522		     average_tx_time,
523		     sn->sample_tt[size_bin],
524		     bin_to_size(size_bin),
525		     dot11rate(rt, rix),
526		     dot11rate_label(rt, rix),
527		     dot11rate(rt, sn->current_rix[size_bin]),
528		     dot11rate_label(rt, sn->current_rix[size_bin]));
529		if (rix != sn->current_rix[size_bin]) {
530			sn->current_sample_rix[size_bin] = rix;
531		} else {
532			sn->current_sample_rix[size_bin] = -1;
533		}
534		sn->packets_since_sample[size_bin] = 0;
535	} else {
536		change_rates = 0;
537		if (!sn->packets_sent[size_bin] || best_rix == -1) {
538			/* no packet has been sent successfully yet */
539			change_rates = 1;
540			if (an->an_node.ni_flags & IEEE80211_NODE_HT)
541				best_rix =
542				    ath_rate_pick_seed_rate_ht(sc, an, frameLen);
543			else
544				best_rix =
545				    ath_rate_pick_seed_rate_legacy(sc, an, frameLen);
546		} else if (sn->packets_sent[size_bin] < 20) {
547			/* let the bit-rate switch quickly during the first few packets */
548			IEEE80211_NOTE(an->an_node.ni_vap,
549			    IEEE80211_MSG_RATECTL, &an->an_node,
550			    "%s: switching quickly..", __func__);
551			change_rates = 1;
552		} else if (ticks - ssc->min_switch > sn->ticks_since_switch[size_bin]) {
553			/* min_switch seconds have gone by */
554			IEEE80211_NOTE(an->an_node.ni_vap,
555			    IEEE80211_MSG_RATECTL, &an->an_node,
556			    "%s: min_switch %d > ticks_since_switch %d..",
557			    __func__, ticks - ssc->min_switch, sn->ticks_since_switch[size_bin]);
558			change_rates = 1;
559		} else if ((! (an->an_node.ni_flags & IEEE80211_NODE_HT)) &&
560		    (2*average_tx_time < sn->stats[size_bin][sn->current_rix[size_bin]].average_tx_time)) {
561			/* the current bit-rate is twice as slow as the best one */
562			IEEE80211_NOTE(an->an_node.ni_vap,
563			    IEEE80211_MSG_RATECTL, &an->an_node,
564			    "%s: 2x att (= %d) < cur_rix att %d",
565			    __func__,
566			    2 * average_tx_time, sn->stats[size_bin][sn->current_rix[size_bin]].average_tx_time);
567			change_rates = 1;
568		} else if ((an->an_node.ni_flags & IEEE80211_NODE_HT)) {
569			int cur_rix = sn->current_rix[size_bin];
570			int cur_att = sn->stats[size_bin][cur_rix].average_tx_time;
571			/*
572			 * If the node is HT, upgrade it if the MCS rate is
573			 * higher and the average tx time is within 20% of
574			 * the current rate. It can fail a little.
575			 *
576			 * This is likely not optimal!
577			 */
578#if 0
579			printf("cur rix/att %x/%d, best rix/att %x/%d\n",
580			    MCS(cur_rix), cur_att, MCS(best_rix), average_tx_time);
581#endif
582			if ((MCS(best_rix) > MCS(cur_rix)) &&
583			    (average_tx_time * 8) <= (cur_att * 10)) {
584				IEEE80211_NOTE(an->an_node.ni_vap,
585				    IEEE80211_MSG_RATECTL, &an->an_node,
586				    "%s: HT: best_rix 0x%d > cur_rix 0x%x, average_tx_time %d, cur_att %d",
587				    __func__,
588				    MCS(best_rix), MCS(cur_rix), average_tx_time, cur_att);
589				change_rates = 1;
590			}
591		}
592
593		sn->packets_since_sample[size_bin]++;
594
595		if (change_rates) {
596			if (best_rix != sn->current_rix[size_bin]) {
597				IEEE80211_NOTE(an->an_node.ni_vap,
598				    IEEE80211_MSG_RATECTL,
599				    &an->an_node,
600"%s: size %d switch rate %d (%d/%d) -> %d (%d/%d) after %d packets mrr %d",
601				    __func__,
602				    bin_to_size(size_bin),
603				    RATE(sn->current_rix[size_bin]),
604				    sn->stats[size_bin][sn->current_rix[size_bin]].average_tx_time,
605				    sn->stats[size_bin][sn->current_rix[size_bin]].perfect_tx_time,
606				    RATE(best_rix),
607				    sn->stats[size_bin][best_rix].average_tx_time,
608				    sn->stats[size_bin][best_rix].perfect_tx_time,
609				    sn->packets_since_switch[size_bin],
610				    mrr);
611			}
612			sn->packets_since_switch[size_bin] = 0;
613			sn->current_rix[size_bin] = best_rix;
614			sn->ticks_since_switch[size_bin] = ticks;
615			/*
616			 * Set the visible txrate for this node.
617			 */
618			an->an_node.ni_txrate = (rt->info[best_rix].phy == IEEE80211_T_HT) ?  MCS(best_rix) : DOT11RATE(best_rix);
619		}
620		rix = sn->current_rix[size_bin];
621		sn->packets_since_switch[size_bin]++;
622	}
623	*try0 = mrr ? sn->sched[rix].t0 : ATH_TXMAXTRY;
624done:
625
626	/*
627	 * This bug totally sucks and should be fixed.
628	 *
629	 * For now though, let's not panic, so we can start to figure
630	 * out how to better reproduce it.
631	 */
632	if (rix < 0 || rix >= rt->rateCount) {
633		printf("%s: ERROR: rix %d out of bounds (rateCount=%d)\n",
634		    __func__,
635		    rix,
636		    rt->rateCount);
637		    rix = 0;	/* XXX just default for now */
638	}
639	KASSERT(rix >= 0 && rix < rt->rateCount, ("rix is %d", rix));
640
641	*rix0 = rix;
642	*txrate = rt->info[rix].rateCode
643		| (shortPreamble ? rt->info[rix].shortPreamble : 0);
644	sn->packets_sent[size_bin]++;
645#undef DOT11RATE
646#undef MCS
647#undef RATE
648}
649
650/*
651 * Get the TX rates. Don't fiddle with short preamble flags for them;
652 * the caller can do that.
653 */
654void
655ath_rate_getxtxrates(struct ath_softc *sc, struct ath_node *an,
656    uint8_t rix0, struct ath_rc_series *rc)
657{
658	struct sample_node *sn = ATH_NODE_SAMPLE(an);
659	const struct txschedule *sched = &sn->sched[rix0];
660
661	KASSERT(rix0 == sched->r0, ("rix0 (%x) != sched->r0 (%x)!\n", rix0, sched->r0));
662
663	rc[0].flags = rc[1].flags = rc[2].flags = rc[3].flags = 0;
664
665	rc[0].rix = sched->r0;
666	rc[1].rix = sched->r1;
667	rc[2].rix = sched->r2;
668	rc[3].rix = sched->r3;
669
670	rc[0].tries = sched->t0;
671	rc[1].tries = sched->t1;
672	rc[2].tries = sched->t2;
673	rc[3].tries = sched->t3;
674}
675
676void
677ath_rate_setupxtxdesc(struct ath_softc *sc, struct ath_node *an,
678		      struct ath_desc *ds, int shortPreamble, u_int8_t rix)
679{
680	struct sample_node *sn = ATH_NODE_SAMPLE(an);
681	const struct txschedule *sched = &sn->sched[rix];
682	const HAL_RATE_TABLE *rt = sc->sc_currates;
683	uint8_t rix1, s1code, rix2, s2code, rix3, s3code;
684
685	/* XXX precalculate short preamble tables */
686	rix1 = sched->r1;
687	s1code = rt->info[rix1].rateCode
688	       | (shortPreamble ? rt->info[rix1].shortPreamble : 0);
689	rix2 = sched->r2;
690	s2code = rt->info[rix2].rateCode
691	       | (shortPreamble ? rt->info[rix2].shortPreamble : 0);
692	rix3 = sched->r3;
693	s3code = rt->info[rix3].rateCode
694	       | (shortPreamble ? rt->info[rix3].shortPreamble : 0);
695	ath_hal_setupxtxdesc(sc->sc_ah, ds,
696	    s1code, sched->t1,		/* series 1 */
697	    s2code, sched->t2,		/* series 2 */
698	    s3code, sched->t3);		/* series 3 */
699}
700
701/*
702 * Update the EWMA percentage.
703 *
704 * This is a simple hack to track an EWMA based on the current
705 * rate scenario. For the rate codes which failed, this will
706 * record a 0% against it. For the rate code which succeeded,
707 * EWMA will record the nbad*100/nframes percentage against it.
708 */
709static void
710update_ewma_stats(struct ath_softc *sc, struct ath_node *an,
711    int frame_size,
712    int rix0, int tries0,
713    int rix1, int tries1,
714    int rix2, int tries2,
715    int rix3, int tries3,
716    int short_tries, int tries, int status,
717    int nframes, int nbad)
718{
719	struct sample_node *sn = ATH_NODE_SAMPLE(an);
720	struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
721	const int size_bin = size_to_bin(frame_size);
722	int tries_so_far;
723	int pct;
724	int rix = rix0;
725
726	/* Calculate percentage based on current rate */
727	if (nframes == 0)
728		nframes = nbad = 1;
729	pct = ((nframes - nbad) * 1000) / nframes;
730
731	/* Figure out which rate index succeeded */
732	tries_so_far = tries0;
733
734	if (tries1 && tries_so_far < tries) {
735		tries_so_far += tries1;
736		rix = rix1;
737		/* XXX bump ewma pct */
738	}
739
740	if (tries2 && tries_so_far < tries) {
741		tries_so_far += tries2;
742		rix = rix2;
743		/* XXX bump ewma pct */
744	}
745
746	if (tries3 && tries_so_far < tries) {
747		rix = rix3;
748		/* XXX bump ewma pct */
749	}
750
751	/* rix is the successful rate, update EWMA for final rix */
752	if (sn->stats[size_bin][rix].total_packets <
753	    ssc->smoothing_minpackets) {
754		/* just average the first few packets */
755		int a_pct = (sn->stats[size_bin][rix].packets_acked * 1000) /
756		    (sn->stats[size_bin][rix].total_packets);
757		sn->stats[size_bin][rix].ewma_pct = a_pct;
758	} else {
759		/* use a ewma */
760		sn->stats[size_bin][rix].ewma_pct =
761			((sn->stats[size_bin][rix].ewma_pct * ssc->smoothing_rate) +
762			 (pct * (100 - ssc->smoothing_rate))) / 100;
763	}
764}
765
766static void
767update_stats(struct ath_softc *sc, struct ath_node *an,
768		  int frame_size,
769		  int rix0, int tries0,
770		  int rix1, int tries1,
771		  int rix2, int tries2,
772		  int rix3, int tries3,
773		  int short_tries, int tries, int status,
774		  int nframes, int nbad)
775{
776	struct sample_node *sn = ATH_NODE_SAMPLE(an);
777	struct sample_softc *ssc = ATH_SOFTC_SAMPLE(sc);
778#ifdef IEEE80211_DEBUG
779	const HAL_RATE_TABLE *rt = sc->sc_currates;
780#endif
781	const int size_bin = size_to_bin(frame_size);
782	const int size = bin_to_size(size_bin);
783	int tt, tries_so_far;
784	int is_ht40 = (an->an_node.ni_chw == 40);
785
786	if (!IS_RATE_DEFINED(sn, rix0))
787		return;
788	tt = calc_usecs_unicast_packet(sc, size, rix0, short_tries,
789		MIN(tries0, tries) - 1, is_ht40);
790	tries_so_far = tries0;
791
792	if (tries1 && tries_so_far < tries) {
793		if (!IS_RATE_DEFINED(sn, rix1))
794			return;
795		tt += calc_usecs_unicast_packet(sc, size, rix1, short_tries,
796			MIN(tries1 + tries_so_far, tries) - tries_so_far - 1, is_ht40);
797		tries_so_far += tries1;
798	}
799
800	if (tries2 && tries_so_far < tries) {
801		if (!IS_RATE_DEFINED(sn, rix2))
802			return;
803		tt += calc_usecs_unicast_packet(sc, size, rix2, short_tries,
804			MIN(tries2 + tries_so_far, tries) - tries_so_far - 1, is_ht40);
805		tries_so_far += tries2;
806	}
807
808	if (tries3 && tries_so_far < tries) {
809		if (!IS_RATE_DEFINED(sn, rix3))
810			return;
811		tt += calc_usecs_unicast_packet(sc, size, rix3, short_tries,
812			MIN(tries3 + tries_so_far, tries) - tries_so_far - 1, is_ht40);
813	}
814
815	if (sn->stats[size_bin][rix0].total_packets < ssc->smoothing_minpackets) {
816		/* just average the first few packets */
817		int avg_tx = sn->stats[size_bin][rix0].average_tx_time;
818		int packets = sn->stats[size_bin][rix0].total_packets;
819		sn->stats[size_bin][rix0].average_tx_time = (tt+(avg_tx*packets))/(packets+nframes);
820	} else {
821		/* use a ewma */
822		sn->stats[size_bin][rix0].average_tx_time =
823			((sn->stats[size_bin][rix0].average_tx_time * ssc->smoothing_rate) +
824			 (tt * (100 - ssc->smoothing_rate))) / 100;
825	}
826
827	/*
828	 * XXX Don't mark the higher bit rates as also having failed; as this
829	 * unfortunately stops those rates from being tasted when trying to
830	 * TX. This happens with 11n aggregation.
831	 */
832	if (nframes == nbad) {
833#if 0
834		int y;
835#endif
836		sn->stats[size_bin][rix0].successive_failures += nbad;
837#if 0
838		for (y = size_bin+1; y < NUM_PACKET_SIZE_BINS; y++) {
839			/*
840			 * Also say larger packets failed since we
841			 * assume if a small packet fails at a
842			 * bit-rate then a larger one will also.
843			 */
844			sn->stats[y][rix0].successive_failures += nbad;
845			sn->stats[y][rix0].last_tx = ticks;
846			sn->stats[y][rix0].tries += tries;
847			sn->stats[y][rix0].total_packets += nframes;
848		}
849#endif
850	} else {
851		sn->stats[size_bin][rix0].packets_acked += (nframes - nbad);
852		sn->stats[size_bin][rix0].successive_failures = 0;
853	}
854	sn->stats[size_bin][rix0].tries += tries;
855	sn->stats[size_bin][rix0].last_tx = ticks;
856	sn->stats[size_bin][rix0].total_packets += nframes;
857
858	if (rix0 == sn->current_sample_rix[size_bin]) {
859		IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
860		   &an->an_node,
861"%s: size %d %s sample rate %d %s tries (%d/%d) tt %d avg_tt (%d/%d) nfrm %d nbad %d",
862		    __func__,
863		    size,
864		    status ? "FAIL" : "OK",
865		    dot11rate(rt, rix0),
866		    dot11rate_label(rt, rix0),
867		    short_tries, tries, tt,
868		    sn->stats[size_bin][rix0].average_tx_time,
869		    sn->stats[size_bin][rix0].perfect_tx_time,
870		    nframes, nbad);
871		sn->sample_tt[size_bin] = tt;
872		sn->current_sample_rix[size_bin] = -1;
873	}
874}
875
876static void
877badrate(struct ifnet *ifp, int series, int hwrate, int tries, int status)
878{
879	if_printf(ifp, "bad series%d hwrate 0x%x, tries %u ts_status 0x%x\n",
880	    series, hwrate, tries, status);
881}
882
883void
884ath_rate_tx_complete(struct ath_softc *sc, struct ath_node *an,
885	const struct ath_rc_series *rc, const struct ath_tx_status *ts,
886	int frame_size, int nframes, int nbad)
887{
888	struct ifnet *ifp = sc->sc_ifp;
889	struct ieee80211com *ic = ifp->if_l2com;
890	struct sample_node *sn = ATH_NODE_SAMPLE(an);
891	int final_rix, short_tries, long_tries;
892	const HAL_RATE_TABLE *rt = sc->sc_currates;
893	int status = ts->ts_status;
894	int mrr;
895
896	final_rix = rt->rateCodeToIndex[ts->ts_rate];
897	short_tries = ts->ts_shortretry;
898	long_tries = ts->ts_longretry + 1;
899
900	if (frame_size == 0)		    /* NB: should not happen */
901		frame_size = 1500;
902
903	if (sn->ratemask == 0) {
904		IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
905		    &an->an_node,
906		    "%s: size %d %s rate/try %d/%d no rates yet",
907		    __func__,
908		    bin_to_size(size_to_bin(frame_size)),
909		    status ? "FAIL" : "OK",
910		    short_tries, long_tries);
911		return;
912	}
913	mrr = sc->sc_mrretry && !(ic->ic_flags & IEEE80211_F_USEPROT);
914	if (!mrr || ts->ts_finaltsi == 0) {
915		if (!IS_RATE_DEFINED(sn, final_rix)) {
916			badrate(ifp, 0, ts->ts_rate, long_tries, status);
917			return;
918		}
919		/*
920		 * Only one rate was used; optimize work.
921		 */
922		IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
923		     &an->an_node, "%s: size %d (%d bytes) %s rate/try %d %s/%d/%d nframes/nbad [%d/%d]",
924		     __func__,
925		     bin_to_size(size_to_bin(frame_size)),
926		     frame_size,
927		     status ? "FAIL" : "OK",
928		     dot11rate(rt, final_rix), dot11rate_label(rt, final_rix),
929		     short_tries, long_tries, nframes, nbad);
930		update_stats(sc, an, frame_size,
931			     final_rix, long_tries,
932			     0, 0,
933			     0, 0,
934			     0, 0,
935			     short_tries, long_tries, status,
936			     nframes, nbad);
937		update_ewma_stats(sc, an, frame_size,
938			     final_rix, long_tries,
939			     0, 0,
940			     0, 0,
941			     0, 0,
942			     short_tries, long_tries, status,
943			     nframes, nbad);
944
945	} else {
946		int finalTSIdx = ts->ts_finaltsi;
947		int i;
948
949		/*
950		 * Process intermediate rates that failed.
951		 */
952
953		IEEE80211_NOTE(an->an_node.ni_vap, IEEE80211_MSG_RATECTL,
954		    &an->an_node,
955"%s: size %d (%d bytes) finaltsidx %d tries %d %s rate/try [%d %s/%d %d %s/%d %d %s/%d %d %s/%d] nframes/nbad [%d/%d]",
956		     __func__,
957		     bin_to_size(size_to_bin(frame_size)),
958		     frame_size,
959		     finalTSIdx,
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
1044void
1045ath_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
1051static 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 */
1069static void
1070ath_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	sn->sched = mrr_schedules[sc->sc_curmode];
1085	KASSERT(sn->sched != NULL,
1086	    ("no mrr schedule for mode %u", sc->sc_curmode));
1087
1088        sn->static_rix = -1;
1089	ath_rate_update_static_rix(sc, ni);
1090
1091	sn->currates = sc->sc_currates;
1092
1093	/*
1094	 * Construct a bitmask of usable rates.  This has all
1095	 * negotiated rates minus those marked by the hal as
1096	 * to be ignored for doing rate control.
1097	 */
1098	sn->ratemask = 0;
1099	/* MCS rates */
1100	if (ni->ni_flags & IEEE80211_NODE_HT) {
1101		for (x = 0; x < ni->ni_htrates.rs_nrates; x++) {
1102			rix = sc->sc_rixmap[MCS(x)];
1103			if (rix == 0xff)
1104				continue;
1105			/* skip rates marked broken by hal */
1106			if (!rt->info[rix].valid)
1107				continue;
1108			KASSERT(rix < SAMPLE_MAXRATES,
1109			    ("mcs %u has rix %d", MCS(x), rix));
1110			sn->ratemask |= 1<<rix;
1111		}
1112	}
1113
1114	/* Legacy rates */
1115	for (x = 0; x < ni->ni_rates.rs_nrates; x++) {
1116		rix = sc->sc_rixmap[RATE(x)];
1117		if (rix == 0xff)
1118			continue;
1119		/* skip rates marked broken by hal */
1120		if (!rt->info[rix].valid)
1121			continue;
1122		KASSERT(rix < SAMPLE_MAXRATES,
1123		    ("rate %u has rix %d", RATE(x), rix));
1124		sn->ratemask |= 1<<rix;
1125	}
1126#ifdef IEEE80211_DEBUG
1127	if (ieee80211_msg(ni->ni_vap, IEEE80211_MSG_RATECTL)) {
1128		uint32_t mask;
1129
1130		ieee80211_note(ni->ni_vap, "[%6D] %s: size 1600 rate/tt",
1131		    ni->ni_macaddr, ":", __func__);
1132		for (mask = sn->ratemask, rix = 0; mask != 0; mask >>= 1, rix++) {
1133			if ((mask & 1) == 0)
1134				continue;
1135			printf(" %d %s/%d", dot11rate(rt, rix), dot11rate_label(rt, rix),
1136			    calc_usecs_unicast_packet(sc, 1600, rix, 0,0,
1137			        (ni->ni_chw == 40)));
1138		}
1139		printf("\n");
1140	}
1141#endif
1142	for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
1143		int size = bin_to_size(y);
1144		uint32_t mask;
1145
1146		sn->packets_sent[y] = 0;
1147		sn->current_sample_rix[y] = -1;
1148		sn->last_sample_rix[y] = 0;
1149		/* XXX start with first valid rate */
1150		sn->current_rix[y] = ffs(sn->ratemask)-1;
1151
1152		/*
1153		 * Initialize the statistics buckets; these are
1154		 * indexed by the rate code index.
1155		 */
1156		for (rix = 0, mask = sn->ratemask; mask != 0; rix++, mask >>= 1) {
1157			if ((mask & 1) == 0)		/* not a valid rate */
1158				continue;
1159			sn->stats[y][rix].successive_failures = 0;
1160			sn->stats[y][rix].tries = 0;
1161			sn->stats[y][rix].total_packets = 0;
1162			sn->stats[y][rix].packets_acked = 0;
1163			sn->stats[y][rix].last_tx = 0;
1164			sn->stats[y][rix].ewma_pct = 0;
1165
1166			sn->stats[y][rix].perfect_tx_time =
1167			    calc_usecs_unicast_packet(sc, size, rix, 0, 0,
1168			    (ni->ni_chw == 40));
1169			sn->stats[y][rix].average_tx_time =
1170			    sn->stats[y][rix].perfect_tx_time;
1171		}
1172	}
1173#if 0
1174	/* XXX 0, num_rates-1 are wrong */
1175	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_RATECTL, ni,
1176	    "%s: %d rates %d%sMbps (%dus)- %d%sMbps (%dus)", __func__,
1177	    sn->num_rates,
1178	    DOT11RATE(0)/2, DOT11RATE(0) % 1 ? ".5" : "",
1179	    sn->stats[1][0].perfect_tx_time,
1180	    DOT11RATE(sn->num_rates-1)/2, DOT11RATE(sn->num_rates-1) % 1 ? ".5" : "",
1181	    sn->stats[1][sn->num_rates-1].perfect_tx_time
1182	);
1183#endif
1184	/* set the visible bit-rate */
1185	if (sn->static_rix != -1)
1186		ni->ni_txrate = DOT11RATE(sn->static_rix);
1187	else
1188		ni->ni_txrate = RATE(0);
1189#undef RATE
1190#undef DOT11RATE
1191}
1192
1193/*
1194 * Fetch the statistics for the given node.
1195 *
1196 * The ieee80211 node must be referenced and unlocked, however the ath_node
1197 * must be locked.
1198 *
1199 * The main difference here is that we convert the rate indexes
1200 * to 802.11 rates, or the userland output won't make much sense
1201 * as it has no access to the rix table.
1202 */
1203int
1204ath_rate_fetch_node_stats(struct ath_softc *sc, struct ath_node *an,
1205    struct ath_rateioctl *rs)
1206{
1207	struct sample_node *sn = ATH_NODE_SAMPLE(an);
1208	const HAL_RATE_TABLE *rt = sc->sc_currates;
1209	struct ath_rateioctl_tlv av;
1210	struct ath_rateioctl_rt *tv;
1211	int y;
1212	int o = 0;
1213
1214	ATH_NODE_LOCK_ASSERT(an);
1215
1216	/*
1217	 * Ensure there's enough space for the statistics.
1218	 */
1219	if (rs->len <
1220	    sizeof(struct ath_rateioctl_tlv) +
1221	    sizeof(struct ath_rateioctl_rt) +
1222	    sizeof(struct ath_rateioctl_tlv) +
1223	    sizeof(struct sample_node)) {
1224		device_printf(sc->sc_dev, "%s: len=%d, too short\n",
1225		    __func__,
1226		    rs->len);
1227		return (EINVAL);
1228	}
1229
1230	/*
1231	 * Take a temporary copy of the sample node state so we can
1232	 * modify it before we copy it.
1233	 */
1234	tv = malloc(sizeof(struct ath_rateioctl_rt), M_TEMP,
1235	    M_NOWAIT | M_ZERO);
1236	if (tv == NULL) {
1237		return (ENOMEM);
1238	}
1239
1240	/*
1241	 * Populate the rate table mapping TLV.
1242	 */
1243	tv->nentries = rt->rateCount;
1244	for (y = 0; y < rt->rateCount; y++) {
1245		tv->ratecode[y] = rt->info[y].dot11Rate & IEEE80211_RATE_VAL;
1246		if (rt->info[y].phy == IEEE80211_T_HT)
1247			tv->ratecode[y] |= IEEE80211_RATE_MCS;
1248	}
1249
1250	o = 0;
1251	/*
1252	 * First TLV - rate code mapping
1253	 */
1254	av.tlv_id = ATH_RATE_TLV_RATETABLE;
1255	av.tlv_len = sizeof(struct ath_rateioctl_rt);
1256	copyout(&av, rs->buf + o, sizeof(struct ath_rateioctl_tlv));
1257	o += sizeof(struct ath_rateioctl_tlv);
1258	copyout(tv, rs->buf + o, sizeof(struct ath_rateioctl_rt));
1259	o += sizeof(struct ath_rateioctl_rt);
1260
1261	/*
1262	 * Second TLV - sample node statistics
1263	 */
1264	av.tlv_id = ATH_RATE_TLV_SAMPLENODE;
1265	av.tlv_len = sizeof(struct sample_node);
1266	copyout(&av, rs->buf + o, sizeof(struct ath_rateioctl_tlv));
1267	o += sizeof(struct ath_rateioctl_tlv);
1268
1269	/*
1270	 * Copy the statistics over to the provided buffer.
1271	 */
1272	copyout(sn, rs->buf + o, sizeof(struct sample_node));
1273	o += sizeof(struct sample_node);
1274
1275	free(tv, M_TEMP);
1276
1277	return (0);
1278}
1279
1280static void
1281sample_stats(void *arg, struct ieee80211_node *ni)
1282{
1283	struct ath_softc *sc = arg;
1284	const HAL_RATE_TABLE *rt = sc->sc_currates;
1285	struct sample_node *sn = ATH_NODE_SAMPLE(ATH_NODE(ni));
1286	uint32_t mask;
1287	int rix, y;
1288
1289	printf("\n[%s] refcnt %d static_rix (%d %s) ratemask 0x%x\n",
1290	    ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni),
1291	    dot11rate(rt, sn->static_rix),
1292	    dot11rate_label(rt, sn->static_rix),
1293	    sn->ratemask);
1294	for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
1295		printf("[%4u] cur rix %d (%d %s) since switch: packets %d ticks %u\n",
1296		    bin_to_size(y), sn->current_rix[y],
1297		    dot11rate(rt, sn->current_rix[y]),
1298		    dot11rate_label(rt, sn->current_rix[y]),
1299		    sn->packets_since_switch[y], sn->ticks_since_switch[y]);
1300		printf("[%4u] last sample (%d %s) cur sample (%d %s) packets sent %d\n",
1301		    bin_to_size(y),
1302		    dot11rate(rt, sn->last_sample_rix[y]),
1303		    dot11rate_label(rt, sn->last_sample_rix[y]),
1304		    dot11rate(rt, sn->current_sample_rix[y]),
1305		    dot11rate_label(rt, sn->current_sample_rix[y]),
1306		    sn->packets_sent[y]);
1307		printf("[%4u] packets since sample %d sample tt %u\n",
1308		    bin_to_size(y), sn->packets_since_sample[y],
1309		    sn->sample_tt[y]);
1310	}
1311	for (mask = sn->ratemask, rix = 0; mask != 0; mask >>= 1, rix++) {
1312		if ((mask & 1) == 0)
1313				continue;
1314		for (y = 0; y < NUM_PACKET_SIZE_BINS; y++) {
1315			if (sn->stats[y][rix].total_packets == 0)
1316				continue;
1317			printf("[%2u %s:%4u] %8ju:%-8ju (%3d%%) (EWMA %3d.%1d%%) T %8ju F %4d avg %5u last %u\n",
1318			    dot11rate(rt, rix), dot11rate_label(rt, rix),
1319			    bin_to_size(y),
1320			    (uintmax_t) sn->stats[y][rix].total_packets,
1321			    (uintmax_t) sn->stats[y][rix].packets_acked,
1322			    (int) ((sn->stats[y][rix].packets_acked * 100ULL) /
1323			     sn->stats[y][rix].total_packets),
1324			    sn->stats[y][rix].ewma_pct / 10,
1325			    sn->stats[y][rix].ewma_pct % 10,
1326			    (uintmax_t) sn->stats[y][rix].tries,
1327			    sn->stats[y][rix].successive_failures,
1328			    sn->stats[y][rix].average_tx_time,
1329			    ticks - sn->stats[y][rix].last_tx);
1330		}
1331	}
1332}
1333
1334static int
1335ath_rate_sysctl_stats(SYSCTL_HANDLER_ARGS)
1336{
1337	struct ath_softc *sc = arg1;
1338	struct ifnet *ifp = sc->sc_ifp;
1339	struct ieee80211com *ic = ifp->if_l2com;
1340	int error, v;
1341
1342	v = 0;
1343	error = sysctl_handle_int(oidp, &v, 0, req);
1344	if (error || !req->newptr)
1345		return error;
1346	ieee80211_iterate_nodes(&ic->ic_sta, sample_stats, sc);
1347	return 0;
1348}
1349
1350static int
1351ath_rate_sysctl_smoothing_rate(SYSCTL_HANDLER_ARGS)
1352{
1353	struct sample_softc *ssc = arg1;
1354	int rate, error;
1355
1356	rate = ssc->smoothing_rate;
1357	error = sysctl_handle_int(oidp, &rate, 0, req);
1358	if (error || !req->newptr)
1359		return error;
1360	if (!(0 <= rate && rate < 100))
1361		return EINVAL;
1362	ssc->smoothing_rate = rate;
1363	ssc->smoothing_minpackets = 100 / (100 - rate);
1364	return 0;
1365}
1366
1367static int
1368ath_rate_sysctl_sample_rate(SYSCTL_HANDLER_ARGS)
1369{
1370	struct sample_softc *ssc = arg1;
1371	int rate, error;
1372
1373	rate = ssc->sample_rate;
1374	error = sysctl_handle_int(oidp, &rate, 0, req);
1375	if (error || !req->newptr)
1376		return error;
1377	if (!(2 <= rate && rate <= 100))
1378		return EINVAL;
1379	ssc->sample_rate = rate;
1380	return 0;
1381}
1382
1383static void
1384ath_rate_sysctlattach(struct ath_softc *sc, struct sample_softc *ssc)
1385{
1386	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
1387	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
1388
1389	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
1390	    "smoothing_rate", CTLTYPE_INT | CTLFLAG_RW, ssc, 0,
1391	    ath_rate_sysctl_smoothing_rate, "I",
1392	    "sample: smoothing rate for avg tx time (%%)");
1393	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
1394	    "sample_rate", CTLTYPE_INT | CTLFLAG_RW, ssc, 0,
1395	    ath_rate_sysctl_sample_rate, "I",
1396	    "sample: percent air time devoted to sampling new rates (%%)");
1397	/* XXX max_successive_failures, stale_failure_timeout, min_switch */
1398	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
1399	    "sample_stats", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
1400	    ath_rate_sysctl_stats, "I", "sample: print statistics");
1401}
1402
1403struct ath_ratectrl *
1404ath_rate_attach(struct ath_softc *sc)
1405{
1406	struct sample_softc *ssc;
1407
1408	ssc = malloc(sizeof(struct sample_softc), M_DEVBUF, M_NOWAIT|M_ZERO);
1409	if (ssc == NULL)
1410		return NULL;
1411	ssc->arc.arc_space = sizeof(struct sample_node);
1412	ssc->smoothing_rate = 95;		/* ewma percentage ([0..99]) */
1413	ssc->smoothing_minpackets = 100 / (100 - ssc->smoothing_rate);
1414	ssc->sample_rate = 10;			/* %time to try diff tx rates */
1415	ssc->max_successive_failures = 3;	/* threshold for rate sampling*/
1416	ssc->stale_failure_timeout = 10 * hz;	/* 10 seconds */
1417	ssc->min_switch = hz;			/* 1 second */
1418	ath_rate_sysctlattach(sc, ssc);
1419	return &ssc->arc;
1420}
1421
1422void
1423ath_rate_detach(struct ath_ratectrl *arc)
1424{
1425	struct sample_softc *ssc = (struct sample_softc *) arc;
1426
1427	free(ssc, M_DEVBUF);
1428}
1429