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