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