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