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 const static 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_STATUS *status)
158 {
159 uint32_t softLedCfg, softLedState;
160 #define	N(a)	(sizeof (a) /sizeof (a[0]))
161 #define	FAIL(_code)	do { ecode = _code; goto bad; } while (0)
162 	struct ath_hal_5211 *ahp = AH5211(ah);
163 	HAL_CHANNEL_INTERNAL *ichan;
164 	uint32_t i, ledstate;
165 	HAL_STATUS ecode;
166 	int q;
167 
168 	uint32_t		data, synthDelay;
169 	uint32_t		macStaId1;
170 	uint16_t		modesIndex = 0, freqIndex = 0;
171 	uint32_t		saveFrameSeqCount[AR_NUM_DCU];
172 	uint32_t		saveTsfLow = 0, saveTsfHigh = 0;
173 	uint32_t		saveDefAntenna;
174 
175 	HALDEBUG(ah, HAL_DEBUG_RESET,
176 	     "%s: opmode %u channel %u/0x%x %s channel\n",
177 	     __func__, opmode, chan->ic_freq, chan->ic_flags,
178 	     bChannelChange ? "change" : "same");
179 
180 	OS_MARK(ah, AH_MARK_RESET, bChannelChange);
181 	/*
182 	 * Map public channel to private.
183 	 */
184 	ichan = ath_hal_checkchannel(ah, chan);
185 	if (ichan == AH_NULL)
186 		FAIL(HAL_EINVAL);
187 	switch (opmode) {
188 	case HAL_M_STA:
189 	case HAL_M_IBSS:
190 	case HAL_M_HOSTAP:
191 	case HAL_M_MONITOR:
192 		break;
193 	default:
194 		HALDEBUG(ah, HAL_DEBUG_ANY,
195 		    "%s: invalid operating mode %u\n", __func__, opmode);
196 		FAIL(HAL_EINVAL);
197 		break;
198 	}
199 	HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3);
200 
201 	/* Preserve certain DMA hardware registers on a channel change */
202 	if (bChannelChange) {
203 		/*
204 		 * Need to save/restore the TSF because of an issue
205 		 * that accelerates the TSF during a chip reset.
206 		 *
207 		 * We could use system timer routines to more
208 		 * accurately restore the TSF, but
209 		 * 1. Timer routines on certain platforms are
210 		 *	not accurate enough (e.g. 1 ms resolution).
211 		 * 2. It would still not be accurate.
212 		 *
213 		 * The most important aspect of this workaround,
214 		 * is that, after reset, the TSF is behind
215 		 * other STAs TSFs.  This will allow the STA to
216 		 * properly resynchronize its TSF in adhoc mode.
217 		 */
218 		saveTsfLow  = OS_REG_READ(ah, AR_TSF_L32);
219 		saveTsfHigh = OS_REG_READ(ah, AR_TSF_U32);
220 
221 		/* Read frame sequence count */
222 		if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
223 			saveFrameSeqCount[0] = OS_REG_READ(ah, AR_D0_SEQNUM);
224 		} else {
225 			for (i = 0; i < AR_NUM_DCU; i++)
226 				saveFrameSeqCount[i] = OS_REG_READ(ah, AR_DSEQNUM(i));
227 		}
228 		if (!IEEE80211_IS_CHAN_DFS(chan))
229 			chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
230 	}
231 
232 	/*
233 	 * Preserve the antenna on a channel change
234 	 */
235 	saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
236 	if (saveDefAntenna == 0)
237 		saveDefAntenna = 1;
238 
239 	/* Save hardware flag before chip reset clears the register */
240 	macStaId1 = OS_REG_READ(ah, AR_STA_ID1) & AR_STA_ID1_BASE_RATE_11B;
241 
242 	/* Save led state from pci config register */
243 	ledstate = OS_REG_READ(ah, AR_PCICFG) &
244 		(AR_PCICFG_LEDCTL | AR_PCICFG_LEDMODE | AR_PCICFG_LEDBLINK |
245 		 AR_PCICFG_LEDSLOW);
246 	softLedCfg = OS_REG_READ(ah, AR_GPIOCR);
247 	softLedState = OS_REG_READ(ah, AR_GPIODO);
248 
249 	if (!ar5211ChipReset(ah, chan)) {
250 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
251 		FAIL(HAL_EIO);
252 	}
253 
254 	/* Setup the indices for the next set of register array writes */
255 	if (IEEE80211_IS_CHAN_5GHZ(chan)) {
256 		freqIndex = 1;
257 		if (IEEE80211_IS_CHAN_TURBO(chan))
258 			modesIndex = 2;
259 		else if (IEEE80211_IS_CHAN_A(chan))
260 			modesIndex = 1;
261 		else {
262 			HALDEBUG(ah, HAL_DEBUG_ANY,
263 			    "%s: invalid channel %u/0x%x\n",
264 			    __func__, chan->ic_freq, chan->ic_flags);
265 			FAIL(HAL_EINVAL);
266 		}
267 	} else {
268 		freqIndex = 2;
269 		if (IEEE80211_IS_CHAN_B(chan))
270 			modesIndex = 3;
271 		else if (IEEE80211_IS_CHAN_PUREG(chan))
272 			modesIndex = 4;
273 		else {
274 			HALDEBUG(ah, HAL_DEBUG_ANY,
275 			    "%s: invalid channel %u/0x%x\n",
276 			    __func__, chan->ic_freq, chan->ic_flags);
277 			FAIL(HAL_EINVAL);
278 		}
279 	}
280 
281 	/* Set correct Baseband to analog shift setting to access analog chips. */
282 	if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
283 		OS_REG_WRITE(ah, AR_PHY_BASE, 0x00000007);
284 	} else {
285 		OS_REG_WRITE(ah, AR_PHY_BASE, 0x00000047);
286 	}
287 
288 	/* Write parameters specific to AR5211 */
289 	if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
290 		if (IEEE80211_IS_CHAN_2GHZ(chan) &&
291 		    AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1) {
292 			HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
293 			uint32_t ob2GHz, db2GHz;
294 
295 			if (IEEE80211_IS_CHAN_CCK(chan)) {
296 				ob2GHz = ee->ee_ob2GHz[0];
297 				db2GHz = ee->ee_db2GHz[0];
298 			} else {
299 				ob2GHz = ee->ee_ob2GHz[1];
300 				db2GHz = ee->ee_db2GHz[1];
301 			}
302 			ob2GHz = ath_hal_reverseBits(ob2GHz, 3);
303 			db2GHz = ath_hal_reverseBits(db2GHz, 3);
304 			ar5211Mode2_4[25][freqIndex] =
305 				(ar5211Mode2_4[25][freqIndex] & ~0xC0) |
306 					((ob2GHz << 6) & 0xC0);
307 			ar5211Mode2_4[26][freqIndex] =
308 				(ar5211Mode2_4[26][freqIndex] & ~0x0F) |
309 					(((ob2GHz >> 2) & 0x1) |
310 					 ((db2GHz << 1) & 0x0E));
311 		}
312 		for (i = 0; i < N(ar5211Mode2_4); i++)
313 			OS_REG_WRITE(ah, ar5211Mode2_4[i][0],
314 				ar5211Mode2_4[i][freqIndex]);
315 	}
316 
317 	/* Write the analog registers 6 and 7 before other config */
318 	ar5211SetRf6and7(ah, chan);
319 
320 	/* Write registers that vary across all modes */
321 	for (i = 0; i < N(ar5211Modes); i++)
322 		OS_REG_WRITE(ah, ar5211Modes[i][0], ar5211Modes[i][modesIndex]);
323 
324 	/* Write RFGain Parameters that differ between 2.4 and 5 GHz */
325 	for (i = 0; i < N(ar5211BB_RfGain); i++)
326 		OS_REG_WRITE(ah, ar5211BB_RfGain[i][0], ar5211BB_RfGain[i][freqIndex]);
327 
328 	/* Write Common Array Parameters */
329 	for (i = 0; i < N(ar5211Common); i++) {
330 		uint32_t reg = ar5211Common[i][0];
331 		/* On channel change, don't reset the PCU registers */
332 		if (!(bChannelChange && (0x8000 <= reg && reg < 0x9000)))
333 			OS_REG_WRITE(ah, reg, ar5211Common[i][1]);
334 	}
335 
336 	/* Fix pre-AR5211 register values, this includes AR5311s. */
337 	if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU) {
338 		/*
339 		 * The TX and RX latency values have changed locations
340 		 * within the USEC register in AR5211.  Since they're
341 		 * set via the .ini, for both AR5211 and AR5311, they
342 		 * are written properly here for AR5311.
343 		 */
344 		data = OS_REG_READ(ah, AR_USEC);
345 		/* Must be 0 for proper write in AR5311 */
346 		HALASSERT((data & 0x00700000) == 0);
347 		OS_REG_WRITE(ah, AR_USEC,
348 			(data & (AR_USEC_M | AR_USEC_32_M | AR5311_USEC_TX_LAT_M)) |
349 			((29 << AR5311_USEC_RX_LAT_S) & AR5311_USEC_RX_LAT_M));
350 		/* The following registers exist only on AR5311. */
351 		OS_REG_WRITE(ah, AR5311_QDCLKGATE, 0);
352 
353 		/* Set proper ADC & DAC delays for AR5311. */
354 		OS_REG_WRITE(ah, 0x00009878, 0x00000008);
355 
356 		/* Enable the PCU FIFO corruption ECO on AR5311. */
357 		OS_REG_WRITE(ah, AR_DIAG_SW,
358 			OS_REG_READ(ah, AR_DIAG_SW) | AR5311_DIAG_SW_USE_ECO);
359 	}
360 
361 	/* Restore certain DMA hardware registers on a channel change */
362 	if (bChannelChange) {
363 		/* Restore TSF */
364 		OS_REG_WRITE(ah, AR_TSF_L32, saveTsfLow);
365 		OS_REG_WRITE(ah, AR_TSF_U32, saveTsfHigh);
366 
367 		if (AH_PRIVATE(ah)->ah_macVersion >= AR_SREV_VERSION_OAHU) {
368 			OS_REG_WRITE(ah, AR_D0_SEQNUM, saveFrameSeqCount[0]);
369 		} else {
370 			for (i = 0; i < AR_NUM_DCU; i++)
371 				OS_REG_WRITE(ah, AR_DSEQNUM(i), saveFrameSeqCount[i]);
372 		}
373 	}
374 
375 	OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
376 	OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
377 		| macStaId1
378 	);
379 	ar5211SetOperatingMode(ah, opmode);
380 
381 	/* Restore previous led state */
382 	OS_REG_WRITE(ah, AR_PCICFG, OS_REG_READ(ah, AR_PCICFG) | ledstate);
383 	OS_REG_WRITE(ah, AR_GPIOCR, softLedCfg);
384 	OS_REG_WRITE(ah, AR_GPIODO, softLedState);
385 
386 	/* Restore previous antenna */
387 	OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
388 
389 	OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
390 	OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4));
391 
392 	/* Restore bmiss rssi & count thresholds */
393 	OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
394 
395 	OS_REG_WRITE(ah, AR_ISR, ~0);		/* cleared on write */
396 
397 	/*
398 	 * for pre-Production Oahu only.
399 	 * Disable clock gating in all DMA blocks. Helps when using
400 	 * 11B and AES but results in higher power consumption.
401 	 */
402 	if (AH_PRIVATE(ah)->ah_macVersion == AR_SREV_VERSION_OAHU &&
403 	    AH_PRIVATE(ah)->ah_macRev < AR_SREV_OAHU_PROD) {
404 		OS_REG_WRITE(ah, AR_CFG,
405 			OS_REG_READ(ah, AR_CFG) | AR_CFG_CLK_GATE_DIS);
406 	}
407 
408 	/* Setup the transmit power values. */
409 	if (!ar5211SetTransmitPower(ah, chan)) {
410 		HALDEBUG(ah, HAL_DEBUG_ANY,
411 		    "%s: error init'ing transmit power\n", __func__);
412 		FAIL(HAL_EIO);
413 	}
414 
415 	/*
416 	 * Configurable OFDM spoofing for 11n compatibility; used
417 	 * only when operating in station mode.
418 	 */
419 	if (opmode != HAL_M_HOSTAP &&
420 	    (AH_PRIVATE(ah)->ah_11nCompat & HAL_DIAG_11N_SERVICES) != 0) {
421 		/* NB: override the .ini setting */
422 		OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
423 			AR_PHY_FRAME_CTL_ERR_SERV,
424 			MS(AH_PRIVATE(ah)->ah_11nCompat, HAL_DIAG_11N_SERVICES)&1);
425 	}
426 
427 	/* Setup board specific options for EEPROM version 3 */
428 	ar5211SetBoardValues(ah, chan);
429 
430 	if (!ar5211SetChannel(ah, chan)) {
431 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set channel\n",
432 		    __func__);
433 		FAIL(HAL_EIO);
434 	}
435 
436 	/* Activate the PHY */
437 	if (AH_PRIVATE(ah)->ah_devid == AR5211_FPGA11B &&
438 	    IEEE80211_IS_CHAN_2GHZ(chan))
439 		OS_REG_WRITE(ah, 0xd808, 0x502); /* required for FPGA */
440 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
441 
442 	/*
443 	 * Wait for the frequency synth to settle (synth goes on
444 	 * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
445 	 * Value is in 100ns increments.
446 	 */
447 	data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_M;
448 	if (IEEE80211_IS_CHAN_CCK(chan)) {
449 		synthDelay = (4 * data) / 22;
450 	} else {
451 		synthDelay = data / 10;
452 	}
453 	/*
454 	 * There is an issue if the AP starts the calibration before
455 	 * the baseband timeout completes.  This could result in the
456 	 * rxclear false triggering.  Add an extra delay to ensure this
457 	 * this does not happen.
458 	 */
459 	OS_DELAY(synthDelay + DELAY_BASE_ACTIVATE);
460 
461 	/* Calibrate the AGC and wait for completion. */
462 	OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
463 		 OS_REG_READ(ah, AR_PHY_AGC_CONTROL) | AR_PHY_AGC_CONTROL_CAL);
464 	(void) ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0);
465 
466 	/* Perform noise floor and set status */
467 	if (!ar5211CalNoiseFloor(ah, chan)) {
468 		if (!IEEE80211_IS_CHAN_CCK(chan))
469 			chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
470 		HALDEBUG(ah, HAL_DEBUG_ANY,
471 		    "%s: noise floor calibration failed\n", __func__);
472 		FAIL(HAL_EIO);
473 	}
474 
475 	/* Start IQ calibration w/ 2^(INIT_IQCAL_LOG_COUNT_MAX+1) samples */
476 	if (ahp->ah_calibrationTime != 0) {
477 		OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4,
478 			AR_PHY_TIMING_CTRL4_DO_IQCAL | (INIT_IQCAL_LOG_COUNT_MAX << AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX_S));
479 		ahp->ah_bIQCalibration = AH_TRUE;
480 	}
481 
482 	/* set 1:1 QCU to DCU mapping for all queues */
483 	for (q = 0; q < AR_NUM_DCU; q++)
484 		OS_REG_WRITE(ah, AR_DQCUMASK(q), 1<<q);
485 
486 	for (q = 0; q < HAL_NUM_TX_QUEUES; q++)
487 		ar5211ResetTxQueue(ah, q);
488 
489 	/* Setup QCU0 transmit interrupt masks (TX_ERR, TX_OK, TX_DESC, TX_URN) */
490 	OS_REG_WRITE(ah, AR_IMR_S0,
491 		 (AR_IMR_S0_QCU_TXOK & AR_QCU_0) |
492 		 (AR_IMR_S0_QCU_TXDESC & (AR_QCU_0<<AR_IMR_S0_QCU_TXDESC_S)));
493 	OS_REG_WRITE(ah, AR_IMR_S1, (AR_IMR_S1_QCU_TXERR & AR_QCU_0));
494 	OS_REG_WRITE(ah, AR_IMR_S2, (AR_IMR_S2_QCU_TXURN & AR_QCU_0));
495 
496 	/*
497 	 * GBL_EIFS must always be written after writing
498 	 *		to any QCUMASK register.
499 	 */
500 	OS_REG_WRITE(ah, AR_D_GBL_IFS_EIFS, OS_REG_READ(ah, AR_D_GBL_IFS_EIFS));
501 
502 	/* Now set up the Interrupt Mask Register and save it for future use */
503 	OS_REG_WRITE(ah, AR_IMR, INIT_INTERRUPT_MASK);
504 	ahp->ah_maskReg = INIT_INTERRUPT_MASK;
505 
506 	/* Enable bus error interrupts */
507 	OS_REG_WRITE(ah, AR_IMR_S2, OS_REG_READ(ah, AR_IMR_S2) |
508 		 AR_IMR_S2_MCABT | AR_IMR_S2_SSERR | AR_IMR_S2_DPERR);
509 
510 	/* Enable interrupts specific to AP */
511 	if (opmode == HAL_M_HOSTAP) {
512 		OS_REG_WRITE(ah, AR_IMR, OS_REG_READ(ah, AR_IMR) | AR_IMR_MIB);
513 		ahp->ah_maskReg |= AR_IMR_MIB;
514 	}
515 
516 	if (AH_PRIVATE(ah)->ah_rfkillEnabled)
517 		ar5211EnableRfKill(ah);
518 
519 	/*
520 	 * Writing to AR_BEACON will start timers. Hence it should
521 	 * be the last register to be written. Do not reset tsf, do
522 	 * not enable beacons at this point, but preserve other values
523 	 * like beaconInterval.
524 	 */
525 	OS_REG_WRITE(ah, AR_BEACON,
526 		(OS_REG_READ(ah, AR_BEACON) &~ (AR_BEACON_EN | AR_BEACON_RESET_TSF)));
527 
528 	/* Restore user-specified slot time and timeouts */
529 	if (ahp->ah_sifstime != (u_int) -1)
530 		ar5211SetSifsTime(ah, ahp->ah_sifstime);
531 	if (ahp->ah_slottime != (u_int) -1)
532 		ar5211SetSlotTime(ah, ahp->ah_slottime);
533 	if (ahp->ah_acktimeout != (u_int) -1)
534 		ar5211SetAckTimeout(ah, ahp->ah_acktimeout);
535 	if (ahp->ah_ctstimeout != (u_int) -1)
536 		ar5211SetCTSTimeout(ah, ahp->ah_ctstimeout);
537 	if (AH_PRIVATE(ah)->ah_diagreg != 0)
538 		OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
539 
540 	AH_PRIVATE(ah)->ah_opmode = opmode;	/* record operating mode */
541 
542 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
543 
544 	return AH_TRUE;
545 bad:
546 	if (status != AH_NULL)
547 		*status = ecode;
548 	return AH_FALSE;
549 #undef FAIL
550 #undef N
551 }
552 
553 /*
554  * Places the PHY and Radio chips into reset.  A full reset
555  * must be called to leave this state.  The PCI/MAC/PCU are
556  * not placed into reset as we must receive interrupt to
557  * re-enable the hardware.
558  */
559 HAL_BOOL
560 ar5211PhyDisable(struct ath_hal *ah)
561 {
562 	return ar5211SetResetReg(ah, AR_RC_BB);
563 }
564 
565 /*
566  * Places all of hardware into reset
567  */
568 HAL_BOOL
569 ar5211Disable(struct ath_hal *ah)
570 {
571 	if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
572 		return AH_FALSE;
573 	/*
574 	 * Reset the HW - PCI must be reset after the rest of the
575 	 * device has been reset.
576 	 */
577 	if (!ar5211SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI))
578 		return AH_FALSE;
579 	OS_DELAY(2100);	   /* 8245 @ 96Mhz hangs with 2000us. */
580 
581 	return AH_TRUE;
582 }
583 
584 /*
585  * Places the hardware into reset and then pulls it out of reset
586  *
587  * Only write the PLL if we're changing to or from CCK mode
588  *
589  * Attach calls with channelFlags = 0, as the coldreset should have
590  * us in the correct mode and we cannot check the hwchannel flags.
591  */
592 HAL_BOOL
593 ar5211ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
594 {
595 	if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
596 		return AH_FALSE;
597 
598 	/* NB: called from attach with chan null */
599 	if (chan != AH_NULL) {
600 		/* Set CCK and Turbo modes correctly */
601 		OS_REG_WRITE(ah, AR_PHY_TURBO, IEEE80211_IS_CHAN_TURBO(chan) ?
602 		    AR_PHY_FC_TURBO_MODE | AR_PHY_FC_TURBO_SHORT : 0);
603 		if (IEEE80211_IS_CHAN_B(chan)) {
604 			OS_REG_WRITE(ah, AR5211_PHY_MODE,
605 			    AR5211_PHY_MODE_CCK | AR5211_PHY_MODE_RF2GHZ);
606 			OS_REG_WRITE(ah, AR_PHY_PLL_CTL, AR_PHY_PLL_CTL_44);
607 			/* Wait for the PLL to settle */
608 			OS_DELAY(DELAY_PLL_SETTLE);
609 		} else if (AH_PRIVATE(ah)->ah_devid == AR5211_DEVID) {
610 			OS_REG_WRITE(ah, AR_PHY_PLL_CTL, AR_PHY_PLL_CTL_40);
611 			OS_DELAY(DELAY_PLL_SETTLE);
612 			OS_REG_WRITE(ah, AR5211_PHY_MODE,
613 			    AR5211_PHY_MODE_OFDM | (IEEE80211_IS_CHAN_2GHZ(chan) ?
614 				AR5211_PHY_MODE_RF2GHZ :
615 				AR5211_PHY_MODE_RF5GHZ));
616 		}
617 	}
618 
619 	/*
620 	 * Reset the HW - PCI must be reset after the rest of the
621 	 * device has been reset
622 	 */
623 	if (!ar5211SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI))
624 		return AH_FALSE;
625 	OS_DELAY(2100);	   /* 8245 @ 96Mhz hangs with 2000us. */
626 
627 	/* Bring out of sleep mode (AGAIN) */
628 	if (!ar5211SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
629 		return AH_FALSE;
630 
631 	/* Clear warm reset register */
632 	return ar5211SetResetReg(ah, 0);
633 }
634 
635 /*
636  * Recalibrate the lower PHY chips to account for temperature/environment
637  * changes.
638  */
639 HAL_BOOL
640 ar5211PerCalibrationN(struct ath_hal *ah,  struct ieee80211_channel *chan,
641 	u_int chainMask, HAL_BOOL longCal, HAL_BOOL *isCalDone)
642 {
643 	struct ath_hal_5211 *ahp = AH5211(ah);
644 	HAL_CHANNEL_INTERNAL *ichan;
645 	int32_t qCoff, qCoffDenom;
646 	uint32_t data;
647 	int32_t iqCorrMeas;
648 	int32_t iCoff, iCoffDenom;
649 	uint32_t powerMeasQ, powerMeasI;
650 
651 	ichan = ath_hal_checkchannel(ah, chan);
652 	if (ichan == AH_NULL) {
653 		HALDEBUG(ah, HAL_DEBUG_ANY,
654 		    "%s: invalid channel %u/0x%x; no mapping\n",
655 		    __func__, chan->ic_freq, chan->ic_flags);
656 		return AH_FALSE;
657 	}
658 	/* IQ calibration in progress. Check to see if it has finished. */
659 	if (ahp->ah_bIQCalibration &&
660 	    !(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_DO_IQCAL)) {
661 		/* IQ Calibration has finished. */
662 		ahp->ah_bIQCalibration = AH_FALSE;
663 
664 		/* Read calibration results. */
665 		powerMeasI = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_I);
666 		powerMeasQ = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_Q);
667 		iqCorrMeas = OS_REG_READ(ah, AR_PHY_IQCAL_RES_IQ_CORR_MEAS);
668 
669 		/*
670 		 * Prescale these values to remove 64-bit operation requirement at the loss
671 		 * of a little precision.
672 		 */
673 		iCoffDenom = (powerMeasI / 2 + powerMeasQ / 2) / 128;
674 		qCoffDenom = powerMeasQ / 64;
675 
676 		/* Protect against divide-by-0. */
677 		if (iCoffDenom != 0 && qCoffDenom != 0) {
678 			iCoff = (-iqCorrMeas) / iCoffDenom;
679 			/* IQCORR_Q_I_COFF is a signed 6 bit number */
680 			iCoff = iCoff & 0x3f;
681 
682 			qCoff = ((int32_t)powerMeasI / qCoffDenom) - 64;
683 			/* IQCORR_Q_Q_COFF is a signed 5 bit number */
684 			qCoff = qCoff & 0x1f;
685 
686 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "powerMeasI = 0x%08x\n",
687 			    powerMeasI);
688 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "powerMeasQ = 0x%08x\n",
689 			    powerMeasQ);
690 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "iqCorrMeas = 0x%08x\n",
691 			    iqCorrMeas);
692 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "iCoff	  = %d\n",
693 			    iCoff);
694 			HALDEBUG(ah, HAL_DEBUG_PERCAL, "qCoff	  = %d\n",
695 			    qCoff);
696 
697 			/* Write IQ */
698 			data  = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) |
699 				AR_PHY_TIMING_CTRL4_IQCORR_ENABLE |
700 				(((uint32_t)iCoff) << AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF_S) |
701 				((uint32_t)qCoff);
702 			OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4, data);
703 		}
704 	}
705 	*isCalDone = !ahp->ah_bIQCalibration;
706 
707 	if (longCal) {
708 		/* Perform noise floor and set status */
709 		if (!ar5211IsNfGood(ah, chan)) {
710 			/* report up and clear internal state */
711 			chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
712 			return AH_FALSE;
713 		}
714 		if (!ar5211CalNoiseFloor(ah, chan)) {
715 			/*
716 			 * Delay 5ms before retrying the noise floor
717 			 * just to make sure, as we are in an error
718 			 * condition here.
719 			 */
720 			OS_DELAY(5000);
721 			if (!ar5211CalNoiseFloor(ah, chan)) {
722 				if (!IEEE80211_IS_CHAN_CCK(chan))
723 					chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
724 				return AH_FALSE;
725 			}
726 		}
727 		ar5211RequestRfgain(ah);
728 	}
729 	return AH_TRUE;
730 }
731 
732 HAL_BOOL
733 ar5211PerCalibration(struct ath_hal *ah, struct ieee80211_channel *chan,
734 	HAL_BOOL *isIQdone)
735 {
736 	return ar5211PerCalibrationN(ah,  chan, 0x1, AH_TRUE, isIQdone);
737 }
738 
739 HAL_BOOL
740 ar5211ResetCalValid(struct ath_hal *ah, const struct ieee80211_channel *chan)
741 {
742 	/* XXX */
743 	return AH_TRUE;
744 }
745 
746 /*
747  * Writes the given reset bit mask into the reset register
748  */
749 static HAL_BOOL
750 ar5211SetResetReg(struct ath_hal *ah, uint32_t resetMask)
751 {
752 	uint32_t mask = resetMask ? resetMask : ~0;
753 	HAL_BOOL rt;
754 
755 	(void) OS_REG_READ(ah, AR_RXDP);/* flush any pending MMR writes */
756 	OS_REG_WRITE(ah, AR_RC, resetMask);
757 
758 	/* need to wait at least 128 clocks when reseting PCI before read */
759 	OS_DELAY(15);
760 
761 	resetMask &= AR_RC_MAC | AR_RC_BB;
762 	mask &= AR_RC_MAC | AR_RC_BB;
763 	rt = ath_hal_wait(ah, AR_RC, mask, resetMask);
764         if ((resetMask & AR_RC_MAC) == 0) {
765 		if (isBigEndian()) {
766 			/*
767 			 * Set CFG, little-endian for register
768 			 * and descriptor accesses.
769 			 */
770 			mask = INIT_CONFIG_STATUS |
771 				AR_CFG_SWTD | AR_CFG_SWRD | AR_CFG_SWRG;
772 			OS_REG_WRITE(ah, AR_CFG, LE_READ_4(&mask));
773 		} else
774 			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
775 	}
776 	return rt;
777 }
778 
779 /*
780  * Takes the MHz channel value and sets the Channel value
781  *
782  * ASSUMES: Writes enabled to analog bus before AGC is active
783  *   or by disabling the AGC.
784  */
785 static HAL_BOOL
786 ar5211SetChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
787 {
788 	uint32_t refClk, reg32, data2111;
789 	int16_t chan5111, chanIEEE;
790 
791 	chanIEEE = chan->ic_ieee;
792 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
793 		const CHAN_INFO_2GHZ* ci =
794 			&chan2GHzData[chanIEEE + CI_2GHZ_INDEX_CORRECTION];
795 
796 		data2111 = ((ath_hal_reverseBits(ci->channelSelect, 8) & 0xff)
797 				<< 5)
798 			 | (ci->refClkSel << 4);
799 		chan5111 = ci->channel5111;
800 	} else {
801 		data2111 = 0;
802 		chan5111 = chanIEEE;
803 	}
804 
805 	/* Rest of the code is common for 5 GHz and 2.4 GHz. */
806 	if (chan5111 >= 145 || (chan5111 & 0x1)) {
807 		reg32 = ath_hal_reverseBits(chan5111 - 24, 8) & 0xFF;
808 		refClk = 1;
809 	} else {
810 		reg32 = ath_hal_reverseBits(((chan5111 - 24) / 2), 8) & 0xFF;
811 		refClk = 0;
812 	}
813 
814 	reg32 = (reg32 << 2) | (refClk << 1) | (1 << 10) | 0x1;
815 	OS_REG_WRITE(ah, AR_PHY(0x27), ((data2111 & 0xff) << 8) | (reg32 & 0xff));
816 	reg32 >>= 8;
817 	OS_REG_WRITE(ah, AR_PHY(0x34), (data2111 & 0xff00) | (reg32 & 0xff));
818 
819 	AH_PRIVATE(ah)->ah_curchan = chan;
820 	return AH_TRUE;
821 }
822 
823 static int16_t
824 ar5211GetNoiseFloor(struct ath_hal *ah)
825 {
826 	int16_t nf;
827 
828 	nf = (OS_REG_READ(ah, AR_PHY(25)) >> 19) & 0x1ff;
829 	if (nf & 0x100)
830 		nf = 0 - ((nf ^ 0x1ff) + 1);
831 	return nf;
832 }
833 
834 /*
835  * Peform the noisefloor calibration for the length of time set
836  * in runTime (valid values 1 to 7)
837  *
838  * Returns: The NF value at the end of the given time (or 0 for failure)
839  */
840 int16_t
841 ar5211RunNoiseFloor(struct ath_hal *ah, uint8_t runTime, int16_t startingNF)
842 {
843 	int i, searchTime;
844 
845 	HALASSERT(runTime <= 7);
846 
847 	/* Setup  noise floor run time and starting value */
848 	OS_REG_WRITE(ah, AR_PHY(25),
849 		(OS_REG_READ(ah, AR_PHY(25)) & ~0xFFF) |
850 			 ((runTime << 9) & 0xE00) | (startingNF & 0x1FF));
851 	/* Calibrate the noise floor */
852 	OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
853 		OS_REG_READ(ah, AR_PHY_AGC_CONTROL) | AR_PHY_AGC_CONTROL_NF);
854 
855 	/* Compute the required amount of searchTime needed to finish NF */
856 	if (runTime == 0) {
857 		/* 8 search windows * 6.4us each */
858 		searchTime = 8  * 7;
859 	} else {
860 		/* 512 * runtime search windows * 6.4us each */
861 		searchTime = (runTime * 512)  * 7;
862 	}
863 
864 	/*
865 	 * Do not read noise floor until it has been updated
866 	 *
867 	 * As a guesstimate - we may only get 1/60th the time on
868 	 * the air to see search windows  in a heavily congested
869 	 * network (40 us every 2400 us of time)
870 	 */
871 	for (i = 0; i < 60; i++) {
872 		if ((OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) == 0)
873 			break;
874 		OS_DELAY(searchTime);
875 	}
876 	if (i >= 60) {
877 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
878 		    "NF with runTime %d failed to end on channel %d\n",
879 		    runTime, AH_PRIVATE(ah)->ah_curchan->ic_freq);
880 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
881 		    "  PHY NF Reg state:	 0x%x\n",
882 		    OS_REG_READ(ah, AR_PHY_AGC_CONTROL));
883 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
884 		    "  PHY Active Reg state: 0x%x\n",
885 		    OS_REG_READ(ah, AR_PHY_ACTIVE));
886 		return 0;
887 	}
888 
889 	return ar5211GetNoiseFloor(ah);
890 }
891 
892 static HAL_BOOL
893 getNoiseFloorThresh(struct ath_hal *ah, const struct ieee80211_channel *chan,
894 	int16_t *nft)
895 {
896 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
897 
898 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
899 	case IEEE80211_CHAN_A:
900 		*nft = ee->ee_noiseFloorThresh[0];
901 		break;
902 	case IEEE80211_CHAN_B:
903 		*nft = ee->ee_noiseFloorThresh[1];
904 		break;
905 	case IEEE80211_CHAN_PUREG:
906 		*nft = ee->ee_noiseFloorThresh[2];
907 		break;
908 	default:
909 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
910 		    __func__, chan->ic_flags);
911 		return AH_FALSE;
912 	}
913 	return AH_TRUE;
914 }
915 
916 /*
917  * Read the NF and check it against the noise floor threshhold
918  *
919  * Returns: TRUE if the NF is good
920  */
921 static HAL_BOOL
922 ar5211IsNfGood(struct ath_hal *ah, struct ieee80211_channel *chan)
923 {
924 	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
925 	int16_t nf, nfThresh;
926 
927 	if (!getNoiseFloorThresh(ah, chan, &nfThresh))
928 		return AH_FALSE;
929 	if (OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF)
930 		HALDEBUG(ah, HAL_DEBUG_ANY,
931 		    "%s: NF did not complete in calibration window\n", __func__);
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)(PWR_STEP * ((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 	ar5211FindValueInList(lFreq, llPcdac, pSrcStruct, &lPwr);
1716 	ar5211FindValueInList(lFreq, ulPcdac, pSrcStruct, &uPwr);
1717 	lScaledPwr = ar5211GetInterpolatedValue(pcdacValue,
1718 				llPcdac, ulPcdac, lPwr, uPwr, 0);
1719 
1720 	ar5211FindValueInList(rFreq, lrPcdac, pSrcStruct, &lPwr);
1721 	ar5211FindValueInList(rFreq, urPcdac, pSrcStruct, &uPwr);
1722 	rScaledPwr = ar5211GetInterpolatedValue(pcdacValue,
1723 				lrPcdac, urPcdac, lPwr, uPwr, 0);
1724 
1725 	return ar5211GetInterpolatedValue(channel, lFreq, rFreq,
1726 		lScaledPwr, rScaledPwr, 0);
1727 }
1728 
1729 /*
1730  * Find the value from the calibrated source data struct
1731  */
1732 HAL_BOOL
1733 ar5211FindValueInList(uint16_t channel, uint16_t pcdacValue,
1734 	const PCDACS_EEPROM *pSrcStruct, uint16_t *powerValue)
1735 {
1736 	const DATA_PER_CHANNEL *pChannelData;
1737 	const uint16_t *pPcdac;
1738 	uint16_t i, j;
1739 
1740 	pChannelData = pSrcStruct->pDataPerChannel;
1741 	for (i = 0; i < pSrcStruct->numChannels; i++ ) {
1742 		if (pChannelData->channelValue == channel) {
1743 			pPcdac = pChannelData->PcdacValues;
1744 			for (j = 0; j < pChannelData->numPcdacValues; j++ ) {
1745 				if (*pPcdac == pcdacValue) {
1746 					*powerValue = pChannelData->PwrValues[j];
1747 					return AH_TRUE;
1748 				}
1749 				pPcdac++;
1750 			}
1751 		}
1752 		pChannelData++;
1753 	}
1754 	return AH_FALSE;
1755 }
1756 
1757 /*
1758  * Returns interpolated or the scaled up interpolated value
1759  */
1760 uint16_t
1761 ar5211GetInterpolatedValue(uint16_t target,
1762 	uint16_t srcLeft, uint16_t srcRight,
1763 	uint16_t targetLeft, uint16_t targetRight,
1764 	HAL_BOOL scaleUp)
1765 {
1766 	uint16_t rv;
1767 	int16_t lRatio;
1768 	uint16_t scaleValue = EEP_SCALE;
1769 
1770 	/* to get an accurate ratio, always scale, if want to scale, then don't scale back down */
1771 	if ((targetLeft * targetRight) == 0)
1772 		return 0;
1773 	if (scaleUp)
1774 		scaleValue = 1;
1775 
1776 	if (srcRight != srcLeft) {
1777 		/*
1778 		 * Note the ratio always need to be scaled,
1779 		 * since it will be a fraction.
1780 		 */
1781 		lRatio = (target - srcLeft) * EEP_SCALE / (srcRight - srcLeft);
1782 		if (lRatio < 0) {
1783 		    /* Return as Left target if value would be negative */
1784 		    rv = targetLeft * (scaleUp ? EEP_SCALE : 1);
1785 		} else if (lRatio > EEP_SCALE) {
1786 		    /* Return as Right target if Ratio is greater than 100% (SCALE) */
1787 		    rv = targetRight * (scaleUp ? EEP_SCALE : 1);
1788 		} else {
1789 			rv = (lRatio * targetRight + (EEP_SCALE - lRatio) *
1790 					targetLeft) / scaleValue;
1791 		}
1792 	} else {
1793 		rv = targetLeft;
1794 		if (scaleUp)
1795 			rv *= EEP_SCALE;
1796 	}
1797 	return rv;
1798 }
1799 
1800 /*
1801  *  Look for value being within 0.1 of the search values
1802  *  however, NDIS can't do float calculations, so multiply everything
1803  *  up by EEP_SCALE so can do integer arithmatic
1804  *
1805  * INPUT  value	   -value to search for
1806  * INPUT  pList	   -ptr to the list to search
1807  * INPUT  listSize	-number of entries in list
1808  * OUTPUT pLowerValue -return the lower value
1809  * OUTPUT pUpperValue -return the upper value
1810  */
1811 void
1812 ar5211GetLowerUpperValues(uint16_t value,
1813 	const uint16_t *pList, uint16_t listSize,
1814 	uint16_t *pLowerValue, uint16_t *pUpperValue)
1815 {
1816 	const uint16_t listEndValue = *(pList + listSize - 1);
1817 	uint32_t target = value * EEP_SCALE;
1818 	int i;
1819 
1820 	/*
1821 	 * See if value is lower than the first value in the list
1822 	 * if so return first value
1823 	 */
1824 	if (target < (uint32_t)(*pList * EEP_SCALE - EEP_DELTA)) {
1825 		*pLowerValue = *pList;
1826 		*pUpperValue = *pList;
1827 		return;
1828 	}
1829 
1830 	/*
1831 	 * See if value is greater than last value in list
1832 	 * if so return last value
1833 	 */
1834 	if (target > (uint32_t)(listEndValue * EEP_SCALE + EEP_DELTA)) {
1835 		*pLowerValue = listEndValue;
1836 		*pUpperValue = listEndValue;
1837 		return;
1838 	}
1839 
1840 	/* look for value being near or between 2 values in list */
1841 	for (i = 0; i < listSize; i++) {
1842 		/*
1843 		 * If value is close to the current value of the list
1844 		 * then target is not between values, it is one of the values
1845 		 */
1846 		if (abs(pList[i] * EEP_SCALE - (int32_t) target) < EEP_DELTA) {
1847 			*pLowerValue = pList[i];
1848 			*pUpperValue = pList[i];
1849 			return;
1850 		}
1851 
1852 		/*
1853 		 * Look for value being between current value and next value
1854 		 * if so return these 2 values
1855 		 */
1856 		if (target < (uint32_t)(pList[i + 1] * EEP_SCALE - EEP_DELTA)) {
1857 			*pLowerValue = pList[i];
1858 			*pUpperValue = pList[i + 1];
1859 			return;
1860 		}
1861 	}
1862 }
1863 
1864 /*
1865  * Get the upper and lower pcdac given the channel and the pcdac
1866  * used in the search
1867  */
1868 void
1869 ar5211GetLowerUpperPcdacs(uint16_t pcdac, uint16_t channel,
1870 	const PCDACS_EEPROM *pSrcStruct,
1871 	uint16_t *pLowerPcdac, uint16_t *pUpperPcdac)
1872 {
1873 	const DATA_PER_CHANNEL *pChannelData;
1874 	int i;
1875 
1876 	/* Find the channel information */
1877 	pChannelData = pSrcStruct->pDataPerChannel;
1878 	for (i = 0; i < pSrcStruct->numChannels; i++) {
1879 		if (pChannelData->channelValue == channel)
1880 			break;
1881 		pChannelData++;
1882 	}
1883 	ar5211GetLowerUpperValues(pcdac, pChannelData->PcdacValues,
1884 		pChannelData->numPcdacValues, pLowerPcdac, pUpperPcdac);
1885 }
1886 
1887 #define	DYN_ADJ_UP_MARGIN	15
1888 #define	DYN_ADJ_LO_MARGIN	20
1889 
1890 static const GAIN_OPTIMIZATION_LADDER gainLadder = {
1891 	9,					/* numStepsInLadder */
1892 	4,					/* defaultStepNum */
1893 	{ { {4, 1, 1, 1},  6, "FG8"},
1894 	  { {4, 0, 1, 1},  4, "FG7"},
1895 	  { {3, 1, 1, 1},  3, "FG6"},
1896 	  { {4, 0, 0, 1},  1, "FG5"},
1897 	  { {4, 1, 1, 0},  0, "FG4"},	/* noJack */
1898 	  { {4, 0, 1, 0}, -2, "FG3"},	/* halfJack */
1899 	  { {3, 1, 1, 0}, -3, "FG2"},	/* clip3 */
1900 	  { {4, 0, 0, 0}, -4, "FG1"},	/* noJack */
1901 	  { {2, 1, 1, 0}, -6, "FG0"} 	/* clip2 */
1902 	}
1903 };
1904 
1905 /*
1906  * Initialize the gain structure to good values
1907  */
1908 void
1909 ar5211InitializeGainValues(struct ath_hal *ah)
1910 {
1911 	struct ath_hal_5211 *ahp = AH5211(ah);
1912 	GAIN_VALUES *gv = &ahp->ah_gainValues;
1913 
1914 	/* initialize gain optimization values */
1915 	gv->currStepNum = gainLadder.defaultStepNum;
1916 	gv->currStep = &gainLadder.optStep[gainLadder.defaultStepNum];
1917 	gv->active = AH_TRUE;
1918 	gv->loTrig = 20;
1919 	gv->hiTrig = 35;
1920 }
1921 
1922 static HAL_BOOL
1923 ar5211InvalidGainReadback(struct ath_hal *ah, GAIN_VALUES *gv)
1924 {
1925 	const struct ieee80211_channel *chan = AH_PRIVATE(ah)->ah_curchan;
1926 	uint32_t gStep, g;
1927 	uint32_t L1, L2, L3, L4;
1928 
1929 	if (IEEE80211_IS_CHAN_CCK(chan)) {
1930 		gStep = 0x18;
1931 		L1 = 0;
1932 		L2 = gStep + 4;
1933 		L3 = 0x40;
1934 		L4 = L3 + 50;
1935 
1936 		gv->loTrig = L1;
1937 		gv->hiTrig = L4+5;
1938 	} else {
1939 		gStep = 0x3f;
1940 		L1 = 0;
1941 		L2 = 50;
1942 		L3 = L1;
1943 		L4 = L3 + 50;
1944 
1945 		gv->loTrig = L1 + DYN_ADJ_LO_MARGIN;
1946 		gv->hiTrig = L4 - DYN_ADJ_UP_MARGIN;
1947 	}
1948 	g = gv->currGain;
1949 
1950 	return !((g >= L1 && g<= L2) || (g >= L3 && g <= L4));
1951 }
1952 
1953 /*
1954  * Enable the probe gain check on the next packet
1955  */
1956 static void
1957 ar5211RequestRfgain(struct ath_hal *ah)
1958 {
1959 	struct ath_hal_5211 *ahp = AH5211(ah);
1960 
1961 	/* Enable the gain readback probe */
1962 	OS_REG_WRITE(ah, AR_PHY_PAPD_PROBE,
1963 		  SM(ahp->ah_tx6PowerInHalfDbm, AR_PHY_PAPD_PROBE_POWERTX)
1964 		| AR_PHY_PAPD_PROBE_NEXT_TX);
1965 
1966 	ahp->ah_rfgainState = HAL_RFGAIN_READ_REQUESTED;
1967 }
1968 
1969 /*
1970  * Exported call to check for a recent gain reading and return
1971  * the current state of the thermal calibration gain engine.
1972  */
1973 HAL_RFGAIN
1974 ar5211GetRfgain(struct ath_hal *ah)
1975 {
1976 	struct ath_hal_5211 *ahp = AH5211(ah);
1977 	GAIN_VALUES *gv = &ahp->ah_gainValues;
1978 	uint32_t rddata;
1979 
1980 	if (!gv->active)
1981 		return HAL_RFGAIN_INACTIVE;
1982 
1983 	if (ahp->ah_rfgainState == HAL_RFGAIN_READ_REQUESTED) {
1984 		/* Caller had asked to setup a new reading. Check it. */
1985 		rddata = OS_REG_READ(ah, AR_PHY_PAPD_PROBE);
1986 
1987 		if ((rddata & AR_PHY_PAPD_PROBE_NEXT_TX) == 0) {
1988 			/* bit got cleared, we have a new reading. */
1989 			gv->currGain = rddata >> AR_PHY_PAPD_PROBE_GAINF_S;
1990 			/* inactive by default */
1991 			ahp->ah_rfgainState = HAL_RFGAIN_INACTIVE;
1992 
1993 			if (!ar5211InvalidGainReadback(ah, gv) &&
1994 			    ar5211IsGainAdjustNeeded(ah, gv) &&
1995 			    ar5211AdjustGain(ah, gv) > 0) {
1996 				/*
1997 				 * Change needed. Copy ladder info
1998 				 * into eeprom info.
1999 				 */
2000 				ar5211SetRfgain(ah, gv);
2001 				ahp->ah_rfgainState = HAL_RFGAIN_NEED_CHANGE;
2002 			}
2003 		}
2004 	}
2005 	return ahp->ah_rfgainState;
2006 }
2007 
2008 /*
2009  * Check to see if our readback gain level sits within the linear
2010  * region of our current variable attenuation window
2011  */
2012 static HAL_BOOL
2013 ar5211IsGainAdjustNeeded(struct ath_hal *ah, const GAIN_VALUES *gv)
2014 {
2015 	return (gv->currGain <= gv->loTrig || gv->currGain >= gv->hiTrig);
2016 }
2017 
2018 /*
2019  * Move the rabbit ears in the correct direction.
2020  */
2021 static int32_t
2022 ar5211AdjustGain(struct ath_hal *ah, GAIN_VALUES *gv)
2023 {
2024 	/* return > 0 for valid adjustments. */
2025 	if (!gv->active)
2026 		return -1;
2027 
2028 	gv->currStep = &gainLadder.optStep[gv->currStepNum];
2029 	if (gv->currGain >= gv->hiTrig) {
2030 		if (gv->currStepNum == 0) {
2031 			HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2032 			    "%s: Max gain limit.\n", __func__);
2033 			return -1;
2034 		}
2035 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2036 		    "%s: Adding gain: currG=%d [%s] --> ",
2037 		    __func__, gv->currGain, gv->currStep->stepName);
2038 		gv->targetGain = gv->currGain;
2039 		while (gv->targetGain >= gv->hiTrig && gv->currStepNum > 0) {
2040 			gv->targetGain -= 2 * (gainLadder.optStep[--(gv->currStepNum)].stepGain -
2041 				gv->currStep->stepGain);
2042 			gv->currStep = &gainLadder.optStep[gv->currStepNum];
2043 		}
2044 		HALDEBUG(ah, HAL_DEBUG_RFPARAM, "targG=%d [%s]\n",
2045 		    gv->targetGain, gv->currStep->stepName);
2046 		return 1;
2047 	}
2048 	if (gv->currGain <= gv->loTrig) {
2049 		if (gv->currStepNum == gainLadder.numStepsInLadder-1) {
2050 			HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2051 			    "%s: Min gain limit.\n", __func__);
2052 			return -2;
2053 		}
2054 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2055 		    "%s: Deducting gain: currG=%d [%s] --> ",
2056 		    __func__, gv->currGain, gv->currStep->stepName);
2057 		gv->targetGain = gv->currGain;
2058 		while (gv->targetGain <= gv->loTrig &&
2059 		      gv->currStepNum < (gainLadder.numStepsInLadder - 1)) {
2060 			gv->targetGain -= 2 *
2061 				(gainLadder.optStep[++(gv->currStepNum)].stepGain - 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 2;
2067 	}
2068 	return 0;		/* caller didn't call needAdjGain first */
2069 }
2070 
2071 /*
2072  * Adjust the 5GHz EEPROM information with the desired calibration values.
2073  */
2074 static void
2075 ar5211SetRfgain(struct ath_hal *ah, const GAIN_VALUES *gv)
2076 {
2077 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
2078 
2079 	if (!gv->active)
2080 		return;
2081 	ee->ee_cornerCal.clip = gv->currStep->paramVal[0]; /* bb_tx_clip */
2082 	ee->ee_cornerCal.pd90 = gv->currStep->paramVal[1]; /* rf_pwd_90 */
2083 	ee->ee_cornerCal.pd84 = gv->currStep->paramVal[2]; /* rf_pwd_84 */
2084 	ee->ee_cornerCal.gSel = gv->currStep->paramVal[3]; /* rf_rfgainsel */
2085 }
2086 
2087 static void
2088 ar5211SetOperatingMode(struct ath_hal *ah, int opmode)
2089 {
2090 	struct ath_hal_5211 *ahp = AH5211(ah);
2091 	uint32_t val;
2092 
2093 	val = OS_REG_READ(ah, AR_STA_ID1) & 0xffff;
2094 	switch (opmode) {
2095 	case HAL_M_HOSTAP:
2096 		OS_REG_WRITE(ah, AR_STA_ID1, val
2097 			| AR_STA_ID1_STA_AP
2098 			| AR_STA_ID1_RTS_USE_DEF
2099 			| ahp->ah_staId1Defaults);
2100 		break;
2101 	case HAL_M_IBSS:
2102 		OS_REG_WRITE(ah, AR_STA_ID1, val
2103 			| AR_STA_ID1_ADHOC
2104 			| AR_STA_ID1_DESC_ANTENNA
2105 			| ahp->ah_staId1Defaults);
2106 		break;
2107 	case HAL_M_STA:
2108 	case HAL_M_MONITOR:
2109 		OS_REG_WRITE(ah, AR_STA_ID1, val
2110 			| AR_STA_ID1_DEFAULT_ANTENNA
2111 			| ahp->ah_staId1Defaults);
2112 		break;
2113 	}
2114 }
2115 
2116 void
2117 ar5211SetPCUConfig(struct ath_hal *ah)
2118 {
2119 	ar5211SetOperatingMode(ah, AH_PRIVATE(ah)->ah_opmode);
2120 }
2121