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