1 /*
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * Copyright (c) 2002-2008 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 #include "ah.h"
22 #include "ah_internal.h"
23 #include "ah_devid.h"
24 
25 #include "ar5212/ar5212.h"
26 #include "ar5212/ar5212reg.h"
27 #include "ar5212/ar5212phy.h"
28 
29 #include "ah_eeprom_v3.h"
30 
31 /* Additional Time delay to wait after activiting the Base band */
32 #define BASE_ACTIVATE_DELAY	100	/* 100 usec */
33 #define PLL_SETTLE_DELAY	300	/* 300 usec */
34 
35 static HAL_BOOL ar5212SetResetReg(struct ath_hal *, uint32_t resetMask);
36 /* NB: public for 5312 use */
37 HAL_BOOL	ar5212IsSpurChannel(struct ath_hal *,
38 		    const struct ieee80211_channel *);
39 HAL_BOOL	ar5212ChannelChange(struct ath_hal *,
40 		    const struct ieee80211_channel *);
41 int16_t		ar5212GetNf(struct ath_hal *, struct ieee80211_channel *);
42 HAL_BOOL	ar5212SetBoardValues(struct ath_hal *,
43 		    const struct ieee80211_channel *);
44 void		ar5212SetDeltaSlope(struct ath_hal *,
45 		    const struct ieee80211_channel *);
46 HAL_BOOL	ar5212SetTransmitPower(struct ath_hal *ah,
47 		   const struct ieee80211_channel *chan, uint16_t *rfXpdGain);
48 static HAL_BOOL ar5212SetRateTable(struct ath_hal *,
49 		   const struct ieee80211_channel *, int16_t tpcScaleReduction,
50 		   int16_t powerLimit,
51 		   HAL_BOOL commit, int16_t *minPower, int16_t *maxPower);
52 static void ar5212CorrectGainDelta(struct ath_hal *, int twiceOfdmCckDelta);
53 static void ar5212GetTargetPowers(struct ath_hal *,
54 		   const struct ieee80211_channel *,
55 		   const TRGT_POWER_INFO *pPowerInfo, uint16_t numChannels,
56 		   TRGT_POWER_INFO *pNewPower);
57 static uint16_t ar5212GetMaxEdgePower(uint16_t channel,
58 		   const RD_EDGES_POWER  *pRdEdgesPower);
59 void		ar5212SetRateDurationTable(struct ath_hal *,
60 		    const struct ieee80211_channel *);
61 void		ar5212SetIFSTiming(struct ath_hal *,
62 		    const struct ieee80211_channel *);
63 
64 /* NB: public for RF backend use */
65 void		ar5212GetLowerUpperValues(uint16_t value,
66 		   uint16_t *pList, uint16_t listSize,
67 		   uint16_t *pLowerValue, uint16_t *pUpperValue);
68 void		ar5212ModifyRfBuffer(uint32_t *rfBuf, uint32_t reg32,
69 		   uint32_t numBits, uint32_t firstBit, uint32_t column);
70 
71 static int
72 write_common(struct ath_hal *ah, const HAL_INI_ARRAY *ia,
73 	HAL_BOOL bChannelChange, int writes)
74 {
75 #define IS_NO_RESET_TIMER_ADDR(x)                      \
76     ( (((x) >= AR_BEACON) && ((x) <= AR_CFP_DUR)) || \
77       (((x) >= AR_SLEEP1) && ((x) <= AR_SLEEP3)))
78 #define	V(r, c)	(ia)->data[((r)*(ia)->cols) + (c)]
79 	int r;
80 
81 	/* Write Common Array Parameters */
82 	for (r = 0; r < ia->rows; r++) {
83 		uint32_t reg = V(r, 0);
84 		/* XXX timer/beacon setup registers? */
85 		/* On channel change, don't reset the PCU registers */
86 		if (!(bChannelChange && IS_NO_RESET_TIMER_ADDR(reg))) {
87 			OS_REG_WRITE(ah, reg, V(r, 1));
88 			DMA_YIELD(writes);
89 		}
90 	}
91 	return writes;
92 #undef IS_NO_RESET_TIMER_ADDR
93 #undef V
94 }
95 
96 #define IS_DISABLE_FAST_ADC_CHAN(x) (((x) == 2462) || ((x) == 2467))
97 
98 /*
99  * Places the device in and out of reset and then places sane
100  * values in the registers based on EEPROM config, initialization
101  * vectors (as determined by the mode), and station configuration
102  *
103  * bChannelChange is used to preserve DMA/PCU registers across
104  * a HW Reset during channel change.
105  */
106 HAL_BOOL
107 ar5212Reset(struct ath_hal *ah, HAL_OPMODE opmode,
108 	struct ieee80211_channel *chan,
109 	HAL_BOOL bChannelChange, HAL_STATUS *status)
110 {
111 #define	N(a)	(sizeof (a) / sizeof (a[0]))
112 #define	FAIL(_code)	do { ecode = _code; goto bad; } while (0)
113 	struct ath_hal_5212 *ahp = AH5212(ah);
114 	HAL_CHANNEL_INTERNAL *ichan = AH_NULL;
115 	const HAL_EEPROM *ee;
116 	uint32_t softLedCfg, softLedState;
117 	uint32_t saveFrameSeqCount, saveDefAntenna, saveLedState;
118 	uint32_t macStaId1, synthDelay, txFrm2TxDStart;
119 	uint16_t rfXpdGain[MAX_NUM_PDGAINS_PER_CHANNEL];
120 	int16_t cckOfdmPwrDelta = 0;
121 	u_int modesIndex, freqIndex;
122 	HAL_STATUS ecode;
123 	int i, regWrites;
124 	uint32_t testReg, powerVal;
125 	int8_t twiceAntennaGain, twiceAntennaReduction;
126 	uint32_t ackTpcPow, ctsTpcPow, chirpTpcPow;
127 	HAL_BOOL isBmode = AH_FALSE;
128 
129 	HALASSERT(ah->ah_magic == AR5212_MAGIC);
130 	ee = AH_PRIVATE(ah)->ah_eeprom;
131 
132 	OS_MARK(ah, AH_MARK_RESET, bChannelChange);
133 
134 	/* Bring out of sleep mode */
135 	if (!ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE)) {
136 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip did not wakeup\n",
137 		    __func__);
138 		FAIL(HAL_EIO);
139 	}
140 
141 	/*
142 	 * Map public channel to private.
143 	 */
144 	ichan = ath_hal_checkchannel(ah, chan);
145 	if (ichan == AH_NULL)
146 		FAIL(HAL_EINVAL);
147 	switch (opmode) {
148 	case HAL_M_STA:
149 	case HAL_M_IBSS:
150 	case HAL_M_HOSTAP:
151 	case HAL_M_MONITOR:
152 		break;
153 	default:
154 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid operating mode %u\n",
155 		    __func__, opmode);
156 		FAIL(HAL_EINVAL);
157 		break;
158 	}
159 	HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER3);
160 
161 	SAVE_CCK(ah, chan, isBmode);
162 
163 	/* Preserve certain DMA hardware registers on a channel change */
164 	if (bChannelChange) {
165 		/*
166 		 * On Venice, the TSF is almost preserved across a reset;
167 		 * it requires doubling writes to the RESET_TSF
168 		 * bit in the AR_BEACON register; it also has the quirk
169 		 * of the TSF going back in time on the station (station
170 		 * latches onto the last beacon's tsf during a reset 50%
171 		 * of the times); the latter is not a problem for adhoc
172 		 * stations since as long as the TSF is behind, it will
173 		 * get resynchronized on receiving the next beacon; the
174 		 * TSF going backwards in time could be a problem for the
175 		 * sleep operation (supported on infrastructure stations
176 		 * only) - the best and most general fix for this situation
177 		 * is to resynchronize the various sleep/beacon timers on
178 		 * the receipt of the next beacon i.e. when the TSF itself
179 		 * gets resynchronized to the AP's TSF - power save is
180 		 * needed to be temporarily disabled until that time
181 		 *
182 		 * Need to save the sequence number to restore it after
183 		 * the reset!
184 		 */
185 		saveFrameSeqCount = OS_REG_READ(ah, AR_D_SEQNUM);
186 	} else
187 		saveFrameSeqCount = 0;		/* NB: silence compiler */
188 #if 0
189 	/*
190 	 * XXX disable for now; this appears to sometimes cause OFDM
191 	 * XXX timing error floods when ani is enabled and bg scanning
192 	 * XXX kicks in
193 	 */
194 	/* If the channel change is across the same mode - perform a fast channel change */
195 	if (IS_2413(ah) || IS_5413(ah)) {
196 		/*
197 		 * Fast channel change can only be used when:
198 		 *  -channel change requested - so it's not the initial reset.
199 		 *  -it's not a change to the current channel -
200 		 *	often called when switching modes on a channel
201 		 *  -the modes of the previous and requested channel are the
202 		 *	same
203 		 * XXX opmode shouldn't change either?
204 		 */
205 		if (bChannelChange &&
206 		    (AH_PRIVATE(ah)->ah_curchan != AH_NULL) &&
207 		    (chan->ic_freq != AH_PRIVATE(ah)->ah_curchan->ic_freq) &&
208 		    ((chan->ic_flags & IEEE80211_CHAN_ALLTURBO) ==
209 		     (AH_PRIVATE(ah)->ah_curchan->ic_flags & IEEE80211_CHAN_ALLTURBO))) {
210 			if (ar5212ChannelChange(ah, chan)) {
211 				/* If ChannelChange completed - skip the rest of reset */
212 				/* XXX ani? */
213 				goto done;
214 			}
215 		}
216 	}
217 #endif
218 	/*
219 	 * Preserve the antenna on a channel change
220 	 */
221 	saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
222 	if (saveDefAntenna == 0)		/* XXX magic constants */
223 		saveDefAntenna = 1;
224 
225 	/* Save hardware flag before chip reset clears the register */
226 	macStaId1 = OS_REG_READ(ah, AR_STA_ID1) &
227 		(AR_STA_ID1_BASE_RATE_11B | AR_STA_ID1_USE_DEFANT);
228 
229 	/* Save led state from pci config register */
230 	saveLedState = OS_REG_READ(ah, AR_PCICFG) &
231 		(AR_PCICFG_LEDCTL | AR_PCICFG_LEDMODE | AR_PCICFG_LEDBLINK |
232 		 AR_PCICFG_LEDSLOW);
233 	softLedCfg = OS_REG_READ(ah, AR_GPIOCR);
234 	softLedState = OS_REG_READ(ah, AR_GPIODO);
235 
236 	ar5212RestoreClock(ah, opmode);		/* move to refclk operation */
237 
238 	/*
239 	 * Adjust gain parameters before reset if
240 	 * there's an outstanding gain updated.
241 	 */
242 	(void) ar5212GetRfgain(ah);
243 
244 	if (!ar5212ChipReset(ah, chan)) {
245 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
246 		FAIL(HAL_EIO);
247 	}
248 
249 	/* Setup the indices for the next set of register array writes */
250 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
251 		freqIndex  = 2;
252 		if (IEEE80211_IS_CHAN_108G(chan))
253 			modesIndex = 5;
254 		else if (IEEE80211_IS_CHAN_G(chan))
255 			modesIndex = 4;
256 		else if (IEEE80211_IS_CHAN_B(chan))
257 			modesIndex = 3;
258 		else {
259 			HALDEBUG(ah, HAL_DEBUG_ANY,
260 			    "%s: invalid channel %u/0x%x\n",
261 			    __func__, chan->ic_freq, chan->ic_flags);
262 			FAIL(HAL_EINVAL);
263 		}
264 	} else {
265 		freqIndex  = 1;
266 		if (IEEE80211_IS_CHAN_TURBO(chan))
267 			modesIndex = 2;
268 		else if (IEEE80211_IS_CHAN_A(chan))
269 			modesIndex = 1;
270 		else {
271 			HALDEBUG(ah, HAL_DEBUG_ANY,
272 			    "%s: invalid channel %u/0x%x\n",
273 			    __func__, chan->ic_freq, chan->ic_flags);
274 			FAIL(HAL_EINVAL);
275 		}
276 	}
277 
278 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
279 
280 	/* Set correct Baseband to analog shift setting to access analog chips. */
281 	OS_REG_WRITE(ah, AR_PHY(0), 0x00000007);
282 
283 	regWrites = ath_hal_ini_write(ah, &ahp->ah_ini_modes, modesIndex, 0);
284 	regWrites = write_common(ah, &ahp->ah_ini_common, bChannelChange,
285 		regWrites);
286 #ifdef AH_RXCFG_SDMAMW_4BYTES
287 	/*
288 	 * Nala doesn't work with 128 byte bursts on pb42(hydra) (ar71xx),
289 	 * use 4 instead.  Enabling it on all platforms would hurt performance,
290 	 * so we only enable it on the ones that are affected by it.
291 	 */
292 	OS_REG_WRITE(ah, AR_RXCFG, 0);
293 #endif
294 	ahp->ah_rfHal->writeRegs(ah, modesIndex, freqIndex, regWrites);
295 
296 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
297 
298 	if (IEEE80211_IS_CHAN_HALF(chan) || IEEE80211_IS_CHAN_QUARTER(chan)) {
299 		ar5212SetIFSTiming(ah, chan);
300 		if (IS_5413(ah)) {
301 			/*
302 			 * Force window_length for 1/2 and 1/4 rate channels,
303 			 * the ini file sets this to zero otherwise.
304 			 */
305 			OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
306 				AR_PHY_FRAME_CTL_WINLEN, 3);
307 		}
308 	}
309 
310 	/* Overwrite INI values for revised chipsets */
311 	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_2) {
312 		/* ADC_CTL */
313 		OS_REG_WRITE(ah, AR_PHY_ADC_CTL,
314 			SM(2, AR_PHY_ADC_CTL_OFF_INBUFGAIN) |
315 			SM(2, AR_PHY_ADC_CTL_ON_INBUFGAIN) |
316 			AR_PHY_ADC_CTL_OFF_PWDDAC |
317 			AR_PHY_ADC_CTL_OFF_PWDADC);
318 
319 		/* TX_PWR_ADJ */
320 		if (ichan->channel == 2484) {
321 			cckOfdmPwrDelta = SCALE_OC_DELTA(
322 			    ee->ee_cckOfdmPwrDelta -
323 			    ee->ee_scaledCh14FilterCckDelta);
324 		} else {
325 			cckOfdmPwrDelta = SCALE_OC_DELTA(
326 			    ee->ee_cckOfdmPwrDelta);
327 		}
328 
329 		if (IEEE80211_IS_CHAN_G(chan)) {
330 		    OS_REG_WRITE(ah, AR_PHY_TXPWRADJ,
331 			SM((ee->ee_cckOfdmPwrDelta*-1),
332 			    AR_PHY_TXPWRADJ_CCK_GAIN_DELTA) |
333 			SM((cckOfdmPwrDelta*-1),
334 			    AR_PHY_TXPWRADJ_CCK_PCDAC_INDEX));
335 		} else {
336 			OS_REG_WRITE(ah, AR_PHY_TXPWRADJ, 0);
337 		}
338 
339 		/* Add barker RSSI thresh enable as disabled */
340 		OS_REG_CLR_BIT(ah, AR_PHY_DAG_CTRLCCK,
341 			AR_PHY_DAG_CTRLCCK_EN_RSSI_THR);
342 		OS_REG_RMW_FIELD(ah, AR_PHY_DAG_CTRLCCK,
343 			AR_PHY_DAG_CTRLCCK_RSSI_THR, 2);
344 
345 		/* Set the mute mask to the correct default */
346 		OS_REG_WRITE(ah, AR_SEQ_MASK, 0x0000000F);
347 	}
348 
349 	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_3) {
350 		/* Clear reg to alllow RX_CLEAR line debug */
351 		OS_REG_WRITE(ah, AR_PHY_BLUETOOTH,  0);
352 	}
353 	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_4) {
354 #ifdef notyet
355 		/* Enable burst prefetch for the data queues */
356 		OS_REG_RMW_FIELD(ah, AR_D_FPCTL, ... );
357 		/* Enable double-buffering */
358 		OS_REG_CLR_BIT(ah, AR_TXCFG, AR_TXCFG_DBL_BUF_DIS);
359 #endif
360 	}
361 
362 	/* Set ADC/DAC select values */
363 	OS_REG_WRITE(ah, AR_PHY_SLEEP_SCAL, 0x0e);
364 
365 	if (IS_5413(ah) || IS_2417(ah)) {
366 		uint32_t newReg = 1;
367 		if (IS_DISABLE_FAST_ADC_CHAN(ichan->channel))
368 			newReg = 0;
369 		/* As it's a clock changing register, only write when the value needs to be changed */
370 		if (OS_REG_READ(ah, AR_PHY_FAST_ADC) != newReg)
371 			OS_REG_WRITE(ah, AR_PHY_FAST_ADC, newReg);
372 	}
373 
374 	/* Setup the transmit power values. */
375 	if (!ar5212SetTransmitPower(ah, chan, rfXpdGain)) {
376 		HALDEBUG(ah, HAL_DEBUG_ANY,
377 		    "%s: error init'ing transmit power\n", __func__);
378 		FAIL(HAL_EIO);
379 	}
380 
381 	/* Write the analog registers */
382 	if (!ahp->ah_rfHal->setRfRegs(ah, chan, modesIndex, rfXpdGain)) {
383 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: ar5212SetRfRegs failed\n",
384 		    __func__);
385 		FAIL(HAL_EIO);
386 	}
387 
388 	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
389 	if (IEEE80211_IS_CHAN_OFDM(chan)) {
390 		if (IS_5413(ah) ||
391 		    AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3)
392 			ar5212SetSpurMitigation(ah, chan);
393 		ar5212SetDeltaSlope(ah, chan);
394 	}
395 
396 	/* Setup board specific options for EEPROM version 3 */
397 	if (!ar5212SetBoardValues(ah, chan)) {
398 		HALDEBUG(ah, HAL_DEBUG_ANY,
399 		    "%s: error setting board options\n", __func__);
400 		FAIL(HAL_EIO);
401 	}
402 
403 	/* Restore certain DMA hardware registers on a channel change */
404 	if (bChannelChange)
405 		OS_REG_WRITE(ah, AR_D_SEQNUM, saveFrameSeqCount);
406 
407 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
408 
409 	OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
410 	OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
411 		| macStaId1
412 		| AR_STA_ID1_RTS_USE_DEF
413 		| ahp->ah_staId1Defaults
414 	);
415 	ar5212SetOperatingMode(ah, opmode);
416 
417 	/* Set Venice BSSID mask according to current state */
418 	OS_REG_WRITE(ah, AR_BSSMSKL, LE_READ_4(ahp->ah_bssidmask));
419 	OS_REG_WRITE(ah, AR_BSSMSKU, LE_READ_2(ahp->ah_bssidmask + 4));
420 
421 	/* Restore previous led state */
422 	OS_REG_WRITE(ah, AR_PCICFG, OS_REG_READ(ah, AR_PCICFG) | saveLedState);
423 
424 	/* Restore soft Led state to GPIO */
425 	OS_REG_WRITE(ah, AR_GPIOCR, softLedCfg);
426 	OS_REG_WRITE(ah, AR_GPIODO, softLedState);
427 
428 	/* Restore previous antenna */
429 	OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
430 
431 	/* then our BSSID */
432 	OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
433 	OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4));
434 
435 	/* Restore bmiss rssi & count thresholds */
436 	OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
437 
438 	OS_REG_WRITE(ah, AR_ISR, ~0);		/* cleared on write */
439 
440 	if (!ar5212SetChannel(ah, chan))
441 		FAIL(HAL_EIO);
442 
443 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
444 
445 	ar5212SetCoverageClass(ah, AH_PRIVATE(ah)->ah_coverageClass, 1);
446 
447 	ar5212SetRateDurationTable(ah, chan);
448 
449 	/* Set Tx frame start to tx data start delay */
450 	if (IS_RAD5112_ANY(ah) &&
451 	    (IEEE80211_IS_CHAN_HALF(chan) || IEEE80211_IS_CHAN_QUARTER(chan))) {
452 		txFrm2TxDStart =
453 			IEEE80211_IS_CHAN_HALF(chan) ?
454 					TX_FRAME_D_START_HALF_RATE:
455 					TX_FRAME_D_START_QUARTER_RATE;
456 		OS_REG_RMW_FIELD(ah, AR_PHY_TX_CTL,
457 			AR_PHY_TX_FRAME_TO_TX_DATA_START, txFrm2TxDStart);
458 	}
459 
460 	/*
461 	 * Setup fast diversity.
462 	 * Fast diversity can be enabled or disabled via regadd.txt.
463 	 * Default is enabled.
464 	 * For reference,
465 	 *    Disable: reg        val
466 	 *             0x00009860 0x00009d18 (if 11a / 11g, else no change)
467 	 *             0x00009970 0x192bb514
468 	 *             0x0000a208 0xd03e4648
469 	 *
470 	 *    Enable:  0x00009860 0x00009d10 (if 11a / 11g, else no change)
471 	 *             0x00009970 0x192fb514
472 	 *             0x0000a208 0xd03e6788
473 	 */
474 
475 	/* XXX Setup pre PHY ENABLE EAR additions */
476 	/*
477 	 * Wait for the frequency synth to settle (synth goes on
478 	 * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
479 	 * Value is in 100ns increments.
480 	 */
481 	synthDelay = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
482 	if (IEEE80211_IS_CHAN_B(chan)) {
483 		synthDelay = (4 * synthDelay) / 22;
484 	} else {
485 		synthDelay /= 10;
486 	}
487 
488 	/* Activate the PHY (includes baseband activate and synthesizer on) */
489 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
490 
491 	/*
492 	 * There is an issue if the AP starts the calibration before
493 	 * the base band timeout completes.  This could result in the
494 	 * rx_clear false triggering.  As a workaround we add delay an
495 	 * extra BASE_ACTIVATE_DELAY usecs to ensure this condition
496 	 * does not happen.
497 	 */
498 	if (IEEE80211_IS_CHAN_HALF(chan)) {
499 		OS_DELAY((synthDelay << 1) + BASE_ACTIVATE_DELAY);
500 	} else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
501 		OS_DELAY((synthDelay << 2) + BASE_ACTIVATE_DELAY);
502 	} else {
503 		OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
504 	}
505 
506 	/*
507 	 * The udelay method is not reliable with notebooks.
508 	 * Need to check to see if the baseband is ready
509 	 */
510 	testReg = OS_REG_READ(ah, AR_PHY_TESTCTRL);
511 	/* Selects the Tx hold */
512 	OS_REG_WRITE(ah, AR_PHY_TESTCTRL, AR_PHY_TESTCTRL_TXHOLD);
513 	i = 0;
514 	while ((i++ < 20) &&
515 	       (OS_REG_READ(ah, 0x9c24) & 0x10)) /* test if baseband not ready */		OS_DELAY(200);
516 	OS_REG_WRITE(ah, AR_PHY_TESTCTRL, testReg);
517 
518 	/* Calibrate the AGC and start a NF calculation */
519 	OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
520 		  OS_REG_READ(ah, AR_PHY_AGC_CONTROL)
521 		| AR_PHY_AGC_CONTROL_CAL
522 		| AR_PHY_AGC_CONTROL_NF);
523 
524 	if (!IEEE80211_IS_CHAN_B(chan) && ahp->ah_bIQCalibration != IQ_CAL_DONE) {
525 		/* Start IQ calibration w/ 2^(INIT_IQCAL_LOG_COUNT_MAX+1) samples */
526 		OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
527 			AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX,
528 			INIT_IQCAL_LOG_COUNT_MAX);
529 		OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
530 			AR_PHY_TIMING_CTRL4_DO_IQCAL);
531 		ahp->ah_bIQCalibration = IQ_CAL_RUNNING;
532 	} else
533 		ahp->ah_bIQCalibration = IQ_CAL_INACTIVE;
534 
535 	/* Setup compression registers */
536 	ar5212SetCompRegs(ah);
537 
538 	/* Set 1:1 QCU to DCU mapping for all queues */
539 	for (i = 0; i < AR_NUM_DCU; i++)
540 		OS_REG_WRITE(ah, AR_DQCUMASK(i), 1 << i);
541 
542 	ahp->ah_intrTxqs = 0;
543 	for (i = 0; i < AH_PRIVATE(ah)->ah_caps.halTotalQueues; i++)
544 		ar5212ResetTxQueue(ah, i);
545 
546 	/*
547 	 * Setup interrupt handling.  Note that ar5212ResetTxQueue
548 	 * manipulates the secondary IMR's as queues are enabled
549 	 * and disabled.  This is done with RMW ops to insure the
550 	 * settings we make here are preserved.
551 	 */
552 	ahp->ah_maskReg = AR_IMR_TXOK | AR_IMR_TXERR | AR_IMR_TXURN
553 			| AR_IMR_RXOK | AR_IMR_RXERR | AR_IMR_RXORN
554 			| AR_IMR_HIUERR
555 			;
556 	if (opmode == HAL_M_HOSTAP)
557 		ahp->ah_maskReg |= AR_IMR_MIB;
558 	OS_REG_WRITE(ah, AR_IMR, ahp->ah_maskReg);
559 	/* Enable bus errors that are OR'd to set the HIUERR bit */
560 	OS_REG_WRITE(ah, AR_IMR_S2,
561 		OS_REG_READ(ah, AR_IMR_S2)
562 		| AR_IMR_S2_MCABT | AR_IMR_S2_SSERR | AR_IMR_S2_DPERR);
563 
564 	if (AH_PRIVATE(ah)->ah_rfkillEnabled)
565 		ar5212EnableRfKill(ah);
566 
567 	if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0)) {
568 		HALDEBUG(ah, HAL_DEBUG_ANY,
569 		    "%s: offset calibration failed to complete in 1ms;"
570 		    " noisy environment?\n", __func__);
571 	}
572 
573 	/*
574 	 * Set clocks back to 32kHz if they had been using refClk, then
575 	 * use an external 32kHz crystal when sleeping, if one exists.
576 	 */
577 	ar5212SetupClock(ah, opmode);
578 
579 	/*
580 	 * Writing to AR_BEACON will start timers. Hence it should
581 	 * be the last register to be written. Do not reset tsf, do
582 	 * not enable beacons at this point, but preserve other values
583 	 * like beaconInterval.
584 	 */
585 	OS_REG_WRITE(ah, AR_BEACON,
586 		(OS_REG_READ(ah, AR_BEACON) &~ (AR_BEACON_EN | AR_BEACON_RESET_TSF)));
587 
588 	/* XXX Setup post reset EAR additions */
589 
590 	/* QoS support */
591 	if (AH_PRIVATE(ah)->ah_macVersion > AR_SREV_VERSION_VENICE ||
592 	    (AH_PRIVATE(ah)->ah_macVersion == AR_SREV_VERSION_VENICE &&
593 	     AH_PRIVATE(ah)->ah_macRev >= AR_SREV_GRIFFIN_LITE)) {
594 		OS_REG_WRITE(ah, AR_QOS_CONTROL, 0x100aa);	/* XXX magic */
595 		OS_REG_WRITE(ah, AR_QOS_SELECT, 0x3210);	/* XXX magic */
596 	}
597 
598 	/* Turn on NOACK Support for QoS packets */
599 	OS_REG_WRITE(ah, AR_NOACK,
600 		SM(2, AR_NOACK_2BIT_VALUE) |
601 		SM(5, AR_NOACK_BIT_OFFSET) |
602 		SM(0, AR_NOACK_BYTE_OFFSET));
603 
604 	/* Get Antenna Gain reduction */
605 	if (IEEE80211_IS_CHAN_5GHZ(chan)) {
606 		ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_5, &twiceAntennaGain);
607 	} else {
608 		ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_2, &twiceAntennaGain);
609 	}
610 	twiceAntennaReduction =
611 		ath_hal_getantennareduction(ah, chan, twiceAntennaGain);
612 
613 	/* TPC for self-generated frames */
614 
615 	ackTpcPow = MS(ahp->ah_macTPC, AR_TPC_ACK);
616 	if ((ackTpcPow-ahp->ah_txPowerIndexOffset) > chan->ic_maxpower)
617 		ackTpcPow = chan->ic_maxpower+ahp->ah_txPowerIndexOffset;
618 
619 	if (ackTpcPow > (2*chan->ic_maxregpower - twiceAntennaReduction))
620 		ackTpcPow = (2*chan->ic_maxregpower - twiceAntennaReduction)
621 			+ ahp->ah_txPowerIndexOffset;
622 
623 	ctsTpcPow = MS(ahp->ah_macTPC, AR_TPC_CTS);
624 	if ((ctsTpcPow-ahp->ah_txPowerIndexOffset) > chan->ic_maxpower)
625 		ctsTpcPow = chan->ic_maxpower+ahp->ah_txPowerIndexOffset;
626 
627 	if (ctsTpcPow > (2*chan->ic_maxregpower - twiceAntennaReduction))
628 		ctsTpcPow = (2*chan->ic_maxregpower - twiceAntennaReduction)
629 			+ ahp->ah_txPowerIndexOffset;
630 
631 	chirpTpcPow = MS(ahp->ah_macTPC, AR_TPC_CHIRP);
632 	if ((chirpTpcPow-ahp->ah_txPowerIndexOffset) > chan->ic_maxpower)
633 		chirpTpcPow = chan->ic_maxpower+ahp->ah_txPowerIndexOffset;
634 
635 	if (chirpTpcPow > (2*chan->ic_maxregpower - twiceAntennaReduction))
636 		chirpTpcPow = (2*chan->ic_maxregpower - twiceAntennaReduction)
637 			+ ahp->ah_txPowerIndexOffset;
638 
639 	if (ackTpcPow > 63)
640 		ackTpcPow = 63;
641 	if (ctsTpcPow > 63)
642 		ctsTpcPow = 63;
643 	if (chirpTpcPow > 63)
644 		chirpTpcPow = 63;
645 
646 	powerVal = SM(ackTpcPow, AR_TPC_ACK) |
647 		SM(ctsTpcPow, AR_TPC_CTS) |
648 		SM(chirpTpcPow, AR_TPC_CHIRP);
649 
650 	OS_REG_WRITE(ah, AR_TPC, powerVal);
651 
652 	/* Restore user-specified settings */
653 	if (ahp->ah_miscMode != 0)
654 		OS_REG_WRITE(ah, AR_MISC_MODE, ahp->ah_miscMode);
655 	if (ahp->ah_sifstime != (u_int) -1)
656 		ar5212SetSifsTime(ah, ahp->ah_sifstime);
657 	if (ahp->ah_slottime != (u_int) -1)
658 		ar5212SetSlotTime(ah, ahp->ah_slottime);
659 	if (ahp->ah_acktimeout != (u_int) -1)
660 		ar5212SetAckTimeout(ah, ahp->ah_acktimeout);
661 	if (ahp->ah_ctstimeout != (u_int) -1)
662 		ar5212SetCTSTimeout(ah, ahp->ah_ctstimeout);
663 	if (AH_PRIVATE(ah)->ah_diagreg != 0)
664 		OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
665 
666 	AH_PRIVATE(ah)->ah_opmode = opmode;	/* record operating mode */
667 #if 0
668 done:
669 #endif
670 	if (bChannelChange && !IEEE80211_IS_CHAN_DFS(chan))
671 		chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
672 
673 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
674 
675 	RESTORE_CCK(ah, chan, isBmode);
676 
677 	OS_MARK(ah, AH_MARK_RESET_DONE, 0);
678 
679 	return AH_TRUE;
680 bad:
681 	RESTORE_CCK(ah, chan, isBmode);
682 
683 	OS_MARK(ah, AH_MARK_RESET_DONE, ecode);
684 	if (status != AH_NULL)
685 		*status = ecode;
686 	return AH_FALSE;
687 #undef FAIL
688 #undef N
689 }
690 
691 /*
692  * Call the rf backend to change the channel.
693  */
694 HAL_BOOL
695 ar5212SetChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
696 {
697 	struct ath_hal_5212 *ahp = AH5212(ah);
698 
699 	/* Change the synth */
700 	if (!ahp->ah_rfHal->setChannel(ah, chan))
701 		return AH_FALSE;
702 	return AH_TRUE;
703 }
704 
705 /*
706  * This channel change evaluates whether the selected hardware can
707  * perform a synthesizer-only channel change (no reset).  If the
708  * TX is not stopped, or the RFBus cannot be granted in the given
709  * time, the function returns false as a reset is necessary
710  */
711 HAL_BOOL
712 ar5212ChannelChange(struct ath_hal *ah, const struct ieee80211_channel *chan)
713 {
714 	uint32_t       ulCount;
715 	uint32_t   data, synthDelay, qnum;
716 	uint16_t   rfXpdGain[MAX_NUM_PDGAINS_PER_CHANNEL];
717 	HAL_BOOL    txStopped = AH_TRUE;
718 	HAL_CHANNEL_INTERNAL *ichan;
719 
720 	/*
721 	 * Map public channel to private.
722 	 */
723 	ichan = ath_hal_checkchannel(ah, chan);
724 
725 	/* TX must be stopped or RF Bus grant will not work */
726 	for (qnum = 0; qnum < AH_PRIVATE(ah)->ah_caps.halTotalQueues; qnum++) {
727 		if (ar5212NumTxPending(ah, qnum)) {
728 			txStopped = AH_FALSE;
729 			break;
730 		}
731 	}
732 	if (!txStopped)
733 		return AH_FALSE;
734 
735 	/* Kill last Baseband Rx Frame */
736 	OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, AR_PHY_RFBUS_REQ_REQUEST); /* Request analog bus grant */
737 	for (ulCount = 0; ulCount < 100; ulCount++) {
738 		if (OS_REG_READ(ah, AR_PHY_RFBUS_GNT))
739 			break;
740 		OS_DELAY(5);
741 	}
742 	if (ulCount >= 100)
743 		return AH_FALSE;
744 
745 	/* Change the synth */
746 	if (!ar5212SetChannel(ah, chan))
747 		return AH_FALSE;
748 
749 	/*
750 	 * Wait for the frequency synth to settle (synth goes on via PHY_ACTIVE_EN).
751 	 * Read the phy active delay register. Value is in 100ns increments.
752 	 */
753 	data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
754 	if (IEEE80211_IS_CHAN_B(chan)) {
755 		synthDelay = (4 * data) / 22;
756 	} else {
757 		synthDelay = data / 10;
758 	}
759 	OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
760 
761 	/* Setup the transmit power values. */
762 	if (!ar5212SetTransmitPower(ah, chan, rfXpdGain)) {
763 		HALDEBUG(ah, HAL_DEBUG_ANY,
764 		    "%s: error init'ing transmit power\n", __func__);
765 		return AH_FALSE;
766 	}
767 
768 	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
769 	if (IEEE80211_IS_CHAN_OFDM(chan)) {
770 		if (IS_5413(ah) ||
771 		    AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3)
772 			ar5212SetSpurMitigation(ah, chan);
773 		ar5212SetDeltaSlope(ah, chan);
774 	}
775 
776 	/* Release the RFBus Grant */
777 	OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, 0);
778 
779 	/* Start Noise Floor Cal */
780 	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
781 	return AH_TRUE;
782 }
783 
784 void
785 ar5212SetOperatingMode(struct ath_hal *ah, int opmode)
786 {
787 	uint32_t val;
788 
789 	val = OS_REG_READ(ah, AR_STA_ID1);
790 	val &= ~(AR_STA_ID1_STA_AP | AR_STA_ID1_ADHOC);
791 	switch (opmode) {
792 	case HAL_M_HOSTAP:
793 		OS_REG_WRITE(ah, AR_STA_ID1, val | AR_STA_ID1_STA_AP
794 					| AR_STA_ID1_KSRCH_MODE);
795 		OS_REG_CLR_BIT(ah, AR_CFG, AR_CFG_AP_ADHOC_INDICATION);
796 		break;
797 	case HAL_M_IBSS:
798 		OS_REG_WRITE(ah, AR_STA_ID1, val | AR_STA_ID1_ADHOC
799 					| AR_STA_ID1_KSRCH_MODE);
800 		OS_REG_SET_BIT(ah, AR_CFG, AR_CFG_AP_ADHOC_INDICATION);
801 		break;
802 	case HAL_M_STA:
803 	case HAL_M_MONITOR:
804 		OS_REG_WRITE(ah, AR_STA_ID1, val | AR_STA_ID1_KSRCH_MODE);
805 		break;
806 	}
807 }
808 
809 /*
810  * Places the PHY and Radio chips into reset.  A full reset
811  * must be called to leave this state.  The PCI/MAC/PCU are
812  * not placed into reset as we must receive interrupt to
813  * re-enable the hardware.
814  */
815 HAL_BOOL
816 ar5212PhyDisable(struct ath_hal *ah)
817 {
818 	return ar5212SetResetReg(ah, AR_RC_BB);
819 }
820 
821 /*
822  * Places all of hardware into reset
823  */
824 HAL_BOOL
825 ar5212Disable(struct ath_hal *ah)
826 {
827 	if (!ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
828 		return AH_FALSE;
829 	/*
830 	 * Reset the HW - PCI must be reset after the rest of the
831 	 * device has been reset.
832 	 */
833 	return ar5212SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI);
834 }
835 
836 /*
837  * Places the hardware into reset and then pulls it out of reset
838  *
839  * TODO: Only write the PLL if we're changing to or from CCK mode
840  *
841  * WARNING: The order of the PLL and mode registers must be correct.
842  */
843 HAL_BOOL
844 ar5212ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
845 {
846 
847 	OS_MARK(ah, AH_MARK_CHIPRESET, chan ? chan->ic_freq : 0);
848 
849 	/*
850 	 * Reset the HW - PCI must be reset after the rest of the
851 	 * device has been reset
852 	 */
853 	if (!ar5212SetResetReg(ah, AR_RC_MAC | AR_RC_BB | AR_RC_PCI))
854 		return AH_FALSE;
855 
856 	/* Bring out of sleep mode (AGAIN) */
857 	if (!ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
858 		return AH_FALSE;
859 
860 	/* Clear warm reset register */
861 	if (!ar5212SetResetReg(ah, 0))
862 		return AH_FALSE;
863 
864 	/*
865 	 * Perform warm reset before the mode/PLL/turbo registers
866 	 * are changed in order to deactivate the radio.  Mode changes
867 	 * with an active radio can result in corrupted shifts to the
868 	 * radio device.
869 	 */
870 
871 	/*
872 	 * Set CCK and Turbo modes correctly.
873 	 */
874 	if (chan != AH_NULL) {		/* NB: can be null during attach */
875 		uint32_t rfMode, phyPLL = 0, curPhyPLL, turbo;
876 
877 		if (IS_5413(ah)) {	/* NB: =>'s 5424 also */
878 			rfMode = AR_PHY_MODE_AR5112;
879 			if (IEEE80211_IS_CHAN_HALF(chan))
880 				rfMode |= AR_PHY_MODE_HALF;
881 			else if (IEEE80211_IS_CHAN_QUARTER(chan))
882 				rfMode |= AR_PHY_MODE_QUARTER;
883 
884 			if (IEEE80211_IS_CHAN_CCK(chan))
885 				phyPLL = AR_PHY_PLL_CTL_44_5112;
886 			else
887 				phyPLL = AR_PHY_PLL_CTL_40_5413;
888 		} else if (IS_RAD5111(ah)) {
889 			rfMode = AR_PHY_MODE_AR5111;
890 			if (IEEE80211_IS_CHAN_CCK(chan))
891 				phyPLL = AR_PHY_PLL_CTL_44;
892 			else
893 				phyPLL = AR_PHY_PLL_CTL_40;
894 			if (IEEE80211_IS_CHAN_HALF(chan))
895 				phyPLL = AR_PHY_PLL_CTL_HALF;
896 			else if (IEEE80211_IS_CHAN_QUARTER(chan))
897 				phyPLL = AR_PHY_PLL_CTL_QUARTER;
898 		} else {		/* 5112, 2413, 2316, 2317 */
899 			rfMode = AR_PHY_MODE_AR5112;
900 			if (IEEE80211_IS_CHAN_CCK(chan))
901 				phyPLL = AR_PHY_PLL_CTL_44_5112;
902 			else
903 				phyPLL = AR_PHY_PLL_CTL_40_5112;
904 			if (IEEE80211_IS_CHAN_HALF(chan))
905 				phyPLL |= AR_PHY_PLL_CTL_HALF;
906 			else if (IEEE80211_IS_CHAN_QUARTER(chan))
907 				phyPLL |= AR_PHY_PLL_CTL_QUARTER;
908 		}
909 		if (IEEE80211_IS_CHAN_G(chan))
910 			rfMode |= AR_PHY_MODE_DYNAMIC;
911 		else if (IEEE80211_IS_CHAN_OFDM(chan))
912 			rfMode |= AR_PHY_MODE_OFDM;
913 		else
914 			rfMode |= AR_PHY_MODE_CCK;
915 		if (IEEE80211_IS_CHAN_5GHZ(chan))
916 			rfMode |= AR_PHY_MODE_RF5GHZ;
917 		else
918 			rfMode |= AR_PHY_MODE_RF2GHZ;
919 		turbo = IEEE80211_IS_CHAN_TURBO(chan) ?
920 			(AR_PHY_FC_TURBO_MODE | AR_PHY_FC_TURBO_SHORT) : 0;
921 		curPhyPLL = OS_REG_READ(ah, AR_PHY_PLL_CTL);
922 		/*
923 		 * PLL, Mode, and Turbo values must be written in the correct
924 		 * order to ensure:
925 		 * - The PLL cannot be set to 44 unless the CCK or DYNAMIC
926 		 *   mode bit is set
927 		 * - Turbo cannot be set at the same time as CCK or DYNAMIC
928 		 */
929 		if (IEEE80211_IS_CHAN_CCK(chan)) {
930 			OS_REG_WRITE(ah, AR_PHY_TURBO, turbo);
931 			OS_REG_WRITE(ah, AR_PHY_MODE, rfMode);
932 			if (curPhyPLL != phyPLL) {
933 				OS_REG_WRITE(ah,  AR_PHY_PLL_CTL,  phyPLL);
934 				/* Wait for the PLL to settle */
935 				OS_DELAY(PLL_SETTLE_DELAY);
936 			}
937 		} else {
938 			if (curPhyPLL != phyPLL) {
939 				OS_REG_WRITE(ah,  AR_PHY_PLL_CTL,  phyPLL);
940 				/* Wait for the PLL to settle */
941 				OS_DELAY(PLL_SETTLE_DELAY);
942 			}
943 			OS_REG_WRITE(ah, AR_PHY_TURBO, turbo);
944 			OS_REG_WRITE(ah, AR_PHY_MODE, rfMode);
945 		}
946 	}
947 	return AH_TRUE;
948 }
949 
950 /*
951  * Recalibrate the lower PHY chips to account for temperature/environment
952  * changes.
953  */
954 HAL_BOOL
955 ar5212PerCalibrationN(struct ath_hal *ah,
956 	struct ieee80211_channel *chan,
957 	u_int chainMask, HAL_BOOL longCal, HAL_BOOL *isCalDone)
958 {
959 #define IQ_CAL_TRIES    10
960 	struct ath_hal_5212 *ahp = AH5212(ah);
961 	HAL_CHANNEL_INTERNAL *ichan;
962 	int32_t qCoff, qCoffDenom;
963 	int32_t iqCorrMeas, iCoff, iCoffDenom;
964 	uint32_t powerMeasQ, powerMeasI;
965 	HAL_BOOL isBmode = AH_FALSE;
966 
967 	OS_MARK(ah, AH_MARK_PERCAL, chan->ic_freq);
968 	*isCalDone = AH_FALSE;
969 	ichan = ath_hal_checkchannel(ah, chan);
970 	if (ichan == AH_NULL) {
971 		HALDEBUG(ah, HAL_DEBUG_ANY,
972 		    "%s: invalid channel %u/0x%x; no mapping\n",
973 		    __func__, chan->ic_freq, chan->ic_flags);
974 		return AH_FALSE;
975 	}
976 	SAVE_CCK(ah, chan, isBmode);
977 
978 	if (ahp->ah_bIQCalibration == IQ_CAL_DONE ||
979 	    ahp->ah_bIQCalibration == IQ_CAL_INACTIVE)
980 		*isCalDone = AH_TRUE;
981 
982 	/* IQ calibration in progress. Check to see if it has finished. */
983 	if (ahp->ah_bIQCalibration == IQ_CAL_RUNNING &&
984 	    !(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_DO_IQCAL)) {
985 		int i;
986 
987 		/* IQ Calibration has finished. */
988 		ahp->ah_bIQCalibration = IQ_CAL_INACTIVE;
989 		*isCalDone = AH_TRUE;
990 
991 		/* workaround for misgated IQ Cal results */
992 		i = 0;
993 		do {
994 			/* Read calibration results. */
995 			powerMeasI = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_I);
996 			powerMeasQ = OS_REG_READ(ah, AR_PHY_IQCAL_RES_PWR_MEAS_Q);
997 			iqCorrMeas = OS_REG_READ(ah, AR_PHY_IQCAL_RES_IQ_CORR_MEAS);
998 			if (powerMeasI && powerMeasQ)
999 				break;
1000 			/* Do we really need this??? */
1001 			OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1002 			    AR_PHY_TIMING_CTRL4_DO_IQCAL);
1003 		} while (++i < IQ_CAL_TRIES);
1004 
1005 		HALDEBUG(ah, HAL_DEBUG_PERCAL,
1006 		    "%s: IQ cal finished: %d tries\n", __func__, i);
1007 		HALDEBUG(ah, HAL_DEBUG_PERCAL,
1008 		    "%s: powerMeasI %u powerMeasQ %u iqCorrMeas %d\n",
1009 		    __func__, powerMeasI, powerMeasQ, iqCorrMeas);
1010 
1011 		/*
1012 		 * Prescale these values to remove 64-bit operation
1013 		 * requirement at the loss of a little precision.
1014 		 */
1015 		iCoffDenom = (powerMeasI / 2 + powerMeasQ / 2) / 128;
1016 		qCoffDenom = powerMeasQ / 128;
1017 
1018 		/* Protect against divide-by-0 and loss of sign bits. */
1019 		if (iCoffDenom != 0 && qCoffDenom >= 2) {
1020 			iCoff = (int8_t)(-iqCorrMeas) / iCoffDenom;
1021 			/* IQCORR_Q_I_COFF is a signed 6 bit number */
1022 			if (iCoff < -32) {
1023 				iCoff = -32;
1024 			} else if (iCoff > 31) {
1025 				iCoff = 31;
1026 			}
1027 
1028 			/* IQCORR_Q_Q_COFF is a signed 5 bit number */
1029 			qCoff = (powerMeasI / qCoffDenom) - 128;
1030 			if (qCoff < -16) {
1031 				qCoff = -16;
1032 			} else if (qCoff > 15) {
1033 				qCoff = 15;
1034 			}
1035 
1036 			HALDEBUG(ah, HAL_DEBUG_PERCAL,
1037 			    "%s: iCoff %d qCoff %d\n", __func__, iCoff, qCoff);
1038 
1039 			/* Write values and enable correction */
1040 			OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1041 				AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF, iCoff);
1042 			OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1043 				AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF, qCoff);
1044 			OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1045 				AR_PHY_TIMING_CTRL4_IQCORR_ENABLE);
1046 
1047 			ahp->ah_bIQCalibration = IQ_CAL_DONE;
1048 			ichan->privFlags |= CHANNEL_IQVALID;
1049 			ichan->iCoff = iCoff;
1050 			ichan->qCoff = qCoff;
1051 		}
1052 	} else if (!IEEE80211_IS_CHAN_B(chan) &&
1053 	    ahp->ah_bIQCalibration == IQ_CAL_DONE &&
1054 	    (ichan->privFlags & CHANNEL_IQVALID) == 0) {
1055 		/*
1056 		 * Start IQ calibration if configured channel has changed.
1057 		 * Use a magic number of 15 based on default value.
1058 		 */
1059 		OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1060 			AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX,
1061 			INIT_IQCAL_LOG_COUNT_MAX);
1062 		OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1063 			AR_PHY_TIMING_CTRL4_DO_IQCAL);
1064 		ahp->ah_bIQCalibration = IQ_CAL_RUNNING;
1065 	}
1066 	/* XXX EAR */
1067 
1068 	if (longCal) {
1069 		/* Check noise floor results */
1070 		ar5212GetNf(ah, chan);
1071 		if (!IEEE80211_IS_CHAN_CWINT(chan)) {
1072 			/* Perform cal for 5Ghz channels and any OFDM on 5112 */
1073 			if (IEEE80211_IS_CHAN_5GHZ(chan) ||
1074 			    (IS_RAD5112(ah) && IEEE80211_IS_CHAN_OFDM(chan)))
1075 				ar5212RequestRfgain(ah);
1076 		}
1077 	}
1078 	RESTORE_CCK(ah, chan, isBmode);
1079 
1080 	return AH_TRUE;
1081 #undef IQ_CAL_TRIES
1082 }
1083 
1084 HAL_BOOL
1085 ar5212PerCalibration(struct ath_hal *ah,  struct ieee80211_channel *chan,
1086 	HAL_BOOL *isIQdone)
1087 {
1088 	return ar5212PerCalibrationN(ah, chan, 0x1, AH_TRUE, isIQdone);
1089 }
1090 
1091 HAL_BOOL
1092 ar5212ResetCalValid(struct ath_hal *ah, const struct ieee80211_channel *chan)
1093 {
1094 	HAL_CHANNEL_INTERNAL *ichan;
1095 
1096 	ichan = ath_hal_checkchannel(ah, chan);
1097 	if (ichan == AH_NULL) {
1098 		HALDEBUG(ah, HAL_DEBUG_ANY,
1099 		    "%s: invalid channel %u/0x%x; no mapping\n",
1100 		    __func__, chan->ic_freq, chan->ic_flags);
1101 		return AH_FALSE;
1102 	}
1103 	ichan->privFlags &= ~CHANNEL_IQVALID;
1104 	return AH_TRUE;
1105 }
1106 
1107 /*
1108  * Write the given reset bit mask into the reset register
1109  */
1110 static HAL_BOOL
1111 ar5212SetResetReg(struct ath_hal *ah, uint32_t resetMask)
1112 {
1113 	uint32_t mask = resetMask ? resetMask : ~0;
1114 	HAL_BOOL rt;
1115 
1116 	/* XXX ar5212MacStop & co. */
1117 
1118 	if (AH_PRIVATE(ah)->ah_ispcie) {
1119 		resetMask &= ~AR_RC_PCI;
1120 	}
1121 
1122 	(void) OS_REG_READ(ah, AR_RXDP);/* flush any pending MMR writes */
1123 	OS_REG_WRITE(ah, AR_RC, resetMask);
1124 	OS_DELAY(15);			/* need to wait at least 128 clocks
1125 					   when reseting PCI before read */
1126 	mask &= (AR_RC_MAC | AR_RC_BB);
1127 	resetMask &= (AR_RC_MAC | AR_RC_BB);
1128 	rt = ath_hal_wait(ah, AR_RC, mask, resetMask);
1129         if ((resetMask & AR_RC_MAC) == 0) {
1130 		if (isBigEndian()) {
1131 			/*
1132 			 * Set CFG, little-endian for register
1133 			 * and descriptor accesses.
1134 			 */
1135 			mask = INIT_CONFIG_STATUS | AR_CFG_SWRD | AR_CFG_SWRG;
1136 #ifndef AH_NEED_DESC_SWAP
1137 			mask |= AR_CFG_SWTD;
1138 #endif
1139 			OS_REG_WRITE(ah, AR_CFG, LE_READ_4(&mask));
1140 		} else
1141 			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
1142 		if (ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
1143 			(void) OS_REG_READ(ah, AR_ISR_RAC);
1144 	}
1145 
1146 	/* track PHY power state so we don't try to r/w BB registers */
1147 	AH5212(ah)->ah_phyPowerOn = ((resetMask & AR_RC_BB) == 0);
1148 	return rt;
1149 }
1150 
1151 int16_t
1152 ar5212GetNoiseFloor(struct ath_hal *ah)
1153 {
1154 	int16_t nf = (OS_REG_READ(ah, AR_PHY(25)) >> 19) & 0x1ff;
1155 	if (nf & 0x100)
1156 		nf = 0 - ((nf ^ 0x1ff) + 1);
1157 	return nf;
1158 }
1159 
1160 static HAL_BOOL
1161 getNoiseFloorThresh(struct ath_hal *ah, const struct ieee80211_channel *chan,
1162 	int16_t *nft)
1163 {
1164 	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1165 
1166 	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1167 
1168 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1169 	case IEEE80211_CHAN_A:
1170 		*nft = ee->ee_noiseFloorThresh[headerInfo11A];
1171 		break;
1172 	case IEEE80211_CHAN_B:
1173 		*nft = ee->ee_noiseFloorThresh[headerInfo11B];
1174 		break;
1175 	case IEEE80211_CHAN_G:
1176 	case IEEE80211_CHAN_PUREG:	/* NB: really 108G */
1177 		*nft = ee->ee_noiseFloorThresh[headerInfo11G];
1178 		break;
1179 	default:
1180 		HALDEBUG(ah, HAL_DEBUG_ANY,
1181 		    "%s: invalid channel flags %u/0x%x\n",
1182 		    __func__, chan->ic_freq, chan->ic_flags);
1183 		return AH_FALSE;
1184 	}
1185 	return AH_TRUE;
1186 }
1187 
1188 /*
1189  * Setup the noise floor cal history buffer.
1190  */
1191 void
1192 ar5212InitNfCalHistBuffer(struct ath_hal *ah)
1193 {
1194 	struct ath_hal_5212 *ahp = AH5212(ah);
1195 	int i;
1196 
1197 	ahp->ah_nfCalHist.first_run = 1;
1198 	ahp->ah_nfCalHist.currIndex = 0;
1199 	ahp->ah_nfCalHist.privNF = AR5212_CCA_MAX_GOOD_VALUE;
1200 	ahp->ah_nfCalHist.invalidNFcount = AR512_NF_CAL_HIST_MAX;
1201 	for (i = 0; i < AR512_NF_CAL_HIST_MAX; i ++)
1202 		ahp->ah_nfCalHist.nfCalBuffer[i] = AR5212_CCA_MAX_GOOD_VALUE;
1203 }
1204 
1205 /*
1206  * Add a noise floor value to the ring buffer.
1207  */
1208 static __inline void
1209 updateNFHistBuff(struct ar5212NfCalHist *h, int16_t nf)
1210 {
1211  	h->nfCalBuffer[h->currIndex] = nf;
1212      	if (++h->currIndex >= AR512_NF_CAL_HIST_MAX)
1213 		h->currIndex = 0;
1214 }
1215 
1216 /*
1217  * Return the median noise floor value in the ring buffer.
1218  */
1219 int16_t
1220 ar5212GetNfHistMid(const int16_t calData[AR512_NF_CAL_HIST_MAX])
1221 {
1222 	int16_t sort[AR512_NF_CAL_HIST_MAX];
1223 	int i, j;
1224 
1225 	OS_MEMCPY(sort, calData, AR512_NF_CAL_HIST_MAX*sizeof(int16_t));
1226 	for (i = 0; i < AR512_NF_CAL_HIST_MAX-1; i ++) {
1227 		for (j = 1; j < AR512_NF_CAL_HIST_MAX-i; j ++) {
1228 			if (sort[j] > sort[j-1]) {
1229 				int16_t nf = sort[j];
1230 				sort[j] = sort[j-1];
1231 				sort[j-1] = nf;
1232 			}
1233 		}
1234 	}
1235 	return sort[(AR512_NF_CAL_HIST_MAX-1)>>1];
1236 }
1237 
1238 /*
1239  * Read the NF and check it against the noise floor threshhold
1240  */
1241 int16_t
1242 ar5212GetNf(struct ath_hal *ah, struct ieee80211_channel *chan)
1243 {
1244 	struct ath_hal_5212 *ahp = AH5212(ah);
1245 	struct ar5212NfCalHist *h = &ahp->ah_nfCalHist;
1246 	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1247 	int16_t nf, nfThresh;
1248  	int32_t val;
1249 
1250 	if (OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) {
1251 		HALDEBUG(ah, HAL_DEBUG_ANY,
1252 		    "%s: NF did not complete in calibration window\n", __func__);
1253 		ichan->rawNoiseFloor = h->privNF;	/* most recent value */
1254 		return ichan->rawNoiseFloor;
1255 	}
1256 
1257 	/*
1258 	 * Finished NF cal, check against threshold.
1259 	 */
1260 	nf = ar5212GetNoiseFloor(ah);
1261 	if (getNoiseFloorThresh(ah, chan, &nfThresh)) {
1262 		if (nf > nfThresh) {
1263 			HALDEBUG(ah, HAL_DEBUG_ANY,
1264 			    "%s: noise floor failed detected; detected %u, "
1265 			    "threshold %u\n", __func__, nf, nfThresh);
1266 			/*
1267 			 * NB: Don't discriminate 2.4 vs 5Ghz, if this
1268 			 *     happens it indicates a problem regardless
1269 			 *     of the band.
1270 			 */
1271 			chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
1272 			nf = 0;
1273 		}
1274 	} else
1275 		nf = 0;
1276 
1277 	/*
1278 	 * Pass through histogram and write median value as
1279 	 * calculated from the accrued window.  We require a
1280 	 * full window of in-range values to be seen before we
1281 	 * start using the history.
1282 	 */
1283 	updateNFHistBuff(h, nf);
1284 	if (h->first_run) {
1285 		if (nf < AR5212_CCA_MIN_BAD_VALUE ||
1286 		    nf > AR5212_CCA_MAX_HIGH_VALUE) {
1287 			nf = AR5212_CCA_MAX_GOOD_VALUE;
1288 			h->invalidNFcount = AR512_NF_CAL_HIST_MAX;
1289 		} else if (--(h->invalidNFcount) == 0) {
1290 			h->first_run = 0;
1291 			h->privNF = nf = ar5212GetNfHistMid(h->nfCalBuffer);
1292 		} else {
1293 			nf = AR5212_CCA_MAX_GOOD_VALUE;
1294 		}
1295 	} else {
1296 		h->privNF = nf = ar5212GetNfHistMid(h->nfCalBuffer);
1297 	}
1298 
1299 	val = OS_REG_READ(ah, AR_PHY(25));
1300 	val &= 0xFFFFFE00;
1301 	val |= (((uint32_t)nf << 1) & 0x1FF);
1302 	OS_REG_WRITE(ah, AR_PHY(25), val);
1303 	OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_ENABLE_NF);
1304 	OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NO_UPDATE_NF);
1305 	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
1306 
1307 	if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF, 0)) {
1308 #ifdef AH_DEBUG
1309 		ath_hal_printf(ah, "%s: AGC not ready AGC_CONTROL 0x%x\n",
1310 		    __func__, OS_REG_READ(ah, AR_PHY_AGC_CONTROL));
1311 #endif
1312 	}
1313 
1314 	/*
1315 	 * Now load a high maxCCAPower value again so that we're
1316 	 * not capped by the median we just loaded
1317 	 */
1318 	val &= 0xFFFFFE00;
1319 	val |= (((uint32_t)(-50) << 1) & 0x1FF);
1320 	OS_REG_WRITE(ah, AR_PHY(25), val);
1321 	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_ENABLE_NF);
1322 	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NO_UPDATE_NF);
1323 	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
1324 
1325 	return (ichan->rawNoiseFloor = nf);
1326 }
1327 
1328 /*
1329  * Set up compression configuration registers
1330  */
1331 void
1332 ar5212SetCompRegs(struct ath_hal *ah)
1333 {
1334 	struct ath_hal_5212 *ahp = AH5212(ah);
1335 	int i;
1336 
1337         /* Check if h/w supports compression */
1338 	if (!AH_PRIVATE(ah)->ah_caps.halCompressSupport)
1339 		return;
1340 
1341 	OS_REG_WRITE(ah, AR_DCCFG, 1);
1342 
1343 	OS_REG_WRITE(ah, AR_CCFG,
1344 		(AR_COMPRESSION_WINDOW_SIZE >> 8) & AR_CCFG_WIN_M);
1345 
1346 	OS_REG_WRITE(ah, AR_CCFG,
1347 		OS_REG_READ(ah, AR_CCFG) | AR_CCFG_MIB_INT_EN);
1348 	OS_REG_WRITE(ah, AR_CCUCFG,
1349 		AR_CCUCFG_RESET_VAL | AR_CCUCFG_CATCHUP_EN);
1350 
1351 	OS_REG_WRITE(ah, AR_CPCOVF, 0);
1352 
1353 	/* reset decompression mask */
1354 	for (i = 0; i < HAL_DECOMP_MASK_SIZE; i++) {
1355 		OS_REG_WRITE(ah, AR_DCM_A, i);
1356 		OS_REG_WRITE(ah, AR_DCM_D, ahp->ah_decompMask[i]);
1357 	}
1358 }
1359 
1360 HAL_BOOL
1361 ar5212SetAntennaSwitchInternal(struct ath_hal *ah, HAL_ANT_SETTING settings,
1362 	const struct ieee80211_channel *chan)
1363 {
1364 #define	ANT_SWITCH_TABLE1	AR_PHY(88)
1365 #define	ANT_SWITCH_TABLE2	AR_PHY(89)
1366 	struct ath_hal_5212 *ahp = AH5212(ah);
1367 	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1368 	uint32_t antSwitchA, antSwitchB;
1369 	int ix;
1370 
1371 	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1372 	HALASSERT(ahp->ah_phyPowerOn);
1373 
1374 	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1375 	case IEEE80211_CHAN_A:
1376 		ix = 0;
1377 		break;
1378 	case IEEE80211_CHAN_G:
1379 	case IEEE80211_CHAN_PUREG:		/* NB: 108G */
1380 		ix = 2;
1381 		break;
1382 	case IEEE80211_CHAN_B:
1383 		if (IS_2425(ah) || IS_2417(ah)) {
1384 			/* NB: Nala/Swan: 11b is handled using 11g */
1385 			ix = 2;
1386 		} else
1387 			ix = 1;
1388 		break;
1389 	default:
1390 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1391 		    __func__, chan->ic_flags);
1392 		return AH_FALSE;
1393 	}
1394 
1395 	antSwitchA =  ee->ee_antennaControl[1][ix]
1396 		   | (ee->ee_antennaControl[2][ix] << 6)
1397 		   | (ee->ee_antennaControl[3][ix] << 12)
1398 		   | (ee->ee_antennaControl[4][ix] << 18)
1399 		   | (ee->ee_antennaControl[5][ix] << 24)
1400 		   ;
1401 	antSwitchB =  ee->ee_antennaControl[6][ix]
1402 		   | (ee->ee_antennaControl[7][ix] << 6)
1403 		   | (ee->ee_antennaControl[8][ix] << 12)
1404 		   | (ee->ee_antennaControl[9][ix] << 18)
1405 		   | (ee->ee_antennaControl[10][ix] << 24)
1406 		   ;
1407 	/*
1408 	 * For fixed antenna, give the same setting for both switch banks
1409 	 */
1410 	switch (settings) {
1411 	case HAL_ANT_FIXED_A:
1412 		antSwitchB = antSwitchA;
1413 		break;
1414 	case HAL_ANT_FIXED_B:
1415 		antSwitchA = antSwitchB;
1416 		break;
1417 	case HAL_ANT_VARIABLE:
1418 		break;
1419 	default:
1420 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: bad antenna setting %u\n",
1421 		    __func__, settings);
1422 		return AH_FALSE;
1423 	}
1424 	if (antSwitchB == antSwitchA) {
1425 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
1426 		    "%s: Setting fast diversity off.\n", __func__);
1427 		OS_REG_CLR_BIT(ah,AR_PHY_CCK_DETECT,
1428 			       AR_PHY_CCK_DETECT_BB_ENABLE_ANT_FAST_DIV);
1429 		ahp->ah_diversity = AH_FALSE;
1430 	} else {
1431 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
1432 		    "%s: Setting fast diversity on.\n", __func__);
1433 		OS_REG_SET_BIT(ah,AR_PHY_CCK_DETECT,
1434 			       AR_PHY_CCK_DETECT_BB_ENABLE_ANT_FAST_DIV);
1435 		ahp->ah_diversity = AH_TRUE;
1436 	}
1437 	ahp->ah_antControl = settings;
1438 
1439 	OS_REG_WRITE(ah, ANT_SWITCH_TABLE1, antSwitchA);
1440 	OS_REG_WRITE(ah, ANT_SWITCH_TABLE2, antSwitchB);
1441 
1442 	return AH_TRUE;
1443 #undef ANT_SWITCH_TABLE2
1444 #undef ANT_SWITCH_TABLE1
1445 }
1446 
1447 HAL_BOOL
1448 ar5212IsSpurChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
1449 {
1450 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1451 	uint32_t clockFreq =
1452 	    ((IS_5413(ah) || IS_RAD5112_ANY(ah) || IS_2417(ah)) ? 40 : 32);
1453 	return ( ((freq % clockFreq) != 0)
1454               && (((freq % clockFreq) < 10)
1455              || (((freq) % clockFreq) > 22)) );
1456 }
1457 
1458 /*
1459  * Read EEPROM header info and program the device for correct operation
1460  * given the channel value.
1461  */
1462 HAL_BOOL
1463 ar5212SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1464 {
1465 #define NO_FALSE_DETECT_BACKOFF   2
1466 #define CB22_FALSE_DETECT_BACKOFF 6
1467 #define	AR_PHY_BIS(_ah, _reg, _mask, _val) \
1468 	OS_REG_WRITE(_ah, AR_PHY(_reg), \
1469 		(OS_REG_READ(_ah, AR_PHY(_reg)) & _mask) | (_val));
1470 	struct ath_hal_5212 *ahp = AH5212(ah);
1471 	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1472 	int arrayMode, falseDectectBackoff;
1473 	int is2GHz = IEEE80211_IS_CHAN_2GHZ(chan);
1474 	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1475 	int8_t adcDesiredSize, pgaDesiredSize;
1476 	uint16_t switchSettling, txrxAtten, rxtxMargin;
1477 	int iCoff, qCoff;
1478 
1479 	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1480 
1481 	switch (chan->ic_flags & IEEE80211_CHAN_ALLTURBOFULL) {
1482 	case IEEE80211_CHAN_A:
1483 	case IEEE80211_CHAN_ST:
1484 		arrayMode = headerInfo11A;
1485 		if (!IS_RAD5112_ANY(ah) && !IS_2413(ah) && !IS_5413(ah))
1486 			OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
1487 				AR_PHY_FRAME_CTL_TX_CLIP,
1488 				ahp->ah_gainValues.currStep->paramVal[GP_TXCLIP]);
1489 		break;
1490 	case IEEE80211_CHAN_B:
1491 		arrayMode = headerInfo11B;
1492 		break;
1493 	case IEEE80211_CHAN_G:
1494 	case IEEE80211_CHAN_108G:
1495 		arrayMode = headerInfo11G;
1496 		break;
1497 	default:
1498 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1499 		    __func__, chan->ic_flags);
1500 		return AH_FALSE;
1501 	}
1502 
1503 	/* Set the antenna register(s) correctly for the chip revision */
1504 	AR_PHY_BIS(ah, 68, 0xFFFFFC06,
1505 		(ee->ee_antennaControl[0][arrayMode] << 4) | 0x1);
1506 
1507 	ar5212SetAntennaSwitchInternal(ah, ahp->ah_antControl, chan);
1508 
1509 	/* Set the Noise Floor Thresh on ar5211 devices */
1510 	OS_REG_WRITE(ah, AR_PHY(90),
1511 		(ee->ee_noiseFloorThresh[arrayMode] & 0x1FF)
1512 		| (1 << 9));
1513 
1514 	if (ee->ee_version >= AR_EEPROM_VER5_0 && IEEE80211_IS_CHAN_TURBO(chan)) {
1515 		switchSettling = ee->ee_switchSettlingTurbo[is2GHz];
1516 		adcDesiredSize = ee->ee_adcDesiredSizeTurbo[is2GHz];
1517 		pgaDesiredSize = ee->ee_pgaDesiredSizeTurbo[is2GHz];
1518 		txrxAtten = ee->ee_txrxAttenTurbo[is2GHz];
1519 		rxtxMargin = ee->ee_rxtxMarginTurbo[is2GHz];
1520 	} else {
1521 		switchSettling = ee->ee_switchSettling[arrayMode];
1522 		adcDesiredSize = ee->ee_adcDesiredSize[arrayMode];
1523 		pgaDesiredSize = ee->ee_pgaDesiredSize[is2GHz];
1524 		txrxAtten = ee->ee_txrxAtten[is2GHz];
1525 		rxtxMargin = ee->ee_rxtxMargin[is2GHz];
1526 	}
1527 
1528 	OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING,
1529 			 AR_PHY_SETTLING_SWITCH, switchSettling);
1530 	OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ,
1531 			 AR_PHY_DESIRED_SZ_ADC, adcDesiredSize);
1532 	OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ,
1533 			 AR_PHY_DESIRED_SZ_PGA, pgaDesiredSize);
1534 	OS_REG_RMW_FIELD(ah, AR_PHY_RXGAIN,
1535 			 AR_PHY_RXGAIN_TXRX_ATTEN, txrxAtten);
1536 	OS_REG_WRITE(ah, AR_PHY(13),
1537 		(ee->ee_txEndToXPAOff[arrayMode] << 24)
1538 		| (ee->ee_txEndToXPAOff[arrayMode] << 16)
1539 		| (ee->ee_txFrameToXPAOn[arrayMode] << 8)
1540 		| ee->ee_txFrameToXPAOn[arrayMode]);
1541 	AR_PHY_BIS(ah, 10, 0xFFFF00FF,
1542 		ee->ee_txEndToXLNAOn[arrayMode] << 8);
1543 	AR_PHY_BIS(ah, 25, 0xFFF80FFF,
1544 		(ee->ee_thresh62[arrayMode] << 12) & 0x7F000);
1545 
1546 	/*
1547 	 * False detect backoff - suspected 32 MHz spur causes false
1548 	 * detects in OFDM, causing Tx Hangs.  Decrease weak signal
1549 	 * sensitivity for this card.
1550 	 */
1551 	falseDectectBackoff = NO_FALSE_DETECT_BACKOFF;
1552 	if (ee->ee_version < AR_EEPROM_VER3_3) {
1553 		/* XXX magic number */
1554 		if (AH_PRIVATE(ah)->ah_subvendorid == 0x1022 &&
1555 		    IEEE80211_IS_CHAN_OFDM(chan))
1556 			falseDectectBackoff += CB22_FALSE_DETECT_BACKOFF;
1557 	} else {
1558 		if (ar5212IsSpurChannel(ah, chan))
1559 			falseDectectBackoff += ee->ee_falseDetectBackoff[arrayMode];
1560 	}
1561 	AR_PHY_BIS(ah, 73, 0xFFFFFF01, (falseDectectBackoff << 1) & 0xFE);
1562 
1563 	if (ichan->privFlags & CHANNEL_IQVALID) {
1564 		iCoff = ichan->iCoff;
1565 		qCoff = ichan->qCoff;
1566 	} else {
1567 		iCoff = ee->ee_iqCalI[is2GHz];
1568 		qCoff = ee->ee_iqCalQ[is2GHz];
1569 	}
1570 
1571 	/* write previous IQ results */
1572 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1573 		AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF, iCoff);
1574 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1575 		AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF, qCoff);
1576 	OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1577 		AR_PHY_TIMING_CTRL4_IQCORR_ENABLE);
1578 
1579 	if (ee->ee_version >= AR_EEPROM_VER4_1) {
1580 		if (!IEEE80211_IS_CHAN_108G(chan) || ee->ee_version >= AR_EEPROM_VER5_0)
1581 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ,
1582 				AR_PHY_GAIN_2GHZ_RXTX_MARGIN, rxtxMargin);
1583 	}
1584 	if (ee->ee_version >= AR_EEPROM_VER5_1) {
1585 		/* for now always disabled */
1586 		OS_REG_WRITE(ah,  AR_PHY_HEAVY_CLIP_ENABLE,  0);
1587 	}
1588 
1589 	return AH_TRUE;
1590 #undef AR_PHY_BIS
1591 #undef NO_FALSE_DETECT_BACKOFF
1592 #undef CB22_FALSE_DETECT_BACKOFF
1593 }
1594 
1595 /*
1596  * Apply Spur Immunity to Boards that require it.
1597  * Applies only to OFDM RX operation.
1598  */
1599 
1600 void
1601 ar5212SetSpurMitigation(struct ath_hal *ah,
1602 	const struct ieee80211_channel *chan)
1603 {
1604 	uint32_t pilotMask[2] = {0, 0}, binMagMask[4] = {0, 0, 0 , 0};
1605 	uint16_t i, finalSpur, curChanAsSpur, binWidth = 0, spurDetectWidth, spurChan;
1606 	int32_t spurDeltaPhase = 0, spurFreqSd = 0, spurOffset, binOffsetNumT16, curBinOffset;
1607 	int16_t numBinOffsets;
1608 	static const uint16_t magMapFor4[4] = {1, 2, 2, 1};
1609 	static const uint16_t magMapFor3[3] = {1, 2, 1};
1610 	const uint16_t *pMagMap;
1611 	HAL_BOOL is2GHz = IEEE80211_IS_CHAN_2GHZ(chan);
1612 	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1613 	uint32_t val;
1614 
1615 #define CHAN_TO_SPUR(_f, _freq)   ( ((_freq) - ((_f) ? 2300 : 4900)) * 10 )
1616 	if (IS_2417(ah)) {
1617 		HALDEBUG(ah, HAL_DEBUG_RFPARAM, "%s: no spur mitigation\n",
1618 		    __func__);
1619 		return;
1620 	}
1621 
1622 	curChanAsSpur = CHAN_TO_SPUR(is2GHz, ichan->channel);
1623 
1624 	if (ichan->mainSpur) {
1625 		/* Pull out the saved spur value */
1626 		finalSpur = ichan->mainSpur;
1627 	} else {
1628 		/*
1629 		 * Check if spur immunity should be performed for this channel
1630 		 * Should only be performed once per channel and then saved
1631 		 */
1632 		finalSpur = AR_NO_SPUR;
1633 		spurDetectWidth = HAL_SPUR_CHAN_WIDTH;
1634 		if (IEEE80211_IS_CHAN_TURBO(chan))
1635 			spurDetectWidth *= 2;
1636 
1637 		/* Decide if any spur affects the current channel */
1638 		for (i = 0; i < AR_EEPROM_MODAL_SPURS; i++) {
1639 			spurChan = ath_hal_getSpurChan(ah, i, is2GHz);
1640 			if (spurChan == AR_NO_SPUR) {
1641 				break;
1642 			}
1643 			if ((curChanAsSpur - spurDetectWidth <= (spurChan & HAL_SPUR_VAL_MASK)) &&
1644 			    (curChanAsSpur + spurDetectWidth >= (spurChan & HAL_SPUR_VAL_MASK))) {
1645 				finalSpur = spurChan & HAL_SPUR_VAL_MASK;
1646 				break;
1647 			}
1648 		}
1649 		/* Save detected spur (or no spur) for this channel */
1650 		ichan->mainSpur = finalSpur;
1651 	}
1652 
1653 	/* Write spur immunity data */
1654 	if (finalSpur == AR_NO_SPUR) {
1655 		/* Disable Spur Immunity Regs if they appear set */
1656 		if (OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER) {
1657 			/* Clear Spur Delta Phase, Spur Freq, and enable bits */
1658 			OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_RATE, 0);
1659 			val = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4);
1660 			val &= ~(AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER |
1661 				 AR_PHY_TIMING_CTRL4_ENABLE_CHAN_MASK |
1662 				 AR_PHY_TIMING_CTRL4_ENABLE_PILOT_MASK);
1663 			OS_REG_WRITE(ah, AR_PHY_MASK_CTL, val);
1664 			OS_REG_WRITE(ah, AR_PHY_TIMING11, 0);
1665 
1666 			/* Clear pilot masks */
1667 			OS_REG_WRITE(ah, AR_PHY_TIMING7, 0);
1668 			OS_REG_RMW_FIELD(ah, AR_PHY_TIMING8, AR_PHY_TIMING8_PILOT_MASK_2, 0);
1669 			OS_REG_WRITE(ah, AR_PHY_TIMING9, 0);
1670 			OS_REG_RMW_FIELD(ah, AR_PHY_TIMING10, AR_PHY_TIMING10_PILOT_MASK_2, 0);
1671 
1672 			/* Clear magnitude masks */
1673 			OS_REG_WRITE(ah, AR_PHY_BIN_MASK_1, 0);
1674 			OS_REG_WRITE(ah, AR_PHY_BIN_MASK_2, 0);
1675 			OS_REG_WRITE(ah, AR_PHY_BIN_MASK_3, 0);
1676 			OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_MASK_4, 0);
1677 			OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_1, 0);
1678 			OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_2, 0);
1679 			OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_3, 0);
1680 			OS_REG_RMW_FIELD(ah, AR_PHY_BIN_MASK2_4, AR_PHY_BIN_MASK2_4_MASK_4, 0);
1681 		}
1682 	} else {
1683 		spurOffset = finalSpur - curChanAsSpur;
1684 		/*
1685 		 * Spur calculations:
1686 		 * spurDeltaPhase is (spurOffsetIn100KHz / chipFrequencyIn100KHz) << 21
1687 		 * spurFreqSd is (spurOffsetIn100KHz / sampleFrequencyIn100KHz) << 11
1688 		 */
1689 		if (IEEE80211_IS_CHAN_TURBO(chan)) {
1690 			/* Chip Frequency & sampleFrequency are 80 MHz */
1691 			spurDeltaPhase = (spurOffset << 16) / 25;
1692 			spurFreqSd = spurDeltaPhase >> 10;
1693 			binWidth = HAL_BIN_WIDTH_TURBO_100HZ;
1694 		} else if (IEEE80211_IS_CHAN_G(chan)) {
1695 			/* Chip Frequency is 44MHz, sampleFrequency is 40 MHz */
1696 			spurFreqSd = (spurOffset << 8) / 55;
1697 			spurDeltaPhase = (spurOffset << 17) / 25;
1698 			binWidth = HAL_BIN_WIDTH_BASE_100HZ;
1699 		} else {
1700 			HALASSERT(!IEEE80211_IS_CHAN_B(chan));
1701 			/* Chip Frequency & sampleFrequency are 40 MHz */
1702 			spurDeltaPhase = (spurOffset << 17) / 25;
1703 			spurFreqSd = spurDeltaPhase >> 10;
1704 			binWidth = HAL_BIN_WIDTH_BASE_100HZ;
1705 		}
1706 
1707 		/* Compute Pilot Mask */
1708 		binOffsetNumT16 = ((spurOffset * 1000) << 4) / binWidth;
1709 		/* The spur is on a bin if it's remainder at times 16 is 0 */
1710 		if (binOffsetNumT16 & 0xF) {
1711 			numBinOffsets = 4;
1712 			pMagMap = magMapFor4;
1713 		} else {
1714 			numBinOffsets = 3;
1715 			pMagMap = magMapFor3;
1716 		}
1717 		for (i = 0; i < numBinOffsets; i++) {
1718 			if ((binOffsetNumT16 >> 4) > HAL_MAX_BINS_ALLOWED) {
1719 				HALDEBUG(ah, HAL_DEBUG_ANY,
1720 				    "Too man bins in spur mitigation\n");
1721 				return;
1722 			}
1723 
1724 			/* Get Pilot Mask values */
1725 			curBinOffset = (binOffsetNumT16 >> 4) + i + 25;
1726 			if ((curBinOffset >= 0) && (curBinOffset <= 32)) {
1727 				if (curBinOffset <= 25)
1728 					pilotMask[0] |= 1 << curBinOffset;
1729 				else if (curBinOffset >= 27)
1730 					pilotMask[0] |= 1 << (curBinOffset - 1);
1731 			} else if ((curBinOffset >= 33) && (curBinOffset <= 52))
1732 				pilotMask[1] |= 1 << (curBinOffset - 33);
1733 
1734 			/* Get viterbi values */
1735 			if ((curBinOffset >= -1) && (curBinOffset <= 14))
1736 				binMagMask[0] |= pMagMap[i] << (curBinOffset + 1) * 2;
1737 			else if ((curBinOffset >= 15) && (curBinOffset <= 30))
1738 				binMagMask[1] |= pMagMap[i] << (curBinOffset - 15) * 2;
1739 			else if ((curBinOffset >= 31) && (curBinOffset <= 46))
1740 				binMagMask[2] |= pMagMap[i] << (curBinOffset -31) * 2;
1741 			else if((curBinOffset >= 47) && (curBinOffset <= 53))
1742 				binMagMask[3] |= pMagMap[i] << (curBinOffset -47) * 2;
1743 		}
1744 
1745 		/* Write Spur Delta Phase, Spur Freq, and enable bits */
1746 		OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_RATE, 0xFF);
1747 		val = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4);
1748 		val |= (AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER |
1749 			AR_PHY_TIMING_CTRL4_ENABLE_CHAN_MASK |
1750 			AR_PHY_TIMING_CTRL4_ENABLE_PILOT_MASK);
1751 		OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4, val);
1752 		OS_REG_WRITE(ah, AR_PHY_TIMING11, AR_PHY_TIMING11_USE_SPUR_IN_AGC |
1753 			     SM(spurFreqSd, AR_PHY_TIMING11_SPUR_FREQ_SD) |
1754 			     SM(spurDeltaPhase, AR_PHY_TIMING11_SPUR_DELTA_PHASE));
1755 
1756 		/* Write pilot masks */
1757 		OS_REG_WRITE(ah, AR_PHY_TIMING7, pilotMask[0]);
1758 		OS_REG_RMW_FIELD(ah, AR_PHY_TIMING8, AR_PHY_TIMING8_PILOT_MASK_2, pilotMask[1]);
1759 		OS_REG_WRITE(ah, AR_PHY_TIMING9, pilotMask[0]);
1760 		OS_REG_RMW_FIELD(ah, AR_PHY_TIMING10, AR_PHY_TIMING10_PILOT_MASK_2, pilotMask[1]);
1761 
1762 		/* Write magnitude masks */
1763 		OS_REG_WRITE(ah, AR_PHY_BIN_MASK_1, binMagMask[0]);
1764 		OS_REG_WRITE(ah, AR_PHY_BIN_MASK_2, binMagMask[1]);
1765 		OS_REG_WRITE(ah, AR_PHY_BIN_MASK_3, binMagMask[2]);
1766 		OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_MASK_4, binMagMask[3]);
1767 		OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_1, binMagMask[0]);
1768 		OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_2, binMagMask[1]);
1769 		OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_3, binMagMask[2]);
1770 		OS_REG_RMW_FIELD(ah, AR_PHY_BIN_MASK2_4, AR_PHY_BIN_MASK2_4_MASK_4, binMagMask[3]);
1771 	}
1772 #undef CHAN_TO_SPUR
1773 }
1774 
1775 
1776 /*
1777  * Delta slope coefficient computation.
1778  * Required for OFDM operation.
1779  */
1780 void
1781 ar5212SetDeltaSlope(struct ath_hal *ah, const struct ieee80211_channel *chan)
1782 {
1783 #define COEF_SCALE_S 24
1784 #define INIT_CLOCKMHZSCALED	0x64000000
1785 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1786 	unsigned long coef_scaled, coef_exp, coef_man, ds_coef_exp, ds_coef_man;
1787 	unsigned long clockMhzScaled = INIT_CLOCKMHZSCALED;
1788 
1789 	if (IEEE80211_IS_CHAN_TURBO(chan))
1790 		clockMhzScaled *= 2;
1791 	/* half and quarter rate can divide the scaled clock by 2 or 4 respectively */
1792 	/* scale for selected channel bandwidth */
1793 	if (IEEE80211_IS_CHAN_HALF(chan)) {
1794 		clockMhzScaled = clockMhzScaled >> 1;
1795 	} else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
1796 		clockMhzScaled = clockMhzScaled >> 2;
1797 	}
1798 
1799 	/*
1800 	 * ALGO -> coef = 1e8/fcarrier*fclock/40;
1801 	 * scaled coef to provide precision for this floating calculation
1802 	 */
1803 	coef_scaled = clockMhzScaled / freq;
1804 
1805 	/*
1806 	 * ALGO -> coef_exp = 14-floor(log2(coef));
1807 	 * floor(log2(x)) is the highest set bit position
1808 	 */
1809 	for (coef_exp = 31; coef_exp > 0; coef_exp--)
1810 		if ((coef_scaled >> coef_exp) & 0x1)
1811 			break;
1812 	/* A coef_exp of 0 is a legal bit position but an unexpected coef_exp */
1813 	HALASSERT(coef_exp);
1814 	coef_exp = 14 - (coef_exp - COEF_SCALE_S);
1815 
1816 	/*
1817 	 * ALGO -> coef_man = floor(coef* 2^coef_exp+0.5);
1818 	 * The coefficient is already shifted up for scaling
1819 	 */
1820 	coef_man = coef_scaled + (1 << (COEF_SCALE_S - coef_exp - 1));
1821 	ds_coef_man = coef_man >> (COEF_SCALE_S - coef_exp);
1822 	ds_coef_exp = coef_exp - 16;
1823 
1824 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
1825 		AR_PHY_TIMING3_DSC_MAN, ds_coef_man);
1826 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
1827 		AR_PHY_TIMING3_DSC_EXP, ds_coef_exp);
1828 #undef INIT_CLOCKMHZSCALED
1829 #undef COEF_SCALE_S
1830 }
1831 
1832 /*
1833  * Set a limit on the overall output power.  Used for dynamic
1834  * transmit power control and the like.
1835  *
1836  * NB: limit is in units of 0.5 dbM.
1837  */
1838 HAL_BOOL
1839 ar5212SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
1840 {
1841 	/* XXX blech, construct local writable copy */
1842 	struct ieee80211_channel dummy = *AH_PRIVATE(ah)->ah_curchan;
1843 	uint16_t dummyXpdGains[2];
1844 	HAL_BOOL isBmode;
1845 
1846 	SAVE_CCK(ah, &dummy, isBmode);
1847 	AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
1848 	return ar5212SetTransmitPower(ah, &dummy, dummyXpdGains);
1849 }
1850 
1851 /*
1852  * Set the transmit power in the baseband for the given
1853  * operating channel and mode.
1854  */
1855 HAL_BOOL
1856 ar5212SetTransmitPower(struct ath_hal *ah,
1857 	const struct ieee80211_channel *chan, uint16_t *rfXpdGain)
1858 {
1859 #define	POW_OFDM(_r, _s)	(((0 & 1)<< ((_s)+6)) | (((_r) & 0x3f) << (_s)))
1860 #define	POW_CCK(_r, _s)		(((_r) & 0x3f) << (_s))
1861 #define	N(a)			(sizeof (a) / sizeof (a[0]))
1862 	static const uint16_t tpcScaleReductionTable[5] =
1863 		{ 0, 3, 6, 9, MAX_RATE_POWER };
1864 	struct ath_hal_5212 *ahp = AH5212(ah);
1865 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1866 	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1867 	int16_t minPower, maxPower, tpcInDb, powerLimit;
1868 	int i;
1869 
1870 	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1871 
1872 	OS_MEMZERO(ahp->ah_pcdacTable, ahp->ah_pcdacTableSize);
1873 	OS_MEMZERO(ahp->ah_ratesArray, sizeof(ahp->ah_ratesArray));
1874 
1875 	powerLimit = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
1876 	if (powerLimit >= MAX_RATE_POWER || powerLimit == 0)
1877 		tpcInDb = tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale];
1878 	else
1879 		tpcInDb = 0;
1880 	if (!ar5212SetRateTable(ah, chan, tpcInDb, powerLimit,
1881 				AH_TRUE, &minPower, &maxPower)) {
1882 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set rate table\n",
1883 		    __func__);
1884 		return AH_FALSE;
1885 	}
1886 	if (!ahp->ah_rfHal->setPowerTable(ah,
1887 		&minPower, &maxPower, chan, rfXpdGain)) {
1888 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set power table\n",
1889 		    __func__);
1890 		return AH_FALSE;
1891 	}
1892 
1893 	/*
1894 	 * Adjust XR power/rate up by 2 dB to account for greater peak
1895 	 * to avg ratio - except in newer avg power designs
1896 	 */
1897 	if (!IS_2413(ah) && !IS_5413(ah))
1898 		ahp->ah_ratesArray[15] += 4;
1899 	/*
1900 	 * txPowerIndexOffset is set by the SetPowerTable() call -
1901 	 *  adjust the rate table
1902 	 */
1903 	for (i = 0; i < N(ahp->ah_ratesArray); i++) {
1904 		ahp->ah_ratesArray[i] += ahp->ah_txPowerIndexOffset;
1905 		if (ahp->ah_ratesArray[i] > 63)
1906 			ahp->ah_ratesArray[i] = 63;
1907 	}
1908 
1909 	if (ee->ee_eepMap < 2) {
1910 		/*
1911 		 * Correct gain deltas for 5212 G operation -
1912 		 * Removed with revised chipset
1913 		 */
1914 		if (AH_PRIVATE(ah)->ah_phyRev < AR_PHY_CHIP_ID_REV_2 &&
1915 		    IEEE80211_IS_CHAN_G(chan)) {
1916 			uint16_t cckOfdmPwrDelta;
1917 
1918 			if (freq == 2484)
1919 				cckOfdmPwrDelta = SCALE_OC_DELTA(
1920 					ee->ee_cckOfdmPwrDelta -
1921 					ee->ee_scaledCh14FilterCckDelta);
1922 			else
1923 				cckOfdmPwrDelta = SCALE_OC_DELTA(
1924 					ee->ee_cckOfdmPwrDelta);
1925 			ar5212CorrectGainDelta(ah, cckOfdmPwrDelta);
1926 		}
1927 		/*
1928 		 * Finally, write the power values into the
1929 		 * baseband power table
1930 		 */
1931 		for (i = 0; i < (PWR_TABLE_SIZE/2); i++) {
1932 			OS_REG_WRITE(ah, AR_PHY_PCDAC_TX_POWER(i),
1933 				 ((((ahp->ah_pcdacTable[2*i + 1] << 8) | 0xff) & 0xffff) << 16)
1934 				| (((ahp->ah_pcdacTable[2*i]     << 8) | 0xff) & 0xffff)
1935 			);
1936 		}
1937 	}
1938 
1939 	/* Write the OFDM power per rate set */
1940 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
1941 		POW_OFDM(ahp->ah_ratesArray[3], 24)
1942 	      | POW_OFDM(ahp->ah_ratesArray[2], 16)
1943 	      | POW_OFDM(ahp->ah_ratesArray[1],  8)
1944 	      | POW_OFDM(ahp->ah_ratesArray[0],  0)
1945 	);
1946 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
1947 		POW_OFDM(ahp->ah_ratesArray[7], 24)
1948 	      | POW_OFDM(ahp->ah_ratesArray[6], 16)
1949 	      | POW_OFDM(ahp->ah_ratesArray[5],  8)
1950 	      | POW_OFDM(ahp->ah_ratesArray[4],  0)
1951 	);
1952 
1953 	/* Write the CCK power per rate set */
1954 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE3,
1955 		POW_CCK(ahp->ah_ratesArray[10], 24)
1956 	      | POW_CCK(ahp->ah_ratesArray[9],  16)
1957 	      | POW_CCK(ahp->ah_ratesArray[15],  8)	/* XR target power */
1958 	      | POW_CCK(ahp->ah_ratesArray[8],   0)
1959 	);
1960 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE4,
1961 		POW_CCK(ahp->ah_ratesArray[14], 24)
1962 	      | POW_CCK(ahp->ah_ratesArray[13], 16)
1963 	      | POW_CCK(ahp->ah_ratesArray[12],  8)
1964 	      | POW_CCK(ahp->ah_ratesArray[11],  0)
1965 	);
1966 
1967 	/*
1968 	 * Set max power to 30 dBm and, optionally,
1969 	 * enable TPC in tx descriptors.
1970 	 */
1971 	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE_MAX, MAX_RATE_POWER |
1972 		(ahp->ah_tpcEnabled ? AR_PHY_POWER_TX_RATE_MAX_TPC_ENABLE : 0));
1973 
1974 	return AH_TRUE;
1975 #undef N
1976 #undef POW_CCK
1977 #undef POW_OFDM
1978 }
1979 
1980 /*
1981  * Sets the transmit power in the baseband for the given
1982  * operating channel and mode.
1983  */
1984 static HAL_BOOL
1985 ar5212SetRateTable(struct ath_hal *ah, const struct ieee80211_channel *chan,
1986 	int16_t tpcScaleReduction, int16_t powerLimit, HAL_BOOL commit,
1987 	int16_t *pMinPower, int16_t *pMaxPower)
1988 {
1989 	struct ath_hal_5212 *ahp = AH5212(ah);
1990 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1991 	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1992 	uint16_t *rpow = ahp->ah_ratesArray;
1993 	uint16_t twiceMaxEdgePower = MAX_RATE_POWER;
1994 	uint16_t twiceMaxEdgePowerCck = MAX_RATE_POWER;
1995 	uint16_t twiceMaxRDPower = MAX_RATE_POWER;
1996 	int i;
1997 	uint8_t cfgCtl;
1998 	int8_t twiceAntennaGain, twiceAntennaReduction;
1999 	const RD_EDGES_POWER *rep;
2000 	TRGT_POWER_INFO targetPowerOfdm, targetPowerCck;
2001 	int16_t scaledPower, maxAvailPower = 0;
2002 	int16_t r13, r9, r7, r0;
2003 
2004 	HALASSERT(ah->ah_magic == AR5212_MAGIC);
2005 
2006 	twiceMaxRDPower = chan->ic_maxregpower * 2;
2007 	*pMaxPower = -MAX_RATE_POWER;
2008 	*pMinPower = MAX_RATE_POWER;
2009 
2010 	/* Get conformance test limit maximum for this channel */
2011 	cfgCtl = ath_hal_getctl(ah, chan);
2012 	for (i = 0; i < ee->ee_numCtls; i++) {
2013 		uint16_t twiceMinEdgePower;
2014 
2015 		if (ee->ee_ctl[i] == 0)
2016 			continue;
2017 		if (ee->ee_ctl[i] == cfgCtl ||
2018 		    cfgCtl == ((ee->ee_ctl[i] & CTL_MODE_M) | SD_NO_CTL)) {
2019 			rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
2020 			twiceMinEdgePower = ar5212GetMaxEdgePower(freq, rep);
2021 			if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
2022 				/* Find the minimum of all CTL edge powers that apply to this channel */
2023 				twiceMaxEdgePower = AH_MIN(twiceMaxEdgePower, twiceMinEdgePower);
2024 			} else {
2025 				twiceMaxEdgePower = twiceMinEdgePower;
2026 				break;
2027 			}
2028 		}
2029 	}
2030 
2031 	if (IEEE80211_IS_CHAN_G(chan)) {
2032 		/* Check for a CCK CTL for 11G CCK powers */
2033 		cfgCtl = (cfgCtl & ~CTL_MODE_M) | CTL_11B;
2034 		for (i = 0; i < ee->ee_numCtls; i++) {
2035 			uint16_t twiceMinEdgePowerCck;
2036 
2037 			if (ee->ee_ctl[i] == 0)
2038 				continue;
2039 			if (ee->ee_ctl[i] == cfgCtl ||
2040 			    cfgCtl == ((ee->ee_ctl[i] & CTL_MODE_M) | SD_NO_CTL)) {
2041 				rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
2042 				twiceMinEdgePowerCck = ar5212GetMaxEdgePower(freq, rep);
2043 				if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
2044 					/* Find the minimum of all CTL edge powers that apply to this channel */
2045 					twiceMaxEdgePowerCck = AH_MIN(twiceMaxEdgePowerCck, twiceMinEdgePowerCck);
2046 				} else {
2047 					twiceMaxEdgePowerCck = twiceMinEdgePowerCck;
2048 					break;
2049 				}
2050 			}
2051 		}
2052 	} else {
2053 		/* Set the 11B cck edge power to the one found before */
2054 		twiceMaxEdgePowerCck = twiceMaxEdgePower;
2055 	}
2056 
2057 	/* Get Antenna Gain reduction */
2058 	if (IEEE80211_IS_CHAN_5GHZ(chan)) {
2059 		ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_5, &twiceAntennaGain);
2060 	} else {
2061 		ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_2, &twiceAntennaGain);
2062 	}
2063 	twiceAntennaReduction =
2064 		ath_hal_getantennareduction(ah, chan, twiceAntennaGain);
2065 
2066 	if (IEEE80211_IS_CHAN_OFDM(chan)) {
2067 		/* Get final OFDM target powers */
2068 		if (IEEE80211_IS_CHAN_2GHZ(chan)) {
2069 			ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11g,
2070 				ee->ee_numTargetPwr_11g, &targetPowerOfdm);
2071 		} else {
2072 			ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11a,
2073 				ee->ee_numTargetPwr_11a, &targetPowerOfdm);
2074 		}
2075 
2076 		/* Get Maximum OFDM power */
2077 		/* Minimum of target and edge powers */
2078 		scaledPower = AH_MIN(twiceMaxEdgePower,
2079 				twiceMaxRDPower - twiceAntennaReduction);
2080 
2081 		/*
2082 		 * If turbo is set, reduce power to keep power
2083 		 * consumption under 2 Watts.  Note that we always do
2084 		 * this unless specially configured.  Then we limit
2085 		 * power only for non-AP operation.
2086 		 */
2087 		if (IEEE80211_IS_CHAN_TURBO(chan)
2088 #ifdef AH_ENABLE_AP_SUPPORT
2089 		    && AH_PRIVATE(ah)->ah_opmode != HAL_M_HOSTAP
2090 #endif
2091 		) {
2092 			/*
2093 			 * If turbo is set, reduce power to keep power
2094 			 * consumption under 2 Watts
2095 			 */
2096 			if (ee->ee_version >= AR_EEPROM_VER3_1)
2097 				scaledPower = AH_MIN(scaledPower,
2098 					ee->ee_turbo2WMaxPower5);
2099 			/*
2100 			 * EEPROM version 4.0 added an additional
2101 			 * constraint on 2.4GHz channels.
2102 			 */
2103 			if (ee->ee_version >= AR_EEPROM_VER4_0 &&
2104 			    IEEE80211_IS_CHAN_2GHZ(chan))
2105 				scaledPower = AH_MIN(scaledPower,
2106 					ee->ee_turbo2WMaxPower2);
2107 		}
2108 
2109 		maxAvailPower = AH_MIN(scaledPower,
2110 					targetPowerOfdm.twicePwr6_24);
2111 
2112 		/* Reduce power by max regulatory domain allowed restrictions */
2113 		scaledPower = maxAvailPower - (tpcScaleReduction * 2);
2114 		scaledPower = (scaledPower < 0) ? 0 : scaledPower;
2115 		scaledPower = AH_MIN(scaledPower, powerLimit);
2116 
2117 		if (commit) {
2118 			/* Set OFDM rates 9, 12, 18, 24 */
2119 			r0 = rpow[0] = rpow[1] = rpow[2] = rpow[3] = rpow[4] = scaledPower;
2120 
2121 			/* Set OFDM rates 36, 48, 54, XR */
2122 			rpow[5] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr36);
2123 			rpow[6] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr48);
2124 			r7 = rpow[7] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr54);
2125 
2126 			if (ee->ee_version >= AR_EEPROM_VER4_0) {
2127 				/* Setup XR target power from EEPROM */
2128 				rpow[15] = AH_MIN(scaledPower, IEEE80211_IS_CHAN_2GHZ(chan) ?
2129 						  ee->ee_xrTargetPower2 : ee->ee_xrTargetPower5);
2130 			} else {
2131 				/* XR uses 6mb power */
2132 				rpow[15] = rpow[0];
2133 			}
2134 			ahp->ah_ofdmTxPower = *pMaxPower;
2135 
2136 		} else {
2137 			r0 = scaledPower;
2138 			r7 = AH_MIN(r0, targetPowerOfdm.twicePwr54);
2139 		}
2140 		*pMinPower = r7;
2141 		*pMaxPower = r0;
2142 
2143 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2144 		    "%s: MaxRD: %d TurboMax: %d MaxCTL: %d "
2145 		    "TPC_Reduction %d chan=%d (0x%x) maxAvailPower=%d pwr6_24=%d, maxPower=%d\n",
2146 		    __func__, twiceMaxRDPower, ee->ee_turbo2WMaxPower5,
2147 		    twiceMaxEdgePower, tpcScaleReduction * 2,
2148 		    chan->ic_freq, chan->ic_flags,
2149 		    maxAvailPower, targetPowerOfdm.twicePwr6_24, *pMaxPower);
2150 	}
2151 
2152 	if (IEEE80211_IS_CHAN_CCK(chan)) {
2153 		/* Get final CCK target powers */
2154 		ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11b,
2155 			ee->ee_numTargetPwr_11b, &targetPowerCck);
2156 
2157 		/* Reduce power by max regulatory domain allowed restrictions */
2158 		scaledPower = AH_MIN(twiceMaxEdgePowerCck,
2159 			twiceMaxRDPower - twiceAntennaReduction);
2160 		if (maxAvailPower < AH_MIN(scaledPower, targetPowerCck.twicePwr6_24))
2161 			maxAvailPower = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24);
2162 
2163 		/* Reduce power by user selection */
2164 		scaledPower = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24) - (tpcScaleReduction * 2);
2165 		scaledPower = (scaledPower < 0) ? 0 : scaledPower;
2166 		scaledPower = AH_MIN(scaledPower, powerLimit);
2167 
2168 		if (commit) {
2169 			/* Set CCK rates 2L, 2S, 5.5L, 5.5S, 11L, 11S */
2170 			rpow[8]  = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24);
2171 			r9 = rpow[9]  = AH_MIN(scaledPower, targetPowerCck.twicePwr36);
2172 			rpow[10] = rpow[9];
2173 			rpow[11] = AH_MIN(scaledPower, targetPowerCck.twicePwr48);
2174 			rpow[12] = rpow[11];
2175 			r13 = rpow[13] = AH_MIN(scaledPower, targetPowerCck.twicePwr54);
2176 			rpow[14] = rpow[13];
2177 		} else {
2178 			r9 = AH_MIN(scaledPower, targetPowerCck.twicePwr36);
2179 			r13 = AH_MIN(scaledPower, targetPowerCck.twicePwr54);
2180 		}
2181 
2182 		/* Set min/max power based off OFDM values or initialization */
2183 		if (r13 < *pMinPower)
2184 			*pMinPower = r13;
2185 		if (r9 > *pMaxPower)
2186 			*pMaxPower = r9;
2187 
2188 		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2189 		    "%s: cck: MaxRD: %d MaxCTL: %d "
2190 		    "TPC_Reduction %d chan=%d (0x%x) maxAvailPower=%d pwr6_24=%d, maxPower=%d\n",
2191 		    __func__, twiceMaxRDPower, twiceMaxEdgePowerCck,
2192 		    tpcScaleReduction * 2, chan->ic_freq, chan->ic_flags,
2193 		    maxAvailPower, targetPowerCck.twicePwr6_24, *pMaxPower);
2194 	}
2195 	if (commit) {
2196 		ahp->ah_tx6PowerInHalfDbm = *pMaxPower;
2197 		AH_PRIVATE(ah)->ah_maxPowerLevel = ahp->ah_tx6PowerInHalfDbm;
2198 	}
2199 	return AH_TRUE;
2200 }
2201 
2202 HAL_BOOL
2203 ar5212GetChipPowerLimits(struct ath_hal *ah, struct ieee80211_channel *chan)
2204 {
2205 	struct ath_hal_5212 *ahp = AH5212(ah);
2206 #if 0
2207 	static const uint16_t tpcScaleReductionTable[5] =
2208 		{ 0, 3, 6, 9, MAX_RATE_POWER };
2209 	int16_t tpcInDb, powerLimit;
2210 #endif
2211 	int16_t minPower, maxPower;
2212 
2213 	/*
2214 	 * Get Pier table max and min powers.
2215 	 */
2216 	if (ahp->ah_rfHal->getChannelMaxMinPower(ah, chan, &maxPower, &minPower)) {
2217 		/* NB: rf code returns 1/4 dBm units, convert */
2218 		chan->ic_maxpower = maxPower / 2;
2219 		chan->ic_minpower = minPower / 2;
2220 	} else {
2221 		HALDEBUG(ah, HAL_DEBUG_ANY,
2222 		    "%s: no min/max power for %u/0x%x\n",
2223 		    __func__, chan->ic_freq, chan->ic_flags);
2224 		chan->ic_maxpower = MAX_RATE_POWER;
2225 		chan->ic_minpower = 0;
2226 	}
2227 #if 0
2228 	/*
2229 	 * Now adjust to reflect any global scale and/or CTL's.
2230 	 * (XXX is that correct?)
2231 	 */
2232 	powerLimit = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
2233 	if (powerLimit >= MAX_RATE_POWER || powerLimit == 0)
2234 		tpcInDb = tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale];
2235 	else
2236 		tpcInDb = 0;
2237 	if (!ar5212SetRateTable(ah, chan, tpcInDb, powerLimit,
2238 				AH_FALSE, &minPower, &maxPower)) {
2239 		HALDEBUG(ah, HAL_DEBUG_ANY,
2240 		    "%s: unable to find max/min power\n",__func__);
2241 		return AH_FALSE;
2242 	}
2243 	if (maxPower < chan->ic_maxpower)
2244 		chan->ic_maxpower = maxPower;
2245 	if (minPower < chan->ic_minpower)
2246 		chan->ic_minpower = minPower;
2247 	HALDEBUG(ah, HAL_DEBUG_RESET,
2248 	    "Chan %d: MaxPow = %d MinPow = %d\n",
2249 	    chan->ic_freq, chan->ic_maxpower, chans->ic_minpower);
2250 #endif
2251 	return AH_TRUE;
2252 }
2253 
2254 /*
2255  * Correct for the gain-delta between ofdm and cck mode target
2256  * powers. Write the results to the rate table and the power table.
2257  *
2258  *   Conventions :
2259  *   1. rpow[ii] is the integer value of 2*(desired power
2260  *    for the rate ii in dBm) to provide 0.5dB resolution. rate
2261  *    mapping is as following :
2262  *     [0..7]  --> ofdm 6, 9, .. 48, 54
2263  *     [8..14] --> cck 1L, 2L, 2S, .. 11L, 11S
2264  *     [15]    --> XR (all rates get the same power)
2265  *   2. powv[ii]  is the pcdac corresponding to ii/2 dBm.
2266  */
2267 static void
2268 ar5212CorrectGainDelta(struct ath_hal *ah, int twiceOfdmCckDelta)
2269 {
2270 #define	N(_a)	(sizeof(_a) / sizeof(_a[0]))
2271 	struct ath_hal_5212 *ahp = AH5212(ah);
2272 	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
2273 	int16_t ratesIndex[N(ahp->ah_ratesArray)];
2274 	uint16_t ii, jj, iter;
2275 	int32_t cckIndex;
2276 	int16_t gainDeltaAdjust;
2277 
2278 	HALASSERT(ah->ah_magic == AR5212_MAGIC);
2279 
2280 	gainDeltaAdjust = ee->ee_cckOfdmGainDelta;
2281 
2282 	/* make a local copy of desired powers as initial indices */
2283 	OS_MEMCPY(ratesIndex, ahp->ah_ratesArray, sizeof(ratesIndex));
2284 
2285 	/* fix only the CCK indices */
2286 	for (ii = 8; ii < 15; ii++) {
2287 		/* apply a gain_delta correction of -15 for CCK */
2288 		ratesIndex[ii] -= gainDeltaAdjust;
2289 
2290 		/* Now check for contention with all ofdm target powers */
2291 		jj = 0;
2292 		iter = 0;
2293 		/* indicates not all ofdm rates checked forcontention yet */
2294 		while (jj < 16) {
2295 			if (ratesIndex[ii] < 0)
2296 				ratesIndex[ii] = 0;
2297 			if (jj == 8) {		/* skip CCK rates */
2298 				jj = 15;
2299 				continue;
2300 			}
2301 			if (ratesIndex[ii] == ahp->ah_ratesArray[jj]) {
2302 				if (ahp->ah_ratesArray[jj] == 0)
2303 					ratesIndex[ii]++;
2304 				else if (iter > 50) {
2305 					/*
2306 					 * To avoid pathological case of of
2307 					 * dm target powers 0 and 0.5dBm
2308 					 */
2309 					ratesIndex[ii]++;
2310 				} else
2311 					ratesIndex[ii]--;
2312 				/* check with all rates again */
2313 				jj = 0;
2314 				iter++;
2315 			} else
2316 				jj++;
2317 		}
2318 		if (ratesIndex[ii] >= PWR_TABLE_SIZE)
2319 			ratesIndex[ii] = PWR_TABLE_SIZE -1;
2320 		cckIndex = ahp->ah_ratesArray[ii] - twiceOfdmCckDelta;
2321 		if (cckIndex < 0)
2322 			cckIndex = 0;
2323 
2324 		/*
2325 		 * Validate that the indexes for the powv are not
2326 		 * out of bounds.
2327 		 */
2328 		HALASSERT(cckIndex < PWR_TABLE_SIZE);
2329 		HALASSERT(ratesIndex[ii] < PWR_TABLE_SIZE);
2330 		ahp->ah_pcdacTable[ratesIndex[ii]] =
2331 			ahp->ah_pcdacTable[cckIndex];
2332 	}
2333 	/* Override rate per power table with new values */
2334 	for (ii = 8; ii < 15; ii++)
2335 		ahp->ah_ratesArray[ii] = ratesIndex[ii];
2336 #undef N
2337 }
2338 
2339 /*
2340  * Find the maximum conformance test limit for the given channel and CTL info
2341  */
2342 static uint16_t
2343 ar5212GetMaxEdgePower(uint16_t channel, const RD_EDGES_POWER *pRdEdgesPower)
2344 {
2345 	/* temp array for holding edge channels */
2346 	uint16_t tempChannelList[NUM_EDGES];
2347 	uint16_t clo, chi, twiceMaxEdgePower;
2348 	int i, numEdges;
2349 
2350 	/* Get the edge power */
2351 	for (i = 0; i < NUM_EDGES; i++) {
2352 		if (pRdEdgesPower[i].rdEdge == 0)
2353 			break;
2354 		tempChannelList[i] = pRdEdgesPower[i].rdEdge;
2355 	}
2356 	numEdges = i;
2357 
2358 	ar5212GetLowerUpperValues(channel, tempChannelList,
2359 		numEdges, &clo, &chi);
2360 	/* Get the index for the lower channel */
2361 	for (i = 0; i < numEdges && clo != tempChannelList[i]; i++)
2362 		;
2363 	/* Is lower channel ever outside the rdEdge? */
2364 	HALASSERT(i != numEdges);
2365 
2366 	if ((clo == chi && clo == channel) || (pRdEdgesPower[i].flag)) {
2367 		/*
2368 		 * If there's an exact channel match or an inband flag set
2369 		 * on the lower channel use the given rdEdgePower
2370 		 */
2371 		twiceMaxEdgePower = pRdEdgesPower[i].twice_rdEdgePower;
2372 		HALASSERT(twiceMaxEdgePower > 0);
2373 	} else
2374 		twiceMaxEdgePower = MAX_RATE_POWER;
2375 	return twiceMaxEdgePower;
2376 }
2377 
2378 /*
2379  * Returns interpolated or the scaled up interpolated value
2380  */
2381 static uint16_t
2382 interpolate(uint16_t target, uint16_t srcLeft, uint16_t srcRight,
2383 	uint16_t targetLeft, uint16_t targetRight)
2384 {
2385 	uint16_t rv;
2386 	int16_t lRatio;
2387 
2388 	/* to get an accurate ratio, always scale, if want to scale, then don't scale back down */
2389 	if ((targetLeft * targetRight) == 0)
2390 		return 0;
2391 
2392 	if (srcRight != srcLeft) {
2393 		/*
2394 		 * Note the ratio always need to be scaled,
2395 		 * since it will be a fraction.
2396 		 */
2397 		lRatio = (target - srcLeft) * EEP_SCALE / (srcRight - srcLeft);
2398 		if (lRatio < 0) {
2399 		    /* Return as Left target if value would be negative */
2400 		    rv = targetLeft;
2401 		} else if (lRatio > EEP_SCALE) {
2402 		    /* Return as Right target if Ratio is greater than 100% (SCALE) */
2403 		    rv = targetRight;
2404 		} else {
2405 			rv = (lRatio * targetRight + (EEP_SCALE - lRatio) *
2406 					targetLeft) / EEP_SCALE;
2407 		}
2408 	} else {
2409 		rv = targetLeft;
2410 	}
2411 	return rv;
2412 }
2413 
2414 /*
2415  * Return the four rates of target power for the given target power table
2416  * channel, and number of channels
2417  */
2418 static void
2419 ar5212GetTargetPowers(struct ath_hal *ah, const struct ieee80211_channel *chan,
2420 	const TRGT_POWER_INFO *powInfo,
2421 	uint16_t numChannels, TRGT_POWER_INFO *pNewPower)
2422 {
2423 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
2424 	/* temp array for holding target power channels */
2425 	uint16_t tempChannelList[NUM_TEST_FREQUENCIES];
2426 	uint16_t clo, chi, ixlo, ixhi;
2427 	int i;
2428 
2429 	/* Copy the target powers into the temp channel list */
2430 	for (i = 0; i < numChannels; i++)
2431 		tempChannelList[i] = powInfo[i].testChannel;
2432 
2433 	ar5212GetLowerUpperValues(freq, tempChannelList,
2434 		numChannels, &clo, &chi);
2435 
2436 	/* Get the indices for the channel */
2437 	ixlo = ixhi = 0;
2438 	for (i = 0; i < numChannels; i++) {
2439 		if (clo == tempChannelList[i]) {
2440 			ixlo = i;
2441 		}
2442 		if (chi == tempChannelList[i]) {
2443 			ixhi = i;
2444 			break;
2445 		}
2446 	}
2447 
2448 	/*
2449 	 * Get the lower and upper channels, target powers,
2450 	 * and interpolate between them.
2451 	 */
2452 	pNewPower->twicePwr6_24 = interpolate(freq, clo, chi,
2453 		powInfo[ixlo].twicePwr6_24, powInfo[ixhi].twicePwr6_24);
2454 	pNewPower->twicePwr36 = interpolate(freq, clo, chi,
2455 		powInfo[ixlo].twicePwr36, powInfo[ixhi].twicePwr36);
2456 	pNewPower->twicePwr48 = interpolate(freq, clo, chi,
2457 		powInfo[ixlo].twicePwr48, powInfo[ixhi].twicePwr48);
2458 	pNewPower->twicePwr54 = interpolate(freq, clo, chi,
2459 		powInfo[ixlo].twicePwr54, powInfo[ixhi].twicePwr54);
2460 }
2461 
2462 /*
2463  * Search a list for a specified value v that is within
2464  * EEP_DELTA of the search values.  Return the closest
2465  * values in the list above and below the desired value.
2466  * EEP_DELTA is a factional value; everything is scaled
2467  * so only integer arithmetic is used.
2468  *
2469  * NB: the input list is assumed to be sorted in ascending order
2470  */
2471 void
2472 ar5212GetLowerUpperValues(uint16_t v, uint16_t *lp, uint16_t listSize,
2473                           uint16_t *vlo, uint16_t *vhi)
2474 {
2475 	uint32_t target = v * EEP_SCALE;
2476 	uint16_t *ep = lp+listSize;
2477 
2478 	/*
2479 	 * Check first and last elements for out-of-bounds conditions.
2480 	 */
2481 	if (target < (uint32_t)(lp[0] * EEP_SCALE - EEP_DELTA)) {
2482 		*vlo = *vhi = lp[0];
2483 		return;
2484 	}
2485 	if (target > (uint32_t)(ep[-1] * EEP_SCALE + EEP_DELTA)) {
2486 		*vlo = *vhi = ep[-1];
2487 		return;
2488 	}
2489 
2490 	/* look for value being near or between 2 values in list */
2491 	for (; lp < ep; lp++) {
2492 		/*
2493 		 * If value is close to the current value of the list
2494 		 * then target is not between values, it is one of the values
2495 		 */
2496 		if (abs(lp[0] * EEP_SCALE - target) < EEP_DELTA) {
2497 			*vlo = *vhi = lp[0];
2498 			return;
2499 		}
2500 		/*
2501 		 * Look for value being between current value and next value
2502 		 * if so return these 2 values
2503 		 */
2504 		if (target < (uint32_t)(lp[1] * EEP_SCALE - EEP_DELTA)) {
2505 			*vlo = lp[0];
2506 			*vhi = lp[1];
2507 			return;
2508 		}
2509 	}
2510 	HALASSERT(AH_FALSE);		/* should not reach here */
2511 }
2512 
2513 /*
2514  * Perform analog "swizzling" of parameters into their location
2515  *
2516  * NB: used by RF backends
2517  */
2518 void
2519 ar5212ModifyRfBuffer(uint32_t *rfBuf, uint32_t reg32, uint32_t numBits,
2520                      uint32_t firstBit, uint32_t column)
2521 {
2522 #define	MAX_ANALOG_START	319		/* XXX */
2523 	uint32_t tmp32, mask, arrayEntry, lastBit;
2524 	int32_t bitPosition, bitsLeft;
2525 
2526 	HALASSERT(column <= 3);
2527 	HALASSERT(numBits <= 32);
2528 	HALASSERT(firstBit + numBits <= MAX_ANALOG_START);
2529 
2530 	tmp32 = ath_hal_reverseBits(reg32, numBits);
2531 	arrayEntry = (firstBit - 1) / 8;
2532 	bitPosition = (firstBit - 1) % 8;
2533 	bitsLeft = numBits;
2534 	while (bitsLeft > 0) {
2535 		lastBit = (bitPosition + bitsLeft > 8) ?
2536 			8 : bitPosition + bitsLeft;
2537 		mask = (((1 << lastBit) - 1) ^ ((1 << bitPosition) - 1)) <<
2538 			(column * 8);
2539 		rfBuf[arrayEntry] &= ~mask;
2540 		rfBuf[arrayEntry] |= ((tmp32 << bitPosition) <<
2541 			(column * 8)) & mask;
2542 		bitsLeft -= 8 - bitPosition;
2543 		tmp32 = tmp32 >> (8 - bitPosition);
2544 		bitPosition = 0;
2545 		arrayEntry++;
2546 	}
2547 #undef MAX_ANALOG_START
2548 }
2549 
2550 /*
2551  * Sets the rate to duration values in MAC - used for multi-
2552  * rate retry.
2553  * The rate duration table needs to cover all valid rate codes;
2554  * the 11g table covers all ofdm rates, while the 11b table
2555  * covers all cck rates => all valid rates get covered between
2556  * these two mode's ratetables!
2557  * But if we're turbo, the ofdm phy is replaced by the turbo phy
2558  * and cck is not valid with turbo => all rates get covered
2559  * by the turbo ratetable only
2560  */
2561 void
2562 ar5212SetRateDurationTable(struct ath_hal *ah,
2563 	const struct ieee80211_channel *chan)
2564 {
2565 	const HAL_RATE_TABLE *rt;
2566 	int i;
2567 
2568 	/* NB: band doesn't matter for 1/2 and 1/4 rate */
2569 	if (IEEE80211_IS_CHAN_HALF(chan)) {
2570 		rt = ar5212GetRateTable(ah, HAL_MODE_11A_HALF_RATE);
2571 	} else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
2572 		rt = ar5212GetRateTable(ah, HAL_MODE_11A_QUARTER_RATE);
2573 	} else {
2574 		rt = ar5212GetRateTable(ah,
2575 			IEEE80211_IS_CHAN_TURBO(chan) ? HAL_MODE_TURBO : HAL_MODE_11G);
2576 	}
2577 
2578 	for (i = 0; i < rt->rateCount; ++i)
2579 		OS_REG_WRITE(ah,
2580 			AR_RATE_DURATION(rt->info[i].rateCode),
2581 			ath_hal_computetxtime(ah, rt,
2582 				WLAN_CTRL_FRAME_SIZE,
2583 				rt->info[i].controlRate, AH_FALSE));
2584 	if (!IEEE80211_IS_CHAN_TURBO(chan)) {
2585 		/* 11g Table is used to cover the CCK rates. */
2586 		rt = ar5212GetRateTable(ah, HAL_MODE_11G);
2587 		for (i = 0; i < rt->rateCount; ++i) {
2588 			uint32_t reg = AR_RATE_DURATION(rt->info[i].rateCode);
2589 
2590 			if (rt->info[i].phy != IEEE80211_T_CCK)
2591 				continue;
2592 
2593 			OS_REG_WRITE(ah, reg,
2594 				ath_hal_computetxtime(ah, rt,
2595 					WLAN_CTRL_FRAME_SIZE,
2596 					rt->info[i].controlRate, AH_FALSE));
2597 			/* cck rates have short preamble option also */
2598 			if (rt->info[i].shortPreamble) {
2599 				reg += rt->info[i].shortPreamble << 2;
2600 				OS_REG_WRITE(ah, reg,
2601 					ath_hal_computetxtime(ah, rt,
2602 						WLAN_CTRL_FRAME_SIZE,
2603 						rt->info[i].controlRate,
2604 						AH_TRUE));
2605 			}
2606 		}
2607 	}
2608 }
2609 
2610 /* Adjust various register settings based on half/quarter rate clock setting.
2611  * This includes: +USEC, TX/RX latency,
2612  *                + IFS params: slot, eifs, misc etc.
2613  */
2614 void
2615 ar5212SetIFSTiming(struct ath_hal *ah, const struct ieee80211_channel *chan)
2616 {
2617 	uint32_t txLat, rxLat, usec, slot, refClock, eifs, init_usec;
2618 
2619 	HALASSERT(IEEE80211_IS_CHAN_HALF(chan) ||
2620 		  IEEE80211_IS_CHAN_QUARTER(chan));
2621 
2622 	refClock = OS_REG_READ(ah, AR_USEC) & AR_USEC_USEC32;
2623 	if (IEEE80211_IS_CHAN_HALF(chan)) {
2624 		slot = IFS_SLOT_HALF_RATE;
2625 		rxLat = RX_NON_FULL_RATE_LATENCY << AR5212_USEC_RX_LAT_S;
2626 		txLat = TX_HALF_RATE_LATENCY << AR5212_USEC_TX_LAT_S;
2627 		usec = HALF_RATE_USEC;
2628 		eifs = IFS_EIFS_HALF_RATE;
2629 		init_usec = INIT_USEC >> 1;
2630 	} else { /* quarter rate */
2631 		slot = IFS_SLOT_QUARTER_RATE;
2632 		rxLat = RX_NON_FULL_RATE_LATENCY << AR5212_USEC_RX_LAT_S;
2633 		txLat = TX_QUARTER_RATE_LATENCY << AR5212_USEC_TX_LAT_S;
2634 		usec = QUARTER_RATE_USEC;
2635 		eifs = IFS_EIFS_QUARTER_RATE;
2636 		init_usec = INIT_USEC >> 2;
2637 	}
2638 
2639 	OS_REG_WRITE(ah, AR_USEC, (usec | refClock | txLat | rxLat));
2640 	OS_REG_WRITE(ah, AR_D_GBL_IFS_SLOT, slot);
2641 	OS_REG_WRITE(ah, AR_D_GBL_IFS_EIFS, eifs);
2642 	OS_REG_RMW_FIELD(ah, AR_D_GBL_IFS_MISC,
2643 				AR_D_GBL_IFS_MISC_USEC_DURATION, init_usec);
2644 }
2645