xref: /freebsd/sys/dev/ath/ath_hal/ar5416/ar5416_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 "ah_eeprom_v14.h"
26 
27 #include "ar5416/ar5416.h"
28 #include "ar5416/ar5416reg.h"
29 #include "ar5416/ar5416phy.h"
30 
31 /* Eeprom versioning macros. Returns true if the version is equal or newer than the ver specified */
32 #define	EEP_MINOR(_ah) \
33 	(AH_PRIVATE(_ah)->ah_eeversion & AR5416_EEP_VER_MINOR_MASK)
34 #define IS_EEP_MINOR_V2(_ah)	(EEP_MINOR(_ah) >= AR5416_EEP_MINOR_VER_2)
35 #define IS_EEP_MINOR_V3(_ah)	(EEP_MINOR(_ah) >= AR5416_EEP_MINOR_VER_3)
36 
37 /* Additional Time delay to wait after activiting the Base band */
38 #define BASE_ACTIVATE_DELAY	100	/* 100 usec */
39 #define PLL_SETTLE_DELAY	300	/* 300 usec */
40 #define RTC_PLL_SETTLE_DELAY    1000    /* 1 ms     */
41 
42 static void ar5416InitDMA(struct ath_hal *ah);
43 static void ar5416InitBB(struct ath_hal *ah, const struct ieee80211_channel *);
44 static void ar5416InitIMR(struct ath_hal *ah, HAL_OPMODE opmode);
45 static void ar5416InitQoS(struct ath_hal *ah);
46 static void ar5416InitUserSettings(struct ath_hal *ah);
47 
48 static HAL_BOOL ar5416SetTransmitPower(struct ath_hal *ah,
49 	const struct ieee80211_channel *chan, uint16_t *rfXpdGain);
50 
51 #if 0
52 static HAL_BOOL	ar5416ChannelChange(struct ath_hal *, const struct ieee80211_channel *);
53 #endif
54 static void ar5416SetDeltaSlope(struct ath_hal *, const struct ieee80211_channel *);
55 
56 static HAL_BOOL ar5416SetResetPowerOn(struct ath_hal *ah);
57 static HAL_BOOL ar5416SetReset(struct ath_hal *ah, int type);
58 static void ar5416InitPLL(struct ath_hal *ah, const struct ieee80211_channel *chan);
59 static HAL_BOOL ar5416SetBoardValues(struct ath_hal *, const struct ieee80211_channel *);
60 static HAL_BOOL ar5416SetPowerPerRateTable(struct ath_hal *ah,
61 	struct ar5416eeprom *pEepData,
62 	const struct ieee80211_channel *chan, int16_t *ratesArray,
63 	uint16_t cfgCtl, uint16_t AntennaReduction,
64 	uint16_t twiceMaxRegulatoryPower,
65 	uint16_t powerLimit);
66 static HAL_BOOL ar5416SetPowerCalTable(struct ath_hal *ah,
67 	struct ar5416eeprom *pEepData,
68 	const struct ieee80211_channel *chan,
69 	int16_t *pTxPowerIndexOffset);
70 static uint16_t ar5416GetMaxEdgePower(uint16_t freq,
71 	CAL_CTL_EDGES *pRdEdgesPower, HAL_BOOL is2GHz);
72 static void ar5416GetTargetPowers(struct ath_hal *ah,
73 	const struct ieee80211_channel *chan, CAL_TARGET_POWER_HT *powInfo,
74 	uint16_t numChannels, CAL_TARGET_POWER_HT *pNewPower,
75 	uint16_t numRates, HAL_BOOL isHt40Target);
76 static void ar5416GetTargetPowersLeg(struct ath_hal *ah,
77 	const struct ieee80211_channel *chan, CAL_TARGET_POWER_LEG *powInfo,
78 	uint16_t numChannels, CAL_TARGET_POWER_LEG *pNewPower,
79 	uint16_t numRates, HAL_BOOL isExtTarget);
80 
81 static int16_t interpolate(uint16_t target, uint16_t srcLeft,
82 	uint16_t srcRight, int16_t targetLeft, int16_t targetRight);
83 static void ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan);
84 static void ar5416GetGainBoundariesAndPdadcs(struct ath_hal *ah,
85 	const struct ieee80211_channel *chan, CAL_DATA_PER_FREQ *pRawDataSet,
86 	uint8_t * bChans, uint16_t availPiers,
87 	uint16_t tPdGainOverlap, int16_t *pMinCalPower,
88 	uint16_t * pPdGainBoundaries, uint8_t * pPDADCValues,
89 	uint16_t numXpdGains);
90 static HAL_BOOL getLowerUpperIndex(uint8_t target, uint8_t *pList,
91 	uint16_t listSize,  uint16_t *indexL, uint16_t *indexR);
92 static HAL_BOOL ar5416FillVpdTable(uint8_t pwrMin, uint8_t pwrMax,
93 	uint8_t *pPwrList, uint8_t *pVpdList,
94 	uint16_t numIntercepts, uint8_t *pRetVpdList);
95 
96 /*
97  * Places the device in and out of reset and then places sane
98  * values in the registers based on EEPROM config, initialization
99  * vectors (as determined by the mode), and station configuration
100  *
101  * bChannelChange is used to preserve DMA/PCU registers across
102  * a HW Reset during channel change.
103  */
104 HAL_BOOL
105 ar5416Reset(struct ath_hal *ah, HAL_OPMODE opmode,
106 	struct ieee80211_channel *chan,
107 	HAL_BOOL bChannelChange, HAL_STATUS *status)
108 {
109 #define	N(a)	(sizeof (a) / sizeof (a[0]))
110 #define	FAIL(_code)	do { ecode = _code; goto bad; } while (0)
111 	struct ath_hal_5212 *ahp = AH5212(ah);
112 	HAL_CHANNEL_INTERNAL *ichan;
113 	uint32_t saveDefAntenna, saveLedState;
114 	uint32_t macStaId1;
115 	uint16_t rfXpdGain[2];
116 	HAL_STATUS ecode;
117 	uint32_t powerVal, rssiThrReg;
118 	uint32_t ackTpcPow, ctsTpcPow, chirpTpcPow;
119 	int i;
120 
121 	OS_MARK(ah, AH_MARK_RESET, bChannelChange);
122 
123 	/* Bring out of sleep mode */
124 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE)) {
125 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip did not wakeup\n",
126 		    __func__);
127 		FAIL(HAL_EIO);
128 	}
129 
130 	/*
131 	 * Map public channel to private.
132 	 */
133 	ichan = ath_hal_checkchannel(ah, chan);
134 	if (ichan == AH_NULL)
135 		FAIL(HAL_EINVAL);
136 	switch (opmode) {
137 	case HAL_M_STA:
138 	case HAL_M_IBSS:
139 	case HAL_M_HOSTAP:
140 	case HAL_M_MONITOR:
141 		break;
142 	default:
143 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid operating mode %u\n",
144 		    __func__, opmode);
145 		FAIL(HAL_EINVAL);
146 		break;
147 	}
148 	HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
149 
150 	/* XXX Turn on fast channel change for 5416 */
151 	/*
152 	 * Preserve the bmiss rssi threshold and count threshold
153 	 * across resets
154 	 */
155 	rssiThrReg = OS_REG_READ(ah, AR_RSSI_THR);
156 	/* If reg is zero, first time thru set to default val */
157 	if (rssiThrReg == 0)
158 		rssiThrReg = INIT_RSSI_THR;
159 
160 	/*
161 	 * Preserve the antenna on a channel change
162 	 */
163 	saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
164 	if (saveDefAntenna == 0)		/* XXX magic constants */
165 		saveDefAntenna = 1;
166 
167 	/* Save hardware flag before chip reset clears the register */
168 	macStaId1 = OS_REG_READ(ah, AR_STA_ID1) &
169 		(AR_STA_ID1_BASE_RATE_11B | AR_STA_ID1_USE_DEFANT);
170 
171 	/* Save led state from pci config register */
172 	saveLedState = OS_REG_READ(ah, AR_MAC_LED) &
173 		(AR_MAC_LED_ASSOC | AR_MAC_LED_MODE |
174 		 AR_MAC_LED_BLINK_THRESH_SEL | AR_MAC_LED_BLINK_SLOW);
175 
176 	if (!ar5416ChipReset(ah, chan)) {
177 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
178 		FAIL(HAL_EIO);
179 	}
180 
181 	/* Restore bmiss rssi & count thresholds */
182 	OS_REG_WRITE(ah, AR_RSSI_THR, rssiThrReg);
183 
184 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
185 
186 	AH5416(ah)->ah_writeIni(ah, chan);
187 
188 	/* Setup 11n MAC/Phy mode registers */
189 	ar5416Set11nRegs(ah, chan);
190 
191 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
192 
193 	HALDEBUG(ah, HAL_DEBUG_RESET, ">>>2 %s: AR_PHY_DAG_CTRLCCK=0x%x\n",
194 		__func__, OS_REG_READ(ah,AR_PHY_DAG_CTRLCCK));
195 	HALDEBUG(ah, HAL_DEBUG_RESET, ">>>2 %s: AR_PHY_ADC_CTL=0x%x\n",
196 		__func__, OS_REG_READ(ah,AR_PHY_ADC_CTL));
197 
198 	/* Set the mute mask to the correct default */
199 	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_2)
200 		OS_REG_WRITE(ah, AR_SEQ_MASK, 0x0000000F);
201 
202 	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_3) {
203 		/* Clear reg to alllow RX_CLEAR line debug */
204 		OS_REG_WRITE(ah, AR_PHY_BLUETOOTH,  0);
205 	}
206 	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_4) {
207 #ifdef notyet
208 		/* Enable burst prefetch for the data queues */
209 		OS_REG_RMW_FIELD(ah, AR_D_FPCTL, ... );
210 		/* Enable double-buffering */
211 		OS_REG_CLR_BIT(ah, AR_TXCFG, AR_TXCFG_DBL_BUF_DIS);
212 #endif
213 	}
214 
215 	/* Set ADC/DAC select values */
216 	OS_REG_WRITE(ah, AR_PHY_SLEEP_SCAL, 0x0e);
217 
218 	if (AH5416(ah)->ah_rx_chainmask == 0x5 ||
219 	    AH5416(ah)->ah_tx_chainmask == 0x5)
220 		OS_REG_WRITE(ah, AR_PHY_ANALOG_SWAP, AR_PHY_SWAP_ALT_CHAIN);
221 	/* Setup Chain Masks */
222 	OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
223 	OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
224 	OS_REG_WRITE(ah, AR_SELFGEN_MASK, AH5416(ah)->ah_tx_chainmask);
225 
226 	/* Setup the transmit power values. */
227 	if (!ar5416SetTransmitPower(ah, chan, rfXpdGain)) {
228 		HALDEBUG(ah, HAL_DEBUG_ANY,
229 		    "%s: error init'ing transmit power\n", __func__);
230 		FAIL(HAL_EIO);
231 	}
232 
233 	/* Write the analog registers */
234 	if (!ahp->ah_rfHal->setRfRegs(ah, chan,
235 	    IEEE80211_IS_CHAN_2GHZ(chan) ? 2: 1, rfXpdGain)) {
236 		HALDEBUG(ah, HAL_DEBUG_ANY,
237 		    "%s: ar5212SetRfRegs failed\n", __func__);
238 		FAIL(HAL_EIO);
239 	}
240 
241 	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
242 	if (IEEE80211_IS_CHAN_OFDM(chan)|| IEEE80211_IS_CHAN_HT(chan))
243 		ar5416SetDeltaSlope(ah, chan);
244 
245 	AH5416(ah)->ah_spurMitigate(ah, chan);
246 
247 	/* Setup board specific options for EEPROM version 3 */
248 	if (!ar5416SetBoardValues(ah, chan)) {
249 		HALDEBUG(ah, HAL_DEBUG_ANY,
250 		    "%s: error setting board options\n", __func__);
251 		FAIL(HAL_EIO);
252 	}
253 
254 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
255 
256 	OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
257 	OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
258 		| macStaId1
259 		| AR_STA_ID1_RTS_USE_DEF
260 		| ahp->ah_staId1Defaults
261 	);
262 	ar5212SetOperatingMode(ah, opmode);
263 
264 	/* Set Venice BSSID mask according to current state */
265 	OS_REG_WRITE(ah, AR_BSSMSKL, LE_READ_4(ahp->ah_bssidmask));
266 	OS_REG_WRITE(ah, AR_BSSMSKU, LE_READ_2(ahp->ah_bssidmask + 4));
267 
268 	/* Restore previous led state */
269 	OS_REG_WRITE(ah, AR_MAC_LED, OS_REG_READ(ah, AR_MAC_LED) | saveLedState);
270 
271 	/* Restore previous antenna */
272 	OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
273 
274 	/* then our BSSID */
275 	OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
276 	OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4));
277 
278 	/* Restore bmiss rssi & count thresholds */
279 	OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
280 
281 	OS_REG_WRITE(ah, AR_ISR, ~0);		/* cleared on write */
282 
283 	if (!ar5212SetChannel(ah, chan))
284 		FAIL(HAL_EIO);
285 
286 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
287 
288 	/* Set 1:1 QCU to DCU mapping for all queues */
289 	for (i = 0; i < AR_NUM_DCU; i++)
290 		OS_REG_WRITE(ah, AR_DQCUMASK(i), 1 << i);
291 
292 	ahp->ah_intrTxqs = 0;
293 	for (i = 0; i < AH_PRIVATE(ah)->ah_caps.halTotalQueues; i++)
294 		ar5212ResetTxQueue(ah, i);
295 
296 	ar5416InitIMR(ah, opmode);
297 	ar5212SetCoverageClass(ah, AH_PRIVATE(ah)->ah_coverageClass, 1);
298 	ar5416InitQoS(ah);
299 	ar5416InitUserSettings(ah);
300 
301 	/*
302 	 * disable seq number generation in hw
303 	 */
304 	 OS_REG_WRITE(ah, AR_STA_ID1,
305 	     OS_REG_READ(ah, AR_STA_ID1) | AR_STA_ID1_PRESERVE_SEQNUM);
306 
307 	ar5416InitDMA(ah);
308 
309 	/*
310 	 * program OBS bus to see MAC interrupts
311 	 */
312 	OS_REG_WRITE(ah, AR_OBS, 8);
313 
314 #ifdef AR5416_INT_MITIGATION
315 	OS_REG_WRITE(ah, AR_MIRT, 0);
316 	OS_REG_RMW_FIELD(ah, AR_RIMT, AR_RIMT_LAST, 500);
317 	OS_REG_RMW_FIELD(ah, AR_RIMT, AR_RIMT_FIRST, 2000);
318 #endif
319 
320 	ar5416InitBB(ah, chan);
321 
322 	/* Setup compression registers */
323 	ar5212SetCompRegs(ah);		/* XXX not needed? */
324 
325 	/*
326 	 * 5416 baseband will check the per rate power table
327 	 * and select the lower of the two
328 	 */
329 	ackTpcPow = 63;
330 	ctsTpcPow = 63;
331 	chirpTpcPow = 63;
332 	powerVal = SM(ackTpcPow, AR_TPC_ACK) |
333 		SM(ctsTpcPow, AR_TPC_CTS) |
334 		SM(chirpTpcPow, AR_TPC_CHIRP);
335 	OS_REG_WRITE(ah, AR_TPC, powerVal);
336 
337 	if (!ar5416InitCal(ah, chan))
338 		FAIL(HAL_ESELFTEST);
339 
340 	AH_PRIVATE(ah)->ah_opmode = opmode;	/* record operating mode */
341 
342 	if (bChannelChange && !IEEE80211_IS_CHAN_DFS(chan))
343 		chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
344 
345 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
346 
347 	OS_MARK(ah, AH_MARK_RESET_DONE, 0);
348 
349 	return AH_TRUE;
350 bad:
351 	OS_MARK(ah, AH_MARK_RESET_DONE, ecode);
352 	if (status != AH_NULL)
353 		*status = ecode;
354 	return AH_FALSE;
355 #undef FAIL
356 #undef N
357 }
358 
359 #if 0
360 /*
361  * This channel change evaluates whether the selected hardware can
362  * perform a synthesizer-only channel change (no reset).  If the
363  * TX is not stopped, or the RFBus cannot be granted in the given
364  * time, the function returns false as a reset is necessary
365  */
366 HAL_BOOL
367 ar5416ChannelChange(struct ath_hal *ah, const structu ieee80211_channel *chan)
368 {
369 	uint32_t       ulCount;
370 	uint32_t   data, synthDelay, qnum;
371 	uint16_t   rfXpdGain[4];
372 	struct ath_hal_5212 *ahp = AH5212(ah);
373 	HAL_CHANNEL_INTERNAL *ichan;
374 
375 	/*
376 	 * Map public channel to private.
377 	 */
378 	ichan = ath_hal_checkchannel(ah, chan);
379 
380 	/* TX must be stopped or RF Bus grant will not work */
381 	for (qnum = 0; qnum < AH_PRIVATE(ah)->ah_caps.halTotalQueues; qnum++) {
382 		if (ar5212NumTxPending(ah, qnum)) {
383 			HALDEBUG(ah, HAL_DEBUG_ANY,
384 			    "%s: frames pending on queue %d\n", __func__, qnum);
385 			return AH_FALSE;
386 		}
387 	}
388 
389 	/*
390 	 * Kill last Baseband Rx Frame - Request analog bus grant
391 	 */
392 	OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, AR_PHY_RFBUS_REQ_REQUEST);
393 	if (!ath_hal_wait(ah, AR_PHY_RFBUS_GNT, AR_PHY_RFBUS_GRANT_EN, AR_PHY_RFBUS_GRANT_EN)) {
394 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: could not kill baseband rx\n",
395 		    __func__);
396 		return AH_FALSE;
397 	}
398 
399 	ar5416Set11nRegs(ah, chan);	/* NB: setup 5416-specific regs */
400 
401 	/* Change the synth */
402 	if (!ar5212SetChannel(ah, chan))
403 		return AH_FALSE;
404 
405 	/* Setup the transmit power values. */
406 	if (!ar5416SetTransmitPower(ah, chan, rfXpdGain)) {
407 		HALDEBUG(ah, HAL_DEBUG_ANY,
408 		    "%s: error init'ing transmit power\n", __func__);
409 		return AH_FALSE;
410 	}
411 
412 	/*
413 	 * Wait for the frequency synth to settle (synth goes on
414 	 * via PHY_ACTIVE_EN).  Read the phy active delay register.
415 	 * Value is in 100ns increments.
416 	 */
417 	data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
418 	if (IS_CHAN_CCK(ichan)) {
419 		synthDelay = (4 * data) / 22;
420 	} else {
421 		synthDelay = data / 10;
422 	}
423 
424 	OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
425 
426 	/* Release the RFBus Grant */
427 	OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, 0);
428 
429 	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
430 	if (IEEE80211_IS_CHAN_OFDM(ichan)|| IEEE80211_IS_CHAN_HT(chan)) {
431 		HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3);
432 		ar5212SetSpurMitigation(ah, chan);
433 		ar5416SetDeltaSlope(ah, chan);
434 	}
435 
436 	/* XXX spur mitigation for Melin */
437 
438 	if (!IEEE80211_IS_CHAN_DFS(chan))
439 		chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
440 
441 	ichan->channel_time = 0;
442 	ichan->tsf_last = ar5212GetTsf64(ah);
443 	ar5212TxEnable(ah, AH_TRUE);
444 	return AH_TRUE;
445 }
446 #endif
447 
448 static void
449 ar5416InitDMA(struct ath_hal *ah)
450 {
451 
452 	/*
453 	 * set AHB_MODE not to do cacheline prefetches
454 	 */
455 	OS_REG_SET_BIT(ah, AR_AHB_MODE, AR_AHB_PREFETCH_RD_EN);
456 
457 	/*
458 	 * let mac dma reads be in 128 byte chunks
459 	 */
460 	OS_REG_WRITE(ah, AR_TXCFG,
461 		(OS_REG_READ(ah, AR_TXCFG) & ~AR_TXCFG_DMASZ_MASK) | AR_TXCFG_DMASZ_128B);
462 
463 	/*
464 	 * let mac dma writes be in 128 byte chunks
465 	 */
466 	OS_REG_WRITE(ah, AR_RXCFG,
467 		(OS_REG_READ(ah, AR_RXCFG) & ~AR_RXCFG_DMASZ_MASK) | AR_RXCFG_DMASZ_128B);
468 
469 	/* XXX restore TX trigger level */
470 
471 	/*
472 	 * Setup receive FIFO threshold to hold off TX activities
473 	 */
474 	OS_REG_WRITE(ah, AR_RXFIFO_CFG, 0x200);
475 
476 	/*
477 	 * reduce the number of usable entries in PCU TXBUF to avoid
478 	 * wrap around.
479 	 */
480 	OS_REG_WRITE(ah, AR_PCU_TXBUF_CTRL, AR_PCU_TXBUF_CTRL_USABLE_SIZE);
481 }
482 
483 static void
484 ar5416InitBB(struct ath_hal *ah, const struct ieee80211_channel *chan)
485 {
486 	uint32_t synthDelay;
487 
488 	/*
489 	 * Wait for the frequency synth to settle (synth goes on
490 	 * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
491 	 * Value is in 100ns increments.
492 	  */
493 	synthDelay = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
494 	if (IEEE80211_IS_CHAN_CCK(chan)) {
495 		synthDelay = (4 * synthDelay) / 22;
496 	} else {
497 		synthDelay /= 10;
498 	}
499 
500 	/* Turn on PLL on 5416 */
501 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s %s channel\n",
502 	    __func__, IEEE80211_IS_CHAN_5GHZ(chan) ? "5GHz" : "2GHz");
503 	ar5416InitPLL(ah, chan);
504 
505 	/* Activate the PHY (includes baseband activate and synthesizer on) */
506 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
507 
508 	/*
509 	 * If the AP starts the calibration before the base band timeout
510 	 * completes  we could get rx_clear false triggering.  Add an
511 	 * extra BASE_ACTIVATE_DELAY usecs to ensure this condition
512 	 * does not happen.
513 	 */
514 	if (IEEE80211_IS_CHAN_HALF(chan)) {
515 		OS_DELAY((synthDelay << 1) + BASE_ACTIVATE_DELAY);
516 	} else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
517 		OS_DELAY((synthDelay << 2) + BASE_ACTIVATE_DELAY);
518 	} else {
519 		OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
520 	}
521 }
522 
523 static void
524 ar5416InitIMR(struct ath_hal *ah, HAL_OPMODE opmode)
525 {
526 	struct ath_hal_5212 *ahp = AH5212(ah);
527 
528 	/*
529 	 * Setup interrupt handling.  Note that ar5212ResetTxQueue
530 	 * manipulates the secondary IMR's as queues are enabled
531 	 * and disabled.  This is done with RMW ops to insure the
532 	 * settings we make here are preserved.
533 	 */
534         ahp->ah_maskReg = AR_IMR_TXERR | AR_IMR_TXURN
535 			| AR_IMR_RXERR | AR_IMR_RXORN
536                         | AR_IMR_BCNMISC;
537 
538 #ifdef AR5416_INT_MITIGATION
539        	ahp->ah_maskReg |= AR_IMR_TXINTM | AR_IMR_RXINTM
540 			|  AR_IMR_TXMINTR | AR_IMR_RXMINTR;
541 #else
542         ahp->ah_maskReg |= AR_IMR_TXOK | AR_IMR_RXOK;
543 #endif
544 	if (opmode == HAL_M_HOSTAP)
545 		ahp->ah_maskReg |= AR_IMR_MIB;
546 	OS_REG_WRITE(ah, AR_IMR, ahp->ah_maskReg);
547 	/* Enable bus errors that are OR'd to set the HIUERR bit */
548 #if 0
549 	OS_REG_WRITE(ah, AR_IMR_S2,
550 	    	OS_REG_READ(ah, AR_IMR_S2) | AR_IMR_S2_GTT | AR_IMR_S2_CST);
551 #endif
552 }
553 
554 static void
555 ar5416InitQoS(struct ath_hal *ah)
556 {
557 	/* QoS support */
558 	OS_REG_WRITE(ah, AR_QOS_CONTROL, 0x100aa);	/* XXX magic */
559 	OS_REG_WRITE(ah, AR_QOS_SELECT, 0x3210);	/* XXX magic */
560 
561 	/* Turn on NOACK Support for QoS packets */
562 	OS_REG_WRITE(ah, AR_NOACK,
563 		SM(2, AR_NOACK_2BIT_VALUE) |
564 		SM(5, AR_NOACK_BIT_OFFSET) |
565 		SM(0, AR_NOACK_BYTE_OFFSET));
566 
567     	/*
568     	 * initialize TXOP for all TIDs
569     	 */
570 	OS_REG_WRITE(ah, AR_TXOP_X, AR_TXOP_X_VAL);
571 	OS_REG_WRITE(ah, AR_TXOP_0_3, 0xFFFFFFFF);
572 	OS_REG_WRITE(ah, AR_TXOP_4_7, 0xFFFFFFFF);
573 	OS_REG_WRITE(ah, AR_TXOP_8_11, 0xFFFFFFFF);
574 	OS_REG_WRITE(ah, AR_TXOP_12_15, 0xFFFFFFFF);
575 }
576 
577 static void
578 ar5416InitUserSettings(struct ath_hal *ah)
579 {
580 	struct ath_hal_5212 *ahp = AH5212(ah);
581 
582 	/* Restore user-specified settings */
583 	if (ahp->ah_miscMode != 0)
584 		OS_REG_WRITE(ah, AR_MISC_MODE, ahp->ah_miscMode);
585 	if (ahp->ah_sifstime != (u_int) -1)
586 		ar5212SetSifsTime(ah, ahp->ah_sifstime);
587 	if (ahp->ah_slottime != (u_int) -1)
588 		ar5212SetSlotTime(ah, ahp->ah_slottime);
589 	if (ahp->ah_acktimeout != (u_int) -1)
590 		ar5212SetAckTimeout(ah, ahp->ah_acktimeout);
591 	if (ahp->ah_ctstimeout != (u_int) -1)
592 		ar5212SetCTSTimeout(ah, ahp->ah_ctstimeout);
593 	if (AH_PRIVATE(ah)->ah_diagreg != 0)
594 		OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
595 #if 0 /* XXX Todo */
596 	if (ahp->ah_globaltxtimeout != (u_int) -1)
597         	ar5416SetGlobalTxTimeout(ah, ahp->ah_globaltxtimeout);
598 #endif
599 }
600 
601 /*
602  * Places the hardware into reset and then pulls it out of reset
603  */
604 HAL_BOOL
605 ar5416ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
606 {
607 	OS_MARK(ah, AH_MARK_CHIPRESET, chan ? chan->ic_freq : 0);
608 	/*
609 	 * Warm reset is optimistic.
610 	 */
611 	if (AR_SREV_MERLIN_20_OR_LATER(ah) &&
612 	    ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) {
613 		if (!ar5416SetResetReg(ah, HAL_RESET_POWER_ON))
614 			return AH_FALSE;
615 	} else {
616 		if (!ar5416SetResetReg(ah, HAL_RESET_WARM))
617 			return AH_FALSE;
618 	}
619 
620 	/* Bring out of sleep mode (AGAIN) */
621 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
622 	       return AH_FALSE;
623 
624 	ar5416InitPLL(ah, chan);
625 
626 	/*
627 	 * Perform warm reset before the mode/PLL/turbo registers
628 	 * are changed in order to deactivate the radio.  Mode changes
629 	 * with an active radio can result in corrupted shifts to the
630 	 * radio device.
631 	 */
632 	if (chan != AH_NULL) {
633 		uint32_t rfMode;
634 
635 		/* treat channel B as channel G , no  B mode suport in owl */
636 		rfMode = IEEE80211_IS_CHAN_CCK(chan) ?
637 		    AR_PHY_MODE_DYNAMIC : AR_PHY_MODE_OFDM;
638 		if (AR_SREV_MERLIN_20(ah) && IS_5GHZ_FAST_CLOCK_EN(ah, chan)) {
639 			/* phy mode bits for 5GHz channels require Fast Clock */
640 			rfMode |= AR_PHY_MODE_DYNAMIC
641 			       |  AR_PHY_MODE_DYN_CCK_DISABLE;
642 		} else if (!AR_SREV_MERLIN_10_OR_LATER(ah)) {
643 			rfMode |= IEEE80211_IS_CHAN_5GHZ(chan) ?
644 				AR_PHY_MODE_RF5GHZ : AR_PHY_MODE_RF2GHZ;
645 		}
646 		OS_REG_WRITE(ah, AR_PHY_MODE, rfMode);
647 	}
648 	return AH_TRUE;
649 }
650 
651 /*
652  * Delta slope coefficient computation.
653  * Required for OFDM operation.
654  */
655 static void
656 ar5416GetDeltaSlopeValues(struct ath_hal *ah, uint32_t coef_scaled,
657                           uint32_t *coef_mantissa, uint32_t *coef_exponent)
658 {
659 #define COEF_SCALE_S 24
660     uint32_t coef_exp, coef_man;
661     /*
662      * ALGO -> coef_exp = 14-floor(log2(coef));
663      * floor(log2(x)) is the highest set bit position
664      */
665     for (coef_exp = 31; coef_exp > 0; coef_exp--)
666             if ((coef_scaled >> coef_exp) & 0x1)
667                     break;
668     /* A coef_exp of 0 is a legal bit position but an unexpected coef_exp */
669     HALASSERT(coef_exp);
670     coef_exp = 14 - (coef_exp - COEF_SCALE_S);
671 
672     /*
673      * ALGO -> coef_man = floor(coef* 2^coef_exp+0.5);
674      * The coefficient is already shifted up for scaling
675      */
676     coef_man = coef_scaled + (1 << (COEF_SCALE_S - coef_exp - 1));
677 
678     *coef_mantissa = coef_man >> (COEF_SCALE_S - coef_exp);
679     *coef_exponent = coef_exp - 16;
680 
681 #undef COEF_SCALE_S
682 }
683 
684 void
685 ar5416SetDeltaSlope(struct ath_hal *ah, const struct ieee80211_channel *chan)
686 {
687 #define INIT_CLOCKMHZSCALED	0x64000000
688 	uint32_t coef_scaled, ds_coef_exp, ds_coef_man;
689 	uint32_t clockMhzScaled;
690 
691 	CHAN_CENTERS centers;
692 
693 	/* half and quarter rate can divide the scaled clock by 2 or 4 respectively */
694 	/* scale for selected channel bandwidth */
695 	clockMhzScaled = INIT_CLOCKMHZSCALED;
696 	if (IEEE80211_IS_CHAN_TURBO(chan))
697 		clockMhzScaled <<= 1;
698 	else if (IEEE80211_IS_CHAN_HALF(chan))
699 		clockMhzScaled >>= 1;
700 	else if (IEEE80211_IS_CHAN_QUARTER(chan))
701 		clockMhzScaled >>= 2;
702 
703 	/*
704 	 * ALGO -> coef = 1e8/fcarrier*fclock/40;
705 	 * scaled coef to provide precision for this floating calculation
706 	 */
707 	ar5416GetChannelCenters(ah, chan, &centers);
708 	coef_scaled = clockMhzScaled / centers.synth_center;
709 
710  	ar5416GetDeltaSlopeValues(ah, coef_scaled, &ds_coef_man, &ds_coef_exp);
711 
712 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
713 		AR_PHY_TIMING3_DSC_MAN, ds_coef_man);
714 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
715 		AR_PHY_TIMING3_DSC_EXP, ds_coef_exp);
716 
717         /*
718          * For Short GI,
719          * scaled coeff is 9/10 that of normal coeff
720          */
721         coef_scaled = (9 * coef_scaled)/10;
722 
723         ar5416GetDeltaSlopeValues(ah, coef_scaled, &ds_coef_man, &ds_coef_exp);
724 
725         /* for short gi */
726         OS_REG_RMW_FIELD(ah, AR_PHY_HALFGI,
727                 AR_PHY_HALFGI_DSC_MAN, ds_coef_man);
728         OS_REG_RMW_FIELD(ah, AR_PHY_HALFGI,
729                 AR_PHY_HALFGI_DSC_EXP, ds_coef_exp);
730 #undef INIT_CLOCKMHZSCALED
731 }
732 
733 /*
734  * Set a limit on the overall output power.  Used for dynamic
735  * transmit power control and the like.
736  *
737  * NB: limit is in units of 0.5 dbM.
738  */
739 HAL_BOOL
740 ar5416SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
741 {
742 	uint16_t dummyXpdGains[2];
743 
744 	AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
745 	return ar5416SetTransmitPower(ah, AH_PRIVATE(ah)->ah_curchan,
746 			dummyXpdGains);
747 }
748 
749 HAL_BOOL
750 ar5416GetChipPowerLimits(struct ath_hal *ah,
751 	struct ieee80211_channel *chan)
752 {
753 	struct ath_hal_5212 *ahp = AH5212(ah);
754 	int16_t minPower, maxPower;
755 
756 	/*
757 	 * Get Pier table max and min powers.
758 	 */
759 	if (ahp->ah_rfHal->getChannelMaxMinPower(ah, chan, &maxPower, &minPower)) {
760 		/* NB: rf code returns 1/4 dBm units, convert */
761 		chan->ic_maxpower = maxPower / 2;
762 		chan->ic_minpower = minPower / 2;
763 	} else {
764 		HALDEBUG(ah, HAL_DEBUG_ANY,
765 		    "%s: no min/max power for %u/0x%x\n",
766 		    __func__, chan->ic_freq, chan->ic_flags);
767 		chan->ic_maxpower = AR5416_MAX_RATE_POWER;
768 		chan->ic_minpower = 0;
769 	}
770 	HALDEBUG(ah, HAL_DEBUG_RESET,
771 	    "Chan %d: MaxPow = %d MinPow = %d\n",
772 	    chan->ic_freq, chan->ic_maxpower, chan->ic_minpower);
773 	return AH_TRUE;
774 }
775 
776 /* XXX gag, this is sick */
777 typedef enum Ar5416_Rates {
778 	rate6mb,  rate9mb,  rate12mb, rate18mb,
779 	rate24mb, rate36mb, rate48mb, rate54mb,
780 	rate1l,   rate2l,   rate2s,   rate5_5l,
781 	rate5_5s, rate11l,  rate11s,  rateXr,
782 	rateHt20_0, rateHt20_1, rateHt20_2, rateHt20_3,
783 	rateHt20_4, rateHt20_5, rateHt20_6, rateHt20_7,
784 	rateHt40_0, rateHt40_1, rateHt40_2, rateHt40_3,
785 	rateHt40_4, rateHt40_5, rateHt40_6, rateHt40_7,
786 	rateDupCck, rateDupOfdm, rateExtCck, rateExtOfdm,
787 	Ar5416RateSize
788 } AR5416_RATES;
789 
790 /**************************************************************
791  * ar5416SetTransmitPower
792  *
793  * Set the transmit power in the baseband for the given
794  * operating channel and mode.
795  */
796 static HAL_BOOL
797 ar5416SetTransmitPower(struct ath_hal *ah,
798 	const struct ieee80211_channel *chan, uint16_t *rfXpdGain)
799 {
800 #define POW_SM(_r, _s)     (((_r) & 0x3f) << (_s))
801 #define N(a)            (sizeof (a) / sizeof (a[0]))
802 
803     MODAL_EEP_HEADER	*pModal;
804     struct ath_hal_5212 *ahp = AH5212(ah);
805     int16_t		ratesArray[Ar5416RateSize];
806     int16_t		txPowerIndexOffset = 0;
807     uint8_t		ht40PowerIncForPdadc = 2;
808     int			i;
809 
810     uint16_t		cfgCtl;
811     uint16_t		powerLimit;
812     uint16_t		twiceAntennaReduction;
813     uint16_t		twiceMaxRegulatoryPower;
814     int16_t		maxPower;
815     HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
816     struct ar5416eeprom	*pEepData = &ee->ee_base;
817 
818     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
819 
820     /* Setup info for the actual eeprom */
821     OS_MEMZERO(ratesArray, sizeof(ratesArray));
822     cfgCtl = ath_hal_getctl(ah, chan);
823     powerLimit = chan->ic_maxregpower * 2;
824     twiceAntennaReduction = chan->ic_maxantgain;
825     twiceMaxRegulatoryPower = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
826     pModal = &pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
827     HALDEBUG(ah, HAL_DEBUG_RESET, "%s Channel=%u CfgCtl=%u\n",
828 	__func__,chan->ic_freq, cfgCtl );
829 
830     if (IS_EEP_MINOR_V2(ah)) {
831         ht40PowerIncForPdadc = pModal->ht40PowerIncForPdadc;
832     }
833 
834     if (!ar5416SetPowerPerRateTable(ah, pEepData,  chan,
835                                     &ratesArray[0],cfgCtl,
836                                     twiceAntennaReduction,
837 				    twiceMaxRegulatoryPower, powerLimit)) {
838         HALDEBUG(ah, HAL_DEBUG_ANY,
839 	    "%s: unable to set tx power per rate table\n", __func__);
840         return AH_FALSE;
841     }
842 
843     if (!ar5416SetPowerCalTable(ah,  pEepData, chan, &txPowerIndexOffset)) {
844         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set power table\n",
845 	    __func__);
846         return AH_FALSE;
847     }
848 
849     maxPower = AH_MAX(ratesArray[rate6mb], ratesArray[rateHt20_0]);
850 
851     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
852         maxPower = AH_MAX(maxPower, ratesArray[rate1l]);
853     }
854 
855     if (IEEE80211_IS_CHAN_HT40(chan)) {
856         maxPower = AH_MAX(maxPower, ratesArray[rateHt40_0]);
857     }
858 
859     ahp->ah_tx6PowerInHalfDbm = maxPower;
860     AH_PRIVATE(ah)->ah_maxPowerLevel = maxPower;
861     ahp->ah_txPowerIndexOffset = txPowerIndexOffset;
862 
863     /*
864      * txPowerIndexOffset is set by the SetPowerTable() call -
865      *  adjust the rate table (0 offset if rates EEPROM not loaded)
866      */
867     for (i = 0; i < N(ratesArray); i++) {
868         ratesArray[i] = (int16_t)(txPowerIndexOffset + ratesArray[i]);
869         if (ratesArray[i] > AR5416_MAX_RATE_POWER)
870             ratesArray[i] = AR5416_MAX_RATE_POWER;
871     }
872 
873 #ifdef AH_EEPROM_DUMP
874     ar5416PrintPowerPerRate(ah, ratesArray);
875 #endif
876 
877     /* Write the OFDM power per rate set */
878     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
879         POW_SM(ratesArray[rate18mb], 24)
880           | POW_SM(ratesArray[rate12mb], 16)
881           | POW_SM(ratesArray[rate9mb], 8)
882           | POW_SM(ratesArray[rate6mb], 0)
883     );
884     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
885         POW_SM(ratesArray[rate54mb], 24)
886           | POW_SM(ratesArray[rate48mb], 16)
887           | POW_SM(ratesArray[rate36mb], 8)
888           | POW_SM(ratesArray[rate24mb], 0)
889     );
890 
891     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
892         /* Write the CCK power per rate set */
893         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE3,
894             POW_SM(ratesArray[rate2s], 24)
895               | POW_SM(ratesArray[rate2l],  16)
896               | POW_SM(ratesArray[rateXr],  8) /* XR target power */
897               | POW_SM(ratesArray[rate1l],   0)
898         );
899         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE4,
900             POW_SM(ratesArray[rate11s], 24)
901               | POW_SM(ratesArray[rate11l], 16)
902               | POW_SM(ratesArray[rate5_5s], 8)
903               | POW_SM(ratesArray[rate5_5l], 0)
904         );
905     HALDEBUG(ah, HAL_DEBUG_RESET,
906 	"%s AR_PHY_POWER_TX_RATE3=0x%x AR_PHY_POWER_TX_RATE4=0x%x\n",
907 	    __func__, OS_REG_READ(ah,AR_PHY_POWER_TX_RATE3),
908 	    OS_REG_READ(ah,AR_PHY_POWER_TX_RATE4));
909     }
910 
911     /* Write the HT20 power per rate set */
912     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE5,
913         POW_SM(ratesArray[rateHt20_3], 24)
914           | POW_SM(ratesArray[rateHt20_2], 16)
915           | POW_SM(ratesArray[rateHt20_1], 8)
916           | POW_SM(ratesArray[rateHt20_0], 0)
917     );
918     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE6,
919         POW_SM(ratesArray[rateHt20_7], 24)
920           | POW_SM(ratesArray[rateHt20_6], 16)
921           | POW_SM(ratesArray[rateHt20_5], 8)
922           | POW_SM(ratesArray[rateHt20_4], 0)
923     );
924 
925     if (IEEE80211_IS_CHAN_HT40(chan)) {
926         /* Write the HT40 power per rate set */
927 	/* Correct PAR difference between HT40 and HT20/LEGACY */
928         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE7,
929             POW_SM(ratesArray[rateHt40_3] + ht40PowerIncForPdadc, 24)
930               | POW_SM(ratesArray[rateHt40_2] + ht40PowerIncForPdadc, 16)
931               | POW_SM(ratesArray[rateHt40_1] + ht40PowerIncForPdadc, 8)
932               | POW_SM(ratesArray[rateHt40_0] + ht40PowerIncForPdadc, 0)
933         );
934         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE8,
935             POW_SM(ratesArray[rateHt40_7] + ht40PowerIncForPdadc, 24)
936               | POW_SM(ratesArray[rateHt40_6] + ht40PowerIncForPdadc, 16)
937               | POW_SM(ratesArray[rateHt40_5] + ht40PowerIncForPdadc, 8)
938               | POW_SM(ratesArray[rateHt40_4] + ht40PowerIncForPdadc, 0)
939         );
940         /* Write the Dup/Ext 40 power per rate set */
941         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE9,
942             POW_SM(ratesArray[rateExtOfdm], 24)
943               | POW_SM(ratesArray[rateExtCck], 16)
944               | POW_SM(ratesArray[rateDupOfdm], 8)
945               | POW_SM(ratesArray[rateDupCck], 0)
946         );
947     }
948 
949     /* Write the Power subtraction for dynamic chain changing, for per-packet powertx */
950     OS_REG_WRITE(ah, AR_PHY_POWER_TX_SUB,
951         POW_SM(pModal->pwrDecreaseFor3Chain, 6)
952           | POW_SM(pModal->pwrDecreaseFor2Chain, 0)
953     );
954     return AH_TRUE;
955 #undef POW_SM
956 #undef N
957 }
958 
959 /*
960  * Exported call to check for a recent gain reading and return
961  * the current state of the thermal calibration gain engine.
962  */
963 HAL_RFGAIN
964 ar5416GetRfgain(struct ath_hal *ah)
965 {
966 	return HAL_RFGAIN_INACTIVE;
967 }
968 
969 /*
970  * Places all of hardware into reset
971  */
972 HAL_BOOL
973 ar5416Disable(struct ath_hal *ah)
974 {
975 	if (!ar5212SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
976 		return AH_FALSE;
977 	return ar5416SetResetReg(ah, HAL_RESET_COLD);
978 }
979 
980 /*
981  * Places the PHY and Radio chips into reset.  A full reset
982  * must be called to leave this state.  The PCI/MAC/PCU are
983  * not placed into reset as we must receive interrupt to
984  * re-enable the hardware.
985  */
986 HAL_BOOL
987 ar5416PhyDisable(struct ath_hal *ah)
988 {
989 	return ar5416SetResetReg(ah, HAL_RESET_WARM);
990 }
991 
992 /*
993  * Write the given reset bit mask into the reset register
994  */
995 HAL_BOOL
996 ar5416SetResetReg(struct ath_hal *ah, uint32_t type)
997 {
998 	switch (type) {
999 	case HAL_RESET_POWER_ON:
1000 		return ar5416SetResetPowerOn(ah);
1001 	case HAL_RESET_WARM:
1002 	case HAL_RESET_COLD:
1003 		return ar5416SetReset(ah, type);
1004 	default:
1005 		HALASSERT(AH_FALSE);
1006 		return AH_FALSE;
1007 	}
1008 }
1009 
1010 static HAL_BOOL
1011 ar5416SetResetPowerOn(struct ath_hal *ah)
1012 {
1013     /* Power On Reset (Hard Reset) */
1014 
1015     /*
1016      * Set force wake
1017      *
1018      * If the MAC was running, previously calling
1019      * reset will wake up the MAC but it may go back to sleep
1020      * before we can start polling.
1021      * Set force wake  stops that
1022      * This must be called before initiating a hard reset.
1023      */
1024     OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1025             AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1026 
1027     /*
1028      * RTC reset and clear
1029      */
1030     OS_REG_WRITE(ah, AR_RTC_RESET, 0);
1031     OS_DELAY(20);
1032     OS_REG_WRITE(ah, AR_RTC_RESET, 1);
1033 
1034     /*
1035      * Poll till RTC is ON
1036      */
1037     if (!ath_hal_wait(ah, AR_RTC_STATUS, AR_RTC_PM_STATUS_M, AR_RTC_STATUS_ON)) {
1038         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: RTC not waking up\n", __func__);
1039         return AH_FALSE;
1040     }
1041 
1042     return ar5416SetReset(ah, HAL_RESET_COLD);
1043 }
1044 
1045 static HAL_BOOL
1046 ar5416SetReset(struct ath_hal *ah, int type)
1047 {
1048     uint32_t tmpReg, mask;
1049 
1050     /*
1051      * Force wake
1052      */
1053     OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1054 	AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1055 
1056     /*
1057      * Reset AHB
1058      */
1059     tmpReg = OS_REG_READ(ah, AR_INTR_SYNC_CAUSE);
1060     if (tmpReg & (AR_INTR_SYNC_LOCAL_TIMEOUT|AR_INTR_SYNC_RADM_CPL_TIMEOUT)) {
1061 	OS_REG_WRITE(ah, AR_INTR_SYNC_ENABLE, 0);
1062 	OS_REG_WRITE(ah, AR_RC, AR_RC_AHB|AR_RC_HOSTIF);
1063     } else {
1064 	OS_REG_WRITE(ah, AR_RC, AR_RC_AHB);
1065     }
1066 
1067     /*
1068      * Set Mac(BB,Phy) Warm Reset
1069      */
1070     switch (type) {
1071     case HAL_RESET_WARM:
1072             OS_REG_WRITE(ah, AR_RTC_RC, AR_RTC_RC_MAC_WARM);
1073             break;
1074     case HAL_RESET_COLD:
1075             OS_REG_WRITE(ah, AR_RTC_RC, AR_RTC_RC_MAC_WARM|AR_RTC_RC_MAC_COLD);
1076             break;
1077     default:
1078             HALASSERT(AH_FALSE);
1079             break;
1080     }
1081 
1082     /*
1083      * Clear resets and force wakeup
1084      */
1085     OS_REG_WRITE(ah, AR_RTC_RC, 0);
1086     if (!ath_hal_wait(ah, AR_RTC_RC, AR_RTC_RC_M, 0)) {
1087         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: RTC stuck in MAC reset\n", __func__);
1088         return AH_FALSE;
1089     }
1090 
1091     /* Clear AHB reset */
1092     OS_REG_WRITE(ah, AR_RC, 0);
1093 
1094 	if (type == HAL_RESET_COLD) {
1095 		if (isBigEndian()) {
1096 			/*
1097 			 * Set CFG, little-endian for register
1098 			 * and descriptor accesses.
1099 			 */
1100 			mask = INIT_CONFIG_STATUS | AR_CFG_SWRD | AR_CFG_SWRG;
1101 #ifndef AH_NEED_DESC_SWAP
1102 			mask |= AR_CFG_SWTD;
1103 #endif
1104 			HALDEBUG(ah, HAL_DEBUG_RESET,
1105 			    "%s Applying descriptor swap\n", __func__);
1106 			OS_REG_WRITE(ah, AR_CFG, LE_READ_4(&mask));
1107 		} else
1108 			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
1109 	}
1110 
1111     ar5416InitPLL(ah, AH_NULL);
1112 
1113     return AH_TRUE;
1114 }
1115 
1116 #ifndef IS_5GHZ_FAST_CLOCK_EN
1117 #define	IS_5GHZ_FAST_CLOCK_EN(ah, chan)	AH_FALSE
1118 #endif
1119 
1120 static void
1121 ar5416InitPLL(struct ath_hal *ah, const struct ieee80211_channel *chan)
1122 {
1123 	uint32_t pll;
1124 
1125 	if (AR_SREV_MERLIN_20(ah) &&
1126 	    chan != AH_NULL && IEEE80211_IS_CHAN_5GHZ(chan)) {
1127 		/*
1128 		 * PLL WAR for Merlin 2.0/2.1
1129 		 * When doing fast clock, set PLL to 0x142c
1130 		 * Else, set PLL to 0x2850 to prevent reset-to-reset variation
1131 		 */
1132 		pll = IS_5GHZ_FAST_CLOCK_EN(ah, chan) ? 0x142c : 0x2850;
1133 	} else if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1134 		pll = SM(0x5, AR_RTC_SOWL_PLL_REFDIV);
1135 		if (chan != AH_NULL) {
1136 			if (IEEE80211_IS_CHAN_HALF(chan))
1137 				pll |= SM(0x1, AR_RTC_SOWL_PLL_CLKSEL);
1138 			else if (IEEE80211_IS_CHAN_QUARTER(chan))
1139 				pll |= SM(0x2, AR_RTC_SOWL_PLL_CLKSEL);
1140 			else if (IEEE80211_IS_CHAN_5GHZ(chan))
1141 				pll |= SM(0x28, AR_RTC_SOWL_PLL_DIV);
1142 			else
1143 				pll |= SM(0x2c, AR_RTC_SOWL_PLL_DIV);
1144 		} else
1145 			pll |= SM(0x2c, AR_RTC_SOWL_PLL_DIV);
1146 	} else if (AR_SREV_SOWL_10_OR_LATER(ah)) {
1147 		pll = SM(0x5, AR_RTC_SOWL_PLL_REFDIV);
1148 		if (chan != AH_NULL) {
1149 			if (IEEE80211_IS_CHAN_HALF(chan))
1150 				pll |= SM(0x1, AR_RTC_SOWL_PLL_CLKSEL);
1151 			else if (IEEE80211_IS_CHAN_QUARTER(chan))
1152 				pll |= SM(0x2, AR_RTC_SOWL_PLL_CLKSEL);
1153 			else if (IEEE80211_IS_CHAN_5GHZ(chan))
1154 				pll |= SM(0x50, AR_RTC_SOWL_PLL_DIV);
1155 			else
1156 				pll |= SM(0x58, AR_RTC_SOWL_PLL_DIV);
1157 		} else
1158 			pll |= SM(0x58, AR_RTC_SOWL_PLL_DIV);
1159 	} else {
1160 		pll = AR_RTC_PLL_REFDIV_5 | AR_RTC_PLL_DIV2;
1161 		if (chan != AH_NULL) {
1162 			if (IEEE80211_IS_CHAN_HALF(chan))
1163 				pll |= SM(0x1, AR_RTC_PLL_CLKSEL);
1164 			else if (IEEE80211_IS_CHAN_QUARTER(chan))
1165 				pll |= SM(0x2, AR_RTC_PLL_CLKSEL);
1166 			else if (IEEE80211_IS_CHAN_5GHZ(chan))
1167 				pll |= SM(0xa, AR_RTC_PLL_DIV);
1168 			else
1169 				pll |= SM(0xb, AR_RTC_PLL_DIV);
1170 		} else
1171 			pll |= SM(0xb, AR_RTC_PLL_DIV);
1172 	}
1173 	OS_REG_WRITE(ah, AR_RTC_PLL_CONTROL, pll);
1174 
1175 	/* TODO:
1176 	* For multi-band owl, switch between bands by reiniting the PLL.
1177 	*/
1178 
1179 	OS_DELAY(RTC_PLL_SETTLE_DELAY);
1180 
1181 	OS_REG_WRITE(ah, AR_RTC_SLEEP_CLK, AR_RTC_SLEEP_DERIVED_CLK);
1182 }
1183 
1184 /*
1185  * Read EEPROM header info and program the device for correct operation
1186  * given the channel value.
1187  */
1188 static HAL_BOOL
1189 ar5416SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1190 {
1191     const HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
1192     const struct ar5416eeprom *eep = &ee->ee_base;
1193     const MODAL_EEP_HEADER *pModal;
1194     int			i, regChainOffset;
1195     uint8_t		txRxAttenLocal;    /* workaround for eeprom versions <= 14.2 */
1196 
1197     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
1198     pModal = &eep->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
1199 
1200     /* NB: workaround for eeprom versions <= 14.2 */
1201     txRxAttenLocal = IEEE80211_IS_CHAN_2GHZ(chan) ? 23 : 44;
1202 
1203     OS_REG_WRITE(ah, AR_PHY_SWITCH_COM, pModal->antCtrlCommon);
1204     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
1205 	   if (AR_SREV_MERLIN(ah)) {
1206 		if (i >= 2) break;
1207 	   }
1208        	   if (AR_SREV_OWL_20_OR_LATER(ah) &&
1209             (AH5416(ah)->ah_rx_chainmask == 0x5 ||
1210 	     AH5416(ah)->ah_tx_chainmask == 0x5) && i != 0) {
1211             /* Regs are swapped from chain 2 to 1 for 5416 2_0 with
1212              * only chains 0 and 2 populated
1213              */
1214             regChainOffset = (i == 1) ? 0x2000 : 0x1000;
1215         } else {
1216             regChainOffset = i * 0x1000;
1217         }
1218 
1219         OS_REG_WRITE(ah, AR_PHY_SWITCH_CHAIN_0 + regChainOffset, pModal->antCtrlChain[i]);
1220         OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4 + regChainOffset,
1221         	(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4 + regChainOffset) &
1222         	~(AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF | AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF)) |
1223         	SM(pModal->iqCalICh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF) |
1224         	SM(pModal->iqCalQCh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF));
1225 
1226         /*
1227          * Large signal upgrade.
1228 	 * XXX update
1229          */
1230 
1231         if ((i == 0) || AR_SREV_OWL_20_OR_LATER(ah)) {
1232             OS_REG_WRITE(ah, AR_PHY_RXGAIN + regChainOffset,
1233 		(OS_REG_READ(ah, AR_PHY_RXGAIN + regChainOffset) & ~AR_PHY_RXGAIN_TXRX_ATTEN) |
1234 			SM(IS_EEP_MINOR_V3(ah)  ? pModal->txRxAttenCh[i] : txRxAttenLocal,
1235 				AR_PHY_RXGAIN_TXRX_ATTEN));
1236 
1237             OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1238 	    	(OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + regChainOffset) & ~AR_PHY_GAIN_2GHZ_RXTX_MARGIN) |
1239 			SM(pModal->rxTxMarginCh[i], AR_PHY_GAIN_2GHZ_RXTX_MARGIN));
1240         }
1241     }
1242 
1243     OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH, pModal->switchSettling);
1244     OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_ADC, pModal->adcDesiredSize);
1245     OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_PGA, pModal->pgaDesiredSize);
1246     OS_REG_WRITE(ah, AR_PHY_RF_CTL4,
1247         SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAA_OFF)
1248         | SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAB_OFF)
1249         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAA_ON)
1250         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAB_ON));
1251 
1252     OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL3, AR_PHY_TX_END_TO_A2_RX_ON, pModal->txEndToRxOn);
1253 
1254     if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1255 	OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR9280_PHY_CCA_THRESH62,
1256 	    pModal->thresh62);
1257 	OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA0, AR_PHY_EXT_CCA0_THRESH62,
1258 	    pModal->thresh62);
1259     } else {
1260 	OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR_PHY_CCA_THRESH62,
1261 	    pModal->thresh62);
1262 	OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA0, AR_PHY_EXT_CCA_THRESH62,
1263 	    pModal->thresh62);
1264     }
1265 
1266     /* Minor Version Specific application */
1267     if (IS_EEP_MINOR_V2(ah)) {
1268         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2,  AR_PHY_TX_FRAME_TO_DATA_START, pModal->txFrameToDataStart);
1269         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2,  AR_PHY_TX_FRAME_TO_PA_ON, pModal->txFrameToPaOn);
1270     }
1271 
1272     if (IS_EEP_MINOR_V3(ah)) {
1273 	if (IEEE80211_IS_CHAN_HT40(chan)) {
1274 		/* Overwrite switch settling with HT40 value */
1275 		OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH, pModal->swSettleHt40);
1276 	}
1277 
1278         if ((AR_SREV_OWL_20_OR_LATER(ah)) &&
1279             (  AH5416(ah)->ah_rx_chainmask == 0x5 || AH5416(ah)->ah_tx_chainmask == 0x5)){
1280             /* Reg Offsets are swapped for logical mapping */
1281 		OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x1000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x1000) & ~AR_PHY_GAIN_2GHZ_BSW_MARGIN) |
1282 			SM(pModal->bswMargin[2], AR_PHY_GAIN_2GHZ_BSW_MARGIN));
1283 		OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x1000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x1000) & ~AR_PHY_GAIN_2GHZ_BSW_ATTEN) |
1284 			SM(pModal->bswAtten[2], AR_PHY_GAIN_2GHZ_BSW_ATTEN));
1285 		OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x2000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x2000) & ~AR_PHY_GAIN_2GHZ_BSW_MARGIN) |
1286 			SM(pModal->bswMargin[1], AR_PHY_GAIN_2GHZ_BSW_MARGIN));
1287 		OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x2000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x2000) & ~AR_PHY_GAIN_2GHZ_BSW_ATTEN) |
1288 			SM(pModal->bswAtten[1], AR_PHY_GAIN_2GHZ_BSW_ATTEN));
1289         } else {
1290 		OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x1000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x1000) & ~AR_PHY_GAIN_2GHZ_BSW_MARGIN) |
1291 			SM(pModal->bswMargin[1], AR_PHY_GAIN_2GHZ_BSW_MARGIN));
1292 		OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x1000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x1000) & ~AR_PHY_GAIN_2GHZ_BSW_ATTEN) |
1293 			SM(pModal->bswAtten[1], AR_PHY_GAIN_2GHZ_BSW_ATTEN));
1294 		OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x2000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x2000) & ~AR_PHY_GAIN_2GHZ_BSW_MARGIN) |
1295 			SM(pModal->bswMargin[2],AR_PHY_GAIN_2GHZ_BSW_MARGIN));
1296 		OS_REG_WRITE(ah, AR_PHY_GAIN_2GHZ + 0x2000, (OS_REG_READ(ah, AR_PHY_GAIN_2GHZ + 0x2000) & ~AR_PHY_GAIN_2GHZ_BSW_ATTEN) |
1297 			SM(pModal->bswAtten[2], AR_PHY_GAIN_2GHZ_BSW_ATTEN));
1298         }
1299         OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ, AR_PHY_GAIN_2GHZ_BSW_MARGIN, pModal->bswMargin[0]);
1300         OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ, AR_PHY_GAIN_2GHZ_BSW_ATTEN, pModal->bswAtten[0]);
1301     }
1302     return AH_TRUE;
1303 }
1304 
1305 /*
1306  * Helper functions common for AP/CB/XB
1307  */
1308 
1309 /*
1310  * ar5416SetPowerPerRateTable
1311  *
1312  * Sets the transmit power in the baseband for the given
1313  * operating channel and mode.
1314  */
1315 static HAL_BOOL
1316 ar5416SetPowerPerRateTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
1317                            const struct ieee80211_channel *chan,
1318                            int16_t *ratesArray, uint16_t cfgCtl,
1319                            uint16_t AntennaReduction,
1320                            uint16_t twiceMaxRegulatoryPower,
1321                            uint16_t powerLimit)
1322 {
1323 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1324 /* Local defines to distinguish between extension and control CTL's */
1325 #define EXT_ADDITIVE (0x8000)
1326 #define CTL_11A_EXT (CTL_11A | EXT_ADDITIVE)
1327 #define CTL_11G_EXT (CTL_11G | EXT_ADDITIVE)
1328 #define CTL_11B_EXT (CTL_11B | EXT_ADDITIVE)
1329 
1330 	uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
1331 	int i;
1332 	int16_t  twiceLargestAntenna;
1333 	CAL_CTL_DATA *rep;
1334 	CAL_TARGET_POWER_LEG targetPowerOfdm, targetPowerCck = {0, {0, 0, 0, 0}};
1335 	CAL_TARGET_POWER_LEG targetPowerOfdmExt = {0, {0, 0, 0, 0}}, targetPowerCckExt = {0, {0, 0, 0, 0}};
1336 	CAL_TARGET_POWER_HT  targetPowerHt20, targetPowerHt40 = {0, {0, 0, 0, 0}};
1337 	int16_t scaledPower, minCtlPower;
1338 
1339 #define SUB_NUM_CTL_MODES_AT_5G_40 2   /* excluding HT40, EXT-OFDM */
1340 #define SUB_NUM_CTL_MODES_AT_2G_40 3   /* excluding HT40, EXT-OFDM, EXT-CCK */
1341 	static const uint16_t ctlModesFor11a[] = {
1342 	   CTL_11A, CTL_5GHT20, CTL_11A_EXT, CTL_5GHT40
1343 	};
1344 	static const uint16_t ctlModesFor11g[] = {
1345 	   CTL_11B, CTL_11G, CTL_2GHT20, CTL_11B_EXT, CTL_11G_EXT, CTL_2GHT40
1346 	};
1347 	const uint16_t *pCtlMode;
1348 	uint16_t numCtlModes, ctlMode, freq;
1349 	CHAN_CENTERS centers;
1350 
1351 	ar5416GetChannelCenters(ah,  chan, &centers);
1352 
1353 	/* Compute TxPower reduction due to Antenna Gain */
1354 
1355 	twiceLargestAntenna = AH_MAX(AH_MAX(
1356 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0],
1357 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]),
1358 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1359 #if 0
1360 	/* Turn it back on if we need to calculate per chain antenna gain reduction */
1361 	/* Use only if the expected gain > 6dbi */
1362 	/* Chain 0 is always used */
1363 	twiceLargestAntenna = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0];
1364 
1365 	/* Look at antenna gains of Chains 1 and 2 if the TX mask is set */
1366 	if (ahp->ah_tx_chainmask & 0x2)
1367 		twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1368 			pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]);
1369 
1370 	if (ahp->ah_tx_chainmask & 0x4)
1371 		twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1372 			pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1373 #endif
1374 	twiceLargestAntenna = (int16_t)AH_MIN((AntennaReduction) - twiceLargestAntenna, 0);
1375 
1376 	/* XXX setup for 5212 use (really used?) */
1377 	ath_hal_eepromSet(ah,
1378 	    IEEE80211_IS_CHAN_2GHZ(chan) ? AR_EEP_ANTGAINMAX_2 : AR_EEP_ANTGAINMAX_5,
1379 	    twiceLargestAntenna);
1380 
1381 	/*
1382 	 * scaledPower is the minimum of the user input power level and
1383 	 * the regulatory allowed power level
1384 	 */
1385 	scaledPower = AH_MIN(powerLimit, twiceMaxRegulatoryPower + twiceLargestAntenna);
1386 
1387 	/* Reduce scaled Power by number of chains active to get to per chain tx power level */
1388 	/* TODO: better value than these? */
1389 	switch (owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask)) {
1390 	case 1:
1391 		break;
1392 	case 2:
1393 		scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor2Chain;
1394 		break;
1395 	case 3:
1396 		scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor3Chain;
1397 		break;
1398 	default:
1399 		return AH_FALSE; /* Unsupported number of chains */
1400 	}
1401 
1402 	scaledPower = AH_MAX(0, scaledPower);
1403 
1404 	/* Get target powers from EEPROM - our baseline for TX Power */
1405 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1406 		/* Setup for CTL modes */
1407 		numCtlModes = N(ctlModesFor11g) - SUB_NUM_CTL_MODES_AT_2G_40; /* CTL_11B, CTL_11G, CTL_2GHT20 */
1408 		pCtlMode = ctlModesFor11g;
1409 
1410 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1411 				AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCck, 4, AH_FALSE);
1412 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1413 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1414 		ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT20,
1415 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1416 
1417 		if (IEEE80211_IS_CHAN_HT40(chan)) {
1418 			numCtlModes = N(ctlModesFor11g);    /* All 2G CTL's */
1419 
1420 			ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT40,
1421 				AR5416_NUM_2G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1422 			/* Get target powers for extension channels */
1423 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1424 				AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCckExt, 4, AH_TRUE);
1425 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1426 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1427 		}
1428 	} else {
1429 		/* Setup for CTL modes */
1430 		numCtlModes = N(ctlModesFor11a) - SUB_NUM_CTL_MODES_AT_5G_40; /* CTL_11A, CTL_5GHT20 */
1431 		pCtlMode = ctlModesFor11a;
1432 
1433 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1434 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1435 		ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT20,
1436 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1437 
1438 		if (IEEE80211_IS_CHAN_HT40(chan)) {
1439 			numCtlModes = N(ctlModesFor11a); /* All 5G CTL's */
1440 
1441 			ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT40,
1442 				AR5416_NUM_5G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1443 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1444 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1445 		}
1446 	}
1447 
1448 	/*
1449 	 * For MIMO, need to apply regulatory caps individually across dynamically
1450 	 * running modes: CCK, OFDM, HT20, HT40
1451 	 *
1452 	 * The outer loop walks through each possible applicable runtime mode.
1453 	 * The inner loop walks through each ctlIndex entry in EEPROM.
1454 	 * The ctl value is encoded as [7:4] == test group, [3:0] == test mode.
1455 	 *
1456 	 */
1457 	for (ctlMode = 0; ctlMode < numCtlModes; ctlMode++) {
1458 		HAL_BOOL isHt40CtlMode = (pCtlMode[ctlMode] == CTL_5GHT40) ||
1459 		    (pCtlMode[ctlMode] == CTL_2GHT40);
1460 		if (isHt40CtlMode) {
1461 			freq = centers.ctl_center;
1462 		} else if (pCtlMode[ctlMode] & EXT_ADDITIVE) {
1463 			freq = centers.ext_center;
1464 		} else {
1465 			freq = centers.ctl_center;
1466 		}
1467 
1468 		/* walk through each CTL index stored in EEPROM */
1469 		for (i = 0; (i < AR5416_NUM_CTLS) && pEepData->ctlIndex[i]; i++) {
1470 			uint16_t twiceMinEdgePower;
1471 
1472 			/* compare test group from regulatory channel list with test mode from pCtlMode list */
1473 			if ((((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) == pEepData->ctlIndex[i]) ||
1474 				(((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) ==
1475 				 ((pEepData->ctlIndex[i] & CTL_MODE_M) | SD_NO_CTL))) {
1476 				rep = &(pEepData->ctlData[i]);
1477 				twiceMinEdgePower = ar5416GetMaxEdgePower(freq,
1478 							rep->ctlEdges[owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask) - 1],
1479 							IEEE80211_IS_CHAN_2GHZ(chan));
1480 				if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
1481 					/* Find the minimum of all CTL edge powers that apply to this channel */
1482 					twiceMaxEdgePower = AH_MIN(twiceMaxEdgePower, twiceMinEdgePower);
1483 				} else {
1484 					/* specific */
1485 					twiceMaxEdgePower = twiceMinEdgePower;
1486 					break;
1487 				}
1488 			}
1489 		}
1490 		minCtlPower = (uint8_t)AH_MIN(twiceMaxEdgePower, scaledPower);
1491 		/* Apply ctl mode to correct target power set */
1492 		switch(pCtlMode[ctlMode]) {
1493 		case CTL_11B:
1494 			for (i = 0; i < N(targetPowerCck.tPow2x); i++) {
1495 				targetPowerCck.tPow2x[i] = (uint8_t)AH_MIN(targetPowerCck.tPow2x[i], minCtlPower);
1496 			}
1497 			break;
1498 		case CTL_11A:
1499 		case CTL_11G:
1500 			for (i = 0; i < N(targetPowerOfdm.tPow2x); i++) {
1501 				targetPowerOfdm.tPow2x[i] = (uint8_t)AH_MIN(targetPowerOfdm.tPow2x[i], minCtlPower);
1502 			}
1503 			break;
1504 		case CTL_5GHT20:
1505 		case CTL_2GHT20:
1506 			for (i = 0; i < N(targetPowerHt20.tPow2x); i++) {
1507 				targetPowerHt20.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt20.tPow2x[i], minCtlPower);
1508 			}
1509 			break;
1510 		case CTL_11B_EXT:
1511 			targetPowerCckExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerCckExt.tPow2x[0], minCtlPower);
1512 			break;
1513 		case CTL_11A_EXT:
1514 		case CTL_11G_EXT:
1515 			targetPowerOfdmExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerOfdmExt.tPow2x[0], minCtlPower);
1516 			break;
1517 		case CTL_5GHT40:
1518 		case CTL_2GHT40:
1519 			for (i = 0; i < N(targetPowerHt40.tPow2x); i++) {
1520 				targetPowerHt40.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt40.tPow2x[i], minCtlPower);
1521 			}
1522 			break;
1523 		default:
1524 			return AH_FALSE;
1525 			break;
1526 		}
1527 	} /* end ctl mode checking */
1528 
1529 	/* Set rates Array from collected data */
1530 	ratesArray[rate6mb] = ratesArray[rate9mb] = ratesArray[rate12mb] = ratesArray[rate18mb] = ratesArray[rate24mb] = targetPowerOfdm.tPow2x[0];
1531 	ratesArray[rate36mb] = targetPowerOfdm.tPow2x[1];
1532 	ratesArray[rate48mb] = targetPowerOfdm.tPow2x[2];
1533 	ratesArray[rate54mb] = targetPowerOfdm.tPow2x[3];
1534 	ratesArray[rateXr] = targetPowerOfdm.tPow2x[0];
1535 
1536 	for (i = 0; i < N(targetPowerHt20.tPow2x); i++) {
1537 		ratesArray[rateHt20_0 + i] = targetPowerHt20.tPow2x[i];
1538 	}
1539 
1540 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1541 		ratesArray[rate1l]  = targetPowerCck.tPow2x[0];
1542 		ratesArray[rate2s] = ratesArray[rate2l]  = targetPowerCck.tPow2x[1];
1543 		ratesArray[rate5_5s] = ratesArray[rate5_5l] = targetPowerCck.tPow2x[2];
1544 		ratesArray[rate11s] = ratesArray[rate11l] = targetPowerCck.tPow2x[3];
1545 	}
1546 	if (IEEE80211_IS_CHAN_HT40(chan)) {
1547 		for (i = 0; i < N(targetPowerHt40.tPow2x); i++) {
1548 			ratesArray[rateHt40_0 + i] = targetPowerHt40.tPow2x[i];
1549 		}
1550 		ratesArray[rateDupOfdm] = targetPowerHt40.tPow2x[0];
1551 		ratesArray[rateDupCck]  = targetPowerHt40.tPow2x[0];
1552 		ratesArray[rateExtOfdm] = targetPowerOfdmExt.tPow2x[0];
1553 		if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1554 			ratesArray[rateExtCck]  = targetPowerCckExt.tPow2x[0];
1555 		}
1556 	}
1557 	return AH_TRUE;
1558 #undef EXT_ADDITIVE
1559 #undef CTL_11A_EXT
1560 #undef CTL_11G_EXT
1561 #undef CTL_11B_EXT
1562 #undef SUB_NUM_CTL_MODES_AT_5G_40
1563 #undef SUB_NUM_CTL_MODES_AT_2G_40
1564 #undef N
1565 }
1566 
1567 /**************************************************************************
1568  * fbin2freq
1569  *
1570  * Get channel value from binary representation held in eeprom
1571  * RETURNS: the frequency in MHz
1572  */
1573 static uint16_t
1574 fbin2freq(uint8_t fbin, HAL_BOOL is2GHz)
1575 {
1576     /*
1577      * Reserved value 0xFF provides an empty definition both as
1578      * an fbin and as a frequency - do not convert
1579      */
1580     if (fbin == AR5416_BCHAN_UNUSED) {
1581         return fbin;
1582     }
1583 
1584     return (uint16_t)((is2GHz) ? (2300 + fbin) : (4800 + 5 * fbin));
1585 }
1586 
1587 /*
1588  * ar5416GetMaxEdgePower
1589  *
1590  * Find the maximum conformance test limit for the given channel and CTL info
1591  */
1592 static uint16_t
1593 ar5416GetMaxEdgePower(uint16_t freq, CAL_CTL_EDGES *pRdEdgesPower, HAL_BOOL is2GHz)
1594 {
1595     uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
1596     int      i;
1597 
1598     /* Get the edge power */
1599     for (i = 0; (i < AR5416_NUM_BAND_EDGES) && (pRdEdgesPower[i].bChannel != AR5416_BCHAN_UNUSED) ; i++) {
1600         /*
1601          * If there's an exact channel match or an inband flag set
1602          * on the lower channel use the given rdEdgePower
1603          */
1604         if (freq == fbin2freq(pRdEdgesPower[i].bChannel, is2GHz)) {
1605             twiceMaxEdgePower = MS(pRdEdgesPower[i].tPowerFlag, CAL_CTL_EDGES_POWER);
1606             break;
1607         } else if ((i > 0) && (freq < fbin2freq(pRdEdgesPower[i].bChannel, is2GHz))) {
1608             if (fbin2freq(pRdEdgesPower[i - 1].bChannel, is2GHz) < freq && (pRdEdgesPower[i - 1].tPowerFlag & CAL_CTL_EDGES_FLAG) != 0) {
1609                 twiceMaxEdgePower = MS(pRdEdgesPower[i - 1].tPowerFlag, CAL_CTL_EDGES_POWER);
1610             }
1611             /* Leave loop - no more affecting edges possible in this monotonic increasing list */
1612             break;
1613         }
1614     }
1615     HALASSERT(twiceMaxEdgePower > 0);
1616     return twiceMaxEdgePower;
1617 }
1618 
1619 /**************************************************************
1620  * ar5416GetTargetPowers
1621  *
1622  * Return the rates of target power for the given target power table
1623  * channel, and number of channels
1624  */
1625 static void
1626 ar5416GetTargetPowers(struct ath_hal *ah,  const struct ieee80211_channel *chan,
1627                       CAL_TARGET_POWER_HT *powInfo, uint16_t numChannels,
1628                       CAL_TARGET_POWER_HT *pNewPower, uint16_t numRates,
1629                       HAL_BOOL isHt40Target)
1630 {
1631     uint16_t clo, chi;
1632     int i;
1633     int matchIndex = -1, lowIndex = -1;
1634     uint16_t freq;
1635     CHAN_CENTERS centers;
1636 
1637     ar5416GetChannelCenters(ah,  chan, &centers);
1638     freq = isHt40Target ? centers.synth_center : centers.ctl_center;
1639 
1640     /* Copy the target powers into the temp channel list */
1641     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
1642         matchIndex = 0;
1643     } else {
1644         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
1645             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
1646                 matchIndex = i;
1647                 break;
1648             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
1649                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
1650             {
1651                 lowIndex = i - 1;
1652                 break;
1653             }
1654         }
1655         if ((matchIndex == -1) && (lowIndex == -1)) {
1656             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
1657             matchIndex = i - 1;
1658         }
1659     }
1660 
1661     if (matchIndex != -1) {
1662         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
1663     } else {
1664         HALASSERT(lowIndex != -1);
1665         /*
1666          * Get the lower and upper channels, target powers,
1667          * and interpolate between them.
1668          */
1669         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
1670         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
1671 
1672         for (i = 0; i < numRates; i++) {
1673             pNewPower->tPow2x[i] = (uint8_t)interpolate(freq, clo, chi,
1674                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
1675         }
1676     }
1677 }
1678 /**************************************************************
1679  * ar5416GetTargetPowersLeg
1680  *
1681  * Return the four rates of target power for the given target power table
1682  * channel, and number of channels
1683  */
1684 static void
1685 ar5416GetTargetPowersLeg(struct ath_hal *ah,
1686                          const struct ieee80211_channel *chan,
1687                          CAL_TARGET_POWER_LEG *powInfo, uint16_t numChannels,
1688                          CAL_TARGET_POWER_LEG *pNewPower, uint16_t numRates,
1689 			 HAL_BOOL isExtTarget)
1690 {
1691     uint16_t clo, chi;
1692     int i;
1693     int matchIndex = -1, lowIndex = -1;
1694     uint16_t freq;
1695     CHAN_CENTERS centers;
1696 
1697     ar5416GetChannelCenters(ah,  chan, &centers);
1698     freq = (isExtTarget) ? centers.ext_center :centers.ctl_center;
1699 
1700     /* Copy the target powers into the temp channel list */
1701     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
1702         matchIndex = 0;
1703     } else {
1704         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
1705             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
1706                 matchIndex = i;
1707                 break;
1708             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
1709                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
1710             {
1711                 lowIndex = i - 1;
1712                 break;
1713             }
1714         }
1715         if ((matchIndex == -1) && (lowIndex == -1)) {
1716             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
1717             matchIndex = i - 1;
1718         }
1719     }
1720 
1721     if (matchIndex != -1) {
1722         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
1723     } else {
1724         HALASSERT(lowIndex != -1);
1725         /*
1726          * Get the lower and upper channels, target powers,
1727          * and interpolate between them.
1728          */
1729         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
1730         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
1731 
1732         for (i = 0; i < numRates; i++) {
1733             pNewPower->tPow2x[i] = (uint8_t)interpolate(freq, clo, chi,
1734                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
1735         }
1736     }
1737 }
1738 
1739 /**************************************************************
1740  * ar5416SetPowerCalTable
1741  *
1742  * Pull the PDADC piers from cal data and interpolate them across the given
1743  * points as well as from the nearest pier(s) to get a power detector
1744  * linear voltage to power level table.
1745  */
1746 static HAL_BOOL
1747 ar5416SetPowerCalTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
1748 	const struct ieee80211_channel *chan, int16_t *pTxPowerIndexOffset)
1749 {
1750     CAL_DATA_PER_FREQ *pRawDataset;
1751     uint8_t  *pCalBChans = AH_NULL;
1752     uint16_t pdGainOverlap_t2;
1753     static uint8_t  pdadcValues[AR5416_NUM_PDADC_VALUES];
1754     uint16_t gainBoundaries[AR5416_PD_GAINS_IN_MASK];
1755     uint16_t numPiers, i, j;
1756     int16_t  tMinCalPower;
1757     uint16_t numXpdGain, xpdMask;
1758     uint16_t xpdGainValues[AR5416_NUM_PD_GAINS];
1759     uint32_t reg32, regOffset, regChainOffset;
1760 
1761     OS_MEMZERO(xpdGainValues, sizeof(xpdGainValues));
1762 
1763     xpdMask = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].xpdGain;
1764 
1765     if (IS_EEP_MINOR_V2(ah)) {
1766         pdGainOverlap_t2 = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pdGainOverlap;
1767     } else {
1768     	pdGainOverlap_t2 = (uint16_t)(MS(OS_REG_READ(ah, AR_PHY_TPCRG5), AR_PHY_TPCRG5_PD_GAIN_OVERLAP));
1769     }
1770 
1771     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1772         pCalBChans = pEepData->calFreqPier2G;
1773         numPiers = AR5416_NUM_2G_CAL_PIERS;
1774     } else {
1775         pCalBChans = pEepData->calFreqPier5G;
1776         numPiers = AR5416_NUM_5G_CAL_PIERS;
1777     }
1778 
1779     numXpdGain = 0;
1780     /* Calculate the value of xpdgains from the xpdGain Mask */
1781     for (i = 1; i <= AR5416_PD_GAINS_IN_MASK; i++) {
1782         if ((xpdMask >> (AR5416_PD_GAINS_IN_MASK - i)) & 1) {
1783             if (numXpdGain >= AR5416_NUM_PD_GAINS) {
1784                 HALASSERT(0);
1785                 break;
1786             }
1787             xpdGainValues[numXpdGain] = (uint16_t)(AR5416_PD_GAINS_IN_MASK - i);
1788             numXpdGain++;
1789         }
1790     }
1791 
1792     /* Write the detector gain biases and their number */
1793     OS_REG_WRITE(ah, AR_PHY_TPCRG1, (OS_REG_READ(ah, AR_PHY_TPCRG1) &
1794     	~(AR_PHY_TPCRG1_NUM_PD_GAIN | AR_PHY_TPCRG1_PD_GAIN_1 | AR_PHY_TPCRG1_PD_GAIN_2 | AR_PHY_TPCRG1_PD_GAIN_3)) |
1795 	SM(numXpdGain - 1, AR_PHY_TPCRG1_NUM_PD_GAIN) | SM(xpdGainValues[0], AR_PHY_TPCRG1_PD_GAIN_1 ) |
1796 	SM(xpdGainValues[1], AR_PHY_TPCRG1_PD_GAIN_2) | SM(xpdGainValues[2],  AR_PHY_TPCRG1_PD_GAIN_3));
1797 
1798     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
1799 
1800             if (AR_SREV_OWL_20_OR_LATER(ah) &&
1801             ( AH5416(ah)->ah_rx_chainmask == 0x5 || AH5416(ah)->ah_tx_chainmask == 0x5) && (i != 0)) {
1802             /* Regs are swapped from chain 2 to 1 for 5416 2_0 with
1803              * only chains 0 and 2 populated
1804              */
1805             regChainOffset = (i == 1) ? 0x2000 : 0x1000;
1806         } else {
1807             regChainOffset = i * 0x1000;
1808         }
1809 
1810         if (pEepData->baseEepHeader.txMask & (1 << i)) {
1811             if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1812                 pRawDataset = pEepData->calPierData2G[i];
1813             } else {
1814                 pRawDataset = pEepData->calPierData5G[i];
1815             }
1816 
1817             ar5416GetGainBoundariesAndPdadcs(ah,  chan, pRawDataset,
1818                                              pCalBChans, numPiers,
1819                                              pdGainOverlap_t2,
1820                                              &tMinCalPower, gainBoundaries,
1821                                              pdadcValues, numXpdGain);
1822 
1823             if ((i == 0) || AR_SREV_OWL_20_OR_LATER(ah)) {
1824                 /*
1825                  * Note the pdadc table may not start at 0 dBm power, could be
1826                  * negative or greater than 0.  Need to offset the power
1827                  * values by the amount of minPower for griffin
1828                  */
1829 
1830                 OS_REG_WRITE(ah, AR_PHY_TPCRG5 + regChainOffset,
1831                      SM(pdGainOverlap_t2, AR_PHY_TPCRG5_PD_GAIN_OVERLAP) |
1832                      SM(gainBoundaries[0], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_1)  |
1833                      SM(gainBoundaries[1], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_2)  |
1834                      SM(gainBoundaries[2], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_3)  |
1835                      SM(gainBoundaries[3], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_4));
1836             }
1837 
1838             /* Write the power values into the baseband power table */
1839             regOffset = AR_PHY_BASE + (672 << 2) + regChainOffset;
1840 
1841             for (j = 0; j < 32; j++) {
1842                 reg32 = ((pdadcValues[4*j + 0] & 0xFF) << 0)  |
1843                     ((pdadcValues[4*j + 1] & 0xFF) << 8)  |
1844                     ((pdadcValues[4*j + 2] & 0xFF) << 16) |
1845                     ((pdadcValues[4*j + 3] & 0xFF) << 24) ;
1846                 OS_REG_WRITE(ah, regOffset, reg32);
1847 
1848 #ifdef PDADC_DUMP
1849 		ath_hal_printf(ah, "PDADC: Chain %d | PDADC %3d Value %3d | PDADC %3d Value %3d | PDADC %3d Value %3d | PDADC %3d Value %3d |\n",
1850 			       i,
1851 			       4*j, pdadcValues[4*j],
1852 			       4*j+1, pdadcValues[4*j + 1],
1853 			       4*j+2, pdadcValues[4*j + 2],
1854 			       4*j+3, pdadcValues[4*j + 3]);
1855 #endif
1856                 regOffset += 4;
1857             }
1858         }
1859     }
1860     *pTxPowerIndexOffset = 0;
1861 
1862     return AH_TRUE;
1863 }
1864 
1865 /**************************************************************
1866  * ar5416GetGainBoundariesAndPdadcs
1867  *
1868  * Uses the data points read from EEPROM to reconstruct the pdadc power table
1869  * Called by ar5416SetPowerCalTable only.
1870  */
1871 static void
1872 ar5416GetGainBoundariesAndPdadcs(struct ath_hal *ah,
1873                                  const struct ieee80211_channel *chan,
1874 				 CAL_DATA_PER_FREQ *pRawDataSet,
1875                                  uint8_t * bChans,  uint16_t availPiers,
1876                                  uint16_t tPdGainOverlap, int16_t *pMinCalPower, uint16_t * pPdGainBoundaries,
1877                                  uint8_t * pPDADCValues, uint16_t numXpdGains)
1878 {
1879 
1880     int       i, j, k;
1881     int16_t   ss;         /* potentially -ve index for taking care of pdGainOverlap */
1882     uint16_t  idxL, idxR, numPiers; /* Pier indexes */
1883 
1884     /* filled out Vpd table for all pdGains (chanL) */
1885     static uint8_t   vpdTableL[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
1886 
1887     /* filled out Vpd table for all pdGains (chanR) */
1888     static uint8_t   vpdTableR[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
1889 
1890     /* filled out Vpd table for all pdGains (interpolated) */
1891     static uint8_t   vpdTableI[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
1892 
1893     uint8_t   *pVpdL, *pVpdR, *pPwrL, *pPwrR;
1894     uint8_t   minPwrT4[AR5416_NUM_PD_GAINS];
1895     uint8_t   maxPwrT4[AR5416_NUM_PD_GAINS];
1896     int16_t   vpdStep;
1897     int16_t   tmpVal;
1898     uint16_t  sizeCurrVpdTable, maxIndex, tgtIndex;
1899     HAL_BOOL    match;
1900     int16_t  minDelta = 0;
1901     CHAN_CENTERS centers;
1902 
1903     ar5416GetChannelCenters(ah, chan, &centers);
1904 
1905     /* Trim numPiers for the number of populated channel Piers */
1906     for (numPiers = 0; numPiers < availPiers; numPiers++) {
1907         if (bChans[numPiers] == AR5416_BCHAN_UNUSED) {
1908             break;
1909         }
1910     }
1911 
1912     /* Find pier indexes around the current channel */
1913     match = getLowerUpperIndex((uint8_t)FREQ2FBIN(centers.synth_center, IEEE80211_IS_CHAN_2GHZ(chan)),
1914 			bChans, numPiers, &idxL, &idxR);
1915 
1916     if (match) {
1917         /* Directly fill both vpd tables from the matching index */
1918         for (i = 0; i < numXpdGains; i++) {
1919             minPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][0];
1920             maxPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][4];
1921             ar5416FillVpdTable(minPwrT4[i], maxPwrT4[i], pRawDataSet[idxL].pwrPdg[i],
1922                                pRawDataSet[idxL].vpdPdg[i], AR5416_PD_GAIN_ICEPTS, vpdTableI[i]);
1923         }
1924     } else {
1925         for (i = 0; i < numXpdGains; i++) {
1926             pVpdL = pRawDataSet[idxL].vpdPdg[i];
1927             pPwrL = pRawDataSet[idxL].pwrPdg[i];
1928             pVpdR = pRawDataSet[idxR].vpdPdg[i];
1929             pPwrR = pRawDataSet[idxR].pwrPdg[i];
1930 
1931             /* Start Vpd interpolation from the max of the minimum powers */
1932             minPwrT4[i] = AH_MAX(pPwrL[0], pPwrR[0]);
1933 
1934             /* End Vpd interpolation from the min of the max powers */
1935             maxPwrT4[i] = AH_MIN(pPwrL[AR5416_PD_GAIN_ICEPTS - 1], pPwrR[AR5416_PD_GAIN_ICEPTS - 1]);
1936             HALASSERT(maxPwrT4[i] > minPwrT4[i]);
1937 
1938             /* Fill pier Vpds */
1939             ar5416FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrL, pVpdL, AR5416_PD_GAIN_ICEPTS, vpdTableL[i]);
1940             ar5416FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrR, pVpdR, AR5416_PD_GAIN_ICEPTS, vpdTableR[i]);
1941 
1942             /* Interpolate the final vpd */
1943             for (j = 0; j <= (maxPwrT4[i] - minPwrT4[i]) / 2; j++) {
1944                 vpdTableI[i][j] = (uint8_t)(interpolate((uint16_t)FREQ2FBIN(centers.synth_center, IEEE80211_IS_CHAN_2GHZ(chan)),
1945                     bChans[idxL], bChans[idxR], vpdTableL[i][j], vpdTableR[i][j]));
1946             }
1947         }
1948     }
1949     *pMinCalPower = (int16_t)(minPwrT4[0] / 2);
1950 
1951     k = 0; /* index for the final table */
1952     for (i = 0; i < numXpdGains; i++) {
1953         if (i == (numXpdGains - 1)) {
1954             pPdGainBoundaries[i] = (uint16_t)(maxPwrT4[i] / 2);
1955         } else {
1956             pPdGainBoundaries[i] = (uint16_t)((maxPwrT4[i] + minPwrT4[i+1]) / 4);
1957         }
1958 
1959         pPdGainBoundaries[i] = (uint16_t)AH_MIN(AR5416_MAX_RATE_POWER, pPdGainBoundaries[i]);
1960 
1961 	/* NB: only applies to owl 1.0 */
1962         if ((i == 0) && !AR_SREV_OWL_20_OR_LATER(ah) ) {
1963 	    /*
1964              * fix the gain delta, but get a delta that can be applied to min to
1965              * keep the upper power values accurate, don't think max needs to
1966              * be adjusted because should not be at that area of the table?
1967 	     */
1968             minDelta = pPdGainBoundaries[0] - 23;
1969             pPdGainBoundaries[0] = 23;
1970         }
1971         else {
1972             minDelta = 0;
1973         }
1974 
1975         /* Find starting index for this pdGain */
1976         if (i == 0) {
1977             ss = 0; /* for the first pdGain, start from index 0 */
1978         } else {
1979 	    /* need overlap entries extrapolated below. */
1980             ss = (int16_t)((pPdGainBoundaries[i-1] - (minPwrT4[i] / 2)) - tPdGainOverlap + 1 + minDelta);
1981         }
1982         vpdStep = (int16_t)(vpdTableI[i][1] - vpdTableI[i][0]);
1983         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
1984         /*
1985          *-ve ss indicates need to extrapolate data below for this pdGain
1986          */
1987         while ((ss < 0) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
1988             tmpVal = (int16_t)(vpdTableI[i][0] + ss * vpdStep);
1989             pPDADCValues[k++] = (uint8_t)((tmpVal < 0) ? 0 : tmpVal);
1990             ss++;
1991         }
1992 
1993         sizeCurrVpdTable = (uint8_t)((maxPwrT4[i] - minPwrT4[i]) / 2 +1);
1994         tgtIndex = (uint8_t)(pPdGainBoundaries[i] + tPdGainOverlap - (minPwrT4[i] / 2));
1995         maxIndex = (tgtIndex < sizeCurrVpdTable) ? tgtIndex : sizeCurrVpdTable;
1996 
1997         while ((ss < maxIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
1998             pPDADCValues[k++] = vpdTableI[i][ss++];
1999         }
2000 
2001         vpdStep = (int16_t)(vpdTableI[i][sizeCurrVpdTable - 1] - vpdTableI[i][sizeCurrVpdTable - 2]);
2002         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
2003         /*
2004          * for last gain, pdGainBoundary == Pmax_t2, so will
2005          * have to extrapolate
2006          */
2007         if (tgtIndex > maxIndex) {  /* need to extrapolate above */
2008             while ((ss <= tgtIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2009                 tmpVal = (int16_t)((vpdTableI[i][sizeCurrVpdTable - 1] +
2010                           (ss - maxIndex +1) * vpdStep));
2011                 pPDADCValues[k++] = (uint8_t)((tmpVal > 255) ? 255 : tmpVal);
2012                 ss++;
2013             }
2014         }               /* extrapolated above */
2015     }                   /* for all pdGainUsed */
2016 
2017     /* Fill out pdGainBoundaries - only up to 2 allowed here, but hardware allows up to 4 */
2018     while (i < AR5416_PD_GAINS_IN_MASK) {
2019         pPdGainBoundaries[i] = pPdGainBoundaries[i-1];
2020         i++;
2021     }
2022 
2023     while (k < AR5416_NUM_PDADC_VALUES) {
2024         pPDADCValues[k] = pPDADCValues[k-1];
2025         k++;
2026     }
2027     return;
2028 }
2029 
2030 /**************************************************************
2031  * getLowerUppderIndex
2032  *
2033  * Return indices surrounding the value in sorted integer lists.
2034  * Requirement: the input list must be monotonically increasing
2035  *     and populated up to the list size
2036  * Returns: match is set if an index in the array matches exactly
2037  *     or a the target is before or after the range of the array.
2038  */
2039 HAL_BOOL
2040 getLowerUpperIndex(uint8_t target, uint8_t *pList, uint16_t listSize,
2041                    uint16_t *indexL, uint16_t *indexR)
2042 {
2043     uint16_t i;
2044 
2045     /*
2046      * Check first and last elements for beyond ordered array cases.
2047      */
2048     if (target <= pList[0]) {
2049         *indexL = *indexR = 0;
2050         return AH_TRUE;
2051     }
2052     if (target >= pList[listSize-1]) {
2053         *indexL = *indexR = (uint16_t)(listSize - 1);
2054         return AH_TRUE;
2055     }
2056 
2057     /* look for value being near or between 2 values in list */
2058     for (i = 0; i < listSize - 1; i++) {
2059         /*
2060          * If value is close to the current value of the list
2061          * then target is not between values, it is one of the values
2062          */
2063         if (pList[i] == target) {
2064             *indexL = *indexR = i;
2065             return AH_TRUE;
2066         }
2067         /*
2068          * Look for value being between current value and next value
2069          * if so return these 2 values
2070          */
2071         if (target < pList[i + 1]) {
2072             *indexL = i;
2073             *indexR = (uint16_t)(i + 1);
2074             return AH_FALSE;
2075         }
2076     }
2077     HALASSERT(0);
2078     *indexL = *indexR = 0;
2079     return AH_FALSE;
2080 }
2081 
2082 /**************************************************************
2083  * ar5416FillVpdTable
2084  *
2085  * Fill the Vpdlist for indices Pmax-Pmin
2086  * Note: pwrMin, pwrMax and Vpdlist are all in dBm * 4
2087  */
2088 static HAL_BOOL
2089 ar5416FillVpdTable(uint8_t pwrMin, uint8_t pwrMax, uint8_t *pPwrList,
2090                    uint8_t *pVpdList, uint16_t numIntercepts, uint8_t *pRetVpdList)
2091 {
2092     uint16_t  i, k;
2093     uint8_t   currPwr = pwrMin;
2094     uint16_t  idxL, idxR;
2095 
2096     HALASSERT(pwrMax > pwrMin);
2097     for (i = 0; i <= (pwrMax - pwrMin) / 2; i++) {
2098         getLowerUpperIndex(currPwr, pPwrList, numIntercepts,
2099                            &(idxL), &(idxR));
2100         if (idxR < 1)
2101             idxR = 1;           /* extrapolate below */
2102         if (idxL == numIntercepts - 1)
2103             idxL = (uint16_t)(numIntercepts - 2);   /* extrapolate above */
2104         if (pPwrList[idxL] == pPwrList[idxR])
2105             k = pVpdList[idxL];
2106         else
2107             k = (uint16_t)( ((currPwr - pPwrList[idxL]) * pVpdList[idxR] + (pPwrList[idxR] - currPwr) * pVpdList[idxL]) /
2108                   (pPwrList[idxR] - pPwrList[idxL]) );
2109         HALASSERT(k < 256);
2110         pRetVpdList[i] = (uint8_t)k;
2111         currPwr += 2;               /* half dB steps */
2112     }
2113 
2114     return AH_TRUE;
2115 }
2116 
2117 /**************************************************************************
2118  * interpolate
2119  *
2120  * Returns signed interpolated or the scaled up interpolated value
2121  */
2122 static int16_t
2123 interpolate(uint16_t target, uint16_t srcLeft, uint16_t srcRight,
2124             int16_t targetLeft, int16_t targetRight)
2125 {
2126     int16_t rv;
2127 
2128     if (srcRight == srcLeft) {
2129         rv = targetLeft;
2130     } else {
2131         rv = (int16_t)( ((target - srcLeft) * targetRight +
2132               (srcRight - target) * targetLeft) / (srcRight - srcLeft) );
2133     }
2134     return rv;
2135 }
2136 
2137 static void
2138 ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan)
2139 {
2140 	uint32_t phymode;
2141 	HAL_HT_MACMODE macmode;		/* MAC - 20/40 mode */
2142 
2143 	if (!IEEE80211_IS_CHAN_HT(chan))
2144 		return;
2145 
2146 	/* Enable 11n HT, 20 MHz */
2147 	phymode = AR_PHY_FC_HT_EN | AR_PHY_FC_SHORT_GI_40
2148 		| AR_PHY_FC_SINGLE_HT_LTF1 | AR_PHY_FC_WALSH;
2149 
2150 	/* Configure baseband for dynamic 20/40 operation */
2151 	if (IEEE80211_IS_CHAN_HT40(chan)) {
2152 		phymode |= AR_PHY_FC_DYN2040_EN | AR_PHY_FC_SHORT_GI_40;
2153 
2154 		/* Configure control (primary) channel at +-10MHz */
2155 		if (IEEE80211_IS_CHAN_HT40U(chan))
2156 			phymode |= AR_PHY_FC_DYN2040_PRI_CH;
2157 #if 0
2158 		/* Configure 20/25 spacing */
2159 		if (ht->ht_extprotspacing == HAL_HT_EXTPROTSPACING_25)
2160 			phymode |= AR_PHY_FC_DYN2040_EXT_CH;
2161 #endif
2162 		macmode = HAL_HT_MACMODE_2040;
2163 	} else
2164 		macmode = HAL_HT_MACMODE_20;
2165 	OS_REG_WRITE(ah, AR_PHY_TURBO, phymode);
2166 
2167 	/* Configure MAC for 20/40 operation */
2168 	ar5416Set11nMac2040(ah, macmode);
2169 
2170 	/* global transmit timeout (25 TUs default)*/
2171 	/* XXX - put this elsewhere??? */
2172 	OS_REG_WRITE(ah, AR_GTXTO, 25 << AR_GTXTO_TIMEOUT_LIMIT_S) ;
2173 
2174 	/* carrier sense timeout */
2175 	OS_REG_SET_BIT(ah, AR_GTTM, AR_GTTM_CST_USEC);
2176 	OS_REG_WRITE(ah, AR_CST, 1 << AR_CST_TIMEOUT_LIMIT_S);
2177 }
2178 
2179 void
2180 ar5416GetChannelCenters(struct ath_hal *ah,
2181 	const struct ieee80211_channel *chan, CHAN_CENTERS *centers)
2182 {
2183 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
2184 
2185 	centers->ctl_center = freq;
2186 	centers->synth_center = freq;
2187 	/*
2188 	 * In 20/40 phy mode, the center frequency is
2189 	 * "between" the control and extension channels.
2190 	 */
2191 	if (IEEE80211_IS_CHAN_HT40U(chan)) {
2192 		centers->synth_center += HT40_CHANNEL_CENTER_SHIFT;
2193 		centers->ext_center =
2194 		    centers->synth_center + HT40_CHANNEL_CENTER_SHIFT;
2195 	} else if (IEEE80211_IS_CHAN_HT40D(chan)) {
2196 		centers->synth_center -= HT40_CHANNEL_CENTER_SHIFT;
2197 		centers->ext_center =
2198 		    centers->synth_center - HT40_CHANNEL_CENTER_SHIFT;
2199 	} else {
2200 		centers->ext_center = freq;
2201 	}
2202 }
2203