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