ar5416_cal.c revision 221778
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_cal.c 221778 2011-05-11 13:25:43Z 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 "ar5212/ar5212.h"	/* for NF cal related declarations */
28
29#include "ar5416/ar5416.h"
30#include "ar5416/ar5416reg.h"
31#include "ar5416/ar5416phy.h"
32
33/* Owl specific stuff */
34#define NUM_NOISEFLOOR_READINGS 6       /* 3 chains * (ctl + ext) */
35
36static void ar5416StartNFCal(struct ath_hal *ah);
37static void ar5416LoadNF(struct ath_hal *ah, const struct ieee80211_channel *);
38static int16_t ar5416GetNf(struct ath_hal *, struct ieee80211_channel *);
39
40static uint16_t ar5416GetDefaultNF(struct ath_hal *ah, const struct ieee80211_channel *chan);
41static void ar5416SanitizeNF(struct ath_hal *ah, int16_t *nf);
42
43/*
44 * Determine if calibration is supported by device and channel flags
45 */
46
47/*
48 * ADC GAIN/DC offset calibration is for calibrating two ADCs that
49 * are acting as one by interleaving incoming symbols. This isn't
50 * relevant for 2.4GHz 20MHz wide modes because, as far as I can tell,
51 * the secondary ADC is never enabled. It is enabled however for
52 * 5GHz modes.
53 *
54 * It hasn't been confirmed whether doing this calibration is needed
55 * at all in the above modes and/or whether it's actually harmful.
56 * So for now, let's leave it enabled and just remember to get
57 * confirmation that it needs to be clarified.
58 *
59 * See US Patent No: US 7,541,952 B1:
60 *  " Method and Apparatus for Offset and Gain Compensation for
61 *    Analog-to-Digital Converters."
62 */
63static OS_INLINE HAL_BOOL
64ar5416IsCalSupp(struct ath_hal *ah, const struct ieee80211_channel *chan,
65	HAL_CAL_TYPE calType)
66{
67	struct ar5416PerCal *cal = &AH5416(ah)->ah_cal;
68
69	switch (calType & cal->suppCals) {
70	case IQ_MISMATCH_CAL:
71		/* Run IQ Mismatch for non-CCK only */
72		return !IEEE80211_IS_CHAN_B(chan);
73	case ADC_GAIN_CAL:
74	case ADC_DC_CAL:
75		/* Run ADC Gain Cal for either 5ghz any or 2ghz HT40 */
76		if (IEEE80211_IS_CHAN_5GHZ(chan))
77			return AH_TRUE;
78		if (IEEE80211_IS_CHAN_HT40(chan))
79			return AH_TRUE;
80		return AH_FALSE;
81	}
82	return AH_FALSE;
83}
84
85/*
86 * Setup HW to collect samples used for current cal
87 */
88static void
89ar5416SetupMeasurement(struct ath_hal *ah, HAL_CAL_LIST *currCal)
90{
91	/* Start calibration w/ 2^(INIT_IQCAL_LOG_COUNT_MAX+1) samples */
92	OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4,
93	    AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX,
94	    currCal->calData->calCountMax);
95
96	/* Select calibration to run */
97	switch (currCal->calData->calType) {
98	case IQ_MISMATCH_CAL:
99		OS_REG_WRITE(ah, AR_PHY_CALMODE, AR_PHY_CALMODE_IQ);
100		HALDEBUG(ah, HAL_DEBUG_PERCAL,
101		    "%s: start IQ Mismatch calibration\n", __func__);
102		break;
103	case ADC_GAIN_CAL:
104		OS_REG_WRITE(ah, AR_PHY_CALMODE, AR_PHY_CALMODE_ADC_GAIN);
105		HALDEBUG(ah, HAL_DEBUG_PERCAL,
106		    "%s: start ADC Gain calibration\n", __func__);
107		break;
108	case ADC_DC_CAL:
109		OS_REG_WRITE(ah, AR_PHY_CALMODE, AR_PHY_CALMODE_ADC_DC_PER);
110		HALDEBUG(ah, HAL_DEBUG_PERCAL,
111		    "%s: start ADC DC calibration\n", __func__);
112		break;
113	case ADC_DC_INIT_CAL:
114		OS_REG_WRITE(ah, AR_PHY_CALMODE, AR_PHY_CALMODE_ADC_DC_INIT);
115		HALDEBUG(ah, HAL_DEBUG_PERCAL,
116		    "%s: start Init ADC DC calibration\n", __func__);
117		break;
118	}
119	/* Kick-off cal */
120	OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4, AR_PHY_TIMING_CTRL4_DO_CAL);
121}
122
123/*
124 * Initialize shared data structures and prepare a cal to be run.
125 */
126static void
127ar5416ResetMeasurement(struct ath_hal *ah, HAL_CAL_LIST *currCal)
128{
129	struct ar5416PerCal *cal = &AH5416(ah)->ah_cal;
130
131	/* Reset data structures shared between different calibrations */
132	OS_MEMZERO(cal->caldata, sizeof(cal->caldata));
133	cal->calSamples = 0;
134
135	/* Setup HW for new calibration */
136	ar5416SetupMeasurement(ah, currCal);
137
138	/* Change SW state to RUNNING for this calibration */
139	currCal->calState = CAL_RUNNING;
140}
141
142#if 0
143/*
144 * Run non-periodic calibrations.
145 */
146static HAL_BOOL
147ar5416RunInitCals(struct ath_hal *ah, int init_cal_count)
148{
149	struct ath_hal_5416 *ahp = AH5416(ah);
150	struct ar5416PerCal *cal = &AH5416(ah)->ah_cal;
151	HAL_CHANNEL_INTERNAL ichan;	/* XXX bogus */
152	HAL_CAL_LIST *curCal = ahp->ah_cal_curr;
153	HAL_BOOL isCalDone;
154	int i;
155
156	if (curCal == AH_NULL)
157		return AH_FALSE;
158
159	ichan.calValid = 0;
160	for (i = 0; i < init_cal_count; i++) {
161		/* Reset this Cal */
162		ar5416ResetMeasurement(ah, curCal);
163		/* Poll for offset calibration complete */
164		if (!ath_hal_wait(ah, AR_PHY_TIMING_CTRL4, AR_PHY_TIMING_CTRL4_DO_CAL, 0)) {
165			HALDEBUG(ah, HAL_DEBUG_ANY,
166			    "%s: Cal %d failed to finish in 100ms.\n",
167			    __func__, curCal->calData->calType);
168			/* Re-initialize list pointers for periodic cals */
169			cal->cal_list = cal->cal_last = cal->cal_curr = AH_NULL;
170			return AH_FALSE;
171		}
172		/* Run this cal */
173		ar5416DoCalibration(ah, &ichan, ahp->ah_rxchainmask,
174		    curCal, &isCalDone);
175		if (!isCalDone)
176			HALDEBUG(ah, HAL_DEBUG_ANY,
177			    "%s: init cal %d did not complete.\n",
178			    __func__, curCal->calData->calType);
179		if (curCal->calNext != AH_NULL)
180			curCal = curCal->calNext;
181	}
182
183	/* Re-initialize list pointers for periodic cals */
184	cal->cal_list = cal->cal_last = cal->cal_curr = AH_NULL;
185	return AH_TRUE;
186}
187#endif
188
189HAL_BOOL
190ar5416InitCalHardware(struct ath_hal *ah, const struct ieee80211_channel *chan)
191{
192	if (AR_SREV_MERLIN_10_OR_LATER(ah)) {
193		/* Enable Rx Filter Cal */
194		OS_REG_CLR_BIT(ah, AR_PHY_ADC_CTL, AR_PHY_ADC_CTL_OFF_PWDADC);
195		OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL,
196		    AR_PHY_AGC_CONTROL_FLTR_CAL);
197
198		/* Clear the carrier leak cal bit */
199		OS_REG_CLR_BIT(ah, AR_PHY_CL_CAL_CTL, AR_PHY_CL_CAL_ENABLE);
200
201		/* kick off the cal */
202		OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL);
203
204		/* Poll for offset calibration complete */
205		if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0)) {
206			HALDEBUG(ah, HAL_DEBUG_ANY,
207			    "%s: offset calibration failed to complete in 1ms; "
208			    "noisy environment?\n", __func__);
209			return AH_FALSE;
210		}
211
212		/* Set the cl cal bit and rerun the cal a 2nd time */
213		/* Enable Rx Filter Cal */
214		OS_REG_CLR_BIT(ah, AR_PHY_ADC_CTL, AR_PHY_ADC_CTL_OFF_PWDADC);
215		OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL,
216		    AR_PHY_AGC_CONTROL_FLTR_CAL);
217
218		OS_REG_SET_BIT(ah, AR_PHY_CL_CAL_CTL, AR_PHY_CL_CAL_ENABLE);
219	}
220
221	/* Calibrate the AGC */
222	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL);
223
224	/* Poll for offset calibration complete */
225	if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0)) {
226		HALDEBUG(ah, HAL_DEBUG_ANY,
227		    "%s: offset calibration did not complete in 1ms; "
228		    "noisy environment?\n", __func__);
229		return AH_FALSE;
230	}
231
232	return AH_TRUE;
233}
234
235/*
236 * Initialize Calibration infrastructure.
237 */
238#define	MAX_CAL_CHECK		32
239HAL_BOOL
240ar5416InitCal(struct ath_hal *ah, const struct ieee80211_channel *chan)
241{
242	struct ar5416PerCal *cal = &AH5416(ah)->ah_cal;
243	HAL_CHANNEL_INTERNAL *ichan;
244
245	ichan = ath_hal_checkchannel(ah, chan);
246	HALASSERT(ichan != AH_NULL);
247
248	/* Do initial chipset-specific calibration */
249	if (! AH5416(ah)->ah_cal_initcal(ah, chan)) {
250		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: initial chipset calibration did "
251		    "not complete in time; noisy environment?\n", __func__);
252		return AH_FALSE;
253	}
254
255	/* If there's PA Cal, do it */
256	if (AH5416(ah)->ah_cal_pacal)
257		AH5416(ah)->ah_cal_pacal(ah, AH_TRUE);
258
259	/*
260	 * Do NF calibration after DC offset and other CALs.
261	 * Per system engineers, noise floor value can sometimes be 20 dB
262	 * higher than normal value if DC offset and noise floor cal are
263	 * triggered at the same time.
264	 */
265	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
266
267	/*
268	 * This may take a while to run; make sure subsequent
269	 * calibration routines check that this has completed
270	 * before reading the value and triggering a subsequent
271	 * calibration.
272	 */
273
274	/* Initialize list pointers */
275	cal->cal_list = cal->cal_last = cal->cal_curr = AH_NULL;
276
277	/*
278	 * Enable IQ, ADC Gain, ADC DC Offset Cals
279	 */
280	if (AR_SREV_SOWL_10_OR_LATER(ah)) {
281		/* Setup all non-periodic, init time only calibrations */
282		/* XXX: Init DC Offset not working yet */
283#if 0
284		if (ar5416IsCalSupp(ah, chan, ADC_DC_INIT_CAL)) {
285			INIT_CAL(&cal->adcDcCalInitData);
286			INSERT_CAL(cal, &cal->adcDcCalInitData);
287		}
288		/* Initialize current pointer to first element in list */
289		cal->cal_curr = cal->cal_list;
290
291		if (cal->ah_cal_curr != AH_NULL && !ar5416RunInitCals(ah, 0))
292			return AH_FALSE;
293#endif
294	}
295
296	/* If Cals are supported, add them to list via INIT/INSERT_CAL */
297	if (ar5416IsCalSupp(ah, chan, ADC_GAIN_CAL)) {
298		INIT_CAL(&cal->adcGainCalData);
299		INSERT_CAL(cal, &cal->adcGainCalData);
300		HALDEBUG(ah, HAL_DEBUG_PERCAL,
301		    "%s: enable ADC Gain Calibration.\n", __func__);
302	}
303	if (ar5416IsCalSupp(ah, chan, ADC_DC_CAL)) {
304		INIT_CAL(&cal->adcDcCalData);
305		INSERT_CAL(cal, &cal->adcDcCalData);
306		HALDEBUG(ah, HAL_DEBUG_PERCAL,
307		    "%s: enable ADC DC Calibration.\n", __func__);
308	}
309	if (ar5416IsCalSupp(ah, chan, IQ_MISMATCH_CAL)) {
310		INIT_CAL(&cal->iqCalData);
311		INSERT_CAL(cal, &cal->iqCalData);
312		HALDEBUG(ah, HAL_DEBUG_PERCAL,
313		    "%s: enable IQ Calibration.\n", __func__);
314	}
315	/* Initialize current pointer to first element in list */
316	cal->cal_curr = cal->cal_list;
317
318	/* Kick off measurements for the first cal */
319	if (cal->cal_curr != AH_NULL)
320		ar5416ResetMeasurement(ah, cal->cal_curr);
321
322	/* Mark all calibrations on this channel as being invalid */
323	ichan->calValid = 0;
324
325	return AH_TRUE;
326#undef	MAX_CAL_CHECK
327}
328
329/*
330 * Entry point for upper layers to restart current cal.
331 * Reset the calibration valid bit in channel.
332 */
333HAL_BOOL
334ar5416ResetCalValid(struct ath_hal *ah, const struct ieee80211_channel *chan)
335{
336	struct ar5416PerCal *cal = &AH5416(ah)->ah_cal;
337	HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
338	HAL_CAL_LIST *currCal = cal->cal_curr;
339
340	if (!AR_SREV_SOWL_10_OR_LATER(ah))
341		return AH_FALSE;
342	if (currCal == AH_NULL)
343		return AH_FALSE;
344	if (ichan == AH_NULL) {
345		HALDEBUG(ah, HAL_DEBUG_ANY,
346		    "%s: invalid channel %u/0x%x; no mapping\n",
347		    __func__, chan->ic_freq, chan->ic_flags);
348		return AH_FALSE;
349	}
350	/*
351	 * Expected that this calibration has run before, post-reset.
352	 * Current state should be done
353	 */
354	if (currCal->calState != CAL_DONE) {
355		HALDEBUG(ah, HAL_DEBUG_ANY,
356		    "%s: Calibration state incorrect, %d\n",
357		    __func__, currCal->calState);
358		return AH_FALSE;
359	}
360
361	/* Verify Cal is supported on this channel */
362	if (!ar5416IsCalSupp(ah, chan, currCal->calData->calType))
363		return AH_FALSE;
364
365	HALDEBUG(ah, HAL_DEBUG_PERCAL,
366	    "%s: Resetting Cal %d state for channel %u/0x%x\n",
367	    __func__, currCal->calData->calType, chan->ic_freq,
368	    chan->ic_flags);
369
370	/* Disable cal validity in channel */
371	ichan->calValid &= ~currCal->calData->calType;
372	currCal->calState = CAL_WAITING;
373
374	return AH_TRUE;
375}
376
377/*
378 * Recalibrate the lower PHY chips to account for temperature/environment
379 * changes.
380 */
381static void
382ar5416DoCalibration(struct ath_hal *ah,  HAL_CHANNEL_INTERNAL *ichan,
383	uint8_t rxchainmask, HAL_CAL_LIST *currCal, HAL_BOOL *isCalDone)
384{
385	struct ar5416PerCal *cal = &AH5416(ah)->ah_cal;
386
387	/* Cal is assumed not done until explicitly set below */
388	*isCalDone = AH_FALSE;
389
390	HALDEBUG(ah, HAL_DEBUG_PERCAL,
391	    "%s: %s Calibration, state %d, calValid 0x%x\n",
392	    __func__, currCal->calData->calName, currCal->calState,
393	    ichan->calValid);
394
395	/* Calibration in progress. */
396	if (currCal->calState == CAL_RUNNING) {
397		/* Check to see if it has finished. */
398		if (!(OS_REG_READ(ah, AR_PHY_TIMING_CTRL4) & AR_PHY_TIMING_CTRL4_DO_CAL)) {
399			HALDEBUG(ah, HAL_DEBUG_PERCAL,
400			    "%s: sample %d of %d finished\n",
401			    __func__, cal->calSamples,
402			    currCal->calData->calNumSamples);
403			/*
404			 * Collect measurements for active chains.
405			 */
406			currCal->calData->calCollect(ah);
407			if (++cal->calSamples >= currCal->calData->calNumSamples) {
408				int i, numChains = 0;
409				for (i = 0; i < AR5416_MAX_CHAINS; i++) {
410					if (rxchainmask & (1 << i))
411						numChains++;
412				}
413				/*
414				 * Process accumulated data
415				 */
416				currCal->calData->calPostProc(ah, numChains);
417
418				/* Calibration has finished. */
419				ichan->calValid |= currCal->calData->calType;
420				currCal->calState = CAL_DONE;
421				*isCalDone = AH_TRUE;
422			} else {
423				/*
424				 * Set-up to collect of another sub-sample.
425				 */
426				ar5416SetupMeasurement(ah, currCal);
427			}
428		}
429	} else if (!(ichan->calValid & currCal->calData->calType)) {
430		/* If current cal is marked invalid in channel, kick it off */
431		ar5416ResetMeasurement(ah, currCal);
432	}
433}
434
435/*
436 * Internal interface to schedule periodic calibration work.
437 */
438HAL_BOOL
439ar5416PerCalibrationN(struct ath_hal *ah, struct ieee80211_channel *chan,
440	u_int rxchainmask, HAL_BOOL longcal, HAL_BOOL *isCalDone)
441{
442	struct ar5416PerCal *cal = &AH5416(ah)->ah_cal;
443	HAL_CAL_LIST *currCal = cal->cal_curr;
444	HAL_CHANNEL_INTERNAL *ichan;
445
446	OS_MARK(ah, AH_MARK_PERCAL, chan->ic_freq);
447
448	*isCalDone = AH_TRUE;
449
450	/*
451	 * Since ath_hal calls the PerCal method with rxchainmask=0x1;
452	 * override it with the current chainmask. The upper levels currently
453	 * doesn't know about the chainmask.
454	 */
455	rxchainmask = AH5416(ah)->ah_rx_chainmask;
456
457	/* Invalid channel check */
458	ichan = ath_hal_checkchannel(ah, chan);
459	if (ichan == AH_NULL) {
460		HALDEBUG(ah, HAL_DEBUG_ANY,
461		    "%s: invalid channel %u/0x%x; no mapping\n",
462		    __func__, chan->ic_freq, chan->ic_flags);
463		return AH_FALSE;
464	}
465
466	/*
467	 * For given calibration:
468	 * 1. Call generic cal routine
469	 * 2. When this cal is done (isCalDone) if we have more cals waiting
470	 *    (eg after reset), mask this to upper layers by not propagating
471	 *    isCalDone if it is set to TRUE.
472	 *    Instead, change isCalDone to FALSE and setup the waiting cal(s)
473	 *    to be run.
474	 */
475	if (currCal != AH_NULL &&
476	    (currCal->calState == CAL_RUNNING ||
477	     currCal->calState == CAL_WAITING)) {
478		ar5416DoCalibration(ah, ichan, rxchainmask, currCal, isCalDone);
479		if (*isCalDone == AH_TRUE) {
480			cal->cal_curr = currCal = currCal->calNext;
481			if (currCal->calState == CAL_WAITING) {
482				*isCalDone = AH_FALSE;
483				ar5416ResetMeasurement(ah, currCal);
484			}
485		}
486	}
487
488	/* Do NF cal only at longer intervals */
489	if (longcal) {
490		/* Do PA calibration if the chipset supports */
491		if (AH5416(ah)->ah_cal_pacal)
492			AH5416(ah)->ah_cal_pacal(ah, AH_FALSE);
493
494		/* Do temperature compensation if the chipset needs it */
495		AH5416(ah)->ah_olcTempCompensation(ah);
496
497		/*
498		 * Get the value from the previous NF cal
499		 * and update the history buffer.
500		 */
501		ar5416GetNf(ah, chan);
502
503		/*
504		 * Load the NF from history buffer of the current channel.
505		 * NF is slow time-variant, so it is OK to use a
506		 * historical value.
507		 */
508		ar5416LoadNF(ah, AH_PRIVATE(ah)->ah_curchan);
509
510		/* start NF calibration, without updating BB NF register*/
511		ar5416StartNFCal(ah);
512	}
513	return AH_TRUE;
514}
515
516/*
517 * Recalibrate the lower PHY chips to account for temperature/environment
518 * changes.
519 */
520HAL_BOOL
521ar5416PerCalibration(struct ath_hal *ah, struct ieee80211_channel *chan,
522	HAL_BOOL *isIQdone)
523{
524	struct ath_hal_5416 *ahp = AH5416(ah);
525	struct ar5416PerCal *cal = &AH5416(ah)->ah_cal;
526	HAL_CAL_LIST *curCal = cal->cal_curr;
527
528	if (curCal != AH_NULL && curCal->calData->calType == IQ_MISMATCH_CAL) {
529		return ar5416PerCalibrationN(ah, chan, ahp->ah_rx_chainmask,
530		    AH_TRUE, isIQdone);
531	} else {
532		HAL_BOOL isCalDone;
533
534		*isIQdone = AH_FALSE;
535		return ar5416PerCalibrationN(ah, chan, ahp->ah_rx_chainmask,
536		    AH_TRUE, &isCalDone);
537	}
538}
539
540static HAL_BOOL
541ar5416GetEepromNoiseFloorThresh(struct ath_hal *ah,
542	const struct ieee80211_channel *chan, int16_t *nft)
543{
544	if (IEEE80211_IS_CHAN_5GHZ(chan)) {
545		ath_hal_eepromGet(ah, AR_EEP_NFTHRESH_5, nft);
546		return AH_TRUE;
547	}
548	if (IEEE80211_IS_CHAN_2GHZ(chan)) {
549		ath_hal_eepromGet(ah, AR_EEP_NFTHRESH_2, nft);
550		return AH_TRUE;
551	}
552	HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
553	    __func__, chan->ic_flags);
554	return AH_FALSE;
555}
556
557static void
558ar5416StartNFCal(struct ath_hal *ah)
559{
560	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_ENABLE_NF);
561	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NO_UPDATE_NF);
562	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
563}
564
565static void
566ar5416LoadNF(struct ath_hal *ah, const struct ieee80211_channel *chan)
567{
568	static const uint32_t ar5416_cca_regs[] = {
569		AR_PHY_CCA,
570		AR_PHY_CH1_CCA,
571		AR_PHY_CH2_CCA,
572		AR_PHY_EXT_CCA,
573		AR_PHY_CH1_EXT_CCA,
574		AR_PHY_CH2_EXT_CCA
575	};
576	struct ar5212NfCalHist *h;
577	int i;
578	int32_t val;
579	uint8_t chainmask;
580	int16_t default_nf = ar5416GetDefaultNF(ah, chan);
581
582	/*
583	 * Force NF calibration for all chains.
584	 */
585	if (AR_SREV_KITE(ah)) {
586		/* Kite has only one chain */
587		chainmask = 0x9;
588	} else if (AR_SREV_MERLIN(ah)) {
589		/* Merlin has only two chains */
590		chainmask = 0x1B;
591	} else {
592		chainmask = 0x3F;
593	}
594
595	/*
596	 * Write filtered NF values into maxCCApwr register parameter
597	 * so we can load below.
598	 */
599	h = AH5416(ah)->ah_cal.nfCalHist;
600	HALDEBUG(ah, HAL_DEBUG_NFCAL, "CCA: ");
601	for (i = 0; i < AR5416_NUM_NF_READINGS; i ++) {
602
603		/* Don't write to EXT radio CCA registers unless in HT/40 mode */
604		/* XXX this check should really be cleaner! */
605		if (i > 2 && !IEEE80211_IS_CHAN_HT40(chan))
606			continue;
607
608		if (chainmask & (1 << i)) {
609			int16_t nf_val;
610
611			if (h)
612				nf_val = h[i].privNF;
613			else
614				nf_val = default_nf;
615
616			val = OS_REG_READ(ah, ar5416_cca_regs[i]);
617			val &= 0xFFFFFE00;
618			val |= (((uint32_t) nf_val << 1) & 0x1ff);
619			HALDEBUG(ah, HAL_DEBUG_NFCAL, "[%d: %d]", i, nf_val);
620			OS_REG_WRITE(ah, ar5416_cca_regs[i], val);
621		}
622	}
623	HALDEBUG(ah, HAL_DEBUG_NFCAL, "\n");
624
625	/* Load software filtered NF value into baseband internal minCCApwr variable. */
626	OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_ENABLE_NF);
627	OS_REG_CLR_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NO_UPDATE_NF);
628	OS_REG_SET_BIT(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_NF);
629
630	/* Wait for load to complete, should be fast, a few 10s of us. */
631	if (! ar5212WaitNFCalComplete(ah, 1000)) {
632		/*
633		 * We timed out waiting for the noisefloor to load, probably due to an
634		 * in-progress rx. Simply return here and allow the load plenty of time
635		 * to complete before the next calibration interval.  We need to avoid
636		 * trying to load -50 (which happens below) while the previous load is
637		 * still in progress as this can cause rx deafness. Instead by returning
638		 * here, the baseband nf cal will just be capped by our present
639		 * noisefloor until the next calibration timer.
640		 */
641		HALDEBUG(ah, HAL_DEBUG_UNMASKABLE, "Timeout while waiting for "
642		    "nf to load: AR_PHY_AGC_CONTROL=0x%x\n",
643		    OS_REG_READ(ah, AR_PHY_AGC_CONTROL));
644		return;
645	}
646
647	/*
648	 * Restore maxCCAPower register parameter again so that we're not capped
649	 * by the median we just loaded.  This will be initial (and max) value
650	 * of next noise floor calibration the baseband does.
651	 */
652	for (i = 0; i < AR5416_NUM_NF_READINGS; i ++)
653
654		/* Don't write to EXT radio CCA registers unless in HT/40 mode */
655		/* XXX this check should really be cleaner! */
656		if (i > 2 && !IEEE80211_IS_CHAN_HT40(chan))
657			continue;
658
659		if (chainmask & (1 << i)) {
660			val = OS_REG_READ(ah, ar5416_cca_regs[i]);
661			val &= 0xFFFFFE00;
662			val |= (((uint32_t)(-50) << 1) & 0x1ff);
663			OS_REG_WRITE(ah, ar5416_cca_regs[i], val);
664		}
665}
666
667/*
668 * This just initialises the "good" values for AR5416 which
669 * may not be right; it'lll be overridden by ar5416SanitizeNF()
670 * to nominal values.
671 */
672void
673ar5416InitNfHistBuff(struct ar5212NfCalHist *h)
674{
675	int i, j;
676
677	for (i = 0; i < AR5416_NUM_NF_READINGS; i ++) {
678		h[i].currIndex = 0;
679		h[i].privNF = AR5416_CCA_MAX_GOOD_VALUE;
680		h[i].invalidNFcount = AR512_NF_CAL_HIST_MAX;
681		for (j = 0; j < AR512_NF_CAL_HIST_MAX; j ++)
682			h[i].nfCalBuffer[j] = AR5416_CCA_MAX_GOOD_VALUE;
683	}
684}
685
686/*
687 * Update the noise floor buffer as a ring buffer
688 */
689static void
690ar5416UpdateNFHistBuff(struct ath_hal *ah, struct ar5212NfCalHist *h,
691    int16_t *nfarray)
692{
693	int i;
694
695	/* XXX TODO: don't record nfarray[] entries for inactive chains */
696	for (i = 0; i < AR5416_NUM_NF_READINGS; i ++) {
697		h[i].nfCalBuffer[h[i].currIndex] = nfarray[i];
698
699		if (++h[i].currIndex >= AR512_NF_CAL_HIST_MAX)
700			h[i].currIndex = 0;
701		if (h[i].invalidNFcount > 0) {
702			if (nfarray[i] < AR5416_CCA_MIN_BAD_VALUE ||
703			    nfarray[i] > AR5416_CCA_MAX_HIGH_VALUE) {
704				h[i].invalidNFcount = AR512_NF_CAL_HIST_MAX;
705			} else {
706				h[i].invalidNFcount--;
707				h[i].privNF = nfarray[i];
708			}
709		} else {
710			h[i].privNF = ar5212GetNfHistMid(h[i].nfCalBuffer);
711		}
712	}
713}
714
715static uint16_t
716ar5416GetDefaultNF(struct ath_hal *ah, const struct ieee80211_channel *chan)
717{
718        struct ar5416NfLimits *limit;
719
720        if (!chan || IEEE80211_IS_CHAN_2GHZ(chan))
721                limit = &AH5416(ah)->nf_2g;
722        else
723                limit = &AH5416(ah)->nf_5g;
724
725        return limit->nominal;
726}
727
728static void
729ar5416SanitizeNF(struct ath_hal *ah, int16_t *nf)
730{
731
732        struct ar5416NfLimits *limit;
733        int i;
734
735        if (IEEE80211_IS_CHAN_2GHZ(AH_PRIVATE(ah)->ah_curchan))
736                limit = &AH5416(ah)->nf_2g;
737        else
738                limit = &AH5416(ah)->nf_5g;
739
740        for (i = 0; i < AR5416_NUM_NF_READINGS; i++) {
741                if (!nf[i])
742                        continue;
743
744                if (nf[i] > limit->max) {
745                        HALDEBUG(ah, HAL_DEBUG_NFCAL,
746                                  "NF[%d] (%d) > MAX (%d), correcting to MAX\n",
747                                  i, nf[i], limit->max);
748                        nf[i] = limit->max;
749                } else if (nf[i] < limit->min) {
750                        HALDEBUG(ah, HAL_DEBUG_NFCAL,
751                                  "NF[%d] (%d) < MIN (%d), correcting to NOM\n",
752                                  i, nf[i], limit->min);
753                        nf[i] = limit->nominal;
754                }
755        }
756}
757
758
759/*
760 * Read the NF and check it against the noise floor threshhold
761 */
762static int16_t
763ar5416GetNf(struct ath_hal *ah, struct ieee80211_channel *chan)
764{
765	int16_t nf, nfThresh;
766	int i;
767
768	if (ar5212IsNFCalInProgress(ah)) {
769		HALDEBUG(ah, HAL_DEBUG_ANY,
770		    "%s: NF didn't complete in calibration window\n", __func__);
771		nf = 0;
772	} else {
773		/* Finished NF cal, check against threshold */
774		int16_t nfarray[NUM_NOISEFLOOR_READINGS] = { 0 };
775		HAL_CHANNEL_INTERNAL *ichan = ath_hal_checkchannel(ah, chan);
776
777		/* TODO - enhance for multiple chains and ext ch */
778		ath_hal_getNoiseFloor(ah, nfarray);
779		nf = nfarray[0];
780		ar5416SanitizeNF(ah, nfarray);
781		if (ar5416GetEepromNoiseFloorThresh(ah, chan, &nfThresh)) {
782			if (nf > nfThresh) {
783				HALDEBUG(ah, HAL_DEBUG_ANY,
784				    "%s: noise floor failed detected; "
785				    "detected %d, threshold %d\n", __func__,
786				    nf, nfThresh);
787				/*
788				 * NB: Don't discriminate 2.4 vs 5Ghz, if this
789				 *     happens it indicates a problem regardless
790				 *     of the band.
791				 */
792				chan->ic_state |= IEEE80211_CHANSTATE_CWINT;
793				nf = 0;
794			}
795		} else {
796			nf = 0;
797		}
798		/* Update MIMO channel statistics, regardless of validity or not (for now) */
799		for (i = 0; i < 3; i++) {
800			ichan->noiseFloorCtl[i] = nfarray[i];
801			ichan->noiseFloorExt[i] = nfarray[i + 3];
802		}
803		ichan->privFlags |= CHANNEL_MIMO_NF_VALID;
804
805		ar5416UpdateNFHistBuff(ah, AH5416(ah)->ah_cal.nfCalHist, nfarray);
806		ichan->rawNoiseFloor = nf;
807	}
808	return nf;
809}
810