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