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