xref: /freebsd/sys/dev/ath/ath_hal/ar5416/ar5416_reset.c (revision b7d683e608ac894e75b2de7eac5eaa083650de54)
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 static void ar5416UpdateChainMasks(struct ath_hal *ah, HAL_BOOL is_ht);
48 static void ar5416OverrideIni(struct ath_hal *ah, const struct ieee80211_channel *);
49 
50 #if 0
51 static HAL_BOOL	ar5416ChannelChange(struct ath_hal *, const struct ieee80211_channel *);
52 #endif
53 static void ar5416SetDeltaSlope(struct ath_hal *, const struct ieee80211_channel *);
54 
55 static HAL_BOOL ar5416SetResetPowerOn(struct ath_hal *ah);
56 static HAL_BOOL ar5416SetReset(struct ath_hal *ah, int type);
57 static HAL_BOOL ar5416SetPowerPerRateTable(struct ath_hal *ah,
58 	struct ar5416eeprom *pEepData,
59 	const struct ieee80211_channel *chan, int16_t *ratesArray,
60 	uint16_t cfgCtl, uint16_t AntennaReduction,
61 	uint16_t twiceMaxRegulatoryPower,
62 	uint16_t powerLimit);
63 static void ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan);
64 static void ar5416MarkPhyInactive(struct ath_hal *ah);
65 
66 /*
67  * Places the device in and out of reset and then places sane
68  * values in the registers based on EEPROM config, initialization
69  * vectors (as determined by the mode), and station configuration
70  *
71  * bChannelChange is used to preserve DMA/PCU registers across
72  * a HW Reset during channel change.
73  */
74 HAL_BOOL
75 ar5416Reset(struct ath_hal *ah, HAL_OPMODE opmode,
76 	struct ieee80211_channel *chan,
77 	HAL_BOOL bChannelChange, HAL_STATUS *status)
78 {
79 #define	N(a)	(sizeof (a) / sizeof (a[0]))
80 #define	FAIL(_code)	do { ecode = _code; goto bad; } while (0)
81 	struct ath_hal_5212 *ahp = AH5212(ah);
82 	HAL_CHANNEL_INTERNAL *ichan;
83 	uint32_t saveDefAntenna, saveLedState;
84 	uint32_t macStaId1;
85 	uint16_t rfXpdGain[2];
86 	HAL_STATUS ecode;
87 	uint32_t powerVal, rssiThrReg;
88 	uint32_t ackTpcPow, ctsTpcPow, chirpTpcPow;
89 	int i;
90 	uint64_t tsf = 0;
91 
92 	OS_MARK(ah, AH_MARK_RESET, bChannelChange);
93 
94 	/* Bring out of sleep mode */
95 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE)) {
96 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip did not wakeup\n",
97 		    __func__);
98 		FAIL(HAL_EIO);
99 	}
100 
101 	/*
102 	 * Map public channel to private.
103 	 */
104 	ichan = ath_hal_checkchannel(ah, chan);
105 	if (ichan == AH_NULL)
106 		FAIL(HAL_EINVAL);
107 	switch (opmode) {
108 	case HAL_M_STA:
109 	case HAL_M_IBSS:
110 	case HAL_M_HOSTAP:
111 	case HAL_M_MONITOR:
112 		break;
113 	default:
114 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid operating mode %u\n",
115 		    __func__, opmode);
116 		FAIL(HAL_EINVAL);
117 		break;
118 	}
119 	HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
120 
121 	/* Blank the channel survey statistics */
122 	OS_MEMZERO(&ahp->ah_chansurvey, sizeof(ahp->ah_chansurvey));
123 
124 	/* XXX Turn on fast channel change for 5416 */
125 	/*
126 	 * Preserve the bmiss rssi threshold and count threshold
127 	 * across resets
128 	 */
129 	rssiThrReg = OS_REG_READ(ah, AR_RSSI_THR);
130 	/* If reg is zero, first time thru set to default val */
131 	if (rssiThrReg == 0)
132 		rssiThrReg = INIT_RSSI_THR;
133 
134 	/*
135 	 * Preserve the antenna on a channel change
136 	 */
137 	saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
138 	if (saveDefAntenna == 0)		/* XXX magic constants */
139 		saveDefAntenna = 1;
140 
141 	/* Save hardware flag before chip reset clears the register */
142 	macStaId1 = OS_REG_READ(ah, AR_STA_ID1) &
143 		(AR_STA_ID1_BASE_RATE_11B | AR_STA_ID1_USE_DEFANT);
144 
145 	/* Save led state from pci config register */
146 	saveLedState = OS_REG_READ(ah, AR_MAC_LED) &
147 		(AR_MAC_LED_ASSOC | AR_MAC_LED_MODE |
148 		 AR_MAC_LED_BLINK_THRESH_SEL | AR_MAC_LED_BLINK_SLOW);
149 
150 	/* For chips on which the RTC reset is done, save TSF before it gets cleared */
151 	if (AR_SREV_HOWL(ah) ||
152 	    (AR_SREV_MERLIN(ah) &&
153 	     ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) ||
154 	    (ah->ah_config.ah_force_full_reset))
155 		tsf = ar5416GetTsf64(ah);
156 
157 	/* Mark PHY as inactive; marked active in ar5416InitBB() */
158 	ar5416MarkPhyInactive(ah);
159 
160 	if (!ar5416ChipReset(ah, chan)) {
161 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
162 		FAIL(HAL_EIO);
163 	}
164 
165 	/* Restore TSF */
166 	if (tsf)
167 		ar5416SetTsf64(ah, tsf);
168 
169 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
170 	if (AR_SREV_MERLIN_10_OR_LATER(ah))
171 		OS_REG_SET_BIT(ah, AR_GPIO_INPUT_EN_VAL, AR_GPIO_JTAG_DISABLE);
172 
173 	AH5416(ah)->ah_writeIni(ah, chan);
174 
175 	if(AR_SREV_KIWI_13_OR_LATER(ah) ) {
176 		/* Enable ASYNC FIFO */
177 		OS_REG_SET_BIT(ah, AR_MAC_PCU_ASYNC_FIFO_REG3,
178 		    AR_MAC_PCU_ASYNC_FIFO_REG3_DATAPATH_SEL);
179 		OS_REG_SET_BIT(ah, AR_PHY_MODE, AR_PHY_MODE_ASYNCFIFO);
180 		OS_REG_CLR_BIT(ah, AR_MAC_PCU_ASYNC_FIFO_REG3,
181 		    AR_MAC_PCU_ASYNC_FIFO_REG3_SOFT_RESET);
182 		OS_REG_SET_BIT(ah, AR_MAC_PCU_ASYNC_FIFO_REG3,
183 		    AR_MAC_PCU_ASYNC_FIFO_REG3_SOFT_RESET);
184 	}
185 
186 	/* Override ini values (that can be overriden in this fashion) */
187 	ar5416OverrideIni(ah, chan);
188 
189 	/* Setup 11n MAC/Phy mode registers */
190 	ar5416Set11nRegs(ah, chan);
191 
192 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
193 
194 	/*
195 	 * Some AR91xx SoC devices frequently fail to accept TSF writes
196 	 * right after the chip reset. When that happens, write a new
197 	 * value after the initvals have been applied, with an offset
198 	 * based on measured time difference
199 	 */
200 	if (AR_SREV_HOWL(ah) && (ar5416GetTsf64(ah) < tsf)) {
201 		tsf += 1500;
202 		ar5416SetTsf64(ah, tsf);
203 	}
204 
205 	HALDEBUG(ah, HAL_DEBUG_RESET, ">>>2 %s: AR_PHY_DAG_CTRLCCK=0x%x\n",
206 		__func__, OS_REG_READ(ah,AR_PHY_DAG_CTRLCCK));
207 	HALDEBUG(ah, HAL_DEBUG_RESET, ">>>2 %s: AR_PHY_ADC_CTL=0x%x\n",
208 		__func__, OS_REG_READ(ah,AR_PHY_ADC_CTL));
209 
210 	/*
211 	 * Setup ah_tx_chainmask / ah_rx_chainmask before we fiddle
212 	 * with enabling the TX/RX radio chains.
213 	 */
214 	ar5416UpdateChainMasks(ah, IEEE80211_IS_CHAN_HT(chan));
215 	/*
216 	 * This routine swaps the analog chains - it should be done
217 	 * before any radio register twiddling is done.
218 	 */
219 	ar5416InitChainMasks(ah);
220 
221 	/* Setup the open-loop power calibration if required */
222 	if (ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) {
223 		AH5416(ah)->ah_olcInit(ah);
224 		AH5416(ah)->ah_olcTempCompensation(ah);
225 	}
226 
227 	/* Setup the transmit power values. */
228 	if (!ah->ah_setTxPower(ah, chan, rfXpdGain)) {
229 		HALDEBUG(ah, HAL_DEBUG_ANY,
230 		    "%s: error init'ing transmit power\n", __func__);
231 		FAIL(HAL_EIO);
232 	}
233 
234 	/* Write the analog registers */
235 	if (!ahp->ah_rfHal->setRfRegs(ah, chan,
236 	    IEEE80211_IS_CHAN_2GHZ(chan) ? 2: 1, rfXpdGain)) {
237 		HALDEBUG(ah, HAL_DEBUG_ANY,
238 		    "%s: ar5212SetRfRegs failed\n", __func__);
239 		FAIL(HAL_EIO);
240 	}
241 
242 	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
243 	if (IEEE80211_IS_CHAN_OFDM(chan)|| IEEE80211_IS_CHAN_HT(chan))
244 		ar5416SetDeltaSlope(ah, chan);
245 
246 	AH5416(ah)->ah_spurMitigate(ah, chan);
247 
248 	/* Setup board specific options for EEPROM version 3 */
249 	if (!ah->ah_setBoardValues(ah, chan)) {
250 		HALDEBUG(ah, HAL_DEBUG_ANY,
251 		    "%s: error setting board options\n", __func__);
252 		FAIL(HAL_EIO);
253 	}
254 
255 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
256 
257 	OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
258 	OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
259 		| macStaId1
260 		| AR_STA_ID1_RTS_USE_DEF
261 		| ahp->ah_staId1Defaults
262 	);
263 	ar5212SetOperatingMode(ah, opmode);
264 
265 	/* Set Venice BSSID mask according to current state */
266 	OS_REG_WRITE(ah, AR_BSSMSKL, LE_READ_4(ahp->ah_bssidmask));
267 	OS_REG_WRITE(ah, AR_BSSMSKU, LE_READ_2(ahp->ah_bssidmask + 4));
268 
269 	/* Restore previous led state */
270 	if (AR_SREV_HOWL(ah))
271 		OS_REG_WRITE(ah, AR_MAC_LED,
272 		    AR_MAC_LED_ASSOC_ACTIVE | AR_CFG_SCLK_32KHZ);
273 	else
274 		OS_REG_WRITE(ah, AR_MAC_LED, OS_REG_READ(ah, AR_MAC_LED) |
275 		    saveLedState);
276 
277         /* Start TSF2 for generic timer 8-15 */
278 #ifdef	NOTYET
279 	if (AR_SREV_KIWI(ah))
280 		ar5416StartTsf2(ah);
281 #endif
282 
283 	/* Restore previous antenna */
284 	OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);
285 
286 	/* then our BSSID and associate id */
287 	OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
288 	OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4) |
289 	    (ahp->ah_assocId & 0x3fff) << AR_BSS_ID1_AID_S);
290 
291 	/* Restore bmiss rssi & count thresholds */
292 	OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);
293 
294 	OS_REG_WRITE(ah, AR_ISR, ~0);		/* cleared on write */
295 
296 	/* Restore bmiss rssi & count thresholds */
297 	OS_REG_WRITE(ah, AR_RSSI_THR, rssiThrReg);
298 
299 	if (!ar5212SetChannel(ah, chan))
300 		FAIL(HAL_EIO);
301 
302 	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);
303 
304 	/* Set 1:1 QCU to DCU mapping for all queues */
305 	for (i = 0; i < AR_NUM_DCU; i++)
306 		OS_REG_WRITE(ah, AR_DQCUMASK(i), 1 << i);
307 
308 	ahp->ah_intrTxqs = 0;
309 	for (i = 0; i < AH_PRIVATE(ah)->ah_caps.halTotalQueues; i++)
310 		ah->ah_resetTxQueue(ah, i);
311 
312 	ar5416InitIMR(ah, opmode);
313 	ar5212SetCoverageClass(ah, AH_PRIVATE(ah)->ah_coverageClass, 1);
314 	ar5416InitQoS(ah);
315 	/* This may override the AR_DIAG_SW register */
316 	ar5416InitUserSettings(ah);
317 
318 	if (AR_SREV_KIWI_13_OR_LATER(ah)) {
319 		/*
320 		 * Enable ASYNC FIFO
321 		 *
322 		 * If Async FIFO is enabled, the following counters change
323 		 * as MAC now runs at 117 Mhz instead of 88/44MHz when
324 		 * async FIFO is disabled.
325 		 *
326 		 * Overwrite the delay/timeouts initialized in ProcessIni()
327 		 * above.
328 		 */
329 		OS_REG_WRITE(ah, AR_D_GBL_IFS_SIFS,
330 		    AR_D_GBL_IFS_SIFS_ASYNC_FIFO_DUR);
331 		OS_REG_WRITE(ah, AR_D_GBL_IFS_SLOT,
332 		    AR_D_GBL_IFS_SLOT_ASYNC_FIFO_DUR);
333 		OS_REG_WRITE(ah, AR_D_GBL_IFS_EIFS,
334 		    AR_D_GBL_IFS_EIFS_ASYNC_FIFO_DUR);
335 
336 		OS_REG_WRITE(ah, AR_TIME_OUT,
337 		    AR_TIME_OUT_ACK_CTS_ASYNC_FIFO_DUR);
338 		OS_REG_WRITE(ah, AR_USEC, AR_USEC_ASYNC_FIFO_DUR);
339 
340 		OS_REG_SET_BIT(ah, AR_MAC_PCU_LOGIC_ANALYZER,
341 		    AR_MAC_PCU_LOGIC_ANALYZER_DISBUG20768);
342 		OS_REG_RMW_FIELD(ah, AR_AHB_MODE, AR_AHB_CUSTOM_BURST_EN,
343 		    AR_AHB_CUSTOM_BURST_ASYNC_FIFO_VAL);
344 	}
345 
346 	if (AR_SREV_KIWI_13_OR_LATER(ah)) {
347 		/* Enable AGGWEP to accelerate encryption engine */
348 		OS_REG_SET_BIT(ah, AR_PCU_MISC_MODE2,
349 		    AR_PCU_MISC_MODE2_ENABLE_AGGWEP);
350 	}
351 
352 
353 	/*
354 	 * disable seq number generation in hw
355 	 */
356 	 OS_REG_WRITE(ah, AR_STA_ID1,
357 	     OS_REG_READ(ah, AR_STA_ID1) | AR_STA_ID1_PRESERVE_SEQNUM);
358 
359 	ar5416InitDMA(ah);
360 
361 	/*
362 	 * program OBS bus to see MAC interrupts
363 	 */
364 	OS_REG_WRITE(ah, AR_OBS, 8);
365 
366 	/*
367 	 * Disable the "general" TX/RX mitigation timers.
368 	 */
369 	OS_REG_WRITE(ah, AR_MIRT, 0);
370 
371 #ifdef	AH_AR5416_INTERRUPT_MITIGATION
372 	/*
373 	 * This initialises the RX interrupt mitigation timers.
374 	 *
375 	 * The mitigation timers begin at idle and are triggered
376 	 * upon the RXOK of a single frame (or sub-frame, for A-MPDU.)
377 	 * Then, the RX mitigation interrupt will fire:
378 	 *
379 	 * + 250uS after the last RX'ed frame, or
380 	 * + 700uS after the first RX'ed frame
381 	 *
382 	 * Thus, the LAST field dictates the extra latency
383 	 * induced by the RX mitigation method and the FIRST
384 	 * field dictates how long to delay before firing an
385 	 * RX mitigation interrupt.
386 	 *
387 	 * Please note this only seems to be for RXOK frames;
388 	 * not CRC or PHY error frames.
389 	 *
390 	 */
391 	OS_REG_RMW_FIELD(ah, AR_RIMT, AR_RIMT_LAST, 250);
392 	OS_REG_RMW_FIELD(ah, AR_RIMT, AR_RIMT_FIRST, 700);
393 #endif
394 	ar5416InitBB(ah, chan);
395 
396 	/* Setup compression registers */
397 	ar5212SetCompRegs(ah);		/* XXX not needed? */
398 
399 	/*
400 	 * 5416 baseband will check the per rate power table
401 	 * and select the lower of the two
402 	 */
403 	ackTpcPow = 63;
404 	ctsTpcPow = 63;
405 	chirpTpcPow = 63;
406 	powerVal = SM(ackTpcPow, AR_TPC_ACK) |
407 		SM(ctsTpcPow, AR_TPC_CTS) |
408 		SM(chirpTpcPow, AR_TPC_CHIRP);
409 	OS_REG_WRITE(ah, AR_TPC, powerVal);
410 
411 	if (!ar5416InitCal(ah, chan))
412 		FAIL(HAL_ESELFTEST);
413 
414 	ar5416RestoreChainMask(ah);
415 
416 	AH_PRIVATE(ah)->ah_opmode = opmode;	/* record operating mode */
417 
418 	if (bChannelChange && !IEEE80211_IS_CHAN_DFS(chan))
419 		chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
420 
421 	if (AR_SREV_HOWL(ah)) {
422 		/*
423 		 * Enable the MBSSID block-ack fix for HOWL.
424 		 * This feature is only supported on Howl 1.4, but it is safe to
425 		 * set bit 22 of STA_ID1 on other Howl revisions (1.1, 1.2, 1.3),
426 		 * since bit 22 is unused in those Howl revisions.
427 		 */
428 		unsigned int reg;
429 		reg = (OS_REG_READ(ah, AR_STA_ID1) | (1<<22));
430 		OS_REG_WRITE(ah,AR_STA_ID1, reg);
431 		ath_hal_printf(ah, "MBSSID Set bit 22 of AR_STA_ID 0x%x\n", reg);
432 	}
433 
434 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);
435 
436 	OS_MARK(ah, AH_MARK_RESET_DONE, 0);
437 
438 	return AH_TRUE;
439 bad:
440 	OS_MARK(ah, AH_MARK_RESET_DONE, ecode);
441 	if (status != AH_NULL)
442 		*status = ecode;
443 	return AH_FALSE;
444 #undef FAIL
445 #undef N
446 }
447 
448 #if 0
449 /*
450  * This channel change evaluates whether the selected hardware can
451  * perform a synthesizer-only channel change (no reset).  If the
452  * TX is not stopped, or the RFBus cannot be granted in the given
453  * time, the function returns false as a reset is necessary
454  */
455 HAL_BOOL
456 ar5416ChannelChange(struct ath_hal *ah, const structu ieee80211_channel *chan)
457 {
458 	uint32_t       ulCount;
459 	uint32_t   data, synthDelay, qnum;
460 	uint16_t   rfXpdGain[4];
461 	struct ath_hal_5212 *ahp = AH5212(ah);
462 	HAL_CHANNEL_INTERNAL *ichan;
463 
464 	/*
465 	 * Map public channel to private.
466 	 */
467 	ichan = ath_hal_checkchannel(ah, chan);
468 
469 	/* TX must be stopped or RF Bus grant will not work */
470 	for (qnum = 0; qnum < AH_PRIVATE(ah)->ah_caps.halTotalQueues; qnum++) {
471 		if (ar5212NumTxPending(ah, qnum)) {
472 			HALDEBUG(ah, HAL_DEBUG_ANY,
473 			    "%s: frames pending on queue %d\n", __func__, qnum);
474 			return AH_FALSE;
475 		}
476 	}
477 
478 	/*
479 	 * Kill last Baseband Rx Frame - Request analog bus grant
480 	 */
481 	OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, AR_PHY_RFBUS_REQ_REQUEST);
482 	if (!ath_hal_wait(ah, AR_PHY_RFBUS_GNT, AR_PHY_RFBUS_GRANT_EN, AR_PHY_RFBUS_GRANT_EN)) {
483 		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: could not kill baseband rx\n",
484 		    __func__);
485 		return AH_FALSE;
486 	}
487 
488 	ar5416Set11nRegs(ah, chan);	/* NB: setup 5416-specific regs */
489 
490 	/* Change the synth */
491 	if (!ar5212SetChannel(ah, chan))
492 		return AH_FALSE;
493 
494 	/* Setup the transmit power values. */
495 	if (!ah->ah_setTxPower(ah, chan, rfXpdGain)) {
496 		HALDEBUG(ah, HAL_DEBUG_ANY,
497 		    "%s: error init'ing transmit power\n", __func__);
498 		return AH_FALSE;
499 	}
500 
501 	/*
502 	 * Wait for the frequency synth to settle (synth goes on
503 	 * via PHY_ACTIVE_EN).  Read the phy active delay register.
504 	 * Value is in 100ns increments.
505 	 */
506 	data = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
507 	if (IS_CHAN_CCK(ichan)) {
508 		synthDelay = (4 * data) / 22;
509 	} else {
510 		synthDelay = data / 10;
511 	}
512 
513 	OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
514 
515 	/* Release the RFBus Grant */
516 	OS_REG_WRITE(ah, AR_PHY_RFBUS_REQ, 0);
517 
518 	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
519 	if (IEEE80211_IS_CHAN_OFDM(ichan)|| IEEE80211_IS_CHAN_HT(chan)) {
520 		HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3);
521 		ar5212SetSpurMitigation(ah, chan);
522 		ar5416SetDeltaSlope(ah, chan);
523 	}
524 
525 	/* XXX spur mitigation for Melin */
526 
527 	if (!IEEE80211_IS_CHAN_DFS(chan))
528 		chan->ic_state &= ~IEEE80211_CHANSTATE_CWINT;
529 
530 	ichan->channel_time = 0;
531 	ichan->tsf_last = ar5416GetTsf64(ah);
532 	ar5212TxEnable(ah, AH_TRUE);
533 	return AH_TRUE;
534 }
535 #endif
536 
537 static void
538 ar5416InitDMA(struct ath_hal *ah)
539 {
540 	struct ath_hal_5212 *ahp = AH5212(ah);
541 
542 	/*
543 	 * set AHB_MODE not to do cacheline prefetches
544 	 */
545 	OS_REG_SET_BIT(ah, AR_AHB_MODE, AR_AHB_PREFETCH_RD_EN);
546 
547 	/*
548 	 * let mac dma reads be in 128 byte chunks
549 	 */
550 	OS_REG_WRITE(ah, AR_TXCFG,
551 		(OS_REG_READ(ah, AR_TXCFG) & ~AR_TXCFG_DMASZ_MASK) | AR_TXCFG_DMASZ_128B);
552 
553 	/*
554 	 * let mac dma writes be in 128 byte chunks
555 	 */
556 	OS_REG_WRITE(ah, AR_RXCFG,
557 		(OS_REG_READ(ah, AR_RXCFG) & ~AR_RXCFG_DMASZ_MASK) | AR_RXCFG_DMASZ_128B);
558 
559 	/* restore TX trigger level */
560 	OS_REG_WRITE(ah, AR_TXCFG,
561 		(OS_REG_READ(ah, AR_TXCFG) &~ AR_FTRIG) |
562 		    SM(ahp->ah_txTrigLev, AR_FTRIG));
563 
564 	/*
565 	 * Setup receive FIFO threshold to hold off TX activities
566 	 */
567 	OS_REG_WRITE(ah, AR_RXFIFO_CFG, 0x200);
568 
569 	/*
570 	 * reduce the number of usable entries in PCU TXBUF to avoid
571 	 * wrap around.
572 	 */
573 	if (AR_SREV_KITE(ah))
574 		/*
575 		 * For AR9285 the number of Fifos are reduced to half.
576 		 * So set the usable tx buf size also to half to
577 		 * avoid data/delimiter underruns
578 		 */
579 		OS_REG_WRITE(ah, AR_PCU_TXBUF_CTRL, AR_9285_PCU_TXBUF_CTRL_USABLE_SIZE);
580 	else
581 		OS_REG_WRITE(ah, AR_PCU_TXBUF_CTRL, AR_PCU_TXBUF_CTRL_USABLE_SIZE);
582 }
583 
584 static void
585 ar5416InitBB(struct ath_hal *ah, const struct ieee80211_channel *chan)
586 {
587 	uint32_t synthDelay;
588 
589 	/*
590 	 * Wait for the frequency synth to settle (synth goes on
591 	 * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
592 	 * Value is in 100ns increments.
593 	  */
594 	synthDelay = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
595 	if (IEEE80211_IS_CHAN_CCK(chan)) {
596 		synthDelay = (4 * synthDelay) / 22;
597 	} else {
598 		synthDelay /= 10;
599 	}
600 
601 	/* Turn on PLL on 5416 */
602 	HALDEBUG(ah, HAL_DEBUG_RESET, "%s %s channel\n",
603 	    __func__, IEEE80211_IS_CHAN_5GHZ(chan) ? "5GHz" : "2GHz");
604 
605 	/* Activate the PHY (includes baseband activate and synthesizer on) */
606 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);
607 
608 	/*
609 	 * If the AP starts the calibration before the base band timeout
610 	 * completes  we could get rx_clear false triggering.  Add an
611 	 * extra BASE_ACTIVATE_DELAY usecs to ensure this condition
612 	 * does not happen.
613 	 */
614 	if (IEEE80211_IS_CHAN_HALF(chan)) {
615 		OS_DELAY((synthDelay << 1) + BASE_ACTIVATE_DELAY);
616 	} else if (IEEE80211_IS_CHAN_QUARTER(chan)) {
617 		OS_DELAY((synthDelay << 2) + BASE_ACTIVATE_DELAY);
618 	} else {
619 		OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
620 	}
621 }
622 
623 static void
624 ar5416InitIMR(struct ath_hal *ah, HAL_OPMODE opmode)
625 {
626 	struct ath_hal_5212 *ahp = AH5212(ah);
627 
628 	/*
629 	 * Setup interrupt handling.  Note that ar5212ResetTxQueue
630 	 * manipulates the secondary IMR's as queues are enabled
631 	 * and disabled.  This is done with RMW ops to insure the
632 	 * settings we make here are preserved.
633 	 */
634         ahp->ah_maskReg = AR_IMR_TXERR | AR_IMR_TXURN
635 			| AR_IMR_RXERR | AR_IMR_RXORN
636                         | AR_IMR_BCNMISC;
637 
638 #ifdef	AH_AR5416_INTERRUPT_MITIGATION
639 	ahp->ah_maskReg |= AR_IMR_RXINTM | AR_IMR_RXMINTR;
640 #else
641 	ahp->ah_maskReg |= AR_IMR_RXOK;
642 #endif
643 	ahp->ah_maskReg |= AR_IMR_TXOK;
644 
645 	if (opmode == HAL_M_HOSTAP)
646 		ahp->ah_maskReg |= AR_IMR_MIB;
647 	OS_REG_WRITE(ah, AR_IMR, ahp->ah_maskReg);
648 
649 #ifdef  ADRIAN_NOTYET
650 	/* This is straight from ath9k */
651 	if (! AR_SREV_HOWL(ah)) {
652 		OS_REG_WRITE(ah, AR_INTR_SYNC_CAUSE, 0xFFFFFFFF);
653 		OS_REG_WRITE(ah, AR_INTR_SYNC_ENABLE, AR_INTR_SYNC_DEFAULT);
654 		OS_REG_WRITE(ah, AR_INTR_SYNC_MASK, 0);
655 	}
656 #endif
657 
658 	/* Enable bus errors that are OR'd to set the HIUERR bit */
659 #if 0
660 	OS_REG_WRITE(ah, AR_IMR_S2,
661 	    	OS_REG_READ(ah, AR_IMR_S2) | AR_IMR_S2_GTT | AR_IMR_S2_CST);
662 #endif
663 }
664 
665 static void
666 ar5416InitQoS(struct ath_hal *ah)
667 {
668 	/* QoS support */
669 	OS_REG_WRITE(ah, AR_QOS_CONTROL, 0x100aa);	/* XXX magic */
670 	OS_REG_WRITE(ah, AR_QOS_SELECT, 0x3210);	/* XXX magic */
671 
672 	/* Turn on NOACK Support for QoS packets */
673 	OS_REG_WRITE(ah, AR_NOACK,
674 		SM(2, AR_NOACK_2BIT_VALUE) |
675 		SM(5, AR_NOACK_BIT_OFFSET) |
676 		SM(0, AR_NOACK_BYTE_OFFSET));
677 
678     	/*
679     	 * initialize TXOP for all TIDs
680     	 */
681 	OS_REG_WRITE(ah, AR_TXOP_X, AR_TXOP_X_VAL);
682 	OS_REG_WRITE(ah, AR_TXOP_0_3, 0xFFFFFFFF);
683 	OS_REG_WRITE(ah, AR_TXOP_4_7, 0xFFFFFFFF);
684 	OS_REG_WRITE(ah, AR_TXOP_8_11, 0xFFFFFFFF);
685 	OS_REG_WRITE(ah, AR_TXOP_12_15, 0xFFFFFFFF);
686 }
687 
688 static void
689 ar5416InitUserSettings(struct ath_hal *ah)
690 {
691 	struct ath_hal_5212 *ahp = AH5212(ah);
692 
693 	/* Restore user-specified settings */
694 	if (ahp->ah_miscMode != 0)
695 		OS_REG_WRITE(ah, AR_MISC_MODE, OS_REG_READ(ah, AR_MISC_MODE)
696 		    | ahp->ah_miscMode);
697 	if (ahp->ah_sifstime != (u_int) -1)
698 		ar5212SetSifsTime(ah, ahp->ah_sifstime);
699 	if (ahp->ah_slottime != (u_int) -1)
700 		ar5212SetSlotTime(ah, ahp->ah_slottime);
701 	if (ahp->ah_acktimeout != (u_int) -1)
702 		ar5212SetAckTimeout(ah, ahp->ah_acktimeout);
703 	if (ahp->ah_ctstimeout != (u_int) -1)
704 		ar5212SetCTSTimeout(ah, ahp->ah_ctstimeout);
705 	if (AH_PRIVATE(ah)->ah_diagreg != 0)
706 		OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);
707 	if (AH5416(ah)->ah_globaltxtimeout != (u_int) -1)
708         	ar5416SetGlobalTxTimeout(ah, AH5416(ah)->ah_globaltxtimeout);
709 }
710 
711 static void
712 ar5416SetRfMode(struct ath_hal *ah, const struct ieee80211_channel *chan)
713 {
714 	uint32_t rfMode;
715 
716 	if (chan == AH_NULL)
717 		return;
718 
719 	/* treat channel B as channel G , no  B mode suport in owl */
720 	rfMode = IEEE80211_IS_CHAN_CCK(chan) ?
721 	    AR_PHY_MODE_DYNAMIC : AR_PHY_MODE_OFDM;
722 
723 	if (AR_SREV_MERLIN_20(ah) && IS_5GHZ_FAST_CLOCK_EN(ah, chan)) {
724 		/* phy mode bits for 5GHz channels require Fast Clock */
725 		rfMode |= AR_PHY_MODE_DYNAMIC
726 		       |  AR_PHY_MODE_DYN_CCK_DISABLE;
727 	} else if (!AR_SREV_MERLIN_10_OR_LATER(ah)) {
728 		rfMode |= IEEE80211_IS_CHAN_5GHZ(chan) ?
729 			AR_PHY_MODE_RF5GHZ : AR_PHY_MODE_RF2GHZ;
730 	}
731 
732 	/*
733 	 * Set half/quarter mode flags if required.
734 	 *
735 	 * This doesn't change the IFS timings at all; that needs to
736 	 * be done as part of the MAC setup.  Similarly, the PLL
737 	 * configuration also needs some changes for the half/quarter
738 	 * rate clock.
739 	 */
740 	if (IEEE80211_IS_CHAN_HALF(chan))
741 		rfMode |= AR_PHY_MODE_HALF;
742 	else if (IEEE80211_IS_CHAN_QUARTER(chan))
743 		rfMode |= AR_PHY_MODE_QUARTER;
744 
745 	OS_REG_WRITE(ah, AR_PHY_MODE, rfMode);
746 }
747 
748 /*
749  * Places the hardware into reset and then pulls it out of reset
750  */
751 HAL_BOOL
752 ar5416ChipReset(struct ath_hal *ah, const struct ieee80211_channel *chan)
753 {
754 	OS_MARK(ah, AH_MARK_CHIPRESET, chan ? chan->ic_freq : 0);
755 	/*
756 	 * Warm reset is optimistic for open-loop TX power control.
757 	 */
758 	if (AR_SREV_MERLIN(ah) &&
759 	    ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) {
760 		if (!ar5416SetResetReg(ah, HAL_RESET_POWER_ON))
761 			return AH_FALSE;
762 	} else if (ah->ah_config.ah_force_full_reset) {
763 		if (!ar5416SetResetReg(ah, HAL_RESET_POWER_ON))
764 			return AH_FALSE;
765 	} else {
766 		if (!ar5416SetResetReg(ah, HAL_RESET_WARM))
767 			return AH_FALSE;
768 	}
769 
770 	/* Bring out of sleep mode (AGAIN) */
771 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
772 	       return AH_FALSE;
773 
774 #ifdef notyet
775 	ahp->ah_chipFullSleep = AH_FALSE;
776 #endif
777 
778 	AH5416(ah)->ah_initPLL(ah, chan);
779 
780 	/*
781 	 * Perform warm reset before the mode/PLL/turbo registers
782 	 * are changed in order to deactivate the radio.  Mode changes
783 	 * with an active radio can result in corrupted shifts to the
784 	 * radio device.
785 	 */
786 	ar5416SetRfMode(ah, chan);
787 
788 	return AH_TRUE;
789 }
790 
791 /*
792  * Delta slope coefficient computation.
793  * Required for OFDM operation.
794  */
795 static void
796 ar5416GetDeltaSlopeValues(struct ath_hal *ah, uint32_t coef_scaled,
797                           uint32_t *coef_mantissa, uint32_t *coef_exponent)
798 {
799 #define COEF_SCALE_S 24
800     uint32_t coef_exp, coef_man;
801     /*
802      * ALGO -> coef_exp = 14-floor(log2(coef));
803      * floor(log2(x)) is the highest set bit position
804      */
805     for (coef_exp = 31; coef_exp > 0; coef_exp--)
806             if ((coef_scaled >> coef_exp) & 0x1)
807                     break;
808     /* A coef_exp of 0 is a legal bit position but an unexpected coef_exp */
809     HALASSERT(coef_exp);
810     coef_exp = 14 - (coef_exp - COEF_SCALE_S);
811 
812     /*
813      * ALGO -> coef_man = floor(coef* 2^coef_exp+0.5);
814      * The coefficient is already shifted up for scaling
815      */
816     coef_man = coef_scaled + (1 << (COEF_SCALE_S - coef_exp - 1));
817 
818     *coef_mantissa = coef_man >> (COEF_SCALE_S - coef_exp);
819     *coef_exponent = coef_exp - 16;
820 
821 #undef COEF_SCALE_S
822 }
823 
824 void
825 ar5416SetDeltaSlope(struct ath_hal *ah, const struct ieee80211_channel *chan)
826 {
827 #define INIT_CLOCKMHZSCALED	0x64000000
828 	uint32_t coef_scaled, ds_coef_exp, ds_coef_man;
829 	uint32_t clockMhzScaled;
830 
831 	CHAN_CENTERS centers;
832 
833 	/* half and quarter rate can divide the scaled clock by 2 or 4 respectively */
834 	/* scale for selected channel bandwidth */
835 	clockMhzScaled = INIT_CLOCKMHZSCALED;
836 	if (IEEE80211_IS_CHAN_TURBO(chan))
837 		clockMhzScaled <<= 1;
838 	else if (IEEE80211_IS_CHAN_HALF(chan))
839 		clockMhzScaled >>= 1;
840 	else if (IEEE80211_IS_CHAN_QUARTER(chan))
841 		clockMhzScaled >>= 2;
842 
843 	/*
844 	 * ALGO -> coef = 1e8/fcarrier*fclock/40;
845 	 * scaled coef to provide precision for this floating calculation
846 	 */
847 	ar5416GetChannelCenters(ah, chan, &centers);
848 	coef_scaled = clockMhzScaled / centers.synth_center;
849 
850  	ar5416GetDeltaSlopeValues(ah, coef_scaled, &ds_coef_man, &ds_coef_exp);
851 
852 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
853 		AR_PHY_TIMING3_DSC_MAN, ds_coef_man);
854 	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING3,
855 		AR_PHY_TIMING3_DSC_EXP, ds_coef_exp);
856 
857         /*
858          * For Short GI,
859          * scaled coeff is 9/10 that of normal coeff
860          */
861         coef_scaled = (9 * coef_scaled)/10;
862 
863         ar5416GetDeltaSlopeValues(ah, coef_scaled, &ds_coef_man, &ds_coef_exp);
864 
865         /* for short gi */
866         OS_REG_RMW_FIELD(ah, AR_PHY_HALFGI,
867                 AR_PHY_HALFGI_DSC_MAN, ds_coef_man);
868         OS_REG_RMW_FIELD(ah, AR_PHY_HALFGI,
869                 AR_PHY_HALFGI_DSC_EXP, ds_coef_exp);
870 #undef INIT_CLOCKMHZSCALED
871 }
872 
873 /*
874  * Set a limit on the overall output power.  Used for dynamic
875  * transmit power control and the like.
876  *
877  * NB: limit is in units of 0.5 dbM.
878  */
879 HAL_BOOL
880 ar5416SetTxPowerLimit(struct ath_hal *ah, uint32_t limit)
881 {
882 	uint16_t dummyXpdGains[2];
883 
884 	AH_PRIVATE(ah)->ah_powerLimit = AH_MIN(limit, MAX_RATE_POWER);
885 	return ah->ah_setTxPower(ah, AH_PRIVATE(ah)->ah_curchan,
886 			dummyXpdGains);
887 }
888 
889 HAL_BOOL
890 ar5416GetChipPowerLimits(struct ath_hal *ah,
891 	struct ieee80211_channel *chan)
892 {
893 	struct ath_hal_5212 *ahp = AH5212(ah);
894 	int16_t minPower, maxPower;
895 
896 	/*
897 	 * Get Pier table max and min powers.
898 	 */
899 	if (ahp->ah_rfHal->getChannelMaxMinPower(ah, chan, &maxPower, &minPower)) {
900 		/* NB: rf code returns 1/4 dBm units, convert */
901 		chan->ic_maxpower = maxPower / 2;
902 		chan->ic_minpower = minPower / 2;
903 	} else {
904 		HALDEBUG(ah, HAL_DEBUG_ANY,
905 		    "%s: no min/max power for %u/0x%x\n",
906 		    __func__, chan->ic_freq, chan->ic_flags);
907 		chan->ic_maxpower = AR5416_MAX_RATE_POWER;
908 		chan->ic_minpower = 0;
909 	}
910 	HALDEBUG(ah, HAL_DEBUG_RESET,
911 	    "Chan %d: MaxPow = %d MinPow = %d\n",
912 	    chan->ic_freq, chan->ic_maxpower, chan->ic_minpower);
913 	return AH_TRUE;
914 }
915 
916 /**************************************************************
917  * ar5416WriteTxPowerRateRegisters
918  *
919  * Write the TX power rate registers from the raw values given
920  * in ratesArray[].
921  *
922  * The CCK and HT40 rate registers are only written if needed.
923  * HT20 and 11g/11a OFDM rate registers are always written.
924  *
925  * The values written are raw values which should be written
926  * to the registers - so it's up to the caller to pre-adjust
927  * them (eg CCK power offset value, or Merlin TX power offset,
928  * etc.)
929  */
930 void
931 ar5416WriteTxPowerRateRegisters(struct ath_hal *ah,
932     const struct ieee80211_channel *chan, const int16_t ratesArray[])
933 {
934 #define POW_SM(_r, _s)     (((_r) & 0x3f) << (_s))
935 
936     /* Write the OFDM power per rate set */
937     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE1,
938         POW_SM(ratesArray[rate18mb], 24)
939           | POW_SM(ratesArray[rate12mb], 16)
940           | POW_SM(ratesArray[rate9mb], 8)
941           | POW_SM(ratesArray[rate6mb], 0)
942     );
943     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE2,
944         POW_SM(ratesArray[rate54mb], 24)
945           | POW_SM(ratesArray[rate48mb], 16)
946           | POW_SM(ratesArray[rate36mb], 8)
947           | POW_SM(ratesArray[rate24mb], 0)
948     );
949 
950     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
951         /* Write the CCK power per rate set */
952         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE3,
953             POW_SM(ratesArray[rate2s], 24)
954               | POW_SM(ratesArray[rate2l],  16)
955               | POW_SM(ratesArray[rateXr],  8) /* XR target power */
956               | POW_SM(ratesArray[rate1l],   0)
957         );
958         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE4,
959             POW_SM(ratesArray[rate11s], 24)
960               | POW_SM(ratesArray[rate11l], 16)
961               | POW_SM(ratesArray[rate5_5s], 8)
962               | POW_SM(ratesArray[rate5_5l], 0)
963         );
964     HALDEBUG(ah, HAL_DEBUG_RESET,
965 	"%s AR_PHY_POWER_TX_RATE3=0x%x AR_PHY_POWER_TX_RATE4=0x%x\n",
966 	    __func__, OS_REG_READ(ah,AR_PHY_POWER_TX_RATE3),
967 	    OS_REG_READ(ah,AR_PHY_POWER_TX_RATE4));
968     }
969 
970     /* Write the HT20 power per rate set */
971     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE5,
972         POW_SM(ratesArray[rateHt20_3], 24)
973           | POW_SM(ratesArray[rateHt20_2], 16)
974           | POW_SM(ratesArray[rateHt20_1], 8)
975           | POW_SM(ratesArray[rateHt20_0], 0)
976     );
977     OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE6,
978         POW_SM(ratesArray[rateHt20_7], 24)
979           | POW_SM(ratesArray[rateHt20_6], 16)
980           | POW_SM(ratesArray[rateHt20_5], 8)
981           | POW_SM(ratesArray[rateHt20_4], 0)
982     );
983 
984     if (IEEE80211_IS_CHAN_HT40(chan)) {
985         /* Write the HT40 power per rate set */
986         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE7,
987             POW_SM(ratesArray[rateHt40_3], 24)
988               | POW_SM(ratesArray[rateHt40_2], 16)
989               | POW_SM(ratesArray[rateHt40_1], 8)
990               | POW_SM(ratesArray[rateHt40_0], 0)
991         );
992         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE8,
993             POW_SM(ratesArray[rateHt40_7], 24)
994               | POW_SM(ratesArray[rateHt40_6], 16)
995               | POW_SM(ratesArray[rateHt40_5], 8)
996               | POW_SM(ratesArray[rateHt40_4], 0)
997         );
998         /* Write the Dup/Ext 40 power per rate set */
999         OS_REG_WRITE(ah, AR_PHY_POWER_TX_RATE9,
1000             POW_SM(ratesArray[rateExtOfdm], 24)
1001               | POW_SM(ratesArray[rateExtCck], 16)
1002               | POW_SM(ratesArray[rateDupOfdm], 8)
1003               | POW_SM(ratesArray[rateDupCck], 0)
1004         );
1005     }
1006 }
1007 
1008 
1009 /**************************************************************
1010  * ar5416SetTransmitPower
1011  *
1012  * Set the transmit power in the baseband for the given
1013  * operating channel and mode.
1014  */
1015 HAL_BOOL
1016 ar5416SetTransmitPower(struct ath_hal *ah,
1017 	const struct ieee80211_channel *chan, uint16_t *rfXpdGain)
1018 {
1019 #define N(a)            (sizeof (a) / sizeof (a[0]))
1020 
1021     MODAL_EEP_HEADER	*pModal;
1022     struct ath_hal_5212 *ahp = AH5212(ah);
1023     int16_t		ratesArray[Ar5416RateSize];
1024     int16_t		txPowerIndexOffset = 0;
1025     uint8_t		ht40PowerIncForPdadc = 2;
1026     int			i;
1027 
1028     uint16_t		cfgCtl;
1029     uint16_t		powerLimit;
1030     uint16_t		twiceAntennaReduction;
1031     uint16_t		twiceMaxRegulatoryPower;
1032     int16_t		maxPower;
1033     HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
1034     struct ar5416eeprom	*pEepData = &ee->ee_base;
1035 
1036     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
1037 
1038     /* Setup info for the actual eeprom */
1039     OS_MEMZERO(ratesArray, sizeof(ratesArray));
1040     cfgCtl = ath_hal_getctl(ah, chan);
1041     powerLimit = chan->ic_maxregpower * 2;
1042     twiceAntennaReduction = chan->ic_maxantgain;
1043     twiceMaxRegulatoryPower = AH_MIN(MAX_RATE_POWER, AH_PRIVATE(ah)->ah_powerLimit);
1044     pModal = &pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
1045     HALDEBUG(ah, HAL_DEBUG_RESET, "%s Channel=%u CfgCtl=%u\n",
1046 	__func__,chan->ic_freq, cfgCtl );
1047 
1048     if (IS_EEP_MINOR_V2(ah)) {
1049         ht40PowerIncForPdadc = pModal->ht40PowerIncForPdadc;
1050     }
1051 
1052     if (!ar5416SetPowerPerRateTable(ah, pEepData,  chan,
1053                                     &ratesArray[0],cfgCtl,
1054                                     twiceAntennaReduction,
1055 				    twiceMaxRegulatoryPower, powerLimit)) {
1056         HALDEBUG(ah, HAL_DEBUG_ANY,
1057 	    "%s: unable to set tx power per rate table\n", __func__);
1058         return AH_FALSE;
1059     }
1060 
1061     if (!AH5416(ah)->ah_setPowerCalTable(ah,  pEepData, chan, &txPowerIndexOffset)) {
1062         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: unable to set power table\n",
1063 	    __func__);
1064         return AH_FALSE;
1065     }
1066 
1067     maxPower = AH_MAX(ratesArray[rate6mb], ratesArray[rateHt20_0]);
1068 
1069     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1070         maxPower = AH_MAX(maxPower, ratesArray[rate1l]);
1071     }
1072 
1073     if (IEEE80211_IS_CHAN_HT40(chan)) {
1074         maxPower = AH_MAX(maxPower, ratesArray[rateHt40_0]);
1075     }
1076 
1077     ahp->ah_tx6PowerInHalfDbm = maxPower;
1078     AH_PRIVATE(ah)->ah_maxPowerLevel = maxPower;
1079     ahp->ah_txPowerIndexOffset = txPowerIndexOffset;
1080 
1081     /*
1082      * txPowerIndexOffset is set by the SetPowerTable() call -
1083      *  adjust the rate table (0 offset if rates EEPROM not loaded)
1084      */
1085     for (i = 0; i < N(ratesArray); i++) {
1086         ratesArray[i] = (int16_t)(txPowerIndexOffset + ratesArray[i]);
1087         if (ratesArray[i] > AR5416_MAX_RATE_POWER)
1088             ratesArray[i] = AR5416_MAX_RATE_POWER;
1089     }
1090 
1091 #ifdef AH_EEPROM_DUMP
1092     /*
1093      * Dump the rate array whilst it represents the intended dBm*2
1094      * values versus what's being adjusted before being programmed
1095      * in. Keep this in mind if you code up this function and enable
1096      * this debugging; the values won't necessarily be what's being
1097      * programmed into the hardware.
1098      */
1099     ar5416PrintPowerPerRate(ah, ratesArray);
1100 #endif
1101 
1102     /*
1103      * Merlin and later have a power offset, so subtract
1104      * pwr_table_offset * 2 from each value. The default
1105      * power offset is -5 dBm - ie, a register value of 0
1106      * equates to a TX power of -5 dBm.
1107      */
1108     if (AR_SREV_MERLIN_20_OR_LATER(ah)) {
1109         int8_t pwr_table_offset;
1110 
1111 	(void) ath_hal_eepromGet(ah, AR_EEP_PWR_TABLE_OFFSET,
1112 	    &pwr_table_offset);
1113 	/* Underflow power gets clamped at raw value 0 */
1114 	/* Overflow power gets camped at AR5416_MAX_RATE_POWER */
1115 	for (i = 0; i < N(ratesArray); i++) {
1116 		/*
1117 		 * + pwr_table_offset is in dBm
1118 		 * + ratesArray is in 1/2 dBm
1119 		 */
1120 		ratesArray[i] -= (pwr_table_offset * 2);
1121 		if (ratesArray[i] < 0)
1122 			ratesArray[i] = 0;
1123 		else if (ratesArray[i] > AR5416_MAX_RATE_POWER)
1124 		    ratesArray[i] = AR5416_MAX_RATE_POWER;
1125 	}
1126     }
1127 
1128     /*
1129      * Adjust rates for OLC where needed
1130      *
1131      * The following CCK rates need adjusting when doing 2.4ghz
1132      * CCK transmission.
1133      *
1134      * + rate2s, rate2l, rate1l, rate11s, rate11l, rate5_5s, rate5_5l
1135      * + rateExtCck, rateDupCck
1136      *
1137      * They're adjusted here regardless. The hardware then gets
1138      * programmed as needed. 5GHz operation doesn't program in CCK
1139      * rates for legacy mode but they seem to be initialised for
1140      * HT40 regardless of channel type.
1141      */
1142     if (AR_SREV_MERLIN_20_OR_LATER(ah) &&
1143 	    ath_hal_eepromGetFlag(ah, AR_EEP_OL_PWRCTRL)) {
1144         int adj[] = {
1145 	              rate2s, rate2l, rate1l, rate11s, rate11l,
1146 	              rate5_5s, rate5_5l, rateExtCck, rateDupCck
1147 		    };
1148         int cck_ofdm_delta = 2;
1149 	int i;
1150 	for (i = 0; i < N(adj); i++) {
1151             ratesArray[adj[i]] -= cck_ofdm_delta;
1152 	    if (ratesArray[adj[i]] < 0)
1153 	        ratesArray[adj[i]] = 0;
1154         }
1155     }
1156 
1157     /*
1158      * Adjust the HT40 power to meet the correct target TX power
1159      * for 40MHz mode, based on TX power curves that are established
1160      * for 20MHz mode.
1161      *
1162      * XXX handle overflow/too high power level?
1163      */
1164     if (IEEE80211_IS_CHAN_HT40(chan)) {
1165 	ratesArray[rateHt40_0] += ht40PowerIncForPdadc;
1166 	ratesArray[rateHt40_1] += ht40PowerIncForPdadc;
1167 	ratesArray[rateHt40_2] += ht40PowerIncForPdadc;
1168 	ratesArray[rateHt40_3] += ht40PowerIncForPdadc;
1169 	ratesArray[rateHt40_4] += ht40PowerIncForPdadc;
1170 	ratesArray[rateHt40_5] += ht40PowerIncForPdadc;
1171 	ratesArray[rateHt40_6] += ht40PowerIncForPdadc;
1172 	ratesArray[rateHt40_7] += ht40PowerIncForPdadc;
1173     }
1174 
1175     /* Write the TX power rate registers */
1176     ar5416WriteTxPowerRateRegisters(ah, chan, ratesArray);
1177 
1178     /* Write the Power subtraction for dynamic chain changing, for per-packet powertx */
1179     OS_REG_WRITE(ah, AR_PHY_POWER_TX_SUB,
1180         POW_SM(pModal->pwrDecreaseFor3Chain, 6)
1181           | POW_SM(pModal->pwrDecreaseFor2Chain, 0)
1182     );
1183     return AH_TRUE;
1184 #undef POW_SM
1185 #undef N
1186 }
1187 
1188 /*
1189  * Exported call to check for a recent gain reading and return
1190  * the current state of the thermal calibration gain engine.
1191  */
1192 HAL_RFGAIN
1193 ar5416GetRfgain(struct ath_hal *ah)
1194 {
1195 
1196 	return (HAL_RFGAIN_INACTIVE);
1197 }
1198 
1199 /*
1200  * Places all of hardware into reset
1201  */
1202 HAL_BOOL
1203 ar5416Disable(struct ath_hal *ah)
1204 {
1205 
1206 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
1207 		return AH_FALSE;
1208 	if (! ar5416SetResetReg(ah, HAL_RESET_COLD))
1209 		return AH_FALSE;
1210 
1211 	AH5416(ah)->ah_initPLL(ah, AH_NULL);
1212 	return (AH_TRUE);
1213 }
1214 
1215 /*
1216  * Places the PHY and Radio chips into reset.  A full reset
1217  * must be called to leave this state.  The PCI/MAC/PCU are
1218  * not placed into reset as we must receive interrupt to
1219  * re-enable the hardware.
1220  */
1221 HAL_BOOL
1222 ar5416PhyDisable(struct ath_hal *ah)
1223 {
1224 
1225 	if (! ar5416SetResetReg(ah, HAL_RESET_WARM))
1226 		return AH_FALSE;
1227 
1228 	AH5416(ah)->ah_initPLL(ah, AH_NULL);
1229 	return (AH_TRUE);
1230 }
1231 
1232 /*
1233  * Write the given reset bit mask into the reset register
1234  */
1235 HAL_BOOL
1236 ar5416SetResetReg(struct ath_hal *ah, uint32_t type)
1237 {
1238 	/*
1239 	 * Set force wake
1240 	 */
1241 	OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1242 	    AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1243 
1244 	switch (type) {
1245 	case HAL_RESET_POWER_ON:
1246 		return ar5416SetResetPowerOn(ah);
1247 	case HAL_RESET_WARM:
1248 	case HAL_RESET_COLD:
1249 		return ar5416SetReset(ah, type);
1250 	default:
1251 		HALASSERT(AH_FALSE);
1252 		return AH_FALSE;
1253 	}
1254 }
1255 
1256 static HAL_BOOL
1257 ar5416SetResetPowerOn(struct ath_hal *ah)
1258 {
1259     /* Power On Reset (Hard Reset) */
1260 
1261     /*
1262      * Set force wake
1263      *
1264      * If the MAC was running, previously calling
1265      * reset will wake up the MAC but it may go back to sleep
1266      * before we can start polling.
1267      * Set force wake  stops that
1268      * This must be called before initiating a hard reset.
1269      */
1270     OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1271             AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1272 
1273     /*
1274      * PowerOn reset can be used in open loop power control or failure recovery.
1275      * If we do RTC reset while DMA is still running, hardware may corrupt memory.
1276      * Therefore, we need to reset AHB first to stop DMA.
1277      */
1278     if (! AR_SREV_HOWL(ah))
1279     	OS_REG_WRITE(ah, AR_RC, AR_RC_AHB);
1280     /*
1281      * RTC reset and clear
1282      */
1283     OS_REG_WRITE(ah, AR_RTC_RESET, 0);
1284     OS_DELAY(20);
1285 
1286     if (! AR_SREV_HOWL(ah))
1287     	OS_REG_WRITE(ah, AR_RC, 0);
1288 
1289     OS_REG_WRITE(ah, AR_RTC_RESET, 1);
1290 
1291     /*
1292      * Poll till RTC is ON
1293      */
1294     if (!ath_hal_wait(ah, AR_RTC_STATUS, AR_RTC_PM_STATUS_M, AR_RTC_STATUS_ON)) {
1295         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: RTC not waking up\n", __func__);
1296         return AH_FALSE;
1297     }
1298 
1299     return ar5416SetReset(ah, HAL_RESET_COLD);
1300 }
1301 
1302 static HAL_BOOL
1303 ar5416SetReset(struct ath_hal *ah, int type)
1304 {
1305     uint32_t tmpReg, mask;
1306     uint32_t rst_flags;
1307 
1308 #ifdef	AH_SUPPORT_AR9130	/* Because of the AR9130 specific registers */
1309     if (AR_SREV_HOWL(ah)) {
1310         HALDEBUG(ah, HAL_DEBUG_ANY, "[ath] HOWL: Fiddling with derived clk!\n");
1311         uint32_t val = OS_REG_READ(ah, AR_RTC_DERIVED_CLK);
1312         val &= ~AR_RTC_DERIVED_CLK_PERIOD;
1313         val |= SM(1, AR_RTC_DERIVED_CLK_PERIOD);
1314         OS_REG_WRITE(ah, AR_RTC_DERIVED_CLK, val);
1315         (void) OS_REG_READ(ah, AR_RTC_DERIVED_CLK);
1316     }
1317 #endif	/* AH_SUPPORT_AR9130 */
1318 
1319     /*
1320      * Force wake
1321      */
1322     OS_REG_WRITE(ah, AR_RTC_FORCE_WAKE,
1323 	AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
1324 
1325 #ifdef	AH_SUPPORT_AR9130
1326     if (AR_SREV_HOWL(ah)) {
1327         rst_flags = AR_RTC_RC_MAC_WARM | AR_RTC_RC_MAC_COLD |
1328           AR_RTC_RC_COLD_RESET | AR_RTC_RC_WARM_RESET;
1329     } else {
1330 #endif	/* AH_SUPPORT_AR9130 */
1331         /*
1332          * Reset AHB
1333          *
1334          * (In case the last interrupt source was a bus timeout.)
1335          * XXX TODO: this is not the way to do it! It should be recorded
1336          * XXX by the interrupt handler and passed _into_ the
1337          * XXX reset path routine so this occurs.
1338          */
1339         tmpReg = OS_REG_READ(ah, AR_INTR_SYNC_CAUSE);
1340         if (tmpReg & (AR_INTR_SYNC_LOCAL_TIMEOUT|AR_INTR_SYNC_RADM_CPL_TIMEOUT)) {
1341             OS_REG_WRITE(ah, AR_INTR_SYNC_ENABLE, 0);
1342             OS_REG_WRITE(ah, AR_RC, AR_RC_AHB|AR_RC_HOSTIF);
1343         } else {
1344 	    OS_REG_WRITE(ah, AR_RC, AR_RC_AHB);
1345         }
1346         rst_flags = AR_RTC_RC_MAC_WARM;
1347         if (type == HAL_RESET_COLD)
1348             rst_flags |= AR_RTC_RC_MAC_COLD;
1349 #ifdef	AH_SUPPORT_AR9130
1350     }
1351 #endif	/* AH_SUPPORT_AR9130 */
1352 
1353     OS_REG_WRITE(ah, AR_RTC_RC, rst_flags);
1354 
1355     if (AR_SREV_HOWL(ah))
1356         OS_DELAY(10000);
1357     else
1358         OS_DELAY(100);
1359 
1360     /*
1361      * Clear resets and force wakeup
1362      */
1363     OS_REG_WRITE(ah, AR_RTC_RC, 0);
1364     if (!ath_hal_wait(ah, AR_RTC_RC, AR_RTC_RC_M, 0)) {
1365         HALDEBUG(ah, HAL_DEBUG_ANY, "%s: RTC stuck in MAC reset\n", __func__);
1366         return AH_FALSE;
1367     }
1368 
1369     /* Clear AHB reset */
1370     if (! AR_SREV_HOWL(ah))
1371         OS_REG_WRITE(ah, AR_RC, 0);
1372 
1373     if (AR_SREV_HOWL(ah))
1374         OS_DELAY(50);
1375 
1376     if (AR_SREV_HOWL(ah)) {
1377                 uint32_t mask;
1378                 mask = OS_REG_READ(ah, AR_CFG);
1379                 if (mask & (AR_CFG_SWRB | AR_CFG_SWTB | AR_CFG_SWRG)) {
1380                         HALDEBUG(ah, HAL_DEBUG_RESET,
1381                                 "CFG Byte Swap Set 0x%x\n", mask);
1382                 } else {
1383                         mask =
1384                                 INIT_CONFIG_STATUS | AR_CFG_SWRB | AR_CFG_SWTB;
1385                         OS_REG_WRITE(ah, AR_CFG, mask);
1386                         HALDEBUG(ah, HAL_DEBUG_RESET,
1387                                 "Setting CFG 0x%x\n", OS_REG_READ(ah, AR_CFG));
1388                 }
1389     } else {
1390 	if (type == HAL_RESET_COLD) {
1391 		if (isBigEndian()) {
1392 			/*
1393 			 * Set CFG, little-endian for descriptor accesses.
1394 			 */
1395 			mask = INIT_CONFIG_STATUS | AR_CFG_SWRD;
1396 #ifndef AH_NEED_DESC_SWAP
1397 			mask |= AR_CFG_SWTD;
1398 #endif
1399 			HALDEBUG(ah, HAL_DEBUG_RESET,
1400 			    "%s Applying descriptor swap\n", __func__);
1401 			OS_REG_WRITE(ah, AR_CFG, mask);
1402 		} else
1403 			OS_REG_WRITE(ah, AR_CFG, INIT_CONFIG_STATUS);
1404 	}
1405     }
1406 
1407     return AH_TRUE;
1408 }
1409 
1410 void
1411 ar5416InitChainMasks(struct ath_hal *ah)
1412 {
1413 	int rx_chainmask = AH5416(ah)->ah_rx_chainmask;
1414 
1415 	/* Flip this for this chainmask regardless of chip */
1416 	if (rx_chainmask == 0x5)
1417 		OS_REG_SET_BIT(ah, AR_PHY_ANALOG_SWAP, AR_PHY_SWAP_ALT_CHAIN);
1418 
1419 	/*
1420 	 * Workaround for OWL 1.0 calibration failure; enable multi-chain;
1421 	 * then set true mask after calibration.
1422 	 */
1423 	if (IS_5416V1(ah) && (rx_chainmask == 0x5 || rx_chainmask == 0x3)) {
1424 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, 0x7);
1425 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, 0x7);
1426 	} else {
1427 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
1428 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, AH5416(ah)->ah_rx_chainmask);
1429 	}
1430 	OS_REG_WRITE(ah, AR_SELFGEN_MASK, AH5416(ah)->ah_tx_chainmask);
1431 
1432 	if (AH5416(ah)->ah_tx_chainmask == 0x5)
1433 		OS_REG_SET_BIT(ah, AR_PHY_ANALOG_SWAP, AR_PHY_SWAP_ALT_CHAIN);
1434 
1435 	if (AR_SREV_HOWL(ah)) {
1436 		OS_REG_WRITE(ah, AR_PHY_ANALOG_SWAP,
1437 		OS_REG_READ(ah, AR_PHY_ANALOG_SWAP) | 0x00000001);
1438 	}
1439 }
1440 
1441 /*
1442  * Work-around for Owl 1.0 calibration failure.
1443  *
1444  * ar5416InitChainMasks sets the RX chainmask to 0x7 if it's Owl 1.0
1445  * due to init calibration failures. ar5416RestoreChainMask restores
1446  * these registers to the correct setting.
1447  */
1448 void
1449 ar5416RestoreChainMask(struct ath_hal *ah)
1450 {
1451 	int rx_chainmask = AH5416(ah)->ah_rx_chainmask;
1452 
1453 	if (IS_5416V1(ah) && (rx_chainmask == 0x5 || rx_chainmask == 0x3)) {
1454 		OS_REG_WRITE(ah, AR_PHY_RX_CHAINMASK, rx_chainmask);
1455 		OS_REG_WRITE(ah, AR_PHY_CAL_CHAINMASK, rx_chainmask);
1456 	}
1457 }
1458 
1459 /*
1460  * Update the chainmask based on the current channel configuration.
1461  *
1462  * XXX ath9k checks bluetooth co-existence here
1463  * XXX ath9k checks whether the current state is "off-channel".
1464  * XXX ath9k sticks the hardware into 1x1 mode for legacy;
1465  *     we're going to leave multi-RX on for multi-path cancellation.
1466  */
1467 static void
1468 ar5416UpdateChainMasks(struct ath_hal *ah, HAL_BOOL is_ht)
1469 {
1470 	struct ath_hal_private *ahpriv = AH_PRIVATE(ah);
1471 	HAL_CAPABILITIES *pCap = &ahpriv->ah_caps;
1472 
1473 	if (is_ht) {
1474 		AH5416(ah)->ah_tx_chainmask = pCap->halTxChainMask;
1475 	} else {
1476 		AH5416(ah)->ah_tx_chainmask = 1;
1477 	}
1478 	AH5416(ah)->ah_rx_chainmask = pCap->halRxChainMask;
1479 	HALDEBUG(ah, HAL_DEBUG_RESET, "TX chainmask: 0x%x; RX chainmask: 0x%x\n",
1480 	    AH5416(ah)->ah_tx_chainmask,
1481 	    AH5416(ah)->ah_rx_chainmask);
1482 }
1483 
1484 void
1485 ar5416InitPLL(struct ath_hal *ah, const struct ieee80211_channel *chan)
1486 {
1487 	uint32_t pll = AR_RTC_PLL_REFDIV_5 | AR_RTC_PLL_DIV2;
1488 	if (chan != AH_NULL) {
1489 		if (IEEE80211_IS_CHAN_HALF(chan))
1490 			pll |= SM(0x1, AR_RTC_PLL_CLKSEL);
1491 		else if (IEEE80211_IS_CHAN_QUARTER(chan))
1492 			pll |= SM(0x2, AR_RTC_PLL_CLKSEL);
1493 
1494 		if (IEEE80211_IS_CHAN_5GHZ(chan))
1495 			pll |= SM(0xa, AR_RTC_PLL_DIV);
1496 		else
1497 			pll |= SM(0xb, AR_RTC_PLL_DIV);
1498 	} else
1499 		pll |= SM(0xb, AR_RTC_PLL_DIV);
1500 
1501 	OS_REG_WRITE(ah, AR_RTC_PLL_CONTROL, pll);
1502 
1503 	/* TODO:
1504 	* For multi-band owl, switch between bands by reiniting the PLL.
1505 	*/
1506 
1507 	OS_DELAY(RTC_PLL_SETTLE_DELAY);
1508 
1509 	OS_REG_WRITE(ah, AR_RTC_SLEEP_CLK, AR_RTC_SLEEP_DERIVED_CLK);
1510 }
1511 
1512 static void
1513 ar5416SetDefGainValues(struct ath_hal *ah,
1514     const MODAL_EEP_HEADER *pModal,
1515     const struct ar5416eeprom *eep,
1516     uint8_t txRxAttenLocal, int regChainOffset, int i)
1517 {
1518 
1519 	if (IS_EEP_MINOR_V3(ah)) {
1520 		txRxAttenLocal = pModal->txRxAttenCh[i];
1521 
1522 		if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1523 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1524 			      AR_PHY_GAIN_2GHZ_XATTEN1_MARGIN,
1525 			      pModal->bswMargin[i]);
1526 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1527 			      AR_PHY_GAIN_2GHZ_XATTEN1_DB,
1528 			      pModal->bswAtten[i]);
1529 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1530 			      AR_PHY_GAIN_2GHZ_XATTEN2_MARGIN,
1531 			      pModal->xatten2Margin[i]);
1532 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1533 			      AR_PHY_GAIN_2GHZ_XATTEN2_DB,
1534 			      pModal->xatten2Db[i]);
1535 		} else {
1536 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1537 			      AR_PHY_GAIN_2GHZ_BSW_MARGIN,
1538 			      pModal->bswMargin[i]);
1539 			OS_REG_RMW_FIELD(ah, AR_PHY_GAIN_2GHZ + regChainOffset,
1540 			      AR_PHY_GAIN_2GHZ_BSW_ATTEN,
1541 			      pModal->bswAtten[i]);
1542 		}
1543 	}
1544 
1545 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1546 		OS_REG_RMW_FIELD(ah,
1547 		      AR_PHY_RXGAIN + regChainOffset,
1548 		      AR9280_PHY_RXGAIN_TXRX_ATTEN, txRxAttenLocal);
1549 		OS_REG_RMW_FIELD(ah,
1550 		      AR_PHY_RXGAIN + regChainOffset,
1551 		      AR9280_PHY_RXGAIN_TXRX_MARGIN, pModal->rxTxMarginCh[i]);
1552 	} else {
1553 		OS_REG_RMW_FIELD(ah,
1554 			  AR_PHY_RXGAIN + regChainOffset,
1555 			  AR_PHY_RXGAIN_TXRX_ATTEN, txRxAttenLocal);
1556 		OS_REG_RMW_FIELD(ah,
1557 			  AR_PHY_GAIN_2GHZ + regChainOffset,
1558 			  AR_PHY_GAIN_2GHZ_RXTX_MARGIN, pModal->rxTxMarginCh[i]);
1559 	}
1560 }
1561 
1562 /*
1563  * Get the register chain offset for the given chain.
1564  *
1565  * Take into account the register chain swapping with AR5416 v2.0.
1566  *
1567  * XXX make sure that the reg chain swapping is only done for
1568  * XXX AR5416 v2.0 or greater, and not later chips?
1569  */
1570 int
1571 ar5416GetRegChainOffset(struct ath_hal *ah, int i)
1572 {
1573 	int regChainOffset;
1574 
1575 	if (AR_SREV_5416_V20_OR_LATER(ah) &&
1576 	    (AH5416(ah)->ah_rx_chainmask == 0x5 ||
1577 	    AH5416(ah)->ah_tx_chainmask == 0x5) && (i != 0)) {
1578 		/* Regs are swapped from chain 2 to 1 for 5416 2_0 with
1579 		 * only chains 0 and 2 populated
1580 		 */
1581 		regChainOffset = (i == 1) ? 0x2000 : 0x1000;
1582 	} else {
1583 		regChainOffset = i * 0x1000;
1584 	}
1585 
1586 	return regChainOffset;
1587 }
1588 
1589 /*
1590  * Read EEPROM header info and program the device for correct operation
1591  * given the channel value.
1592  */
1593 HAL_BOOL
1594 ar5416SetBoardValues(struct ath_hal *ah, const struct ieee80211_channel *chan)
1595 {
1596     const HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
1597     const struct ar5416eeprom *eep = &ee->ee_base;
1598     const MODAL_EEP_HEADER *pModal;
1599     int			i, regChainOffset;
1600     uint8_t		txRxAttenLocal;    /* workaround for eeprom versions <= 14.2 */
1601 
1602     HALASSERT(AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER14_1);
1603     pModal = &eep->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)];
1604 
1605     /* NB: workaround for eeprom versions <= 14.2 */
1606     txRxAttenLocal = IEEE80211_IS_CHAN_2GHZ(chan) ? 23 : 44;
1607 
1608     OS_REG_WRITE(ah, AR_PHY_SWITCH_COM, pModal->antCtrlCommon);
1609     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
1610 	   if (AR_SREV_MERLIN(ah)) {
1611 		if (i >= 2) break;
1612 	   }
1613 	regChainOffset = ar5416GetRegChainOffset(ah, i);
1614 
1615         OS_REG_WRITE(ah, AR_PHY_SWITCH_CHAIN_0 + regChainOffset, pModal->antCtrlChain[i]);
1616 
1617         OS_REG_WRITE(ah, AR_PHY_TIMING_CTRL4 + regChainOffset,
1618         	(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4 + regChainOffset) &
1619         	~(AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF | AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF)) |
1620         	SM(pModal->iqCalICh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_I_COFF) |
1621         	SM(pModal->iqCalQCh[i], AR_PHY_TIMING_CTRL4_IQCORR_Q_Q_COFF));
1622 
1623         /*
1624          * Large signal upgrade,
1625 	 * If 14.3 or later EEPROM, use
1626 	 * txRxAttenLocal = pModal->txRxAttenCh[i]
1627 	 * else txRxAttenLocal is fixed value above.
1628          */
1629 
1630         if ((i == 0) || AR_SREV_5416_V20_OR_LATER(ah))
1631 	    ar5416SetDefGainValues(ah, pModal, eep, txRxAttenLocal, regChainOffset, i);
1632 
1633     }
1634 
1635 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1636                 if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1637                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH0, AR_AN_RF2G1_CH0_OB, pModal->ob);
1638                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH0, AR_AN_RF2G1_CH0_DB, pModal->db);
1639                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH1, AR_AN_RF2G1_CH1_OB, pModal->ob_ch1);
1640                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF2G1_CH1, AR_AN_RF2G1_CH1_DB, pModal->db_ch1);
1641                 } else {
1642                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH0, AR_AN_RF5G1_CH0_OB5, pModal->ob);
1643                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH0, AR_AN_RF5G1_CH0_DB5, pModal->db);
1644                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH1, AR_AN_RF5G1_CH1_OB5, pModal->ob_ch1);
1645                         OS_A_REG_RMW_FIELD(ah, AR_AN_RF5G1_CH1, AR_AN_RF5G1_CH1_DB5, pModal->db_ch1);
1646                 }
1647                 OS_A_REG_RMW_FIELD(ah, AR_AN_TOP2, AR_AN_TOP2_XPABIAS_LVL, pModal->xpaBiasLvl);
1648                 OS_A_REG_RMW_FIELD(ah, AR_AN_TOP2, AR_AN_TOP2_LOCALBIAS,
1649 		    !!(pModal->flagBits & AR5416_EEP_FLAG_LOCALBIAS));
1650                 OS_A_REG_RMW_FIELD(ah, AR_PHY_XPA_CFG, AR_PHY_FORCE_XPA_CFG,
1651 		    !!(pModal->flagBits & AR5416_EEP_FLAG_FORCEXPAON));
1652         }
1653 
1654     OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH, pModal->switchSettling);
1655     OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_ADC, pModal->adcDesiredSize);
1656 
1657     if (! AR_SREV_MERLIN_10_OR_LATER(ah))
1658     	OS_REG_RMW_FIELD(ah, AR_PHY_DESIRED_SZ, AR_PHY_DESIRED_SZ_PGA, pModal->pgaDesiredSize);
1659 
1660     OS_REG_WRITE(ah, AR_PHY_RF_CTL4,
1661         SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAA_OFF)
1662         | SM(pModal->txEndToXpaOff, AR_PHY_RF_CTL4_TX_END_XPAB_OFF)
1663         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAA_ON)
1664         | SM(pModal->txFrameToXpaOn, AR_PHY_RF_CTL4_FRAME_XPAB_ON));
1665 
1666     OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL3, AR_PHY_TX_END_TO_A2_RX_ON,
1667 	pModal->txEndToRxOn);
1668 
1669     if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
1670 	OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR9280_PHY_CCA_THRESH62,
1671 	    pModal->thresh62);
1672 	OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA0, AR_PHY_EXT_CCA0_THRESH62,
1673 	    pModal->thresh62);
1674     } else {
1675 	OS_REG_RMW_FIELD(ah, AR_PHY_CCA, AR_PHY_CCA_THRESH62,
1676 	    pModal->thresh62);
1677 	OS_REG_RMW_FIELD(ah, AR_PHY_EXT_CCA, AR_PHY_EXT_CCA_THRESH62,
1678 	    pModal->thresh62);
1679     }
1680 
1681     /* Minor Version Specific application */
1682     if (IS_EEP_MINOR_V2(ah)) {
1683         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2, AR_PHY_TX_FRAME_TO_DATA_START,
1684 	    pModal->txFrameToDataStart);
1685         OS_REG_RMW_FIELD(ah, AR_PHY_RF_CTL2, AR_PHY_TX_FRAME_TO_PA_ON,
1686 	    pModal->txFrameToPaOn);
1687     }
1688 
1689     if (IS_EEP_MINOR_V3(ah) && IEEE80211_IS_CHAN_HT40(chan))
1690 		/* Overwrite switch settling with HT40 value */
1691 		OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_SWITCH,
1692 		    pModal->swSettleHt40);
1693 
1694     if (AR_SREV_MERLIN_20_OR_LATER(ah) && EEP_MINOR(ah) >= AR5416_EEP_MINOR_VER_19)
1695          OS_REG_RMW_FIELD(ah, AR_PHY_CCK_TX_CTRL, AR_PHY_CCK_TX_CTRL_TX_DAC_SCALE_CCK, pModal->miscBits);
1696 
1697         if (AR_SREV_MERLIN_20(ah) && EEP_MINOR(ah) >= AR5416_EEP_MINOR_VER_20) {
1698                 if (IEEE80211_IS_CHAN_2GHZ(chan))
1699                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE,
1700 			    eep->baseEepHeader.dacLpMode);
1701                 else if (eep->baseEepHeader.dacHiPwrMode_5G)
1702                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE, 0);
1703                 else
1704                         OS_A_REG_RMW_FIELD(ah, AR_AN_TOP1, AR_AN_TOP1_DACIPMODE,
1705 			    eep->baseEepHeader.dacLpMode);
1706 
1707 		OS_DELAY(100);
1708 
1709                 OS_REG_RMW_FIELD(ah, AR_PHY_FRAME_CTL, AR_PHY_FRAME_CTL_TX_CLIP,
1710 		    pModal->miscBits >> 2);
1711                 OS_REG_RMW_FIELD(ah, AR_PHY_TX_PWRCTRL9, AR_PHY_TX_DESIRED_SCALE_CCK,
1712 		    eep->baseEepHeader.desiredScaleCCK);
1713         }
1714 
1715     return (AH_TRUE);
1716 }
1717 
1718 /*
1719  * Helper functions common for AP/CB/XB
1720  */
1721 
1722 /*
1723  * Set the target power array "ratesArray" from the
1724  * given set of target powers.
1725  *
1726  * This is used by the various chipset/EEPROM TX power
1727  * setup routines.
1728  */
1729 void
1730 ar5416SetRatesArrayFromTargetPower(struct ath_hal *ah,
1731     const struct ieee80211_channel *chan,
1732     int16_t *ratesArray,
1733     const CAL_TARGET_POWER_LEG *targetPowerCck,
1734     const CAL_TARGET_POWER_LEG *targetPowerCckExt,
1735     const CAL_TARGET_POWER_LEG *targetPowerOfdm,
1736     const CAL_TARGET_POWER_LEG *targetPowerOfdmExt,
1737     const CAL_TARGET_POWER_HT *targetPowerHt20,
1738     const CAL_TARGET_POWER_HT *targetPowerHt40)
1739 {
1740 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1741 	int i;
1742 
1743 	/* Blank the rates array, to be consistent */
1744 	for (i = 0; i < Ar5416RateSize; i++)
1745 		ratesArray[i] = 0;
1746 
1747 	/* Set rates Array from collected data */
1748 	ratesArray[rate6mb] = ratesArray[rate9mb] = ratesArray[rate12mb] =
1749 	ratesArray[rate18mb] = ratesArray[rate24mb] =
1750 	    targetPowerOfdm->tPow2x[0];
1751 	ratesArray[rate36mb] = targetPowerOfdm->tPow2x[1];
1752 	ratesArray[rate48mb] = targetPowerOfdm->tPow2x[2];
1753 	ratesArray[rate54mb] = targetPowerOfdm->tPow2x[3];
1754 	ratesArray[rateXr] = targetPowerOfdm->tPow2x[0];
1755 
1756 	for (i = 0; i < N(targetPowerHt20->tPow2x); i++) {
1757 		ratesArray[rateHt20_0 + i] = targetPowerHt20->tPow2x[i];
1758 	}
1759 
1760 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1761 		ratesArray[rate1l]  = targetPowerCck->tPow2x[0];
1762 		ratesArray[rate2s] = ratesArray[rate2l]  = targetPowerCck->tPow2x[1];
1763 		ratesArray[rate5_5s] = ratesArray[rate5_5l] = targetPowerCck->tPow2x[2];
1764 		ratesArray[rate11s] = ratesArray[rate11l] = targetPowerCck->tPow2x[3];
1765 	}
1766 	if (IEEE80211_IS_CHAN_HT40(chan)) {
1767 		for (i = 0; i < N(targetPowerHt40->tPow2x); i++) {
1768 			ratesArray[rateHt40_0 + i] = targetPowerHt40->tPow2x[i];
1769 		}
1770 		ratesArray[rateDupOfdm] = targetPowerHt40->tPow2x[0];
1771 		ratesArray[rateDupCck]  = targetPowerHt40->tPow2x[0];
1772 		ratesArray[rateExtOfdm] = targetPowerOfdmExt->tPow2x[0];
1773 		if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1774 			ratesArray[rateExtCck]  = targetPowerCckExt->tPow2x[0];
1775 		}
1776 	}
1777 #undef	N
1778 }
1779 
1780 /*
1781  * ar5416SetPowerPerRateTable
1782  *
1783  * Sets the transmit power in the baseband for the given
1784  * operating channel and mode.
1785  */
1786 static HAL_BOOL
1787 ar5416SetPowerPerRateTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
1788                            const struct ieee80211_channel *chan,
1789                            int16_t *ratesArray, uint16_t cfgCtl,
1790                            uint16_t AntennaReduction,
1791                            uint16_t twiceMaxRegulatoryPower,
1792                            uint16_t powerLimit)
1793 {
1794 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1795 /* Local defines to distinguish between extension and control CTL's */
1796 #define EXT_ADDITIVE (0x8000)
1797 #define CTL_11A_EXT (CTL_11A | EXT_ADDITIVE)
1798 #define CTL_11G_EXT (CTL_11G | EXT_ADDITIVE)
1799 #define CTL_11B_EXT (CTL_11B | EXT_ADDITIVE)
1800 
1801 	uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
1802 	int i;
1803 	int16_t  twiceLargestAntenna;
1804 	CAL_CTL_DATA *rep;
1805 	CAL_TARGET_POWER_LEG targetPowerOfdm, targetPowerCck = {0, {0, 0, 0, 0}};
1806 	CAL_TARGET_POWER_LEG targetPowerOfdmExt = {0, {0, 0, 0, 0}}, targetPowerCckExt = {0, {0, 0, 0, 0}};
1807 	CAL_TARGET_POWER_HT  targetPowerHt20, targetPowerHt40 = {0, {0, 0, 0, 0}};
1808 	int16_t scaledPower, minCtlPower;
1809 
1810 #define SUB_NUM_CTL_MODES_AT_5G_40 2   /* excluding HT40, EXT-OFDM */
1811 #define SUB_NUM_CTL_MODES_AT_2G_40 3   /* excluding HT40, EXT-OFDM, EXT-CCK */
1812 	static const uint16_t ctlModesFor11a[] = {
1813 	   CTL_11A, CTL_5GHT20, CTL_11A_EXT, CTL_5GHT40
1814 	};
1815 	static const uint16_t ctlModesFor11g[] = {
1816 	   CTL_11B, CTL_11G, CTL_2GHT20, CTL_11B_EXT, CTL_11G_EXT, CTL_2GHT40
1817 	};
1818 	const uint16_t *pCtlMode;
1819 	uint16_t numCtlModes, ctlMode, freq;
1820 	CHAN_CENTERS centers;
1821 
1822 	ar5416GetChannelCenters(ah,  chan, &centers);
1823 
1824 	/* Compute TxPower reduction due to Antenna Gain */
1825 
1826 	twiceLargestAntenna = AH_MAX(AH_MAX(
1827 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0],
1828 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]),
1829 	    pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1830 #if 0
1831 	/* Turn it back on if we need to calculate per chain antenna gain reduction */
1832 	/* Use only if the expected gain > 6dbi */
1833 	/* Chain 0 is always used */
1834 	twiceLargestAntenna = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[0];
1835 
1836 	/* Look at antenna gains of Chains 1 and 2 if the TX mask is set */
1837 	if (ahp->ah_tx_chainmask & 0x2)
1838 		twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1839 			pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[1]);
1840 
1841 	if (ahp->ah_tx_chainmask & 0x4)
1842 		twiceLargestAntenna = AH_MAX(twiceLargestAntenna,
1843 			pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].antennaGainCh[2]);
1844 #endif
1845 	twiceLargestAntenna = (int16_t)AH_MIN((AntennaReduction) - twiceLargestAntenna, 0);
1846 
1847 	/* XXX setup for 5212 use (really used?) */
1848 	ath_hal_eepromSet(ah,
1849 	    IEEE80211_IS_CHAN_2GHZ(chan) ? AR_EEP_ANTGAINMAX_2 : AR_EEP_ANTGAINMAX_5,
1850 	    twiceLargestAntenna);
1851 
1852 	/*
1853 	 * scaledPower is the minimum of the user input power level and
1854 	 * the regulatory allowed power level
1855 	 */
1856 	scaledPower = AH_MIN(powerLimit, twiceMaxRegulatoryPower + twiceLargestAntenna);
1857 
1858 	/* Reduce scaled Power by number of chains active to get to per chain tx power level */
1859 	/* TODO: better value than these? */
1860 	switch (owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask)) {
1861 	case 1:
1862 		break;
1863 	case 2:
1864 		scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor2Chain;
1865 		break;
1866 	case 3:
1867 		scaledPower -= pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pwrDecreaseFor3Chain;
1868 		break;
1869 	default:
1870 		return AH_FALSE; /* Unsupported number of chains */
1871 	}
1872 
1873 	scaledPower = AH_MAX(0, scaledPower);
1874 
1875 	/* Get target powers from EEPROM - our baseline for TX Power */
1876 	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1877 		/* Setup for CTL modes */
1878 		numCtlModes = N(ctlModesFor11g) - SUB_NUM_CTL_MODES_AT_2G_40; /* CTL_11B, CTL_11G, CTL_2GHT20 */
1879 		pCtlMode = ctlModesFor11g;
1880 
1881 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1882 				AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCck, 4, AH_FALSE);
1883 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1884 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1885 		ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT20,
1886 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1887 
1888 		if (IEEE80211_IS_CHAN_HT40(chan)) {
1889 			numCtlModes = N(ctlModesFor11g);    /* All 2G CTL's */
1890 
1891 			ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower2GHT40,
1892 				AR5416_NUM_2G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1893 			/* Get target powers for extension channels */
1894 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPowerCck,
1895 				AR5416_NUM_2G_CCK_TARGET_POWERS, &targetPowerCckExt, 4, AH_TRUE);
1896 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower2G,
1897 				AR5416_NUM_2G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1898 		}
1899 	} else {
1900 		/* Setup for CTL modes */
1901 		numCtlModes = N(ctlModesFor11a) - SUB_NUM_CTL_MODES_AT_5G_40; /* CTL_11A, CTL_5GHT20 */
1902 		pCtlMode = ctlModesFor11a;
1903 
1904 		ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1905 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdm, 4, AH_FALSE);
1906 		ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT20,
1907 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerHt20, 8, AH_FALSE);
1908 
1909 		if (IEEE80211_IS_CHAN_HT40(chan)) {
1910 			numCtlModes = N(ctlModesFor11a); /* All 5G CTL's */
1911 
1912 			ar5416GetTargetPowers(ah,  chan, pEepData->calTargetPower5GHT40,
1913 				AR5416_NUM_5G_40_TARGET_POWERS, &targetPowerHt40, 8, AH_TRUE);
1914 			ar5416GetTargetPowersLeg(ah,  chan, pEepData->calTargetPower5G,
1915 				AR5416_NUM_5G_20_TARGET_POWERS, &targetPowerOfdmExt, 4, AH_TRUE);
1916 		}
1917 	}
1918 
1919 	/*
1920 	 * For MIMO, need to apply regulatory caps individually across dynamically
1921 	 * running modes: CCK, OFDM, HT20, HT40
1922 	 *
1923 	 * The outer loop walks through each possible applicable runtime mode.
1924 	 * The inner loop walks through each ctlIndex entry in EEPROM.
1925 	 * The ctl value is encoded as [7:4] == test group, [3:0] == test mode.
1926 	 *
1927 	 */
1928 	for (ctlMode = 0; ctlMode < numCtlModes; ctlMode++) {
1929 		HAL_BOOL isHt40CtlMode = (pCtlMode[ctlMode] == CTL_5GHT40) ||
1930 		    (pCtlMode[ctlMode] == CTL_2GHT40);
1931 		if (isHt40CtlMode) {
1932 			freq = centers.ctl_center;
1933 		} else if (pCtlMode[ctlMode] & EXT_ADDITIVE) {
1934 			freq = centers.ext_center;
1935 		} else {
1936 			freq = centers.ctl_center;
1937 		}
1938 
1939 		/* walk through each CTL index stored in EEPROM */
1940 		for (i = 0; (i < AR5416_NUM_CTLS) && pEepData->ctlIndex[i]; i++) {
1941 			uint16_t twiceMinEdgePower;
1942 
1943 			/* compare test group from regulatory channel list with test mode from pCtlMode list */
1944 			if ((((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) == pEepData->ctlIndex[i]) ||
1945 				(((cfgCtl & ~CTL_MODE_M) | (pCtlMode[ctlMode] & CTL_MODE_M)) ==
1946 				 ((pEepData->ctlIndex[i] & CTL_MODE_M) | SD_NO_CTL))) {
1947 				rep = &(pEepData->ctlData[i]);
1948 				twiceMinEdgePower = ar5416GetMaxEdgePower(freq,
1949 							rep->ctlEdges[owl_get_ntxchains(AH5416(ah)->ah_tx_chainmask) - 1],
1950 							IEEE80211_IS_CHAN_2GHZ(chan));
1951 				if ((cfgCtl & ~CTL_MODE_M) == SD_NO_CTL) {
1952 					/* Find the minimum of all CTL edge powers that apply to this channel */
1953 					twiceMaxEdgePower = AH_MIN(twiceMaxEdgePower, twiceMinEdgePower);
1954 				} else {
1955 					/* specific */
1956 					twiceMaxEdgePower = twiceMinEdgePower;
1957 					break;
1958 				}
1959 			}
1960 		}
1961 		minCtlPower = (uint8_t)AH_MIN(twiceMaxEdgePower, scaledPower);
1962 		/* Apply ctl mode to correct target power set */
1963 		switch(pCtlMode[ctlMode]) {
1964 		case CTL_11B:
1965 			for (i = 0; i < N(targetPowerCck.tPow2x); i++) {
1966 				targetPowerCck.tPow2x[i] = (uint8_t)AH_MIN(targetPowerCck.tPow2x[i], minCtlPower);
1967 			}
1968 			break;
1969 		case CTL_11A:
1970 		case CTL_11G:
1971 			for (i = 0; i < N(targetPowerOfdm.tPow2x); i++) {
1972 				targetPowerOfdm.tPow2x[i] = (uint8_t)AH_MIN(targetPowerOfdm.tPow2x[i], minCtlPower);
1973 			}
1974 			break;
1975 		case CTL_5GHT20:
1976 		case CTL_2GHT20:
1977 			for (i = 0; i < N(targetPowerHt20.tPow2x); i++) {
1978 				targetPowerHt20.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt20.tPow2x[i], minCtlPower);
1979 			}
1980 			break;
1981 		case CTL_11B_EXT:
1982 			targetPowerCckExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerCckExt.tPow2x[0], minCtlPower);
1983 			break;
1984 		case CTL_11A_EXT:
1985 		case CTL_11G_EXT:
1986 			targetPowerOfdmExt.tPow2x[0] = (uint8_t)AH_MIN(targetPowerOfdmExt.tPow2x[0], minCtlPower);
1987 			break;
1988 		case CTL_5GHT40:
1989 		case CTL_2GHT40:
1990 			for (i = 0; i < N(targetPowerHt40.tPow2x); i++) {
1991 				targetPowerHt40.tPow2x[i] = (uint8_t)AH_MIN(targetPowerHt40.tPow2x[i], minCtlPower);
1992 			}
1993 			break;
1994 		default:
1995 			return AH_FALSE;
1996 			break;
1997 		}
1998 	} /* end ctl mode checking */
1999 
2000 	/* Set rates Array from collected data */
2001 	ar5416SetRatesArrayFromTargetPower(ah, chan, ratesArray,
2002 	    &targetPowerCck,
2003 	    &targetPowerCckExt,
2004 	    &targetPowerOfdm,
2005 	    &targetPowerOfdmExt,
2006 	    &targetPowerHt20,
2007 	    &targetPowerHt40);
2008 	return AH_TRUE;
2009 #undef EXT_ADDITIVE
2010 #undef CTL_11A_EXT
2011 #undef CTL_11G_EXT
2012 #undef CTL_11B_EXT
2013 #undef SUB_NUM_CTL_MODES_AT_5G_40
2014 #undef SUB_NUM_CTL_MODES_AT_2G_40
2015 #undef N
2016 }
2017 
2018 /**************************************************************************
2019  * fbin2freq
2020  *
2021  * Get channel value from binary representation held in eeprom
2022  * RETURNS: the frequency in MHz
2023  */
2024 static uint16_t
2025 fbin2freq(uint8_t fbin, HAL_BOOL is2GHz)
2026 {
2027     /*
2028      * Reserved value 0xFF provides an empty definition both as
2029      * an fbin and as a frequency - do not convert
2030      */
2031     if (fbin == AR5416_BCHAN_UNUSED) {
2032         return fbin;
2033     }
2034 
2035     return (uint16_t)((is2GHz) ? (2300 + fbin) : (4800 + 5 * fbin));
2036 }
2037 
2038 /*
2039  * ar5416GetMaxEdgePower
2040  *
2041  * Find the maximum conformance test limit for the given channel and CTL info
2042  */
2043 uint16_t
2044 ar5416GetMaxEdgePower(uint16_t freq, CAL_CTL_EDGES *pRdEdgesPower, HAL_BOOL is2GHz)
2045 {
2046     uint16_t twiceMaxEdgePower = AR5416_MAX_RATE_POWER;
2047     int      i;
2048 
2049     /* Get the edge power */
2050     for (i = 0; (i < AR5416_NUM_BAND_EDGES) && (pRdEdgesPower[i].bChannel != AR5416_BCHAN_UNUSED) ; i++) {
2051         /*
2052          * If there's an exact channel match or an inband flag set
2053          * on the lower channel use the given rdEdgePower
2054          */
2055         if (freq == fbin2freq(pRdEdgesPower[i].bChannel, is2GHz)) {
2056             twiceMaxEdgePower = MS(pRdEdgesPower[i].tPowerFlag, CAL_CTL_EDGES_POWER);
2057             break;
2058         } else if ((i > 0) && (freq < fbin2freq(pRdEdgesPower[i].bChannel, is2GHz))) {
2059             if (fbin2freq(pRdEdgesPower[i - 1].bChannel, is2GHz) < freq && (pRdEdgesPower[i - 1].tPowerFlag & CAL_CTL_EDGES_FLAG) != 0) {
2060                 twiceMaxEdgePower = MS(pRdEdgesPower[i - 1].tPowerFlag, CAL_CTL_EDGES_POWER);
2061             }
2062             /* Leave loop - no more affecting edges possible in this monotonic increasing list */
2063             break;
2064         }
2065     }
2066     HALASSERT(twiceMaxEdgePower > 0);
2067     return twiceMaxEdgePower;
2068 }
2069 
2070 /**************************************************************
2071  * ar5416GetTargetPowers
2072  *
2073  * Return the rates of target power for the given target power table
2074  * channel, and number of channels
2075  */
2076 void
2077 ar5416GetTargetPowers(struct ath_hal *ah,  const struct ieee80211_channel *chan,
2078                       CAL_TARGET_POWER_HT *powInfo, uint16_t numChannels,
2079                       CAL_TARGET_POWER_HT *pNewPower, uint16_t numRates,
2080                       HAL_BOOL isHt40Target)
2081 {
2082     uint16_t clo, chi;
2083     int i;
2084     int matchIndex = -1, lowIndex = -1;
2085     uint16_t freq;
2086     CHAN_CENTERS centers;
2087 
2088     ar5416GetChannelCenters(ah,  chan, &centers);
2089     freq = isHt40Target ? centers.synth_center : centers.ctl_center;
2090 
2091     /* Copy the target powers into the temp channel list */
2092     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2093         matchIndex = 0;
2094     } else {
2095         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
2096             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2097                 matchIndex = i;
2098                 break;
2099             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
2100                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
2101             {
2102                 lowIndex = i - 1;
2103                 break;
2104             }
2105         }
2106         if ((matchIndex == -1) && (lowIndex == -1)) {
2107             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
2108             matchIndex = i - 1;
2109         }
2110     }
2111 
2112     if (matchIndex != -1) {
2113         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
2114     } else {
2115         HALASSERT(lowIndex != -1);
2116         /*
2117          * Get the lower and upper channels, target powers,
2118          * and interpolate between them.
2119          */
2120         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2121         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2122 
2123         for (i = 0; i < numRates; i++) {
2124             pNewPower->tPow2x[i] = (uint8_t)ath_ee_interpolate(freq, clo, chi,
2125                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
2126         }
2127     }
2128 }
2129 /**************************************************************
2130  * ar5416GetTargetPowersLeg
2131  *
2132  * Return the four rates of target power for the given target power table
2133  * channel, and number of channels
2134  */
2135 void
2136 ar5416GetTargetPowersLeg(struct ath_hal *ah,
2137                          const struct ieee80211_channel *chan,
2138                          CAL_TARGET_POWER_LEG *powInfo, uint16_t numChannels,
2139                          CAL_TARGET_POWER_LEG *pNewPower, uint16_t numRates,
2140 			 HAL_BOOL isExtTarget)
2141 {
2142     uint16_t clo, chi;
2143     int i;
2144     int matchIndex = -1, lowIndex = -1;
2145     uint16_t freq;
2146     CHAN_CENTERS centers;
2147 
2148     ar5416GetChannelCenters(ah,  chan, &centers);
2149     freq = (isExtTarget) ? centers.ext_center :centers.ctl_center;
2150 
2151     /* Copy the target powers into the temp channel list */
2152     if (freq <= fbin2freq(powInfo[0].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2153         matchIndex = 0;
2154     } else {
2155         for (i = 0; (i < numChannels) && (powInfo[i].bChannel != AR5416_BCHAN_UNUSED); i++) {
2156             if (freq == fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) {
2157                 matchIndex = i;
2158                 break;
2159             } else if ((freq < fbin2freq(powInfo[i].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))) &&
2160                        (freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan))))
2161             {
2162                 lowIndex = i - 1;
2163                 break;
2164             }
2165         }
2166         if ((matchIndex == -1) && (lowIndex == -1)) {
2167             HALASSERT(freq > fbin2freq(powInfo[i - 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan)));
2168             matchIndex = i - 1;
2169         }
2170     }
2171 
2172     if (matchIndex != -1) {
2173         OS_MEMCPY(pNewPower, &powInfo[matchIndex], sizeof(*pNewPower));
2174     } else {
2175         HALASSERT(lowIndex != -1);
2176         /*
2177          * Get the lower and upper channels, target powers,
2178          * and interpolate between them.
2179          */
2180         clo = fbin2freq(powInfo[lowIndex].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2181         chi = fbin2freq(powInfo[lowIndex + 1].bChannel, IEEE80211_IS_CHAN_2GHZ(chan));
2182 
2183         for (i = 0; i < numRates; i++) {
2184             pNewPower->tPow2x[i] = (uint8_t)ath_ee_interpolate(freq, clo, chi,
2185                                    powInfo[lowIndex].tPow2x[i], powInfo[lowIndex + 1].tPow2x[i]);
2186         }
2187     }
2188 }
2189 
2190 /*
2191  * Set the gain boundaries for the given radio chain.
2192  *
2193  * The gain boundaries tell the hardware at what point in the
2194  * PDADC array to "switch over" from one PD gain setting
2195  * to another. There's also a gain overlap between two
2196  * PDADC array gain curves where there's valid PD values
2197  * for 2 gain settings.
2198  *
2199  * The hardware uses the gain overlap and gain boundaries
2200  * to determine which gain curve to use for the given
2201  * target TX power.
2202  */
2203 void
2204 ar5416SetGainBoundariesClosedLoop(struct ath_hal *ah, int i,
2205     uint16_t pdGainOverlap_t2, uint16_t gainBoundaries[])
2206 {
2207 	int regChainOffset;
2208 
2209 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2210 
2211 	HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: chain %d: gainOverlap_t2: %d,"
2212 	    " gainBoundaries: %d, %d, %d, %d\n", __func__, i, pdGainOverlap_t2,
2213 	    gainBoundaries[0], gainBoundaries[1], gainBoundaries[2],
2214 	    gainBoundaries[3]);
2215 	OS_REG_WRITE(ah, AR_PHY_TPCRG5 + regChainOffset,
2216 	    SM(pdGainOverlap_t2, AR_PHY_TPCRG5_PD_GAIN_OVERLAP) |
2217 	    SM(gainBoundaries[0], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_1)  |
2218 	    SM(gainBoundaries[1], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_2)  |
2219 	    SM(gainBoundaries[2], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_3)  |
2220 	    SM(gainBoundaries[3], AR_PHY_TPCRG5_PD_GAIN_BOUNDARY_4));
2221 }
2222 
2223 /*
2224  * Get the gain values and the number of gain levels given
2225  * in xpdMask.
2226  *
2227  * The EEPROM xpdMask determines which power detector gain
2228  * levels were used during calibration. Each of these mask
2229  * bits maps to a fixed gain level in hardware.
2230  */
2231 uint16_t
2232 ar5416GetXpdGainValues(struct ath_hal *ah, uint16_t xpdMask,
2233     uint16_t xpdGainValues[])
2234 {
2235     int i;
2236     uint16_t numXpdGain = 0;
2237 
2238     for (i = 1; i <= AR5416_PD_GAINS_IN_MASK; i++) {
2239         if ((xpdMask >> (AR5416_PD_GAINS_IN_MASK - i)) & 1) {
2240             if (numXpdGain >= AR5416_NUM_PD_GAINS) {
2241                 HALASSERT(0);
2242                 break;
2243             }
2244             xpdGainValues[numXpdGain] = (uint16_t)(AR5416_PD_GAINS_IN_MASK - i);
2245             numXpdGain++;
2246         }
2247     }
2248     return numXpdGain;
2249 }
2250 
2251 /*
2252  * Write the detector gain and biases.
2253  *
2254  * There are four power detector gain levels. The xpdMask in the EEPROM
2255  * determines which power detector gain levels have TX power calibration
2256  * data associated with them. This function writes the number of
2257  * PD gain levels and their values into the hardware.
2258  *
2259  * This is valid for all TX chains - the calibration data itself however
2260  * will likely differ per-chain.
2261  */
2262 void
2263 ar5416WriteDetectorGainBiases(struct ath_hal *ah, uint16_t numXpdGain,
2264     uint16_t xpdGainValues[])
2265 {
2266     HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: numXpdGain: %d,"
2267       " xpdGainValues: %d, %d, %d\n", __func__, numXpdGain,
2268       xpdGainValues[0], xpdGainValues[1], xpdGainValues[2]);
2269 
2270     OS_REG_WRITE(ah, AR_PHY_TPCRG1, (OS_REG_READ(ah, AR_PHY_TPCRG1) &
2271     	~(AR_PHY_TPCRG1_NUM_PD_GAIN | AR_PHY_TPCRG1_PD_GAIN_1 |
2272 	AR_PHY_TPCRG1_PD_GAIN_2 | AR_PHY_TPCRG1_PD_GAIN_3)) |
2273 	SM(numXpdGain - 1, AR_PHY_TPCRG1_NUM_PD_GAIN) |
2274 	SM(xpdGainValues[0], AR_PHY_TPCRG1_PD_GAIN_1 ) |
2275 	SM(xpdGainValues[1], AR_PHY_TPCRG1_PD_GAIN_2) |
2276 	SM(xpdGainValues[2],  AR_PHY_TPCRG1_PD_GAIN_3));
2277 }
2278 
2279 /*
2280  * Write the PDADC array to the given radio chain i.
2281  *
2282  * The 32 PDADC registers are written without any care about
2283  * their contents - so if various chips treat values as "special",
2284  * this routine will not care.
2285  */
2286 void
2287 ar5416WritePdadcValues(struct ath_hal *ah, int i, uint8_t pdadcValues[])
2288 {
2289 	int regOffset, regChainOffset;
2290 	int j;
2291 	int reg32;
2292 
2293 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2294 	regOffset = AR_PHY_BASE + (672 << 2) + regChainOffset;
2295 
2296 	for (j = 0; j < 32; j++) {
2297 		reg32 = ((pdadcValues[4*j + 0] & 0xFF) << 0)  |
2298 		    ((pdadcValues[4*j + 1] & 0xFF) << 8)  |
2299 		    ((pdadcValues[4*j + 2] & 0xFF) << 16) |
2300 		    ((pdadcValues[4*j + 3] & 0xFF) << 24) ;
2301 		OS_REG_WRITE(ah, regOffset, reg32);
2302 		HALDEBUG(ah, HAL_DEBUG_EEPROM, "PDADC: Chain %d |"
2303 		    " PDADC %3d Value %3d | PDADC %3d Value %3d | PDADC %3d"
2304 		    " Value %3d | PDADC %3d Value %3d |\n",
2305 		    i,
2306 		    4*j, pdadcValues[4*j],
2307 		    4*j+1, pdadcValues[4*j + 1],
2308 		    4*j+2, pdadcValues[4*j + 2],
2309 		    4*j+3, pdadcValues[4*j + 3]);
2310 		regOffset += 4;
2311 	}
2312 }
2313 
2314 /**************************************************************
2315  * ar5416SetPowerCalTable
2316  *
2317  * Pull the PDADC piers from cal data and interpolate them across the given
2318  * points as well as from the nearest pier(s) to get a power detector
2319  * linear voltage to power level table.
2320  */
2321 HAL_BOOL
2322 ar5416SetPowerCalTable(struct ath_hal *ah, struct ar5416eeprom *pEepData,
2323 	const struct ieee80211_channel *chan, int16_t *pTxPowerIndexOffset)
2324 {
2325     CAL_DATA_PER_FREQ *pRawDataset;
2326     uint8_t  *pCalBChans = AH_NULL;
2327     uint16_t pdGainOverlap_t2;
2328     static uint8_t  pdadcValues[AR5416_NUM_PDADC_VALUES];
2329     uint16_t gainBoundaries[AR5416_PD_GAINS_IN_MASK];
2330     uint16_t numPiers, i;
2331     int16_t  tMinCalPower;
2332     uint16_t numXpdGain, xpdMask;
2333     uint16_t xpdGainValues[AR5416_NUM_PD_GAINS];
2334     uint32_t regChainOffset;
2335 
2336     OS_MEMZERO(xpdGainValues, sizeof(xpdGainValues));
2337 
2338     xpdMask = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].xpdGain;
2339 
2340     if (IS_EEP_MINOR_V2(ah)) {
2341         pdGainOverlap_t2 = pEepData->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)].pdGainOverlap;
2342     } else {
2343     	pdGainOverlap_t2 = (uint16_t)(MS(OS_REG_READ(ah, AR_PHY_TPCRG5), AR_PHY_TPCRG5_PD_GAIN_OVERLAP));
2344     }
2345 
2346     if (IEEE80211_IS_CHAN_2GHZ(chan)) {
2347         pCalBChans = pEepData->calFreqPier2G;
2348         numPiers = AR5416_NUM_2G_CAL_PIERS;
2349     } else {
2350         pCalBChans = pEepData->calFreqPier5G;
2351         numPiers = AR5416_NUM_5G_CAL_PIERS;
2352     }
2353 
2354     /* Calculate the value of xpdgains from the xpdGain Mask */
2355     numXpdGain = ar5416GetXpdGainValues(ah, xpdMask, xpdGainValues);
2356 
2357     /* Write the detector gain biases and their number */
2358     ar5416WriteDetectorGainBiases(ah, numXpdGain, xpdGainValues);
2359 
2360     for (i = 0; i < AR5416_MAX_CHAINS; i++) {
2361 	regChainOffset = ar5416GetRegChainOffset(ah, i);
2362 
2363         if (pEepData->baseEepHeader.txMask & (1 << i)) {
2364             if (IEEE80211_IS_CHAN_2GHZ(chan)) {
2365                 pRawDataset = pEepData->calPierData2G[i];
2366             } else {
2367                 pRawDataset = pEepData->calPierData5G[i];
2368             }
2369 
2370             /* Fetch the gain boundaries and the PDADC values */
2371 	    ar5416GetGainBoundariesAndPdadcs(ah,  chan, pRawDataset,
2372                                              pCalBChans, numPiers,
2373                                              pdGainOverlap_t2,
2374                                              &tMinCalPower, gainBoundaries,
2375                                              pdadcValues, numXpdGain);
2376 
2377             if ((i == 0) || AR_SREV_5416_V20_OR_LATER(ah)) {
2378 		ar5416SetGainBoundariesClosedLoop(ah, i, pdGainOverlap_t2,
2379 		  gainBoundaries);
2380             }
2381 
2382             /* Write the power values into the baseband power table */
2383 	    ar5416WritePdadcValues(ah, i, pdadcValues);
2384         }
2385     }
2386     *pTxPowerIndexOffset = 0;
2387 
2388     return AH_TRUE;
2389 }
2390 
2391 /**************************************************************
2392  * ar5416GetGainBoundariesAndPdadcs
2393  *
2394  * Uses the data points read from EEPROM to reconstruct the pdadc power table
2395  * Called by ar5416SetPowerCalTable only.
2396  */
2397 void
2398 ar5416GetGainBoundariesAndPdadcs(struct ath_hal *ah,
2399                                  const struct ieee80211_channel *chan,
2400 				 CAL_DATA_PER_FREQ *pRawDataSet,
2401                                  uint8_t * bChans,  uint16_t availPiers,
2402                                  uint16_t tPdGainOverlap, int16_t *pMinCalPower, uint16_t * pPdGainBoundaries,
2403                                  uint8_t * pPDADCValues, uint16_t numXpdGains)
2404 {
2405 
2406     int       i, j, k;
2407     int16_t   ss;         /* potentially -ve index for taking care of pdGainOverlap */
2408     uint16_t  idxL, idxR, numPiers; /* Pier indexes */
2409 
2410     /* filled out Vpd table for all pdGains (chanL) */
2411     static uint8_t   vpdTableL[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2412 
2413     /* filled out Vpd table for all pdGains (chanR) */
2414     static uint8_t   vpdTableR[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2415 
2416     /* filled out Vpd table for all pdGains (interpolated) */
2417     static uint8_t   vpdTableI[AR5416_NUM_PD_GAINS][AR5416_MAX_PWR_RANGE_IN_HALF_DB];
2418 
2419     uint8_t   *pVpdL, *pVpdR, *pPwrL, *pPwrR;
2420     uint8_t   minPwrT4[AR5416_NUM_PD_GAINS];
2421     uint8_t   maxPwrT4[AR5416_NUM_PD_GAINS];
2422     int16_t   vpdStep;
2423     int16_t   tmpVal;
2424     uint16_t  sizeCurrVpdTable, maxIndex, tgtIndex;
2425     HAL_BOOL    match;
2426     int16_t  minDelta = 0;
2427     CHAN_CENTERS centers;
2428 
2429     ar5416GetChannelCenters(ah, chan, &centers);
2430 
2431     /* Trim numPiers for the number of populated channel Piers */
2432     for (numPiers = 0; numPiers < availPiers; numPiers++) {
2433         if (bChans[numPiers] == AR5416_BCHAN_UNUSED) {
2434             break;
2435         }
2436     }
2437 
2438     /* Find pier indexes around the current channel */
2439     match = ath_ee_getLowerUpperIndex((uint8_t)FREQ2FBIN(centers.synth_center,
2440 	IEEE80211_IS_CHAN_2GHZ(chan)), bChans, numPiers, &idxL, &idxR);
2441 
2442     if (match) {
2443         /* Directly fill both vpd tables from the matching index */
2444         for (i = 0; i < numXpdGains; i++) {
2445             minPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][0];
2446             maxPwrT4[i] = pRawDataSet[idxL].pwrPdg[i][4];
2447             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pRawDataSet[idxL].pwrPdg[i],
2448                                pRawDataSet[idxL].vpdPdg[i], AR5416_PD_GAIN_ICEPTS, vpdTableI[i]);
2449         }
2450     } else {
2451         for (i = 0; i < numXpdGains; i++) {
2452             pVpdL = pRawDataSet[idxL].vpdPdg[i];
2453             pPwrL = pRawDataSet[idxL].pwrPdg[i];
2454             pVpdR = pRawDataSet[idxR].vpdPdg[i];
2455             pPwrR = pRawDataSet[idxR].pwrPdg[i];
2456 
2457             /* Start Vpd interpolation from the max of the minimum powers */
2458             minPwrT4[i] = AH_MAX(pPwrL[0], pPwrR[0]);
2459 
2460             /* End Vpd interpolation from the min of the max powers */
2461             maxPwrT4[i] = AH_MIN(pPwrL[AR5416_PD_GAIN_ICEPTS - 1], pPwrR[AR5416_PD_GAIN_ICEPTS - 1]);
2462             HALASSERT(maxPwrT4[i] > minPwrT4[i]);
2463 
2464             /* Fill pier Vpds */
2465             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrL, pVpdL, AR5416_PD_GAIN_ICEPTS, vpdTableL[i]);
2466             ath_ee_FillVpdTable(minPwrT4[i], maxPwrT4[i], pPwrR, pVpdR, AR5416_PD_GAIN_ICEPTS, vpdTableR[i]);
2467 
2468             /* Interpolate the final vpd */
2469             for (j = 0; j <= (maxPwrT4[i] - minPwrT4[i]) / 2; j++) {
2470                 vpdTableI[i][j] = (uint8_t)(ath_ee_interpolate((uint16_t)FREQ2FBIN(centers.synth_center,
2471 		    IEEE80211_IS_CHAN_2GHZ(chan)),
2472                     bChans[idxL], bChans[idxR], vpdTableL[i][j], vpdTableR[i][j]));
2473             }
2474         }
2475     }
2476     *pMinCalPower = (int16_t)(minPwrT4[0] / 2);
2477 
2478     k = 0; /* index for the final table */
2479     for (i = 0; i < numXpdGains; i++) {
2480         if (i == (numXpdGains - 1)) {
2481             pPdGainBoundaries[i] = (uint16_t)(maxPwrT4[i] / 2);
2482         } else {
2483             pPdGainBoundaries[i] = (uint16_t)((maxPwrT4[i] + minPwrT4[i+1]) / 4);
2484         }
2485 
2486         pPdGainBoundaries[i] = (uint16_t)AH_MIN(AR5416_MAX_RATE_POWER, pPdGainBoundaries[i]);
2487 
2488 	/* NB: only applies to owl 1.0 */
2489         if ((i == 0) && !AR_SREV_5416_V20_OR_LATER(ah) ) {
2490 	    /*
2491              * fix the gain delta, but get a delta that can be applied to min to
2492              * keep the upper power values accurate, don't think max needs to
2493              * be adjusted because should not be at that area of the table?
2494 	     */
2495             minDelta = pPdGainBoundaries[0] - 23;
2496             pPdGainBoundaries[0] = 23;
2497         }
2498         else {
2499             minDelta = 0;
2500         }
2501 
2502         /* Find starting index for this pdGain */
2503         if (i == 0) {
2504             if (AR_SREV_MERLIN_10_OR_LATER(ah))
2505                 ss = (int16_t)(0 - (minPwrT4[i] / 2));
2506             else
2507                 ss = 0; /* for the first pdGain, start from index 0 */
2508         } else {
2509 	    /* need overlap entries extrapolated below. */
2510             ss = (int16_t)((pPdGainBoundaries[i-1] - (minPwrT4[i] / 2)) - tPdGainOverlap + 1 + minDelta);
2511         }
2512         vpdStep = (int16_t)(vpdTableI[i][1] - vpdTableI[i][0]);
2513         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
2514         /*
2515          *-ve ss indicates need to extrapolate data below for this pdGain
2516          */
2517         while ((ss < 0) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2518             tmpVal = (int16_t)(vpdTableI[i][0] + ss * vpdStep);
2519             pPDADCValues[k++] = (uint8_t)((tmpVal < 0) ? 0 : tmpVal);
2520             ss++;
2521         }
2522 
2523         sizeCurrVpdTable = (uint8_t)((maxPwrT4[i] - minPwrT4[i]) / 2 +1);
2524         tgtIndex = (uint8_t)(pPdGainBoundaries[i] + tPdGainOverlap - (minPwrT4[i] / 2));
2525         maxIndex = (tgtIndex < sizeCurrVpdTable) ? tgtIndex : sizeCurrVpdTable;
2526 
2527         while ((ss < maxIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2528             pPDADCValues[k++] = vpdTableI[i][ss++];
2529         }
2530 
2531         vpdStep = (int16_t)(vpdTableI[i][sizeCurrVpdTable - 1] - vpdTableI[i][sizeCurrVpdTable - 2]);
2532         vpdStep = (int16_t)((vpdStep < 1) ? 1 : vpdStep);
2533         /*
2534          * for last gain, pdGainBoundary == Pmax_t2, so will
2535          * have to extrapolate
2536          */
2537         if (tgtIndex >= maxIndex) {  /* need to extrapolate above */
2538             while ((ss <= tgtIndex) && (k < (AR5416_NUM_PDADC_VALUES - 1))) {
2539                 tmpVal = (int16_t)((vpdTableI[i][sizeCurrVpdTable - 1] +
2540                           (ss - maxIndex +1) * vpdStep));
2541                 pPDADCValues[k++] = (uint8_t)((tmpVal > 255) ? 255 : tmpVal);
2542                 ss++;
2543             }
2544         }               /* extrapolated above */
2545     }                   /* for all pdGainUsed */
2546 
2547     /* Fill out pdGainBoundaries - only up to 2 allowed here, but hardware allows up to 4 */
2548     while (i < AR5416_PD_GAINS_IN_MASK) {
2549         pPdGainBoundaries[i] = pPdGainBoundaries[i-1];
2550         i++;
2551     }
2552 
2553     while (k < AR5416_NUM_PDADC_VALUES) {
2554         pPDADCValues[k] = pPDADCValues[k-1];
2555         k++;
2556     }
2557     return;
2558 }
2559 
2560 /*
2561  * The linux ath9k driver and (from what I've been told) the reference
2562  * Atheros driver enables the 11n PHY by default whether or not it's
2563  * configured.
2564  */
2565 static void
2566 ar5416Set11nRegs(struct ath_hal *ah, const struct ieee80211_channel *chan)
2567 {
2568 	uint32_t phymode;
2569 	uint32_t enableDacFifo = 0;
2570 	HAL_HT_MACMODE macmode;		/* MAC - 20/40 mode */
2571 
2572 	if (AR_SREV_KITE_10_OR_LATER(ah))
2573 		enableDacFifo = (OS_REG_READ(ah, AR_PHY_TURBO) & AR_PHY_FC_ENABLE_DAC_FIFO);
2574 
2575 	/* Enable 11n HT, 20 MHz */
2576 	phymode = AR_PHY_FC_HT_EN | AR_PHY_FC_SHORT_GI_40
2577 		| AR_PHY_FC_SINGLE_HT_LTF1 | AR_PHY_FC_WALSH | enableDacFifo;
2578 
2579 	/* Configure baseband for dynamic 20/40 operation */
2580 	if (IEEE80211_IS_CHAN_HT40(chan)) {
2581 		phymode |= AR_PHY_FC_DYN2040_EN;
2582 
2583 		/* Configure control (primary) channel at +-10MHz */
2584 		if (IEEE80211_IS_CHAN_HT40U(chan))
2585 			phymode |= AR_PHY_FC_DYN2040_PRI_CH;
2586 #if 0
2587 		/* Configure 20/25 spacing */
2588 		if (ht->ht_extprotspacing == HAL_HT_EXTPROTSPACING_25)
2589 			phymode |= AR_PHY_FC_DYN2040_EXT_CH;
2590 #endif
2591 		macmode = HAL_HT_MACMODE_2040;
2592 	} else
2593 		macmode = HAL_HT_MACMODE_20;
2594 	OS_REG_WRITE(ah, AR_PHY_TURBO, phymode);
2595 
2596 	/* Configure MAC for 20/40 operation */
2597 	ar5416Set11nMac2040(ah, macmode);
2598 
2599 	/* global transmit timeout (25 TUs default)*/
2600 	/* XXX - put this elsewhere??? */
2601 	OS_REG_WRITE(ah, AR_GTXTO, 25 << AR_GTXTO_TIMEOUT_LIMIT_S) ;
2602 
2603 	/* carrier sense timeout */
2604 	OS_REG_SET_BIT(ah, AR_GTTM, AR_GTTM_CST_USEC);
2605 	OS_REG_WRITE(ah, AR_CST, 0xF << AR_CST_TIMEOUT_LIMIT_S);
2606 }
2607 
2608 void
2609 ar5416GetChannelCenters(struct ath_hal *ah,
2610 	const struct ieee80211_channel *chan, CHAN_CENTERS *centers)
2611 {
2612 	uint16_t freq = ath_hal_gethwchannel(ah, chan);
2613 
2614 	centers->ctl_center = freq;
2615 	centers->synth_center = freq;
2616 	/*
2617 	 * In 20/40 phy mode, the center frequency is
2618 	 * "between" the control and extension channels.
2619 	 */
2620 	if (IEEE80211_IS_CHAN_HT40U(chan)) {
2621 		centers->synth_center += HT40_CHANNEL_CENTER_SHIFT;
2622 		centers->ext_center =
2623 		    centers->synth_center + HT40_CHANNEL_CENTER_SHIFT;
2624 	} else if (IEEE80211_IS_CHAN_HT40D(chan)) {
2625 		centers->synth_center -= HT40_CHANNEL_CENTER_SHIFT;
2626 		centers->ext_center =
2627 		    centers->synth_center - HT40_CHANNEL_CENTER_SHIFT;
2628 	} else {
2629 		centers->ext_center = freq;
2630 	}
2631 }
2632 
2633 /*
2634  * Override the INI vals being programmed.
2635  */
2636 static void
2637 ar5416OverrideIni(struct ath_hal *ah, const struct ieee80211_channel *chan)
2638 {
2639 	uint32_t val;
2640 
2641 	/*
2642 	 * Set the RX_ABORT and RX_DIS and clear if off only after
2643 	 * RXE is set for MAC. This prevents frames with corrupted
2644 	 * descriptor status.
2645 	 */
2646 	OS_REG_SET_BIT(ah, AR_DIAG_SW, (AR_DIAG_RX_DIS | AR_DIAG_RX_ABORT));
2647 
2648 	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
2649 		val = OS_REG_READ(ah, AR_PCU_MISC_MODE2);
2650 		val &= (~AR_PCU_MISC_MODE2_ADHOC_MCAST_KEYID_ENABLE);
2651 		if (!AR_SREV_9271(ah))
2652 			val &= ~AR_PCU_MISC_MODE2_HWWAR1;
2653 
2654 		if (AR_SREV_KIWI_10_OR_LATER(ah))
2655 			val = val & (~AR_PCU_MISC_MODE2_HWWAR2);
2656 
2657 		OS_REG_WRITE(ah, AR_PCU_MISC_MODE2, val);
2658 	}
2659 
2660 	/*
2661 	 * Disable RIFS search on some chips to avoid baseband
2662 	 * hang issues.
2663 	 */
2664 	if (AR_SREV_HOWL(ah) || AR_SREV_SOWL(ah))
2665 		(void) ar5416SetRifsDelay(ah, chan, AH_FALSE);
2666 
2667         if (!AR_SREV_5416_V20_OR_LATER(ah) || AR_SREV_MERLIN(ah))
2668 		return;
2669 
2670 	/*
2671 	 * Disable BB clock gating
2672 	 * Necessary to avoid issues on AR5416 2.0
2673 	 */
2674 	OS_REG_WRITE(ah, 0x9800 + (651 << 2), 0x11);
2675 }
2676 
2677 struct ini {
2678 	uint32_t        *data;          /* NB: !const */
2679 	int             rows, cols;
2680 };
2681 
2682 /*
2683  * Override XPA bias level based on operating frequency.
2684  * This is a v14 EEPROM specific thing for the AR9160.
2685  */
2686 void
2687 ar5416EepromSetAddac(struct ath_hal *ah, const struct ieee80211_channel *chan)
2688 {
2689 #define	XPA_LVL_FREQ(cnt)	(pModal->xpaBiasLvlFreq[cnt])
2690 	MODAL_EEP_HEADER	*pModal;
2691 	HAL_EEPROM_v14 *ee = AH_PRIVATE(ah)->ah_eeprom;
2692 	struct ar5416eeprom	*eep = &ee->ee_base;
2693 	uint8_t biaslevel;
2694 
2695 	if (! AR_SREV_SOWL(ah))
2696 		return;
2697 
2698         if (EEP_MINOR(ah) < AR5416_EEP_MINOR_VER_7)
2699                 return;
2700 
2701 	pModal = &(eep->modalHeader[IEEE80211_IS_CHAN_2GHZ(chan)]);
2702 
2703 	if (pModal->xpaBiasLvl != 0xff)
2704 		biaslevel = pModal->xpaBiasLvl;
2705 	else {
2706 		uint16_t resetFreqBin, freqBin, freqCount = 0;
2707 		CHAN_CENTERS centers;
2708 
2709 		ar5416GetChannelCenters(ah, chan, &centers);
2710 
2711 		resetFreqBin = FREQ2FBIN(centers.synth_center, IEEE80211_IS_CHAN_2GHZ(chan));
2712 		freqBin = XPA_LVL_FREQ(0) & 0xff;
2713 		biaslevel = (uint8_t) (XPA_LVL_FREQ(0) >> 14);
2714 
2715 		freqCount++;
2716 
2717 		while (freqCount < 3) {
2718 			if (XPA_LVL_FREQ(freqCount) == 0x0)
2719 			break;
2720 
2721 			freqBin = XPA_LVL_FREQ(freqCount) & 0xff;
2722 			if (resetFreqBin >= freqBin)
2723 				biaslevel = (uint8_t)(XPA_LVL_FREQ(freqCount) >> 14);
2724 			else
2725 				break;
2726 			freqCount++;
2727 		}
2728 	}
2729 
2730 	HALDEBUG(ah, HAL_DEBUG_EEPROM, "%s: overriding XPA bias level = %d\n",
2731 	    __func__, biaslevel);
2732 
2733 	/*
2734 	 * This is a dirty workaround for the const initval data,
2735 	 * which will upset multiple AR9160's on the same board.
2736 	 *
2737 	 * The HAL should likely just have a private copy of the addac
2738 	 * data per instance.
2739 	 */
2740 	if (IEEE80211_IS_CHAN_2GHZ(chan))
2741                 HAL_INI_VAL((struct ini *) &AH5416(ah)->ah_ini_addac, 7, 1) =
2742 		    (HAL_INI_VAL(&AH5416(ah)->ah_ini_addac, 7, 1) & (~0x18)) | biaslevel << 3;
2743         else
2744                 HAL_INI_VAL((struct ini *) &AH5416(ah)->ah_ini_addac, 6, 1) =
2745 		    (HAL_INI_VAL(&AH5416(ah)->ah_ini_addac, 6, 1) & (~0xc0)) | biaslevel << 6;
2746 #undef XPA_LVL_FREQ
2747 }
2748 
2749 static void
2750 ar5416MarkPhyInactive(struct ath_hal *ah)
2751 {
2752 	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_DIS);
2753 }
2754