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