1 /*
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * Copyright (c) 2002-2006 Atheros Communications, Inc.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  *
17  * $FreeBSD$
18  */
19 #include "opt_ah.h"
20 
21 /*
22  * Chips specific device attachment and device info collection
23  * Connects Init Reg Vectors, EEPROM Data, and device Functions.
24  */
25 #include "ah.h"
26 #include "ah_internal.h"
27 #include "ah_devid.h"
28 
29 #include "ar5211/ar5211.h"
30 #include "ar5211/ar5211reg.h"
31 #include "ar5211/ar5211phy.h"
32 
33 #include "ah_eeprom_v3.h"
34 
35 /* Add static register initialization vectors */
36 #include "ar5211/boss.ini"
37 
38 /*
39  * Structure to hold 11b tuning information for Beanie/Sombrero
40  * 16 MHz mode, divider ratio = 198 = NP+S. N=16, S=4 or 6, P=12
41  */
42 typedef struct {
43 	uint32_t	refClkSel;	/* reference clock, 1 for 16 MHz */
44 	uint32_t	channelSelect;	/* P[7:4]S[3:0] bits */
45 	uint16_t	channel5111;	/* 11a channel for 5111 */
46 } CHAN_INFO_2GHZ;
47 
48 #define CI_2GHZ_INDEX_CORRECTION 19
49 static const CHAN_INFO_2GHZ chan2GHzData[] = {
50 	{ 1, 0x46, 96  },	/* 2312 -19 */
51 	{ 1, 0x46, 97  },	/* 2317 -18 */
52 	{ 1, 0x46, 98  },	/* 2322 -17 */
53 	{ 1, 0x46, 99  },	/* 2327 -16 */
54 	{ 1, 0x46, 100 },	/* 2332 -15 */
55 	{ 1, 0x46, 101 },	/* 2337 -14 */
56 	{ 1, 0x46, 102 },	/* 2342 -13 */
57 	{ 1, 0x46, 103 },	/* 2347 -12 */
58 	{ 1, 0x46, 104 },	/* 2352 -11 */
59 	{ 1, 0x46, 105 },	/* 2357 -10 */
60 	{ 1, 0x46, 106 },	/* 2362  -9 */
61 	{ 1, 0x46, 107 },	/* 2367  -8 */
62 	{ 1, 0x46, 108 },	/* 2372  -7 */
63 	/* index -6 to 0 are pad to make this a nolookup table */
64 	{ 1, 0x46, 116 },	/*       -6 */
65 	{ 1, 0x46, 116 },	/*       -5 */
66 	{ 1, 0x46, 116 },	/*       -4 */
67 	{ 1, 0x46, 116 },	/*       -3 */
68 	{ 1, 0x46, 116 },	/*       -2 */
69 	{ 1, 0x46, 116 },	/*       -1 */
70 	{ 1, 0x46, 116 },	/*        0 */
71 	{ 1, 0x46, 116 },	/* 2412   1 */
72 	{ 1, 0x46, 117 },	/* 2417   2 */
73 	{ 1, 0x46, 118 },	/* 2422   3 */
74 	{ 1, 0x46, 119 },	/* 2427   4 */
75 	{ 1, 0x46, 120 },	/* 2432   5 */
76 	{ 1, 0x46, 121 },	/* 2437   6 */
77 	{ 1, 0x46, 122 },	/* 2442   7 */
78 	{ 1, 0x46, 123 },	/* 2447   8 */
79 	{ 1, 0x46, 124 },	/* 2452   9 */
80 	{ 1, 0x46, 125 },	/* 2457  10 */
81 	{ 1, 0x46, 126 },	/* 2462  11 */
82 	{ 1, 0x46, 127 },	/* 2467  12 */
83 	{ 1, 0x46, 128 },	/* 2472  13 */
84 	{ 1, 0x44, 124 },	/* 2484  14 */
85 	{ 1, 0x46, 136 },	/* 2512  15 */
86 	{ 1, 0x46, 140 },	/* 2532  16 */
87 	{ 1, 0x46, 144 },	/* 2552  17 */
88 	{ 1, 0x46, 148 },	/* 2572  18 */
89 	{ 1, 0x46, 152 },	/* 2592  19 */
90 	{ 1, 0x46, 156 },	/* 2612  20 */
91 	{ 1, 0x46, 160 },	/* 2632  21 */
92 	{ 1, 0x46, 164 },	/* 2652  22 */
93 	{ 1, 0x46, 168 },	/* 2672  23 */
94 	{ 1, 0x46, 172 },	/* 2692  24 */
95 	{ 1, 0x46, 176 },	/* 2712  25 */
96 	{ 1, 0x46, 180 } 	/* 2732  26 */
97 };
98 
99 /* Power timeouts in usec to wait for chip to wake-up. */
100 #define POWER_UP_TIME	2000
101 
102 #define	DELAY_PLL_SETTLE	300		/* 300 us */
103 #define	DELAY_BASE_ACTIVATE	100		/* 100 us */
104 
105 #define NUM_RATES	8
106 
107 static HAL_BOOL ar5211SetResetReg(struct ath_hal *ah, uint32_t resetMask);
108 static HAL_BOOL ar5211SetChannel(struct ath_hal *,
109 		const struct ieee80211_channel *);
110 static int16_t ar5211RunNoiseFloor(struct ath_hal *,
111 		uint8_t runTime, int16_t startingNF);
112 static HAL_BOOL ar5211IsNfGood(struct ath_hal *,
113 		struct ieee80211_channel *chan);
114 static HAL_BOOL ar5211SetRf6and7(struct ath_hal *,
115 		const struct ieee80211_channel *chan);
116 static HAL_BOOL ar5211SetBoardValues(struct ath_hal *,
117 		const struct ieee80211_channel *chan);
118 static void ar5211SetPowerTable(struct ath_hal *,
119 		PCDACS_EEPROM *pSrcStruct, uint16_t channel);
120 static HAL_BOOL ar5211SetTransmitPower(struct ath_hal *,
121 		const struct ieee80211_channel *);
122 static void ar5211SetRateTable(struct ath_hal *,
123 		RD_EDGES_POWER *pRdEdgesPower, TRGT_POWER_INFO *pPowerInfo,
124 		uint16_t numChannels, const struct ieee80211_channel *chan);
125 static uint16_t ar5211GetScaledPower(uint16_t channel, uint16_t pcdacValue,
126 		const PCDACS_EEPROM *pSrcStruct);
127 static HAL_BOOL ar5211FindValueInList(uint16_t channel, uint16_t pcdacValue,
128 		const PCDACS_EEPROM *pSrcStruct, uint16_t *powerValue);
129 static uint16_t ar5211GetInterpolatedValue(uint16_t target,
130 		uint16_t srcLeft, uint16_t srcRight,
131 		uint16_t targetLeft, uint16_t targetRight, HAL_BOOL scaleUp);
132 static void ar5211GetLowerUpperValues(uint16_t value,
133 		const uint16_t *pList, uint16_t listSize,
134 		uint16_t *pLowerValue, uint16_t *pUpperValue);
135 static void ar5211GetLowerUpperPcdacs(uint16_t pcdac,
136 		uint16_t channel, const PCDACS_EEPROM *pSrcStruct,
137 		uint16_t *pLowerPcdac, uint16_t *pUpperPcdac);
138 
139 static void ar5211SetRfgain(struct ath_hal *, const GAIN_VALUES *);
140 static void ar5211RequestRfgain(struct ath_hal *);
141 static HAL_BOOL ar5211InvalidGainReadback(struct ath_hal *, GAIN_VALUES *);
142 static HAL_BOOL ar5211IsGainAdjustNeeded(struct ath_hal *, const GAIN_VALUES *);
143 static int32_t ar5211AdjustGain(struct ath_hal *, GAIN_VALUES *);
144 static void ar5211SetOperatingMode(struct ath_hal *, int opmode);
145 
146 /*
147  * Places the device in and out of reset and then places sane
148  * values in the registers based on EEPROM config, initialization
149  * vectors (as determined by the mode), and station configuration
150  *
151  * bChannelChange is used to preserve DMA/PCU registers across
152  * a HW Reset during channel change.
153  */
154 HAL_BOOL
155 ar5211Reset(struct ath_hal *ah, HAL_OPMODE opmode,
156 	struct ieee80211_channel *chan, HAL_BOOL bChannelChange,
157 	HAL_RESET_TYPE resetType,
158 	HAL_STATUS *status)
159 {
160 uint32_t softLedCfg, softLedState;
161 #define	N(a)	(sizeof (a) /sizeof (a[0]))
162 #define	FAIL(_code)	do { ecode = _code; goto bad; } while (0)
163 	struct ath_hal_5211 *ahp = AH5211(ah);
164 	HAL_CHANNEL_INTERNAL *ichan;
165 	uint32_t i, ledstate;
166 	HAL_STATUS ecode;
167 	int q;
168 
169 	uint32_t		data, synthDelay;
170 	uint32_t		macStaId1;
171 	uint16_t		modesIndex = 0, freqIndex = 0;
172 	uint32_t		saveFrameSeqCount[AR_NUM_DCU];
173 	uint32_t		saveTsfLow = 0, saveTsfHigh = 0;
174 	uint32_t		saveDefAntenna;
175 
176 	HALDEBUG(ah, HAL_DEBUG_RESET,
177 	     "%s: opmode %u channel %u/0x%x %s channel\n",
178 	     __func__, opmode, chan->ic_freq, chan->ic_flags,
179 	     bChannelChange ? "change" : "same");
180 
181 	OS_MARK(ah, AH_MARK_RESET, bChannelChange);
182 	/*
183 	 * Map public channel to private.
184 	 */
185 	ichan = ath_hal_checkchannel(ah, chan);
186 	if (ichan == AH_NULL)
187 		FAIL(HAL_EINVAL);
188 	switch (opmode) {
189 	case HAL_M_STA:
190 	case HAL_M_IBSS:
191 	case HAL_M_HOSTAP:
192 	case HAL_M_MONITOR:
193 		break;
194 	default:
195 		HALDEBUG(ah, HAL_DEBUG_ANY,
196 		    "%s: invalid operating mode %u\n", __func__, opmode);
197 		FAIL(HAL_EINVAL);
198 		break;
199 	}
200 	HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3);
201 
202 	/* Preserve certain DMA hardware registers on a channel change */
203 	if (bChannelChange) {
204 		/*
205 		 * Need to save/restore the TSF because of an issue
206 		 * that accelerates the TSF during a chip reset.
207 		 *
208 		 * We could use system timer routines to more
209 		 * accurately restore the TSF, but
210 		 * 1. Timer routines on certain platforms are
211 		 *	not accurate enough (e.g. 1 ms resolution).
212 		 * 2. It would still not be accurate.
213 		 *
214 		 * The most important aspect of this workaround,
215 		 * is that, after reset, the TSF is behind
216 		 * other STAs TSFs.  This will allow the STA to
217 		 * properly resynchronize its TSF in adhoc mode.
218 		 */
219 		saveTsfLow  = OS_REG_READ(ah, AR_TSF_L32);
220 		saveTsfHigh = OS_REG_READ(ah, AR_TSF_U32);
221 
222 		/* Read frame sequence count */
223 		if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
224 			saveFrameSeqCount[0] = OS_REG_READ(ah, AR_D0_SEQNUM);
225 		} else {
226 			for (i = 0; i < AR_NUM_DCU; i++)
227 				saveFrameSeqCount[i] = OS_REG_READ(ah, AR_DSEQNUM(i));
228 		}
229 		if (!IEEE80211_IS_CHAN_DFS(chan))
230 			chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
231 	}
232 
233 	/*
234 	 * Preserve the antenna on a channel change
235 	 */
236 	saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
237 	if (saveDefAntenna == 0)
238 		saveDefAntenna = 1;
239 
240 	/* Save hardware flag before chip reset clears the register */
241 	macStaId1 = OS_REG_READ(ah, AR_STA_ID1) & AR_STA_ID1_BASE_RATE_11B;
242 
243 	/* Save led state from pci config register */
244 	ledstate = OS_REG_READ(ah, AR_PCICFG) &
245 		(AR_PCICFG_LEDCTL | AR_PCICFG_LEDMODE | AR_PCICFG_LEDBLINK |
246 		 AR_PCICFG_LEDSLOW);
247 	softLedCfg = OS_REG_READ(ah, AR_GPIOCR);
248 	softLedState = OS_REG_READ(ah, AR_GPIODO);
249 
250 	if (!ar5211ChipReset(ah, chan)) {
251 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
252 		FAIL(HAL_EIO);
253 	}
254 
255 	/* Setup the indices for the next set of register array writes */
256 	if (IEEE80211_IS_CHAN_5GHZ(chan)) {
257 		freqIndex = 1;
258 		if (IEEE80211_IS_CHAN_TURBO(chan))
259 			modesIndex = 2;
260 		else if (IEEE80211_IS_CHAN_A(chan))
261 			modesIndex = 1;
262 		else {
263 			HALDEBUG(ah, HAL_DEBUG_ANY,
264 			    "%s: invalid channel %u/0x%x\n",
265 			    __func__, chan->ic_freq, chan->ic_flags);
266 			FAIL(HAL_EINVAL);
267 		}
268 	} else {
269 		freqIndex = 2;
270 		if (IEEE80211_IS_CHAN_B(chan))
271 			modesIndex = 3;
272 		else if (IEEE80211_IS_CHAN_PUREG(chan))
273 			modesIndex = 4;
274 		else {
275 			HALDEBUG(ah, HAL_DEBUG_ANY,
276 			    "%s: invalid channel %u/0x%x\n",
277 			    __func__, chan->ic_freq, chan->ic_flags);
278 			FAIL(HAL_EINVAL);
279 		}
280 	}
281 
282 	/* Set correct Baseband to analog shift setting to access analog chips. */
283 	if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
284 		OS_REG_WRITE(ah, AR_PHY_BASE, 0x00000007);
285 	} else {
286 		OS_REG_WRITE(ah, AR_PHY_BASE, 0x00000047);
287 	}
288 
289 	/* Write parameters specific to AR5211 */
290 	if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
291 		if (IEEE80211_IS_CHAN_2GHZ(chan) &&
292 		    AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1) {
293 			HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
294 			uint32_t ob2GHz, db2GHz;
295 
296 			if (IEEE80211_IS_CHAN_CCK(chan)) {
297 				ob2GHz = ee->ee_ob2GHz[0];
298 				db2GHz = ee->ee_db2GHz[0];
299 			} else {
300 				ob2GHz = ee->ee_ob2GHz[1];
301 				db2GHz = ee->ee_db2GHz[1];
302 			}
303 			ob2GHz = ath_hal_reverseBits(ob2GHz, 3);
304 			db2GHz = ath_hal_reverseBits(db2GHz, 3);
305 			ar5211Mode2_4[25][freqIndex] =
306 				(ar5211Mode2_4[25][freqIndex] & ~0xC0) |
307 					((ob2GHz << 6) & 0xC0);
308 			ar5211Mode2_4[26][freqIndex] =
309 				(ar5211Mode2_4[26][freqIndex] & ~0x0F) |
310 					(((ob2GHz >> 2) & 0x1) |
311 					 ((db2GHz << 1) & 0x0E));
312 		}
313 		for (i = 0; i < N(ar5211Mode2_4); i++)
314 			OS_REG_WRITE(ah, ar5211Mode2_4[i][0],
315 				ar5211Mode2_4[i][freqIndex]);
316 	}
317 
318 	/* Write the analog registers 6 and 7 before other config */
319 	ar5211SetRf6and7(ah, chan);
320 
321 	/* Write registers that vary across all modes */
322 	for (i = 0; i < N(ar5211Modes); i++)
323 		OS_REG_WRITE(ah, ar5211Modes[i][0], ar5211Modes[i][modesIndex]);
324 
325 	/* Write RFGain Parameters that differ between 2.4 and 5 GHz */
326 	for (i = 0; i < N(ar5211BB_RfGain); i++)
327 		OS_REG_WRITE(ah, ar5211BB_RfGain[i][0], ar5211BB_RfGain[i][freqIndex]);
328 
329 	/* Write Common Array Parameters */
330 	for (i = 0; i < N(ar5211Common); i++) {
331 		uint32_t reg = ar5211Common[i][0];
332 		/* On channel change, don't reset the PCU registers */
333 		if (!(bChannelChange && (0x8000 <= reg && reg < 0x9000)))
334 			OS_REG_WRITE(ah, reg, ar5211Common[i][1]);
335 	}
336 
337 	/* Fix pre-AR5211 register values, this includes AR5311s. */
338 	if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU) {
339 		/*
340 		 * The TX and RX latency values have changed locations
341 		 * within the USEC register in AR5211.  Since they're
342 		 * set via the .ini, for both AR5211 and AR5311, they
343 		 * are written properly here for AR5311.
344 		 */
345 		data = OS_REG_READ(ah, AR_USEC);
346 		/* Must be 0 for proper write in AR5311 */
347 		HALASSERT((data & 0x00700000) == 0);
348 		OS_REG_WRITE(ah, AR_USEC,
349 			(data & (AR_USEC_M | AR_USEC_32_M | AR5311_USEC_TX_LAT_M)) |
350 			((29 << AR5311_USEC_RX_LAT_S) & AR5311_USEC_RX_LAT_M));
351 		/* The following registers exist only on AR5311. */
352 		OS_REG_WRITE(ah, AR5311_QDCLKGATE, 0);
353 
354 		/* Set proper ADC & DAC delays for AR5311. */
355 		OS_REG_WRITE(ah, 0x00009878, 0x00000008);
356 
357 		/* Enable the PCU FIFO corruption ECO on AR5311. */
358 		OS_REG_WRITE(ah, AR_DIAG_SW,
359 			OS_REG_READ(ah, AR_DIAG_SW) | AR5311_DIAG_SW_USE_ECO);
360 	}
361 
362 	/* Restore certain DMA hardware registers on a channel change */
363 	if (bChannelChange) {
364 		/* Restore TSF */
365 		OS_REG_WRITE(ah, AR_TSF_L32, saveTsfLow);
366 		OS_REG_WRITE(ah, AR_TSF_U32, saveTsfHigh);
367 
368 		if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
369 			OS_REG_WRITE(ah, AR_D0_SEQNUM, saveFrameSeqCount[0]);
370 		} else {
371 			for (i = 0; i < AR_NUM_DCU; i++)
372 				OS_REG_WRITE(ah, AR_DSEQNUM(i), saveFrameSeqCount[i]);
373 		}
374 	}
375 
376 	OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
377 	OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
378 		| macStaId1
379 	);
380 	ar5211SetOperatingMode(ah, opmode);
381 
382 	/* Restore previous led state */
383 	OS_REG_WRITE(ah, AR_PCICFG, OS_REG_READ(ah, AR_PCICFG) | ledstate);
384 	OS_REG_WRITE(ah, AR_GPIOCR, softLedCfg);
385 	OS_REG_WRITE(ah, AR_GPIODO, softLedState);
386 
387 	/* Restore previous antenna */
388 	OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
389 
390 	OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
391 	OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4));
392 
393 	/* Restore bmiss rssi & count thresholds */
394 	OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
395 
396 	OS_REG_WRITE(ah, AR_ISR, ~0);		/* cleared on write */
397 
398 	/*
399 	 * for pre-Production Oahu only.
400 	 * Disable clock gating in all DMA blocks. Helps when using
401 	 * 11B and AES but results in higher power consumption.
402 	 */
403 	if (AH_PRIVATE(ah)->ah_macVersion == AR_SREV_VERSION_OAHU &&
404 	    AH_PRIVATE(ah)->ah_macRev < AR_SREV_OAHU_PROD) {
405 		OS_REG_WRITE(ah, AR_CFG,
406 			OS_REG_READ(ah, AR_CFG) | AR_CFG_CLK_GATE_DIS);
407 	}
408 
409 	/* Setup the transmit power values. */
410 	if (!ar5211SetTransmitPower(ah, chan)) {
411 		HALDEBUG(ah, HAL_DEBUG_ANY,
412 		    "%s: error init'ing transmit power\n", __func__);
413 		FAIL(HAL_EIO);
414 	}
415 
416 	/*
417 	 * Configurable OFDM spoofing for 11n compatibility; used
418 	 * only when operating in station mode.
419 	 */
420 	if (opmode != HAL_M_HOSTAP &&
421 	    (AH_PRIVATE(ah)->ah_11nCompat & HAL_DIAG_11N_SERVICES) != 0) {
422 		/* NB: override the .ini setting */
423 		OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
424 			AR_PHY_FRAME_CTL_ERR_SERV,
425 			MS(AH_PRIVATE(ah)->ah_11nCompat, HAL_DIAG_11N_SERVICES)&1);
426 	}
427 
428 	/* Setup board specific options for EEPROM version 3 */
429 	ar5211SetBoardValues(ah, chan);
430 
431 	if (!ar5211SetChannel(ah, chan)) {
432 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set channel\n",
433 		    __func__);
434 		FAIL(HAL_EIO);
435 	}
436 
437 	/* Activate the PHY */
438 	if (AH_PRIVATE(ah)->ah_devid == AR5211_FPGA11B &&
439 	    IEEE80211_IS_CHAN_2GHZ(chan))
440 		OS_REG_WRITE(ah, 0xd808, 0x502); /* required for FPGA */
441 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
442 
443 	/*
444 	 * Wait for the frequency synth to settle (synth goes on
445 	 * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
446 	 * Value is in 100ns increments.
447 	 */
448 	data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_M;
449 	if (IEEE80211_IS_CHAN_CCK(chan)) {
450 		synthDelay = (4 * data) / 22;
451 	} else {
452 		synthDelay = data / 10;
453 	}
454 	/*
455 	 * There is an issue if the AP starts the calibration before
456 	 * the baseband timeout completes.  This could result in the
457 	 * rxclear false triggering.  Add an extra delay to ensure this
458 	 * this does not happen.
459 	 */
460 	OS_DELAY(synthDelay + DELAY_BASE_ACTIVATE);
461 
462 	/* Calibrate the AGC and wait for completion. */
463 	OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
464 		 OS_REG_READ(ah, AR_PHY_AGC_CONTROL) | AR_PHY_AGC_CONTROL_CAL);
465 	(void) ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0);
466 
467 	/* Perform noise floor and set status */
468 	if (!ar5211CalNoiseFloor(ah, chan)) {
469 		if (!IEEE80211_IS_CHAN_CCK(chan))
470 			chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
471 		HALDEBUG(ah, HAL_DEBUG_ANY,
472 		    "%s: noise floor calibration failed\n", __func__);
473 		FAIL(HAL_EIO);
474 	}
475 
476 	/* Start IQ calibration w/ 2^(INIT_IQCAL_LOG_COUNT_MAX+1) samples */
477 	if (ahp->ah_calibrationTime != 0) {
478 		OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4,
479 			AR_PHY_TIMING_CTRL4_DO_IQCAL | (INIT_IQCAL_LOG_COUNT_MAX << AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX_S));
480 		ahp->ah_bIQCalibration = AH_TRUE;
481 	}
482 
483 	/* set 1:1 QCU to DCU mapping for all queues */
484 	for (q = 0; q < AR_NUM_DCU; q++)
485 		OS_REG_WRITE(ah, AR_DQCUMASK(q), 1<<q);
486 
487 	for (q = 0; q < HAL_NUM_TX_QUEUES; q++)
488 		ar5211ResetTxQueue(ah, q);
489 
490 	/* Setup QCU0 transmit interrupt masks (TX_ERR, TX_OK, TX_DESC, TX_URN) */
491 	OS_REG_WRITE(ah, AR_IMR_S0,
492 		 (AR_IMR_S0_QCU_TXOK & AR_QCU_0) |
493 		 (AR_IMR_S0_QCU_TXDESC & (AR_QCU_0<<AR_IMR_S0_QCU_TXDESC_S)));
494 	OS_REG_WRITE(ah, AR_IMR_S1, (AR_IMR_S1_QCU_TXERR & AR_QCU_0));
495 	OS_REG_WRITE(ah, AR_IMR_S2, (AR_IMR_S2_QCU_TXURN & AR_QCU_0));
496 
497 	/*
498 	 * GBL_EIFS must always be written after writing
499 	 *		to any QCUMASK register.
500 	 */
501 	OS_REG_WRITE(ah, AR_D_GBL_IFS_EIFS, OS_REG_READ(ah, AR_D_GBL_IFS_EIFS));
502 
503 	/* Now set up the Interrupt Mask Register and save it for future use */
504 	OS_REG_WRITE(ah, AR_IMR, INIT_INTERRUPT_MASK);
505 	ahp->ah_maskReg = INIT_INTERRUPT_MASK;
506 
507 	/* Enable bus error interrupts */
508 	OS_REG_WRITE(ah, AR_IMR_S2, OS_REG_READ(ah, AR_IMR_S2) |
509 		 AR_IMR_S2_MCABT | AR_IMR_S2_SSERR | AR_IMR_S2_DPERR);
510 
511 	/* Enable interrupts specific to AP */
512 	if (opmode == HAL_M_HOSTAP) {
513 		OS_REG_WRITE(ah, AR_IMR, OS_REG_READ(ah, AR_IMR) | AR_IMR_MIB);
514 		ahp->ah_maskReg |= AR_IMR_MIB;
515 	}
516 
517 	if (AH_PRIVATE(ah)->ah_rfkillEnabled)
518 		ar5211EnableRfKill(ah);
519 
520 	/*
521 	 * Writing to AR_BEACON will start timers. Hence it should
522 	 * be the last register to be written. Do not reset tsf, do
523 	 * not enable beacons at this point, but preserve other values
524 	 * like beaconInterval.
525 	 */
526 	OS_REG_WRITE(ah, AR_BEACON,
527 		(OS_REG_READ(ah, AR_BEACON) &~ (AR_BEACON_EN | AR_BEACON_RESET_TSF)));
528 
529 	/* Restore user-specified slot time and timeouts */
530 	if (ahp->ah_sifstime != (u_int) -1)
531 		ar5211SetSifsTime(ah, ahp->ah_sifstime);
532 	if (ahp->ah_slottime != (u_int) -1)
533 		ar5211SetSlotTime(ah, ahp->ah_slottime);
534 	if (ahp->ah_acktimeout != (u_int) -1)
535 		ar5211SetAckTimeout(ah, ahp->ah_acktimeout);
536 	if (ahp->ah_ctstimeout != (u_int) -1)
537 		ar5211SetCTSTimeout(ah, ahp->ah_ctstimeout);
538 	if (AH_PRIVATE(ah)->ah_diagreg != 0)
539 		OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
540 
541 	AH_PRIVATE(ah)->ah_opmode = opmode;	/* record operating mode */
542 
543 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
544 
545 	return AH_TRUE;
546 bad:
547 	if (status != AH_NULL)
548 		*status = ecode;
549 	return AH_FALSE;
550 #undef FAIL
551 #undef N
552 }
553 
554 /*
555  * Places the PHY and Radio chips into reset.  A full reset
556  * must be called to leave this state.  The PCI/MAC/PCU are
557  * not placed into reset as we must receive interrupt to
558  * re-enable the hardware.
559  */
560 HAL_BOOL
561 ar5211PhyDisable(struct ath_hal *ah)
562 {
563 	return ar5211SetResetReg(ah, AR_RC_BB);
564 }
565 
566 /*
567  * Places all of hardware into reset
568  */
569 HAL_BOOL
570 ar5211Disable(struct ath_hal *ah)
571 {
572 	if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
573 		return AH_FALSE;
574 	/*
575 	 * Reset the HW - PCI must be reset after the rest of the
576 	 * device has been reset.
577 	 */
578 	if (!ar5211SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI))
579 		return AH_FALSE;
580 	OS_DELAY(2100);	   /* 8245 @ 96Mhz hangs with 2000us. */
581 
582 	return AH_TRUE;
583 }
584 
585 /*
586  * Places the hardware into reset and then pulls it out of reset
587  *
588  * Only write the PLL if we're changing to or from CCK mode
589  *
590  * Attach calls with channelFlags = 0, as the coldreset should have
591  * us in the correct mode and we cannot check the hwchannel flags.
592  */
593 HAL_BOOL
594 ar5211ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
595 {
596 	if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
597 		return AH_FALSE;
598 
599 	/* NB: called from attach with chan null */
600 	if (chan != AH_NULL) {
601 		/* Set CCK and Turbo modes correctly */
602 		OS_REG_WRITE(ah, AR_PHY_TURBO, IEEE80211_IS_CHAN_TURBO(chan) ?
603 		    AR_PHY_FC_TURBO_MODE | AR_PHY_FC_TURBO_SHORT : 0);
604 		if (IEEE80211_IS_CHAN_B(chan)) {
605 			OS_REG_WRITE(ah, AR5211_PHY_MODE,
606 			    AR5211_PHY_MODE_CCK | AR5211_PHY_MODE_RF2GHZ);
607 			OS_REG_WRITE(ah, AR_PHY_PLL_CTL, AR_PHY_PLL_CTL_44);
608 			/* Wait for the PLL to settle */
609 			OS_DELAY(DELAY_PLL_SETTLE);
610 		} else if (AH_PRIVATE(ah)->ah_devid == AR5211_DEVID) {
611 			OS_REG_WRITE(ah, AR_PHY_PLL_CTL, AR_PHY_PLL_CTL_40);
612 			OS_DELAY(DELAY_PLL_SETTLE);
613 			OS_REG_WRITE(ah, AR5211_PHY_MODE,
614 			    AR5211_PHY_MODE_OFDM | (IEEE80211_IS_CHAN_2GHZ(chan) ?
615 				AR5211_PHY_MODE_RF2GHZ :
616 				AR5211_PHY_MODE_RF5GHZ));
617 		}
618 	}
619 
620 	/*
621 	 * Reset the HW - PCI must be reset after the rest of the
622 	 * device has been reset
623 	 */
624 	if (!ar5211SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI))
625 		return AH_FALSE;
626 	OS_DELAY(2100);	   /* 8245 @ 96Mhz hangs with 2000us. */
627 
628 	/* Bring out of sleep mode (AGAIN) */
629 	if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
630 		return AH_FALSE;
631 
632 	/* Clear warm reset register */
633 	return ar5211SetResetReg(ah, 0);
634 }
635 
636 /*
637  * Recalibrate the lower PHY chips to account for temperature/environment
638  * changes.
639  */
640 HAL_BOOL
641 ar5211PerCalibrationN(struct ath_hal *ah,  struct ieee80211_channel *chan,
642 	u_int chainMask, HAL_BOOL longCal, HAL_BOOL *isCalDone)
643 {
644 	struct ath_hal_5211 *ahp = AH5211(ah);
645 	HAL_CHANNEL_INTERNAL *ichan;
646 	int32_t qCoff, qCoffDenom;
647 	uint32_t data;
648 	int32_t iqCorrMeas;
649 	int32_t iCoff, iCoffDenom;
650 	uint32_t powerMeasQ, powerMeasI;
651 
652 	ichan = ath_hal_checkchannel(ah, chan);
653 	if (ichan == AH_NULL) {
654 		HALDEBUG(ah, HAL_DEBUG_ANY,
655 		    "%s: invalid channel %u/0x%x; no mapping\n",
656 		    __func__, chan->ic_freq, chan->ic_flags);
657 		return AH_FALSE;
658 	}
659 	/* IQ calibration in progress. Check to see if it has finished. */
660 	if (ahp->ah_bIQCalibration &&
661 	    !(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_DO_IQCAL)) {
662 		/* IQ Calibration has finished. */
663 		ahp->ah_bIQCalibration = AH_FALSE;
664 
665 		/* Read calibration results. */
666 		powerMeasI = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_I);
667 		powerMeasQ = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_Q);
668 		iqCorrMeas = OS_REG_READ(ah, AR_PHY_IQCAL_RES_IQ_CORR_MEAS);
669 
670 		/*
671 		 * Prescale these values to remove 64-bit operation requirement at the loss
672 		 * of a little precision.
673 		 */
674 		iCoffDenom = (powerMeasI / 2 + powerMeasQ / 2) / 128;
675 		qCoffDenom = powerMeasQ / 64;
676 
677 		/* Protect against divide-by-0. */
678 		if (iCoffDenom != 0 && qCoffDenom != 0) {
679 			iCoff = (-iqCorrMeas) / iCoffDenom;
680 			/* IQCORR_Q_I_COFF is a signed 6 bit number */
681 			iCoff = iCoff & 0x3f;
682 
683 			qCoff = ((int32_t)powerMeasI / qCoffDenom) - 64;
684 			/* IQCORR_Q_Q_COFF is a signed 5 bit number */
685 			qCoff = qCoff & 0x1f;
686 
687 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "powerMeasI = 0x%08x\n",
688 			    powerMeasI);
689 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "powerMeasQ = 0x%08x\n",
690 			    powerMeasQ);
691 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "iqCorrMeas = 0x%08x\n",
692 			    iqCorrMeas);
693 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "iCoff	  = %d\n",
694 			    iCoff);
695 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "qCoff	  = %d\n",
696 			    qCoff);
697 
698 			/* Write IQ */
699 			data  = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) |
700 				AR_PHY_TIMING_CTRL4_IQCORR_ENABLE |
701 				(((uint32_t)iCoff) << AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF_S) |
702 				((uint32_t)qCoff);
703 			OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4, data);
704 		}
705 	}
706 	*isCalDone = !ahp->ah_bIQCalibration;
707 
708 	if (longCal) {
709 		/* Perform noise floor and set status */
710 		if (!ar5211IsNfGood(ah, chan)) {
711 			/* report up and clear internal state */
712 			chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
713 			return AH_FALSE;
714 		}
715 		if (!ar5211CalNoiseFloor(ah, chan)) {
716 			/*
717 			 * Delay 5ms before retrying the noise floor
718 			 * just to make sure, as we are in an error
719 			 * condition here.
720 			 */
721 			OS_DELAY(5000);
722 			if (!ar5211CalNoiseFloor(ah, chan)) {
723 				if (!IEEE80211_IS_CHAN_CCK(chan))
724 					chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
725 				return AH_FALSE;
726 			}
727 		}
728 		ar5211RequestRfgain(ah);
729 	}
730 	return AH_TRUE;
731 }
732 
733 HAL_BOOL
734 ar5211PerCalibration(struct ath_hal *ah, struct ieee80211_channel *chan,
735 	HAL_BOOL *isIQdone)
736 {
737 	return ar5211PerCalibrationN(ah,  chan, 0x1, AH_TRUE, isIQdone);
738 }
739 
740 HAL_BOOL
741 ar5211ResetCalValid(struct ath_hal *ah, const struct ieee80211_channel *chan)
742 {
743 	/* XXX */
744 	return AH_TRUE;
745 }
746 
747 /*
748  * Writes the given reset bit mask into the reset register
749  */
750 static HAL_BOOL
751 ar5211SetResetReg(struct ath_hal *ah, uint32_t resetMask)
752 {
753 	uint32_t mask = resetMask ? resetMask : ~0;
754 	HAL_BOOL rt;
755 
756 	(void) OS_REG_READ(ah, AR_RXDP);/* flush any pending MMR writes */
757 	OS_REG_WRITE(ah, AR_RC, resetMask);
758 
759 	/* need to wait at least 128 clocks when reseting PCI before read */
760 	OS_DELAY(15);
761 
762 	resetMask &= AR_RC_MAC | AR_RC_BB;
763 	mask &= AR_RC_MAC | AR_RC_BB;
764 	rt = ath_hal_wait(ah, AR_RC, mask, resetMask);
765         if ((resetMask & AR_RC_MAC) == 0) {
766 		if (isBigEndian()) {
767 			/*
768 			 * Set CFG, little-endian for descriptor accesses.
769 			 */
770 			mask = INIT_CONFIG_STATUS | AR_CFG_SWTD | AR_CFG_SWRD;
771 			OS_REG_WRITE(ah, AR_CFG, mask);
772 		} else
773 			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
774 	}
775 	return rt;
776 }
777 
778 /*
779  * Takes the MHz channel value and sets the Channel value
780  *
781  * ASSUMES: Writes enabled to analog bus before AGC is active
782  *   or by disabling the AGC.
783  */
784 static HAL_BOOL
785 ar5211SetChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
786 {
787 	uint32_t refClk, reg32, data2111;
788 	int16_t chan5111, chanIEEE;
789 
790 	chanIEEE = chan->ic_ieee;
791 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
792 		const CHAN_INFO_2GHZ* ci =
793 			&chan2GHzData[chanIEEE + CI_2GHZ_INDEX_CORRECTION];
794 
795 		data2111 = ((ath_hal_reverseBits(ci->channelSelect, 8) & 0xff)
796 				<< 5)
797 			 | (ci->refClkSel << 4);
798 		chan5111 = ci->channel5111;
799 	} else {
800 		data2111 = 0;
801 		chan5111 = chanIEEE;
802 	}
803 
804 	/* Rest of the code is common for 5 GHz and 2.4 GHz. */
805 	if (chan5111 >= 145 || (chan5111 & 0x1)) {
806 		reg32 = ath_hal_reverseBits(chan5111 - 24, 8) & 0xFF;
807 		refClk = 1;
808 	} else {
809 		reg32 = ath_hal_reverseBits(((chan5111 - 24) / 2), 8) & 0xFF;
810 		refClk = 0;
811 	}
812 
813 	reg32 = (reg32 << 2) | (refClk << 1) | (1 << 10) | 0x1;
814 	OS_REG_WRITE(ah, AR_PHY(0x27), ((data2111 & 0xff) << 8) | (reg32 & 0xff));
815 	reg32 >>= 8;
816 	OS_REG_WRITE(ah, AR_PHY(0x34), (data2111 & 0xff00) | (reg32 & 0xff));
817 
818 	AH_PRIVATE(ah)->ah_curchan = chan;
819 	return AH_TRUE;
820 }
821 
822 static int16_t
823 ar5211GetNoiseFloor(struct ath_hal *ah)
824 {
825 	int16_t nf;
826 
827 	nf = (OS_REG_READ(ah, AR_PHY(25)) >> 19) & 0x1ff;
828 	if (nf & 0x100)
829 		nf = 0 - ((nf ^ 0x1ff) + 1);
830 	return nf;
831 }
832 
833 /*
834  * Peform the noisefloor calibration for the length of time set
835  * in runTime (valid values 1 to 7)
836  *
837  * Returns: The NF value at the end of the given time (or 0 for failure)
838  */
839 int16_t
840 ar5211RunNoiseFloor(struct ath_hal *ah, uint8_t runTime, int16_t startingNF)
841 {
842 	int i, searchTime;
843 
844 	HALASSERT(runTime <= 7);
845 
846 	/* Setup  noise floor run time and starting value */
847 	OS_REG_WRITE(ah, AR_PHY(25),
848 		(OS_REG_READ(ah, AR_PHY(25)) & ~0xFFF) |
849 			 ((runTime << 9) & 0xE00) | (startingNF & 0x1FF));
850 	/* Calibrate the noise floor */
851 	OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
852 		OS_REG_READ(ah, AR_PHY_AGC_CONTROL) | AR_PHY_AGC_CONTROL_NF);
853 
854 	/* Compute the required amount of searchTime needed to finish NF */
855 	if (runTime == 0) {
856 		/* 8 search windows * 6.4us each */
857 		searchTime = 8  * 7;
858 	} else {
859 		/* 512 * runtime search windows * 6.4us each */
860 		searchTime = (runTime * 512)  * 7;
861 	}
862 
863 	/*
864 	 * Do not read noise floor until it has been updated
865 	 *
866 	 * As a guesstimate - we may only get 1/60th the time on
867 	 * the air to see search windows  in a heavily congested
868 	 * network (40 us every 2400 us of time)
869 	 */
870 	for (i = 0; i < 60; i++) {
871 		if ((OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) == 0)
872 			break;
873 		OS_DELAY(searchTime);
874 	}
875 	if (i >= 60) {
876 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
877 		    "NF with runTime %d failed to end on channel %d\n",
878 		    runTime, AH_PRIVATE(ah)->ah_curchan->ic_freq);
879 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
880 		    "  PHY NF Reg state:	 0x%x\n",
881 		    OS_REG_READ(ah, AR_PHY_AGC_CONTROL));
882 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
883 		    "  PHY Active Reg state: 0x%x\n",
884 		    OS_REG_READ(ah, AR_PHY_ACTIVE));
885 		return 0;
886 	}
887 
888 	return ar5211GetNoiseFloor(ah);
889 }
890 
891 static HAL_BOOL
892 getNoiseFloorThresh(struct ath_hal *ah, const struct ieee80211_channel *chan,
893 	int16_t *nft)
894 {
895 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
896 
897 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
898 	case IEEE80211_CHAN_A:
899 		*nft = ee->ee_noiseFloorThresh[0];
900 		break;
901 	case IEEE80211_CHAN_B:
902 		*nft = ee->ee_noiseFloorThresh[1];
903 		break;
904 	case IEEE80211_CHAN_PUREG:
905 		*nft = ee->ee_noiseFloorThresh[2];
906 		break;
907 	default:
908 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
909 		    __func__, chan->ic_flags);
910 		return AH_FALSE;
911 	}
912 	return AH_TRUE;
913 }
914 
915 /*
916  * Read the NF and check it against the noise floor threshold
917  *
918  * Returns: TRUE if the NF is good
919  */
920 static HAL_BOOL
921 ar5211IsNfGood(struct ath_hal *ah, struct ieee80211_channel *chan)
922 {
923 	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
924 	int16_t nf, nfThresh;
925 
926 	if (!getNoiseFloorThresh(ah, chan, &nfThresh))
927 		return AH_FALSE;
928 	if (OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) {
929 		HALDEBUG(ah, HAL_DEBUG_ANY,
930 		    "%s: NF did not complete in calibration window\n", __func__);
931 	}
932 	nf = ar5211GetNoiseFloor(ah);
933 	if (nf > nfThresh) {
934 		HALDEBUG(ah, HAL_DEBUG_ANY,
935 		    "%s: noise floor failed; detected %u, threshold %u\n",
936 		    __func__, nf, nfThresh);
937 		/*
938 		 * NB: Don't discriminate 2.4 vs 5Ghz, if this
939 		 *     happens it indicates a problem regardless
940 		 *     of the band.
941 		 */
942 		chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
943 	}
944 	ichan->rawNoiseFloor = nf;
945 	return (nf <= nfThresh);
946 }
947 
948 /*
949  * Peform the noisefloor calibration and check for any constant channel
950  * interference.
951  *
952  * NOTE: preAR5211 have a lengthy carrier wave detection process - hence
953  * it is if'ed for MKK regulatory domain only.
954  *
955  * Returns: TRUE for a successful noise floor calibration; else FALSE
956  */
957 HAL_BOOL
958 ar5211CalNoiseFloor(struct ath_hal *ah, const struct ieee80211_channel *chan)
959 {
960 #define	N(a)	(sizeof (a) / sizeof (a[0]))
961 	/* Check for Carrier Wave interference in MKK regulatory zone */
962 	if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU &&
963 	    (chan->ic_flags & CHANNEL_NFCREQUIRED)) {
964 		static const uint8_t runtime[3] = { 0, 2, 7 };
965 		HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
966 		int16_t nf, nfThresh;
967 		int i;
968 
969 		if (!getNoiseFloorThresh(ah, chan, &nfThresh))
970 			return AH_FALSE;
971 		/*
972 		 * Run a quick noise floor that will hopefully
973 		 * complete (decrease delay time).
974 		 */
975 		for (i = 0; i < N(runtime); i++) {
976 			nf = ar5211RunNoiseFloor(ah, runtime[i], 0);
977 			if (nf > nfThresh) {
978 				HALDEBUG(ah, HAL_DEBUG_ANY,
979 				    "%s: run failed with %u > threshold %u "
980 				    "(runtime %u)\n", __func__,
981 				    nf, nfThresh, runtime[i]);
982 				ichan->rawNoiseFloor = 0;
983 			} else
984 				ichan->rawNoiseFloor = nf;
985 		}
986 		return (i <= N(runtime));
987 	} else {
988 		/* Calibrate the noise floor */
989 		OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
990 			OS_REG_READ(ah, AR_PHY_AGC_CONTROL) |
991 				 AR_PHY_AGC_CONTROL_NF);
992 	}
993 	return AH_TRUE;
994 #undef N
995 }
996 
997 /*
998  * Adjust NF based on statistical values for 5GHz frequencies.
999  */
1000 int16_t
1001 ar5211GetNfAdjust(struct ath_hal *ah, const HAL_CHANNEL_INTERNAL *c)
1002 {
1003 	static const struct {
1004 		uint16_t freqLow;
1005 		int16_t	  adjust;
1006 	} adjust5111[] = {
1007 		{ 5790,	11 },	/* NB: ordered high -> low */
1008 		{ 5730, 10 },
1009 		{ 5690,  9 },
1010 		{ 5660,  8 },
1011 		{ 5610,  7 },
1012 		{ 5530,  5 },
1013 		{ 5450,  4 },
1014 		{ 5379,  2 },
1015 		{ 5209,  0 },	/* XXX? bogus but doesn't matter */
1016 		{    0,  1 },
1017 	};
1018 	int i;
1019 
1020 	for (i = 0; c->channel <= adjust5111[i].freqLow; i++)
1021 		;
1022 	/* NB: placeholder for 5111's less severe requirement */
1023 	return adjust5111[i].adjust / 3;
1024 }
1025 
1026 /*
1027  * Reads EEPROM header info from device structure and programs
1028  * analog registers 6 and 7
1029  *
1030  * REQUIRES: Access to the analog device
1031  */
1032 static HAL_BOOL
1033 ar5211SetRf6and7(struct ath_hal *ah, const struct ieee80211_channel *chan)
1034 {
1035 #define	N(a)	(sizeof (a) / sizeof (a[0]))
1036 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1037 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1038 	struct ath_hal_5211 *ahp = AH5211(ah);
1039 	uint16_t rfXpdGain, rfPloSel, rfPwdXpd;
1040 	uint16_t tempOB, tempDB;
1041 	uint16_t freqIndex;
1042 	int i;
1043 
1044 	freqIndex = IEEE80211_IS_CHAN_2GHZ(chan) ? 2 : 1;
1045 
1046 	/*
1047 	 * TODO: This array mode correspondes with the index used
1048 	 *	 during the read.
1049 	 * For readability, this should be changed to an enum or #define
1050 	 */
1051 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1052 	case IEEE80211_CHAN_A:
1053 		if (freq > 4000 && freq < 5260) {
1054 			tempOB = ee->ee_ob1;
1055 			tempDB = ee->ee_db1;
1056 		} else if (freq >= 5260 && freq < 5500) {
1057 			tempOB = ee->ee_ob2;
1058 			tempDB = ee->ee_db2;
1059 		} else if (freq >= 5500 && freq < 5725) {
1060 			tempOB = ee->ee_ob3;
1061 			tempDB = ee->ee_db3;
1062 		} else if (freq >= 5725) {
1063 			tempOB = ee->ee_ob4;
1064 			tempDB = ee->ee_db4;
1065 		} else {
1066 			/* XXX panic?? */
1067 			tempOB = tempDB = 0;
1068 		}
1069 
1070 		rfXpdGain = ee->ee_xgain[0];
1071 		rfPloSel  = ee->ee_xpd[0];
1072 		rfPwdXpd  = !ee->ee_xpd[0];
1073 
1074 		ar5211Rf6n7[5][freqIndex]  =
1075 			(ar5211Rf6n7[5][freqIndex] & ~0x10000000) |
1076 				(ee->ee_cornerCal.pd84<< 28);
1077 		ar5211Rf6n7[6][freqIndex]  =
1078 			(ar5211Rf6n7[6][freqIndex] & ~0x04000000) |
1079 				(ee->ee_cornerCal.pd90 << 26);
1080 		ar5211Rf6n7[21][freqIndex] =
1081 			(ar5211Rf6n7[21][freqIndex] & ~0x08) |
1082 				(ee->ee_cornerCal.gSel << 3);
1083 		break;
1084 	case IEEE80211_CHAN_B:
1085 		tempOB = ee->ee_obFor24;
1086 		tempDB = ee->ee_dbFor24;
1087 		rfXpdGain = ee->ee_xgain[1];
1088 		rfPloSel  = ee->ee_xpd[1];
1089 		rfPwdXpd  = !ee->ee_xpd[1];
1090 		break;
1091 	case IEEE80211_CHAN_PUREG:
1092 		tempOB = ee->ee_obFor24g;
1093 		tempDB = ee->ee_dbFor24g;
1094 		rfXpdGain = ee->ee_xgain[2];
1095 		rfPloSel  = ee->ee_xpd[2];
1096 		rfPwdXpd  = !ee->ee_xpd[2];
1097 		break;
1098 	default:
1099 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1100 		    __func__, chan->ic_flags);
1101 		return AH_FALSE;
1102 	}
1103 
1104 	HALASSERT(1 <= tempOB && tempOB <= 5);
1105 	HALASSERT(1 <= tempDB && tempDB <= 5);
1106 
1107 	/* Set rfXpdGain and rfPwdXpd */
1108 	ar5211Rf6n7[11][freqIndex] =  (ar5211Rf6n7[11][freqIndex] & ~0xC0) |
1109 		(((ath_hal_reverseBits(rfXpdGain, 4) << 7) | (rfPwdXpd << 6)) & 0xC0);
1110 	ar5211Rf6n7[12][freqIndex] =  (ar5211Rf6n7[12][freqIndex] & ~0x07) |
1111 		((ath_hal_reverseBits(rfXpdGain, 4) >> 1) & 0x07);
1112 
1113 	/* Set OB */
1114 	ar5211Rf6n7[12][freqIndex] =  (ar5211Rf6n7[12][freqIndex] & ~0x80) |
1115 		((ath_hal_reverseBits(tempOB, 3) << 7) & 0x80);
1116 	ar5211Rf6n7[13][freqIndex] =  (ar5211Rf6n7[13][freqIndex] & ~0x03) |
1117 		((ath_hal_reverseBits(tempOB, 3) >> 1) & 0x03);
1118 
1119 	/* Set DB */
1120 	ar5211Rf6n7[13][freqIndex] =  (ar5211Rf6n7[13][freqIndex] & ~0x1C) |
1121 		((ath_hal_reverseBits(tempDB, 3) << 2) & 0x1C);
1122 
1123 	/* Set rfPloSel */
1124 	ar5211Rf6n7[17][freqIndex] =  (ar5211Rf6n7[17][freqIndex] & ~0x08) |
1125 		((rfPloSel << 3) & 0x08);
1126 
1127 	/* Write the Rf registers 6 & 7 */
1128 	for (i = 0; i < N(ar5211Rf6n7); i++)
1129 		OS_REG_WRITE(ah, ar5211Rf6n7[i][0], ar5211Rf6n7[i][freqIndex]);
1130 
1131 	/* Now that we have reprogrammed rfgain value, clear the flag. */
1132 	ahp->ah_rfgainState = RFGAIN_INACTIVE;
1133 
1134 	return AH_TRUE;
1135 #undef N
1136 }
1137 
1138 HAL_BOOL
1139 ar5211SetAntennaSwitchInternal(struct ath_hal *ah, HAL_ANT_SETTING settings,
1140 	const struct ieee80211_channel *chan)
1141 {
1142 #define	ANT_SWITCH_TABLE1	0x9960
1143 #define	ANT_SWITCH_TABLE2	0x9964
1144 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1145 	struct ath_hal_5211 *ahp = AH5211(ah);
1146 	uint32_t antSwitchA, antSwitchB;
1147 	int ix;
1148 
1149 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1150 	case IEEE80211_CHAN_A:		ix = 0; break;
1151 	case IEEE80211_CHAN_B:		ix = 1; break;
1152 	case IEEE80211_CHAN_PUREG:	ix = 2; break;
1153 	default:
1154 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1155 		    __func__, chan->ic_flags);
1156 		return AH_FALSE;
1157 	}
1158 
1159 	antSwitchA =  ee->ee_antennaControl[1][ix]
1160 		   | (ee->ee_antennaControl[2][ix] << 6)
1161 		   | (ee->ee_antennaControl[3][ix] << 12)
1162 		   | (ee->ee_antennaControl[4][ix] << 18)
1163 		   | (ee->ee_antennaControl[5][ix] << 24)
1164 		   ;
1165 	antSwitchB =  ee->ee_antennaControl[6][ix]
1166 		   | (ee->ee_antennaControl[7][ix] << 6)
1167 		   | (ee->ee_antennaControl[8][ix] << 12)
1168 		   | (ee->ee_antennaControl[9][ix] << 18)
1169 		   | (ee->ee_antennaControl[10][ix] << 24)
1170 		   ;
1171 	/*
1172 	 * For fixed antenna, give the same setting for both switch banks
1173 	 */
1174 	switch (settings) {
1175 	case HAL_ANT_FIXED_A:
1176 		antSwitchB = antSwitchA;
1177 		break;
1178 	case HAL_ANT_FIXED_B:
1179 		antSwitchA = antSwitchB;
1180 		break;
1181 	case HAL_ANT_VARIABLE:
1182 		break;
1183 	default:
1184 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: bad antenna setting %u\n",
1185 		    __func__, settings);
1186 		return AH_FALSE;
1187 	}
1188 	ahp->ah_diversityControl = settings;
1189 
1190 	OS_REG_WRITE(ah, ANT_SWITCH_TABLE1, antSwitchA);
1191 	OS_REG_WRITE(ah, ANT_SWITCH_TABLE2, antSwitchB);
1192 
1193 	return AH_TRUE;
1194 #undef ANT_SWITCH_TABLE1
1195 #undef ANT_SWITCH_TABLE2
1196 }
1197 
1198 /*
1199  * Reads EEPROM header info and programs the device for correct operation
1200  * given the channel value
1201  */
1202 static HAL_BOOL
1203 ar5211SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1204 {
1205 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1206 	struct ath_hal_5211 *ahp = AH5211(ah);
1207 	int arrayMode, falseDectectBackoff;
1208 
1209 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1210 	case IEEE80211_CHAN_A:
1211 		arrayMode = 0;
1212 		OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
1213 			AR_PHY_FRAME_CTL_TX_CLIP, ee->ee_cornerCal.clip);
1214 		break;
1215 	case IEEE80211_CHAN_B:
1216 		arrayMode = 1;
1217 		break;
1218 	case IEEE80211_CHAN_PUREG:
1219 		arrayMode = 2;
1220 		break;
1221 	default:
1222 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1223 		    __func__, chan->ic_flags);
1224 		return AH_FALSE;
1225 	}
1226 
1227 	/* Set the antenna register(s) correctly for the chip revision */
1228 	if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU) {
1229 		OS_REG_WRITE(ah, AR_PHY(68),
1230 			(OS_REG_READ(ah, AR_PHY(68)) & 0xFFFFFFFC) | 0x3);
1231 	} else {
1232 		OS_REG_WRITE(ah, AR_PHY(68),
1233 			(OS_REG_READ(ah, AR_PHY(68)) & 0xFFFFFC06) |
1234 			(ee->ee_antennaControl[0][arrayMode] << 4) | 0x1);
1235 
1236 		ar5211SetAntennaSwitchInternal(ah,
1237 			ahp->ah_diversityControl, chan);
1238 
1239 		/* Set the Noise Floor Thresh on ar5211 devices */
1240 		OS_REG_WRITE(ah, AR_PHY_BASE + (90 << 2),
1241 			(ee->ee_noiseFloorThresh[arrayMode] & 0x1FF) | (1<<9));
1242 	}
1243 	OS_REG_WRITE(ah, AR_PHY_BASE + (17 << 2),
1244 		(OS_REG_READ(ah, AR_PHY_BASE + (17 << 2)) & 0xFFFFC07F) |
1245 		((ee->ee_switchSettling[arrayMode] << 7) & 0x3F80));
1246 	OS_REG_WRITE(ah, AR_PHY_BASE + (18 << 2),
1247 		(OS_REG_READ(ah, AR_PHY_BASE + (18 << 2)) & 0xFFFC0FFF) |
1248 		((ee->ee_txrxAtten[arrayMode] << 12) & 0x3F000));
1249 	OS_REG_WRITE(ah, AR_PHY_BASE + (20 << 2),
1250 		(OS_REG_READ(ah, AR_PHY_BASE + (20 << 2)) & 0xFFFF0000) |
1251 		((ee->ee_pgaDesiredSize[arrayMode] << 8) & 0xFF00) |
1252 		(ee->ee_adcDesiredSize[arrayMode] & 0x00FF));
1253 	OS_REG_WRITE(ah, AR_PHY_BASE + (13 << 2),
1254 		(ee->ee_txEndToXPAOff[arrayMode] << 24) |
1255 		(ee->ee_txEndToXPAOff[arrayMode] << 16) |
1256 		(ee->ee_txFrameToXPAOn[arrayMode] << 8) |
1257 		ee->ee_txFrameToXPAOn[arrayMode]);
1258 	OS_REG_WRITE(ah, AR_PHY_BASE + (10 << 2),
1259 		(OS_REG_READ(ah, AR_PHY_BASE + (10 << 2)) & 0xFFFF00FF) |
1260 		(ee->ee_txEndToXLNAOn[arrayMode] << 8));
1261 	OS_REG_WRITE(ah, AR_PHY_BASE + (25 << 2),
1262 		(OS_REG_READ(ah, AR_PHY_BASE + (25 << 2)) & 0xFFF80FFF) |
1263 		((ee->ee_thresh62[arrayMode] << 12) & 0x7F000));
1264 
1265 #define NO_FALSE_DETECT_BACKOFF   2
1266 #define CB22_FALSE_DETECT_BACKOFF 6
1267 	/*
1268 	 * False detect backoff - suspected 32 MHz spur causes
1269 	 * false detects in OFDM, causing Tx Hangs.  Decrease
1270 	 * weak signal sensitivity for this card.
1271 	 */
1272 	falseDectectBackoff = NO_FALSE_DETECT_BACKOFF;
1273 	if (AH_PRIVATE(ah)->ah_eeversion < AR_EEPROM_VER3_3) {
1274 		if (AH_PRIVATE(ah)->ah_subvendorid == 0x1022 &&
1275 		    IEEE80211_IS_CHAN_OFDM(chan))
1276 			falseDectectBackoff += CB22_FALSE_DETECT_BACKOFF;
1277 	} else {
1278 		uint16_t freq = ath_hal_gethwchannel(ah, chan);
1279 		uint32_t remainder = freq % 32;
1280 
1281 		if (remainder && (remainder < 10 || remainder > 22))
1282 			falseDectectBackoff += ee->ee_falseDetectBackoff[arrayMode];
1283 	}
1284 	OS_REG_WRITE(ah, 0x9924,
1285 		(OS_REG_READ(ah, 0x9924) & 0xFFFFFF01)
1286 		| ((falseDectectBackoff << 1) & 0xF7));
1287 
1288 	return AH_TRUE;
1289 #undef NO_FALSE_DETECT_BACKOFF
1290 #undef CB22_FALSE_DETECT_BACKOFF
1291 }
1292 
1293 /*
1294  * Set the limit on the overall output power.  Used for dynamic
1295  * transmit power control and the like.
1296  *
1297  * NOTE: The power is passed in is in units of 0.5 dBm.
1298  */
1299 HAL_BOOL
1300 ar5211SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
1301 {
1302 
1303 	AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
1304 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE_MAX, limit);
1305 	return AH_TRUE;
1306 }
1307 
1308 /*
1309  * Sets the transmit power in the baseband for the given
1310  * operating channel and mode.
1311  */
1312 static HAL_BOOL
1313 ar5211SetTransmitPower(struct ath_hal *ah, const struct ieee80211_channel *chan)
1314 {
1315 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1316 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1317 	TRGT_POWER_INFO *pi;
1318 	RD_EDGES_POWER *rep;
1319 	PCDACS_EEPROM eepromPcdacs;
1320 	u_int nchan, cfgCtl;
1321 	int i;
1322 
1323 	/* setup the pcdac struct to point to the correct info, based on mode */
1324 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1325 	case IEEE80211_CHAN_A:
1326 		eepromPcdacs.numChannels = ee->ee_numChannels11a;
1327 		eepromPcdacs.pChannelList= ee->ee_channels11a;
1328 		eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11a;
1329 		nchan = ee->ee_numTargetPwr_11a;
1330 		pi = ee->ee_trgtPwr_11a;
1331 		break;
1332 	case IEEE80211_CHAN_PUREG:
1333 		eepromPcdacs.numChannels = ee->ee_numChannels2_4;
1334 		eepromPcdacs.pChannelList= ee->ee_channels11g;
1335 		eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11g;
1336 		nchan = ee->ee_numTargetPwr_11g;
1337 		pi = ee->ee_trgtPwr_11g;
1338 		break;
1339 	case IEEE80211_CHAN_B:
1340 		eepromPcdacs.numChannels = ee->ee_numChannels2_4;
1341 		eepromPcdacs.pChannelList= ee->ee_channels11b;
1342 		eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11b;
1343 		nchan = ee->ee_numTargetPwr_11b;
1344 		pi = ee->ee_trgtPwr_11b;
1345 		break;
1346 	default:
1347 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1348 		    __func__, chan->ic_flags);
1349 		return AH_FALSE;
1350 	}
1351 
1352 	ar5211SetPowerTable(ah, &eepromPcdacs, freq);
1353 
1354 	rep = AH_NULL;
1355 	/* Match CTL to EEPROM value */
1356 	cfgCtl = ath_hal_getctl(ah, chan);
1357 	for (i = 0; i < ee->ee_numCtls; i++)
1358 		if (ee->ee_ctl[i] != 0 && ee->ee_ctl[i] == cfgCtl) {
1359 			rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
1360 			break;
1361 		}
1362 	ar5211SetRateTable(ah, rep, pi, nchan, chan);
1363 
1364 	return AH_TRUE;
1365 }
1366 
1367 /*
1368  * Read the transmit power levels from the structures taken
1369  * from EEPROM. Interpolate read transmit power values for
1370  * this channel. Organize the transmit power values into a
1371  * table for writing into the hardware.
1372  */
1373 void
1374 ar5211SetPowerTable(struct ath_hal *ah, PCDACS_EEPROM *pSrcStruct,
1375 	uint16_t channel)
1376 {
1377 	static FULL_PCDAC_STRUCT pcdacStruct;
1378 	static uint16_t pcdacTable[PWR_TABLE_SIZE];
1379 
1380 	uint16_t	 i, j;
1381 	uint16_t	 *pPcdacValues;
1382 	int16_t	  *pScaledUpDbm;
1383 	int16_t	  minScaledPwr;
1384 	int16_t	  maxScaledPwr;
1385 	int16_t	  pwr;
1386 	uint16_t	 pcdacMin = 0;
1387 	uint16_t	 pcdacMax = 63;
1388 	uint16_t	 pcdacTableIndex;
1389 	uint16_t	 scaledPcdac;
1390 	uint32_t	 addr;
1391 	uint32_t	 temp32;
1392 
1393 	OS_MEMZERO(&pcdacStruct, sizeof(FULL_PCDAC_STRUCT));
1394 	OS_MEMZERO(pcdacTable, sizeof(uint16_t) * PWR_TABLE_SIZE);
1395 	pPcdacValues = pcdacStruct.PcdacValues;
1396 	pScaledUpDbm = pcdacStruct.PwrValues;
1397 
1398 	/* Initialize the pcdacs to dBM structs pcdacs to be 1 to 63 */
1399 	for (i = PCDAC_START, j = 0; i <= PCDAC_STOP; i+= PCDAC_STEP, j++)
1400 		pPcdacValues[j] = i;
1401 
1402 	pcdacStruct.numPcdacValues = j;
1403 	pcdacStruct.pcdacMin = PCDAC_START;
1404 	pcdacStruct.pcdacMax = PCDAC_STOP;
1405 
1406 	/* Fill out the power values for this channel */
1407 	for (j = 0; j < pcdacStruct.numPcdacValues; j++ )
1408 		pScaledUpDbm[j] = ar5211GetScaledPower(channel, pPcdacValues[j], pSrcStruct);
1409 
1410 	/* Now scale the pcdac values to fit in the 64 entry power table */
1411 	minScaledPwr = pScaledUpDbm[0];
1412 	maxScaledPwr = pScaledUpDbm[pcdacStruct.numPcdacValues - 1];
1413 
1414 	/* find minimum and make monotonic */
1415 	for (j = 0; j < pcdacStruct.numPcdacValues; j++) {
1416 		if (minScaledPwr >= pScaledUpDbm[j]) {
1417 			minScaledPwr = pScaledUpDbm[j];
1418 			pcdacMin = j;
1419 		}
1420 		/*
1421 		 * Make the full_hsh monotonically increasing otherwise
1422 		 * interpolation algorithm will get fooled gotta start
1423 		 * working from the top, hence i = 63 - j.
1424 		 */
1425 		i = (uint16_t)(pcdacStruct.numPcdacValues - 1 - j);
1426 		if (i == 0)
1427 			break;
1428 		if (pScaledUpDbm[i-1] > pScaledUpDbm[i]) {
1429 			/*
1430 			 * It could be a glitch, so make the power for
1431 			 * this pcdac the same as the power from the
1432 			 * next highest pcdac.
1433 			 */
1434 			pScaledUpDbm[i - 1] = pScaledUpDbm[i];
1435 		}
1436 	}
1437 
1438 	for (j = 0; j < pcdacStruct.numPcdacValues; j++)
1439 		if (maxScaledPwr < pScaledUpDbm[j]) {
1440 			maxScaledPwr = pScaledUpDbm[j];
1441 			pcdacMax = j;
1442 		}
1443 
1444 	/* Find the first power level with a pcdac */
1445 	pwr = (uint16_t)(rounddown(minScaledPwr - PWR_MIN + PWR_STEP / 2, PWR_STEP)  + PWR_MIN);
1446 
1447 	/* Write all the first pcdac entries based off the pcdacMin */
1448 	pcdacTableIndex = 0;
1449 	for (i = 0; i < (2 * (pwr - PWR_MIN) / EEP_SCALE + 1); i++)
1450 		pcdacTable[pcdacTableIndex++] = pcdacMin;
1451 
1452 	i = 0;
1453 	while (pwr < pScaledUpDbm[pcdacStruct.numPcdacValues - 1]) {
1454 		pwr += PWR_STEP;
1455 		/* stop if dbM > max_power_possible */
1456 		while (pwr < pScaledUpDbm[pcdacStruct.numPcdacValues - 1] &&
1457 		       (pwr - pScaledUpDbm[i])*(pwr - pScaledUpDbm[i+1]) > 0)
1458 			i++;
1459 		/* scale by 2 and add 1 to enable round up or down as needed */
1460 		scaledPcdac = (uint16_t)(ar5211GetInterpolatedValue(pwr,
1461 				pScaledUpDbm[i], pScaledUpDbm[i+1],
1462 				(uint16_t)(pPcdacValues[i] * 2),
1463 				(uint16_t)(pPcdacValues[i+1] * 2), 0) + 1);
1464 
1465 		pcdacTable[pcdacTableIndex] = scaledPcdac / 2;
1466 		if (pcdacTable[pcdacTableIndex] > pcdacMax)
1467 			pcdacTable[pcdacTableIndex] = pcdacMax;
1468 		pcdacTableIndex++;
1469 	}
1470 
1471 	/* Write all the last pcdac entries based off the last valid pcdac */
1472 	while (pcdacTableIndex < PWR_TABLE_SIZE) {
1473 		pcdacTable[pcdacTableIndex] = pcdacTable[pcdacTableIndex - 1];
1474 		pcdacTableIndex++;
1475 	}
1476 
1477 	/* Finally, write the power values into the baseband power table */
1478 	addr = AR_PHY_BASE + (608 << 2);
1479 	for (i = 0; i < 32; i++) {
1480 		temp32 = 0xffff & ((pcdacTable[2 * i + 1] << 8) | 0xff);
1481 		temp32 = (temp32 << 16) | (0xffff & ((pcdacTable[2 * i] << 8) | 0xff));
1482 		OS_REG_WRITE(ah, addr, temp32);
1483 		addr += 4;
1484 	}
1485 
1486 }
1487 
1488 /*
1489  * Set the transmit power in the baseband for the given
1490  * operating channel and mode.
1491  */
1492 static void
1493 ar5211SetRateTable(struct ath_hal *ah, RD_EDGES_POWER *pRdEdgesPower,
1494 	TRGT_POWER_INFO *pPowerInfo, uint16_t numChannels,
1495 	const struct ieee80211_channel *chan)
1496 {
1497 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1498 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1499 	struct ath_hal_5211 *ahp = AH5211(ah);
1500 	static uint16_t ratesArray[NUM_RATES];
1501 	static const uint16_t tpcScaleReductionTable[5] =
1502 		{ 0, 3, 6, 9, MAX_RATE_POWER };
1503 
1504 	uint16_t	*pRatesPower;
1505 	uint16_t	lowerChannel, lowerIndex=0, lowerPower=0;
1506 	uint16_t	upperChannel, upperIndex=0, upperPower=0;
1507 	uint16_t	twiceMaxEdgePower=63;
1508 	uint16_t	twicePower = 0;
1509 	uint16_t	i, numEdges;
1510 	uint16_t	tempChannelList[NUM_EDGES]; /* temp array for holding edge channels */
1511 	uint16_t	twiceMaxRDPower;
1512 	int16_t	 scaledPower = 0;		/* for gcc -O2 */
1513 	uint16_t	mask = 0x3f;
1514 	HAL_BOOL	  paPreDEnable = 0;
1515 	int8_t	  twiceAntennaGain, twiceAntennaReduction = 0;
1516 
1517 	pRatesPower = ratesArray;
1518 	twiceMaxRDPower = chan->ic_maxregpower * 2;
1519 
1520 	if (IEEE80211_IS_CHAN_5GHZ(chan)) {
1521 		twiceAntennaGain = ee->ee_antennaGainMax[0];
1522 	} else {
1523 		twiceAntennaGain = ee->ee_antennaGainMax[1];
1524 	}
1525 
1526 	twiceAntennaReduction = ath_hal_getantennareduction(ah, chan, twiceAntennaGain);
1527 
1528 	if (pRdEdgesPower) {
1529 		/* Get the edge power */
1530 		for (i = 0; i < NUM_EDGES; i++) {
1531 			if (pRdEdgesPower[i].rdEdge == 0)
1532 				break;
1533 			tempChannelList[i] = pRdEdgesPower[i].rdEdge;
1534 		}
1535 		numEdges = i;
1536 
1537 		ar5211GetLowerUpperValues(freq, tempChannelList,
1538 			numEdges, &lowerChannel, &upperChannel);
1539 		/* Get the index for this channel */
1540 		for (i = 0; i < numEdges; i++)
1541 			if (lowerChannel == tempChannelList[i])
1542 				break;
1543 		HALASSERT(i != numEdges);
1544 
1545 		if ((lowerChannel == upperChannel &&
1546 		     lowerChannel == freq) ||
1547 		    pRdEdgesPower[i].flag) {
1548 			twiceMaxEdgePower = pRdEdgesPower[i].twice_rdEdgePower;
1549 			HALASSERT(twiceMaxEdgePower > 0);
1550 		}
1551 	}
1552 
1553 	/* extrapolate the power values for the test Groups */
1554 	for (i = 0; i < numChannels; i++)
1555 		tempChannelList[i] = pPowerInfo[i].testChannel;
1556 
1557 	ar5211GetLowerUpperValues(freq, tempChannelList,
1558 		numChannels, &lowerChannel, &upperChannel);
1559 
1560 	/* get the index for the channel */
1561 	for (i = 0; i < numChannels; i++) {
1562 		if (lowerChannel == tempChannelList[i])
1563 			lowerIndex = i;
1564 		if (upperChannel == tempChannelList[i]) {
1565 			upperIndex = i;
1566 			break;
1567 		}
1568 	}
1569 
1570 	for (i = 0; i < NUM_RATES; i++) {
1571 		if (IEEE80211_IS_CHAN_OFDM(chan)) {
1572 			/* power for rates 6,9,12,18,24 is all the same */
1573 			if (i < 5) {
1574 				lowerPower = pPowerInfo[lowerIndex].twicePwr6_24;
1575 				upperPower = pPowerInfo[upperIndex].twicePwr6_24;
1576 			} else if (i == 5) {
1577 				lowerPower = pPowerInfo[lowerIndex].twicePwr36;
1578 				upperPower = pPowerInfo[upperIndex].twicePwr36;
1579 			} else if (i == 6) {
1580 				lowerPower = pPowerInfo[lowerIndex].twicePwr48;
1581 				upperPower = pPowerInfo[upperIndex].twicePwr48;
1582 			} else if (i == 7) {
1583 				lowerPower = pPowerInfo[lowerIndex].twicePwr54;
1584 				upperPower = pPowerInfo[upperIndex].twicePwr54;
1585 			}
1586 		} else {
1587 			switch (i) {
1588 			case 0:
1589 			case 1:
1590 				lowerPower = pPowerInfo[lowerIndex].twicePwr6_24;
1591 				upperPower = pPowerInfo[upperIndex].twicePwr6_24;
1592 				break;
1593 			case 2:
1594 			case 3:
1595 				lowerPower = pPowerInfo[lowerIndex].twicePwr36;
1596 				upperPower = pPowerInfo[upperIndex].twicePwr36;
1597 				break;
1598 			case 4:
1599 			case 5:
1600 				lowerPower = pPowerInfo[lowerIndex].twicePwr48;
1601 				upperPower = pPowerInfo[upperIndex].twicePwr48;
1602 				break;
1603 			case 6:
1604 			case 7:
1605 				lowerPower = pPowerInfo[lowerIndex].twicePwr54;
1606 				upperPower = pPowerInfo[upperIndex].twicePwr54;
1607 				break;
1608 			}
1609 		}
1610 
1611 		twicePower = ar5211GetInterpolatedValue(freq,
1612 			lowerChannel, upperChannel, lowerPower, upperPower, 0);
1613 
1614 		/* Reduce power by band edge restrictions */
1615 		twicePower = AH_MIN(twicePower, twiceMaxEdgePower);
1616 
1617 		/*
1618 		 * If turbo is set, reduce power to keep power
1619 		 * consumption under 2 Watts.  Note that we always do
1620 		 * this unless specially configured.  Then we limit
1621 		 * power only for non-AP operation.
1622 		 */
1623 		if (IEEE80211_IS_CHAN_TURBO(chan) &&
1624 		    AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1
1625 #ifdef AH_ENABLE_AP_SUPPORT
1626 		    && AH_PRIVATE(ah)->ah_opmode != HAL_M_HOSTAP
1627 #endif
1628 		) {
1629 			twicePower = AH_MIN(twicePower, ee->ee_turbo2WMaxPower5);
1630 		}
1631 
1632 		/* Reduce power by max regulatory domain allowed restrictions */
1633 		pRatesPower[i] = AH_MIN(twicePower, twiceMaxRDPower - twiceAntennaReduction);
1634 
1635 		/* Use 6 Mb power level for transmit power scaling reduction */
1636 		/* We don't want to reduce higher rates if its not needed */
1637 		if (i == 0) {
1638 			scaledPower = pRatesPower[0] -
1639 				(tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale] * 2);
1640 			if (scaledPower < 1)
1641 				scaledPower = 1;
1642 		}
1643 
1644 		pRatesPower[i] = AH_MIN(pRatesPower[i], scaledPower);
1645 	}
1646 
1647 	/* Record txPower at Rate 6 for info gathering */
1648 	ahp->ah_tx6PowerInHalfDbm = pRatesPower[0];
1649 
1650 #ifdef AH_DEBUG
1651 	HALDEBUG(ah, HAL_DEBUG_RESET,
1652 	    "%s: final output power setting %d MHz:\n",
1653 	    __func__, chan->ic_freq);
1654 	HALDEBUG(ah, HAL_DEBUG_RESET,
1655 	    "6 Mb %d dBm, MaxRD: %d dBm, MaxEdge %d dBm\n",
1656 	    scaledPower / 2, twiceMaxRDPower / 2, twiceMaxEdgePower / 2);
1657 	HALDEBUG(ah, HAL_DEBUG_RESET, "TPC Scale %d dBm - Ant Red %d dBm\n",
1658 	    tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale] * 2,
1659 	    twiceAntennaReduction / 2);
1660 	if (IEEE80211_IS_CHAN_TURBO(chan) &&
1661 	    AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1)
1662 		HALDEBUG(ah, HAL_DEBUG_RESET, "Max Turbo %d dBm\n",
1663 		    ee->ee_turbo2WMaxPower5);
1664 	HALDEBUG(ah, HAL_DEBUG_RESET,
1665 	    "  %2d | %2d | %2d | %2d | %2d | %2d | %2d | %2d dBm\n",
1666 	    pRatesPower[0] / 2, pRatesPower[1] / 2, pRatesPower[2] / 2,
1667 	    pRatesPower[3] / 2, pRatesPower[4] / 2, pRatesPower[5] / 2,
1668 	    pRatesPower[6] / 2, pRatesPower[7] / 2);
1669 #endif /* AH_DEBUG */
1670 
1671 	/* Write the power table into the hardware */
1672 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
1673 		 ((paPreDEnable & 1)<< 30) | ((pRatesPower[3] & mask) << 24) |
1674 		 ((paPreDEnable & 1)<< 22) | ((pRatesPower[2] & mask) << 16) |
1675 		 ((paPreDEnable & 1)<< 14) | ((pRatesPower[1] & mask) << 8) |
1676 		 ((paPreDEnable & 1)<< 6 ) |  (pRatesPower[0] & mask));
1677 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
1678 		 ((paPreDEnable & 1)<< 30) | ((pRatesPower[7] & mask) << 24) |
1679 		 ((paPreDEnable & 1)<< 22) | ((pRatesPower[6] & mask) << 16) |
1680 		 ((paPreDEnable & 1)<< 14) | ((pRatesPower[5] & mask) << 8) |
1681 		 ((paPreDEnable & 1)<< 6 ) |  (pRatesPower[4] & mask));
1682 
1683 	/* set max power to the power value at rate 6 */
1684 	ar5211SetTxPowerLimit(ah, pRatesPower[0]);
1685 
1686 	AH_PRIVATE(ah)->ah_maxPowerLevel = pRatesPower[0];
1687 }
1688 
1689 /*
1690  * Get or interpolate the pcdac value from the calibrated data
1691  */
1692 uint16_t
1693 ar5211GetScaledPower(uint16_t channel, uint16_t pcdacValue,
1694 	const PCDACS_EEPROM *pSrcStruct)
1695 {
1696 	uint16_t powerValue;
1697 	uint16_t lFreq, rFreq;		/* left and right frequency values */
1698 	uint16_t llPcdac, ulPcdac;	/* lower and upper left pcdac values */
1699 	uint16_t lrPcdac, urPcdac;	/* lower and upper right pcdac values */
1700 	uint16_t lPwr, uPwr;		/* lower and upper temp pwr values */
1701 	uint16_t lScaledPwr, rScaledPwr; /* left and right scaled power */
1702 
1703 	if (ar5211FindValueInList(channel, pcdacValue, pSrcStruct, &powerValue))
1704 		/* value was copied from srcStruct */
1705 		return powerValue;
1706 
1707 	ar5211GetLowerUpperValues(channel, pSrcStruct->pChannelList,
1708 		pSrcStruct->numChannels, &lFreq, &rFreq);
1709 	ar5211GetLowerUpperPcdacs(pcdacValue, lFreq, pSrcStruct,
1710 		&llPcdac, &ulPcdac);
1711 	ar5211GetLowerUpperPcdacs(pcdacValue, rFreq, pSrcStruct,
1712 		&lrPcdac, &urPcdac);
1713 
1714 	/* get the power index for the pcdac value */
1715 	lPwr = 0;	/* avoid gcc warnings */
1716 	uPwr = 0;	/* avoid gcc warnings */
1717 	ar5211FindValueInList(lFreq, llPcdac, pSrcStruct, &lPwr);
1718 	ar5211FindValueInList(lFreq, ulPcdac, pSrcStruct, &uPwr);
1719 	lScaledPwr = ar5211GetInterpolatedValue(pcdacValue,
1720 				llPcdac, ulPcdac, lPwr, uPwr, 0);
1721 
1722 	ar5211FindValueInList(rFreq, lrPcdac, pSrcStruct, &lPwr);
1723 	ar5211FindValueInList(rFreq, urPcdac, pSrcStruct, &uPwr);
1724 	rScaledPwr = ar5211GetInterpolatedValue(pcdacValue,
1725 				lrPcdac, urPcdac, lPwr, uPwr, 0);
1726 
1727 	return ar5211GetInterpolatedValue(channel, lFreq, rFreq,
1728 		lScaledPwr, rScaledPwr, 0);
1729 }
1730 
1731 /*
1732  * Find the value from the calibrated source data struct
1733  */
1734 HAL_BOOL
1735 ar5211FindValueInList(uint16_t channel, uint16_t pcdacValue,
1736 	const PCDACS_EEPROM *pSrcStruct, uint16_t *powerValue)
1737 {
1738 	const DATA_PER_CHANNEL *pChannelData;
1739 	const uint16_t *pPcdac;
1740 	uint16_t i, j;
1741 
1742 	pChannelData = pSrcStruct->pDataPerChannel;
1743 	for (i = 0; i < pSrcStruct->numChannels; i++ ) {
1744 		if (pChannelData->channelValue == channel) {
1745 			pPcdac = pChannelData->PcdacValues;
1746 			for (j = 0; j < pChannelData->numPcdacValues; j++ ) {
1747 				if (*pPcdac == pcdacValue) {
1748 					*powerValue = pChannelData->PwrValues[j];
1749 					return AH_TRUE;
1750 				}
1751 				pPcdac++;
1752 			}
1753 		}
1754 		pChannelData++;
1755 	}
1756 	return AH_FALSE;
1757 }
1758 
1759 /*
1760  * Returns interpolated or the scaled up interpolated value
1761  */
1762 uint16_t
1763 ar5211GetInterpolatedValue(uint16_t target,
1764 	uint16_t srcLeft, uint16_t srcRight,
1765 	uint16_t targetLeft, uint16_t targetRight,
1766 	HAL_BOOL scaleUp)
1767 {
1768 	uint16_t rv;
1769 	int16_t lRatio;
1770 	uint16_t scaleValue = EEP_SCALE;
1771 
1772 	/* to get an accurate ratio, always scale, if want to scale, then don't scale back down */
1773 	if ((targetLeft * targetRight) == 0)
1774 		return 0;
1775 	if (scaleUp)
1776 		scaleValue = 1;
1777 
1778 	if (srcRight != srcLeft) {
1779 		/*
1780 		 * Note the ratio always need to be scaled,
1781 		 * since it will be a fraction.
1782 		 */
1783 		lRatio = (target - srcLeft) * EEP_SCALE / (srcRight - srcLeft);
1784 		if (lRatio < 0) {
1785 		    /* Return as Left target if value would be negative */
1786 		    rv = targetLeft * (scaleUp ? EEP_SCALE : 1);
1787 		} else if (lRatio > EEP_SCALE) {
1788 		    /* Return as Right target if Ratio is greater than 100% (SCALE) */
1789 		    rv = targetRight * (scaleUp ? EEP_SCALE : 1);
1790 		} else {
1791 			rv = (lRatio * targetRight + (EEP_SCALE - lRatio) *
1792 					targetLeft) / scaleValue;
1793 		}
1794 	} else {
1795 		rv = targetLeft;
1796 		if (scaleUp)
1797 			rv *= EEP_SCALE;
1798 	}
1799 	return rv;
1800 }
1801 
1802 /*
1803  *  Look for value being within 0.1 of the search values
1804  *  however, NDIS can't do float calculations, so multiply everything
1805  *  up by EEP_SCALE so can do integer arithmatic
1806  *
1807  * INPUT  value	   -value to search for
1808  * INPUT  pList	   -ptr to the list to search
1809  * INPUT  listSize	-number of entries in list
1810  * OUTPUT pLowerValue -return the lower value
1811  * OUTPUT pUpperValue -return the upper value
1812  */
1813 void
1814 ar5211GetLowerUpperValues(uint16_t value,
1815 	const uint16_t *pList, uint16_t listSize,
1816 	uint16_t *pLowerValue, uint16_t *pUpperValue)
1817 {
1818 	const uint16_t listEndValue = *(pList + listSize - 1);
1819 	uint32_t target = value * EEP_SCALE;
1820 	int i;
1821 
1822 	*pLowerValue = 0;	/* avoid gcc warnings */
1823 	*pUpperValue = 0;	/* avoid gcc warnings */
1824 
1825 	/*
1826 	 * See if value is lower than the first value in the list
1827 	 * if so return first value
1828 	 */
1829 	if (target < (uint32_t)(*pList * EEP_SCALE - EEP_DELTA)) {
1830 		*pLowerValue = *pList;
1831 		*pUpperValue = *pList;
1832 		return;
1833 	}
1834 
1835 	/*
1836 	 * See if value is greater than last value in list
1837 	 * if so return last value
1838 	 */
1839 	if (target > (uint32_t)(listEndValue * EEP_SCALE + EEP_DELTA)) {
1840 		*pLowerValue = listEndValue;
1841 		*pUpperValue = listEndValue;
1842 		return;
1843 	}
1844 
1845 	/* look for value being near or between 2 values in list */
1846 	for (i = 0; i < listSize; i++) {
1847 		/*
1848 		 * If value is close to the current value of the list
1849 		 * then target is not between values, it is one of the values
1850 		 */
1851 		if (abs(pList[i] * EEP_SCALE - (int32_t) target) < EEP_DELTA) {
1852 			*pLowerValue = pList[i];
1853 			*pUpperValue = pList[i];
1854 			return;
1855 		}
1856 
1857 		/*
1858 		 * Look for value being between current value and next value
1859 		 * if so return these 2 values
1860 		 */
1861 		if (target < (uint32_t)(pList[i + 1] * EEP_SCALE - EEP_DELTA)) {
1862 			*pLowerValue = pList[i];
1863 			*pUpperValue = pList[i + 1];
1864 			return;
1865 		}
1866 	}
1867 }
1868 
1869 /*
1870  * Get the upper and lower pcdac given the channel and the pcdac
1871  * used in the search
1872  */
1873 void
1874 ar5211GetLowerUpperPcdacs(uint16_t pcdac, uint16_t channel,
1875 	const PCDACS_EEPROM *pSrcStruct,
1876 	uint16_t *pLowerPcdac, uint16_t *pUpperPcdac)
1877 {
1878 	const DATA_PER_CHANNEL *pChannelData;
1879 	int i;
1880 
1881 	/* Find the channel information */
1882 	pChannelData = pSrcStruct->pDataPerChannel;
1883 	for (i = 0; i < pSrcStruct->numChannels; i++) {
1884 		if (pChannelData->channelValue == channel)
1885 			break;
1886 		pChannelData++;
1887 	}
1888 	ar5211GetLowerUpperValues(pcdac, pChannelData->PcdacValues,
1889 		pChannelData->numPcdacValues, pLowerPcdac, pUpperPcdac);
1890 }
1891 
1892 #define	DYN_ADJ_UP_MARGIN	15
1893 #define	DYN_ADJ_LO_MARGIN	20
1894 
1895 static const GAIN_OPTIMIZATION_LADDER gainLadder = {
1896 	9,					/* numStepsInLadder */
1897 	4,					/* defaultStepNum */
1898 	{ { {4, 1, 1, 1},  6, "FG8"},
1899 	  { {4, 0, 1, 1},  4, "FG7"},
1900 	  { {3, 1, 1, 1},  3, "FG6"},
1901 	  { {4, 0, 0, 1},  1, "FG5"},
1902 	  { {4, 1, 1, 0},  0, "FG4"},	/* noJack */
1903 	  { {4, 0, 1, 0}, -2, "FG3"},	/* halfJack */
1904 	  { {3, 1, 1, 0}, -3, "FG2"},	/* clip3 */
1905 	  { {4, 0, 0, 0}, -4, "FG1"},	/* noJack */
1906 	  { {2, 1, 1, 0}, -6, "FG0"} 	/* clip2 */
1907 	}
1908 };
1909 
1910 /*
1911  * Initialize the gain structure to good values
1912  */
1913 void
1914 ar5211InitializeGainValues(struct ath_hal *ah)
1915 {
1916 	struct ath_hal_5211 *ahp = AH5211(ah);
1917 	GAIN_VALUES *gv = &ahp->ah_gainValues;
1918 
1919 	/* initialize gain optimization values */
1920 	gv->currStepNum = gainLadder.defaultStepNum;
1921 	gv->currStep = &gainLadder.optStep[gainLadder.defaultStepNum];
1922 	gv->active = AH_TRUE;
1923 	gv->loTrig = 20;
1924 	gv->hiTrig = 35;
1925 }
1926 
1927 static HAL_BOOL
1928 ar5211InvalidGainReadback(struct ath_hal *ah, GAIN_VALUES *gv)
1929 {
1930 	const struct ieee80211_channel *chan = AH_PRIVATE(ah)->ah_curchan;
1931 	uint32_t gStep, g;
1932 	uint32_t L1, L2, L3, L4;
1933 
1934 	if (IEEE80211_IS_CHAN_CCK(chan)) {
1935 		gStep = 0x18;
1936 		L1 = 0;
1937 		L2 = gStep + 4;
1938 		L3 = 0x40;
1939 		L4 = L3 + 50;
1940 
1941 		gv->loTrig = L1;
1942 		gv->hiTrig = L4+5;
1943 	} else {
1944 		gStep = 0x3f;
1945 		L1 = 0;
1946 		L2 = 50;
1947 		L3 = L1;
1948 		L4 = L3 + 50;
1949 
1950 		gv->loTrig = L1 + DYN_ADJ_LO_MARGIN;
1951 		gv->hiTrig = L4 - DYN_ADJ_UP_MARGIN;
1952 	}
1953 	g = gv->currGain;
1954 
1955 	return !((g >= L1 && g<= L2) || (g >= L3 && g <= L4));
1956 }
1957 
1958 /*
1959  * Enable the probe gain check on the next packet
1960  */
1961 static void
1962 ar5211RequestRfgain(struct ath_hal *ah)
1963 {
1964 	struct ath_hal_5211 *ahp = AH5211(ah);
1965 
1966 	/* Enable the gain readback probe */
1967 	OS_REG_WRITE(ah, AR_PHY_PAPD_PROBE,
1968 		  SM(ahp->ah_tx6PowerInHalfDbm, AR_PHY_PAPD_PROBE_POWERTX)
1969 		| AR_PHY_PAPD_PROBE_NEXT_TX);
1970 
1971 	ahp->ah_rfgainState = HAL_RFGAIN_READ_REQUESTED;
1972 }
1973 
1974 /*
1975  * Exported call to check for a recent gain reading and return
1976  * the current state of the thermal calibration gain engine.
1977  */
1978 HAL_RFGAIN
1979 ar5211GetRfgain(struct ath_hal *ah)
1980 {
1981 	struct ath_hal_5211 *ahp = AH5211(ah);
1982 	GAIN_VALUES *gv = &ahp->ah_gainValues;
1983 	uint32_t rddata;
1984 
1985 	if (!gv->active)
1986 		return HAL_RFGAIN_INACTIVE;
1987 
1988 	if (ahp->ah_rfgainState == HAL_RFGAIN_READ_REQUESTED) {
1989 		/* Caller had asked to setup a new reading. Check it. */
1990 		rddata = OS_REG_READ(ah, AR_PHY_PAPD_PROBE);
1991 
1992 		if ((rddata & AR_PHY_PAPD_PROBE_NEXT_TX) == 0) {
1993 			/* bit got cleared, we have a new reading. */
1994 			gv->currGain = rddata >> AR_PHY_PAPD_PROBE_GAINF_S;
1995 			/* inactive by default */
1996 			ahp->ah_rfgainState = HAL_RFGAIN_INACTIVE;
1997 
1998 			if (!ar5211InvalidGainReadback(ah, gv) &&
1999 			    ar5211IsGainAdjustNeeded(ah, gv) &&
2000 			    ar5211AdjustGain(ah, gv) > 0) {
2001 				/*
2002 				 * Change needed. Copy ladder info
2003 				 * into eeprom info.
2004 				 */
2005 				ar5211SetRfgain(ah, gv);
2006 				ahp->ah_rfgainState = HAL_RFGAIN_NEED_CHANGE;
2007 			}
2008 		}
2009 	}
2010 	return ahp->ah_rfgainState;
2011 }
2012 
2013 /*
2014  * Check to see if our readback gain level sits within the linear
2015  * region of our current variable attenuation window
2016  */
2017 static HAL_BOOL
2018 ar5211IsGainAdjustNeeded(struct ath_hal *ah, const GAIN_VALUES *gv)
2019 {
2020 	return (gv->currGain <= gv->loTrig || gv->currGain >= gv->hiTrig);
2021 }
2022 
2023 /*
2024  * Move the rabbit ears in the correct direction.
2025  */
2026 static int32_t
2027 ar5211AdjustGain(struct ath_hal *ah, GAIN_VALUES *gv)
2028 {
2029 	/* return > 0 for valid adjustments. */
2030 	if (!gv->active)
2031 		return -1;
2032 
2033 	gv->currStep = &gainLadder.optStep[gv->currStepNum];
2034 	if (gv->currGain >= gv->hiTrig) {
2035 		if (gv->currStepNum == 0) {
2036 			HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2037 			    "%s: Max gain limit.\n", __func__);
2038 			return -1;
2039 		}
2040 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2041 		    "%s: Adding gain: currG=%d [%s] --> ",
2042 		    __func__, gv->currGain, gv->currStep->stepName);
2043 		gv->targetGain = gv->currGain;
2044 		while (gv->targetGain >= gv->hiTrig && gv->currStepNum > 0) {
2045 			gv->targetGain -= 2 * (gainLadder.optStep[--(gv->currStepNum)].stepGain -
2046 				gv->currStep->stepGain);
2047 			gv->currStep = &gainLadder.optStep[gv->currStepNum];
2048 		}
2049 		HALDEBUG(ah, HAL_DEBUG_RFPARAM, "targG=%d [%s]\n",
2050 		    gv->targetGain, gv->currStep->stepName);
2051 		return 1;
2052 	}
2053 	if (gv->currGain <= gv->loTrig) {
2054 		if (gv->currStepNum == gainLadder.numStepsInLadder-1) {
2055 			HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2056 			    "%s: Min gain limit.\n", __func__);
2057 			return -2;
2058 		}
2059 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2060 		    "%s: Deducting gain: currG=%d [%s] --> ",
2061 		    __func__, gv->currGain, gv->currStep->stepName);
2062 		gv->targetGain = gv->currGain;
2063 		while (gv->targetGain <= gv->loTrig &&
2064 		      gv->currStepNum < (gainLadder.numStepsInLadder - 1)) {
2065 			gv->targetGain -= 2 *
2066 				(gainLadder.optStep[++(gv->currStepNum)].stepGain - gv->currStep->stepGain);
2067 			gv->currStep = &gainLadder.optStep[gv->currStepNum];
2068 		}
2069 		HALDEBUG(ah, HAL_DEBUG_RFPARAM, "targG=%d [%s]\n",
2070 		    gv->targetGain, gv->currStep->stepName);
2071 		return 2;
2072 	}
2073 	return 0;		/* caller didn't call needAdjGain first */
2074 }
2075 
2076 /*
2077  * Adjust the 5GHz EEPROM information with the desired calibration values.
2078  */
2079 static void
2080 ar5211SetRfgain(struct ath_hal *ah, const GAIN_VALUES *gv)
2081 {
2082 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
2083 
2084 	if (!gv->active)
2085 		return;
2086 	ee->ee_cornerCal.clip = gv->currStep->paramVal[0]; /* bb_tx_clip */
2087 	ee->ee_cornerCal.pd90 = gv->currStep->paramVal[1]; /* rf_pwd_90 */
2088 	ee->ee_cornerCal.pd84 = gv->currStep->paramVal[2]; /* rf_pwd_84 */
2089 	ee->ee_cornerCal.gSel = gv->currStep->paramVal[3]; /* rf_rfgainsel */
2090 }
2091 
2092 static void
2093 ar5211SetOperatingMode(struct ath_hal *ah, int opmode)
2094 {
2095 	struct ath_hal_5211 *ahp = AH5211(ah);
2096 	uint32_t val;
2097 
2098 	val = OS_REG_READ(ah, AR_STA_ID1) & 0xffff;
2099 	switch (opmode) {
2100 	case HAL_M_HOSTAP:
2101 		OS_REG_WRITE(ah, AR_STA_ID1, val
2102 			| AR_STA_ID1_STA_AP
2103 			| AR_STA_ID1_RTS_USE_DEF
2104 			| ahp->ah_staId1Defaults);
2105 		break;
2106 	case HAL_M_IBSS:
2107 		OS_REG_WRITE(ah, AR_STA_ID1, val
2108 			| AR_STA_ID1_ADHOC
2109 			| AR_STA_ID1_DESC_ANTENNA
2110 			| ahp->ah_staId1Defaults);
2111 		break;
2112 	case HAL_M_STA:
2113 	case HAL_M_MONITOR:
2114 		OS_REG_WRITE(ah, AR_STA_ID1, val
2115 			| AR_STA_ID1_DEFAULT_ANTENNA
2116 			| ahp->ah_staId1Defaults);
2117 		break;
2118 	}
2119 }
2120 
2121 void
2122 ar5211SetPCUConfig(struct ath_hal *ah)
2123 {
2124 	ar5211SetOperatingMode(ah, AH_PRIVATE(ah)->ah_opmode);
2125 }
2126