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