ar5212_reset.c revision 188191
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: head/sys/dev/ath/ath_hal/ar5212/ar5212_reset.c 188191 2009-02-05 20:48:30Z sam $
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
35static HAL_BOOL ar5212SetResetReg(struct ath_hal *, uint32_t resetMask);
36/* NB: public for 5312 use */
37HAL_BOOL	ar5212IsSpurChannel(struct ath_hal *,
38		    const struct ieee80211_channel *);
39HAL_BOOL	ar5212ChannelChange(struct ath_hal *,
40		    const struct ieee80211_channel *);
41int16_t		ar5212GetNf(struct ath_hal *, struct ieee80211_channel *);
42HAL_BOOL	ar5212SetBoardValues(struct ath_hal *,
43		    const struct ieee80211_channel *);
44void		ar5212SetDeltaSlope(struct ath_hal *,
45		    const struct ieee80211_channel *);
46HAL_BOOL	ar5212SetTransmitPower(struct ath_hal *ah,
47		   const struct ieee80211_channel *chan, uint16_t *rfXpdGain);
48static 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);
52static void ar5212CorrectGainDelta(struct ath_hal *, int twiceOfdmCckDelta);
53static void ar5212GetTargetPowers(struct ath_hal *,
54		   const struct ieee80211_channel *,
55		   const TRGT_POWER_INFO *pPowerInfo, uint16_t numChannels,
56		   TRGT_POWER_INFO *pNewPower);
57static uint16_t ar5212GetMaxEdgePower(uint16_t channel,
58		   const RD_EDGES_POWER  *pRdEdgesPower);
59void		ar5212SetRateDurationTable(struct ath_hal *,
60		    const struct ieee80211_channel *);
61void		ar5212SetIFSTiming(struct ath_hal *,
62		    const struct ieee80211_channel *);
63
64/* NB: public for RF backend use */
65void		ar5212GetLowerUpperValues(uint16_t value,
66		   uint16_t *pList, uint16_t listSize,
67		   uint16_t *pLowerValue, uint16_t *pUpperValue);
68void		ar5212ModifyRfBuffer(uint32_t *rfBuf, uint32_t reg32,
69		   uint32_t numBits, uint32_t firstBit, uint32_t column);
70
71static int
72write_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 */
106HAL_BOOL
107ar5212Reset(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
660done:
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;
672bad:
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 */
686HAL_BOOL
687ar5212SetChannel(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 */
703HAL_BOOL
704ar5212ChannelChange(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
776void
777ar5212SetOperatingMode(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 */
807HAL_BOOL
808ar5212PhyDisable(struct ath_hal *ah)
809{
810	return ar5212SetResetReg(ah, AR_RC_BB);
811}
812
813/*
814 * Places all of hardware into reset
815 */
816HAL_BOOL
817ar5212Disable(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 */
835HAL_BOOL
836ar5212ChipReset(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 */
946HAL_BOOL
947ar5212PerCalibrationN(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		/*
998		 * Prescale these values to remove 64-bit operation
999		 * requirement at the loss of a little precision.
1000		 */
1001		iCoffDenom = (powerMeasI / 2 + powerMeasQ / 2) / 128;
1002		qCoffDenom = powerMeasQ / 128;
1003
1004		/* Protect against divide-by-0 and loss of sign bits. */
1005		if (iCoffDenom != 0 && qCoffDenom >= 2) {
1006			iCoff = (int8_t)(-iqCorrMeas) / iCoffDenom;
1007			/* IQCORR_Q_I_COFF is a signed 6 bit number */
1008			if (iCoff < -32) {
1009				iCoff = -32;
1010			} else if (iCoff > 31) {
1011				iCoff = 31;
1012			}
1013
1014			/* IQCORR_Q_Q_COFF is a signed 5 bit number */
1015			qCoff = (powerMeasI / qCoffDenom) - 128;
1016			if (qCoff < -16) {
1017				qCoff = -16;
1018			} else if (qCoff > 15) {
1019				qCoff = 15;
1020			}
1021
1022			HALDEBUG(ah, HAL_DEBUG_PERCAL,
1023			    "****************** MISGATED IQ CAL! *******************\n");
1024			HALDEBUG(ah, HAL_DEBUG_PERCAL,
1025			    "time       = %d, i = %d, \n", OS_GETUPTIME(ah), i);
1026			HALDEBUG(ah, HAL_DEBUG_PERCAL,
1027			    "powerMeasI = 0x%08x\n", powerMeasI);
1028			HALDEBUG(ah, HAL_DEBUG_PERCAL,
1029			    "powerMeasQ = 0x%08x\n", powerMeasQ);
1030			HALDEBUG(ah, HAL_DEBUG_PERCAL,
1031			    "iqCorrMeas = 0x%08x\n", iqCorrMeas);
1032			HALDEBUG(ah, HAL_DEBUG_PERCAL,
1033			    "iCoff      = %d\n", iCoff);
1034			HALDEBUG(ah, HAL_DEBUG_PERCAL,
1035			    "qCoff      = %d\n", qCoff);
1036
1037			/* Write values and enable correction */
1038			OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1039				AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF, iCoff);
1040			OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1041				AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF, qCoff);
1042			OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1043				AR_PHY_TIMING_CTRL4_IQCORR_ENABLE);
1044
1045			ahp->ah_bIQCalibration = IQ_CAL_DONE;
1046			ichan->privFlags |= CHANNEL_IQVALID;
1047			ichan->iCoff = iCoff;
1048			ichan->qCoff = qCoff;
1049		}
1050	} else if (!IEEE80211_IS_CHAN_B(chan) && ahp->ah_bIQCalibration == IQ_CAL_DONE &&
1051	    (ichan->privFlags & CHANNEL_IQVALID) == 0) {
1052		/*
1053		 * Start IQ calibration if configured channel has changed.
1054		 * Use a magic number of 15 based on default value.
1055		 */
1056		OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1057			AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX,
1058			INIT_IQCAL_LOG_COUNT_MAX);
1059		OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1060			AR_PHY_TIMING_CTRL4_DO_IQCAL);
1061		ahp->ah_bIQCalibration = IQ_CAL_RUNNING;
1062	}
1063	/* XXX EAR */
1064
1065	if (longCal) {
1066		/* Check noise floor results */
1067		ar5212GetNf(ah, chan);
1068		if (!IEEE80211_IS_CHAN_CWINT(chan)) {
1069			/* Perform cal for 5Ghz channels and any OFDM on 5112 */
1070			if (IEEE80211_IS_CHAN_5GHZ(chan) ||
1071			    (IS_RAD5112(ah) && IEEE80211_IS_CHAN_OFDM(chan)))
1072				ar5212RequestRfgain(ah);
1073		}
1074	}
1075	RESTORE_CCK(ah, chan, isBmode);
1076
1077	return AH_TRUE;
1078#undef IQ_CAL_TRIES
1079}
1080
1081HAL_BOOL
1082ar5212PerCalibration(struct ath_hal *ah,  struct ieee80211_channel *chan,
1083	HAL_BOOL *isIQdone)
1084{
1085	return ar5212PerCalibrationN(ah, chan, 0x1, AH_TRUE, isIQdone);
1086}
1087
1088HAL_BOOL
1089ar5212ResetCalValid(struct ath_hal *ah, const struct ieee80211_channel *chan)
1090{
1091	/* XXX */
1092	return AH_TRUE;
1093}
1094
1095/*
1096 * Write the given reset bit mask into the reset register
1097 */
1098static HAL_BOOL
1099ar5212SetResetReg(struct ath_hal *ah, uint32_t resetMask)
1100{
1101	uint32_t mask = resetMask ? resetMask : ~0;
1102	HAL_BOOL rt;
1103
1104	/* XXX ar5212MacStop & co. */
1105
1106	if (IS_PCIE(ah)) {
1107		resetMask &= ~AR_RC_PCI;
1108	}
1109
1110	(void) OS_REG_READ(ah, AR_RXDP);/* flush any pending MMR writes */
1111	OS_REG_WRITE(ah, AR_RC, resetMask);
1112	OS_DELAY(15);			/* need to wait at least 128 clocks
1113					   when reseting PCI before read */
1114	mask &= (AR_RC_MAC | AR_RC_BB);
1115	resetMask &= (AR_RC_MAC | AR_RC_BB);
1116	rt = ath_hal_wait(ah, AR_RC, mask, resetMask);
1117        if ((resetMask & AR_RC_MAC) == 0) {
1118		if (isBigEndian()) {
1119			/*
1120			 * Set CFG, little-endian for register
1121			 * and descriptor accesses.
1122			 */
1123			mask = INIT_CONFIG_STATUS | AR_CFG_SWRD | AR_CFG_SWRG;
1124#ifndef AH_NEED_DESC_SWAP
1125			mask |= AR_CFG_SWTD;
1126#endif
1127			OS_REG_WRITE(ah, AR_CFG, LE_READ_4(&mask));
1128		} else
1129			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
1130		if (ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
1131			(void) OS_REG_READ(ah, AR_ISR_RAC);
1132	}
1133
1134	/* track PHY power state so we don't try to r/w BB registers */
1135	AH5212(ah)->ah_phyPowerOn = ((resetMask & AR_RC_BB) == 0);
1136	return rt;
1137}
1138
1139int16_t
1140ar5212GetNoiseFloor(struct ath_hal *ah)
1141{
1142	int16_t nf = (OS_REG_READ(ah, AR_PHY(25)) >> 19) & 0x1ff;
1143	if (nf & 0x100)
1144		nf = 0 - ((nf ^ 0x1ff) + 1);
1145	return nf;
1146}
1147
1148static HAL_BOOL
1149getNoiseFloorThresh(struct ath_hal *ah, const struct ieee80211_channel *chan,
1150	int16_t *nft)
1151{
1152	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1153
1154	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1155
1156	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1157	case IEEE80211_CHAN_A:
1158		*nft = ee->ee_noiseFloorThresh[headerInfo11A];
1159		break;
1160	case IEEE80211_CHAN_B:
1161		*nft = ee->ee_noiseFloorThresh[headerInfo11B];
1162		break;
1163	case IEEE80211_CHAN_G:
1164	case IEEE80211_CHAN_PUREG:	/* NB: really 108G */
1165		*nft = ee->ee_noiseFloorThresh[headerInfo11G];
1166		break;
1167	default:
1168		HALDEBUG(ah, HAL_DEBUG_ANY,
1169		    "%s: invalid channel flags %u/0x%x\n",
1170		    __func__, chan->ic_freq, chan->ic_flags);
1171		return AH_FALSE;
1172	}
1173	return AH_TRUE;
1174}
1175
1176/*
1177 * Setup the noise floor cal history buffer.
1178 */
1179void
1180ar5212InitNfCalHistBuffer(struct ath_hal *ah)
1181{
1182	struct ath_hal_5212 *ahp = AH5212(ah);
1183	int i;
1184
1185	ahp->ah_nfCalHist.first_run = 1;
1186	ahp->ah_nfCalHist.currIndex = 0;
1187	ahp->ah_nfCalHist.privNF = AR5212_CCA_MAX_GOOD_VALUE;
1188	ahp->ah_nfCalHist.invalidNFcount = AR512_NF_CAL_HIST_MAX;
1189	for (i = 0; i < AR512_NF_CAL_HIST_MAX; i ++)
1190		ahp->ah_nfCalHist.nfCalBuffer[i] = AR5212_CCA_MAX_GOOD_VALUE;
1191}
1192
1193/*
1194 * Add a noise floor value to the ring buffer.
1195 */
1196static __inline void
1197updateNFHistBuff(struct ar5212NfCalHist *h, int16_t nf)
1198{
1199 	h->nfCalBuffer[h->currIndex] = nf;
1200     	if (++h->currIndex >= AR512_NF_CAL_HIST_MAX)
1201		h->currIndex = 0;
1202}
1203
1204/*
1205 * Return the median noise floor value in the ring buffer.
1206 */
1207int16_t
1208ar5212GetNfHistMid(const int16_t calData[AR512_NF_CAL_HIST_MAX])
1209{
1210	int16_t sort[AR512_NF_CAL_HIST_MAX];
1211	int i, j;
1212
1213	OS_MEMCPY(sort, calData, AR512_NF_CAL_HIST_MAX*sizeof(int16_t));
1214	for (i = 0; i < AR512_NF_CAL_HIST_MAX-1; i ++) {
1215		for (j = 1; j < AR512_NF_CAL_HIST_MAX-i; j ++) {
1216			if (sort[j] > sort[j-1]) {
1217				int16_t nf = sort[j];
1218				sort[j] = sort[j-1];
1219				sort[j-1] = nf;
1220			}
1221		}
1222	}
1223	return sort[(AR512_NF_CAL_HIST_MAX-1)>>1];
1224}
1225
1226/*
1227 * Read the NF and check it against the noise floor threshhold
1228 */
1229int16_t
1230ar5212GetNf(struct ath_hal *ah, struct ieee80211_channel *chan)
1231{
1232	struct ath_hal_5212 *ahp = AH5212(ah);
1233	struct ar5212NfCalHist *h = &ahp->ah_nfCalHist;
1234	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1235	int16_t nf, nfThresh;
1236 	int32_t val;
1237
1238	if (OS_REG_READ(ah, AR_PHY_AGC_CONTROL) & AR_PHY_AGC_CONTROL_NF) {
1239		HALDEBUG(ah, HAL_DEBUG_ANY,
1240		    "%s: NF did not complete in calibration window\n", __func__);
1241		ichan->rawNoiseFloor = h->privNF;	/* most recent value */
1242		return ichan->rawNoiseFloor;
1243	}
1244
1245	/*
1246	 * Finished NF cal, check against threshold.
1247	 */
1248	nf = ar5212GetNoiseFloor(ah);
1249	if (getNoiseFloorThresh(ah, chan, &nfThresh)) {
1250		if (nf > nfThresh) {
1251			HALDEBUG(ah, HAL_DEBUG_ANY,
1252			    "%s: noise floor failed detected; detected %u, "
1253			    "threshold %u\n", __func__, nf, nfThresh);
1254			/*
1255			 * NB: Don't discriminate 2.4 vs 5Ghz, if this
1256			 *     happens it indicates a problem regardless
1257			 *     of the band.
1258			 */
1259			chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
1260			nf = 0;
1261		}
1262	} else
1263		nf = 0;
1264
1265	/*
1266	 * Pass through histogram and write median value as
1267	 * calculated from the accrued window.  We require a
1268	 * full window of in-range values to be seen before we
1269	 * start using the history.
1270	 */
1271	updateNFHistBuff(h, nf);
1272	if (h->first_run) {
1273		if (nf < AR5212_CCA_MIN_BAD_VALUE ||
1274		    nf > AR5212_CCA_MAX_HIGH_VALUE) {
1275			nf = AR5212_CCA_MAX_GOOD_VALUE;
1276			h->invalidNFcount = AR512_NF_CAL_HIST_MAX;
1277		} else if (--(h->invalidNFcount) == 0) {
1278			h->first_run = 0;
1279			h->privNF = nf = ar5212GetNfHistMid(h->nfCalBuffer);
1280		} else {
1281			nf = AR5212_CCA_MAX_GOOD_VALUE;
1282		}
1283	} else {
1284		h->privNF = nf = ar5212GetNfHistMid(h->nfCalBuffer);
1285	}
1286
1287	val = OS_REG_READ(ah, AR_PHY(25));
1288	val &= 0xFFFFFE00;
1289	val |= (((uint32_t)nf << 1) & 0x1FF);
1290	OS_REG_WRITE(ah, AR_PHY(25), val);
1291	OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_ENABLE_NF);
1292	OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NO_UPDATE_NF);
1293	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
1294
1295	if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF, 0)) {
1296#ifdef AH_DEBUG
1297		ath_hal_printf(ah, "%s: AGC not ready AGC_CONTROL 0x%x\n",
1298		    __func__, OS_REG_READ(ah, AR_PHY_AGC_CONTROL));
1299#endif
1300	}
1301
1302	/*
1303	 * Now load a high maxCCAPower value again so that we're
1304	 * not capped by the median we just loaded
1305	 */
1306	val &= 0xFFFFFE00;
1307	val |= (((uint32_t)(-50) << 1) & 0x1FF);
1308	OS_REG_WRITE(ah, AR_PHY(25), val);
1309	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_ENABLE_NF);
1310	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NO_UPDATE_NF);
1311	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
1312
1313	return (ichan->rawNoiseFloor = nf);
1314}
1315
1316/*
1317 * Set up compression configuration registers
1318 */
1319void
1320ar5212SetCompRegs(struct ath_hal *ah)
1321{
1322	struct ath_hal_5212 *ahp = AH5212(ah);
1323	int i;
1324
1325        /* Check if h/w supports compression */
1326	if (!AH_PRIVATE(ah)->ah_caps.halCompressSupport)
1327		return;
1328
1329	OS_REG_WRITE(ah, AR_DCCFG, 1);
1330
1331	OS_REG_WRITE(ah, AR_CCFG,
1332		(AR_COMPRESSION_WINDOW_SIZE >> 8) & AR_CCFG_WIN_M);
1333
1334	OS_REG_WRITE(ah, AR_CCFG,
1335		OS_REG_READ(ah, AR_CCFG) | AR_CCFG_MIB_INT_EN);
1336	OS_REG_WRITE(ah, AR_CCUCFG,
1337		AR_CCUCFG_RESET_VAL | AR_CCUCFG_CATCHUP_EN);
1338
1339	OS_REG_WRITE(ah, AR_CPCOVF, 0);
1340
1341	/* reset decompression mask */
1342	for (i = 0; i < HAL_DECOMP_MASK_SIZE; i++) {
1343		OS_REG_WRITE(ah, AR_DCM_A, i);
1344		OS_REG_WRITE(ah, AR_DCM_D, ahp->ah_decompMask[i]);
1345	}
1346}
1347
1348HAL_BOOL
1349ar5212SetAntennaSwitchInternal(struct ath_hal *ah, HAL_ANT_SETTING settings,
1350	const struct ieee80211_channel *chan)
1351{
1352#define	ANT_SWITCH_TABLE1	AR_PHY(88)
1353#define	ANT_SWITCH_TABLE2	AR_PHY(89)
1354	struct ath_hal_5212 *ahp = AH5212(ah);
1355	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1356	uint32_t antSwitchA, antSwitchB;
1357	int ix;
1358
1359	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1360	HALASSERT(ahp->ah_phyPowerOn);
1361
1362	switch (chan->ic_flags & IEEE80211_CHAN_ALLFULL) {
1363	case IEEE80211_CHAN_A:
1364		ix = 0;
1365		break;
1366	case IEEE80211_CHAN_G:
1367	case IEEE80211_CHAN_PUREG:		/* NB: 108G */
1368		ix = 2;
1369		break;
1370	case IEEE80211_CHAN_B:
1371		if (IS_2425(ah) || IS_2417(ah)) {
1372			/* NB: Nala/Swan: 11b is handled using 11g */
1373			ix = 2;
1374		} else
1375			ix = 1;
1376		break;
1377	default:
1378		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1379		    __func__, chan->ic_flags);
1380		return AH_FALSE;
1381	}
1382
1383	antSwitchA =  ee->ee_antennaControl[1][ix]
1384		   | (ee->ee_antennaControl[2][ix] << 6)
1385		   | (ee->ee_antennaControl[3][ix] << 12)
1386		   | (ee->ee_antennaControl[4][ix] << 18)
1387		   | (ee->ee_antennaControl[5][ix] << 24)
1388		   ;
1389	antSwitchB =  ee->ee_antennaControl[6][ix]
1390		   | (ee->ee_antennaControl[7][ix] << 6)
1391		   | (ee->ee_antennaControl[8][ix] << 12)
1392		   | (ee->ee_antennaControl[9][ix] << 18)
1393		   | (ee->ee_antennaControl[10][ix] << 24)
1394		   ;
1395	/*
1396	 * For fixed antenna, give the same setting for both switch banks
1397	 */
1398	switch (settings) {
1399	case HAL_ANT_FIXED_A:
1400		antSwitchB = antSwitchA;
1401		break;
1402	case HAL_ANT_FIXED_B:
1403		antSwitchA = antSwitchB;
1404		break;
1405	case HAL_ANT_VARIABLE:
1406		break;
1407	default:
1408		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: bad antenna setting %u\n",
1409		    __func__, settings);
1410		return AH_FALSE;
1411	}
1412	if (antSwitchB == antSwitchA) {
1413		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
1414		    "%s: Setting fast diversity off.\n", __func__);
1415		OS_REG_CLR_BIT(ah,AR_PHY_CCK_DETECT,
1416			       AR_PHY_CCK_DETECT_BB_ENABLE_ANT_FAST_DIV);
1417		ahp->ah_diversity = AH_FALSE;
1418	} else {
1419		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
1420		    "%s: Setting fast diversity on.\n", __func__);
1421		OS_REG_SET_BIT(ah,AR_PHY_CCK_DETECT,
1422			       AR_PHY_CCK_DETECT_BB_ENABLE_ANT_FAST_DIV);
1423		ahp->ah_diversity = AH_TRUE;
1424	}
1425	ahp->ah_antControl = settings;
1426
1427	OS_REG_WRITE(ah, ANT_SWITCH_TABLE1, antSwitchA);
1428	OS_REG_WRITE(ah, ANT_SWITCH_TABLE2, antSwitchB);
1429
1430	return AH_TRUE;
1431#undef ANT_SWITCH_TABLE2
1432#undef ANT_SWITCH_TABLE1
1433}
1434
1435HAL_BOOL
1436ar5212IsSpurChannel(struct ath_hal *ah, const struct ieee80211_channel *chan)
1437{
1438	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1439	uint32_t clockFreq =
1440	    ((IS_5413(ah) || IS_RAD5112_ANY(ah) || IS_2417(ah)) ? 40 : 32);
1441	return ( ((freq % clockFreq) != 0)
1442              && (((freq % clockFreq) < 10)
1443             || (((freq) % clockFreq) > 22)) );
1444}
1445
1446/*
1447 * Read EEPROM header info and program the device for correct operation
1448 * given the channel value.
1449 */
1450HAL_BOOL
1451ar5212SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1452{
1453#define NO_FALSE_DETECT_BACKOFF   2
1454#define CB22_FALSE_DETECT_BACKOFF 6
1455#define	AR_PHY_BIS(_ah, _reg, _mask, _val) \
1456	OS_REG_WRITE(_ah, AR_PHY(_reg), \
1457		(OS_REG_READ(_ah, AR_PHY(_reg)) & _mask) | (_val));
1458	struct ath_hal_5212 *ahp = AH5212(ah);
1459	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1460	int arrayMode, falseDectectBackoff;
1461	int is2GHz = IEEE80211_IS_CHAN_2GHZ(chan);
1462	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1463	int8_t adcDesiredSize, pgaDesiredSize;
1464	uint16_t switchSettling, txrxAtten, rxtxMargin;
1465	int iCoff, qCoff;
1466
1467	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1468
1469	switch (chan->ic_flags & IEEE80211_CHAN_ALLTURBOFULL) {
1470	case IEEE80211_CHAN_A:
1471	case IEEE80211_CHAN_ST:
1472		arrayMode = headerInfo11A;
1473		if (!IS_RAD5112_ANY(ah) && !IS_2413(ah) && !IS_5413(ah))
1474			OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL,
1475				AR_PHY_FRAME_CTL_TX_CLIP,
1476				ahp->ah_gainValues.currStep->paramVal[GP_TXCLIP]);
1477		break;
1478	case IEEE80211_CHAN_B:
1479		arrayMode = headerInfo11B;
1480		break;
1481	case IEEE80211_CHAN_G:
1482	case IEEE80211_CHAN_108G:
1483		arrayMode = headerInfo11G;
1484		break;
1485	default:
1486		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
1487		    __func__, chan->ic_flags);
1488		return AH_FALSE;
1489	}
1490
1491	/* Set the antenna register(s) correctly for the chip revision */
1492	AR_PHY_BIS(ah, 68, 0xFFFFFC06,
1493		(ee->ee_antennaControl[0][arrayMode] << 4) | 0x1);
1494
1495	ar5212SetAntennaSwitchInternal(ah, ahp->ah_antControl, chan);
1496
1497	/* Set the Noise Floor Thresh on ar5211 devices */
1498	OS_REG_WRITE(ah, AR_PHY(90),
1499		(ee->ee_noiseFloorThresh[arrayMode] & 0x1FF)
1500		| (1 << 9));
1501
1502	if (ee->ee_version >= AR_EEPROM_VER5_0 && IEEE80211_IS_CHAN_TURBO(chan)) {
1503		switchSettling = ee->ee_switchSettlingTurbo[is2GHz];
1504		adcDesiredSize = ee->ee_adcDesiredSizeTurbo[is2GHz];
1505		pgaDesiredSize = ee->ee_pgaDesiredSizeTurbo[is2GHz];
1506		txrxAtten = ee->ee_txrxAttenTurbo[is2GHz];
1507		rxtxMargin = ee->ee_rxtxMarginTurbo[is2GHz];
1508	} else {
1509		switchSettling = ee->ee_switchSettling[arrayMode];
1510		adcDesiredSize = ee->ee_adcDesiredSize[arrayMode];
1511		pgaDesiredSize = ee->ee_pgaDesiredSize[is2GHz];
1512		txrxAtten = ee->ee_txrxAtten[is2GHz];
1513		rxtxMargin = ee->ee_rxtxMargin[is2GHz];
1514	}
1515
1516	OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING,
1517			 AR_PHY_SETTLING_SWITCH, switchSettling);
1518	OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ,
1519			 AR_PHY_DESIRED_SZ_ADC, adcDesiredSize);
1520	OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ,
1521			 AR_PHY_DESIRED_SZ_PGA, pgaDesiredSize);
1522	OS_REG_RMW_FIELD(ah, AR_PHY_RXGAIN,
1523			 AR_PHY_RXGAIN_TXRX_ATTEN, txrxAtten);
1524	OS_REG_WRITE(ah, AR_PHY(13),
1525		(ee->ee_txEndToXPAOff[arrayMode] << 24)
1526		| (ee->ee_txEndToXPAOff[arrayMode] << 16)
1527		| (ee->ee_txFrameToXPAOn[arrayMode] << 8)
1528		| ee->ee_txFrameToXPAOn[arrayMode]);
1529	AR_PHY_BIS(ah, 10, 0xFFFF00FF,
1530		ee->ee_txEndToXLNAOn[arrayMode] << 8);
1531	AR_PHY_BIS(ah, 25, 0xFFF80FFF,
1532		(ee->ee_thresh62[arrayMode] << 12) & 0x7F000);
1533
1534	/*
1535	 * False detect backoff - suspected 32 MHz spur causes false
1536	 * detects in OFDM, causing Tx Hangs.  Decrease weak signal
1537	 * sensitivity for this card.
1538	 */
1539	falseDectectBackoff = NO_FALSE_DETECT_BACKOFF;
1540	if (ee->ee_version < AR_EEPROM_VER3_3) {
1541		/* XXX magic number */
1542		if (AH_PRIVATE(ah)->ah_subvendorid == 0x1022 &&
1543		    IEEE80211_IS_CHAN_OFDM(chan))
1544			falseDectectBackoff += CB22_FALSE_DETECT_BACKOFF;
1545	} else {
1546		if (ar5212IsSpurChannel(ah, chan))
1547			falseDectectBackoff += ee->ee_falseDetectBackoff[arrayMode];
1548	}
1549	AR_PHY_BIS(ah, 73, 0xFFFFFF01, (falseDectectBackoff << 1) & 0xFE);
1550
1551	if (ichan->privFlags & CHANNEL_IQVALID) {
1552		iCoff = ichan->iCoff;
1553		qCoff = ichan->qCoff;
1554	} else {
1555		iCoff = ee->ee_iqCalI[is2GHz];
1556		qCoff = ee->ee_iqCalQ[is2GHz];
1557	}
1558
1559	/* write previous IQ results */
1560	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1561		AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF, iCoff);
1562	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
1563		AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF, qCoff);
1564	OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
1565		AR_PHY_TIMING_CTRL4_IQCORR_ENABLE);
1566
1567	if (ee->ee_version >= AR_EEPROM_VER4_1) {
1568		if (!IEEE80211_IS_CHAN_108G(chan) || ee->ee_version >= AR_EEPROM_VER5_0)
1569			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ,
1570				AR_PHY_GAIN_2GHZ_RXTX_MARGIN, rxtxMargin);
1571	}
1572	if (ee->ee_version >= AR_EEPROM_VER5_1) {
1573		/* for now always disabled */
1574		OS_REG_WRITE(ah,  AR_PHY_HEAVY_CLIP_ENABLE,  0);
1575	}
1576
1577	return AH_TRUE;
1578#undef AR_PHY_BIS
1579#undef NO_FALSE_DETECT_BACKOFF
1580#undef CB22_FALSE_DETECT_BACKOFF
1581}
1582
1583/*
1584 * Apply Spur Immunity to Boards that require it.
1585 * Applies only to OFDM RX operation.
1586 */
1587
1588void
1589ar5212SetSpurMitigation(struct ath_hal *ah,
1590	const struct ieee80211_channel *chan)
1591{
1592	uint32_t pilotMask[2] = {0, 0}, binMagMask[4] = {0, 0, 0 , 0};
1593	uint16_t i, finalSpur, curChanAsSpur, binWidth = 0, spurDetectWidth, spurChan;
1594	int32_t spurDeltaPhase = 0, spurFreqSd = 0, spurOffset, binOffsetNumT16, curBinOffset;
1595	int16_t numBinOffsets;
1596	static const uint16_t magMapFor4[4] = {1, 2, 2, 1};
1597	static const uint16_t magMapFor3[3] = {1, 2, 1};
1598	const uint16_t *pMagMap;
1599	HAL_BOOL is2GHz = IEEE80211_IS_CHAN_2GHZ(chan);
1600	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
1601	uint32_t val;
1602
1603#define CHAN_TO_SPUR(_f, _freq)   ( ((_freq) - ((_f) ? 2300 : 4900)) * 10 )
1604	if (IS_2417(ah)) {
1605		HALDEBUG(ah, HAL_DEBUG_RFPARAM, "%s: no spur mitigation\n",
1606		    __func__);
1607		return;
1608	}
1609
1610	curChanAsSpur = CHAN_TO_SPUR(is2GHz, ichan->channel);
1611
1612	if (ichan->mainSpur) {
1613		/* Pull out the saved spur value */
1614		finalSpur = ichan->mainSpur;
1615	} else {
1616		/*
1617		 * Check if spur immunity should be performed for this channel
1618		 * Should only be performed once per channel and then saved
1619		 */
1620		finalSpur = AR_NO_SPUR;
1621		spurDetectWidth = HAL_SPUR_CHAN_WIDTH;
1622		if (IEEE80211_IS_CHAN_TURBO(chan))
1623			spurDetectWidth *= 2;
1624
1625		/* Decide if any spur affects the current channel */
1626		for (i = 0; i < AR_EEPROM_MODAL_SPURS; i++) {
1627			spurChan = ath_hal_getSpurChan(ah, i, is2GHz);
1628			if (spurChan == AR_NO_SPUR) {
1629				break;
1630			}
1631			if ((curChanAsSpur - spurDetectWidth <= (spurChan & HAL_SPUR_VAL_MASK)) &&
1632			    (curChanAsSpur + spurDetectWidth >= (spurChan & HAL_SPUR_VAL_MASK))) {
1633				finalSpur = spurChan & HAL_SPUR_VAL_MASK;
1634				break;
1635			}
1636		}
1637		/* Save detected spur (or no spur) for this channel */
1638		ichan->mainSpur = finalSpur;
1639	}
1640
1641	/* Write spur immunity data */
1642	if (finalSpur == AR_NO_SPUR) {
1643		/* Disable Spur Immunity Regs if they appear set */
1644		if (OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER) {
1645			/* Clear Spur Delta Phase, Spur Freq, and enable bits */
1646			OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_RATE, 0);
1647			val = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4);
1648			val &= ~(AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER |
1649				 AR_PHY_TIMING_CTRL4_ENABLE_CHAN_MASK |
1650				 AR_PHY_TIMING_CTRL4_ENABLE_PILOT_MASK);
1651			OS_REG_WRITE(ah, AR_PHY_MASK_CTL, val);
1652			OS_REG_WRITE(ah, AR_PHY_TIMING11, 0);
1653
1654			/* Clear pilot masks */
1655			OS_REG_WRITE(ah, AR_PHY_TIMING7, 0);
1656			OS_REG_RMW_FIELD(ah, AR_PHY_TIMING8, AR_PHY_TIMING8_PILOT_MASK_2, 0);
1657			OS_REG_WRITE(ah, AR_PHY_TIMING9, 0);
1658			OS_REG_RMW_FIELD(ah, AR_PHY_TIMING10, AR_PHY_TIMING10_PILOT_MASK_2, 0);
1659
1660			/* Clear magnitude masks */
1661			OS_REG_WRITE(ah, AR_PHY_BIN_MASK_1, 0);
1662			OS_REG_WRITE(ah, AR_PHY_BIN_MASK_2, 0);
1663			OS_REG_WRITE(ah, AR_PHY_BIN_MASK_3, 0);
1664			OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_MASK_4, 0);
1665			OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_1, 0);
1666			OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_2, 0);
1667			OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_3, 0);
1668			OS_REG_RMW_FIELD(ah, AR_PHY_BIN_MASK2_4, AR_PHY_BIN_MASK2_4_MASK_4, 0);
1669		}
1670	} else {
1671		spurOffset = finalSpur - curChanAsSpur;
1672		/*
1673		 * Spur calculations:
1674		 * spurDeltaPhase is (spurOffsetIn100KHz / chipFrequencyIn100KHz) << 21
1675		 * spurFreqSd is (spurOffsetIn100KHz / sampleFrequencyIn100KHz) << 11
1676		 */
1677		if (IEEE80211_IS_CHAN_TURBO(chan)) {
1678			/* Chip Frequency & sampleFrequency are 80 MHz */
1679			spurDeltaPhase = (spurOffset << 16) / 25;
1680			spurFreqSd = spurDeltaPhase >> 10;
1681			binWidth = HAL_BIN_WIDTH_TURBO_100HZ;
1682		} else if (IEEE80211_IS_CHAN_G(chan)) {
1683			/* Chip Frequency is 44MHz, sampleFrequency is 40 MHz */
1684			spurFreqSd = (spurOffset << 8) / 55;
1685			spurDeltaPhase = (spurOffset << 17) / 25;
1686			binWidth = HAL_BIN_WIDTH_BASE_100HZ;
1687		} else {
1688			HALASSERT(!IEEE80211_IS_CHAN_B(chan));
1689			/* Chip Frequency & sampleFrequency are 40 MHz */
1690			spurDeltaPhase = (spurOffset << 17) / 25;
1691			spurFreqSd = spurDeltaPhase >> 10;
1692			binWidth = HAL_BIN_WIDTH_BASE_100HZ;
1693		}
1694
1695		/* Compute Pilot Mask */
1696		binOffsetNumT16 = ((spurOffset * 1000) << 4) / binWidth;
1697		/* The spur is on a bin if it's remainder at times 16 is 0 */
1698		if (binOffsetNumT16 & 0xF) {
1699			numBinOffsets = 4;
1700			pMagMap = magMapFor4;
1701		} else {
1702			numBinOffsets = 3;
1703			pMagMap = magMapFor3;
1704		}
1705		for (i = 0; i < numBinOffsets; i++) {
1706			if ((binOffsetNumT16 >> 4) > HAL_MAX_BINS_ALLOWED) {
1707				HALDEBUG(ah, HAL_DEBUG_ANY,
1708				    "Too man bins in spur mitigation\n");
1709				return;
1710			}
1711
1712			/* Get Pilot Mask values */
1713			curBinOffset = (binOffsetNumT16 >> 4) + i + 25;
1714			if ((curBinOffset >= 0) && (curBinOffset <= 32)) {
1715				if (curBinOffset <= 25)
1716					pilotMask[0] |= 1 << curBinOffset;
1717				else if (curBinOffset >= 27)
1718					pilotMask[0] |= 1 << (curBinOffset - 1);
1719			} else if ((curBinOffset >= 33) && (curBinOffset <= 52))
1720				pilotMask[1] |= 1 << (curBinOffset - 33);
1721
1722			/* Get viterbi values */
1723			if ((curBinOffset >= -1) && (curBinOffset <= 14))
1724				binMagMask[0] |= pMagMap[i] << (curBinOffset + 1) * 2;
1725			else if ((curBinOffset >= 15) && (curBinOffset <= 30))
1726				binMagMask[1] |= pMagMap[i] << (curBinOffset - 15) * 2;
1727			else if ((curBinOffset >= 31) && (curBinOffset <= 46))
1728				binMagMask[2] |= pMagMap[i] << (curBinOffset -31) * 2;
1729			else if((curBinOffset >= 47) && (curBinOffset <= 53))
1730				binMagMask[3] |= pMagMap[i] << (curBinOffset -47) * 2;
1731		}
1732
1733		/* Write Spur Delta Phase, Spur Freq, and enable bits */
1734		OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_RATE, 0xFF);
1735		val = OS_REG_READ(ah, AR_PHY_TIMING_CTRL4);
1736		val |= (AR_PHY_TIMING_CTRL4_ENABLE_SPUR_FILTER |
1737			AR_PHY_TIMING_CTRL4_ENABLE_CHAN_MASK |
1738			AR_PHY_TIMING_CTRL4_ENABLE_PILOT_MASK);
1739		OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4, val);
1740		OS_REG_WRITE(ah, AR_PHY_TIMING11, AR_PHY_TIMING11_USE_SPUR_IN_AGC |
1741			     SM(spurFreqSd, AR_PHY_TIMING11_SPUR_FREQ_SD) |
1742			     SM(spurDeltaPhase, AR_PHY_TIMING11_SPUR_DELTA_PHASE));
1743
1744		/* Write pilot masks */
1745		OS_REG_WRITE(ah, AR_PHY_TIMING7, pilotMask[0]);
1746		OS_REG_RMW_FIELD(ah, AR_PHY_TIMING8, AR_PHY_TIMING8_PILOT_MASK_2, pilotMask[1]);
1747		OS_REG_WRITE(ah, AR_PHY_TIMING9, pilotMask[0]);
1748		OS_REG_RMW_FIELD(ah, AR_PHY_TIMING10, AR_PHY_TIMING10_PILOT_MASK_2, pilotMask[1]);
1749
1750		/* Write magnitude masks */
1751		OS_REG_WRITE(ah, AR_PHY_BIN_MASK_1, binMagMask[0]);
1752		OS_REG_WRITE(ah, AR_PHY_BIN_MASK_2, binMagMask[1]);
1753		OS_REG_WRITE(ah, AR_PHY_BIN_MASK_3, binMagMask[2]);
1754		OS_REG_RMW_FIELD(ah, AR_PHY_MASK_CTL, AR_PHY_MASK_CTL_MASK_4, binMagMask[3]);
1755		OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_1, binMagMask[0]);
1756		OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_2, binMagMask[1]);
1757		OS_REG_WRITE(ah, AR_PHY_BIN_MASK2_3, binMagMask[2]);
1758		OS_REG_RMW_FIELD(ah, AR_PHY_BIN_MASK2_4, AR_PHY_BIN_MASK2_4_MASK_4, binMagMask[3]);
1759	}
1760#undef CHAN_TO_SPUR
1761}
1762
1763
1764/*
1765 * Delta slope coefficient computation.
1766 * Required for OFDM operation.
1767 */
1768void
1769ar5212SetDeltaSlope(struct ath_hal *ah, const struct ieee80211_channel *chan)
1770{
1771#define COEF_SCALE_S 24
1772#define INIT_CLOCKMHZSCALED	0x64000000
1773	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1774	unsigned long coef_scaled, coef_exp, coef_man, ds_coef_exp, ds_coef_man;
1775	unsigned long clockMhzScaled = INIT_CLOCKMHZSCALED;
1776
1777	if (IEEE80211_IS_CHAN_TURBO(chan))
1778		clockMhzScaled *= 2;
1779	/* half and quarter rate can divide the scaled clock by 2 or 4 respectively */
1780	/* scale for selected channel bandwidth */
1781	if (IEEE80211_IS_CHAN_HALF(chan)) {
1782		clockMhzScaled = clockMhzScaled >> 1;
1783	} else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
1784		clockMhzScaled = clockMhzScaled >> 2;
1785	}
1786
1787	/*
1788	 * ALGO -> coef = 1e8/fcarrier*fclock/40;
1789	 * scaled coef to provide precision for this floating calculation
1790	 */
1791	coef_scaled = clockMhzScaled / freq;
1792
1793	/*
1794	 * ALGO -> coef_exp = 14-floor(log2(coef));
1795	 * floor(log2(x)) is the highest set bit position
1796	 */
1797	for (coef_exp = 31; coef_exp > 0; coef_exp--)
1798		if ((coef_scaled >> coef_exp) & 0x1)
1799			break;
1800	/* A coef_exp of 0 is a legal bit position but an unexpected coef_exp */
1801	HALASSERT(coef_exp);
1802	coef_exp = 14 - (coef_exp - COEF_SCALE_S);
1803
1804	/*
1805	 * ALGO -> coef_man = floor(coef* 2^coef_exp+0.5);
1806	 * The coefficient is already shifted up for scaling
1807	 */
1808	coef_man = coef_scaled + (1 << (COEF_SCALE_S - coef_exp - 1));
1809	ds_coef_man = coef_man >> (COEF_SCALE_S - coef_exp);
1810	ds_coef_exp = coef_exp - 16;
1811
1812	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
1813		AR_PHY_TIMING3_DSC_MAN, ds_coef_man);
1814	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
1815		AR_PHY_TIMING3_DSC_EXP, ds_coef_exp);
1816#undef INIT_CLOCKMHZSCALED
1817#undef COEF_SCALE_S
1818}
1819
1820/*
1821 * Set a limit on the overall output power.  Used for dynamic
1822 * transmit power control and the like.
1823 *
1824 * NB: limit is in units of 0.5 dbM.
1825 */
1826HAL_BOOL
1827ar5212SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
1828{
1829	/* XXX blech, construct local writable copy */
1830	struct ieee80211_channel dummy = *AH_PRIVATE(ah)->ah_curchan;
1831	uint16_t dummyXpdGains[2];
1832	HAL_BOOL isBmode;
1833
1834	SAVE_CCK(ah, &dummy, isBmode);
1835	AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
1836	return ar5212SetTransmitPower(ah, &dummy, dummyXpdGains);
1837}
1838
1839/*
1840 * Set the transmit power in the baseband for the given
1841 * operating channel and mode.
1842 */
1843HAL_BOOL
1844ar5212SetTransmitPower(struct ath_hal *ah,
1845	const struct ieee80211_channel *chan, uint16_t *rfXpdGain)
1846{
1847#define	POW_OFDM(_r, _s)	(((0 & 1)<< ((_s)+6)) | (((_r) & 0x3f) << (_s)))
1848#define	POW_CCK(_r, _s)		(((_r) & 0x3f) << (_s))
1849#define	N(a)			(sizeof (a) / sizeof (a[0]))
1850	static const uint16_t tpcScaleReductionTable[5] =
1851		{ 0, 3, 6, 9, MAX_RATE_POWER };
1852	struct ath_hal_5212 *ahp = AH5212(ah);
1853	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1854	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1855	int16_t minPower, maxPower, tpcInDb, powerLimit;
1856	int i;
1857
1858	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1859
1860	OS_MEMZERO(ahp->ah_pcdacTable, ahp->ah_pcdacTableSize);
1861	OS_MEMZERO(ahp->ah_ratesArray, sizeof(ahp->ah_ratesArray));
1862
1863	powerLimit = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
1864	if (powerLimit >= MAX_RATE_POWER || powerLimit == 0)
1865		tpcInDb = tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale];
1866	else
1867		tpcInDb = 0;
1868	if (!ar5212SetRateTable(ah, chan, tpcInDb, powerLimit,
1869				AH_TRUE, &minPower, &maxPower)) {
1870		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set rate table\n",
1871		    __func__);
1872		return AH_FALSE;
1873	}
1874	if (!ahp->ah_rfHal->setPowerTable(ah,
1875		&minPower, &maxPower, chan, rfXpdGain)) {
1876		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set power table\n",
1877		    __func__);
1878		return AH_FALSE;
1879	}
1880
1881	/*
1882	 * Adjust XR power/rate up by 2 dB to account for greater peak
1883	 * to avg ratio - except in newer avg power designs
1884	 */
1885	if (!IS_2413(ah) && !IS_5413(ah))
1886		ahp->ah_ratesArray[15] += 4;
1887	/*
1888	 * txPowerIndexOffset is set by the SetPowerTable() call -
1889	 *  adjust the rate table
1890	 */
1891	for (i = 0; i < N(ahp->ah_ratesArray); i++) {
1892		ahp->ah_ratesArray[i] += ahp->ah_txPowerIndexOffset;
1893		if (ahp->ah_ratesArray[i] > 63)
1894			ahp->ah_ratesArray[i] = 63;
1895	}
1896
1897	if (ee->ee_eepMap < 2) {
1898		/*
1899		 * Correct gain deltas for 5212 G operation -
1900		 * Removed with revised chipset
1901		 */
1902		if (AH_PRIVATE(ah)->ah_phyRev < AR_PHY_CHIP_ID_REV_2 &&
1903		    IEEE80211_IS_CHAN_G(chan)) {
1904			uint16_t cckOfdmPwrDelta;
1905
1906			if (freq == 2484)
1907				cckOfdmPwrDelta = SCALE_OC_DELTA(
1908					ee->ee_cckOfdmPwrDelta -
1909					ee->ee_scaledCh14FilterCckDelta);
1910			else
1911				cckOfdmPwrDelta = SCALE_OC_DELTA(
1912					ee->ee_cckOfdmPwrDelta);
1913			ar5212CorrectGainDelta(ah, cckOfdmPwrDelta);
1914		}
1915		/*
1916		 * Finally, write the power values into the
1917		 * baseband power table
1918		 */
1919		for (i = 0; i < (PWR_TABLE_SIZE/2); i++) {
1920			OS_REG_WRITE(ah, AR_PHY_PCDAC_TX_POWER(i),
1921				 ((((ahp->ah_pcdacTable[2*i + 1] << 8) | 0xff) & 0xffff) << 16)
1922				| (((ahp->ah_pcdacTable[2*i]     << 8) | 0xff) & 0xffff)
1923			);
1924		}
1925	}
1926
1927	/* Write the OFDM power per rate set */
1928	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
1929		POW_OFDM(ahp->ah_ratesArray[3], 24)
1930	      | POW_OFDM(ahp->ah_ratesArray[2], 16)
1931	      | POW_OFDM(ahp->ah_ratesArray[1],  8)
1932	      | POW_OFDM(ahp->ah_ratesArray[0],  0)
1933	);
1934	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
1935		POW_OFDM(ahp->ah_ratesArray[7], 24)
1936	      | POW_OFDM(ahp->ah_ratesArray[6], 16)
1937	      | POW_OFDM(ahp->ah_ratesArray[5],  8)
1938	      | POW_OFDM(ahp->ah_ratesArray[4],  0)
1939	);
1940
1941	/* Write the CCK power per rate set */
1942	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE3,
1943		POW_CCK(ahp->ah_ratesArray[10], 24)
1944	      | POW_CCK(ahp->ah_ratesArray[9],  16)
1945	      | POW_CCK(ahp->ah_ratesArray[15],  8)	/* XR target power */
1946	      | POW_CCK(ahp->ah_ratesArray[8],   0)
1947	);
1948	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE4,
1949		POW_CCK(ahp->ah_ratesArray[14], 24)
1950	      | POW_CCK(ahp->ah_ratesArray[13], 16)
1951	      | POW_CCK(ahp->ah_ratesArray[12],  8)
1952	      | POW_CCK(ahp->ah_ratesArray[11],  0)
1953	);
1954
1955	/*
1956	 * Set max power to 30 dBm and, optionally,
1957	 * enable TPC in tx descriptors.
1958	 */
1959	OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE_MAX, MAX_RATE_POWER |
1960		(ahp->ah_tpcEnabled ? AR_PHY_POWER_TX_RATE_MAX_TPC_ENABLE : 0));
1961
1962	return AH_TRUE;
1963#undef N
1964#undef POW_CCK
1965#undef POW_OFDM
1966}
1967
1968/*
1969 * Sets the transmit power in the baseband for the given
1970 * operating channel and mode.
1971 */
1972static HAL_BOOL
1973ar5212SetRateTable(struct ath_hal *ah, const struct ieee80211_channel *chan,
1974	int16_t tpcScaleReduction, int16_t powerLimit, HAL_BOOL commit,
1975	int16_t *pMinPower, int16_t *pMaxPower)
1976{
1977	struct ath_hal_5212 *ahp = AH5212(ah);
1978	uint16_t freq = ath_hal_gethwchannel(ah, chan);
1979	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
1980	uint16_t *rpow = ahp->ah_ratesArray;
1981	uint16_t twiceMaxEdgePower = MAX_RATE_POWER;
1982	uint16_t twiceMaxEdgePowerCck = MAX_RATE_POWER;
1983	uint16_t twiceMaxRDPower = MAX_RATE_POWER;
1984	int i;
1985	uint8_t cfgCtl;
1986	int8_t twiceAntennaGain, twiceAntennaReduction;
1987	const RD_EDGES_POWER *rep;
1988	TRGT_POWER_INFO targetPowerOfdm, targetPowerCck;
1989	int16_t scaledPower, maxAvailPower = 0;
1990	int16_t r13, r9, r7, r0;
1991
1992	HALASSERT(ah->ah_magic == AR5212_MAGIC);
1993
1994	twiceMaxRDPower = chan->ic_maxregpower * 2;
1995	*pMaxPower = -MAX_RATE_POWER;
1996	*pMinPower = MAX_RATE_POWER;
1997
1998	/* Get conformance test limit maximum for this channel */
1999	cfgCtl = ath_hal_getctl(ah, chan);
2000	for (i = 0; i < ee->ee_numCtls; i++) {
2001		uint16_t twiceMinEdgePower;
2002
2003		if (ee->ee_ctl[i] == 0)
2004			continue;
2005		if (ee->ee_ctl[i] == cfgCtl ||
2006		    cfgCtl == ((ee->ee_ctl[i] & CTL_MODE_M) | SD_NO_CTL)) {
2007			rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
2008			twiceMinEdgePower = ar5212GetMaxEdgePower(freq, rep);
2009			if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
2010				/* Find the minimum of all CTL edge powers that apply to this channel */
2011				twiceMaxEdgePower = AH_MIN(twiceMaxEdgePower, twiceMinEdgePower);
2012			} else {
2013				twiceMaxEdgePower = twiceMinEdgePower;
2014				break;
2015			}
2016		}
2017	}
2018
2019	if (IEEE80211_IS_CHAN_G(chan)) {
2020		/* Check for a CCK CTL for 11G CCK powers */
2021		cfgCtl = (cfgCtl & ~CTL_MODE_M) | CTL_11B;
2022		for (i = 0; i < ee->ee_numCtls; i++) {
2023			uint16_t twiceMinEdgePowerCck;
2024
2025			if (ee->ee_ctl[i] == 0)
2026				continue;
2027			if (ee->ee_ctl[i] == cfgCtl ||
2028			    cfgCtl == ((ee->ee_ctl[i] & CTL_MODE_M) | SD_NO_CTL)) {
2029				rep = &ee->ee_rdEdgesPower[i * NUM_EDGES];
2030				twiceMinEdgePowerCck = ar5212GetMaxEdgePower(freq, rep);
2031				if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
2032					/* Find the minimum of all CTL edge powers that apply to this channel */
2033					twiceMaxEdgePowerCck = AH_MIN(twiceMaxEdgePowerCck, twiceMinEdgePowerCck);
2034				} else {
2035					twiceMaxEdgePowerCck = twiceMinEdgePowerCck;
2036					break;
2037				}
2038			}
2039		}
2040	} else {
2041		/* Set the 11B cck edge power to the one found before */
2042		twiceMaxEdgePowerCck = twiceMaxEdgePower;
2043	}
2044
2045	/* Get Antenna Gain reduction */
2046	if (IEEE80211_IS_CHAN_5GHZ(chan)) {
2047		ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_5, &twiceAntennaGain);
2048	} else {
2049		ath_hal_eepromGet(ah, AR_EEP_ANTGAINMAX_2, &twiceAntennaGain);
2050	}
2051	twiceAntennaReduction =
2052		ath_hal_getantennareduction(ah, chan, twiceAntennaGain);
2053
2054	if (IEEE80211_IS_CHAN_OFDM(chan)) {
2055		/* Get final OFDM target powers */
2056		if (IEEE80211_IS_CHAN_2GHZ(chan)) {
2057			ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11g,
2058				ee->ee_numTargetPwr_11g, &targetPowerOfdm);
2059		} else {
2060			ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11a,
2061				ee->ee_numTargetPwr_11a, &targetPowerOfdm);
2062		}
2063
2064		/* Get Maximum OFDM power */
2065		/* Minimum of target and edge powers */
2066		scaledPower = AH_MIN(twiceMaxEdgePower,
2067				twiceMaxRDPower - twiceAntennaReduction);
2068
2069		/*
2070		 * If turbo is set, reduce power to keep power
2071		 * consumption under 2 Watts.  Note that we always do
2072		 * this unless specially configured.  Then we limit
2073		 * power only for non-AP operation.
2074		 */
2075		if (IEEE80211_IS_CHAN_TURBO(chan)
2076#ifdef AH_ENABLE_AP_SUPPORT
2077		    && AH_PRIVATE(ah)->ah_opmode != HAL_M_HOSTAP
2078#endif
2079		) {
2080			/*
2081			 * If turbo is set, reduce power to keep power
2082			 * consumption under 2 Watts
2083			 */
2084			if (ee->ee_version >= AR_EEPROM_VER3_1)
2085				scaledPower = AH_MIN(scaledPower,
2086					ee->ee_turbo2WMaxPower5);
2087			/*
2088			 * EEPROM version 4.0 added an additional
2089			 * constraint on 2.4GHz channels.
2090			 */
2091			if (ee->ee_version >= AR_EEPROM_VER4_0 &&
2092			    IEEE80211_IS_CHAN_2GHZ(chan))
2093				scaledPower = AH_MIN(scaledPower,
2094					ee->ee_turbo2WMaxPower2);
2095		}
2096
2097		maxAvailPower = AH_MIN(scaledPower,
2098					targetPowerOfdm.twicePwr6_24);
2099
2100		/* Reduce power by max regulatory domain allowed restrictions */
2101		scaledPower = maxAvailPower - (tpcScaleReduction * 2);
2102		scaledPower = (scaledPower < 0) ? 0 : scaledPower;
2103		scaledPower = AH_MIN(scaledPower, powerLimit);
2104
2105		if (commit) {
2106			/* Set OFDM rates 9, 12, 18, 24 */
2107			r0 = rpow[0] = rpow[1] = rpow[2] = rpow[3] = rpow[4] = scaledPower;
2108
2109			/* Set OFDM rates 36, 48, 54, XR */
2110			rpow[5] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr36);
2111			rpow[6] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr48);
2112			r7 = rpow[7] = AH_MIN(rpow[0], targetPowerOfdm.twicePwr54);
2113
2114			if (ee->ee_version >= AR_EEPROM_VER4_0) {
2115				/* Setup XR target power from EEPROM */
2116				rpow[15] = AH_MIN(scaledPower, IEEE80211_IS_CHAN_2GHZ(chan) ?
2117						  ee->ee_xrTargetPower2 : ee->ee_xrTargetPower5);
2118			} else {
2119				/* XR uses 6mb power */
2120				rpow[15] = rpow[0];
2121			}
2122			ahp->ah_ofdmTxPower = *pMaxPower;
2123
2124		} else {
2125			r0 = scaledPower;
2126			r7 = AH_MIN(r0, targetPowerOfdm.twicePwr54);
2127		}
2128		*pMinPower = r7;
2129		*pMaxPower = r0;
2130
2131		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2132		    "%s: MaxRD: %d TurboMax: %d MaxCTL: %d "
2133		    "TPC_Reduction %d chan=%d (0x%x) maxAvailPower=%d pwr6_24=%d, maxPower=%d\n",
2134		    __func__, twiceMaxRDPower, ee->ee_turbo2WMaxPower5,
2135		    twiceMaxEdgePower, tpcScaleReduction * 2,
2136		    chan->ic_freq, chan->ic_flags,
2137		    maxAvailPower, targetPowerOfdm.twicePwr6_24, *pMaxPower);
2138	}
2139
2140	if (IEEE80211_IS_CHAN_CCK(chan)) {
2141		/* Get final CCK target powers */
2142		ar5212GetTargetPowers(ah, chan, ee->ee_trgtPwr_11b,
2143			ee->ee_numTargetPwr_11b, &targetPowerCck);
2144
2145		/* Reduce power by max regulatory domain allowed restrictions */
2146		scaledPower = AH_MIN(twiceMaxEdgePowerCck,
2147			twiceMaxRDPower - twiceAntennaReduction);
2148		if (maxAvailPower < AH_MIN(scaledPower, targetPowerCck.twicePwr6_24))
2149			maxAvailPower = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24);
2150
2151		/* Reduce power by user selection */
2152		scaledPower = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24) - (tpcScaleReduction * 2);
2153		scaledPower = (scaledPower < 0) ? 0 : scaledPower;
2154		scaledPower = AH_MIN(scaledPower, powerLimit);
2155
2156		if (commit) {
2157			/* Set CCK rates 2L, 2S, 5.5L, 5.5S, 11L, 11S */
2158			rpow[8]  = AH_MIN(scaledPower, targetPowerCck.twicePwr6_24);
2159			r9 = rpow[9]  = AH_MIN(scaledPower, targetPowerCck.twicePwr36);
2160			rpow[10] = rpow[9];
2161			rpow[11] = AH_MIN(scaledPower, targetPowerCck.twicePwr48);
2162			rpow[12] = rpow[11];
2163			r13 = rpow[13] = AH_MIN(scaledPower, targetPowerCck.twicePwr54);
2164			rpow[14] = rpow[13];
2165		} else {
2166			r9 = AH_MIN(scaledPower, targetPowerCck.twicePwr36);
2167			r13 = AH_MIN(scaledPower, targetPowerCck.twicePwr54);
2168		}
2169
2170		/* Set min/max power based off OFDM values or initialization */
2171		if (r13 < *pMinPower)
2172			*pMinPower = r13;
2173		if (r9 > *pMaxPower)
2174			*pMaxPower = r9;
2175
2176		HALDEBUG(ah, HAL_DEBUG_RFPARAM,
2177		    "%s: cck: MaxRD: %d MaxCTL: %d "
2178		    "TPC_Reduction %d chan=%d (0x%x) maxAvailPower=%d pwr6_24=%d, maxPower=%d\n",
2179		    __func__, twiceMaxRDPower, twiceMaxEdgePowerCck,
2180		    tpcScaleReduction * 2, chan->ic_freq, chan->ic_flags,
2181		    maxAvailPower, targetPowerCck.twicePwr6_24, *pMaxPower);
2182	}
2183	if (commit) {
2184		ahp->ah_tx6PowerInHalfDbm = *pMaxPower;
2185		AH_PRIVATE(ah)->ah_maxPowerLevel = ahp->ah_tx6PowerInHalfDbm;
2186	}
2187	return AH_TRUE;
2188}
2189
2190HAL_BOOL
2191ar5212GetChipPowerLimits(struct ath_hal *ah, struct ieee80211_channel *chan)
2192{
2193	struct ath_hal_5212 *ahp = AH5212(ah);
2194#if 0
2195	static const uint16_t tpcScaleReductionTable[5] =
2196		{ 0, 3, 6, 9, MAX_RATE_POWER };
2197	int16_t tpcInDb, powerLimit;
2198#endif
2199	int16_t minPower, maxPower;
2200
2201	/*
2202	 * Get Pier table max and min powers.
2203	 */
2204	if (ahp->ah_rfHal->getChannelMaxMinPower(ah, chan, &maxPower, &minPower)) {
2205		/* NB: rf code returns 1/4 dBm units, convert */
2206		chan->ic_maxpower = maxPower / 2;
2207		chan->ic_minpower = minPower / 2;
2208	} else {
2209		HALDEBUG(ah, HAL_DEBUG_ANY,
2210		    "%s: no min/max power for %u/0x%x\n",
2211		    __func__, chan->ic_freq, chan->ic_flags);
2212		chan->ic_maxpower = MAX_RATE_POWER;
2213		chan->ic_minpower = 0;
2214	}
2215#if 0
2216	/*
2217	 * Now adjust to reflect any global scale and/or CTL's.
2218	 * (XXX is that correct?)
2219	 */
2220	powerLimit = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
2221	if (powerLimit >= MAX_RATE_POWER || powerLimit == 0)
2222		tpcInDb = tpcScaleReductionTable[AH_PRIVATE(ah)->ah_tpScale];
2223	else
2224		tpcInDb = 0;
2225	if (!ar5212SetRateTable(ah, chan, tpcInDb, powerLimit,
2226				AH_FALSE, &minPower, &maxPower)) {
2227		HALDEBUG(ah, HAL_DEBUG_ANY,
2228		    "%s: unable to find max/min power\n",__func__);
2229		return AH_FALSE;
2230	}
2231	if (maxPower < chan->ic_maxpower)
2232		chan->ic_maxpower = maxPower;
2233	if (minPower < chan->ic_minpower)
2234		chan->ic_minpower = minPower;
2235	HALDEBUG(ah, HAL_DEBUG_RESET,
2236	    "Chan %d: MaxPow = %d MinPow = %d\n",
2237	    chan->ic_freq, chan->ic_maxpower, chans->ic_minpower);
2238#endif
2239	return AH_TRUE;
2240}
2241
2242/*
2243 * Correct for the gain-delta between ofdm and cck mode target
2244 * powers. Write the results to the rate table and the power table.
2245 *
2246 *   Conventions :
2247 *   1. rpow[ii] is the integer value of 2*(desired power
2248 *    for the rate ii in dBm) to provide 0.5dB resolution. rate
2249 *    mapping is as following :
2250 *     [0..7]  --> ofdm 6, 9, .. 48, 54
2251 *     [8..14] --> cck 1L, 2L, 2S, .. 11L, 11S
2252 *     [15]    --> XR (all rates get the same power)
2253 *   2. powv[ii]  is the pcdac corresponding to ii/2 dBm.
2254 */
2255static void
2256ar5212CorrectGainDelta(struct ath_hal *ah, int twiceOfdmCckDelta)
2257{
2258#define	N(_a)	(sizeof(_a) / sizeof(_a[0]))
2259	struct ath_hal_5212 *ahp = AH5212(ah);
2260	const HAL_EEPROM *ee = AH_PRIVATE(ah)->ah_eeprom;
2261	int16_t ratesIndex[N(ahp->ah_ratesArray)];
2262	uint16_t ii, jj, iter;
2263	int32_t cckIndex;
2264	int16_t gainDeltaAdjust;
2265
2266	HALASSERT(ah->ah_magic == AR5212_MAGIC);
2267
2268	gainDeltaAdjust = ee->ee_cckOfdmGainDelta;
2269
2270	/* make a local copy of desired powers as initial indices */
2271	OS_MEMCPY(ratesIndex, ahp->ah_ratesArray, sizeof(ratesIndex));
2272
2273	/* fix only the CCK indices */
2274	for (ii = 8; ii < 15; ii++) {
2275		/* apply a gain_delta correction of -15 for CCK */
2276		ratesIndex[ii] -= gainDeltaAdjust;
2277
2278		/* Now check for contention with all ofdm target powers */
2279		jj = 0;
2280		iter = 0;
2281		/* indicates not all ofdm rates checked forcontention yet */
2282		while (jj < 16) {
2283			if (ratesIndex[ii] < 0)
2284				ratesIndex[ii] = 0;
2285			if (jj == 8) {		/* skip CCK rates */
2286				jj = 15;
2287				continue;
2288			}
2289			if (ratesIndex[ii] == ahp->ah_ratesArray[jj]) {
2290				if (ahp->ah_ratesArray[jj] == 0)
2291					ratesIndex[ii]++;
2292				else if (iter > 50) {
2293					/*
2294					 * To avoid pathological case of of
2295					 * dm target powers 0 and 0.5dBm
2296					 */
2297					ratesIndex[ii]++;
2298				} else
2299					ratesIndex[ii]--;
2300				/* check with all rates again */
2301				jj = 0;
2302				iter++;
2303			} else
2304				jj++;
2305		}
2306		if (ratesIndex[ii] >= PWR_TABLE_SIZE)
2307			ratesIndex[ii] = PWR_TABLE_SIZE -1;
2308		cckIndex = ahp->ah_ratesArray[ii] - twiceOfdmCckDelta;
2309		if (cckIndex < 0)
2310			cckIndex = 0;
2311
2312		/*
2313		 * Validate that the indexes for the powv are not
2314		 * out of bounds.
2315		 */
2316		HALASSERT(cckIndex < PWR_TABLE_SIZE);
2317		HALASSERT(ratesIndex[ii] < PWR_TABLE_SIZE);
2318		ahp->ah_pcdacTable[ratesIndex[ii]] =
2319			ahp->ah_pcdacTable[cckIndex];
2320	}
2321	/* Override rate per power table with new values */
2322	for (ii = 8; ii < 15; ii++)
2323		ahp->ah_ratesArray[ii] = ratesIndex[ii];
2324#undef N
2325}
2326
2327/*
2328 * Find the maximum conformance test limit for the given channel and CTL info
2329 */
2330static uint16_t
2331ar5212GetMaxEdgePower(uint16_t channel, const RD_EDGES_POWER *pRdEdgesPower)
2332{
2333	/* temp array for holding edge channels */
2334	uint16_t tempChannelList[NUM_EDGES];
2335	uint16_t clo, chi, twiceMaxEdgePower;
2336	int i, numEdges;
2337
2338	/* Get the edge power */
2339	for (i = 0; i < NUM_EDGES; i++) {
2340		if (pRdEdgesPower[i].rdEdge == 0)
2341			break;
2342		tempChannelList[i] = pRdEdgesPower[i].rdEdge;
2343	}
2344	numEdges = i;
2345
2346	ar5212GetLowerUpperValues(channel, tempChannelList,
2347		numEdges, &clo, &chi);
2348	/* Get the index for the lower channel */
2349	for (i = 0; i < numEdges && clo != tempChannelList[i]; i++)
2350		;
2351	/* Is lower channel ever outside the rdEdge? */
2352	HALASSERT(i != numEdges);
2353
2354	if ((clo == chi && clo == channel) || (pRdEdgesPower[i].flag)) {
2355		/*
2356		 * If there's an exact channel match or an inband flag set
2357		 * on the lower channel use the given rdEdgePower
2358		 */
2359		twiceMaxEdgePower = pRdEdgesPower[i].twice_rdEdgePower;
2360		HALASSERT(twiceMaxEdgePower > 0);
2361	} else
2362		twiceMaxEdgePower = MAX_RATE_POWER;
2363	return twiceMaxEdgePower;
2364}
2365
2366/*
2367 * Returns interpolated or the scaled up interpolated value
2368 */
2369static uint16_t
2370interpolate(uint16_t target, uint16_t srcLeft, uint16_t srcRight,
2371	uint16_t targetLeft, uint16_t targetRight)
2372{
2373	uint16_t rv;
2374	int16_t lRatio;
2375
2376	/* to get an accurate ratio, always scale, if want to scale, then don't scale back down */
2377	if ((targetLeft * targetRight) == 0)
2378		return 0;
2379
2380	if (srcRight != srcLeft) {
2381		/*
2382		 * Note the ratio always need to be scaled,
2383		 * since it will be a fraction.
2384		 */
2385		lRatio = (target - srcLeft) * EEP_SCALE / (srcRight - srcLeft);
2386		if (lRatio < 0) {
2387		    /* Return as Left target if value would be negative */
2388		    rv = targetLeft;
2389		} else if (lRatio > EEP_SCALE) {
2390		    /* Return as Right target if Ratio is greater than 100% (SCALE) */
2391		    rv = targetRight;
2392		} else {
2393			rv = (lRatio * targetRight + (EEP_SCALE - lRatio) *
2394					targetLeft) / EEP_SCALE;
2395		}
2396	} else {
2397		rv = targetLeft;
2398	}
2399	return rv;
2400}
2401
2402/*
2403 * Return the four rates of target power for the given target power table
2404 * channel, and number of channels
2405 */
2406static void
2407ar5212GetTargetPowers(struct ath_hal *ah, const struct ieee80211_channel *chan,
2408	const TRGT_POWER_INFO *powInfo,
2409	uint16_t numChannels, TRGT_POWER_INFO *pNewPower)
2410{
2411	uint16_t freq = ath_hal_gethwchannel(ah, chan);
2412	/* temp array for holding target power channels */
2413	uint16_t tempChannelList[NUM_TEST_FREQUENCIES];
2414	uint16_t clo, chi, ixlo, ixhi;
2415	int i;
2416
2417	/* Copy the target powers into the temp channel list */
2418	for (i = 0; i < numChannels; i++)
2419		tempChannelList[i] = powInfo[i].testChannel;
2420
2421	ar5212GetLowerUpperValues(freq, tempChannelList,
2422		numChannels, &clo, &chi);
2423
2424	/* Get the indices for the channel */
2425	ixlo = ixhi = 0;
2426	for (i = 0; i < numChannels; i++) {
2427		if (clo == tempChannelList[i]) {
2428			ixlo = i;
2429		}
2430		if (chi == tempChannelList[i]) {
2431			ixhi = i;
2432			break;
2433		}
2434	}
2435
2436	/*
2437	 * Get the lower and upper channels, target powers,
2438	 * and interpolate between them.
2439	 */
2440	pNewPower->twicePwr6_24 = interpolate(freq, clo, chi,
2441		powInfo[ixlo].twicePwr6_24, powInfo[ixhi].twicePwr6_24);
2442	pNewPower->twicePwr36 = interpolate(freq, clo, chi,
2443		powInfo[ixlo].twicePwr36, powInfo[ixhi].twicePwr36);
2444	pNewPower->twicePwr48 = interpolate(freq, clo, chi,
2445		powInfo[ixlo].twicePwr48, powInfo[ixhi].twicePwr48);
2446	pNewPower->twicePwr54 = interpolate(freq, clo, chi,
2447		powInfo[ixlo].twicePwr54, powInfo[ixhi].twicePwr54);
2448}
2449
2450/*
2451 * Search a list for a specified value v that is within
2452 * EEP_DELTA of the search values.  Return the closest
2453 * values in the list above and below the desired value.
2454 * EEP_DELTA is a factional value; everything is scaled
2455 * so only integer arithmetic is used.
2456 *
2457 * NB: the input list is assumed to be sorted in ascending order
2458 */
2459void
2460ar5212GetLowerUpperValues(uint16_t v, uint16_t *lp, uint16_t listSize,
2461                          uint16_t *vlo, uint16_t *vhi)
2462{
2463	uint32_t target = v * EEP_SCALE;
2464	uint16_t *ep = lp+listSize;
2465
2466	/*
2467	 * Check first and last elements for out-of-bounds conditions.
2468	 */
2469	if (target < (uint32_t)(lp[0] * EEP_SCALE - EEP_DELTA)) {
2470		*vlo = *vhi = lp[0];
2471		return;
2472	}
2473	if (target > (uint32_t)(ep[-1] * EEP_SCALE + EEP_DELTA)) {
2474		*vlo = *vhi = ep[-1];
2475		return;
2476	}
2477
2478	/* look for value being near or between 2 values in list */
2479	for (; lp < ep; lp++) {
2480		/*
2481		 * If value is close to the current value of the list
2482		 * then target is not between values, it is one of the values
2483		 */
2484		if (abs(lp[0] * EEP_SCALE - target) < EEP_DELTA) {
2485			*vlo = *vhi = lp[0];
2486			return;
2487		}
2488		/*
2489		 * Look for value being between current value and next value
2490		 * if so return these 2 values
2491		 */
2492		if (target < (uint32_t)(lp[1] * EEP_SCALE - EEP_DELTA)) {
2493			*vlo = lp[0];
2494			*vhi = lp[1];
2495			return;
2496		}
2497	}
2498	HALASSERT(AH_FALSE);		/* should not reach here */
2499}
2500
2501/*
2502 * Perform analog "swizzling" of parameters into their location
2503 *
2504 * NB: used by RF backends
2505 */
2506void
2507ar5212ModifyRfBuffer(uint32_t *rfBuf, uint32_t reg32, uint32_t numBits,
2508                     uint32_t firstBit, uint32_t column)
2509{
2510#define	MAX_ANALOG_START	319		/* XXX */
2511	uint32_t tmp32, mask, arrayEntry, lastBit;
2512	int32_t bitPosition, bitsLeft;
2513
2514	HALASSERT(column <= 3);
2515	HALASSERT(numBits <= 32);
2516	HALASSERT(firstBit + numBits <= MAX_ANALOG_START);
2517
2518	tmp32 = ath_hal_reverseBits(reg32, numBits);
2519	arrayEntry = (firstBit - 1) / 8;
2520	bitPosition = (firstBit - 1) % 8;
2521	bitsLeft = numBits;
2522	while (bitsLeft > 0) {
2523		lastBit = (bitPosition + bitsLeft > 8) ?
2524			8 : bitPosition + bitsLeft;
2525		mask = (((1 << lastBit) - 1) ^ ((1 << bitPosition) - 1)) <<
2526			(column * 8);
2527		rfBuf[arrayEntry] &= ~mask;
2528		rfBuf[arrayEntry] |= ((tmp32 << bitPosition) <<
2529			(column * 8)) & mask;
2530		bitsLeft -= 8 - bitPosition;
2531		tmp32 = tmp32 >> (8 - bitPosition);
2532		bitPosition = 0;
2533		arrayEntry++;
2534	}
2535#undef MAX_ANALOG_START
2536}
2537
2538/*
2539 * Sets the rate to duration values in MAC - used for multi-
2540 * rate retry.
2541 * The rate duration table needs to cover all valid rate codes;
2542 * the 11g table covers all ofdm rates, while the 11b table
2543 * covers all cck rates => all valid rates get covered between
2544 * these two mode's ratetables!
2545 * But if we're turbo, the ofdm phy is replaced by the turbo phy
2546 * and cck is not valid with turbo => all rates get covered
2547 * by the turbo ratetable only
2548 */
2549void
2550ar5212SetRateDurationTable(struct ath_hal *ah,
2551	const struct ieee80211_channel *chan)
2552{
2553	const HAL_RATE_TABLE *rt;
2554	int i;
2555
2556	/* NB: band doesn't matter for 1/2 and 1/4 rate */
2557	if (IEEE80211_IS_CHAN_HALF(chan)) {
2558		rt = ar5212GetRateTable(ah, HAL_MODE_11A_HALF_RATE);
2559	} else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
2560		rt = ar5212GetRateTable(ah, HAL_MODE_11A_QUARTER_RATE);
2561	} else {
2562		rt = ar5212GetRateTable(ah,
2563			IEEE80211_IS_CHAN_TURBO(chan) ? HAL_MODE_TURBO : HAL_MODE_11G);
2564	}
2565
2566	for (i = 0; i < rt->rateCount; ++i)
2567		OS_REG_WRITE(ah,
2568			AR_RATE_DURATION(rt->info[i].rateCode),
2569			ath_hal_computetxtime(ah, rt,
2570				WLAN_CTRL_FRAME_SIZE,
2571				rt->info[i].controlRate, AH_FALSE));
2572	if (!IEEE80211_IS_CHAN_TURBO(chan)) {
2573		/* 11g Table is used to cover the CCK rates. */
2574		rt = ar5212GetRateTable(ah, HAL_MODE_11G);
2575		for (i = 0; i < rt->rateCount; ++i) {
2576			uint32_t reg = AR_RATE_DURATION(rt->info[i].rateCode);
2577
2578			if (rt->info[i].phy != IEEE80211_T_CCK)
2579				continue;
2580
2581			OS_REG_WRITE(ah, reg,
2582				ath_hal_computetxtime(ah, rt,
2583					WLAN_CTRL_FRAME_SIZE,
2584					rt->info[i].controlRate, AH_FALSE));
2585			/* cck rates have short preamble option also */
2586			if (rt->info[i].shortPreamble) {
2587				reg += rt->info[i].shortPreamble << 2;
2588				OS_REG_WRITE(ah, reg,
2589					ath_hal_computetxtime(ah, rt,
2590						WLAN_CTRL_FRAME_SIZE,
2591						rt->info[i].controlRate,
2592						AH_TRUE));
2593			}
2594		}
2595	}
2596}
2597
2598/* Adjust various register settings based on half/quarter rate clock setting.
2599 * This includes: +USEC, TX/RX latency,
2600 *                + IFS params: slot, eifs, misc etc.
2601 */
2602void
2603ar5212SetIFSTiming(struct ath_hal *ah, const struct ieee80211_channel *chan)
2604{
2605	uint32_t txLat, rxLat, usec, slot, refClock, eifs, init_usec;
2606
2607	HALASSERT(IEEE80211_IS_CHAN_HALF(chan) ||
2608		  IEEE80211_IS_CHAN_QUARTER(chan));
2609
2610	refClock = OS_REG_READ(ah, AR_USEC) & AR_USEC_USEC32;
2611	if (IEEE80211_IS_CHAN_HALF(chan)) {
2612		slot = IFS_SLOT_HALF_RATE;
2613		rxLat = RX_NON_FULL_RATE_LATENCY << AR5212_USEC_RX_LAT_S;
2614		txLat = TX_HALF_RATE_LATENCY << AR5212_USEC_TX_LAT_S;
2615		usec = HALF_RATE_USEC;
2616		eifs = IFS_EIFS_HALF_RATE;
2617		init_usec = INIT_USEC >> 1;
2618	} else { /* quarter rate */
2619		slot = IFS_SLOT_QUARTER_RATE;
2620		rxLat = RX_NON_FULL_RATE_LATENCY << AR5212_USEC_RX_LAT_S;
2621		txLat = TX_QUARTER_RATE_LATENCY << AR5212_USEC_TX_LAT_S;
2622		usec = QUARTER_RATE_USEC;
2623		eifs = IFS_EIFS_QUARTER_RATE;
2624		init_usec = INIT_USEC >> 2;
2625	}
2626
2627	OS_REG_WRITE(ah, AR_USEC, (usec | refClock | txLat | rxLat));
2628	OS_REG_WRITE(ah, AR_D_GBL_IFS_SLOT, slot);
2629	OS_REG_WRITE(ah, AR_D_GBL_IFS_EIFS, eifs);
2630	OS_REG_RMW_FIELD(ah, AR_D_GBL_IFS_MISC,
2631				AR_D_GBL_IFS_MISC_USEC_DURATION, init_usec);
2632}
2633