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