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