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