1 /*
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * Copyright (c) 2002-2006 Atheros Communications, Inc.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  *
17  * $FreeBSD$
18  */
19 #include "opt_ah.h"
20 
21 /*
22  * Chips specific device attachment and device info collection
23  * Connects Init Reg Vectors, EEPROM Data, and device Functions.
24  */
25 #include "ah.h"
26 #include "ah_internal.h"
27 #include "ah_devid.h"
28 
29 #include "ar5211/ar5211.h"
30 #include "ar5211/ar5211reg.h"
31 #include "ar5211/ar5211phy.h"
32 
33 #include "ah_eeprom_v3.h"
34 
35 /* Add static register initialization vectors */
36 #include "ar5211/boss.ini"
37 
38 /*
39  * Structure to hold 11b tuning information for Beanie/Sombrero
40  * 16 MHz mode, divider ratio = 198 = NP+S. N=16, S=4 or 6, P=12
41  */
42 typedef struct {
43 	uint32_t	refClkSel;	/* reference clock, 1 for 16 MHz */
44 	uint32_t	channelSelect;	/* P[7:4]S[3:0] bits */
45 	uint16_t	channel5111;	/* 11a channel for 5111 */
46 } CHAN_INFO_2GHZ;
47 
48 #define CI_2GHZ_INDEX_CORRECTION 19
49 static const CHAN_INFO_2GHZ chan2GHzData[] = {
50 	{ 1, 0x46, 96  },	/* 2312 -19 */
51 	{ 1, 0x46, 97  },	/* 2317 -18 */
52 	{ 1, 0x46, 98  },	/* 2322 -17 */
53 	{ 1, 0x46, 99  },	/* 2327 -16 */
54 	{ 1, 0x46, 100 },	/* 2332 -15 */
55 	{ 1, 0x46, 101 },	/* 2337 -14 */
56 	{ 1, 0x46, 102 },	/* 2342 -13 */
57 	{ 1, 0x46, 103 },	/* 2347 -12 */
58 	{ 1, 0x46, 104 },	/* 2352 -11 */
59 	{ 1, 0x46, 105 },	/* 2357 -10 */
60 	{ 1, 0x46, 106 },	/* 2362  -9 */
61 	{ 1, 0x46, 107 },	/* 2367  -8 */
62 	{ 1, 0x46, 108 },	/* 2372  -7 */
63 	/* index -6 to 0 are pad to make this a nolookup table */
64 	{ 1, 0x46, 116 },	/*       -6 */
65 	{ 1, 0x46, 116 },	/*       -5 */
66 	{ 1, 0x46, 116 },	/*       -4 */
67 	{ 1, 0x46, 116 },	/*       -3 */
68 	{ 1, 0x46, 116 },	/*       -2 */
69 	{ 1, 0x46, 116 },	/*       -1 */
70 	{ 1, 0x46, 116 },	/*        0 */
71 	{ 1, 0x46, 116 },	/* 2412   1 */
72 	{ 1, 0x46, 117 },	/* 2417   2 */
73 	{ 1, 0x46, 118 },	/* 2422   3 */
74 	{ 1, 0x46, 119 },	/* 2427   4 */
75 	{ 1, 0x46, 120 },	/* 2432   5 */
76 	{ 1, 0x46, 121 },	/* 2437   6 */
77 	{ 1, 0x46, 122 },	/* 2442   7 */
78 	{ 1, 0x46, 123 },	/* 2447   8 */
79 	{ 1, 0x46, 124 },	/* 2452   9 */
80 	{ 1, 0x46, 125 },	/* 2457  10 */
81 	{ 1, 0x46, 126 },	/* 2462  11 */
82 	{ 1, 0x46, 127 },	/* 2467  12 */
83 	{ 1, 0x46, 128 },	/* 2472  13 */
84 	{ 1, 0x44, 124 },	/* 2484  14 */
85 	{ 1, 0x46, 136 },	/* 2512  15 */
86 	{ 1, 0x46, 140 },	/* 2532  16 */
87 	{ 1, 0x46, 144 },	/* 2552  17 */
88 	{ 1, 0x46, 148 },	/* 2572  18 */
89 	{ 1, 0x46, 152 },	/* 2592  19 */
90 	{ 1, 0x46, 156 },	/* 2612  20 */
91 	{ 1, 0x46, 160 },	/* 2632  21 */
92 	{ 1, 0x46, 164 },	/* 2652  22 */
93 	{ 1, 0x46, 168 },	/* 2672  23 */
94 	{ 1, 0x46, 172 },	/* 2692  24 */
95 	{ 1, 0x46, 176 },	/* 2712  25 */
96 	{ 1, 0x46, 180 } 	/* 2732  26 */
97 };
98 
99 /* Power timeouts in usec to wait for chip to wake-up. */
100 #define POWER_UP_TIME	2000
101 
102 #define	DELAY_PLL_SETTLE	300		/* 300 us */
103 #define	DELAY_BASE_ACTIVATE	100		/* 100 us */
104 
105 #define NUM_RATES	8
106 
107 static HAL_BOOL ar5211SetResetReg(struct ath_hal *ah, uint32_t resetMask);
108 static HAL_BOOL ar5211SetChannel(struct ath_hal *,
109 		const struct ieee80211_channel *);
110 static int16_t ar5211RunNoiseFloor(struct ath_hal *,
111 		uint8_t runTime, int16_t startingNF);
112 static HAL_BOOL ar5211IsNfGood(struct ath_hal *,
113 		struct ieee80211_channel *chan);
114 static HAL_BOOL ar5211SetRf6and7(struct ath_hal *,
115 		const struct ieee80211_channel *chan);
116 static HAL_BOOL ar5211SetBoardValues(struct ath_hal *,
117 		const struct ieee80211_channel *chan);
118 static void ar5211SetPowerTable(struct ath_hal *,
119 		PCDACS_EEPROM *pSrcStruct, uint16_t channel);
120 static HAL_BOOL ar5211SetTransmitPower(struct ath_hal *,
121 		const struct ieee80211_channel *);
122 static void ar5211SetRateTable(struct ath_hal *,
123 		RD_EDGES_POWER *pRdEdgesPower, TRGT_POWER_INFO *pPowerInfo,
124 		uint16_t numChannels, const struct ieee80211_channel *chan);
125 static uint16_t ar5211GetScaledPower(uint16_t channel, uint16_t pcdacValue,
126 		const PCDACS_EEPROM *pSrcStruct);
127 static HAL_BOOL ar5211FindValueInList(uint16_t channel, uint16_t pcdacValue,
128 		const PCDACS_EEPROM *pSrcStruct, uint16_t *powerValue);
129 static uint16_t ar5211GetInterpolatedValue(uint16_t target,
130 		uint16_t srcLeft, uint16_t srcRight,
131 		uint16_t targetLeft, uint16_t targetRight, HAL_BOOL scaleUp);
132 static void ar5211GetLowerUpperValues(uint16_t value,
133 		const uint16_t *pList, uint16_t listSize,
134 		uint16_t *pLowerValue, uint16_t *pUpperValue);
135 static void ar5211GetLowerUpperPcdacs(uint16_t pcdac,
136 		uint16_t channel, const PCDACS_EEPROM *pSrcStruct,
137 		uint16_t *pLowerPcdac, uint16_t *pUpperPcdac);
138 
139 static void ar5211SetRfgain(struct ath_hal *, const GAIN_VALUES *);
140 static void ar5211RequestRfgain(struct ath_hal *);
141 static HAL_BOOL ar5211InvalidGainReadback(struct ath_hal *, GAIN_VALUES *);
142 static HAL_BOOL ar5211IsGainAdjustNeeded(struct ath_hal *, const GAIN_VALUES *);
143 static int32_t ar5211AdjustGain(struct ath_hal *, GAIN_VALUES *);
144 static void ar5211SetOperatingMode(struct ath_hal *, int opmode);
145 
146 /*
147  * Places the device in and out of reset and then places sane
148  * values in the registers based on EEPROM config, initialization
149  * vectors (as determined by the mode), and station configuration
150  *
151  * bChannelChange is used to preserve DMA/PCU registers across
152  * a HW Reset during channel change.
153  */
154 HAL_BOOL
155 ar5211Reset(struct ath_hal *ah, HAL_OPMODE opmode,
156 	struct ieee80211_channel *chan, HAL_BOOL bChannelChange,
157 	HAL_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 descriptor accesses.
768 			 */
769 			mask = INIT_CONFIG_STATUS | AR_CFG_SWTD | AR_CFG_SWRD;
770 			OS_REG_WRITE(ah, AR_CFG, mask);
771 		} else
772 			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
773 	}
774 	return rt;
775 }
776 
777 /*
778  * Takes the MHz channel value and sets the Channel value
779  *
780  * ASSUMES: Writes enabled to analog bus before AGC is active
781  *   or by disabling the AGC.
782  */
783 static HAL_BOOL
784 ar5211SetChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
785 {
786 	uint32_t refClk, reg32, data2111;
787 	int16_t chan5111, chanIEEE;
788 
789 	chanIEEE = chan->ic_ieee;
790 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
791 		const CHAN_INFO_2GHZ* ci =
792 			&chan2GHzData[chanIEEE + CI_2GHZ_INDEX_CORRECTION];
793 
794 		data2111 = ((ath_hal_reverseBits(ci->channelSelect, 8) & 0xff)
795 				<< 5)
796 			 | (ci->refClkSel << 4);
797 		chan5111 = ci->channel5111;
798 	} else {
799 		data2111 = 0;
800 		chan5111 = chanIEEE;
801 	}
802 
803 	/* Rest of the code is common for 5 GHz and 2.4 GHz. */
804 	if (chan5111 >= 145 || (chan5111 & 0x1)) {
805 		reg32 = ath_hal_reverseBits(chan5111 - 24, 8) & 0xFF;
806 		refClk = 1;
807 	} else {
808 		reg32 = ath_hal_reverseBits(((chan5111 - 24) / 2), 8) & 0xFF;
809 		refClk = 0;
810 	}
811 
812 	reg32 = (reg32 << 2) | (refClk << 1) | (1 << 10) | 0x1;
813 	OS_REG_WRITE(ah, AR_PHY(0x27), ((data2111 & 0xff) << 8) | (reg32 & 0xff));
814 	reg32 >>= 8;
815 	OS_REG_WRITE(ah, AR_PHY(0x34), (data2111 & 0xff00) | (reg32 & 0xff));
816 
817 	AH_PRIVATE(ah)->ah_curchan = chan;
818 	return AH_TRUE;
819 }
820 
821 static int16_t
822 ar5211GetNoiseFloor(struct ath_hal *ah)
823 {
824 	int16_t nf;
825 
826 	nf = (OS_REG_READ(ah, AR_PHY(25)) >> 19) & 0x1ff;
827 	if (nf & 0x100)
828 		nf = 0 - ((nf ^ 0x1ff) + 1);
829 	return nf;
830 }
831 
832 /*
833  * Peform the noisefloor calibration for the length of time set
834  * in runTime (valid values 1 to 7)
835  *
836  * Returns: The NF value at the end of the given time (or 0 for failure)
837  */
838 int16_t
839 ar5211RunNoiseFloor(struct ath_hal *ah, uint8_t runTime, int16_t startingNF)
840 {
841 	int i, searchTime;
842 
843 	HALASSERT(runTime <= 7);
844 
845 	/* Setup  noise floor run time and starting value */
846 	OS_REG_WRITE(ah, AR_PHY(25),
847 		(OS_REG_READ(ah, AR_PHY(25)) & ~0xFFF) |
848 			 ((runTime << 9) & 0xE00) | (startingNF & 0x1FF));
849 	/* Calibrate the noise floor */
850 	OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
851 		OS_REG_READ(ah, AR_PHY_AGC_CONTROL) | AR_PHY_AGC_CONTROL_NF);
852 
853 	/* Compute the required amount of searchTime needed to finish NF */
854 	if (runTime == 0) {
855 		/* 8 search windows * 6.4us each */
856 		searchTime = 8  * 7;
857 	} else {
858 		/* 512 * runtime search windows * 6.4us each */
859 		searchTime = (runTime * 512)  * 7;
860 	}
861 
862 	/*
863 	 * Do not read noise floor until it has been updated
864 	 *
865 	 * As a guesstimate - we may only get 1/60th the time on
866 	 * the air to see search windows  in a heavily congested
867 	 * network (40 us every 2400 us of time)
868 	 */
869 	for (i = 0; i < 60; i++) {
870 		if ((OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) == 0)
871 			break;
872 		OS_DELAY(searchTime);
873 	}
874 	if (i >= 60) {
875 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
876 		    "NF with runTime %d failed to end on channel %d\n",
877 		    runTime, AH_PRIVATE(ah)->ah_curchan->ic_freq);
878 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
879 		    "  PHY NF Reg state:	 0x%x\n",
880 		    OS_REG_READ(ah, AR_PHY_AGC_CONTROL));
881 		HALDEBUG(ah, HAL_DEBUG_NFCAL,
882 		    "  PHY Active Reg state: 0x%x\n",
883 		    OS_REG_READ(ah, AR_PHY_ACTIVE));
884 		return 0;
885 	}
886 
887 	return ar5211GetNoiseFloor(ah);
888 }
889 
890 static HAL_BOOL
891 getNoiseFloorThresh(struct ath_hal *ah, const struct ieee80211_channel *chan,
892 	int16_t *nft)
893 {
894 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
895 
896 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
897 	case IEEE80211_CHAN_A:
898 		*nft = ee->ee_noiseFloorThresh[0];
899 		break;
900 	case IEEE80211_CHAN_B:
901 		*nft = ee->ee_noiseFloorThresh[1];
902 		break;
903 	case IEEE80211_CHAN_PUREG:
904 		*nft = ee->ee_noiseFloorThresh[2];
905 		break;
906 	default:
907 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
908 		    __func__, chan->ic_flags);
909 		return AH_FALSE;
910 	}
911 	return AH_TRUE;
912 }
913 
914 /*
915  * Read the NF and check it against the noise floor threshhold
916  *
917  * Returns: TRUE if the NF is good
918  */
919 static HAL_BOOL
920 ar5211IsNfGood(struct ath_hal *ah, struct ieee80211_channel *chan)
921 {
922 	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
923 	int16_t nf, nfThresh;
924 
925 	if (!getNoiseFloorThresh(ah, chan, &nfThresh))
926 		return AH_FALSE;
927 	if (OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) {
928 		HALDEBUG(ah, HAL_DEBUG_ANY,
929 		    "%s: NF did not complete in calibration window\n", __func__);
930 	}
931 	nf = ar5211GetNoiseFloor(ah);
932 	if (nf > nfThresh) {
933 		HALDEBUG(ah, HAL_DEBUG_ANY,
934 		    "%s: noise floor failed; detected %u, threshold %u\n",
935 		    __func__, nf, nfThresh);
936 		/*
937 		 * NB: Don't discriminate 2.4 vs 5Ghz, if this
938 		 *     happens it indicates a problem regardless
939 		 *     of the band.
940 		 */
941 		chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
942 	}
943 	ichan->rawNoiseFloor = nf;
944 	return (nf <= nfThresh);
945 }
946 
947 /*
948  * Peform the noisefloor calibration and check for any constant channel
949  * interference.
950  *
951  * NOTE: preAR5211 have a lengthy carrier wave detection process - hence
952  * it is if'ed for MKK regulatory domain only.
953  *
954  * Returns: TRUE for a successful noise floor calibration; else FALSE
955  */
956 HAL_BOOL
957 ar5211CalNoiseFloor(struct ath_hal *ah, const struct ieee80211_channel *chan)
958 {
959 #define	N(a)	(sizeof (a) / sizeof (a[0]))
960 	/* Check for Carrier Wave interference in MKK regulatory zone */
961 	if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU &&
962 	    (chan->ic_flags & CHANNEL_NFCREQUIRED)) {
963 		static const uint8_t runtime[3] = { 0, 2, 7 };
964 		HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
965 		int16_t nf, nfThresh;
966 		int i;
967 
968 		if (!getNoiseFloorThresh(ah, chan, &nfThresh))
969 			return AH_FALSE;
970 		/*
971 		 * Run a quick noise floor that will hopefully
972 		 * complete (decrease delay time).
973 		 */
974 		for (i = 0; i < N(runtime); i++) {
975 			nf = ar5211RunNoiseFloor(ah, runtime[i], 0);
976 			if (nf > nfThresh) {
977 				HALDEBUG(ah, HAL_DEBUG_ANY,
978 				    "%s: run failed with %u > threshold %u "
979 				    "(runtime %u)\n", __func__,
980 				    nf, nfThresh, runtime[i]);
981 				ichan->rawNoiseFloor = 0;
982 			} else
983 				ichan->rawNoiseFloor = nf;
984 		}
985 		return (i <= N(runtime));
986 	} else {
987 		/* Calibrate the noise floor */
988 		OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
989 			OS_REG_READ(ah, AR_PHY_AGC_CONTROL) |
990 				 AR_PHY_AGC_CONTROL_NF);
991 	}
992 	return AH_TRUE;
993 #undef N
994 }
995 
996 /*
997  * Adjust NF based on statistical values for 5GHz frequencies.
998  */
999 int16_t
1000 ar5211GetNfAdjust(struct ath_hal *ah, const HAL_CHANNEL_INTERNAL *c)
1001 {
1002 	static const struct {
1003 		uint16_t freqLow;
1004 		int16_t	  adjust;
1005 	} adjust5111[] = {
1006 		{ 5790,	11 },	/* NB: ordered high -> low */
1007 		{ 5730, 10 },
1008 		{ 5690,  9 },
1009 		{ 5660,  8 },
1010 		{ 5610,  7 },
1011 		{ 5530,  5 },
1012 		{ 5450,  4 },
1013 		{ 5379,  2 },
1014 		{ 5209,  0 },	/* XXX? bogus but doesn't matter */
1015 		{    0,  1 },
1016 	};
1017 	int i;
1018 
1019 	for (i = 0; c->channel <= adjust5111[i].freqLow; i++)
1020 		;
1021 	/* NB: placeholder for 5111's less severe requirement */
1022 	return adjust5111[i].adjust / 3;
1023 }
1024 
1025 /*
1026  * Reads EEPROM header info from device structure and programs
1027  * analog registers 6 and 7
1028  *
1029  * REQUIRES: Access to the analog device
1030  */
1031 static HAL_BOOL
1032 ar5211SetRf6and7(struct ath_hal *ah, const struct ieee80211_channel *chan)
1033 {
1034 #define	N(a)	(sizeof (a) / sizeof (a[0]))
1035 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1036 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1037 	struct ath_hal_5211 *ahp = AH5211(ah);
1038 	uint16_t rfXpdGain, rfPloSel, rfPwdXpd;
1039 	uint16_t tempOB, tempDB;
1040 	uint16_t freqIndex;
1041 	int i;
1042 
1043 	freqIndex = IEEE80211_IS_CHAN_2GHZ(chan) ? 2 : 1;
1044 
1045 	/*
1046 	 * TODO: This array mode correspondes with the index used
1047 	 *	 during the read.
1048 	 * For readability, this should be changed to an enum or #define
1049 	 */
1050 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1051 	case IEEE80211_CHAN_A:
1052 		if (freq > 4000 && freq < 5260) {
1053 			tempOB = ee->ee_ob1;
1054 			tempDB = ee->ee_db1;
1055 		} else if (freq >= 5260 && freq < 5500) {
1056 			tempOB = ee->ee_ob2;
1057 			tempDB = ee->ee_db2;
1058 		} else if (freq >= 5500 && freq < 5725) {
1059 			tempOB = ee->ee_ob3;
1060 			tempDB = ee->ee_db3;
1061 		} else if (freq >= 5725) {
1062 			tempOB = ee->ee_ob4;
1063 			tempDB = ee->ee_db4;
1064 		} else {
1065 			/* XXX panic?? */
1066 			tempOB = tempDB = 0;
1067 		}
1068 
1069 		rfXpdGain = ee->ee_xgain[0];
1070 		rfPloSel  = ee->ee_xpd[0];
1071 		rfPwdXpd  = !ee->ee_xpd[0];
1072 
1073 		ar5211Rf6n7[5][freqIndex]  =
1074 			(ar5211Rf6n7[5][freqIndex] & ~0x10000000) |
1075 				(ee->ee_cornerCal.pd84<< 28);
1076 		ar5211Rf6n7[6][freqIndex]  =
1077 			(ar5211Rf6n7[6][freqIndex] & ~0x04000000) |
1078 				(ee->ee_cornerCal.pd90 << 26);
1079 		ar5211Rf6n7[21][freqIndex] =
1080 			(ar5211Rf6n7[21][freqIndex] & ~0x08) |
1081 				(ee->ee_cornerCal.gSel << 3);
1082 		break;
1083 	case IEEE80211_CHAN_B:
1084 		tempOB = ee->ee_obFor24;
1085 		tempDB = ee->ee_dbFor24;
1086 		rfXpdGain = ee->ee_xgain[1];
1087 		rfPloSel  = ee->ee_xpd[1];
1088 		rfPwdXpd  = !ee->ee_xpd[1];
1089 		break;
1090 	case IEEE80211_CHAN_PUREG:
1091 		tempOB = ee->ee_obFor24g;
1092 		tempDB = ee->ee_dbFor24g;
1093 		rfXpdGain = ee->ee_xgain[2];
1094 		rfPloSel  = ee->ee_xpd[2];
1095 		rfPwdXpd  = !ee->ee_xpd[2];
1096 		break;
1097 	default:
1098 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1099 		    __func__, chan->ic_flags);
1100 		return AH_FALSE;
1101 	}
1102 
1103 	HALASSERT(1 <= tempOB && tempOB <= 5);
1104 	HALASSERT(1 <= tempDB && tempDB <= 5);
1105 
1106 	/* Set rfXpdGain and rfPwdXpd */
1107 	ar5211Rf6n7[11][freqIndex] =  (ar5211Rf6n7[11][freqIndex] & ~0xC0) |
1108 		(((ath_hal_reverseBits(rfXpdGain, 4) << 7) | (rfPwdXpd << 6)) & 0xC0);
1109 	ar5211Rf6n7[12][freqIndex] =  (ar5211Rf6n7[12][freqIndex] & ~0x07) |
1110 		((ath_hal_reverseBits(rfXpdGain, 4) >> 1) & 0x07);
1111 
1112 	/* Set OB */
1113 	ar5211Rf6n7[12][freqIndex] =  (ar5211Rf6n7[12][freqIndex] & ~0x80) |
1114 		((ath_hal_reverseBits(tempOB, 3) << 7) & 0x80);
1115 	ar5211Rf6n7[13][freqIndex] =  (ar5211Rf6n7[13][freqIndex] & ~0x03) |
1116 		((ath_hal_reverseBits(tempOB, 3) >> 1) & 0x03);
1117 
1118 	/* Set DB */
1119 	ar5211Rf6n7[13][freqIndex] =  (ar5211Rf6n7[13][freqIndex] & ~0x1C) |
1120 		((ath_hal_reverseBits(tempDB, 3) << 2) & 0x1C);
1121 
1122 	/* Set rfPloSel */
1123 	ar5211Rf6n7[17][freqIndex] =  (ar5211Rf6n7[17][freqIndex] & ~0x08) |
1124 		((rfPloSel << 3) & 0x08);
1125 
1126 	/* Write the Rf registers 6 & 7 */
1127 	for (i = 0; i < N(ar5211Rf6n7); i++)
1128 		OS_REG_WRITE(ah, ar5211Rf6n7[i][0], ar5211Rf6n7[i][freqIndex]);
1129 
1130 	/* Now that we have reprogrammed rfgain value, clear the flag. */
1131 	ahp->ah_rfgainState = RFGAIN_INACTIVE;
1132 
1133 	return AH_TRUE;
1134 #undef N
1135 }
1136 
1137 HAL_BOOL
1138 ar5211SetAntennaSwitchInternal(struct ath_hal *ah, HAL_ANT_SETTING settings,
1139 	const struct ieee80211_channel *chan)
1140 {
1141 #define	ANT_SWITCH_TABLE1	0x9960
1142 #define	ANT_SWITCH_TABLE2	0x9964
1143 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1144 	struct ath_hal_5211 *ahp = AH5211(ah);
1145 	uint32_t antSwitchA, antSwitchB;
1146 	int ix;
1147 
1148 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1149 	case IEEE80211_CHAN_A:		ix = 0; break;
1150 	case IEEE80211_CHAN_B:		ix = 1; break;
1151 	case IEEE80211_CHAN_PUREG:	ix = 2; break;
1152 	default:
1153 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1154 		    __func__, chan->ic_flags);
1155 		return AH_FALSE;
1156 	}
1157 
1158 	antSwitchA =  ee->ee_antennaControl[1][ix]
1159 		   | (ee->ee_antennaControl[2][ix] << 6)
1160 		   | (ee->ee_antennaControl[3][ix] << 12)
1161 		   | (ee->ee_antennaControl[4][ix] << 18)
1162 		   | (ee->ee_antennaControl[5][ix] << 24)
1163 		   ;
1164 	antSwitchB =  ee->ee_antennaControl[6][ix]
1165 		   | (ee->ee_antennaControl[7][ix] << 6)
1166 		   | (ee->ee_antennaControl[8][ix] << 12)
1167 		   | (ee->ee_antennaControl[9][ix] << 18)
1168 		   | (ee->ee_antennaControl[10][ix] << 24)
1169 		   ;
1170 	/*
1171 	 * For fixed antenna, give the same setting for both switch banks
1172 	 */
1173 	switch (settings) {
1174 	case HAL_ANT_FIXED_A:
1175 		antSwitchB = antSwitchA;
1176 		break;
1177 	case HAL_ANT_FIXED_B:
1178 		antSwitchA = antSwitchB;
1179 		break;
1180 	case HAL_ANT_VARIABLE:
1181 		break;
1182 	default:
1183 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: bad antenna setting %u\n",
1184 		    __func__, settings);
1185 		return AH_FALSE;
1186 	}
1187 	ahp->ah_diversityControl = settings;
1188 
1189 	OS_REG_WRITE(ah, ANT_SWITCH_TABLE1, antSwitchA);
1190 	OS_REG_WRITE(ah, ANT_SWITCH_TABLE2, antSwitchB);
1191 
1192 	return AH_TRUE;
1193 #undef ANT_SWITCH_TABLE1
1194 #undef ANT_SWITCH_TABLE2
1195 }
1196 
1197 /*
1198  * Reads EEPROM header info and programs the device for correct operation
1199  * given the channel value
1200  */
1201 static HAL_BOOL
1202 ar5211SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1203 {
1204 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1205 	struct ath_hal_5211 *ahp = AH5211(ah);
1206 	int arrayMode, falseDectectBackoff;
1207 
1208 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1209 	case IEEE80211_CHAN_A:
1210 		arrayMode = 0;
1211 		OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
1212 			AR_PHY_FRAME_CTL_TX_CLIP, ee->ee_cornerCal.clip);
1213 		break;
1214 	case IEEE80211_CHAN_B:
1215 		arrayMode = 1;
1216 		break;
1217 	case IEEE80211_CHAN_PUREG:
1218 		arrayMode = 2;
1219 		break;
1220 	default:
1221 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1222 		    __func__, chan->ic_flags);
1223 		return AH_FALSE;
1224 	}
1225 
1226 	/* Set the antenna register(s) correctly for the chip revision */
1227 	if (AH_PRIVATE(ah)->ah_macVersion < AR_SREV_VERSION_OAHU) {
1228 		OS_REG_WRITE(ah, AR_PHY(68),
1229 			(OS_REG_READ(ah, AR_PHY(68)) & 0xFFFFFFFC) | 0x3);
1230 	} else {
1231 		OS_REG_WRITE(ah, AR_PHY(68),
1232 			(OS_REG_READ(ah, AR_PHY(68)) & 0xFFFFFC06) |
1233 			(ee->ee_antennaControl[0][arrayMode] << 4) | 0x1);
1234 
1235 		ar5211SetAntennaSwitchInternal(ah,
1236 			ahp->ah_diversityControl, chan);
1237 
1238 		/* Set the Noise Floor Thresh on ar5211 devices */
1239 		OS_REG_WRITE(ah, AR_PHY_BASE + (90 << 2),
1240 			(ee->ee_noiseFloorThresh[arrayMode] & 0x1FF) | (1<<9));
1241 	}
1242 	OS_REG_WRITE(ah, AR_PHY_BASE + (17 << 2),
1243 		(OS_REG_READ(ah, AR_PHY_BASE + (17 << 2)) & 0xFFFFC07F) |
1244 		((ee->ee_switchSettling[arrayMode] << 7) & 0x3F80));
1245 	OS_REG_WRITE(ah, AR_PHY_BASE + (18 << 2),
1246 		(OS_REG_READ(ah, AR_PHY_BASE + (18 << 2)) & 0xFFFC0FFF) |
1247 		((ee->ee_txrxAtten[arrayMode] << 12) & 0x3F000));
1248 	OS_REG_WRITE(ah, AR_PHY_BASE + (20 << 2),
1249 		(OS_REG_READ(ah, AR_PHY_BASE + (20 << 2)) & 0xFFFF0000) |
1250 		((ee->ee_pgaDesiredSize[arrayMode] << 8) & 0xFF00) |
1251 		(ee->ee_adcDesiredSize[arrayMode] & 0x00FF));
1252 	OS_REG_WRITE(ah, AR_PHY_BASE + (13 << 2),
1253 		(ee->ee_txEndToXPAOff[arrayMode] << 24) |
1254 		(ee->ee_txEndToXPAOff[arrayMode] << 16) |
1255 		(ee->ee_txFrameToXPAOn[arrayMode] << 8) |
1256 		ee->ee_txFrameToXPAOn[arrayMode]);
1257 	OS_REG_WRITE(ah, AR_PHY_BASE + (10 << 2),
1258 		(OS_REG_READ(ah, AR_PHY_BASE + (10 << 2)) & 0xFFFF00FF) |
1259 		(ee->ee_txEndToXLNAOn[arrayMode] << 8));
1260 	OS_REG_WRITE(ah, AR_PHY_BASE + (25 << 2),
1261 		(OS_REG_READ(ah, AR_PHY_BASE + (25 << 2)) & 0xFFF80FFF) |
1262 		((ee->ee_thresh62[arrayMode] << 12) & 0x7F000));
1263 
1264 #define NO_FALSE_DETECT_BACKOFF   2
1265 #define CB22_FALSE_DETECT_BACKOFF 6
1266 	/*
1267 	 * False detect backoff - suspected 32 MHz spur causes
1268 	 * false detects in OFDM, causing Tx Hangs.  Decrease
1269 	 * weak signal sensitivity for this card.
1270 	 */
1271 	falseDectectBackoff = NO_FALSE_DETECT_BACKOFF;
1272 	if (AH_PRIVATE(ah)->ah_eeversion < AR_EEPROM_VER3_3) {
1273 		if (AH_PRIVATE(ah)->ah_subvendorid == 0x1022 &&
1274 		    IEEE80211_IS_CHAN_OFDM(chan))
1275 			falseDectectBackoff += CB22_FALSE_DETECT_BACKOFF;
1276 	} else {
1277 		uint16_t freq = ath_hal_gethwchannel(ah, chan);
1278 		uint32_t remainder = freq % 32;
1279 
1280 		if (remainder && (remainder < 10 || remainder > 22))
1281 			falseDectectBackoff += ee->ee_falseDetectBackoff[arrayMode];
1282 	}
1283 	OS_REG_WRITE(ah, 0x9924,
1284 		(OS_REG_READ(ah, 0x9924) & 0xFFFFFF01)
1285 		| ((falseDectectBackoff << 1) & 0xF7));
1286 
1287 	return AH_TRUE;
1288 #undef NO_FALSE_DETECT_BACKOFF
1289 #undef CB22_FALSE_DETECT_BACKOFF
1290 }
1291 
1292 /*
1293  * Set the limit on the overall output power.  Used for dynamic
1294  * transmit power control and the like.
1295  *
1296  * NOTE: The power is passed in is in units of 0.5 dBm.
1297  */
1298 HAL_BOOL
1299 ar5211SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
1300 {
1301 
1302 	AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
1303 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE_MAX, limit);
1304 	return AH_TRUE;
1305 }
1306 
1307 /*
1308  * Sets the transmit power in the baseband for the given
1309  * operating channel and mode.
1310  */
1311 static HAL_BOOL
1312 ar5211SetTransmitPower(struct ath_hal *ah, const struct ieee80211_channel *chan)
1313 {
1314 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1315 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1316 	TRGT_POWER_INFO *pi;
1317 	RD_EDGES_POWER *rep;
1318 	PCDACS_EEPROM eepromPcdacs;
1319 	u_int nchan, cfgCtl;
1320 	int i;
1321 
1322 	/* setup the pcdac struct to point to the correct info, based on mode */
1323 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1324 	case IEEE80211_CHAN_A:
1325 		eepromPcdacs.numChannels = ee->ee_numChannels11a;
1326 		eepromPcdacs.pChannelList= ee->ee_channels11a;
1327 		eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11a;
1328 		nchan = ee->ee_numTargetPwr_11a;
1329 		pi = ee->ee_trgtPwr_11a;
1330 		break;
1331 	case IEEE80211_CHAN_PUREG:
1332 		eepromPcdacs.numChannels = ee->ee_numChannels2_4;
1333 		eepromPcdacs.pChannelList= ee->ee_channels11g;
1334 		eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11g;
1335 		nchan = ee->ee_numTargetPwr_11g;
1336 		pi = ee->ee_trgtPwr_11g;
1337 		break;
1338 	case IEEE80211_CHAN_B:
1339 		eepromPcdacs.numChannels = ee->ee_numChannels2_4;
1340 		eepromPcdacs.pChannelList= ee->ee_channels11b;
1341 		eepromPcdacs.pDataPerChannel = ee->ee_dataPerChannel11b;
1342 		nchan = ee->ee_numTargetPwr_11b;
1343 		pi = ee->ee_trgtPwr_11b;
1344 		break;
1345 	default:
1346 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1347 		    __func__, chan->ic_flags);
1348 		return AH_FALSE;
1349 	}
1350 
1351 	ar5211SetPowerTable(ah, &eepromPcdacs, freq);
1352 
1353 	rep = AH_NULL;
1354 	/* Match CTL to EEPROM value */
1355 	cfgCtl = ath_hal_getctl(ah, chan);
1356 	for (i = 0; i < ee->ee_numCtls; i++)
1357 		if (ee->ee_ctl[i] != 0 && ee->ee_ctl[i] == cfgCtl) {
1358 			rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
1359 			break;
1360 		}
1361 	ar5211SetRateTable(ah, rep, pi, nchan, chan);
1362 
1363 	return AH_TRUE;
1364 }
1365 
1366 /*
1367  * Read the transmit power levels from the structures taken
1368  * from EEPROM. Interpolate read transmit power values for
1369  * this channel. Organize the transmit power values into a
1370  * table for writing into the hardware.
1371  */
1372 void
1373 ar5211SetPowerTable(struct ath_hal *ah, PCDACS_EEPROM *pSrcStruct,
1374 	uint16_t channel)
1375 {
1376 	static FULL_PCDAC_STRUCT pcdacStruct;
1377 	static uint16_t pcdacTable[PWR_TABLE_SIZE];
1378 
1379 	uint16_t	 i, j;
1380 	uint16_t	 *pPcdacValues;
1381 	int16_t	  *pScaledUpDbm;
1382 	int16_t	  minScaledPwr;
1383 	int16_t	  maxScaledPwr;
1384 	int16_t	  pwr;
1385 	uint16_t	 pcdacMin = 0;
1386 	uint16_t	 pcdacMax = 63;
1387 	uint16_t	 pcdacTableIndex;
1388 	uint16_t	 scaledPcdac;
1389 	uint32_t	 addr;
1390 	uint32_t	 temp32;
1391 
1392 	OS_MEMZERO(&pcdacStruct, sizeof(FULL_PCDAC_STRUCT));
1393 	OS_MEMZERO(pcdacTable, sizeof(uint16_t) * PWR_TABLE_SIZE);
1394 	pPcdacValues = pcdacStruct.PcdacValues;
1395 	pScaledUpDbm = pcdacStruct.PwrValues;
1396 
1397 	/* Initialize the pcdacs to dBM structs pcdacs to be 1 to 63 */
1398 	for (i = PCDAC_START, j = 0; i <= PCDAC_STOP; i+= PCDAC_STEP, j++)
1399 		pPcdacValues[j] = i;
1400 
1401 	pcdacStruct.numPcdacValues = j;
1402 	pcdacStruct.pcdacMin = PCDAC_START;
1403 	pcdacStruct.pcdacMax = PCDAC_STOP;
1404 
1405 	/* Fill out the power values for this channel */
1406 	for (j = 0; j < pcdacStruct.numPcdacValues; j++ )
1407 		pScaledUpDbm[j] = ar5211GetScaledPower(channel, pPcdacValues[j], pSrcStruct);
1408 
1409 	/* Now scale the pcdac values to fit in the 64 entry power table */
1410 	minScaledPwr = pScaledUpDbm[0];
1411 	maxScaledPwr = pScaledUpDbm[pcdacStruct.numPcdacValues - 1];
1412 
1413 	/* find minimum and make monotonic */
1414 	for (j = 0; j < pcdacStruct.numPcdacValues; j++) {
1415 		if (minScaledPwr >= pScaledUpDbm[j]) {
1416 			minScaledPwr = pScaledUpDbm[j];
1417 			pcdacMin = j;
1418 		}
1419 		/*
1420 		 * Make the full_hsh monotonically increasing otherwise
1421 		 * interpolation algorithm will get fooled gotta start
1422 		 * working from the top, hence i = 63 - j.
1423 		 */
1424 		i = (uint16_t)(pcdacStruct.numPcdacValues - 1 - j);
1425 		if (i == 0)
1426 			break;
1427 		if (pScaledUpDbm[i-1] > pScaledUpDbm[i]) {
1428 			/*
1429 			 * It could be a glitch, so make the power for
1430 			 * this pcdac the same as the power from the
1431 			 * next highest pcdac.
1432 			 */
1433 			pScaledUpDbm[i - 1] = pScaledUpDbm[i];
1434 		}
1435 	}
1436 
1437 	for (j = 0; j < pcdacStruct.numPcdacValues; j++)
1438 		if (maxScaledPwr < pScaledUpDbm[j]) {
1439 			maxScaledPwr = pScaledUpDbm[j];
1440 			pcdacMax = j;
1441 		}
1442 
1443 	/* Find the first power level with a pcdac */
1444 	pwr = (uint16_t)(PWR_STEP * ((minScaledPwr - PWR_MIN + PWR_STEP / 2) / PWR_STEP)  + PWR_MIN);
1445 
1446 	/* Write all the first pcdac entries based off the pcdacMin */
1447 	pcdacTableIndex = 0;
1448 	for (i = 0; i < (2 * (pwr - PWR_MIN) / EEP_SCALE + 1); i++)
1449 		pcdacTable[pcdacTableIndex++] = pcdacMin;
1450 
1451 	i = 0;
1452 	while (pwr < pScaledUpDbm[pcdacStruct.numPcdacValues - 1]) {
1453 		pwr += PWR_STEP;
1454 		/* stop if dbM > max_power_possible */
1455 		while (pwr < pScaledUpDbm[pcdacStruct.numPcdacValues - 1] &&
1456 		       (pwr - pScaledUpDbm[i])*(pwr - pScaledUpDbm[i+1]) > 0)
1457 			i++;
1458 		/* scale by 2 and add 1 to enable round up or down as needed */
1459 		scaledPcdac = (uint16_t)(ar5211GetInterpolatedValue(pwr,
1460 				pScaledUpDbm[i], pScaledUpDbm[i+1],
1461 				(uint16_t)(pPcdacValues[i] * 2),
1462 				(uint16_t)(pPcdacValues[i+1] * 2), 0) + 1);
1463 
1464 		pcdacTable[pcdacTableIndex] = scaledPcdac / 2;
1465 		if (pcdacTable[pcdacTableIndex] > pcdacMax)
1466 			pcdacTable[pcdacTableIndex] = pcdacMax;
1467 		pcdacTableIndex++;
1468 	}
1469 
1470 	/* Write all the last pcdac entries based off the last valid pcdac */
1471 	while (pcdacTableIndex < PWR_TABLE_SIZE) {
1472 		pcdacTable[pcdacTableIndex] = pcdacTable[pcdacTableIndex - 1];
1473 		pcdacTableIndex++;
1474 	}
1475 
1476 	/* Finally, write the power values into the baseband power table */
1477 	addr = AR_PHY_BASE + (608 << 2);
1478 	for (i = 0; i < 32; i++) {
1479 		temp32 = 0xffff & ((pcdacTable[2 * i + 1] << 8) | 0xff);
1480 		temp32 = (temp32 << 16) | (0xffff & ((pcdacTable[2 * i] << 8) | 0xff));
1481 		OS_REG_WRITE(ah, addr, temp32);
1482 		addr += 4;
1483 	}
1484 
1485 }
1486 
1487 /*
1488  * Set the transmit power in the baseband for the given
1489  * operating channel and mode.
1490  */
1491 static void
1492 ar5211SetRateTable(struct ath_hal *ah, RD_EDGES_POWER *pRdEdgesPower,
1493 	TRGT_POWER_INFO *pPowerInfo, uint16_t numChannels,
1494 	const struct ieee80211_channel *chan)
1495 {
1496 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1497 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1498 	struct ath_hal_5211 *ahp = AH5211(ah);
1499 	static uint16_t ratesArray[NUM_RATES];
1500 	static const uint16_t tpcScaleReductionTable[5] =
1501 		{ 0, 3, 6, 9, MAX_RATE_POWER };
1502 
1503 	uint16_t	*pRatesPower;
1504 	uint16_t	lowerChannel, lowerIndex=0, lowerPower=0;
1505 	uint16_t	upperChannel, upperIndex=0, upperPower=0;
1506 	uint16_t	twiceMaxEdgePower=63;
1507 	uint16_t	twicePower = 0;
1508 	uint16_t	i, numEdges;
1509 	uint16_t	tempChannelList[NUM_EDGES]; /* temp array for holding edge channels */
1510 	uint16_t	twiceMaxRDPower;
1511 	int16_t	 scaledPower = 0;		/* for gcc -O2 */
1512 	uint16_t	mask = 0x3f;
1513 	HAL_BOOL	  paPreDEnable = 0;
1514 	int8_t	  twiceAntennaGain, twiceAntennaReduction = 0;
1515 
1516 	pRatesPower = ratesArray;
1517 	twiceMaxRDPower = chan->ic_maxregpower * 2;
1518 
1519 	if (IEEE80211_IS_CHAN_5GHZ(chan)) {
1520 		twiceAntennaGain = ee->ee_antennaGainMax[0];
1521 	} else {
1522 		twiceAntennaGain = ee->ee_antennaGainMax[1];
1523 	}
1524 
1525 	twiceAntennaReduction = ath_hal_getantennareduction(ah, chan, twiceAntennaGain);
1526 
1527 	if (pRdEdgesPower) {
1528 		/* Get the edge power */
1529 		for (i = 0; i < NUM_EDGES; i++) {
1530 			if (pRdEdgesPower[i].rdEdge == 0)
1531 				break;
1532 			tempChannelList[i] = pRdEdgesPower[i].rdEdge;
1533 		}
1534 		numEdges = i;
1535 
1536 		ar5211GetLowerUpperValues(freq, tempChannelList,
1537 			numEdges, &lowerChannel, &upperChannel);
1538 		/* Get the index for this channel */
1539 		for (i = 0; i < numEdges; i++)
1540 			if (lowerChannel == tempChannelList[i])
1541 				break;
1542 		HALASSERT(i != numEdges);
1543 
1544 		if ((lowerChannel == upperChannel &&
1545 		     lowerChannel == freq) ||
1546 		    pRdEdgesPower[i].flag) {
1547 			twiceMaxEdgePower = pRdEdgesPower[i].twice_rdEdgePower;
1548 			HALASSERT(twiceMaxEdgePower > 0);
1549 		}
1550 	}
1551 
1552 	/* extrapolate the power values for the test Groups */
1553 	for (i = 0; i < numChannels; i++)
1554 		tempChannelList[i] = pPowerInfo[i].testChannel;
1555 
1556 	ar5211GetLowerUpperValues(freq, tempChannelList,
1557 		numChannels, &lowerChannel, &upperChannel);
1558 
1559 	/* get the index for the channel */
1560 	for (i = 0; i < numChannels; i++) {
1561 		if (lowerChannel == tempChannelList[i])
1562 			lowerIndex = i;
1563 		if (upperChannel == tempChannelList[i]) {
1564 			upperIndex = i;
1565 			break;
1566 		}
1567 	}
1568 
1569 	for (i = 0; i < NUM_RATES; i++) {
1570 		if (IEEE80211_IS_CHAN_OFDM(chan)) {
1571 			/* power for rates 6,9,12,18,24 is all the same */
1572 			if (i < 5) {
1573 				lowerPower = pPowerInfo[lowerIndex].twicePwr6_24;
1574 				upperPower = pPowerInfo[upperIndex].twicePwr6_24;
1575 			} else if (i == 5) {
1576 				lowerPower = pPowerInfo[lowerIndex].twicePwr36;
1577 				upperPower = pPowerInfo[upperIndex].twicePwr36;
1578 			} else if (i == 6) {
1579 				lowerPower = pPowerInfo[lowerIndex].twicePwr48;
1580 				upperPower = pPowerInfo[upperIndex].twicePwr48;
1581 			} else if (i == 7) {
1582 				lowerPower = pPowerInfo[lowerIndex].twicePwr54;
1583 				upperPower = pPowerInfo[upperIndex].twicePwr54;
1584 			}
1585 		} else {
1586 			switch (i) {
1587 			case 0:
1588 			case 1:
1589 				lowerPower = pPowerInfo[lowerIndex].twicePwr6_24;
1590 				upperPower = pPowerInfo[upperIndex].twicePwr6_24;
1591 				break;
1592 			case 2:
1593 			case 3:
1594 				lowerPower = pPowerInfo[lowerIndex].twicePwr36;
1595 				upperPower = pPowerInfo[upperIndex].twicePwr36;
1596 				break;
1597 			case 4:
1598 			case 5:
1599 				lowerPower = pPowerInfo[lowerIndex].twicePwr48;
1600 				upperPower = pPowerInfo[upperIndex].twicePwr48;
1601 				break;
1602 			case 6:
1603 			case 7:
1604 				lowerPower = pPowerInfo[lowerIndex].twicePwr54;
1605 				upperPower = pPowerInfo[upperIndex].twicePwr54;
1606 				break;
1607 			}
1608 		}
1609 
1610 		twicePower = ar5211GetInterpolatedValue(freq,
1611 			lowerChannel, upperChannel, lowerPower, upperPower, 0);
1612 
1613 		/* Reduce power by band edge restrictions */
1614 		twicePower = AH_MIN(twicePower, twiceMaxEdgePower);
1615 
1616 		/*
1617 		 * If turbo is set, reduce power to keep power
1618 		 * consumption under 2 Watts.  Note that we always do
1619 		 * this unless specially configured.  Then we limit
1620 		 * power only for non-AP operation.
1621 		 */
1622 		if (IEEE80211_IS_CHAN_TURBO(chan) &&
1623 		    AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1
1624 #ifdef AH_ENABLE_AP_SUPPORT
1625 		    && AH_PRIVATE(ah)->ah_opmode != HAL_M_HOSTAP
1626 #endif
1627 		) {
1628 			twicePower = AH_MIN(twicePower, ee->ee_turbo2WMaxPower5);
1629 		}
1630 
1631 		/* Reduce power by max regulatory domain allowed restrictions */
1632 		pRatesPower[i] = AH_MIN(twicePower, twiceMaxRDPower - twiceAntennaReduction);
1633 
1634 		/* Use 6 Mb power level for transmit power scaling reduction */
1635 		/* We don't want to reduce higher rates if its not needed */
1636 		if (i == 0) {
1637 			scaledPower = pRatesPower[0] -
1638 				(tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale] * 2);
1639 			if (scaledPower < 1)
1640 				scaledPower = 1;
1641 		}
1642 
1643 		pRatesPower[i] = AH_MIN(pRatesPower[i], scaledPower);
1644 	}
1645 
1646 	/* Record txPower at Rate 6 for info gathering */
1647 	ahp->ah_tx6PowerInHalfDbm = pRatesPower[0];
1648 
1649 #ifdef AH_DEBUG
1650 	HALDEBUG(ah, HAL_DEBUG_RESET,
1651 	    "%s: final output power setting %d MHz:\n",
1652 	    __func__, chan->ic_freq);
1653 	HALDEBUG(ah, HAL_DEBUG_RESET,
1654 	    "6 Mb %d dBm, MaxRD: %d dBm, MaxEdge %d dBm\n",
1655 	    scaledPower / 2, twiceMaxRDPower / 2, twiceMaxEdgePower / 2);
1656 	HALDEBUG(ah, HAL_DEBUG_RESET, "TPC Scale %d dBm - Ant Red %d dBm\n",
1657 	    tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale] * 2,
1658 	    twiceAntennaReduction / 2);
1659 	if (IEEE80211_IS_CHAN_TURBO(chan) &&
1660 	    AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3_1)
1661 		HALDEBUG(ah, HAL_DEBUG_RESET, "Max Turbo %d dBm\n",
1662 		    ee->ee_turbo2WMaxPower5);
1663 	HALDEBUG(ah, HAL_DEBUG_RESET,
1664 	    "  %2d | %2d | %2d | %2d | %2d | %2d | %2d | %2d dBm\n",
1665 	    pRatesPower[0] / 2, pRatesPower[1] / 2, pRatesPower[2] / 2,
1666 	    pRatesPower[3] / 2, pRatesPower[4] / 2, pRatesPower[5] / 2,
1667 	    pRatesPower[6] / 2, pRatesPower[7] / 2);
1668 #endif /* AH_DEBUG */
1669 
1670 	/* Write the power table into the hardware */
1671 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
1672 		 ((paPreDEnable & 1)<< 30) | ((pRatesPower[3] & mask) << 24) |
1673 		 ((paPreDEnable & 1)<< 22) | ((pRatesPower[2] & mask) << 16) |
1674 		 ((paPreDEnable & 1)<< 14) | ((pRatesPower[1] & mask) << 8) |
1675 		 ((paPreDEnable & 1)<< 6 ) |  (pRatesPower[0] & mask));
1676 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
1677 		 ((paPreDEnable & 1)<< 30) | ((pRatesPower[7] & mask) << 24) |
1678 		 ((paPreDEnable & 1)<< 22) | ((pRatesPower[6] & mask) << 16) |
1679 		 ((paPreDEnable & 1)<< 14) | ((pRatesPower[5] & mask) << 8) |
1680 		 ((paPreDEnable & 1)<< 6 ) |  (pRatesPower[4] & mask));
1681 
1682 	/* set max power to the power value at rate 6 */
1683 	ar5211SetTxPowerLimit(ah, pRatesPower[0]);
1684 
1685 	AH_PRIVATE(ah)->ah_maxPowerLevel = pRatesPower[0];
1686 }
1687 
1688 /*
1689  * Get or interpolate the pcdac value from the calibrated data
1690  */
1691 uint16_t
1692 ar5211GetScaledPower(uint16_t channel, uint16_t pcdacValue,
1693 	const PCDACS_EEPROM *pSrcStruct)
1694 {
1695 	uint16_t powerValue;
1696 	uint16_t lFreq, rFreq;		/* left and right frequency values */
1697 	uint16_t llPcdac, ulPcdac;	/* lower and upper left pcdac values */
1698 	uint16_t lrPcdac, urPcdac;	/* lower and upper right pcdac values */
1699 	uint16_t lPwr, uPwr;		/* lower and upper temp pwr values */
1700 	uint16_t lScaledPwr, rScaledPwr; /* left and right scaled power */
1701 
1702 	if (ar5211FindValueInList(channel, pcdacValue, pSrcStruct, &powerValue))
1703 		/* value was copied from srcStruct */
1704 		return powerValue;
1705 
1706 	ar5211GetLowerUpperValues(channel, pSrcStruct->pChannelList,
1707 		pSrcStruct->numChannels, &lFreq, &rFreq);
1708 	ar5211GetLowerUpperPcdacs(pcdacValue, lFreq, pSrcStruct,
1709 		&llPcdac, &ulPcdac);
1710 	ar5211GetLowerUpperPcdacs(pcdacValue, rFreq, pSrcStruct,
1711 		&lrPcdac, &urPcdac);
1712 
1713 	/* get the power index for the pcdac value */
1714 	ar5211FindValueInList(lFreq, llPcdac, pSrcStruct, &lPwr);
1715 	ar5211FindValueInList(lFreq, ulPcdac, pSrcStruct, &uPwr);
1716 	lScaledPwr = ar5211GetInterpolatedValue(pcdacValue,
1717 				llPcdac, ulPcdac, lPwr, uPwr, 0);
1718 
1719 	ar5211FindValueInList(rFreq, lrPcdac, pSrcStruct, &lPwr);
1720 	ar5211FindValueInList(rFreq, urPcdac, pSrcStruct, &uPwr);
1721 	rScaledPwr = ar5211GetInterpolatedValue(pcdacValue,
1722 				lrPcdac, urPcdac, lPwr, uPwr, 0);
1723 
1724 	return ar5211GetInterpolatedValue(channel, lFreq, rFreq,
1725 		lScaledPwr, rScaledPwr, 0);
1726 }
1727 
1728 /*
1729  * Find the value from the calibrated source data struct
1730  */
1731 HAL_BOOL
1732 ar5211FindValueInList(uint16_t channel, uint16_t pcdacValue,
1733 	const PCDACS_EEPROM *pSrcStruct, uint16_t *powerValue)
1734 {
1735 	const DATA_PER_CHANNEL *pChannelData;
1736 	const uint16_t *pPcdac;
1737 	uint16_t i, j;
1738 
1739 	pChannelData = pSrcStruct->pDataPerChannel;
1740 	for (i = 0; i < pSrcStruct->numChannels; i++ ) {
1741 		if (pChannelData->channelValue == channel) {
1742 			pPcdac = pChannelData->PcdacValues;
1743 			for (j = 0; j < pChannelData->numPcdacValues; j++ ) {
1744 				if (*pPcdac == pcdacValue) {
1745 					*powerValue = pChannelData->PwrValues[j];
1746 					return AH_TRUE;
1747 				}
1748 				pPcdac++;
1749 			}
1750 		}
1751 		pChannelData++;
1752 	}
1753 	return AH_FALSE;
1754 }
1755 
1756 /*
1757  * Returns interpolated or the scaled up interpolated value
1758  */
1759 uint16_t
1760 ar5211GetInterpolatedValue(uint16_t target,
1761 	uint16_t srcLeft, uint16_t srcRight,
1762 	uint16_t targetLeft, uint16_t targetRight,
1763 	HAL_BOOL scaleUp)
1764 {
1765 	uint16_t rv;
1766 	int16_t lRatio;
1767 	uint16_t scaleValue = EEP_SCALE;
1768 
1769 	/* to get an accurate ratio, always scale, if want to scale, then don't scale back down */
1770 	if ((targetLeft * targetRight) == 0)
1771 		return 0;
1772 	if (scaleUp)
1773 		scaleValue = 1;
1774 
1775 	if (srcRight != srcLeft) {
1776 		/*
1777 		 * Note the ratio always need to be scaled,
1778 		 * since it will be a fraction.
1779 		 */
1780 		lRatio = (target - srcLeft) * EEP_SCALE / (srcRight - srcLeft);
1781 		if (lRatio < 0) {
1782 		    /* Return as Left target if value would be negative */
1783 		    rv = targetLeft * (scaleUp ? EEP_SCALE : 1);
1784 		} else if (lRatio > EEP_SCALE) {
1785 		    /* Return as Right target if Ratio is greater than 100% (SCALE) */
1786 		    rv = targetRight * (scaleUp ? EEP_SCALE : 1);
1787 		} else {
1788 			rv = (lRatio * targetRight + (EEP_SCALE - lRatio) *
1789 					targetLeft) / scaleValue;
1790 		}
1791 	} else {
1792 		rv = targetLeft;
1793 		if (scaleUp)
1794 			rv *= EEP_SCALE;
1795 	}
1796 	return rv;
1797 }
1798 
1799 /*
1800  *  Look for value being within 0.1 of the search values
1801  *  however, NDIS can't do float calculations, so multiply everything
1802  *  up by EEP_SCALE so can do integer arithmatic
1803  *
1804  * INPUT  value	   -value to search for
1805  * INPUT  pList	   -ptr to the list to search
1806  * INPUT  listSize	-number of entries in list
1807  * OUTPUT pLowerValue -return the lower value
1808  * OUTPUT pUpperValue -return the upper value
1809  */
1810 void
1811 ar5211GetLowerUpperValues(uint16_t value,
1812 	const uint16_t *pList, uint16_t listSize,
1813 	uint16_t *pLowerValue, uint16_t *pUpperValue)
1814 {
1815 	const uint16_t listEndValue = *(pList + listSize - 1);
1816 	uint32_t target = value * EEP_SCALE;
1817 	int i;
1818 
1819 	/*
1820 	 * See if value is lower than the first value in the list
1821 	 * if so return first value
1822 	 */
1823 	if (target < (uint32_t)(*pList * EEP_SCALE - EEP_DELTA)) {
1824 		*pLowerValue = *pList;
1825 		*pUpperValue = *pList;
1826 		return;
1827 	}
1828 
1829 	/*
1830 	 * See if value is greater than last value in list
1831 	 * if so return last value
1832 	 */
1833 	if (target > (uint32_t)(listEndValue * EEP_SCALE + EEP_DELTA)) {
1834 		*pLowerValue = listEndValue;
1835 		*pUpperValue = listEndValue;
1836 		return;
1837 	}
1838 
1839 	/* look for value being near or between 2 values in list */
1840 	for (i = 0; i < listSize; i++) {
1841 		/*
1842 		 * If value is close to the current value of the list
1843 		 * then target is not between values, it is one of the values
1844 		 */
1845 		if (abs(pList[i] * EEP_SCALE - (int32_t) target) < EEP_DELTA) {
1846 			*pLowerValue = pList[i];
1847 			*pUpperValue = pList[i];
1848 			return;
1849 		}
1850 
1851 		/*
1852 		 * Look for value being between current value and next value
1853 		 * if so return these 2 values
1854 		 */
1855 		if (target < (uint32_t)(pList[i + 1] * EEP_SCALE - EEP_DELTA)) {
1856 			*pLowerValue = pList[i];
1857 			*pUpperValue = pList[i + 1];
1858 			return;
1859 		}
1860 	}
1861 }
1862 
1863 /*
1864  * Get the upper and lower pcdac given the channel and the pcdac
1865  * used in the search
1866  */
1867 void
1868 ar5211GetLowerUpperPcdacs(uint16_t pcdac, uint16_t channel,
1869 	const PCDACS_EEPROM *pSrcStruct,
1870 	uint16_t *pLowerPcdac, uint16_t *pUpperPcdac)
1871 {
1872 	const DATA_PER_CHANNEL *pChannelData;
1873 	int i;
1874 
1875 	/* Find the channel information */
1876 	pChannelData = pSrcStruct->pDataPerChannel;
1877 	for (i = 0; i < pSrcStruct->numChannels; i++) {
1878 		if (pChannelData->channelValue == channel)
1879 			break;
1880 		pChannelData++;
1881 	}
1882 	ar5211GetLowerUpperValues(pcdac, pChannelData->PcdacValues,
1883 		pChannelData->numPcdacValues, pLowerPcdac, pUpperPcdac);
1884 }
1885 
1886 #define	DYN_ADJ_UP_MARGIN	15
1887 #define	DYN_ADJ_LO_MARGIN	20
1888 
1889 static const GAIN_OPTIMIZATION_LADDER gainLadder = {
1890 	9,					/* numStepsInLadder */
1891 	4,					/* defaultStepNum */
1892 	{ { {4, 1, 1, 1},  6, "FG8"},
1893 	  { {4, 0, 1, 1},  4, "FG7"},
1894 	  { {3, 1, 1, 1},  3, "FG6"},
1895 	  { {4, 0, 0, 1},  1, "FG5"},
1896 	  { {4, 1, 1, 0},  0, "FG4"},	/* noJack */
1897 	  { {4, 0, 1, 0}, -2, "FG3"},	/* halfJack */
1898 	  { {3, 1, 1, 0}, -3, "FG2"},	/* clip3 */
1899 	  { {4, 0, 0, 0}, -4, "FG1"},	/* noJack */
1900 	  { {2, 1, 1, 0}, -6, "FG0"} 	/* clip2 */
1901 	}
1902 };
1903 
1904 /*
1905  * Initialize the gain structure to good values
1906  */
1907 void
1908 ar5211InitializeGainValues(struct ath_hal *ah)
1909 {
1910 	struct ath_hal_5211 *ahp = AH5211(ah);
1911 	GAIN_VALUES *gv = &ahp->ah_gainValues;
1912 
1913 	/* initialize gain optimization values */
1914 	gv->currStepNum = gainLadder.defaultStepNum;
1915 	gv->currStep = &gainLadder.optStep[gainLadder.defaultStepNum];
1916 	gv->active = AH_TRUE;
1917 	gv->loTrig = 20;
1918 	gv->hiTrig = 35;
1919 }
1920 
1921 static HAL_BOOL
1922 ar5211InvalidGainReadback(struct ath_hal *ah, GAIN_VALUES *gv)
1923 {
1924 	const struct ieee80211_channel *chan = AH_PRIVATE(ah)->ah_curchan;
1925 	uint32_t gStep, g;
1926 	uint32_t L1, L2, L3, L4;
1927 
1928 	if (IEEE80211_IS_CHAN_CCK(chan)) {
1929 		gStep = 0x18;
1930 		L1 = 0;
1931 		L2 = gStep + 4;
1932 		L3 = 0x40;
1933 		L4 = L3 + 50;
1934 
1935 		gv->loTrig = L1;
1936 		gv->hiTrig = L4+5;
1937 	} else {
1938 		gStep = 0x3f;
1939 		L1 = 0;
1940 		L2 = 50;
1941 		L3 = L1;
1942 		L4 = L3 + 50;
1943 
1944 		gv->loTrig = L1 + DYN_ADJ_LO_MARGIN;
1945 		gv->hiTrig = L4 - DYN_ADJ_UP_MARGIN;
1946 	}
1947 	g = gv->currGain;
1948 
1949 	return !((g >= L1 && g<= L2) || (g >= L3 && g <= L4));
1950 }
1951 
1952 /*
1953  * Enable the probe gain check on the next packet
1954  */
1955 static void
1956 ar5211RequestRfgain(struct ath_hal *ah)
1957 {
1958 	struct ath_hal_5211 *ahp = AH5211(ah);
1959 
1960 	/* Enable the gain readback probe */
1961 	OS_REG_WRITE(ah, AR_PHY_PAPD_PROBE,
1962 		  SM(ahp->ah_tx6PowerInHalfDbm, AR_PHY_PAPD_PROBE_POWERTX)
1963 		| AR_PHY_PAPD_PROBE_NEXT_TX);
1964 
1965 	ahp->ah_rfgainState = HAL_RFGAIN_READ_REQUESTED;
1966 }
1967 
1968 /*
1969  * Exported call to check for a recent gain reading and return
1970  * the current state of the thermal calibration gain engine.
1971  */
1972 HAL_RFGAIN
1973 ar5211GetRfgain(struct ath_hal *ah)
1974 {
1975 	struct ath_hal_5211 *ahp = AH5211(ah);
1976 	GAIN_VALUES *gv = &ahp->ah_gainValues;
1977 	uint32_t rddata;
1978 
1979 	if (!gv->active)
1980 		return HAL_RFGAIN_INACTIVE;
1981 
1982 	if (ahp->ah_rfgainState == HAL_RFGAIN_READ_REQUESTED) {
1983 		/* Caller had asked to setup a new reading. Check it. */
1984 		rddata = OS_REG_READ(ah, AR_PHY_PAPD_PROBE);
1985 
1986 		if ((rddata & AR_PHY_PAPD_PROBE_NEXT_TX) == 0) {
1987 			/* bit got cleared, we have a new reading. */
1988 			gv->currGain = rddata >> AR_PHY_PAPD_PROBE_GAINF_S;
1989 			/* inactive by default */
1990 			ahp->ah_rfgainState = HAL_RFGAIN_INACTIVE;
1991 
1992 			if (!ar5211InvalidGainReadback(ah, gv) &&
1993 			    ar5211IsGainAdjustNeeded(ah, gv) &&
1994 			    ar5211AdjustGain(ah, gv) > 0) {
1995 				/*
1996 				 * Change needed. Copy ladder info
1997 				 * into eeprom info.
1998 				 */
1999 				ar5211SetRfgain(ah, gv);
2000 				ahp->ah_rfgainState = HAL_RFGAIN_NEED_CHANGE;
2001 			}
2002 		}
2003 	}
2004 	return ahp->ah_rfgainState;
2005 }
2006 
2007 /*
2008  * Check to see if our readback gain level sits within the linear
2009  * region of our current variable attenuation window
2010  */
2011 static HAL_BOOL
2012 ar5211IsGainAdjustNeeded(struct ath_hal *ah, const GAIN_VALUES *gv)
2013 {
2014 	return (gv->currGain <= gv->loTrig || gv->currGain >= gv->hiTrig);
2015 }
2016 
2017 /*
2018  * Move the rabbit ears in the correct direction.
2019  */
2020 static int32_t
2021 ar5211AdjustGain(struct ath_hal *ah, GAIN_VALUES *gv)
2022 {
2023 	/* return > 0 for valid adjustments. */
2024 	if (!gv->active)
2025 		return -1;
2026 
2027 	gv->currStep = &gainLadder.optStep[gv->currStepNum];
2028 	if (gv->currGain >= gv->hiTrig) {
2029 		if (gv->currStepNum == 0) {
2030 			HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2031 			    "%s: Max gain limit.\n", __func__);
2032 			return -1;
2033 		}
2034 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2035 		    "%s: Adding gain: currG=%d [%s] --> ",
2036 		    __func__, gv->currGain, gv->currStep->stepName);
2037 		gv->targetGain = gv->currGain;
2038 		while (gv->targetGain >= gv->hiTrig && gv->currStepNum > 0) {
2039 			gv->targetGain -= 2 * (gainLadder.optStep[--(gv->currStepNum)].stepGain -
2040 				gv->currStep->stepGain);
2041 			gv->currStep = &gainLadder.optStep[gv->currStepNum];
2042 		}
2043 		HALDEBUG(ah, HAL_DEBUG_RFPARAM, "targG=%d [%s]\n",
2044 		    gv->targetGain, gv->currStep->stepName);
2045 		return 1;
2046 	}
2047 	if (gv->currGain <= gv->loTrig) {
2048 		if (gv->currStepNum == gainLadder.numStepsInLadder-1) {
2049 			HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2050 			    "%s: Min gain limit.\n", __func__);
2051 			return -2;
2052 		}
2053 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2054 		    "%s: Deducting gain: currG=%d [%s] --> ",
2055 		    __func__, gv->currGain, gv->currStep->stepName);
2056 		gv->targetGain = gv->currGain;
2057 		while (gv->targetGain <= gv->loTrig &&
2058 		      gv->currStepNum < (gainLadder.numStepsInLadder - 1)) {
2059 			gv->targetGain -= 2 *
2060 				(gainLadder.optStep[++(gv->currStepNum)].stepGain - gv->currStep->stepGain);
2061 			gv->currStep = &gainLadder.optStep[gv->currStepNum];
2062 		}
2063 		HALDEBUG(ah, HAL_DEBUG_RFPARAM, "targG=%d [%s]\n",
2064 		    gv->targetGain, gv->currStep->stepName);
2065 		return 2;
2066 	}
2067 	return 0;		/* caller didn't call needAdjGain first */
2068 }
2069 
2070 /*
2071  * Adjust the 5GHz EEPROM information with the desired calibration values.
2072  */
2073 static void
2074 ar5211SetRfgain(struct ath_hal *ah, const GAIN_VALUES *gv)
2075 {
2076 	HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
2077 
2078 	if (!gv->active)
2079 		return;
2080 	ee->ee_cornerCal.clip = gv->currStep->paramVal[0]; /* bb_tx_clip */
2081 	ee->ee_cornerCal.pd90 = gv->currStep->paramVal[1]; /* rf_pwd_90 */
2082 	ee->ee_cornerCal.pd84 = gv->currStep->paramVal[2]; /* rf_pwd_84 */
2083 	ee->ee_cornerCal.gSel = gv->currStep->paramVal[3]; /* rf_rfgainsel */
2084 }
2085 
2086 static void
2087 ar5211SetOperatingMode(struct ath_hal *ah, int opmode)
2088 {
2089 	struct ath_hal_5211 *ahp = AH5211(ah);
2090 	uint32_t val;
2091 
2092 	val = OS_REG_READ(ah, AR_STA_ID1) & 0xffff;
2093 	switch (opmode) {
2094 	case HAL_M_HOSTAP:
2095 		OS_REG_WRITE(ah, AR_STA_ID1, val
2096 			| AR_STA_ID1_STA_AP
2097 			| AR_STA_ID1_RTS_USE_DEF
2098 			| ahp->ah_staId1Defaults);
2099 		break;
2100 	case HAL_M_IBSS:
2101 		OS_REG_WRITE(ah, AR_STA_ID1, val
2102 			| AR_STA_ID1_ADHOC
2103 			| AR_STA_ID1_DESC_ANTENNA
2104 			| ahp->ah_staId1Defaults);
2105 		break;
2106 	case HAL_M_STA:
2107 	case HAL_M_MONITOR:
2108 		OS_REG_WRITE(ah, AR_STA_ID1, val
2109 			| AR_STA_ID1_DEFAULT_ANTENNA
2110 			| ahp->ah_staId1Defaults);
2111 		break;
2112 	}
2113 }
2114 
2115 void
2116 ar5211SetPCUConfig(struct ath_hal *ah)
2117 {
2118 	ar5211SetOperatingMode(ah, AH_PRIVATE(ah)->ah_opmode);
2119 }
2120