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