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