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