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