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