]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/staging/brcm80211/brcmsmac/main.c
staging: brcm80211: use fragment number provided in transmit frame
[karo-tx-linux.git] / drivers / staging / brcm80211 / brcmsmac / main.c
1 /*
2  * Copyright (c) 2010 Broadcom Corporation
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
11  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
13  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
14  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <linux/pci_ids.h>
18 #include <linux/if_ether.h>
19 #include <net/mac80211.h>
20 #include <brcm_hw_ids.h>
21 #include <aiutils.h>
22 #include <chipcommon.h>
23 #include "rate.h"
24 #include "scb.h"
25 #include "phy/phy_hal.h"
26 #include "channel.h"
27 #include "antsel.h"
28 #include "stf.h"
29 #include "ampdu.h"
30 #include "mac80211_if.h"
31 #include "ucode_loader.h"
32 #include "main.h"
33
34 /*
35  * Indication for txflowcontrol that all priority bits in
36  * TXQ_STOP_FOR_PRIOFC_MASK are to be considered.
37  */
38 #define ALLPRIO         -1
39
40 /*
41  * 32 SSID chars, max of 4 chars for each SSID char "\xFF", plus NULL.
42  */
43 #define SSID_FMT_BUF_LEN        ((4 * IEEE80211_MAX_SSID_LEN) + 1)
44
45 /* watchdog timer, in unit of ms */
46 #define TIMER_INTERVAL_WATCHDOG 1000
47 /* radio monitor timer, in unit of ms */
48 #define TIMER_INTERVAL_RADIOCHK 800
49
50 /* Max MPC timeout, in unit of watchdog */
51 #ifndef BRCMS_MPC_MAX_DELAYCNT
52 #define BRCMS_MPC_MAX_DELAYCNT  10
53 #endif
54
55 /* Min MPC timeout, in unit of watchdog */
56 #define BRCMS_MPC_MIN_DELAYCNT  1
57 #define BRCMS_MPC_THRESHOLD     3       /* MPC count threshold level */
58
59 /* beacon interval, in unit of 1024TU */
60 #define BEACON_INTERVAL_DEFAULT 100
61 /* DTIM interval, in unit of beacon interval */
62 #define DTIM_INTERVAL_DEFAULT   3
63
64 /* Scale down delays to accommodate QT slow speed */
65 /* beacon interval, in unit of 1024TU */
66 #define BEACON_INTERVAL_DEF_QT  20
67 /* DTIM interval, in unit of beacon interval */
68 #define DTIM_INTERVAL_DEF_QT    1
69
70 #define TBTT_ALIGN_LEEWAY_US    100     /* min leeway before first TBTT in us */
71
72 /* n-mode support capability */
73 /* 2x2 includes both 1x1 & 2x2 devices
74  * reserved #define 2 for future when we want to separate 1x1 & 2x2 and
75  * control it independently
76  */
77 #define WL_11N_2x2                      1
78 #define WL_11N_3x3                      3
79 #define WL_11N_4x4                      4
80
81 /* define 11n feature disable flags */
82 #define WLFEATURE_DISABLE_11N           0x00000001
83 #define WLFEATURE_DISABLE_11N_STBC_TX   0x00000002
84 #define WLFEATURE_DISABLE_11N_STBC_RX   0x00000004
85 #define WLFEATURE_DISABLE_11N_SGI_TX    0x00000008
86 #define WLFEATURE_DISABLE_11N_SGI_RX    0x00000010
87 #define WLFEATURE_DISABLE_11N_AMPDU_TX  0x00000020
88 #define WLFEATURE_DISABLE_11N_AMPDU_RX  0x00000040
89 #define WLFEATURE_DISABLE_11N_GF        0x00000080
90
91 #define EDCF_ACI_MASK                0x60
92 #define EDCF_ACI_SHIFT               5
93 #define EDCF_ECWMIN_MASK             0x0f
94 #define EDCF_ECWMAX_SHIFT            4
95 #define EDCF_AIFSN_MASK              0x0f
96 #define EDCF_AIFSN_MAX               15
97 #define EDCF_ECWMAX_MASK             0xf0
98
99 #define EDCF_AC_BE_TXOP_STA          0x0000
100 #define EDCF_AC_BK_TXOP_STA          0x0000
101 #define EDCF_AC_VO_ACI_STA           0x62
102 #define EDCF_AC_VO_ECW_STA           0x32
103 #define EDCF_AC_VI_ACI_STA           0x42
104 #define EDCF_AC_VI_ECW_STA           0x43
105 #define EDCF_AC_BK_ECW_STA           0xA4
106 #define EDCF_AC_VI_TXOP_STA          0x005e
107 #define EDCF_AC_VO_TXOP_STA          0x002f
108 #define EDCF_AC_BE_ACI_STA           0x03
109 #define EDCF_AC_BE_ECW_STA           0xA4
110 #define EDCF_AC_BK_ACI_STA           0x27
111 #define EDCF_AC_VO_TXOP_AP           0x002f
112
113 #define EDCF_TXOP2USEC(txop)         ((txop) << 5)
114 #define EDCF_ECW2CW(exp)             ((1 << (exp)) - 1)
115
116 #define APHY_SYMBOL_TIME        4
117 #define APHY_PREAMBLE_TIME      16
118 #define APHY_SIGNAL_TIME        4
119 #define APHY_SIFS_TIME          16
120 #define APHY_SERVICE_NBITS      16
121 #define APHY_TAIL_NBITS         6
122 #define BPHY_SIFS_TIME          10
123 #define BPHY_PLCP_SHORT_TIME    96
124
125 #define PREN_PREAMBLE           24
126 #define PREN_MM_EXT             12
127 #define PREN_PREAMBLE_EXT       4
128
129 #define DOT11_MAC_HDR_LEN               24
130 #define DOT11_ACK_LEN           10
131 #define DOT11_BA_LEN            4
132 #define DOT11_OFDM_SIGNAL_EXTENSION     6
133 #define DOT11_MIN_FRAG_LEN              256
134 #define DOT11_RTS_LEN           16
135 #define DOT11_CTS_LEN           10
136 #define DOT11_BA_BITMAP_LEN             128
137 #define DOT11_MIN_BEACON_PERIOD         1
138 #define DOT11_MAX_BEACON_PERIOD         0xFFFF
139 #define DOT11_MAXNUMFRAGS       16
140 #define DOT11_MAX_FRAG_LEN              2346
141
142 #define BPHY_PLCP_TIME          192
143 #define RIFS_11N_TIME           2
144
145 #define WME_VER                 1
146 #define WME_SUBTYPE_PARAM_IE    1
147 #define WME_TYPE                2
148 #define WME_OUI                 "\x00\x50\xf2"
149
150 #define AC_BE                   0
151 #define AC_BK                   1
152 #define AC_VI                   2
153 #define AC_VO                   3
154
155 #define BCN_TMPL_LEN            512     /* length of the BCN template area */
156
157 /* brcms_bss_info flag bit values */
158 #define BRCMS_BSS_HT            0x0020  /* BSS is HT (MIMO) capable */
159
160 /* Flags used in brcms_c_txq_info.stopped */
161 /* per prio flow control bits */
162 #define TXQ_STOP_FOR_PRIOFC_MASK        0x000000FF
163 /* stop txq enqueue for packet drain */
164 #define TXQ_STOP_FOR_PKT_DRAIN          0x00000100
165 /* stop txq enqueue for ampdu flow control */
166 #define TXQ_STOP_FOR_AMPDU_FLOW_CNTRL   0x00000200
167
168 #define BRCMS_HWRXOFF           38      /* chip rx buffer offset */
169
170 /* Find basic rate for a given rate */
171 static u8 brcms_basic_rate(struct brcms_c_info *wlc, u32 rspec)
172 {
173         if (is_mcs_rate(rspec))
174                 return wlc->band->basic_rate[mcs_table[rspec & RSPEC_RATE_MASK]
175                        .leg_ofdm];
176         return wlc->band->basic_rate[rspec & RSPEC_RATE_MASK];
177 }
178
179 static u16 frametype(u32 rspec, u8 mimoframe)
180 {
181         if (is_mcs_rate(rspec))
182                 return mimoframe;
183         return is_cck_rate(rspec) ? FT_CCK : FT_OFDM;
184 }
185
186 /* rfdisable delay timer 500 ms, runs of ALP clock */
187 #define RFDISABLE_DEFAULT       10000000
188
189 #define BRCMS_TEMPSENSE_PERIOD          10      /* 10 second timeout */
190
191 /* precedences numbers for wlc queues. These are twice as may levels as
192  * 802.1D priorities.
193  * Odd numbers are used for HI priority traffic at same precedence levels
194  * These constants are used ONLY by wlc_prio2prec_map.  Do not use them
195  * elsewhere.
196  */
197 #define _BRCMS_PREC_NONE                0       /* None = - */
198 #define _BRCMS_PREC_BK          2       /* BK - Background */
199 #define _BRCMS_PREC_BE          4       /* BE - Best-effort */
200 #define _BRCMS_PREC_EE          6       /* EE - Excellent-effort */
201 #define _BRCMS_PREC_CL          8       /* CL - Controlled Load */
202 #define _BRCMS_PREC_VI          10      /* Vi - Video */
203 #define _BRCMS_PREC_VO          12      /* Vo - Voice */
204 #define _BRCMS_PREC_NC          14      /* NC - Network Control */
205
206 /* The BSS is generating beacons in HW */
207 #define BRCMS_BSSCFG_HW_BCN     0x20
208
209 #define SYNTHPU_DLY_APHY_US     3700    /* a phy synthpu_dly time in us */
210 #define SYNTHPU_DLY_BPHY_US     1050    /* b/g phy synthpu_dly time in us */
211 #define SYNTHPU_DLY_NPHY_US     2048    /* n phy REV3 synthpu_dly time in us */
212 #define SYNTHPU_DLY_LPPHY_US    300     /* lpphy synthpu_dly time in us */
213
214 #define SYNTHPU_DLY_PHY_US_QT   100     /* QT synthpu_dly time in us */
215
216 #define ANTCNT                  10      /* vanilla M_MAX_ANTCNT value */
217
218 /* Per-AC retry limit register definitions; uses defs.h bitfield macros */
219 #define EDCF_SHORT_S            0
220 #define EDCF_SFB_S              4
221 #define EDCF_LONG_S             8
222 #define EDCF_LFB_S              12
223 #define EDCF_SHORT_M            BITFIELD_MASK(4)
224 #define EDCF_SFB_M              BITFIELD_MASK(4)
225 #define EDCF_LONG_M             BITFIELD_MASK(4)
226 #define EDCF_LFB_M              BITFIELD_MASK(4)
227
228 #define RETRY_SHORT_DEF                 7       /* Default Short retry Limit */
229 #define RETRY_SHORT_MAX                 255     /* Maximum Short retry Limit */
230 #define RETRY_LONG_DEF                  4       /* Default Long retry count */
231 #define RETRY_SHORT_FB                  3 /* Short count for fallback rate */
232 #define RETRY_LONG_FB                   2 /* Long count for fallback rate */
233
234 #define APHY_CWMIN              15
235 #define PHY_CWMAX               1023
236
237 #define EDCF_AIFSN_MIN               1
238
239 #define FRAGNUM_MASK            0xF
240
241 #define APHY_SLOT_TIME          9
242 #define BPHY_SLOT_TIME          20
243
244 #define WL_SPURAVOID_OFF        0
245 #define WL_SPURAVOID_ON1        1
246 #define WL_SPURAVOID_ON2        2
247
248 /* invalid core flags, use the saved coreflags */
249 #define BRCMS_USE_COREFLAGS     0xffffffff
250
251 /* values for PLCPHdr_override */
252 #define BRCMS_PLCP_AUTO -1
253 #define BRCMS_PLCP_SHORT        0
254 #define BRCMS_PLCP_LONG 1
255
256 /* values for g_protection_override and n_protection_override */
257 #define BRCMS_PROTECTION_AUTO           -1
258 #define BRCMS_PROTECTION_OFF            0
259 #define BRCMS_PROTECTION_ON             1
260 #define BRCMS_PROTECTION_MMHDR_ONLY     2
261 #define BRCMS_PROTECTION_CTS_ONLY               3
262
263 /* values for g_protection_control and n_protection_control */
264 #define BRCMS_PROTECTION_CTL_OFF                0
265 #define BRCMS_PROTECTION_CTL_LOCAL      1
266 #define BRCMS_PROTECTION_CTL_OVERLAP    2
267
268 /* values for n_protection */
269 #define BRCMS_N_PROTECTION_OFF          0
270 #define BRCMS_N_PROTECTION_OPTIONAL     1
271 #define BRCMS_N_PROTECTION_20IN40               2
272 #define BRCMS_N_PROTECTION_MIXEDMODE    3
273
274 /* values for band specific 40MHz capabilities */
275 #define BRCMS_N_BW_20ALL                        0
276 #define BRCMS_N_BW_40ALL                        1
277 #define BRCMS_N_BW_20IN2G_40IN5G                2
278
279 /* bitflags for SGI support (sgi_rx iovar) */
280 #define BRCMS_N_SGI_20                  0x01
281 #define BRCMS_N_SGI_40                  0x02
282
283 /* defines used by the nrate iovar */
284 /* MSC in use,indicates b0-6 holds an mcs */
285 #define NRATE_MCS_INUSE 0x00000080
286 /* rate/mcs value */
287 #define NRATE_RATE_MASK 0x0000007f
288 /* stf mode mask: siso, cdd, stbc, sdm */
289 #define NRATE_STF_MASK  0x0000ff00
290 /* stf mode shift */
291 #define NRATE_STF_SHIFT 8
292 /* bit indicates override both rate & mode */
293 #define NRATE_OVERRIDE  0x80000000
294 /* bit indicate to override mcs only */
295 #define NRATE_OVERRIDE_MCS_ONLY 0x40000000
296 #define NRATE_SGI_MASK  0x00800000      /* sgi mode */
297 #define NRATE_SGI_SHIFT 23      /* sgi mode */
298 #define NRATE_LDPC_CODING 0x00400000    /* bit indicates adv coding in use */
299 #define NRATE_LDPC_SHIFT 22     /* ldpc shift */
300
301 #define NRATE_STF_SISO  0       /* stf mode SISO */
302 #define NRATE_STF_CDD   1       /* stf mode CDD */
303 #define NRATE_STF_STBC  2       /* stf mode STBC */
304 #define NRATE_STF_SDM   3       /* stf mode SDM */
305
306 #define MAX_DMA_SEGS 4
307
308 /* Max # of entries in Tx FIFO based on 4kb page size */
309 #define NTXD            256
310 /* Max # of entries in Rx FIFO based on 4kb page size */
311 #define NRXD            256
312
313 /* try to keep this # rbufs posted to the chip */
314 #define NRXBUFPOST      32
315
316 /* data msg txq hiwat mark */
317 #define BRCMS_DATAHIWAT         50
318
319 /* bounded rx loops */
320 #define RXBND           8 /* max # frames to process in brcms_c_recv() */
321 #define TXSBND          8 /* max # tx status to process in wlc_txstatus() */
322
323 /*
324  * 32 SSID chars, max of 4 chars for each SSID char "\xFF", plus NULL.
325  */
326 #define SSID_FMT_BUF_LEN        ((4 * IEEE80211_MAX_SSID_LEN) + 1)
327
328 /*
329  * The following table lists the buffer memory allocated to xmt fifos in HW.
330  * the size is in units of 256bytes(one block), total size is HW dependent
331  * ucode has default fifo partition, sw can overwrite if necessary
332  *
333  * This is documented in twiki under the topic UcodeTxFifo. Please ensure
334  * the twiki is updated before making changes.
335  */
336
337 /* Starting corerev for the fifo size table */
338 #define XMTFIFOTBL_STARTREV     20
339
340 struct d11init {
341         u16 addr;
342         u16 size;
343         u32 value;
344 };
345
346 /* currently the best mechanism for determining SIFS is the band in use */
347 static u16 get_sifs(struct brcms_band *band)
348 {
349         return band->bandtype == BRCM_BAND_5G ? APHY_SIFS_TIME :
350                                  BPHY_SIFS_TIME;
351 }
352
353
354 /*
355  * Detect Card removed.
356  * Even checking an sbconfig register read will not false trigger when the core
357  * is in reset it breaks CF address mechanism. Accessing gphy phyversion will
358  * cause SB error if aphy is in reset on 4306B0-DB. Need a simple accessible
359  * reg with fixed 0/1 pattern (some platforms return all 0).
360  * If clocks are present, call the sb routine which will figure out if the
361  * device is removed.
362  */
363 static bool brcms_deviceremoved(struct brcms_c_info *wlc)
364 {
365         if (!wlc->hw->clk)
366                 return ai_deviceremoved(wlc->hw->sih);
367         return (R_REG(&wlc->hw->regs->maccontrol) &
368                 (MCTL_PSM_JMP_0 | MCTL_IHR_EN)) != MCTL_IHR_EN;
369 }
370
371 /* sum the individual fifo tx pending packet counts */
372 static s16 brcms_txpktpendtot(struct brcms_c_info *wlc)
373 {
374         return wlc->core->txpktpend[0] + wlc->core->txpktpend[1] +
375                wlc->core->txpktpend[2] + wlc->core->txpktpend[3];
376 }
377
378 static bool brcms_is_mband_unlocked(struct brcms_c_info *wlc)
379 {
380         return wlc->pub->_nbands > 1 && !wlc->bandlocked;
381 }
382
383 static int brcms_chspec_bw(u16 chanspec)
384 {
385         if (CHSPEC_IS40(chanspec))
386                 return BRCMS_40_MHZ;
387         if (CHSPEC_IS20(chanspec))
388                 return BRCMS_20_MHZ;
389
390         return BRCMS_10_MHZ;
391 }
392
393 /* dup state between BMAC(struct brcms_hardware) and HIGH(struct brcms_c_info)
394    driver */
395 struct brcms_b_state {
396         u32 machwcap;   /* mac hw capibility */
397         u32 preamble_ovr;       /* preamble override */
398 };
399
400 struct edcf_acparam {
401         u8 ACI;
402         u8 ECW;
403         u16 TXOP;
404 } __packed;
405
406 const u8 prio2fifo[NUMPRIO] = {
407         TX_AC_BE_FIFO,          /* 0    BE      AC_BE   Best Effort */
408         TX_AC_BK_FIFO,          /* 1    BK      AC_BK   Background */
409         TX_AC_BK_FIFO,          /* 2    --      AC_BK   Background */
410         TX_AC_BE_FIFO,          /* 3    EE      AC_BE   Best Effort */
411         TX_AC_VI_FIFO,          /* 4    CL      AC_VI   Video */
412         TX_AC_VI_FIFO,          /* 5    VI      AC_VI   Video */
413         TX_AC_VO_FIFO,          /* 6    VO      AC_VO   Voice */
414         TX_AC_VO_FIFO           /* 7    NC      AC_VO   Voice */
415 };
416
417 /* debug/trace */
418 uint brcm_msg_level =
419 #if defined(BCMDBG)
420         LOG_ERROR_VAL;
421 #else
422         0;
423 #endif                          /* BCMDBG */
424
425 /* TX FIFO number to WME/802.1E Access Category */
426 const u8 wme_fifo2ac[] = { AC_BK, AC_BE, AC_VI, AC_VO, AC_BE, AC_BE };
427
428 /* WME/802.1E Access Category to TX FIFO number */
429 static const u8 wme_ac2fifo[] = { 1, 0, 2, 3 };
430
431 static bool in_send_q;
432
433 /* 802.1D Priority to precedence queue mapping */
434 const u8 wlc_prio2prec_map[] = {
435         _BRCMS_PREC_BE,         /* 0 BE - Best-effort */
436         _BRCMS_PREC_BK,         /* 1 BK - Background */
437         _BRCMS_PREC_NONE,               /* 2 None = - */
438         _BRCMS_PREC_EE,         /* 3 EE - Excellent-effort */
439         _BRCMS_PREC_CL,         /* 4 CL - Controlled Load */
440         _BRCMS_PREC_VI,         /* 5 Vi - Video */
441         _BRCMS_PREC_VO,         /* 6 Vo - Voice */
442         _BRCMS_PREC_NC,         /* 7 NC - Network Control */
443 };
444
445 static u16 xmtfifo_sz[][NFIFO] = {
446         /* corerev 20: 5120, 49152, 49152, 5376, 4352, 1280 */
447         {20, 192, 192, 21, 17, 5},
448         /* corerev 21: 2304, 14848, 5632, 3584, 3584, 1280 */
449         {9, 58, 22, 14, 14, 5},
450         /* corerev 22: 5120, 49152, 49152, 5376, 4352, 1280 */
451         {20, 192, 192, 21, 17, 5},
452         /* corerev 23: 5120, 49152, 49152, 5376, 4352, 1280 */
453         {20, 192, 192, 21, 17, 5},
454         /* corerev 24: 2304, 14848, 5632, 3584, 3584, 1280 */
455         {9, 58, 22, 14, 14, 5},
456 };
457
458 static const u8 acbitmap2maxprio[] = {
459         PRIO_8021D_BE, PRIO_8021D_BE, PRIO_8021D_BK, PRIO_8021D_BK,
460         PRIO_8021D_VI, PRIO_8021D_VI, PRIO_8021D_VI, PRIO_8021D_VI,
461         PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO,
462         PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO
463 };
464
465 #ifdef BCMDBG
466 static const char * const fifo_names[] = {
467         "AC_BK", "AC_BE", "AC_VI", "AC_VO", "BCMC", "ATIM" };
468 #else
469 static const char fifo_names[6][0];
470 #endif
471
472 #ifdef BCMDBG
473 /* pointer to most recently allocated wl/wlc */
474 static struct brcms_c_info *wlc_info_dbg = (struct brcms_c_info *) (NULL);
475 #endif
476
477 static void brcms_c_bsscfg_mfree(struct brcms_bss_cfg *cfg)
478 {
479         if (cfg == NULL)
480                 return;
481
482         kfree(cfg->current_bss);
483         kfree(cfg);
484 }
485
486 static void brcms_c_detach_mfree(struct brcms_c_info *wlc)
487 {
488         if (wlc == NULL)
489                 return;
490
491         brcms_c_bsscfg_mfree(wlc->bsscfg);
492         kfree(wlc->pub);
493         kfree(wlc->modulecb);
494         kfree(wlc->default_bss);
495         kfree(wlc->protection);
496         kfree(wlc->stf);
497         kfree(wlc->bandstate[0]);
498         kfree(wlc->corestate->macstat_snapshot);
499         kfree(wlc->corestate);
500         kfree(wlc->hw->bandstate[0]);
501         kfree(wlc->hw);
502
503         /* free the wlc */
504         kfree(wlc);
505         wlc = NULL;
506 }
507
508 static struct brcms_bss_cfg *brcms_c_bsscfg_malloc(uint unit)
509 {
510         struct brcms_bss_cfg *cfg;
511
512         cfg = kzalloc(sizeof(struct brcms_bss_cfg), GFP_ATOMIC);
513         if (cfg == NULL)
514                 goto fail;
515
516         cfg->current_bss = kzalloc(sizeof(struct brcms_bss_info), GFP_ATOMIC);
517         if (cfg->current_bss == NULL)
518                 goto fail;
519
520         return cfg;
521
522  fail:
523         brcms_c_bsscfg_mfree(cfg);
524         return NULL;
525 }
526
527 static struct brcms_c_info *
528 brcms_c_attach_malloc(uint unit, uint *err, uint devid)
529 {
530         struct brcms_c_info *wlc;
531
532         wlc = kzalloc(sizeof(struct brcms_c_info), GFP_ATOMIC);
533         if (wlc == NULL) {
534                 *err = 1002;
535                 goto fail;
536         }
537
538         /* allocate struct brcms_c_pub state structure */
539         wlc->pub = kzalloc(sizeof(struct brcms_pub), GFP_ATOMIC);
540         if (wlc->pub == NULL) {
541                 *err = 1003;
542                 goto fail;
543         }
544         wlc->pub->wlc = wlc;
545
546         /* allocate struct brcms_hardware state structure */
547
548         wlc->hw = kzalloc(sizeof(struct brcms_hardware), GFP_ATOMIC);
549         if (wlc->hw == NULL) {
550                 *err = 1005;
551                 goto fail;
552         }
553         wlc->hw->wlc = wlc;
554
555         wlc->hw->bandstate[0] =
556                 kzalloc(sizeof(struct brcms_hw_band) * MAXBANDS, GFP_ATOMIC);
557         if (wlc->hw->bandstate[0] == NULL) {
558                 *err = 1006;
559                 goto fail;
560         } else {
561                 int i;
562
563                 for (i = 1; i < MAXBANDS; i++)
564                         wlc->hw->bandstate[i] = (struct brcms_hw_band *)
565                             ((unsigned long)wlc->hw->bandstate[0] +
566                              (sizeof(struct brcms_hw_band) * i));
567         }
568
569         wlc->modulecb =
570                 kzalloc(sizeof(struct modulecb) * BRCMS_MAXMODULES, GFP_ATOMIC);
571         if (wlc->modulecb == NULL) {
572                 *err = 1009;
573                 goto fail;
574         }
575
576         wlc->default_bss = kzalloc(sizeof(struct brcms_bss_info), GFP_ATOMIC);
577         if (wlc->default_bss == NULL) {
578                 *err = 1010;
579                 goto fail;
580         }
581
582         wlc->bsscfg = brcms_c_bsscfg_malloc(unit);
583         if (wlc->bsscfg == NULL) {
584                 *err = 1011;
585                 goto fail;
586         }
587
588         wlc->protection = kzalloc(sizeof(struct brcms_protection),
589                                   GFP_ATOMIC);
590         if (wlc->protection == NULL) {
591                 *err = 1016;
592                 goto fail;
593         }
594
595         wlc->stf = kzalloc(sizeof(struct brcms_stf), GFP_ATOMIC);
596         if (wlc->stf == NULL) {
597                 *err = 1017;
598                 goto fail;
599         }
600
601         wlc->bandstate[0] =
602                 kzalloc(sizeof(struct brcms_band)*MAXBANDS, GFP_ATOMIC);
603         if (wlc->bandstate[0] == NULL) {
604                 *err = 1025;
605                 goto fail;
606         } else {
607                 int i;
608
609                 for (i = 1; i < MAXBANDS; i++)
610                         wlc->bandstate[i] = (struct brcms_band *)
611                                 ((unsigned long)wlc->bandstate[0]
612                                 + (sizeof(struct brcms_band)*i));
613         }
614
615         wlc->corestate = kzalloc(sizeof(struct brcms_core), GFP_ATOMIC);
616         if (wlc->corestate == NULL) {
617                 *err = 1026;
618                 goto fail;
619         }
620
621         wlc->corestate->macstat_snapshot =
622                 kzalloc(sizeof(struct macstat), GFP_ATOMIC);
623         if (wlc->corestate->macstat_snapshot == NULL) {
624                 *err = 1027;
625                 goto fail;
626         }
627
628         return wlc;
629
630  fail:
631         brcms_c_detach_mfree(wlc);
632         return NULL;
633 }
634
635 /*
636  * Update the slot timing for standard 11b/g (20us slots)
637  * or shortslot 11g (9us slots)
638  * The PSM needs to be suspended for this call.
639  */
640 static void brcms_b_update_slot_timing(struct brcms_hardware *wlc_hw,
641                                         bool shortslot)
642 {
643         struct d11regs *regs;
644
645         regs = wlc_hw->regs;
646
647         if (shortslot) {
648                 /* 11g short slot: 11a timing */
649                 W_REG(&regs->ifs_slot, 0x0207); /* APHY_SLOT_TIME */
650                 brcms_b_write_shm(wlc_hw, M_DOT11_SLOT, APHY_SLOT_TIME);
651         } else {
652                 /* 11g long slot: 11b timing */
653                 W_REG(&regs->ifs_slot, 0x0212); /* BPHY_SLOT_TIME */
654                 brcms_b_write_shm(wlc_hw, M_DOT11_SLOT, BPHY_SLOT_TIME);
655         }
656 }
657
658 static void brcms_c_write_inits(struct brcms_hardware *wlc_hw,
659                                 const struct d11init *inits)
660 {
661         int i;
662         u8 *base;
663         u8 *addr;
664         u16 size;
665         u32 value;
666
667         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
668
669         base = (u8 *)wlc_hw->regs;
670
671         for (i = 0; inits[i].addr != 0xffff; i++) {
672                 size = le16_to_cpu(inits[i].size);
673                 addr = base + le16_to_cpu(inits[i].addr);
674                 value = le32_to_cpu(inits[i].value);
675                 if (size == 2)
676                         W_REG((u16 *)addr, value);
677                 else if (size == 4)
678                         W_REG((u32 *)addr, value);
679                 else
680                         break;
681         }
682 }
683
684 static void brcms_c_write_mhf(struct brcms_hardware *wlc_hw, u16 *mhfs)
685 {
686         u8 idx;
687         u16 addr[] = {
688                 M_HOST_FLAGS1, M_HOST_FLAGS2, M_HOST_FLAGS3, M_HOST_FLAGS4,
689                 M_HOST_FLAGS5
690         };
691
692         for (idx = 0; idx < MHFMAX; idx++)
693                 brcms_b_write_shm(wlc_hw, addr[idx], mhfs[idx]);
694 }
695
696 static void brcms_c_ucode_bsinit(struct brcms_hardware *wlc_hw)
697 {
698         struct wiphy *wiphy = wlc_hw->wlc->wiphy;
699         struct brcms_ucode *ucode = &wlc_hw->wlc->wl->ucode;
700
701         /* init microcode host flags */
702         brcms_c_write_mhf(wlc_hw, wlc_hw->band->mhfs);
703
704         /* do band-specific ucode IHR, SHM, and SCR inits */
705         if (D11REV_IS(wlc_hw->corerev, 23)) {
706                 if (BRCMS_ISNPHY(wlc_hw->band))
707                         brcms_c_write_inits(wlc_hw, ucode->d11n0bsinitvals16);
708                 else
709                         wiphy_err(wiphy, "%s: wl%d: unsupported phy in corerev"
710                                   " %d\n", __func__, wlc_hw->unit,
711                                   wlc_hw->corerev);
712         } else {
713                 if (D11REV_IS(wlc_hw->corerev, 24)) {
714                         if (BRCMS_ISLCNPHY(wlc_hw->band))
715                                 brcms_c_write_inits(wlc_hw,
716                                                     ucode->d11lcn0bsinitvals24);
717                         else
718                                 wiphy_err(wiphy, "%s: wl%d: unsupported phy in"
719                                           " core rev %d\n", __func__,
720                                           wlc_hw->unit, wlc_hw->corerev);
721                 } else {
722                         wiphy_err(wiphy, "%s: wl%d: unsupported corerev %d\n",
723                                 __func__, wlc_hw->unit, wlc_hw->corerev);
724                 }
725         }
726 }
727
728 static void brcms_b_core_phy_clk(struct brcms_hardware *wlc_hw, bool clk)
729 {
730         BCMMSG(wlc_hw->wlc->wiphy, "wl%d: clk %d\n", wlc_hw->unit, clk);
731
732         wlc_hw->phyclk = clk;
733
734         if (OFF == clk) {       /* clear gmode bit, put phy into reset */
735
736                 ai_core_cflags(wlc_hw->sih, (SICF_PRST | SICF_FGC | SICF_GMODE),
737                                (SICF_PRST | SICF_FGC));
738                 udelay(1);
739                 ai_core_cflags(wlc_hw->sih, (SICF_PRST | SICF_FGC), SICF_PRST);
740                 udelay(1);
741
742         } else {                /* take phy out of reset */
743
744                 ai_core_cflags(wlc_hw->sih, (SICF_PRST | SICF_FGC), SICF_FGC);
745                 udelay(1);
746                 ai_core_cflags(wlc_hw->sih, (SICF_FGC), 0);
747                 udelay(1);
748
749         }
750 }
751
752 /* switch to new band but leave it inactive */
753 static u32 brcms_c_setband_inact(struct brcms_c_info *wlc, uint bandunit)
754 {
755         struct brcms_hardware *wlc_hw = wlc->hw;
756         u32 macintmask;
757
758         BCMMSG(wlc->wiphy, "wl%d\n", wlc_hw->unit);
759
760         WARN_ON((R_REG(&wlc_hw->regs->maccontrol) & MCTL_EN_MAC) != 0);
761
762         /* disable interrupts */
763         macintmask = brcms_intrsoff(wlc->wl);
764
765         /* radio off */
766         wlc_phy_switch_radio(wlc_hw->band->pi, OFF);
767
768         brcms_b_core_phy_clk(wlc_hw, OFF);
769
770         brcms_c_setxband(wlc_hw, bandunit);
771
772         return macintmask;
773 }
774
775 /* Process received frames */
776 /*
777  * Return true if more frames need to be processed. false otherwise.
778  * Param 'bound' indicates max. # frames to process before break out.
779  */
780 static bool
781 brcms_b_recv(struct brcms_hardware *wlc_hw, uint fifo, bool bound)
782 {
783         struct sk_buff *p;
784         struct sk_buff *head = NULL;
785         struct sk_buff *tail = NULL;
786         uint n = 0;
787         uint bound_limit = bound ? RXBND : -1;
788         struct brcms_d11rxhdr *wlc_rxhdr = NULL;
789
790         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
791         /* gather received frames */
792         while ((p = dma_rx(wlc_hw->di[fifo]))) {
793
794                 if (!tail)
795                         head = tail = p;
796                 else {
797                         tail->prev = p;
798                         tail = p;
799                 }
800
801                 /* !give others some time to run! */
802                 if (++n >= bound_limit)
803                         break;
804         }
805
806         /* post more rbufs */
807         dma_rxfill(wlc_hw->di[fifo]);
808
809         /* process each frame */
810         while ((p = head) != NULL) {
811                 head = head->prev;
812                 p->prev = NULL;
813
814                 wlc_rxhdr = (struct brcms_d11rxhdr *) p->data;
815
816                 /*
817                  * compute the RSSI from d11rxhdr and record it in wlc_rxd11hr
818                  */
819                 wlc_phy_rssi_compute(wlc_hw->band->pi, wlc_rxhdr);
820
821                 brcms_c_recv(wlc_hw->wlc, p);
822         }
823
824         return n >= bound_limit;
825 }
826
827 /* process an individual struct tx_status */
828 static bool
829 brcms_c_dotxstatus(struct brcms_c_info *wlc, struct tx_status *txs)
830 {
831         struct sk_buff *p;
832         uint queue;
833         struct d11txh *txh;
834         struct scb *scb = NULL;
835         bool free_pdu;
836         int tx_rts, tx_frame_count, tx_rts_count;
837         uint totlen, supr_status;
838         bool lastframe;
839         struct ieee80211_hdr *h;
840         u16 mcl;
841         struct ieee80211_tx_info *tx_info;
842         struct ieee80211_tx_rate *txrate;
843         int i;
844
845         /* discard intermediate indications for ucode with one legitimate case:
846          *   e.g. if "useRTS" is set. ucode did a successful rts/cts exchange,
847          *   but the subsequent tx of DATA failed. so it will start rts/cts
848          *   from the beginning (resetting the rts transmission count)
849          */
850         if (!(txs->status & TX_STATUS_AMPDU)
851             && (txs->status & TX_STATUS_INTERMEDIATE)) {
852                 wiphy_err(wlc->wiphy, "%s: INTERMEDIATE but not AMPDU\n",
853                           __func__);
854                 return false;
855         }
856
857         queue = txs->frameid & TXFID_QUEUE_MASK;
858         if (queue >= NFIFO) {
859                 p = NULL;
860                 goto fatal;
861         }
862
863         p = dma_getnexttxp(wlc->hw->di[queue], DMA_RANGE_TRANSMITTED);
864         if (p == NULL)
865                 goto fatal;
866
867         txh = (struct d11txh *) (p->data);
868         mcl = le16_to_cpu(txh->MacTxControlLow);
869
870         if (txs->phyerr) {
871                 if (brcm_msg_level & LOG_ERROR_VAL) {
872                         wiphy_err(wlc->wiphy, "phyerr 0x%x, rate 0x%x\n",
873                                   txs->phyerr, txh->MainRates);
874                         brcms_c_print_txdesc(txh);
875                 }
876                 brcms_c_print_txstatus(txs);
877         }
878
879         if (txs->frameid != cpu_to_le16(txh->TxFrameID))
880                 goto fatal;
881         tx_info = IEEE80211_SKB_CB(p);
882         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
883
884         if (tx_info->control.sta)
885                 scb = (struct scb *)tx_info->control.sta->drv_priv;
886
887         if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
888                 brcms_c_ampdu_dotxstatus(wlc->ampdu, scb, p, txs);
889                 return false;
890         }
891
892         supr_status = txs->status & TX_STATUS_SUPR_MASK;
893         if (supr_status == TX_STATUS_SUPR_BADCH)
894                 BCMMSG(wlc->wiphy,
895                        "%s: Pkt tx suppressed, possibly channel %d\n",
896                        __func__, CHSPEC_CHANNEL(wlc->default_bss->chanspec));
897
898         tx_rts = cpu_to_le16(txh->MacTxControlLow) & TXC_SENDRTS;
899         tx_frame_count =
900             (txs->status & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT;
901         tx_rts_count =
902             (txs->status & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT;
903
904         lastframe = !ieee80211_has_morefrags(h->frame_control);
905
906         if (!lastframe) {
907                 wiphy_err(wlc->wiphy, "Not last frame!\n");
908         } else {
909                 /*
910                  * Set information to be consumed by Minstrel ht.
911                  *
912                  * The "fallback limit" is the number of tx attempts a given
913                  * MPDU is sent at the "primary" rate. Tx attempts beyond that
914                  * limit are sent at the "secondary" rate.
915                  * A 'short frame' does not exceed RTS treshold.
916                  */
917                 u16 sfbl,       /* Short Frame Rate Fallback Limit */
918                     lfbl,       /* Long Frame Rate Fallback Limit */
919                     fbl;
920
921                 if (queue < AC_COUNT) {
922                         sfbl = GFIELD(wlc->wme_retries[wme_fifo2ac[queue]],
923                                       EDCF_SFB);
924                         lfbl = GFIELD(wlc->wme_retries[wme_fifo2ac[queue]],
925                                       EDCF_LFB);
926                 } else {
927                         sfbl = wlc->SFBL;
928                         lfbl = wlc->LFBL;
929                 }
930
931                 txrate = tx_info->status.rates;
932                 if (txrate[0].flags & IEEE80211_TX_RC_USE_RTS_CTS)
933                         fbl = lfbl;
934                 else
935                         fbl = sfbl;
936
937                 ieee80211_tx_info_clear_status(tx_info);
938
939                 if ((tx_frame_count > fbl) && (txrate[1].idx >= 0)) {
940                         /*
941                          * rate selection requested a fallback rate
942                          * and we used it
943                          */
944                         txrate[0].count = fbl;
945                         txrate[1].count = tx_frame_count - fbl;
946                 } else {
947                         /*
948                          * rate selection did not request fallback rate, or
949                          * we didn't need it
950                          */
951                         txrate[0].count = tx_frame_count;
952                         /*
953                          * rc80211_minstrel.c:minstrel_tx_status() expects
954                          * unused rates to be marked with idx = -1
955                          */
956                         txrate[1].idx = -1;
957                         txrate[1].count = 0;
958                 }
959
960                 /* clear the rest of the rates */
961                 for (i = 2; i < IEEE80211_TX_MAX_RATES; i++) {
962                         txrate[i].idx = -1;
963                         txrate[i].count = 0;
964                 }
965
966                 if (txs->status & TX_STATUS_ACK_RCV)
967                         tx_info->flags |= IEEE80211_TX_STAT_ACK;
968         }
969
970         totlen = brcmu_pkttotlen(p);
971         free_pdu = true;
972
973         brcms_c_txfifo_complete(wlc, queue, 1);
974
975         if (lastframe) {
976                 p->next = NULL;
977                 p->prev = NULL;
978                 /* remove PLCP & Broadcom tx descriptor header */
979                 skb_pull(p, D11_PHY_HDR_LEN);
980                 skb_pull(p, D11_TXH_LEN);
981                 ieee80211_tx_status_irqsafe(wlc->pub->ieee_hw, p);
982         } else {
983                 wiphy_err(wlc->wiphy, "%s: Not last frame => not calling "
984                           "tx_status\n", __func__);
985         }
986
987         return false;
988
989  fatal:
990         if (p)
991                 brcmu_pkt_buf_free_skb(p);
992
993         return true;
994
995 }
996
997 static bool
998 brcms_b_dotxstatus(struct brcms_hardware *wlc_hw, struct tx_status *txs)
999 {
1000         /* discard intermediate indications for ucode with one legitimate case:
1001          *   e.g. if "useRTS" is set. ucode did a successful rts/cts exchange,
1002          *   but the subsequent tx of DATA failed. so it will start rts/cts from
1003          *   the beginning (resetting the rts transmission count)
1004          */
1005         if (!(txs->status & TX_STATUS_AMPDU)
1006             && (txs->status & TX_STATUS_INTERMEDIATE))
1007                 return false;
1008
1009         return brcms_c_dotxstatus(wlc_hw->wlc, txs);
1010 }
1011
1012 /* process tx completion events in BMAC
1013  * Return true if more tx status need to be processed. false otherwise.
1014  */
1015 static bool
1016 brcms_b_txstatus(struct brcms_hardware *wlc_hw, bool bound, bool *fatal)
1017 {
1018         bool morepending = false;
1019         struct brcms_c_info *wlc = wlc_hw->wlc;
1020         struct d11regs *regs;
1021         struct tx_status txstatus, *txs;
1022         u32 s1, s2;
1023         uint n = 0;
1024         /*
1025          * Param 'max_tx_num' indicates max. # tx status to process before
1026          * break out.
1027          */
1028         uint max_tx_num = bound ? TXSBND : -1;
1029
1030         BCMMSG(wlc->wiphy, "wl%d\n", wlc_hw->unit);
1031
1032         txs = &txstatus;
1033         regs = wlc_hw->regs;
1034         while (!(*fatal)
1035                && (s1 = R_REG(&regs->frmtxstatus)) & TXS_V) {
1036
1037                 if (s1 == 0xffffffff) {
1038                         wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n",
1039                                 wlc_hw->unit, __func__);
1040                         return morepending;
1041                 }
1042
1043                         s2 = R_REG(&regs->frmtxstatus2);
1044
1045                 txs->status = s1 & TXS_STATUS_MASK;
1046                 txs->frameid = (s1 & TXS_FID_MASK) >> TXS_FID_SHIFT;
1047                 txs->sequence = s2 & TXS_SEQ_MASK;
1048                 txs->phyerr = (s2 & TXS_PTX_MASK) >> TXS_PTX_SHIFT;
1049                 txs->lasttxtime = 0;
1050
1051                 *fatal = brcms_b_dotxstatus(wlc_hw, txs);
1052
1053                 /* !give others some time to run! */
1054                 if (++n >= max_tx_num)
1055                         break;
1056         }
1057
1058         if (*fatal)
1059                 return 0;
1060
1061         if (n >= max_tx_num)
1062                 morepending = true;
1063
1064         if (!pktq_empty(&wlc->pkt_queue->q))
1065                 brcms_c_send_q(wlc);
1066
1067         return morepending;
1068 }
1069
1070 /* brcms_b_tx_fifo_suspended:
1071  * Check the MAC's tx suspend status for a tx fifo.
1072  *
1073  * When the MAC acknowledges a tx suspend, it indicates that no more
1074  * packets will be transmitted out the radio. This is independent of
1075  * DMA channel suspension---the DMA may have finished suspending, or may still
1076  * be pulling data into a tx fifo, by the time the MAC acks the suspend
1077  * request.
1078  */
1079 static bool brcms_b_tx_fifo_suspended(struct brcms_hardware *wlc_hw,
1080                                       uint tx_fifo)
1081 {
1082         /* check that a suspend has been requested and is no longer pending */
1083
1084         /*
1085          * for DMA mode, the suspend request is set in xmtcontrol of the DMA
1086          * engine, and the tx fifo suspend at the lower end of the MAC is
1087          * acknowledged in the chnstatus register.
1088          *
1089          * The tx fifo suspend completion is independent of the DMA suspend
1090          * completion and may be acked before or after the DMA is suspended.
1091          */
1092         if (dma_txsuspended(wlc_hw->di[tx_fifo]) &&
1093             (R_REG(&wlc_hw->regs->chnstatus) &
1094              (1 << tx_fifo)) == 0)
1095                 return true;
1096
1097         return false;
1098 }
1099
1100 /* second-level interrupt processing
1101  *   Return true if another dpc needs to be re-scheduled. false otherwise.
1102  *   Param 'bounded' indicates if applicable loops should be bounded.
1103  */
1104 bool brcms_c_dpc(struct brcms_c_info *wlc, bool bounded)
1105 {
1106         u32 macintstatus;
1107         struct brcms_hardware *wlc_hw = wlc->hw;
1108         struct d11regs *regs = wlc_hw->regs;
1109         bool fatal = false;
1110         struct wiphy *wiphy = wlc->wiphy;
1111
1112         if (brcms_deviceremoved(wlc)) {
1113                 wiphy_err(wiphy, "wl%d: %s: dead chip\n", wlc_hw->unit,
1114                           __func__);
1115                 brcms_down(wlc->wl);
1116                 return false;
1117         }
1118
1119         /* grab and clear the saved software intstatus bits */
1120         macintstatus = wlc->macintstatus;
1121         wlc->macintstatus = 0;
1122
1123         BCMMSG(wlc->wiphy, "wl%d: macintstatus 0x%x\n",
1124                wlc_hw->unit, macintstatus);
1125
1126         WARN_ON(macintstatus & MI_PRQ); /* PRQ Interrupt in non-MBSS */
1127
1128         /* tx status */
1129         if (macintstatus & MI_TFS) {
1130                 if (brcms_b_txstatus(wlc->hw, bounded, &fatal))
1131                         wlc->macintstatus |= MI_TFS;
1132                 if (fatal) {
1133                         wiphy_err(wiphy, "MI_TFS: fatal\n");
1134                         goto fatal;
1135                 }
1136         }
1137
1138         if (macintstatus & (MI_TBTT | MI_DTIM_TBTT))
1139                 brcms_c_tbtt(wlc);
1140
1141         /* ATIM window end */
1142         if (macintstatus & MI_ATIMWINEND) {
1143                 BCMMSG(wlc->wiphy, "end of ATIM window\n");
1144                 OR_REG(&regs->maccommand, wlc->qvalid);
1145                 wlc->qvalid = 0;
1146         }
1147
1148         /*
1149          * received data or control frame, MI_DMAINT is
1150          * indication of RX_FIFO interrupt
1151          */
1152         if (macintstatus & MI_DMAINT)
1153                 if (brcms_b_recv(wlc_hw, RX_FIFO, bounded))
1154                         wlc->macintstatus |= MI_DMAINT;
1155
1156         /* TX FIFO suspend/flush completion */
1157         if (macintstatus & MI_TXSTOP)
1158                 brcms_b_tx_fifo_suspended(wlc_hw, TX_DATA_FIFO);
1159
1160         /* noise sample collected */
1161         if (macintstatus & MI_BG_NOISE)
1162                 wlc_phy_noise_sample_intr(wlc_hw->band->pi);
1163
1164         if (macintstatus & MI_GP0) {
1165                 wiphy_err(wiphy, "wl%d: PSM microcode watchdog fired at %d "
1166                         "(seconds). Resetting.\n", wlc_hw->unit, wlc_hw->now);
1167
1168                 printk_once("%s : PSM Watchdog, chipid 0x%x, chiprev 0x%x\n",
1169                                         __func__, wlc_hw->sih->chip,
1170                                         wlc_hw->sih->chiprev);
1171                 /* big hammer */
1172                 brcms_init(wlc->wl);
1173         }
1174
1175         /* gptimer timeout */
1176         if (macintstatus & MI_TO)
1177                 W_REG(&regs->gptimer, 0);
1178
1179         if (macintstatus & MI_RFDISABLE) {
1180                 BCMMSG(wlc->wiphy, "wl%d: BMAC Detected a change on the"
1181                        " RF Disable Input\n", wlc_hw->unit);
1182                 brcms_rfkill_set_hw_state(wlc->wl);
1183         }
1184
1185         /* send any enq'd tx packets. Just makes sure to jump start tx */
1186         if (!pktq_empty(&wlc->pkt_queue->q))
1187                 brcms_c_send_q(wlc);
1188
1189         /* it isn't done and needs to be resched if macintstatus is non-zero */
1190         return wlc->macintstatus != 0;
1191
1192  fatal:
1193         brcms_init(wlc->wl);
1194         return wlc->macintstatus != 0;
1195 }
1196
1197 static int brcms_b_state_get(struct brcms_hardware *wlc_hw,
1198                       struct brcms_b_state *state)
1199 {
1200         state->machwcap = wlc_hw->machwcap;
1201
1202         return 0;
1203 }
1204
1205 /* set initial host flags value */
1206 static void
1207 brcms_c_mhfdef(struct brcms_c_info *wlc, u16 *mhfs, u16 mhf2_init)
1208 {
1209         struct brcms_hardware *wlc_hw = wlc->hw;
1210
1211         memset(mhfs, 0, MHFMAX * sizeof(u16));
1212
1213         mhfs[MHF2] |= mhf2_init;
1214
1215         /* prohibit use of slowclock on multifunction boards */
1216         if (wlc_hw->boardflags & BFL_NOPLLDOWN)
1217                 mhfs[MHF1] |= MHF1_FORCEFASTCLK;
1218
1219         if (BRCMS_ISNPHY(wlc_hw->band) && NREV_LT(wlc_hw->band->phyrev, 2)) {
1220                 mhfs[MHF2] |= MHF2_NPHY40MHZ_WAR;
1221                 mhfs[MHF1] |= MHF1_IQSWAP_WAR;
1222         }
1223 }
1224
1225 static struct dma64regs *
1226 dmareg(struct brcms_hardware *hw, uint direction, uint fifonum)
1227 {
1228         if (direction == DMA_TX)
1229                 return &(hw->regs->fifo64regs[fifonum].dmaxmt);
1230         return &(hw->regs->fifo64regs[fifonum].dmarcv);
1231 }
1232
1233 static bool brcms_b_attach_dmapio(struct brcms_c_info *wlc, uint j, bool wme)
1234 {
1235         uint i;
1236         char name[8];
1237         /*
1238          * ucode host flag 2 needed for pio mode, independent of band and fifo
1239          */
1240         u16 pio_mhf2 = 0;
1241         struct brcms_hardware *wlc_hw = wlc->hw;
1242         uint unit = wlc_hw->unit;
1243         struct wiphy *wiphy = wlc->wiphy;
1244
1245         /* name and offsets for dma_attach */
1246         snprintf(name, sizeof(name), "wl%d", unit);
1247
1248         if (wlc_hw->di[0] == NULL) {    /* Init FIFOs */
1249                 int dma_attach_err = 0;
1250
1251                 /*
1252                  * FIFO 0
1253                  * TX: TX_AC_BK_FIFO (TX AC Background data packets)
1254                  * RX: RX_FIFO (RX data packets)
1255                  */
1256                 wlc_hw->di[0] = dma_attach(name, wlc_hw->sih,
1257                                            (wme ? dmareg(wlc_hw, DMA_TX, 0) :
1258                                             NULL), dmareg(wlc_hw, DMA_RX, 0),
1259                                            (wme ? NTXD : 0), NRXD,
1260                                            RXBUFSZ, -1, NRXBUFPOST,
1261                                            BRCMS_HWRXOFF, &brcm_msg_level);
1262                 dma_attach_err |= (NULL == wlc_hw->di[0]);
1263
1264                 /*
1265                  * FIFO 1
1266                  * TX: TX_AC_BE_FIFO (TX AC Best-Effort data packets)
1267                  *   (legacy) TX_DATA_FIFO (TX data packets)
1268                  * RX: UNUSED
1269                  */
1270                 wlc_hw->di[1] = dma_attach(name, wlc_hw->sih,
1271                                            dmareg(wlc_hw, DMA_TX, 1), NULL,
1272                                            NTXD, 0, 0, -1, 0, 0,
1273                                            &brcm_msg_level);
1274                 dma_attach_err |= (NULL == wlc_hw->di[1]);
1275
1276                 /*
1277                  * FIFO 2
1278                  * TX: TX_AC_VI_FIFO (TX AC Video data packets)
1279                  * RX: UNUSED
1280                  */
1281                 wlc_hw->di[2] = dma_attach(name, wlc_hw->sih,
1282                                            dmareg(wlc_hw, DMA_TX, 2), NULL,
1283                                            NTXD, 0, 0, -1, 0, 0,
1284                                            &brcm_msg_level);
1285                 dma_attach_err |= (NULL == wlc_hw->di[2]);
1286                 /*
1287                  * FIFO 3
1288                  * TX: TX_AC_VO_FIFO (TX AC Voice data packets)
1289                  *   (legacy) TX_CTL_FIFO (TX control & mgmt packets)
1290                  */
1291                 wlc_hw->di[3] = dma_attach(name, wlc_hw->sih,
1292                                            dmareg(wlc_hw, DMA_TX, 3),
1293                                            NULL, NTXD, 0, 0, -1,
1294                                            0, 0, &brcm_msg_level);
1295                 dma_attach_err |= (NULL == wlc_hw->di[3]);
1296 /* Cleaner to leave this as if with AP defined */
1297
1298                 if (dma_attach_err) {
1299                         wiphy_err(wiphy, "wl%d: wlc_attach: dma_attach failed"
1300                                   "\n", unit);
1301                         return false;
1302                 }
1303
1304                 /* get pointer to dma engine tx flow control variable */
1305                 for (i = 0; i < NFIFO; i++)
1306                         if (wlc_hw->di[i])
1307                                 wlc_hw->txavail[i] =
1308                                     (uint *) dma_getvar(wlc_hw->di[i],
1309                                                         "&txavail");
1310         }
1311
1312         /* initial ucode host flags */
1313         brcms_c_mhfdef(wlc, wlc_hw->band->mhfs, pio_mhf2);
1314
1315         return true;
1316 }
1317
1318 static void brcms_b_detach_dmapio(struct brcms_hardware *wlc_hw)
1319 {
1320         uint j;
1321
1322         for (j = 0; j < NFIFO; j++) {
1323                 if (wlc_hw->di[j]) {
1324                         dma_detach(wlc_hw->di[j]);
1325                         wlc_hw->di[j] = NULL;
1326                 }
1327         }
1328 }
1329
1330 /*
1331  * Initialize brcms_c_info default values ...
1332  * may get overrides later in this function
1333  *  BMAC_NOTES, move low out and resolve the dangling ones
1334  */
1335 static void brcms_b_info_init(struct brcms_hardware *wlc_hw)
1336 {
1337         struct brcms_c_info *wlc = wlc_hw->wlc;
1338
1339         /* set default sw macintmask value */
1340         wlc->defmacintmask = DEF_MACINTMASK;
1341
1342         /* various 802.11g modes */
1343         wlc_hw->shortslot = false;
1344
1345         wlc_hw->SFBL = RETRY_SHORT_FB;
1346         wlc_hw->LFBL = RETRY_LONG_FB;
1347
1348         /* default mac retry limits */
1349         wlc_hw->SRL = RETRY_SHORT_DEF;
1350         wlc_hw->LRL = RETRY_LONG_DEF;
1351         wlc_hw->chanspec = ch20mhz_chspec(1);
1352 }
1353
1354 static void brcms_b_wait_for_wake(struct brcms_hardware *wlc_hw)
1355 {
1356         /* delay before first read of ucode state */
1357         udelay(40);
1358
1359         /* wait until ucode is no longer asleep */
1360         SPINWAIT((brcms_b_read_shm(wlc_hw, M_UCODE_DBGST) ==
1361                   DBGST_ASLEEP), wlc_hw->wlc->fastpwrup_dly);
1362 }
1363
1364 static void brcms_b_hw_etheraddr(struct brcms_hardware *wlc_hw, u8 *ea)
1365 {
1366         memcpy(ea, wlc_hw->etheraddr, ETH_ALEN);
1367 }
1368
1369 static int brcms_b_bandtype(struct brcms_hardware *wlc_hw)
1370 {
1371         return wlc_hw->band->bandtype;
1372 }
1373
1374 /* control chip clock to save power, enable dynamic clock or force fast clock */
1375 static void brcms_b_clkctl_clk(struct brcms_hardware *wlc_hw, uint mode)
1376 {
1377         if (wlc_hw->sih->cccaps & CC_CAP_PMU) {
1378                 /* new chips with PMU, CCS_FORCEHT will distribute the HT clock
1379                  * on backplane, but mac core will still run on ALP(not HT) when
1380                  * it enters powersave mode, which means the FCA bit may not be
1381                  * set. Should wakeup mac if driver wants it to run on HT.
1382                  */
1383
1384                 if (wlc_hw->clk) {
1385                         if (mode == CLK_FAST) {
1386                                 OR_REG(&wlc_hw->regs->clk_ctl_st,
1387                                        CCS_FORCEHT);
1388
1389                                 udelay(64);
1390
1391                                 SPINWAIT(((R_REG
1392                                            (&wlc_hw->regs->
1393                                             clk_ctl_st) & CCS_HTAVAIL) == 0),
1394                                          PMU_MAX_TRANSITION_DLY);
1395                                 WARN_ON(!(R_REG
1396                                           (&wlc_hw->regs->
1397                                            clk_ctl_st) & CCS_HTAVAIL));
1398                         } else {
1399                                 if ((wlc_hw->sih->pmurev == 0) &&
1400                                     (R_REG
1401                                      (&wlc_hw->regs->
1402                                       clk_ctl_st) & (CCS_FORCEHT | CCS_HTAREQ)))
1403                                         SPINWAIT(((R_REG
1404                                                    (&wlc_hw->regs->
1405                                                     clk_ctl_st) & CCS_HTAVAIL)
1406                                                   == 0),
1407                                                  PMU_MAX_TRANSITION_DLY);
1408                                 AND_REG(&wlc_hw->regs->clk_ctl_st,
1409                                         ~CCS_FORCEHT);
1410                         }
1411                 }
1412                 wlc_hw->forcefastclk = (mode == CLK_FAST);
1413         } else {
1414
1415                 /* old chips w/o PMU, force HT through cc,
1416                  * then use FCA to verify mac is running fast clock
1417                  */
1418
1419                 wlc_hw->forcefastclk = ai_clkctl_cc(wlc_hw->sih, mode);
1420
1421                 /* check fast clock is available (if core is not in reset) */
1422                 if (wlc_hw->forcefastclk && wlc_hw->clk)
1423                         WARN_ON(!(ai_core_sflags(wlc_hw->sih, 0, 0) &
1424                                   SISF_FCLKA));
1425
1426                 /*
1427                  * keep the ucode wake bit on if forcefastclk is on since we
1428                  * do not want ucode to put us back to slow clock when it dozes
1429                  * for PM mode. Code below matches the wake override bit with
1430                  * current forcefastclk state. Only setting bit in wake_override
1431                  * instead of waking ucode immediately since old code had this
1432                  * behavior. Older code set wlc->forcefastclk but only had the
1433                  * wake happen if the wakup_ucode work (protected by an up
1434                  * check) was executed just below.
1435                  */
1436                 if (wlc_hw->forcefastclk)
1437                         mboolset(wlc_hw->wake_override,
1438                                  BRCMS_WAKE_OVERRIDE_FORCEFAST);
1439                 else
1440                         mboolclr(wlc_hw->wake_override,
1441                                  BRCMS_WAKE_OVERRIDE_FORCEFAST);
1442         }
1443 }
1444
1445 /* set or clear ucode host flag bits
1446  * it has an optimization for no-change write
1447  * it only writes through shared memory when the core has clock;
1448  * pre-CLK changes should use wlc_write_mhf to get around the optimization
1449  *
1450  *
1451  * bands values are: BRCM_BAND_AUTO <--- Current band only
1452  *                   BRCM_BAND_5G   <--- 5G band only
1453  *                   BRCM_BAND_2G   <--- 2G band only
1454  *                   BRCM_BAND_ALL  <--- All bands
1455  */
1456 void
1457 brcms_b_mhf(struct brcms_hardware *wlc_hw, u8 idx, u16 mask, u16 val,
1458              int bands)
1459 {
1460         u16 save;
1461         u16 addr[MHFMAX] = {
1462                 M_HOST_FLAGS1, M_HOST_FLAGS2, M_HOST_FLAGS3, M_HOST_FLAGS4,
1463                 M_HOST_FLAGS5
1464         };
1465         struct brcms_hw_band *band;
1466
1467         if ((val & ~mask) || idx >= MHFMAX)
1468                 return; /* error condition */
1469
1470         switch (bands) {
1471                 /* Current band only or all bands,
1472                  * then set the band to current band
1473                  */
1474         case BRCM_BAND_AUTO:
1475         case BRCM_BAND_ALL:
1476                 band = wlc_hw->band;
1477                 break;
1478         case BRCM_BAND_5G:
1479                 band = wlc_hw->bandstate[BAND_5G_INDEX];
1480                 break;
1481         case BRCM_BAND_2G:
1482                 band = wlc_hw->bandstate[BAND_2G_INDEX];
1483                 break;
1484         default:
1485                 band = NULL;    /* error condition */
1486         }
1487
1488         if (band) {
1489                 save = band->mhfs[idx];
1490                 band->mhfs[idx] = (band->mhfs[idx] & ~mask) | val;
1491
1492                 /* optimization: only write through if changed, and
1493                  * changed band is the current band
1494                  */
1495                 if (wlc_hw->clk && (band->mhfs[idx] != save)
1496                     && (band == wlc_hw->band))
1497                         brcms_b_write_shm(wlc_hw, addr[idx],
1498                                            (u16) band->mhfs[idx]);
1499         }
1500
1501         if (bands == BRCM_BAND_ALL) {
1502                 wlc_hw->bandstate[0]->mhfs[idx] =
1503                     (wlc_hw->bandstate[0]->mhfs[idx] & ~mask) | val;
1504                 wlc_hw->bandstate[1]->mhfs[idx] =
1505                     (wlc_hw->bandstate[1]->mhfs[idx] & ~mask) | val;
1506         }
1507 }
1508
1509 /* set the maccontrol register to desired reset state and
1510  * initialize the sw cache of the register
1511  */
1512 static void brcms_c_mctrl_reset(struct brcms_hardware *wlc_hw)
1513 {
1514         /* IHR accesses are always enabled, PSM disabled, HPS off and WAKE on */
1515         wlc_hw->maccontrol = 0;
1516         wlc_hw->suspended_fifos = 0;
1517         wlc_hw->wake_override = 0;
1518         wlc_hw->mute_override = 0;
1519         brcms_b_mctrl(wlc_hw, ~0, MCTL_IHR_EN | MCTL_WAKE);
1520 }
1521
1522 /*
1523  * write the software state of maccontrol and
1524  * overrides to the maccontrol register
1525  */
1526 static void brcms_c_mctrl_write(struct brcms_hardware *wlc_hw)
1527 {
1528         u32 maccontrol = wlc_hw->maccontrol;
1529
1530         /* OR in the wake bit if overridden */
1531         if (wlc_hw->wake_override)
1532                 maccontrol |= MCTL_WAKE;
1533
1534         /* set AP and INFRA bits for mute if needed */
1535         if (wlc_hw->mute_override) {
1536                 maccontrol &= ~(MCTL_AP);
1537                 maccontrol |= MCTL_INFRA;
1538         }
1539
1540         W_REG(&wlc_hw->regs->maccontrol, maccontrol);
1541 }
1542
1543 /* set or clear maccontrol bits */
1544 void brcms_b_mctrl(struct brcms_hardware *wlc_hw, u32 mask, u32 val)
1545 {
1546         u32 maccontrol;
1547         u32 new_maccontrol;
1548
1549         if (val & ~mask)
1550                 return; /* error condition */
1551         maccontrol = wlc_hw->maccontrol;
1552         new_maccontrol = (maccontrol & ~mask) | val;
1553
1554         /* if the new maccontrol value is the same as the old, nothing to do */
1555         if (new_maccontrol == maccontrol)
1556                 return;
1557
1558         /* something changed, cache the new value */
1559         wlc_hw->maccontrol = new_maccontrol;
1560
1561         /* write the new values with overrides applied */
1562         brcms_c_mctrl_write(wlc_hw);
1563 }
1564
1565 void brcms_c_ucode_wake_override_set(struct brcms_hardware *wlc_hw,
1566                                  u32 override_bit)
1567 {
1568         if (wlc_hw->wake_override || (wlc_hw->maccontrol & MCTL_WAKE)) {
1569                 mboolset(wlc_hw->wake_override, override_bit);
1570                 return;
1571         }
1572
1573         mboolset(wlc_hw->wake_override, override_bit);
1574
1575         brcms_c_mctrl_write(wlc_hw);
1576         brcms_b_wait_for_wake(wlc_hw);
1577
1578         return;
1579 }
1580
1581 void brcms_c_ucode_wake_override_clear(struct brcms_hardware *wlc_hw,
1582                                    u32 override_bit)
1583 {
1584         mboolclr(wlc_hw->wake_override, override_bit);
1585
1586         if (wlc_hw->wake_override || (wlc_hw->maccontrol & MCTL_WAKE))
1587                 return;
1588
1589         brcms_c_mctrl_write(wlc_hw);
1590
1591         return;
1592 }
1593
1594 /* When driver needs ucode to stop beaconing, it has to make sure that
1595  * MCTL_AP is clear and MCTL_INFRA is set
1596  * Mode           MCTL_AP        MCTL_INFRA
1597  * AP                1              1
1598  * STA               0              1 <--- This will ensure no beacons
1599  * IBSS              0              0
1600  */
1601 static void brcms_c_ucode_mute_override_set(struct brcms_hardware *wlc_hw)
1602 {
1603         wlc_hw->mute_override = 1;
1604
1605         /* if maccontrol already has AP == 0 and INFRA == 1 without this
1606          * override, then there is no change to write
1607          */
1608         if ((wlc_hw->maccontrol & (MCTL_AP | MCTL_INFRA)) == MCTL_INFRA)
1609                 return;
1610
1611         brcms_c_mctrl_write(wlc_hw);
1612
1613         return;
1614 }
1615
1616 /* Clear the override on AP and INFRA bits */
1617 static void brcms_c_ucode_mute_override_clear(struct brcms_hardware *wlc_hw)
1618 {
1619         if (wlc_hw->mute_override == 0)
1620                 return;
1621
1622         wlc_hw->mute_override = 0;
1623
1624         /* if maccontrol already has AP == 0 and INFRA == 1 without this
1625          * override, then there is no change to write
1626          */
1627         if ((wlc_hw->maccontrol & (MCTL_AP | MCTL_INFRA)) == MCTL_INFRA)
1628                 return;
1629
1630         brcms_c_mctrl_write(wlc_hw);
1631 }
1632
1633 /*
1634  * Write a MAC address to the given match reg offset in the RXE match engine.
1635  */
1636 static void
1637 brcms_b_set_addrmatch(struct brcms_hardware *wlc_hw, int match_reg_offset,
1638                        const u8 *addr)
1639 {
1640         struct d11regs *regs;
1641         u16 mac_l;
1642         u16 mac_m;
1643         u16 mac_h;
1644
1645         BCMMSG(wlc_hw->wlc->wiphy, "wl%d: brcms_b_set_addrmatch\n",
1646                  wlc_hw->unit);
1647
1648         regs = wlc_hw->regs;
1649         mac_l = addr[0] | (addr[1] << 8);
1650         mac_m = addr[2] | (addr[3] << 8);
1651         mac_h = addr[4] | (addr[5] << 8);
1652
1653         /* enter the MAC addr into the RXE match registers */
1654         W_REG(&regs->rcm_ctl, RCM_INC_DATA | match_reg_offset);
1655         W_REG(&regs->rcm_mat_data, mac_l);
1656         W_REG(&regs->rcm_mat_data, mac_m);
1657         W_REG(&regs->rcm_mat_data, mac_h);
1658
1659 }
1660
1661 void
1662 brcms_b_write_template_ram(struct brcms_hardware *wlc_hw, int offset, int len,
1663                             void *buf)
1664 {
1665         struct d11regs *regs;
1666         u32 word;
1667         bool be_bit;
1668         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
1669
1670         regs = wlc_hw->regs;
1671         W_REG(&regs->tplatewrptr, offset);
1672
1673         /* if MCTL_BIGEND bit set in mac control register,
1674          * the chip swaps data in fifo, as well as data in
1675          * template ram
1676          */
1677         be_bit = (R_REG(&regs->maccontrol) & MCTL_BIGEND) != 0;
1678
1679         while (len > 0) {
1680                 memcpy(&word, buf, sizeof(u32));
1681
1682                 if (be_bit)
1683                         word = cpu_to_be32(word);
1684                 else
1685                         word = cpu_to_le32(word);
1686
1687                 W_REG(&regs->tplatewrdata, word);
1688
1689                 buf = (u8 *) buf + sizeof(u32);
1690                 len -= sizeof(u32);
1691         }
1692 }
1693
1694 static void brcms_b_set_cwmin(struct brcms_hardware *wlc_hw, u16 newmin)
1695 {
1696         wlc_hw->band->CWmin = newmin;
1697
1698         W_REG(&wlc_hw->regs->objaddr, OBJADDR_SCR_SEL | S_DOT11_CWMIN);
1699         (void)R_REG(&wlc_hw->regs->objaddr);
1700         W_REG(&wlc_hw->regs->objdata, newmin);
1701 }
1702
1703 static void brcms_b_set_cwmax(struct brcms_hardware *wlc_hw, u16 newmax)
1704 {
1705         wlc_hw->band->CWmax = newmax;
1706
1707         W_REG(&wlc_hw->regs->objaddr, OBJADDR_SCR_SEL | S_DOT11_CWMAX);
1708         (void)R_REG(&wlc_hw->regs->objaddr);
1709         W_REG(&wlc_hw->regs->objdata, newmax);
1710 }
1711
1712 void brcms_b_bw_set(struct brcms_hardware *wlc_hw, u16 bw)
1713 {
1714         bool fastclk;
1715
1716         /* request FAST clock if not on */
1717         fastclk = wlc_hw->forcefastclk;
1718         if (!fastclk)
1719                 brcms_b_clkctl_clk(wlc_hw, CLK_FAST);
1720
1721         wlc_phy_bw_state_set(wlc_hw->band->pi, bw);
1722
1723         brcms_b_phy_reset(wlc_hw);
1724         wlc_phy_init(wlc_hw->band->pi, wlc_phy_chanspec_get(wlc_hw->band->pi));
1725
1726         /* restore the clk */
1727         if (!fastclk)
1728                 brcms_b_clkctl_clk(wlc_hw, CLK_DYNAMIC);
1729 }
1730
1731 static void
1732 brcms_c_write_hw_bcntemplate0(struct brcms_hardware *wlc_hw, u16 bcn[],
1733                               int len)
1734 {
1735         struct d11regs *regs = wlc_hw->regs;
1736
1737         brcms_b_write_template_ram(wlc_hw, T_BCN0_TPL_BASE, (len + 3) & ~3,
1738                                     bcn);
1739         /* write beacon length to SCR */
1740         brcms_b_write_shm(wlc_hw, M_BCN0_FRM_BYTESZ, (u16) len);
1741         /* mark beacon0 valid */
1742         OR_REG(&regs->maccommand, MCMD_BCN0VLD);
1743 }
1744
1745 static void
1746 brcms_c_write_hw_bcntemplate1(struct brcms_hardware *wlc_hw, u16 bcn[],
1747                               int len)
1748 {
1749         struct d11regs *regs = wlc_hw->regs;
1750
1751         brcms_b_write_template_ram(wlc_hw, T_BCN1_TPL_BASE, (len + 3) & ~3,
1752                                     bcn);
1753         /* write beacon length to SCR */
1754         brcms_b_write_shm(wlc_hw, M_BCN1_FRM_BYTESZ, (u16) len);
1755         /* mark beacon1 valid */
1756         OR_REG(&regs->maccommand, MCMD_BCN1VLD);
1757 }
1758
1759 static void brcms_b_upd_synthpu(struct brcms_hardware *wlc_hw)
1760 {
1761         u16 v;
1762         struct brcms_c_info *wlc = wlc_hw->wlc;
1763         /* update SYNTHPU_DLY */
1764
1765         if (BRCMS_ISLCNPHY(wlc->band))
1766                 v = SYNTHPU_DLY_LPPHY_US;
1767         else if (BRCMS_ISNPHY(wlc->band) && (NREV_GE(wlc->band->phyrev, 3)))
1768                 v = SYNTHPU_DLY_NPHY_US;
1769         else
1770                 v = SYNTHPU_DLY_BPHY_US;
1771
1772         brcms_b_write_shm(wlc_hw, M_SYNTHPU_DLY, v);
1773 }
1774
1775 static void brcms_c_ucode_txant_set(struct brcms_hardware *wlc_hw)
1776 {
1777         u16 phyctl;
1778         u16 phytxant = wlc_hw->bmac_phytxant;
1779         u16 mask = PHY_TXC_ANT_MASK;
1780
1781         /* set the Probe Response frame phy control word */
1782         phyctl = brcms_b_read_shm(wlc_hw, M_CTXPRS_BLK + C_CTX_PCTLWD_POS);
1783         phyctl = (phyctl & ~mask) | phytxant;
1784         brcms_b_write_shm(wlc_hw, M_CTXPRS_BLK + C_CTX_PCTLWD_POS, phyctl);
1785
1786         /* set the Response (ACK/CTS) frame phy control word */
1787         phyctl = brcms_b_read_shm(wlc_hw, M_RSP_PCTLWD);
1788         phyctl = (phyctl & ~mask) | phytxant;
1789         brcms_b_write_shm(wlc_hw, M_RSP_PCTLWD, phyctl);
1790 }
1791
1792 static u16 brcms_b_ofdm_ratetable_offset(struct brcms_hardware *wlc_hw,
1793                                          u8 rate)
1794 {
1795         uint i;
1796         u8 plcp_rate = 0;
1797         struct plcp_signal_rate_lookup {
1798                 u8 rate;
1799                 u8 signal_rate;
1800         };
1801         /* OFDM RATE sub-field of PLCP SIGNAL field, per 802.11 sec 17.3.4.1 */
1802         const struct plcp_signal_rate_lookup rate_lookup[] = {
1803                 {BRCM_RATE_6M, 0xB},
1804                 {BRCM_RATE_9M, 0xF},
1805                 {BRCM_RATE_12M, 0xA},
1806                 {BRCM_RATE_18M, 0xE},
1807                 {BRCM_RATE_24M, 0x9},
1808                 {BRCM_RATE_36M, 0xD},
1809                 {BRCM_RATE_48M, 0x8},
1810                 {BRCM_RATE_54M, 0xC}
1811         };
1812
1813         for (i = 0; i < ARRAY_SIZE(rate_lookup); i++) {
1814                 if (rate == rate_lookup[i].rate) {
1815                         plcp_rate = rate_lookup[i].signal_rate;
1816                         break;
1817                 }
1818         }
1819
1820         /* Find the SHM pointer to the rate table entry by looking in the
1821          * Direct-map Table
1822          */
1823         return 2 * brcms_b_read_shm(wlc_hw, M_RT_DIRMAP_A + (plcp_rate * 2));
1824 }
1825
1826 static void brcms_upd_ofdm_pctl1_table(struct brcms_hardware *wlc_hw)
1827 {
1828         u8 rate;
1829         u8 rates[8] = {
1830                 BRCM_RATE_6M, BRCM_RATE_9M, BRCM_RATE_12M, BRCM_RATE_18M,
1831                 BRCM_RATE_24M, BRCM_RATE_36M, BRCM_RATE_48M, BRCM_RATE_54M
1832         };
1833         u16 entry_ptr;
1834         u16 pctl1;
1835         uint i;
1836
1837         if (!BRCMS_PHY_11N_CAP(wlc_hw->band))
1838                 return;
1839
1840         /* walk the phy rate table and update the entries */
1841         for (i = 0; i < ARRAY_SIZE(rates); i++) {
1842                 rate = rates[i];
1843
1844                 entry_ptr = brcms_b_ofdm_ratetable_offset(wlc_hw, rate);
1845
1846                 /* read the SHM Rate Table entry OFDM PCTL1 values */
1847                 pctl1 =
1848                     brcms_b_read_shm(wlc_hw, entry_ptr + M_RT_OFDM_PCTL1_POS);
1849
1850                 /* modify the value */
1851                 pctl1 &= ~PHY_TXC1_MODE_MASK;
1852                 pctl1 |= (wlc_hw->hw_stf_ss_opmode << PHY_TXC1_MODE_SHIFT);
1853
1854                 /* Update the SHM Rate Table entry OFDM PCTL1 values */
1855                 brcms_b_write_shm(wlc_hw, entry_ptr + M_RT_OFDM_PCTL1_POS,
1856                                    pctl1);
1857         }
1858 }
1859
1860 /* band-specific init */
1861 static void brcms_b_bsinit(struct brcms_c_info *wlc, u16 chanspec)
1862 {
1863         struct brcms_hardware *wlc_hw = wlc->hw;
1864
1865         BCMMSG(wlc->wiphy, "wl%d: bandunit %d\n", wlc_hw->unit,
1866                 wlc_hw->band->bandunit);
1867
1868         brcms_c_ucode_bsinit(wlc_hw);
1869
1870         wlc_phy_init(wlc_hw->band->pi, chanspec);
1871
1872         brcms_c_ucode_txant_set(wlc_hw);
1873
1874         /*
1875          * cwmin is band-specific, update hardware
1876          * with value for current band
1877          */
1878         brcms_b_set_cwmin(wlc_hw, wlc_hw->band->CWmin);
1879         brcms_b_set_cwmax(wlc_hw, wlc_hw->band->CWmax);
1880
1881         brcms_b_update_slot_timing(wlc_hw,
1882                                    wlc_hw->band->bandtype == BRCM_BAND_5G ?
1883                                    true : wlc_hw->shortslot);
1884
1885         /* write phytype and phyvers */
1886         brcms_b_write_shm(wlc_hw, M_PHYTYPE, (u16) wlc_hw->band->phytype);
1887         brcms_b_write_shm(wlc_hw, M_PHYVER, (u16) wlc_hw->band->phyrev);
1888
1889         /*
1890          * initialize the txphyctl1 rate table since
1891          * shmem is shared between bands
1892          */
1893         brcms_upd_ofdm_pctl1_table(wlc_hw);
1894
1895         brcms_b_upd_synthpu(wlc_hw);
1896 }
1897
1898 /* Perform a soft reset of the PHY PLL */
1899 void brcms_b_core_phypll_reset(struct brcms_hardware *wlc_hw)
1900 {
1901         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
1902
1903         ai_corereg(wlc_hw->sih, SI_CC_IDX,
1904                    offsetof(struct chipcregs, chipcontrol_addr), ~0, 0);
1905         udelay(1);
1906         ai_corereg(wlc_hw->sih, SI_CC_IDX,
1907                    offsetof(struct chipcregs, chipcontrol_data), 0x4, 0);
1908         udelay(1);
1909         ai_corereg(wlc_hw->sih, SI_CC_IDX,
1910                    offsetof(struct chipcregs, chipcontrol_data), 0x4, 4);
1911         udelay(1);
1912         ai_corereg(wlc_hw->sih, SI_CC_IDX,
1913                    offsetof(struct chipcregs, chipcontrol_data), 0x4, 0);
1914         udelay(1);
1915 }
1916
1917 /* light way to turn on phy clock without reset for NPHY only
1918  *  refer to brcms_b_core_phy_clk for full version
1919  */
1920 void brcms_b_phyclk_fgc(struct brcms_hardware *wlc_hw, bool clk)
1921 {
1922         /* support(necessary for NPHY and HYPHY) only */
1923         if (!BRCMS_ISNPHY(wlc_hw->band))
1924                 return;
1925
1926         if (ON == clk)
1927                 ai_core_cflags(wlc_hw->sih, SICF_FGC, SICF_FGC);
1928         else
1929                 ai_core_cflags(wlc_hw->sih, SICF_FGC, 0);
1930
1931 }
1932
1933 void brcms_b_macphyclk_set(struct brcms_hardware *wlc_hw, bool clk)
1934 {
1935         if (ON == clk)
1936                 ai_core_cflags(wlc_hw->sih, SICF_MPCLKE, SICF_MPCLKE);
1937         else
1938                 ai_core_cflags(wlc_hw->sih, SICF_MPCLKE, 0);
1939 }
1940
1941 void brcms_b_phy_reset(struct brcms_hardware *wlc_hw)
1942 {
1943         struct brcms_phy_pub *pih = wlc_hw->band->pi;
1944         u32 phy_bw_clkbits;
1945         bool phy_in_reset = false;
1946
1947         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
1948
1949         if (pih == NULL)
1950                 return;
1951
1952         phy_bw_clkbits = wlc_phy_clk_bwbits(wlc_hw->band->pi);
1953
1954         /* Specific reset sequence required for NPHY rev 3 and 4 */
1955         if (BRCMS_ISNPHY(wlc_hw->band) && NREV_GE(wlc_hw->band->phyrev, 3) &&
1956             NREV_LE(wlc_hw->band->phyrev, 4)) {
1957                 /* Set the PHY bandwidth */
1958                 ai_core_cflags(wlc_hw->sih, SICF_BWMASK, phy_bw_clkbits);
1959
1960                 udelay(1);
1961
1962                 /* Perform a soft reset of the PHY PLL */
1963                 brcms_b_core_phypll_reset(wlc_hw);
1964
1965                 /* reset the PHY */
1966                 ai_core_cflags(wlc_hw->sih, (SICF_PRST | SICF_PCLKE),
1967                                (SICF_PRST | SICF_PCLKE));
1968                 phy_in_reset = true;
1969         } else {
1970                 ai_core_cflags(wlc_hw->sih,
1971                                (SICF_PRST | SICF_PCLKE | SICF_BWMASK),
1972                                (SICF_PRST | SICF_PCLKE | phy_bw_clkbits));
1973         }
1974
1975         udelay(2);
1976         brcms_b_core_phy_clk(wlc_hw, ON);
1977
1978         if (pih)
1979                 wlc_phy_anacore(pih, ON);
1980 }
1981
1982 /* switch to and initialize new band */
1983 static void brcms_b_setband(struct brcms_hardware *wlc_hw, uint bandunit,
1984                             u16 chanspec) {
1985         struct brcms_c_info *wlc = wlc_hw->wlc;
1986         u32 macintmask;
1987
1988         /* Enable the d11 core before accessing it */
1989         if (!ai_iscoreup(wlc_hw->sih)) {
1990                 ai_core_reset(wlc_hw->sih, 0, 0);
1991                 brcms_c_mctrl_reset(wlc_hw);
1992         }
1993
1994         macintmask = brcms_c_setband_inact(wlc, bandunit);
1995
1996         if (!wlc_hw->up)
1997                 return;
1998
1999         brcms_b_core_phy_clk(wlc_hw, ON);
2000
2001         /* band-specific initializations */
2002         brcms_b_bsinit(wlc, chanspec);
2003
2004         /*
2005          * If there are any pending software interrupt bits,
2006          * then replace these with a harmless nonzero value
2007          * so brcms_c_dpc() will re-enable interrupts when done.
2008          */
2009         if (wlc->macintstatus)
2010                 wlc->macintstatus = MI_DMAINT;
2011
2012         /* restore macintmask */
2013         brcms_intrsrestore(wlc->wl, macintmask);
2014
2015         /* ucode should still be suspended.. */
2016         WARN_ON((R_REG(&wlc_hw->regs->maccontrol) & MCTL_EN_MAC) != 0);
2017 }
2018
2019 /* low-level band switch utility routine */
2020 void brcms_c_setxband(struct brcms_hardware *wlc_hw, uint bandunit)
2021 {
2022         BCMMSG(wlc_hw->wlc->wiphy, "wl%d: bandunit %d\n", wlc_hw->unit,
2023                 bandunit);
2024
2025         wlc_hw->band = wlc_hw->bandstate[bandunit];
2026
2027         /*
2028          * BMAC_NOTE:
2029          *   until we eliminate need for wlc->band refs in low level code
2030          */
2031         wlc_hw->wlc->band = wlc_hw->wlc->bandstate[bandunit];
2032
2033         /* set gmode core flag */
2034         if (wlc_hw->sbclk && !wlc_hw->noreset)
2035                 ai_core_cflags(wlc_hw->sih, SICF_GMODE,
2036                                ((bandunit == 0) ? SICF_GMODE : 0));
2037 }
2038
2039 static bool brcms_c_isgoodchip(struct brcms_hardware *wlc_hw)
2040 {
2041
2042         /* reject unsupported corerev */
2043         if (!CONF_HAS(D11CONF, wlc_hw->corerev)) {
2044                 wiphy_err(wlc_hw->wlc->wiphy, "unsupported core rev %d\n",
2045                           wlc_hw->corerev);
2046                 return false;
2047         }
2048
2049         return true;
2050 }
2051
2052 /* Validate some board info parameters */
2053 static bool brcms_c_validboardtype(struct brcms_hardware *wlc_hw)
2054 {
2055         uint boardrev = wlc_hw->boardrev;
2056
2057         /* 4 bits each for board type, major, minor, and tiny version */
2058         uint brt = (boardrev & 0xf000) >> 12;
2059         uint b0 = (boardrev & 0xf00) >> 8;
2060         uint b1 = (boardrev & 0xf0) >> 4;
2061         uint b2 = boardrev & 0xf;
2062
2063         /* voards from other vendors are always considered valid */
2064         if (wlc_hw->sih->boardvendor != PCI_VENDOR_ID_BROADCOM)
2065                 return true;
2066
2067         /* do some boardrev sanity checks when boardvendor is Broadcom */
2068         if (boardrev == 0)
2069                 return false;
2070
2071         if (boardrev <= 0xff)
2072                 return true;
2073
2074         if ((brt > 2) || (brt == 0) || (b0 > 9) || (b0 == 0) || (b1 > 9)
2075                 || (b2 > 9))
2076                 return false;
2077
2078         return true;
2079 }
2080
2081 static char *brcms_c_get_macaddr(struct brcms_hardware *wlc_hw)
2082 {
2083         const char *varname = "macaddr";
2084         char *macaddr;
2085
2086         /* If macaddr exists, use it (Sromrev4, CIS, ...). */
2087         macaddr = getvar(wlc_hw->vars, varname);
2088         if (macaddr != NULL)
2089                 return macaddr;
2090
2091         if (wlc_hw->_nbands > 1)
2092                 varname = "et1macaddr";
2093         else
2094                 varname = "il0macaddr";
2095
2096         macaddr = getvar(wlc_hw->vars, varname);
2097         if (macaddr == NULL)
2098                 wiphy_err(wlc_hw->wlc->wiphy, "wl%d: wlc_get_macaddr: macaddr "
2099                           "getvar(%s) not found\n", wlc_hw->unit, varname);
2100
2101         return macaddr;
2102 }
2103
2104 /* power both the pll and external oscillator on/off */
2105 static void brcms_b_xtal(struct brcms_hardware *wlc_hw, bool want)
2106 {
2107         BCMMSG(wlc_hw->wlc->wiphy, "wl%d: want %d\n", wlc_hw->unit, want);
2108
2109         /*
2110          * dont power down if plldown is false or
2111          * we must poll hw radio disable
2112          */
2113         if (!want && wlc_hw->pllreq)
2114                 return;
2115
2116         if (wlc_hw->sih)
2117                 ai_clkctl_xtal(wlc_hw->sih, XTAL | PLL, want);
2118
2119         wlc_hw->sbclk = want;
2120         if (!wlc_hw->sbclk) {
2121                 wlc_hw->clk = false;
2122                 if (wlc_hw->band && wlc_hw->band->pi)
2123                         wlc_phy_hw_clk_state_upd(wlc_hw->band->pi, false);
2124         }
2125 }
2126
2127 /*
2128  * Return true if radio is disabled, otherwise false.
2129  * hw radio disable signal is an external pin, users activate it asynchronously
2130  * this function could be called when driver is down and w/o clock
2131  * it operates on different registers depending on corerev and boardflag.
2132  */
2133 static bool brcms_b_radio_read_hwdisabled(struct brcms_hardware *wlc_hw)
2134 {
2135         bool v, clk, xtal;
2136         u32 resetbits = 0, flags = 0;
2137
2138         xtal = wlc_hw->sbclk;
2139         if (!xtal)
2140                 brcms_b_xtal(wlc_hw, ON);
2141
2142         /* may need to take core out of reset first */
2143         clk = wlc_hw->clk;
2144         if (!clk) {
2145                 /*
2146                  * mac no longer enables phyclk automatically when driver
2147                  * accesses phyreg throughput mac. This can be skipped since
2148                  * only mac reg is accessed below
2149                  */
2150                 flags |= SICF_PCLKE;
2151
2152                 /*
2153                  * AI chip doesn't restore bar0win2 on
2154                  * hibernation/resume, need sw fixup
2155                  */
2156                 if ((wlc_hw->sih->chip == BCM43224_CHIP_ID) ||
2157                     (wlc_hw->sih->chip == BCM43225_CHIP_ID))
2158                         wlc_hw->regs = (struct d11regs *)
2159                                         ai_setcore(wlc_hw->sih, D11_CORE_ID, 0);
2160                 ai_core_reset(wlc_hw->sih, flags, resetbits);
2161                 brcms_c_mctrl_reset(wlc_hw);
2162         }
2163
2164         v = ((R_REG(&wlc_hw->regs->phydebug) & PDBG_RFD) != 0);
2165
2166         /* put core back into reset */
2167         if (!clk)
2168                 ai_core_disable(wlc_hw->sih, 0);
2169
2170         if (!xtal)
2171                 brcms_b_xtal(wlc_hw, OFF);
2172
2173         return v;
2174 }
2175
2176 static bool wlc_dma_rxreset(struct brcms_hardware *wlc_hw, uint fifo)
2177 {
2178         struct dma_pub *di = wlc_hw->di[fifo];
2179         return dma_rxreset(di);
2180 }
2181
2182 /* d11 core reset
2183  *   ensure fask clock during reset
2184  *   reset dma
2185  *   reset d11(out of reset)
2186  *   reset phy(out of reset)
2187  *   clear software macintstatus for fresh new start
2188  * one testing hack wlc_hw->noreset will bypass the d11/phy reset
2189  */
2190 void brcms_b_corereset(struct brcms_hardware *wlc_hw, u32 flags)
2191 {
2192         struct d11regs *regs;
2193         uint i;
2194         bool fastclk;
2195         u32 resetbits = 0;
2196
2197         if (flags == BRCMS_USE_COREFLAGS)
2198                 flags = (wlc_hw->band->pi ? wlc_hw->band->core_flags : 0);
2199
2200         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
2201
2202         regs = wlc_hw->regs;
2203
2204         /* request FAST clock if not on  */
2205         fastclk = wlc_hw->forcefastclk;
2206         if (!fastclk)
2207                 brcms_b_clkctl_clk(wlc_hw, CLK_FAST);
2208
2209         /* reset the dma engines except first time thru */
2210         if (ai_iscoreup(wlc_hw->sih)) {
2211                 for (i = 0; i < NFIFO; i++)
2212                         if ((wlc_hw->di[i]) && (!dma_txreset(wlc_hw->di[i])))
2213                                 wiphy_err(wlc_hw->wlc->wiphy, "wl%d: %s: "
2214                                           "dma_txreset[%d]: cannot stop dma\n",
2215                                            wlc_hw->unit, __func__, i);
2216
2217                 if ((wlc_hw->di[RX_FIFO])
2218                     && (!wlc_dma_rxreset(wlc_hw, RX_FIFO)))
2219                         wiphy_err(wlc_hw->wlc->wiphy, "wl%d: %s: dma_rxreset"
2220                                   "[%d]: cannot stop dma\n",
2221                                   wlc_hw->unit, __func__, RX_FIFO);
2222         }
2223         /* if noreset, just stop the psm and return */
2224         if (wlc_hw->noreset) {
2225                 wlc_hw->wlc->macintstatus = 0;  /* skip wl_dpc after down */
2226                 brcms_b_mctrl(wlc_hw, MCTL_PSM_RUN | MCTL_EN_MAC, 0);
2227                 return;
2228         }
2229
2230         /*
2231          * mac no longer enables phyclk automatically when driver accesses
2232          * phyreg throughput mac, AND phy_reset is skipped at early stage when
2233          * band->pi is invalid. need to enable PHY CLK
2234          */
2235         flags |= SICF_PCLKE;
2236
2237         /*
2238          * reset the core
2239          * In chips with PMU, the fastclk request goes through d11 core
2240          * reg 0x1e0, which is cleared by the core_reset. have to re-request it.
2241          *
2242          * This adds some delay and we can optimize it by also requesting
2243          * fastclk through chipcommon during this period if necessary. But
2244          * that has to work coordinate with other driver like mips/arm since
2245          * they may touch chipcommon as well.
2246          */
2247         wlc_hw->clk = false;
2248         ai_core_reset(wlc_hw->sih, flags, resetbits);
2249         wlc_hw->clk = true;
2250         if (wlc_hw->band && wlc_hw->band->pi)
2251                 wlc_phy_hw_clk_state_upd(wlc_hw->band->pi, true);
2252
2253         brcms_c_mctrl_reset(wlc_hw);
2254
2255         if (wlc_hw->sih->cccaps & CC_CAP_PMU)
2256                 brcms_b_clkctl_clk(wlc_hw, CLK_FAST);
2257
2258         brcms_b_phy_reset(wlc_hw);
2259
2260         /* turn on PHY_PLL */
2261         brcms_b_core_phypll_ctl(wlc_hw, true);
2262
2263         /* clear sw intstatus */
2264         wlc_hw->wlc->macintstatus = 0;
2265
2266         /* restore the clk setting */
2267         if (!fastclk)
2268                 brcms_b_clkctl_clk(wlc_hw, CLK_DYNAMIC);
2269 }
2270
2271 /* txfifo sizes needs to be modified(increased) since the newer cores
2272  * have more memory.
2273  */
2274 static void brcms_b_corerev_fifofixup(struct brcms_hardware *wlc_hw)
2275 {
2276         struct d11regs *regs = wlc_hw->regs;
2277         u16 fifo_nu;
2278         u16 txfifo_startblk = TXFIFO_START_BLK, txfifo_endblk;
2279         u16 txfifo_def, txfifo_def1;
2280         u16 txfifo_cmd;
2281
2282         /* tx fifos start at TXFIFO_START_BLK from the Base address */
2283         txfifo_startblk = TXFIFO_START_BLK;
2284
2285         /* sequence of operations:  reset fifo, set fifo size, reset fifo */
2286         for (fifo_nu = 0; fifo_nu < NFIFO; fifo_nu++) {
2287
2288                 txfifo_endblk = txfifo_startblk + wlc_hw->xmtfifo_sz[fifo_nu];
2289                 txfifo_def = (txfifo_startblk & 0xff) |
2290                     (((txfifo_endblk - 1) & 0xff) << TXFIFO_FIFOTOP_SHIFT);
2291                 txfifo_def1 = ((txfifo_startblk >> 8) & 0x1) |
2292                     ((((txfifo_endblk -
2293                         1) >> 8) & 0x1) << TXFIFO_FIFOTOP_SHIFT);
2294                 txfifo_cmd =
2295                     TXFIFOCMD_RESET_MASK | (fifo_nu << TXFIFOCMD_FIFOSEL_SHIFT);
2296
2297                 W_REG(&regs->xmtfifocmd, txfifo_cmd);
2298                 W_REG(&regs->xmtfifodef, txfifo_def);
2299                 W_REG(&regs->xmtfifodef1, txfifo_def1);
2300
2301                 W_REG(&regs->xmtfifocmd, txfifo_cmd);
2302
2303                 txfifo_startblk += wlc_hw->xmtfifo_sz[fifo_nu];
2304         }
2305         /*
2306          * need to propagate to shm location to be in sync since ucode/hw won't
2307          * do this
2308          */
2309         brcms_b_write_shm(wlc_hw, M_FIFOSIZE0,
2310                            wlc_hw->xmtfifo_sz[TX_AC_BE_FIFO]);
2311         brcms_b_write_shm(wlc_hw, M_FIFOSIZE1,
2312                            wlc_hw->xmtfifo_sz[TX_AC_VI_FIFO]);
2313         brcms_b_write_shm(wlc_hw, M_FIFOSIZE2,
2314                            ((wlc_hw->xmtfifo_sz[TX_AC_VO_FIFO] << 8) | wlc_hw->
2315                             xmtfifo_sz[TX_AC_BK_FIFO]));
2316         brcms_b_write_shm(wlc_hw, M_FIFOSIZE3,
2317                            ((wlc_hw->xmtfifo_sz[TX_ATIM_FIFO] << 8) | wlc_hw->
2318                             xmtfifo_sz[TX_BCMC_FIFO]));
2319 }
2320
2321 /* This function is used for changing the tsf frac register
2322  * If spur avoidance mode is off, the mac freq will be 80/120/160Mhz
2323  * If spur avoidance mode is on1, the mac freq will be 82/123/164Mhz
2324  * If spur avoidance mode is on2, the mac freq will be 84/126/168Mhz
2325  * HTPHY Formula is 2^26/freq(MHz) e.g.
2326  * For spuron2 - 126MHz -> 2^26/126 = 532610.0
2327  *  - 532610 = 0x82082 => tsf_clk_frac_h = 0x8, tsf_clk_frac_l = 0x2082
2328  * For spuron: 123MHz -> 2^26/123    = 545600.5
2329  *  - 545601 = 0x85341 => tsf_clk_frac_h = 0x8, tsf_clk_frac_l = 0x5341
2330  * For spur off: 120MHz -> 2^26/120    = 559240.5
2331  *  - 559241 = 0x88889 => tsf_clk_frac_h = 0x8, tsf_clk_frac_l = 0x8889
2332  */
2333
2334 void brcms_b_switch_macfreq(struct brcms_hardware *wlc_hw, u8 spurmode)
2335 {
2336         struct d11regs *regs;
2337         regs = wlc_hw->regs;
2338
2339         if ((wlc_hw->sih->chip == BCM43224_CHIP_ID) ||
2340             (wlc_hw->sih->chip == BCM43225_CHIP_ID)) {
2341                 if (spurmode == WL_SPURAVOID_ON2) {     /* 126Mhz */
2342                         W_REG(&regs->tsf_clk_frac_l, 0x2082);
2343                         W_REG(&regs->tsf_clk_frac_h, 0x8);
2344                 } else if (spurmode == WL_SPURAVOID_ON1) {      /* 123Mhz */
2345                         W_REG(&regs->tsf_clk_frac_l, 0x5341);
2346                         W_REG(&regs->tsf_clk_frac_h, 0x8);
2347                 } else {        /* 120Mhz */
2348                         W_REG(&regs->tsf_clk_frac_l, 0x8889);
2349                         W_REG(&regs->tsf_clk_frac_h, 0x8);
2350                 }
2351         } else if (BRCMS_ISLCNPHY(wlc_hw->band)) {
2352                 if (spurmode == WL_SPURAVOID_ON1) {     /* 82Mhz */
2353                         W_REG(&regs->tsf_clk_frac_l, 0x7CE0);
2354                         W_REG(&regs->tsf_clk_frac_h, 0xC);
2355                 } else {        /* 80Mhz */
2356                         W_REG(&regs->tsf_clk_frac_l, 0xCCCD);
2357                         W_REG(&regs->tsf_clk_frac_h, 0xC);
2358                 }
2359         }
2360 }
2361
2362 /* Initialize GPIOs that are controlled by D11 core */
2363 static void brcms_c_gpio_init(struct brcms_c_info *wlc)
2364 {
2365         struct brcms_hardware *wlc_hw = wlc->hw;
2366         struct d11regs *regs;
2367         u32 gc, gm;
2368
2369         regs = wlc_hw->regs;
2370
2371         /* use GPIO select 0 to get all gpio signals from the gpio out reg */
2372         brcms_b_mctrl(wlc_hw, MCTL_GPOUT_SEL_MASK, 0);
2373
2374         /*
2375          * Common GPIO setup:
2376          *      G0 = LED 0 = WLAN Activity
2377          *      G1 = LED 1 = WLAN 2.4 GHz Radio State
2378          *      G2 = LED 2 = WLAN 5 GHz Radio State
2379          *      G4 = radio disable input (HI enabled, LO disabled)
2380          */
2381
2382         gc = gm = 0;
2383
2384         /* Allocate GPIOs for mimo antenna diversity feature */
2385         if (wlc_hw->antsel_type == ANTSEL_2x3) {
2386                 /* Enable antenna diversity, use 2x3 mode */
2387                 brcms_b_mhf(wlc_hw, MHF3, MHF3_ANTSEL_EN,
2388                              MHF3_ANTSEL_EN, BRCM_BAND_ALL);
2389                 brcms_b_mhf(wlc_hw, MHF3, MHF3_ANTSEL_MODE,
2390                              MHF3_ANTSEL_MODE, BRCM_BAND_ALL);
2391
2392                 /* init superswitch control */
2393                 wlc_phy_antsel_init(wlc_hw->band->pi, false);
2394
2395         } else if (wlc_hw->antsel_type == ANTSEL_2x4) {
2396                 gm |= gc |= (BOARD_GPIO_12 | BOARD_GPIO_13);
2397                 /*
2398                  * The board itself is powered by these GPIOs
2399                  * (when not sending pattern) so set them high
2400                  */
2401                 OR_REG(&regs->psm_gpio_oe,
2402                        (BOARD_GPIO_12 | BOARD_GPIO_13));
2403                 OR_REG(&regs->psm_gpio_out,
2404                        (BOARD_GPIO_12 | BOARD_GPIO_13));
2405
2406                 /* Enable antenna diversity, use 2x4 mode */
2407                 brcms_b_mhf(wlc_hw, MHF3, MHF3_ANTSEL_EN,
2408                              MHF3_ANTSEL_EN, BRCM_BAND_ALL);
2409                 brcms_b_mhf(wlc_hw, MHF3, MHF3_ANTSEL_MODE, 0,
2410                              BRCM_BAND_ALL);
2411
2412                 /* Configure the desired clock to be 4Mhz */
2413                 brcms_b_write_shm(wlc_hw, M_ANTSEL_CLKDIV,
2414                                    ANTSEL_CLKDIV_4MHZ);
2415         }
2416
2417         /*
2418          * gpio 9 controls the PA. ucode is responsible
2419          * for wiggling out and oe
2420          */
2421         if (wlc_hw->boardflags & BFL_PACTRL)
2422                 gm |= gc |= BOARD_GPIO_PACTRL;
2423
2424         /* apply to gpiocontrol register */
2425         ai_gpiocontrol(wlc_hw->sih, gm, gc, GPIO_DRV_PRIORITY);
2426 }
2427
2428 static void brcms_ucode_write(struct brcms_hardware *wlc_hw, const u32 ucode[],
2429                               const uint nbytes) {
2430         struct d11regs *regs = wlc_hw->regs;
2431         uint i;
2432         uint count;
2433
2434         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
2435
2436         count = (nbytes / sizeof(u32));
2437
2438         W_REG(&regs->objaddr, (OBJADDR_AUTO_INC | OBJADDR_UCM_SEL));
2439         (void)R_REG(&regs->objaddr);
2440         for (i = 0; i < count; i++)
2441                 W_REG(&regs->objdata, le32_to_cpu(ucode[i]));
2442
2443 }
2444
2445 static void brcms_ucode_download(struct brcms_hardware *wlc_hw)
2446 {
2447         struct brcms_c_info *wlc;
2448         struct brcms_ucode *ucode = &wlc_hw->wlc->wl->ucode;
2449
2450         wlc = wlc_hw->wlc;
2451
2452         if (wlc_hw->ucode_loaded)
2453                 return;
2454
2455         if (D11REV_IS(wlc_hw->corerev, 23)) {
2456                 if (BRCMS_ISNPHY(wlc_hw->band)) {
2457                         brcms_ucode_write(wlc_hw, ucode->bcm43xx_16_mimo,
2458                                           ucode->bcm43xx_16_mimosz);
2459                         wlc_hw->ucode_loaded = true;
2460                 } else
2461                         wiphy_err(wlc->wiphy, "%s: wl%d: unsupported phy in "
2462                                   "corerev %d\n",
2463                                   __func__, wlc_hw->unit, wlc_hw->corerev);
2464         } else if (D11REV_IS(wlc_hw->corerev, 24)) {
2465                 if (BRCMS_ISLCNPHY(wlc_hw->band)) {
2466                         brcms_ucode_write(wlc_hw, ucode->bcm43xx_24_lcn,
2467                                           ucode->bcm43xx_24_lcnsz);
2468                         wlc_hw->ucode_loaded = true;
2469                 } else {
2470                         wiphy_err(wlc->wiphy, "%s: wl%d: unsupported phy in "
2471                                   "corerev %d\n",
2472                                   __func__, wlc_hw->unit, wlc_hw->corerev);
2473                 }
2474         }
2475 }
2476
2477 void brcms_b_txant_set(struct brcms_hardware *wlc_hw, u16 phytxant)
2478 {
2479         /* update sw state */
2480         wlc_hw->bmac_phytxant = phytxant;
2481
2482         /* push to ucode if up */
2483         if (!wlc_hw->up)
2484                 return;
2485         brcms_c_ucode_txant_set(wlc_hw);
2486
2487 }
2488
2489 u16 brcms_b_get_txant(struct brcms_hardware *wlc_hw)
2490 {
2491         return (u16) wlc_hw->wlc->stf->txant;
2492 }
2493
2494 void brcms_b_antsel_type_set(struct brcms_hardware *wlc_hw, u8 antsel_type)
2495 {
2496         wlc_hw->antsel_type = antsel_type;
2497
2498         /* Update the antsel type for phy module to use */
2499         wlc_phy_antsel_type_set(wlc_hw->band->pi, antsel_type);
2500 }
2501
2502 static void brcms_b_fifoerrors(struct brcms_hardware *wlc_hw)
2503 {
2504         bool fatal = false;
2505         uint unit;
2506         uint intstatus, idx;
2507         struct d11regs *regs = wlc_hw->regs;
2508         struct wiphy *wiphy = wlc_hw->wlc->wiphy;
2509
2510         unit = wlc_hw->unit;
2511
2512         for (idx = 0; idx < NFIFO; idx++) {
2513                 /* read intstatus register and ignore any non-error bits */
2514                 intstatus =
2515                     R_REG(&regs->intctrlregs[idx].intstatus) & I_ERRORS;
2516                 if (!intstatus)
2517                         continue;
2518
2519                 BCMMSG(wlc_hw->wlc->wiphy, "wl%d: intstatus%d 0x%x\n",
2520                         unit, idx, intstatus);
2521
2522                 if (intstatus & I_RO) {
2523                         wiphy_err(wiphy, "wl%d: fifo %d: receive fifo "
2524                                   "overflow\n", unit, idx);
2525                         fatal = true;
2526                 }
2527
2528                 if (intstatus & I_PC) {
2529                         wiphy_err(wiphy, "wl%d: fifo %d: descriptor error\n",
2530                                  unit, idx);
2531                         fatal = true;
2532                 }
2533
2534                 if (intstatus & I_PD) {
2535                         wiphy_err(wiphy, "wl%d: fifo %d: data error\n", unit,
2536                                   idx);
2537                         fatal = true;
2538                 }
2539
2540                 if (intstatus & I_DE) {
2541                         wiphy_err(wiphy, "wl%d: fifo %d: descriptor protocol "
2542                                   "error\n", unit, idx);
2543                         fatal = true;
2544                 }
2545
2546                 if (intstatus & I_RU)
2547                         wiphy_err(wiphy, "wl%d: fifo %d: receive descriptor "
2548                                   "underflow\n", idx, unit);
2549
2550                 if (intstatus & I_XU) {
2551                         wiphy_err(wiphy, "wl%d: fifo %d: transmit fifo "
2552                                   "underflow\n", idx, unit);
2553                         fatal = true;
2554                 }
2555
2556                 if (fatal) {
2557                         brcms_c_fatal_error(wlc_hw->wlc);       /* big hammer */
2558                         break;
2559                 } else
2560                         W_REG(&regs->intctrlregs[idx].intstatus,
2561                               intstatus);
2562         }
2563 }
2564
2565 void brcms_c_intrson(struct brcms_c_info *wlc)
2566 {
2567         struct brcms_hardware *wlc_hw = wlc->hw;
2568         wlc->macintmask = wlc->defmacintmask;
2569         W_REG(&wlc_hw->regs->macintmask, wlc->macintmask);
2570 }
2571
2572 /*
2573  * callback for siutils.c, which has only wlc handler, no wl they both check
2574  * up, not only because there is no need to off/restore d11 interrupt but also
2575  * because per-port code may require sync with valid interrupt.
2576  */
2577 static u32 brcms_c_wlintrsoff(struct brcms_c_info *wlc)
2578 {
2579         if (!wlc->hw->up)
2580                 return 0;
2581
2582         return brcms_intrsoff(wlc->wl);
2583 }
2584
2585 static void brcms_c_wlintrsrestore(struct brcms_c_info *wlc, u32 macintmask)
2586 {
2587         if (!wlc->hw->up)
2588                 return;
2589
2590         brcms_intrsrestore(wlc->wl, macintmask);
2591 }
2592
2593 u32 brcms_c_intrsoff(struct brcms_c_info *wlc)
2594 {
2595         struct brcms_hardware *wlc_hw = wlc->hw;
2596         u32 macintmask;
2597
2598         if (!wlc_hw->clk)
2599                 return 0;
2600
2601         macintmask = wlc->macintmask;   /* isr can still happen */
2602
2603         W_REG(&wlc_hw->regs->macintmask, 0);
2604         (void)R_REG(&wlc_hw->regs->macintmask); /* sync readback */
2605         udelay(1);              /* ensure int line is no longer driven */
2606         wlc->macintmask = 0;
2607
2608         /* return previous macintmask; resolve race between us and our isr */
2609         return wlc->macintstatus ? 0 : macintmask;
2610 }
2611
2612 void brcms_c_intrsrestore(struct brcms_c_info *wlc, u32 macintmask)
2613 {
2614         struct brcms_hardware *wlc_hw = wlc->hw;
2615         if (!wlc_hw->clk)
2616                 return;
2617
2618         wlc->macintmask = macintmask;
2619         W_REG(&wlc_hw->regs->macintmask, wlc->macintmask);
2620 }
2621
2622 static void brcms_b_tx_fifo_suspend(struct brcms_hardware *wlc_hw,
2623                                     uint tx_fifo)
2624 {
2625         u8 fifo = 1 << tx_fifo;
2626
2627         /* Two clients of this code, 11h Quiet period and scanning. */
2628
2629         /* only suspend if not already suspended */
2630         if ((wlc_hw->suspended_fifos & fifo) == fifo)
2631                 return;
2632
2633         /* force the core awake only if not already */
2634         if (wlc_hw->suspended_fifos == 0)
2635                 brcms_c_ucode_wake_override_set(wlc_hw,
2636                                                 BRCMS_WAKE_OVERRIDE_TXFIFO);
2637
2638         wlc_hw->suspended_fifos |= fifo;
2639
2640         if (wlc_hw->di[tx_fifo]) {
2641                 /*
2642                  * Suspending AMPDU transmissions in the middle can cause
2643                  * underflow which may result in mismatch between ucode and
2644                  * driver so suspend the mac before suspending the FIFO
2645                  */
2646                 if (BRCMS_PHY_11N_CAP(wlc_hw->band))
2647                         brcms_c_suspend_mac_and_wait(wlc_hw->wlc);
2648
2649                 dma_txsuspend(wlc_hw->di[tx_fifo]);
2650
2651                 if (BRCMS_PHY_11N_CAP(wlc_hw->band))
2652                         brcms_c_enable_mac(wlc_hw->wlc);
2653         }
2654 }
2655
2656 static void brcms_b_tx_fifo_resume(struct brcms_hardware *wlc_hw,
2657                                    uint tx_fifo)
2658 {
2659         /* BMAC_NOTE: BRCMS_TX_FIFO_ENAB is done in brcms_c_dpc() for DMA case
2660          * but need to be done here for PIO otherwise the watchdog will catch
2661          * the inconsistency and fire
2662          */
2663         /* Two clients of this code, 11h Quiet period and scanning. */
2664         if (wlc_hw->di[tx_fifo])
2665                 dma_txresume(wlc_hw->di[tx_fifo]);
2666
2667         /* allow core to sleep again */
2668         if (wlc_hw->suspended_fifos == 0)
2669                 return;
2670         else {
2671                 wlc_hw->suspended_fifos &= ~(1 << tx_fifo);
2672                 if (wlc_hw->suspended_fifos == 0)
2673                         brcms_c_ucode_wake_override_clear(wlc_hw,
2674                                                 BRCMS_WAKE_OVERRIDE_TXFIFO);
2675         }
2676 }
2677
2678 static void brcms_b_mute(struct brcms_hardware *wlc_hw, bool on, u32 flags)
2679 {
2680         u8 null_ether_addr[ETH_ALEN] = {0, 0, 0, 0, 0, 0};
2681
2682         if (on) {
2683                 /* suspend tx fifos */
2684                 brcms_b_tx_fifo_suspend(wlc_hw, TX_DATA_FIFO);
2685                 brcms_b_tx_fifo_suspend(wlc_hw, TX_CTL_FIFO);
2686                 brcms_b_tx_fifo_suspend(wlc_hw, TX_AC_BK_FIFO);
2687                 brcms_b_tx_fifo_suspend(wlc_hw, TX_AC_VI_FIFO);
2688
2689                 /* zero the address match register so we do not send ACKs */
2690                 brcms_b_set_addrmatch(wlc_hw, RCM_MAC_OFFSET,
2691                                        null_ether_addr);
2692         } else {
2693                 /* resume tx fifos */
2694                 brcms_b_tx_fifo_resume(wlc_hw, TX_DATA_FIFO);
2695                 brcms_b_tx_fifo_resume(wlc_hw, TX_CTL_FIFO);
2696                 brcms_b_tx_fifo_resume(wlc_hw, TX_AC_BK_FIFO);
2697                 brcms_b_tx_fifo_resume(wlc_hw, TX_AC_VI_FIFO);
2698
2699                 /* Restore address */
2700                 brcms_b_set_addrmatch(wlc_hw, RCM_MAC_OFFSET,
2701                                        wlc_hw->etheraddr);
2702         }
2703
2704         wlc_phy_mute_upd(wlc_hw->band->pi, on, flags);
2705
2706         if (on)
2707                 brcms_c_ucode_mute_override_set(wlc_hw);
2708         else
2709                 brcms_c_ucode_mute_override_clear(wlc_hw);
2710 }
2711
2712 /*
2713  * Read and clear macintmask and macintstatus and intstatus registers.
2714  * This routine should be called with interrupts off
2715  * Return:
2716  *   -1 if brcms_deviceremoved(wlc) evaluates to true;
2717  *   0 if the interrupt is not for us, or we are in some special cases;
2718  *   device interrupt status bits otherwise.
2719  */
2720 static inline u32 wlc_intstatus(struct brcms_c_info *wlc, bool in_isr)
2721 {
2722         struct brcms_hardware *wlc_hw = wlc->hw;
2723         struct d11regs *regs = wlc_hw->regs;
2724         u32 macintstatus;
2725
2726         /* macintstatus includes a DMA interrupt summary bit */
2727         macintstatus = R_REG(&regs->macintstatus);
2728
2729         BCMMSG(wlc->wiphy, "wl%d: macintstatus: 0x%x\n", wlc_hw->unit,
2730                  macintstatus);
2731
2732         /* detect cardbus removed, in power down(suspend) and in reset */
2733         if (brcms_deviceremoved(wlc))
2734                 return -1;
2735
2736         /* brcms_deviceremoved() succeeds even when the core is still resetting,
2737          * handle that case here.
2738          */
2739         if (macintstatus == 0xffffffff)
2740                 return 0;
2741
2742         /* defer unsolicited interrupts */
2743         macintstatus &= (in_isr ? wlc->macintmask : wlc->defmacintmask);
2744
2745         /* if not for us */
2746         if (macintstatus == 0)
2747                 return 0;
2748
2749         /* interrupts are already turned off for CFE build
2750          * Caution: For CFE Turning off the interrupts again has some undesired
2751          * consequences
2752          */
2753         /* turn off the interrupts */
2754         W_REG(&regs->macintmask, 0);
2755         (void)R_REG(&regs->macintmask); /* sync readback */
2756         wlc->macintmask = 0;
2757
2758         /* clear device interrupts */
2759         W_REG(&regs->macintstatus, macintstatus);
2760
2761         /* MI_DMAINT is indication of non-zero intstatus */
2762         if (macintstatus & MI_DMAINT)
2763                 /*
2764                  * only fifo interrupt enabled is I_RI in
2765                  * RX_FIFO. If MI_DMAINT is set, assume it
2766                  * is set and clear the interrupt.
2767                  */
2768                 W_REG(&regs->intctrlregs[RX_FIFO].intstatus,
2769                       DEF_RXINTMASK);
2770
2771         return macintstatus;
2772 }
2773
2774 /* Update wlc->macintstatus and wlc->intstatus[]. */
2775 /* Return true if they are updated successfully. false otherwise */
2776 bool brcms_c_intrsupd(struct brcms_c_info *wlc)
2777 {
2778         u32 macintstatus;
2779
2780         /* read and clear macintstatus and intstatus registers */
2781         macintstatus = wlc_intstatus(wlc, false);
2782
2783         /* device is removed */
2784         if (macintstatus == 0xffffffff)
2785                 return false;
2786
2787         /* update interrupt status in software */
2788         wlc->macintstatus |= macintstatus;
2789
2790         return true;
2791 }
2792
2793 /*
2794  * First-level interrupt processing.
2795  * Return true if this was our interrupt, false otherwise.
2796  * *wantdpc will be set to true if further brcms_c_dpc() processing is required,
2797  * false otherwise.
2798  */
2799 bool brcms_c_isr(struct brcms_c_info *wlc, bool *wantdpc)
2800 {
2801         struct brcms_hardware *wlc_hw = wlc->hw;
2802         u32 macintstatus;
2803
2804         *wantdpc = false;
2805
2806         if (!wlc_hw->up || !wlc->macintmask)
2807                 return false;
2808
2809         /* read and clear macintstatus and intstatus registers */
2810         macintstatus = wlc_intstatus(wlc, true);
2811
2812         if (macintstatus == 0xffffffff)
2813                 wiphy_err(wlc->wiphy, "DEVICEREMOVED detected in the ISR code"
2814                           " path\n");
2815
2816         /* it is not for us */
2817         if (macintstatus == 0)
2818                 return false;
2819
2820         *wantdpc = true;
2821
2822         /* save interrupt status bits */
2823         wlc->macintstatus = macintstatus;
2824
2825         return true;
2826
2827 }
2828
2829 void brcms_c_suspend_mac_and_wait(struct brcms_c_info *wlc)
2830 {
2831         struct brcms_hardware *wlc_hw = wlc->hw;
2832         struct d11regs *regs = wlc_hw->regs;
2833         u32 mc, mi;
2834         struct wiphy *wiphy = wlc->wiphy;
2835
2836         BCMMSG(wlc->wiphy, "wl%d: bandunit %d\n", wlc_hw->unit,
2837                 wlc_hw->band->bandunit);
2838
2839         /*
2840          * Track overlapping suspend requests
2841          */
2842         wlc_hw->mac_suspend_depth++;
2843         if (wlc_hw->mac_suspend_depth > 1)
2844                 return;
2845
2846         /* force the core awake */
2847         brcms_c_ucode_wake_override_set(wlc_hw, BRCMS_WAKE_OVERRIDE_MACSUSPEND);
2848
2849         mc = R_REG(&regs->maccontrol);
2850
2851         if (mc == 0xffffffff) {
2852                 wiphy_err(wiphy, "wl%d: %s: dead chip\n", wlc_hw->unit,
2853                           __func__);
2854                 brcms_down(wlc->wl);
2855                 return;
2856         }
2857         WARN_ON(mc & MCTL_PSM_JMP_0);
2858         WARN_ON(!(mc & MCTL_PSM_RUN));
2859         WARN_ON(!(mc & MCTL_EN_MAC));
2860
2861         mi = R_REG(&regs->macintstatus);
2862         if (mi == 0xffffffff) {
2863                 wiphy_err(wiphy, "wl%d: %s: dead chip\n", wlc_hw->unit,
2864                           __func__);
2865                 brcms_down(wlc->wl);
2866                 return;
2867         }
2868         WARN_ON(mi & MI_MACSSPNDD);
2869
2870         brcms_b_mctrl(wlc_hw, MCTL_EN_MAC, 0);
2871
2872         SPINWAIT(!(R_REG(&regs->macintstatus) & MI_MACSSPNDD),
2873                  BRCMS_MAX_MAC_SUSPEND);
2874
2875         if (!(R_REG(&regs->macintstatus) & MI_MACSSPNDD)) {
2876                 wiphy_err(wiphy, "wl%d: wlc_suspend_mac_and_wait: waited %d uS"
2877                           " and MI_MACSSPNDD is still not on.\n",
2878                           wlc_hw->unit, BRCMS_MAX_MAC_SUSPEND);
2879                 wiphy_err(wiphy, "wl%d: psmdebug 0x%08x, phydebug 0x%08x, "
2880                           "psm_brc 0x%04x\n", wlc_hw->unit,
2881                           R_REG(&regs->psmdebug),
2882                           R_REG(&regs->phydebug),
2883                           R_REG(&regs->psm_brc));
2884         }
2885
2886         mc = R_REG(&regs->maccontrol);
2887         if (mc == 0xffffffff) {
2888                 wiphy_err(wiphy, "wl%d: %s: dead chip\n", wlc_hw->unit,
2889                           __func__);
2890                 brcms_down(wlc->wl);
2891                 return;
2892         }
2893         WARN_ON(mc & MCTL_PSM_JMP_0);
2894         WARN_ON(!(mc & MCTL_PSM_RUN));
2895         WARN_ON(mc & MCTL_EN_MAC);
2896 }
2897
2898 void brcms_c_enable_mac(struct brcms_c_info *wlc)
2899 {
2900         struct brcms_hardware *wlc_hw = wlc->hw;
2901         struct d11regs *regs = wlc_hw->regs;
2902         u32 mc, mi;
2903
2904         BCMMSG(wlc->wiphy, "wl%d: bandunit %d\n", wlc_hw->unit,
2905                 wlc->band->bandunit);
2906
2907         /*
2908          * Track overlapping suspend requests
2909          */
2910         wlc_hw->mac_suspend_depth--;
2911         if (wlc_hw->mac_suspend_depth > 0)
2912                 return;
2913
2914         mc = R_REG(&regs->maccontrol);
2915         WARN_ON(mc & MCTL_PSM_JMP_0);
2916         WARN_ON(mc & MCTL_EN_MAC);
2917         WARN_ON(!(mc & MCTL_PSM_RUN));
2918
2919         brcms_b_mctrl(wlc_hw, MCTL_EN_MAC, MCTL_EN_MAC);
2920         W_REG(&regs->macintstatus, MI_MACSSPNDD);
2921
2922         mc = R_REG(&regs->maccontrol);
2923         WARN_ON(mc & MCTL_PSM_JMP_0);
2924         WARN_ON(!(mc & MCTL_EN_MAC));
2925         WARN_ON(!(mc & MCTL_PSM_RUN));
2926
2927         mi = R_REG(&regs->macintstatus);
2928         WARN_ON(mi & MI_MACSSPNDD);
2929
2930         brcms_c_ucode_wake_override_clear(wlc_hw,
2931                                           BRCMS_WAKE_OVERRIDE_MACSUSPEND);
2932 }
2933
2934 void brcms_b_band_stf_ss_set(struct brcms_hardware *wlc_hw, u8 stf_mode)
2935 {
2936         wlc_hw->hw_stf_ss_opmode = stf_mode;
2937
2938         if (wlc_hw->clk)
2939                 brcms_upd_ofdm_pctl1_table(wlc_hw);
2940 }
2941
2942 static bool brcms_b_validate_chip_access(struct brcms_hardware *wlc_hw)
2943 {
2944         struct d11regs *regs;
2945         u32 w, val;
2946         struct wiphy *wiphy = wlc_hw->wlc->wiphy;
2947
2948         BCMMSG(wiphy, "wl%d\n", wlc_hw->unit);
2949
2950         regs = wlc_hw->regs;
2951
2952         /* Validate dchip register access */
2953
2954         W_REG(&regs->objaddr, OBJADDR_SHM_SEL | 0);
2955         (void)R_REG(&regs->objaddr);
2956         w = R_REG(&regs->objdata);
2957
2958         /* Can we write and read back a 32bit register? */
2959         W_REG(&regs->objaddr, OBJADDR_SHM_SEL | 0);
2960         (void)R_REG(&regs->objaddr);
2961         W_REG(&regs->objdata, (u32) 0xaa5555aa);
2962
2963         W_REG(&regs->objaddr, OBJADDR_SHM_SEL | 0);
2964         (void)R_REG(&regs->objaddr);
2965         val = R_REG(&regs->objdata);
2966         if (val != (u32) 0xaa5555aa) {
2967                 wiphy_err(wiphy, "wl%d: validate_chip_access: SHM = 0x%x, "
2968                           "expected 0xaa5555aa\n", wlc_hw->unit, val);
2969                 return false;
2970         }
2971
2972         W_REG(&regs->objaddr, OBJADDR_SHM_SEL | 0);
2973         (void)R_REG(&regs->objaddr);
2974         W_REG(&regs->objdata, (u32) 0x55aaaa55);
2975
2976         W_REG(&regs->objaddr, OBJADDR_SHM_SEL | 0);
2977         (void)R_REG(&regs->objaddr);
2978         val = R_REG(&regs->objdata);
2979         if (val != (u32) 0x55aaaa55) {
2980                 wiphy_err(wiphy, "wl%d: validate_chip_access: SHM = 0x%x, "
2981                           "expected 0x55aaaa55\n", wlc_hw->unit, val);
2982                 return false;
2983         }
2984
2985         W_REG(&regs->objaddr, OBJADDR_SHM_SEL | 0);
2986         (void)R_REG(&regs->objaddr);
2987         W_REG(&regs->objdata, w);
2988
2989         /* clear CFPStart */
2990         W_REG(&regs->tsf_cfpstart, 0);
2991
2992         w = R_REG(&regs->maccontrol);
2993         if ((w != (MCTL_IHR_EN | MCTL_WAKE)) &&
2994             (w != (MCTL_IHR_EN | MCTL_GMODE | MCTL_WAKE))) {
2995                 wiphy_err(wiphy, "wl%d: validate_chip_access: maccontrol = "
2996                           "0x%x, expected 0x%x or 0x%x\n", wlc_hw->unit, w,
2997                           (MCTL_IHR_EN | MCTL_WAKE),
2998                           (MCTL_IHR_EN | MCTL_GMODE | MCTL_WAKE));
2999                 return false;
3000         }
3001
3002         return true;
3003 }
3004
3005 #define PHYPLL_WAIT_US  100000
3006
3007 void brcms_b_core_phypll_ctl(struct brcms_hardware *wlc_hw, bool on)
3008 {
3009         struct d11regs *regs;
3010         u32 tmp;
3011
3012         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
3013
3014         tmp = 0;
3015         regs = wlc_hw->regs;
3016
3017         if (on) {
3018                 if ((wlc_hw->sih->chip == BCM4313_CHIP_ID)) {
3019                         OR_REG(&regs->clk_ctl_st,
3020                                (CCS_ERSRC_REQ_HT | CCS_ERSRC_REQ_D11PLL |
3021                                 CCS_ERSRC_REQ_PHYPLL));
3022                         SPINWAIT((R_REG(&regs->clk_ctl_st) &
3023                                   (CCS_ERSRC_AVAIL_HT)) != (CCS_ERSRC_AVAIL_HT),
3024                                  PHYPLL_WAIT_US);
3025
3026                         tmp = R_REG(&regs->clk_ctl_st);
3027                         if ((tmp & (CCS_ERSRC_AVAIL_HT)) !=
3028                             (CCS_ERSRC_AVAIL_HT))
3029                                 wiphy_err(wlc_hw->wlc->wiphy, "%s: turn on PHY"
3030                                           " PLL failed\n", __func__);
3031                 } else {
3032                         OR_REG(&regs->clk_ctl_st,
3033                                (CCS_ERSRC_REQ_D11PLL | CCS_ERSRC_REQ_PHYPLL));
3034                         SPINWAIT((R_REG(&regs->clk_ctl_st) &
3035                                   (CCS_ERSRC_AVAIL_D11PLL |
3036                                    CCS_ERSRC_AVAIL_PHYPLL)) !=
3037                                  (CCS_ERSRC_AVAIL_D11PLL |
3038                                   CCS_ERSRC_AVAIL_PHYPLL), PHYPLL_WAIT_US);
3039
3040                         tmp = R_REG(&regs->clk_ctl_st);
3041                         if ((tmp &
3042                              (CCS_ERSRC_AVAIL_D11PLL | CCS_ERSRC_AVAIL_PHYPLL))
3043                             !=
3044                             (CCS_ERSRC_AVAIL_D11PLL | CCS_ERSRC_AVAIL_PHYPLL))
3045                                 wiphy_err(wlc_hw->wlc->wiphy, "%s: turn on "
3046                                           "PHY PLL failed\n", __func__);
3047                 }
3048         } else {
3049                 /*
3050                  * Since the PLL may be shared, other cores can still
3051                  * be requesting it; so we'll deassert the request but
3052                  * not wait for status to comply.
3053                  */
3054                 AND_REG(&regs->clk_ctl_st, ~CCS_ERSRC_REQ_PHYPLL);
3055                 tmp = R_REG(&regs->clk_ctl_st);
3056         }
3057 }
3058
3059 void brcms_c_coredisable(struct brcms_hardware *wlc_hw)
3060 {
3061         bool dev_gone;
3062
3063         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
3064
3065         dev_gone = brcms_deviceremoved(wlc_hw->wlc);
3066
3067         if (dev_gone)
3068                 return;
3069
3070         if (wlc_hw->noreset)
3071                 return;
3072
3073         /* radio off */
3074         wlc_phy_switch_radio(wlc_hw->band->pi, OFF);
3075
3076         /* turn off analog core */
3077         wlc_phy_anacore(wlc_hw->band->pi, OFF);
3078
3079         /* turn off PHYPLL to save power */
3080         brcms_b_core_phypll_ctl(wlc_hw, false);
3081
3082         wlc_hw->clk = false;
3083         ai_core_disable(wlc_hw->sih, 0);
3084         wlc_phy_hw_clk_state_upd(wlc_hw->band->pi, false);
3085 }
3086
3087 static void brcms_c_flushqueues(struct brcms_c_info *wlc)
3088 {
3089         struct brcms_hardware *wlc_hw = wlc->hw;
3090         uint i;
3091
3092         /* free any posted tx packets */
3093         for (i = 0; i < NFIFO; i++)
3094                 if (wlc_hw->di[i]) {
3095                         dma_txreclaim(wlc_hw->di[i], DMA_RANGE_ALL);
3096                         wlc->core->txpktpend[i] = 0;
3097                         BCMMSG(wlc->wiphy, "pktpend fifo %d clrd\n", i);
3098                 }
3099
3100         /* free any posted rx packets */
3101         dma_rxreclaim(wlc_hw->di[RX_FIFO]);
3102 }
3103
3104 static u16
3105 brcms_b_read_objmem(struct brcms_hardware *wlc_hw, uint offset, u32 sel)
3106 {
3107         struct d11regs *regs = wlc_hw->regs;
3108         u16 *objdata_lo = (u16 *)&regs->objdata;
3109         u16 *objdata_hi = objdata_lo + 1;
3110         u16 v;
3111
3112         W_REG(&regs->objaddr, sel | (offset >> 2));
3113         (void)R_REG(&regs->objaddr);
3114         if (offset & 2)
3115                 v = R_REG(objdata_hi);
3116         else
3117                 v = R_REG(objdata_lo);
3118
3119         return v;
3120 }
3121
3122 static void
3123 brcms_b_write_objmem(struct brcms_hardware *wlc_hw, uint offset, u16 v,
3124                      u32 sel)
3125 {
3126         struct d11regs *regs = wlc_hw->regs;
3127         u16 *objdata_lo = (u16 *)&regs->objdata;
3128         u16 *objdata_hi = objdata_lo + 1;
3129
3130         W_REG(&regs->objaddr, sel | (offset >> 2));
3131         (void)R_REG(&regs->objaddr);
3132         if (offset & 2)
3133                 W_REG(objdata_hi, v);
3134         else
3135                 W_REG(objdata_lo, v);
3136 }
3137
3138 u16 brcms_b_read_shm(struct brcms_hardware *wlc_hw, uint offset)
3139 {
3140         return brcms_b_read_objmem(wlc_hw, offset, OBJADDR_SHM_SEL);
3141 }
3142
3143 void brcms_b_write_shm(struct brcms_hardware *wlc_hw, uint offset, u16 v)
3144 {
3145         brcms_b_write_objmem(wlc_hw, offset, v, OBJADDR_SHM_SEL);
3146 }
3147
3148 /* Copy a buffer to shared memory of specified type .
3149  * SHM 'offset' needs to be an even address and
3150  * Buffer length 'len' must be an even number of bytes
3151  * 'sel' selects the type of memory
3152  */
3153 void
3154 brcms_b_copyto_objmem(struct brcms_hardware *wlc_hw, uint offset,
3155                       const void *buf, int len, u32 sel)
3156 {
3157         u16 v;
3158         const u8 *p = (const u8 *)buf;
3159         int i;
3160
3161         if (len <= 0 || (offset & 1) || (len & 1))
3162                 return;
3163
3164         for (i = 0; i < len; i += 2) {
3165                 v = p[i] | (p[i + 1] << 8);
3166                 brcms_b_write_objmem(wlc_hw, offset + i, v, sel);
3167         }
3168 }
3169
3170 /* Copy a piece of shared memory of specified type to a buffer .
3171  * SHM 'offset' needs to be an even address and
3172  * Buffer length 'len' must be an even number of bytes
3173  * 'sel' selects the type of memory
3174  */
3175 void
3176 brcms_b_copyfrom_objmem(struct brcms_hardware *wlc_hw, uint offset, void *buf,
3177                          int len, u32 sel)
3178 {
3179         u16 v;
3180         u8 *p = (u8 *) buf;
3181         int i;
3182
3183         if (len <= 0 || (offset & 1) || (len & 1))
3184                 return;
3185
3186         for (i = 0; i < len; i += 2) {
3187                 v = brcms_b_read_objmem(wlc_hw, offset + i, sel);
3188                 p[i] = v & 0xFF;
3189                 p[i + 1] = (v >> 8) & 0xFF;
3190         }
3191 }
3192
3193 static void brcms_b_copyfrom_vars(struct brcms_hardware *wlc_hw, char **buf,
3194                            uint *len)
3195 {
3196         BCMMSG(wlc_hw->wlc->wiphy, "nvram vars totlen=%d\n",
3197                 wlc_hw->vars_size);
3198
3199         *buf = wlc_hw->vars;
3200         *len = wlc_hw->vars_size;
3201 }
3202
3203 static void brcms_b_retrylimit_upd(struct brcms_hardware *wlc_hw,
3204                                    u16 SRL, u16 LRL)
3205 {
3206         wlc_hw->SRL = SRL;
3207         wlc_hw->LRL = LRL;
3208
3209         /* write retry limit to SCR, shouldn't need to suspend */
3210         if (wlc_hw->up) {
3211                 W_REG(&wlc_hw->regs->objaddr,
3212                       OBJADDR_SCR_SEL | S_DOT11_SRC_LMT);
3213                 (void)R_REG(&wlc_hw->regs->objaddr);
3214                 W_REG(&wlc_hw->regs->objdata, wlc_hw->SRL);
3215                 W_REG(&wlc_hw->regs->objaddr,
3216                       OBJADDR_SCR_SEL | S_DOT11_LRC_LMT);
3217                 (void)R_REG(&wlc_hw->regs->objaddr);
3218                 W_REG(&wlc_hw->regs->objdata, wlc_hw->LRL);
3219         }
3220 }
3221
3222 static void brcms_b_pllreq(struct brcms_hardware *wlc_hw, bool set, u32 req_bit)
3223 {
3224         if (set) {
3225                 if (mboolisset(wlc_hw->pllreq, req_bit))
3226                         return;
3227
3228                 mboolset(wlc_hw->pllreq, req_bit);
3229
3230                 if (mboolisset(wlc_hw->pllreq, BRCMS_PLLREQ_FLIP)) {
3231                         if (!wlc_hw->sbclk)
3232                                 brcms_b_xtal(wlc_hw, ON);
3233                 }
3234         } else {
3235                 if (!mboolisset(wlc_hw->pllreq, req_bit))
3236                         return;
3237
3238                 mboolclr(wlc_hw->pllreq, req_bit);
3239
3240                 if (mboolisset(wlc_hw->pllreq, BRCMS_PLLREQ_FLIP)) {
3241                         if (wlc_hw->sbclk)
3242                                 brcms_b_xtal(wlc_hw, OFF);
3243                 }
3244         }
3245
3246         return;
3247 }
3248
3249 static void brcms_b_antsel_set(struct brcms_hardware *wlc_hw, u32 antsel_avail)
3250 {
3251         wlc_hw->antsel_avail = antsel_avail;
3252 }
3253
3254 /*
3255  * conditions under which the PM bit should be set in outgoing frames
3256  * and STAY_AWAKE is meaningful
3257  */
3258 bool brcms_c_ps_allowed(struct brcms_c_info *wlc)
3259 {
3260         struct brcms_bss_cfg *cfg = wlc->bsscfg;
3261
3262         /* disallow PS when one of the following global conditions meets */
3263         if (!wlc->pub->associated)
3264                 return false;
3265
3266         /* disallow PS when one of these meets when not scanning */
3267         if (wlc->monitor)
3268                 return false;
3269
3270         if (cfg->associated) {
3271                 /*
3272                  * disallow PS when one of the following
3273                  * bsscfg specific conditions meets
3274                  */
3275                 if (!cfg->BSS)
3276                         return false;
3277
3278                 if (!cfg->dtim_programmed)
3279                         return false;
3280         }
3281
3282         return true;
3283 }
3284
3285 static void brcms_b_reset(struct brcms_hardware *wlc_hw)
3286 {
3287         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
3288
3289         /* reset the core */
3290         if (!brcms_deviceremoved(wlc_hw->wlc))
3291                 brcms_b_corereset(wlc_hw, BRCMS_USE_COREFLAGS);
3292
3293         /* purge the dma rings */
3294         brcms_c_flushqueues(wlc_hw->wlc);
3295
3296         brcms_c_reset_bmac_done(wlc_hw->wlc);
3297 }
3298
3299 void brcms_c_reset(struct brcms_c_info *wlc)
3300 {
3301         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
3302
3303         /* slurp up hw mac counters before core reset */
3304         brcms_c_statsupd(wlc);
3305
3306         /* reset our snapshot of macstat counters */
3307         memset((char *)wlc->core->macstat_snapshot, 0,
3308                 sizeof(struct macstat));
3309
3310         brcms_b_reset(wlc->hw);
3311 }
3312
3313 void brcms_c_fatal_error(struct brcms_c_info *wlc)
3314 {
3315         wiphy_err(wlc->wiphy, "wl%d: fatal error, reinitializing\n",
3316                   wlc->pub->unit);
3317         brcms_init(wlc->wl);
3318 }
3319
3320 /* Return the channel the driver should initialize during brcms_c_init.
3321  * the channel may have to be changed from the currently configured channel
3322  * if other configurations are in conflict (bandlocked, 11n mode disabled,
3323  * invalid channel for current country, etc.)
3324  */
3325 static u16 brcms_c_init_chanspec(struct brcms_c_info *wlc)
3326 {
3327         u16 chanspec =
3328             1 | WL_CHANSPEC_BW_20 | WL_CHANSPEC_CTL_SB_NONE |
3329             WL_CHANSPEC_BAND_2G;
3330
3331         return chanspec;
3332 }
3333
3334 static struct scb global_scb;
3335
3336 static void brcms_c_init_scb(struct brcms_c_info *wlc, struct scb *scb)
3337 {
3338         int i;
3339         scb->flags = SCB_WMECAP | SCB_HTCAP;
3340         for (i = 0; i < NUMPRIO; i++)
3341                 scb->seqnum[i] = 0;
3342 }
3343
3344 /* d11 core init
3345  *   reset PSM
3346  *   download ucode/PCM
3347  *   let ucode run to suspended
3348  *   download ucode inits
3349  *   config other core registers
3350  *   init dma
3351  */
3352 static void brcms_b_coreinit(struct brcms_c_info *wlc)
3353 {
3354         struct brcms_hardware *wlc_hw = wlc->hw;
3355         struct d11regs *regs;
3356         u32 sflags;
3357         uint bcnint_us;
3358         uint i = 0;
3359         bool fifosz_fixup = false;
3360         int err = 0;
3361         u16 buf[NFIFO];
3362         struct wiphy *wiphy = wlc->wiphy;
3363         struct brcms_ucode *ucode = &wlc_hw->wlc->wl->ucode;
3364
3365         regs = wlc_hw->regs;
3366
3367         BCMMSG(wlc->wiphy, "wl%d\n", wlc_hw->unit);
3368
3369         /* reset PSM */
3370         brcms_b_mctrl(wlc_hw, ~0, (MCTL_IHR_EN | MCTL_PSM_JMP_0 | MCTL_WAKE));
3371
3372         brcms_ucode_download(wlc_hw);
3373         /*
3374          * FIFOSZ fixup. driver wants to controls the fifo allocation.
3375          */
3376         fifosz_fixup = true;
3377
3378         /* let the PSM run to the suspended state, set mode to BSS STA */
3379         W_REG(&regs->macintstatus, -1);
3380         brcms_b_mctrl(wlc_hw, ~0,
3381                        (MCTL_IHR_EN | MCTL_INFRA | MCTL_PSM_RUN | MCTL_WAKE));
3382
3383         /* wait for ucode to self-suspend after auto-init */
3384         SPINWAIT(((R_REG(&regs->macintstatus) & MI_MACSSPNDD) == 0),
3385                  1000 * 1000);
3386         if ((R_REG(&regs->macintstatus) & MI_MACSSPNDD) == 0)
3387                 wiphy_err(wiphy, "wl%d: wlc_coreinit: ucode did not self-"
3388                           "suspend!\n", wlc_hw->unit);
3389
3390         brcms_c_gpio_init(wlc);
3391
3392         sflags = ai_core_sflags(wlc_hw->sih, 0, 0);
3393
3394         if (D11REV_IS(wlc_hw->corerev, 23)) {
3395                 if (BRCMS_ISNPHY(wlc_hw->band))
3396                         brcms_c_write_inits(wlc_hw, ucode->d11n0initvals16);
3397                 else
3398                         wiphy_err(wiphy, "%s: wl%d: unsupported phy in corerev"
3399                                   " %d\n", __func__, wlc_hw->unit,
3400                                   wlc_hw->corerev);
3401         } else if (D11REV_IS(wlc_hw->corerev, 24)) {
3402                 if (BRCMS_ISLCNPHY(wlc_hw->band))
3403                         brcms_c_write_inits(wlc_hw, ucode->d11lcn0initvals24);
3404                 else
3405                         wiphy_err(wiphy, "%s: wl%d: unsupported phy in corerev"
3406                                   " %d\n", __func__, wlc_hw->unit,
3407                                   wlc_hw->corerev);
3408         } else {
3409                 wiphy_err(wiphy, "%s: wl%d: unsupported corerev %d\n",
3410                           __func__, wlc_hw->unit, wlc_hw->corerev);
3411         }
3412
3413         /* For old ucode, txfifo sizes needs to be modified(increased) */
3414         if (fifosz_fixup == true)
3415                 brcms_b_corerev_fifofixup(wlc_hw);
3416
3417         /* check txfifo allocations match between ucode and driver */
3418         buf[TX_AC_BE_FIFO] = brcms_b_read_shm(wlc_hw, M_FIFOSIZE0);
3419         if (buf[TX_AC_BE_FIFO] != wlc_hw->xmtfifo_sz[TX_AC_BE_FIFO]) {
3420                 i = TX_AC_BE_FIFO;
3421                 err = -1;
3422         }
3423         buf[TX_AC_VI_FIFO] = brcms_b_read_shm(wlc_hw, M_FIFOSIZE1);
3424         if (buf[TX_AC_VI_FIFO] != wlc_hw->xmtfifo_sz[TX_AC_VI_FIFO]) {
3425                 i = TX_AC_VI_FIFO;
3426                 err = -1;
3427         }
3428         buf[TX_AC_BK_FIFO] = brcms_b_read_shm(wlc_hw, M_FIFOSIZE2);
3429         buf[TX_AC_VO_FIFO] = (buf[TX_AC_BK_FIFO] >> 8) & 0xff;
3430         buf[TX_AC_BK_FIFO] &= 0xff;
3431         if (buf[TX_AC_BK_FIFO] != wlc_hw->xmtfifo_sz[TX_AC_BK_FIFO]) {
3432                 i = TX_AC_BK_FIFO;
3433                 err = -1;
3434         }
3435         if (buf[TX_AC_VO_FIFO] != wlc_hw->xmtfifo_sz[TX_AC_VO_FIFO]) {
3436                 i = TX_AC_VO_FIFO;
3437                 err = -1;
3438         }
3439         buf[TX_BCMC_FIFO] = brcms_b_read_shm(wlc_hw, M_FIFOSIZE3);
3440         buf[TX_ATIM_FIFO] = (buf[TX_BCMC_FIFO] >> 8) & 0xff;
3441         buf[TX_BCMC_FIFO] &= 0xff;
3442         if (buf[TX_BCMC_FIFO] != wlc_hw->xmtfifo_sz[TX_BCMC_FIFO]) {
3443                 i = TX_BCMC_FIFO;
3444                 err = -1;
3445         }
3446         if (buf[TX_ATIM_FIFO] != wlc_hw->xmtfifo_sz[TX_ATIM_FIFO]) {
3447                 i = TX_ATIM_FIFO;
3448                 err = -1;
3449         }
3450         if (err != 0)
3451                 wiphy_err(wiphy, "wlc_coreinit: txfifo mismatch: ucode size %d"
3452                           " driver size %d index %d\n", buf[i],
3453                           wlc_hw->xmtfifo_sz[i], i);
3454
3455         /* make sure we can still talk to the mac */
3456         WARN_ON(R_REG(&regs->maccontrol) == 0xffffffff);
3457
3458         /* band-specific inits done by wlc_bsinit() */
3459
3460         /* Set up frame burst size and antenna swap threshold init values */
3461         brcms_b_write_shm(wlc_hw, M_MBURST_SIZE, MAXTXFRAMEBURST);
3462         brcms_b_write_shm(wlc_hw, M_MAX_ANTCNT, ANTCNT);
3463
3464         /* enable one rx interrupt per received frame */
3465         W_REG(&regs->intrcvlazy[0], (1 << IRL_FC_SHIFT));
3466
3467         /* set the station mode (BSS STA) */
3468         brcms_b_mctrl(wlc_hw,
3469                        (MCTL_INFRA | MCTL_DISCARD_PMQ | MCTL_AP),
3470                        (MCTL_INFRA | MCTL_DISCARD_PMQ));
3471
3472         /* set up Beacon interval */
3473         bcnint_us = 0x8000 << 10;
3474         W_REG(&regs->tsf_cfprep, (bcnint_us << CFPREP_CBI_SHIFT));
3475         W_REG(&regs->tsf_cfpstart, bcnint_us);
3476         W_REG(&regs->macintstatus, MI_GP1);
3477
3478         /* write interrupt mask */
3479         W_REG(&regs->intctrlregs[RX_FIFO].intmask, DEF_RXINTMASK);
3480
3481         /* allow the MAC to control the PHY clock (dynamic on/off) */
3482         brcms_b_macphyclk_set(wlc_hw, ON);
3483
3484         /* program dynamic clock control fast powerup delay register */
3485         wlc->fastpwrup_dly = ai_clkctl_fast_pwrup_delay(wlc_hw->sih);
3486         W_REG(&regs->scc_fastpwrup_dly, wlc->fastpwrup_dly);
3487
3488         /* tell the ucode the corerev */
3489         brcms_b_write_shm(wlc_hw, M_MACHW_VER, (u16) wlc_hw->corerev);
3490
3491         /* tell the ucode MAC capabilities */
3492         brcms_b_write_shm(wlc_hw, M_MACHW_CAP_L,
3493                            (u16) (wlc_hw->machwcap & 0xffff));
3494         brcms_b_write_shm(wlc_hw, M_MACHW_CAP_H,
3495                            (u16) ((wlc_hw->
3496                                       machwcap >> 16) & 0xffff));
3497
3498         /* write retry limits to SCR, this done after PSM init */
3499         W_REG(&regs->objaddr, OBJADDR_SCR_SEL | S_DOT11_SRC_LMT);
3500         (void)R_REG(&regs->objaddr);
3501         W_REG(&regs->objdata, wlc_hw->SRL);
3502         W_REG(&regs->objaddr, OBJADDR_SCR_SEL | S_DOT11_LRC_LMT);
3503         (void)R_REG(&regs->objaddr);
3504         W_REG(&regs->objdata, wlc_hw->LRL);
3505
3506         /* write rate fallback retry limits */
3507         brcms_b_write_shm(wlc_hw, M_SFRMTXCNTFBRTHSD, wlc_hw->SFBL);
3508         brcms_b_write_shm(wlc_hw, M_LFRMTXCNTFBRTHSD, wlc_hw->LFBL);
3509
3510         AND_REG(&regs->ifs_ctl, 0x0FFF);
3511         W_REG(&regs->ifs_aifsn, EDCF_AIFSN_MIN);
3512
3513         /* init the tx dma engines */
3514         for (i = 0; i < NFIFO; i++) {
3515                 if (wlc_hw->di[i])
3516                         dma_txinit(wlc_hw->di[i]);
3517         }
3518
3519         /* init the rx dma engine(s) and post receive buffers */
3520         dma_rxinit(wlc_hw->di[RX_FIFO]);
3521         dma_rxfill(wlc_hw->di[RX_FIFO]);
3522 }
3523
3524 void
3525 static brcms_b_init(struct brcms_hardware *wlc_hw, u16 chanspec,
3526                           bool mute) {
3527         u32 macintmask;
3528         bool fastclk;
3529         struct brcms_c_info *wlc = wlc_hw->wlc;
3530
3531         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
3532
3533         /* request FAST clock if not on */
3534         fastclk = wlc_hw->forcefastclk;
3535         if (!fastclk)
3536                 brcms_b_clkctl_clk(wlc_hw, CLK_FAST);
3537
3538         /* disable interrupts */
3539         macintmask = brcms_intrsoff(wlc->wl);
3540
3541         /* set up the specified band and chanspec */
3542         brcms_c_setxband(wlc_hw, chspec_bandunit(chanspec));
3543         wlc_phy_chanspec_radio_set(wlc_hw->band->pi, chanspec);
3544
3545         /* do one-time phy inits and calibration */
3546         wlc_phy_cal_init(wlc_hw->band->pi);
3547
3548         /* core-specific initialization */
3549         brcms_b_coreinit(wlc);
3550
3551         /* suspend the tx fifos and mute the phy for preism cac time */
3552         if (mute)
3553                 brcms_b_mute(wlc_hw, ON, PHY_MUTE_FOR_PREISM);
3554
3555         /* band-specific inits */
3556         brcms_b_bsinit(wlc, chanspec);
3557
3558         /* restore macintmask */
3559         brcms_intrsrestore(wlc->wl, macintmask);
3560
3561         /* seed wake_override with BRCMS_WAKE_OVERRIDE_MACSUSPEND since the mac
3562          * is suspended and brcms_c_enable_mac() will clear this override bit.
3563          */
3564         mboolset(wlc_hw->wake_override, BRCMS_WAKE_OVERRIDE_MACSUSPEND);
3565
3566         /*
3567          * initialize mac_suspend_depth to 1 to match ucode
3568          * initial suspended state
3569          */
3570         wlc_hw->mac_suspend_depth = 1;
3571
3572         /* restore the clk */
3573         if (!fastclk)
3574                 brcms_b_clkctl_clk(wlc_hw, CLK_DYNAMIC);
3575 }
3576
3577 static void brcms_c_set_phy_chanspec(struct brcms_c_info *wlc,
3578                                      u16 chanspec)
3579 {
3580         /* Save our copy of the chanspec */
3581         wlc->chanspec = chanspec;
3582
3583         /* Set the chanspec and power limits for this locale */
3584         brcms_c_channel_set_chanspec(wlc->cmi, chanspec, BRCMS_TXPWR_MAX);
3585
3586         if (wlc->stf->ss_algosel_auto)
3587                 brcms_c_stf_ss_algo_channel_get(wlc, &wlc->stf->ss_algo_channel,
3588                                             chanspec);
3589
3590         brcms_c_stf_ss_update(wlc, wlc->band);
3591
3592 }
3593
3594 static void brcms_c_bandinit_ordered(struct brcms_c_info *wlc,
3595                                      u16 chanspec)
3596 {
3597         struct brcms_c_rateset default_rateset;
3598         uint parkband;
3599         uint i, band_order[2];
3600
3601         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
3602         /*
3603          * We might have been bandlocked during down and the chip
3604          * power-cycled (hibernate). Figure out the right band to park on
3605          */
3606         if (wlc->bandlocked || wlc->pub->_nbands == 1) {
3607                 /* updated in brcms_c_bandlock() */
3608                 parkband = wlc->band->bandunit;
3609                 band_order[0] = band_order[1] = parkband;
3610         } else {
3611                 /* park on the band of the specified chanspec */
3612                 parkband = chspec_bandunit(chanspec);
3613
3614                 /* order so that parkband initialize last */
3615                 band_order[0] = parkband ^ 1;
3616                 band_order[1] = parkband;
3617         }
3618
3619         /* make each band operational, software state init */
3620         for (i = 0; i < wlc->pub->_nbands; i++) {
3621                 uint j = band_order[i];
3622
3623                 wlc->band = wlc->bandstate[j];
3624
3625                 brcms_default_rateset(wlc, &default_rateset);
3626
3627                 /* fill in hw_rate */
3628                 brcms_c_rateset_filter(&default_rateset, &wlc->band->hw_rateset,
3629                                    false, BRCMS_RATES_CCK_OFDM, BRCMS_RATE_MASK,
3630                                    (bool) (wlc->pub->_n_enab & SUPPORT_11N));
3631
3632                 /* init basic rate lookup */
3633                 brcms_c_rate_lookup_init(wlc, &default_rateset);
3634         }
3635
3636         /* sync up phy/radio chanspec */
3637         brcms_c_set_phy_chanspec(wlc, chanspec);
3638 }
3639
3640 /*
3641  * ucode, hwmac update
3642  *    Channel dependent updates for ucode and hw
3643  */
3644 static void brcms_c_ucode_mac_upd(struct brcms_c_info *wlc)
3645 {
3646         /* enable or disable any active IBSSs depending on whether or not
3647          * we are on the home channel
3648          */
3649         if (wlc->home_chanspec == wlc_phy_chanspec_get(wlc->band->pi)) {
3650                 if (wlc->pub->associated) {
3651                         /*
3652                          * BMAC_NOTE: This is something that should be fixed
3653                          * in ucode inits. I think that the ucode inits set
3654                          * up the bcn templates and shm values with a bogus
3655                          * beacon. This should not be done in the inits. If
3656                          * ucode needs to set up a beacon for testing, the
3657                          * test routines should write it down, not expect the
3658                          * inits to populate a bogus beacon.
3659                          */
3660                         if (BRCMS_PHY_11N_CAP(wlc->band))
3661                                 brcms_c_write_shm(wlc, M_BCN_TXTSF_OFFSET, 0);
3662                 }
3663         } else {
3664                 /* disable an active IBSS if we are not on the home channel */
3665         }
3666
3667         /* update the various promisc bits */
3668         brcms_c_mac_bcn_promisc(wlc);
3669         brcms_c_mac_promisc(wlc);
3670 }
3671
3672 /* band-specific init */
3673 static void brcms_c_bsinit(struct brcms_c_info *wlc)
3674 {
3675         BCMMSG(wlc->wiphy, "wl%d: bandunit %d\n",
3676                  wlc->pub->unit, wlc->band->bandunit);
3677
3678         /* write ucode ACK/CTS rate table */
3679         brcms_c_set_ratetable(wlc);
3680
3681         /* update some band specific mac configuration */
3682         brcms_c_ucode_mac_upd(wlc);
3683
3684         /* init antenna selection */
3685         brcms_c_antsel_init(wlc->asi);
3686
3687 }
3688
3689 /* formula:  IDLE_BUSY_RATIO_X_16 = (100-duty_cycle)/duty_cycle*16 */
3690 static int
3691 brcms_c_duty_cycle_set(struct brcms_c_info *wlc, int duty_cycle, bool isOFDM,
3692                    bool writeToShm)
3693 {
3694         int idle_busy_ratio_x_16 = 0;
3695         uint offset =
3696             isOFDM ? M_TX_IDLE_BUSY_RATIO_X_16_OFDM :
3697             M_TX_IDLE_BUSY_RATIO_X_16_CCK;
3698         if (duty_cycle > 100 || duty_cycle < 0) {
3699                 wiphy_err(wlc->wiphy, "wl%d:  duty cycle value off limit\n",
3700                           wlc->pub->unit);
3701                 return -EINVAL;
3702         }
3703         if (duty_cycle)
3704                 idle_busy_ratio_x_16 = (100 - duty_cycle) * 16 / duty_cycle;
3705         /* Only write to shared memory  when wl is up */
3706         if (writeToShm)
3707                 brcms_c_write_shm(wlc, offset, (u16) idle_busy_ratio_x_16);
3708
3709         if (isOFDM)
3710                 wlc->tx_duty_cycle_ofdm = (u16) duty_cycle;
3711         else
3712                 wlc->tx_duty_cycle_cck = (u16) duty_cycle;
3713
3714         return 0;
3715 }
3716
3717 /*
3718  * Initialize the base precedence map for dequeueing
3719  * from txq based on WME settings
3720  */
3721 static void brcms_c_tx_prec_map_init(struct brcms_c_info *wlc)
3722 {
3723         wlc->tx_prec_map = BRCMS_PREC_BMP_ALL;
3724         memset(wlc->fifo2prec_map, 0, NFIFO * sizeof(u16));
3725
3726         wlc->fifo2prec_map[TX_AC_BK_FIFO] = BRCMS_PREC_BMP_AC_BK;
3727         wlc->fifo2prec_map[TX_AC_BE_FIFO] = BRCMS_PREC_BMP_AC_BE;
3728         wlc->fifo2prec_map[TX_AC_VI_FIFO] = BRCMS_PREC_BMP_AC_VI;
3729         wlc->fifo2prec_map[TX_AC_VO_FIFO] = BRCMS_PREC_BMP_AC_VO;
3730 }
3731
3732 static void
3733 brcms_c_txflowcontrol_signal(struct brcms_c_info *wlc,
3734                              struct brcms_txq_info *qi, bool on, int prio)
3735 {
3736         /* transmit flowcontrol is not yet implemented */
3737 }
3738
3739 static void brcms_c_txflowcontrol_reset(struct brcms_c_info *wlc)
3740 {
3741         struct brcms_txq_info *qi;
3742
3743         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
3744                 if (qi->stopped) {
3745                         brcms_c_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
3746                         qi->stopped = 0;
3747                 }
3748         }
3749 }
3750
3751 void brcms_c_init(struct brcms_c_info *wlc)
3752 {
3753         struct d11regs *regs;
3754         u16 chanspec;
3755         bool mute = false;
3756
3757         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
3758
3759         regs = wlc->regs;
3760
3761         /*
3762          * This will happen if a big-hammer was executed. In
3763          * that case, we want to go back to the channel that
3764          * we were on and not new channel
3765          */
3766         if (wlc->pub->associated)
3767                 chanspec = wlc->home_chanspec;
3768         else
3769                 chanspec = brcms_c_init_chanspec(wlc);
3770
3771         brcms_b_init(wlc->hw, chanspec, mute);
3772
3773         /* update beacon listen interval */
3774         brcms_c_bcn_li_upd(wlc);
3775
3776         /* the world is new again, so is our reported rate */
3777         brcms_c_reprate_init(wlc);
3778
3779         /* write ethernet address to core */
3780         brcms_c_set_mac(wlc->bsscfg);
3781         brcms_c_set_bssid(wlc->bsscfg);
3782
3783         /* Update tsf_cfprep if associated and up */
3784         if (wlc->pub->associated && wlc->bsscfg->up) {
3785                 u32 bi;
3786
3787                 /* get beacon period and convert to uS */
3788                 bi = wlc->bsscfg->current_bss->beacon_period << 10;
3789                 /*
3790                  * update since init path would reset
3791                  * to default value
3792                  */
3793                 W_REG(&regs->tsf_cfprep,
3794                       (bi << CFPREP_CBI_SHIFT));
3795
3796                 /* Update maccontrol PM related bits */
3797                 brcms_c_set_ps_ctrl(wlc);
3798         }
3799
3800         brcms_c_bandinit_ordered(wlc, chanspec);
3801
3802         brcms_c_init_scb(wlc, &global_scb);
3803
3804         /* init probe response timeout */
3805         brcms_c_write_shm(wlc, M_PRS_MAXTIME, wlc->prb_resp_timeout);
3806
3807         /* init max burst txop (framebursting) */
3808         brcms_c_write_shm(wlc, M_MBURST_TXOP,
3809                       (wlc->
3810                        _rifs ? (EDCF_AC_VO_TXOP_AP << 5) : MAXFRAMEBURST_TXOP));
3811
3812         /* initialize maximum allowed duty cycle */
3813         brcms_c_duty_cycle_set(wlc, wlc->tx_duty_cycle_ofdm, true, true);
3814         brcms_c_duty_cycle_set(wlc, wlc->tx_duty_cycle_cck, false, true);
3815
3816         /*
3817          * Update some shared memory locations related to
3818          * max AMPDU size allowed to received
3819          */
3820         brcms_c_ampdu_shm_upd(wlc->ampdu);
3821
3822         /* band-specific inits */
3823         brcms_c_bsinit(wlc);
3824
3825         /* Enable EDCF mode (while the MAC is suspended) */
3826         OR_REG(&regs->ifs_ctl, IFS_USEEDCF);
3827         brcms_c_edcf_setparams(wlc, false);
3828
3829         /* Init precedence maps for empty FIFOs */
3830         brcms_c_tx_prec_map_init(wlc);
3831
3832         /* read the ucode version if we have not yet done so */
3833         if (wlc->ucode_rev == 0) {
3834                 wlc->ucode_rev =
3835                     brcms_c_read_shm(wlc, M_BOM_REV_MAJOR) << NBITS(u16);
3836                 wlc->ucode_rev |= brcms_c_read_shm(wlc, M_BOM_REV_MINOR);
3837         }
3838
3839         /* ..now really unleash hell (allow the MAC out of suspend) */
3840         brcms_c_enable_mac(wlc);
3841
3842         /* clear tx flow control */
3843         brcms_c_txflowcontrol_reset(wlc);
3844
3845         /* enable the RF Disable Delay timer */
3846         W_REG(&wlc->regs->rfdisabledly, RFDISABLE_DEFAULT);
3847
3848         /* initialize mpc delay */
3849         wlc->mpc_delay_off = wlc->mpc_dlycnt = BRCMS_MPC_MIN_DELAYCNT;
3850
3851         /*
3852          * Initialize WME parameters; if they haven't been set by some other
3853          * mechanism (IOVar, etc) then read them from the hardware.
3854          */
3855         if (GFIELD(wlc->wme_retries[0], EDCF_SHORT) == 0) {
3856                 /* Uninitialized; read from HW */
3857                 int ac;
3858
3859                 for (ac = 0; ac < AC_COUNT; ac++)
3860                         wlc->wme_retries[ac] =
3861                             brcms_c_read_shm(wlc, M_AC_TXLMT_ADDR(ac));
3862         }
3863 }
3864
3865 void brcms_c_mac_bcn_promisc_change(struct brcms_c_info *wlc, bool promisc)
3866 {
3867         wlc->bcnmisc_monitor = promisc;
3868         brcms_c_mac_bcn_promisc(wlc);
3869 }
3870
3871 void brcms_c_mac_bcn_promisc(struct brcms_c_info *wlc)
3872 {
3873         if (wlc->bcnmisc_monitor)
3874                 brcms_c_mctrl(wlc, MCTL_BCNS_PROMISC, MCTL_BCNS_PROMISC);
3875         else
3876                 brcms_c_mctrl(wlc, MCTL_BCNS_PROMISC, 0);
3877 }
3878
3879 /* set or clear maccontrol bits MCTL_PROMISC and MCTL_KEEPCONTROL */
3880 void brcms_c_mac_promisc(struct brcms_c_info *wlc)
3881 {
3882         u32 promisc_bits = 0;
3883
3884         /*
3885          * promiscuous mode just sets MCTL_PROMISC
3886          * Note: APs get all BSS traffic without the need to set
3887          * the MCTL_PROMISC bit since all BSS data traffic is
3888          * directed at the AP
3889          */
3890         if (wlc->pub->promisc)
3891                 promisc_bits |= MCTL_PROMISC;
3892
3893         /* monitor mode needs both MCTL_PROMISC and MCTL_KEEPCONTROL
3894          * Note: monitor mode also needs MCTL_BCNS_PROMISC, but that is
3895          * handled in brcms_c_mac_bcn_promisc()
3896          */
3897         if (wlc->monitor)
3898                 promisc_bits |= MCTL_PROMISC | MCTL_KEEPCONTROL;
3899
3900         brcms_c_mctrl(wlc, MCTL_PROMISC | MCTL_KEEPCONTROL, promisc_bits);
3901 }
3902
3903 /* push sw hps and wake state through hardware */
3904 void brcms_c_set_ps_ctrl(struct brcms_c_info *wlc)
3905 {
3906         u32 v1, v2;
3907         bool hps;
3908         bool awake_before;
3909
3910         hps = brcms_c_ps_allowed(wlc);
3911
3912         BCMMSG(wlc->wiphy, "wl%d: hps %d\n", wlc->pub->unit, hps);
3913
3914         v1 = R_REG(&wlc->regs->maccontrol);
3915         v2 = MCTL_WAKE;
3916         if (hps)
3917                 v2 |= MCTL_HPS;
3918
3919         brcms_c_mctrl(wlc, MCTL_WAKE | MCTL_HPS, v2);
3920
3921         awake_before = ((v1 & MCTL_WAKE) || ((v1 & MCTL_HPS) == 0));
3922
3923         if (!awake_before)
3924                 brcms_b_wait_for_wake(wlc->hw);
3925
3926 }
3927
3928 /*
3929  * Write this BSS config's MAC address to core.
3930  * Updates RXE match engine.
3931  */
3932 int brcms_c_set_mac(struct brcms_bss_cfg *bsscfg)
3933 {
3934         int err = 0;
3935         struct brcms_c_info *wlc = bsscfg->wlc;
3936
3937         /* enter the MAC addr into the RXE match registers */
3938         brcms_c_set_addrmatch(wlc, RCM_MAC_OFFSET, bsscfg->cur_etheraddr);
3939
3940         brcms_c_ampdu_macaddr_upd(wlc);
3941
3942         return err;
3943 }
3944
3945 /* Write the BSS config's BSSID address to core (set_bssid in d11procs.tcl).
3946  * Updates RXE match engine.
3947  */
3948 void brcms_c_set_bssid(struct brcms_bss_cfg *bsscfg)
3949 {
3950         /* we need to update BSSID in RXE match registers */
3951         brcms_c_set_addrmatch(bsscfg->wlc, RCM_BSSID_OFFSET, bsscfg->BSSID);
3952 }
3953
3954 static void brcms_b_set_shortslot(struct brcms_hardware *wlc_hw, bool shortslot)
3955 {
3956         wlc_hw->shortslot = shortslot;
3957
3958         if (brcms_b_bandtype(wlc_hw) == BRCM_BAND_2G && wlc_hw->up) {
3959                 brcms_c_suspend_mac_and_wait(wlc_hw->wlc);
3960                 brcms_b_update_slot_timing(wlc_hw, shortslot);
3961                 brcms_c_enable_mac(wlc_hw->wlc);
3962         }
3963 }
3964
3965 /*
3966  * Suspend the the MAC and update the slot timing
3967  * for standard 11b/g (20us slots) or shortslot 11g (9us slots).
3968  */
3969 void brcms_c_switch_shortslot(struct brcms_c_info *wlc, bool shortslot)
3970 {
3971         /* use the override if it is set */
3972         if (wlc->shortslot_override != BRCMS_SHORTSLOT_AUTO)
3973                 shortslot = (wlc->shortslot_override == BRCMS_SHORTSLOT_ON);
3974
3975         if (wlc->shortslot == shortslot)
3976                 return;
3977
3978         wlc->shortslot = shortslot;
3979
3980         brcms_b_set_shortslot(wlc->hw, shortslot);
3981 }
3982
3983 void brcms_c_set_home_chanspec(struct brcms_c_info *wlc, u16 chanspec)
3984 {
3985         if (wlc->home_chanspec != chanspec) {
3986                 wlc->home_chanspec = chanspec;
3987
3988                 if (wlc->bsscfg->associated)
3989                         wlc->bsscfg->current_bss->chanspec = chanspec;
3990         }
3991 }
3992
3993 void
3994 brcms_b_set_chanspec(struct brcms_hardware *wlc_hw, u16 chanspec,
3995                       bool mute, struct txpwr_limits *txpwr)
3996 {
3997         uint bandunit;
3998
3999         BCMMSG(wlc_hw->wlc->wiphy, "wl%d: 0x%x\n", wlc_hw->unit, chanspec);
4000
4001         wlc_hw->chanspec = chanspec;
4002
4003         /* Switch bands if necessary */
4004         if (wlc_hw->_nbands > 1) {
4005                 bandunit = chspec_bandunit(chanspec);
4006                 if (wlc_hw->band->bandunit != bandunit) {
4007                         /* brcms_b_setband disables other bandunit,
4008                          *  use light band switch if not up yet
4009                          */
4010                         if (wlc_hw->up) {
4011                                 wlc_phy_chanspec_radio_set(wlc_hw->
4012                                                            bandstate[bandunit]->
4013                                                            pi, chanspec);
4014                                 brcms_b_setband(wlc_hw, bandunit, chanspec);
4015                         } else {
4016                                 brcms_c_setxband(wlc_hw, bandunit);
4017                         }
4018                 }
4019         }
4020
4021         wlc_phy_initcal_enable(wlc_hw->band->pi, !mute);
4022
4023         if (!wlc_hw->up) {
4024                 if (wlc_hw->clk)
4025                         wlc_phy_txpower_limit_set(wlc_hw->band->pi, txpwr,
4026                                                   chanspec);
4027                 wlc_phy_chanspec_radio_set(wlc_hw->band->pi, chanspec);
4028         } else {
4029                 wlc_phy_chanspec_set(wlc_hw->band->pi, chanspec);
4030                 wlc_phy_txpower_limit_set(wlc_hw->band->pi, txpwr, chanspec);
4031
4032                 /* Update muting of the channel */
4033                 brcms_b_mute(wlc_hw, mute, 0);
4034         }
4035 }
4036
4037 /* switch to and initialize new band */
4038 static void brcms_c_setband(struct brcms_c_info *wlc,
4039                                            uint bandunit)
4040 {
4041         struct brcms_bss_cfg *cfg = wlc->bsscfg;
4042
4043         wlc->band = wlc->bandstate[bandunit];
4044
4045         if (!wlc->pub->up)
4046                 return;
4047
4048         /* wait for at least one beacon before entering sleeping state */
4049         if (cfg->associated)
4050                 cfg->PMawakebcn = true;
4051
4052         brcms_c_set_ps_ctrl(wlc);
4053
4054         /* band-specific initializations */
4055         brcms_c_bsinit(wlc);
4056 }
4057
4058 void brcms_c_set_chanspec(struct brcms_c_info *wlc, u16 chanspec)
4059 {
4060         uint bandunit;
4061         bool switchband = false;
4062         u16 old_chanspec = wlc->chanspec;
4063
4064         if (!brcms_c_valid_chanspec_db(wlc->cmi, chanspec)) {
4065                 wiphy_err(wlc->wiphy, "wl%d: %s: Bad channel %d\n",
4066                           wlc->pub->unit, __func__, CHSPEC_CHANNEL(chanspec));
4067                 return;
4068         }
4069
4070         /* Switch bands if necessary */
4071         if (wlc->pub->_nbands > 1) {
4072                 bandunit = chspec_bandunit(chanspec);
4073                 if (wlc->band->bandunit != bandunit || wlc->bandinit_pending) {
4074                         switchband = true;
4075                         if (wlc->bandlocked) {
4076                                 wiphy_err(wlc->wiphy, "wl%d: %s: chspec %d "
4077                                           "band is locked!\n",
4078                                           wlc->pub->unit, __func__,
4079                                           CHSPEC_CHANNEL(chanspec));
4080                                 return;
4081                         }
4082                         /*
4083                          * should the setband call come after the
4084                          * brcms_b_chanspec() ? if the setband updates
4085                          * (brcms_c_bsinit) use low level calls to inspect and
4086                          * set state, the state inspected may be from the wrong
4087                          * band, or the following brcms_b_set_chanspec() may
4088                          * undo the work.
4089                          */
4090                         brcms_c_setband(wlc, bandunit);
4091                 }
4092         }
4093
4094         /* sync up phy/radio chanspec */
4095         brcms_c_set_phy_chanspec(wlc, chanspec);
4096
4097         /* init antenna selection */
4098         if (brcms_chspec_bw(old_chanspec) != brcms_chspec_bw(chanspec)) {
4099                 brcms_c_antsel_init(wlc->asi);
4100
4101                 /* Fix the hardware rateset based on bw.
4102                  * Mainly add MCS32 for 40Mhz, remove MCS 32 for 20Mhz
4103                  */
4104                 brcms_c_rateset_bw_mcs_filter(&wlc->band->hw_rateset,
4105                         wlc->band->mimo_cap_40 ? brcms_chspec_bw(chanspec) : 0);
4106         }
4107
4108         /* update some mac configuration since chanspec changed */
4109         brcms_c_ucode_mac_upd(wlc);
4110 }
4111
4112 u32 brcms_c_lowest_basic_rspec(struct brcms_c_info *wlc,
4113                                       struct brcms_c_rateset *rs)
4114 {
4115         u32 lowest_basic_rspec;
4116         uint i;
4117
4118         /* Use the lowest basic rate */
4119         lowest_basic_rspec = rs->rates[0] & BRCMS_RATE_MASK;
4120         for (i = 0; i < rs->count; i++) {
4121                 if (rs->rates[i] & BRCMS_RATE_FLAG) {
4122                         lowest_basic_rspec = rs->rates[i] & BRCMS_RATE_MASK;
4123                         break;
4124                 }
4125         }
4126
4127         /*
4128          * pick siso/cdd as default for OFDM (note no basic
4129          * rate MCSs are supported yet)
4130          */
4131         if (is_ofdm_rate(lowest_basic_rspec))
4132                 lowest_basic_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
4133
4134         return lowest_basic_rspec;
4135 }
4136
4137 /*
4138  * This function changes the phytxctl for beacon based on current
4139  * beacon ratespec AND txant setting as per this table:
4140  *  ratespec     CCK            ant = wlc->stf->txant
4141  *              OFDM            ant = 3
4142  */
4143 void brcms_c_beacon_phytxctl_txant_upd(struct brcms_c_info *wlc,
4144                                        u32 bcn_rspec)
4145 {
4146         u16 phyctl;
4147         u16 phytxant = wlc->stf->phytxant;
4148         u16 mask = PHY_TXC_ANT_MASK;
4149
4150         /* for non-siso rates or default setting, use the available chains */
4151         if (BRCMS_PHY_11N_CAP(wlc->band))
4152                 phytxant = brcms_c_stf_phytxchain_sel(wlc, bcn_rspec);
4153
4154         phyctl = brcms_c_read_shm(wlc, M_BCN_PCTLWD);
4155         phyctl = (phyctl & ~mask) | phytxant;
4156         brcms_c_write_shm(wlc, M_BCN_PCTLWD, phyctl);
4157 }
4158
4159 /*
4160  * centralized protection config change function to simplify debugging, no
4161  * consistency checking this should be called only on changes to avoid overhead
4162  * in periodic function
4163  */
4164 void brcms_c_protection_upd(struct brcms_c_info *wlc, uint idx, int val)
4165 {
4166         BCMMSG(wlc->wiphy, "idx %d, val %d\n", idx, val);
4167
4168         switch (idx) {
4169         case BRCMS_PROT_G_SPEC:
4170                 wlc->protection->_g = (bool) val;
4171                 break;
4172         case BRCMS_PROT_G_OVR:
4173                 wlc->protection->g_override = (s8) val;
4174                 break;
4175         case BRCMS_PROT_G_USER:
4176                 wlc->protection->gmode_user = (u8) val;
4177                 break;
4178         case BRCMS_PROT_OVERLAP:
4179                 wlc->protection->overlap = (s8) val;
4180                 break;
4181         case BRCMS_PROT_N_USER:
4182                 wlc->protection->nmode_user = (s8) val;
4183                 break;
4184         case BRCMS_PROT_N_CFG:
4185                 wlc->protection->n_cfg = (s8) val;
4186                 break;
4187         case BRCMS_PROT_N_CFG_OVR:
4188                 wlc->protection->n_cfg_override = (s8) val;
4189                 break;
4190         case BRCMS_PROT_N_NONGF:
4191                 wlc->protection->nongf = (bool) val;
4192                 break;
4193         case BRCMS_PROT_N_NONGF_OVR:
4194                 wlc->protection->nongf_override = (s8) val;
4195                 break;
4196         case BRCMS_PROT_N_PAM_OVR:
4197                 wlc->protection->n_pam_override = (s8) val;
4198                 break;
4199         case BRCMS_PROT_N_OBSS:
4200                 wlc->protection->n_obss = (bool) val;
4201                 break;
4202
4203         default:
4204                 break;
4205         }
4206
4207 }
4208
4209 static void brcms_c_ht_update_sgi_rx(struct brcms_c_info *wlc, int val)
4210 {
4211         if (wlc->pub->up) {
4212                 brcms_c_update_beacon(wlc);
4213                 brcms_c_update_probe_resp(wlc, true);
4214         }
4215 }
4216
4217 static void brcms_c_ht_update_ldpc(struct brcms_c_info *wlc, s8 val)
4218 {
4219         wlc->stf->ldpc = val;
4220
4221         if (wlc->pub->up) {
4222                 brcms_c_update_beacon(wlc);
4223                 brcms_c_update_probe_resp(wlc, true);
4224                 wlc_phy_ldpc_override_set(wlc->band->pi, (val ? true : false));
4225         }
4226 }
4227
4228 void brcms_c_wme_setparams(struct brcms_c_info *wlc, u16 aci,
4229                        const struct ieee80211_tx_queue_params *params,
4230                        bool suspend)
4231 {
4232         int i;
4233         struct shm_acparams acp_shm;
4234         u16 *shm_entry;
4235
4236         /* Only apply params if the core is out of reset and has clocks */
4237         if (!wlc->clk) {
4238                 wiphy_err(wlc->wiphy, "wl%d: %s : no-clock\n", wlc->pub->unit,
4239                           __func__);
4240                 return;
4241         }
4242
4243         do {
4244                 memset((char *)&acp_shm, 0, sizeof(struct shm_acparams));
4245                 /* fill in shm ac params struct */
4246                 acp_shm.txop = le16_to_cpu(params->txop);
4247                 /* convert from units of 32us to us for ucode */
4248                 wlc->edcf_txop[aci & 0x3] = acp_shm.txop =
4249                     EDCF_TXOP2USEC(acp_shm.txop);
4250                 acp_shm.aifs = (params->aifs & EDCF_AIFSN_MASK);
4251
4252                 if (aci == AC_VI && acp_shm.txop == 0
4253                     && acp_shm.aifs < EDCF_AIFSN_MAX)
4254                         acp_shm.aifs++;
4255
4256                 if (acp_shm.aifs < EDCF_AIFSN_MIN
4257                     || acp_shm.aifs > EDCF_AIFSN_MAX) {
4258                         wiphy_err(wlc->wiphy, "wl%d: edcf_setparams: bad "
4259                                   "aifs %d\n", wlc->pub->unit, acp_shm.aifs);
4260                         continue;
4261                 }
4262
4263                 acp_shm.cwmin = params->cw_min;
4264                 acp_shm.cwmax = params->cw_max;
4265                 acp_shm.cwcur = acp_shm.cwmin;
4266                 acp_shm.bslots =
4267                     R_REG(&wlc->regs->tsf_random) & acp_shm.cwcur;
4268                 acp_shm.reggap = acp_shm.bslots + acp_shm.aifs;
4269                 /* Indicate the new params to the ucode */
4270                 acp_shm.status = brcms_c_read_shm(wlc, (M_EDCF_QINFO +
4271                                                   wme_ac2fifo[aci] *
4272                                                   M_EDCF_QLEN +
4273                                                   M_EDCF_STATUS_OFF));
4274                 acp_shm.status |= WME_STATUS_NEWAC;
4275
4276                 /* Fill in shm acparam table */
4277                 shm_entry = (u16 *) &acp_shm;
4278                 for (i = 0; i < (int)sizeof(struct shm_acparams); i += 2)
4279                         brcms_c_write_shm(wlc,
4280                                           M_EDCF_QINFO +
4281                                           wme_ac2fifo[aci] * M_EDCF_QLEN + i,
4282                                           *shm_entry++);
4283
4284         } while (0);
4285
4286         if (suspend)
4287                 brcms_c_suspend_mac_and_wait(wlc);
4288
4289         if (suspend)
4290                 brcms_c_enable_mac(wlc);
4291
4292 }
4293
4294 void brcms_c_edcf_setparams(struct brcms_c_info *wlc, bool suspend)
4295 {
4296         u16 aci;
4297         int i_ac;
4298         struct ieee80211_tx_queue_params txq_pars;
4299         struct ieee80211_tx_queue_params *params = &txq_pars;
4300         static struct edcf_acparam default_edcf_acparams[] = {
4301                  {EDCF_AC_BE_ACI_STA, EDCF_AC_BE_ECW_STA,
4302                   cpu_to_le16(EDCF_AC_BE_TXOP_STA)},
4303                  {EDCF_AC_BK_ACI_STA, EDCF_AC_BK_ECW_STA,
4304                   cpu_to_le16(EDCF_AC_BK_TXOP_STA)},
4305                  {EDCF_AC_VI_ACI_STA, EDCF_AC_VI_ECW_STA,
4306                   cpu_to_le16(EDCF_AC_VI_TXOP_STA)},
4307                  {EDCF_AC_VO_ACI_STA, EDCF_AC_VO_ECW_STA,
4308                   cpu_to_le16(EDCF_AC_VO_TXOP_STA)}
4309         }; /* ucode needs these parameters during its initialization */
4310         struct edcf_acparam *edcf_acp = &default_edcf_acparams[0];
4311
4312         for (i_ac = 0; i_ac < AC_COUNT; i_ac++, edcf_acp++) {
4313                 /* find out which ac this set of params applies to */
4314                 aci = (edcf_acp->ACI & EDCF_ACI_MASK) >> EDCF_ACI_SHIFT;
4315
4316                 /* fill in shm ac params struct */
4317                 params->txop = edcf_acp->TXOP;
4318                 params->aifs = edcf_acp->ACI;
4319
4320                 /* CWmin = 2^(ECWmin) - 1 */
4321                 params->cw_min = EDCF_ECW2CW(edcf_acp->ECW & EDCF_ECWMIN_MASK);
4322                 /* CWmax = 2^(ECWmax) - 1 */
4323                 params->cw_max = EDCF_ECW2CW((edcf_acp->ECW & EDCF_ECWMAX_MASK)
4324                                             >> EDCF_ECWMAX_SHIFT);
4325                 brcms_c_wme_setparams(wlc, aci, params, suspend);
4326         }
4327
4328         if (suspend)
4329                 brcms_c_suspend_mac_and_wait(wlc);
4330
4331         if (suspend)
4332                 brcms_c_enable_mac(wlc);
4333
4334 }
4335
4336 /* maintain LED behavior in down state */
4337 static void brcms_c_down_led_upd(struct brcms_c_info *wlc)
4338 {
4339         /*
4340          * maintain LEDs while in down state, turn on sbclk if
4341          * not available yet. Turn on sbclk if necessary
4342          */
4343         brcms_c_pllreq(wlc, true, BRCMS_PLLREQ_FLIP);
4344         brcms_c_pllreq(wlc, false, BRCMS_PLLREQ_FLIP);
4345 }
4346
4347 static bool brcms_c_radio_monitor_start(struct brcms_c_info *wlc)
4348 {
4349         /* Don't start the timer if HWRADIO feature is disabled */
4350         if (wlc->radio_monitor)
4351                 return true;
4352
4353         wlc->radio_monitor = true;
4354         brcms_c_pllreq(wlc, true, BRCMS_PLLREQ_RADIO_MON);
4355         brcms_add_timer(wlc->wl, wlc->radio_timer, TIMER_INTERVAL_RADIOCHK,
4356                         true);
4357         return true;
4358 }
4359
4360 void brcms_c_radio_disable(struct brcms_c_info *wlc)
4361 {
4362         if (!wlc->pub->up) {
4363                 brcms_c_down_led_upd(wlc);
4364                 return;
4365         }
4366
4367         brcms_c_radio_monitor_start(wlc);
4368         brcms_down(wlc->wl);
4369 }
4370
4371 static void brcms_c_radio_enable(struct brcms_c_info *wlc)
4372 {
4373         if (wlc->pub->up)
4374                 return;
4375
4376         if (brcms_deviceremoved(wlc))
4377                 return;
4378
4379         brcms_up(wlc->wl);
4380 }
4381
4382 bool brcms_c_radio_monitor_stop(struct brcms_c_info *wlc)
4383 {
4384         if (!wlc->radio_monitor)
4385                 return true;
4386
4387         wlc->radio_monitor = false;
4388         brcms_c_pllreq(wlc, false, BRCMS_PLLREQ_RADIO_MON);
4389         return brcms_del_timer(wlc->wl, wlc->radio_timer);
4390 }
4391
4392 /* read hwdisable state and propagate to wlc flag */
4393 static void brcms_c_radio_hwdisable_upd(struct brcms_c_info *wlc)
4394 {
4395         if (wlc->pub->hw_off)
4396                 return;
4397
4398         if (brcms_b_radio_read_hwdisabled(wlc->hw))
4399                 mboolset(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE);
4400         else
4401                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE);
4402 }
4403
4404 /*
4405  * centralized radio disable/enable function,
4406  * invoke radio enable/disable after updating hwradio status
4407  */
4408 static void brcms_c_radio_upd(struct brcms_c_info *wlc)
4409 {
4410         if (wlc->pub->radio_disabled)
4411                 brcms_c_radio_disable(wlc);
4412         else
4413                 brcms_c_radio_enable(wlc);
4414 }
4415
4416 /* update hwradio status and return it */
4417 bool brcms_c_check_radio_disabled(struct brcms_c_info *wlc)
4418 {
4419         brcms_c_radio_hwdisable_upd(wlc);
4420
4421         return mboolisset(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE) ?
4422                         true : false;
4423 }
4424
4425 /* periodical query hw radio button while driver is "down" */
4426 static void brcms_c_radio_timer(void *arg)
4427 {
4428         struct brcms_c_info *wlc = (struct brcms_c_info *) arg;
4429
4430         if (brcms_deviceremoved(wlc)) {
4431                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
4432                         __func__);
4433                 brcms_down(wlc->wl);
4434                 return;
4435         }
4436
4437         /* cap mpc off count */
4438         if (wlc->mpc_offcnt < BRCMS_MPC_MAX_DELAYCNT)
4439                 wlc->mpc_offcnt++;
4440
4441         brcms_c_radio_hwdisable_upd(wlc);
4442         brcms_c_radio_upd(wlc);
4443 }
4444
4445 /* common low-level watchdog code */
4446 static void brcms_b_watchdog(void *arg)
4447 {
4448         struct brcms_c_info *wlc = (struct brcms_c_info *) arg;
4449         struct brcms_hardware *wlc_hw = wlc->hw;
4450
4451         BCMMSG(wlc->wiphy, "wl%d\n", wlc_hw->unit);
4452
4453         if (!wlc_hw->up)
4454                 return;
4455
4456         /* increment second count */
4457         wlc_hw->now++;
4458
4459         /* Check for FIFO error interrupts */
4460         brcms_b_fifoerrors(wlc_hw);
4461
4462         /* make sure RX dma has buffers */
4463         dma_rxfill(wlc->hw->di[RX_FIFO]);
4464
4465         wlc_phy_watchdog(wlc_hw->band->pi);
4466 }
4467
4468 /* common watchdog code */
4469 static void brcms_c_watchdog(void *arg)
4470 {
4471         struct brcms_c_info *wlc = (struct brcms_c_info *) arg;
4472
4473         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
4474
4475         if (!wlc->pub->up)
4476                 return;
4477
4478         if (brcms_deviceremoved(wlc)) {
4479                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
4480                           __func__);
4481                 brcms_down(wlc->wl);
4482                 return;
4483         }
4484
4485         /* increment second count */
4486         wlc->pub->now++;
4487
4488         /* delay radio disable */
4489         if (wlc->mpc_delay_off) {
4490                 if (--wlc->mpc_delay_off == 0) {
4491                         mboolset(wlc->pub->radio_disabled,
4492                                  WL_RADIO_MPC_DISABLE);
4493                         if (wlc->mpc && brcms_c_ismpc(wlc))
4494                                 wlc->mpc_offcnt = 0;
4495                 }
4496         }
4497
4498         /* mpc sync */
4499         brcms_c_radio_mpc_upd(wlc);
4500         /* radio sync: sw/hw/mpc --> radio_disable/radio_enable */
4501         brcms_c_radio_hwdisable_upd(wlc);
4502         brcms_c_radio_upd(wlc);
4503         /* if radio is disable, driver may be down, quit here */
4504         if (wlc->pub->radio_disabled)
4505                 return;
4506
4507         brcms_b_watchdog(wlc);
4508
4509         /*
4510          * occasionally sample mac stat counters to
4511          * detect 16-bit counter wrap
4512          */
4513         if ((wlc->pub->now % SW_TIMER_MAC_STAT_UPD) == 0)
4514                 brcms_c_statsupd(wlc);
4515
4516         if (BRCMS_ISNPHY(wlc->band) &&
4517             ((wlc->pub->now - wlc->tempsense_lasttime) >=
4518              BRCMS_TEMPSENSE_PERIOD)) {
4519                 wlc->tempsense_lasttime = wlc->pub->now;
4520                 brcms_c_tempsense_upd(wlc);
4521         }
4522 }
4523
4524 static void brcms_c_watchdog_by_timer(void *arg)
4525 {
4526         brcms_c_watchdog(arg);
4527 }
4528
4529 bool brcms_c_timers_init(struct brcms_c_info *wlc, int unit)
4530 {
4531         wlc->wdtimer = brcms_init_timer(wlc->wl, brcms_c_watchdog_by_timer,
4532                 wlc, "watchdog");
4533         if (!wlc->wdtimer) {
4534                 wiphy_err(wlc->wiphy, "wl%d:  wl_init_timer for wdtimer "
4535                           "failed\n", unit);
4536                 goto fail;
4537         }
4538
4539         wlc->radio_timer = brcms_init_timer(wlc->wl, brcms_c_radio_timer,
4540                 wlc, "radio");
4541         if (!wlc->radio_timer) {
4542                 wiphy_err(wlc->wiphy, "wl%d:  wl_init_timer for radio_timer "
4543                           "failed\n", unit);
4544                 goto fail;
4545         }
4546
4547         return true;
4548
4549  fail:
4550         return false;
4551 }
4552
4553 /*
4554  * Initialize brcms_c_info default values ...
4555  * may get overrides later in this function
4556  */
4557 void brcms_c_info_init(struct brcms_c_info *wlc, int unit)
4558 {
4559         int i;
4560
4561         /* Save our copy of the chanspec */
4562         wlc->chanspec = ch20mhz_chspec(1);
4563
4564         /* various 802.11g modes */
4565         wlc->shortslot = false;
4566         wlc->shortslot_override = BRCMS_SHORTSLOT_AUTO;
4567
4568         brcms_c_protection_upd(wlc, BRCMS_PROT_G_OVR, BRCMS_PROTECTION_AUTO);
4569         brcms_c_protection_upd(wlc, BRCMS_PROT_G_SPEC, false);
4570
4571         brcms_c_protection_upd(wlc, BRCMS_PROT_N_CFG_OVR,
4572                                BRCMS_PROTECTION_AUTO);
4573         brcms_c_protection_upd(wlc, BRCMS_PROT_N_CFG, BRCMS_N_PROTECTION_OFF);
4574         brcms_c_protection_upd(wlc, BRCMS_PROT_N_NONGF_OVR,
4575                                BRCMS_PROTECTION_AUTO);
4576         brcms_c_protection_upd(wlc, BRCMS_PROT_N_NONGF, false);
4577         brcms_c_protection_upd(wlc, BRCMS_PROT_N_PAM_OVR, AUTO);
4578
4579         brcms_c_protection_upd(wlc, BRCMS_PROT_OVERLAP,
4580                                BRCMS_PROTECTION_CTL_OVERLAP);
4581
4582         /* 802.11g draft 4.0 NonERP elt advertisement */
4583         wlc->include_legacy_erp = true;
4584
4585         wlc->stf->ant_rx_ovr = ANT_RX_DIV_DEF;
4586         wlc->stf->txant = ANT_TX_DEF;
4587
4588         wlc->prb_resp_timeout = BRCMS_PRB_RESP_TIMEOUT;
4589
4590         wlc->usr_fragthresh = DOT11_DEFAULT_FRAG_LEN;
4591         for (i = 0; i < NFIFO; i++)
4592                 wlc->fragthresh[i] = DOT11_DEFAULT_FRAG_LEN;
4593         wlc->RTSThresh = DOT11_DEFAULT_RTS_LEN;
4594
4595         /* default rate fallback retry limits */
4596         wlc->SFBL = RETRY_SHORT_FB;
4597         wlc->LFBL = RETRY_LONG_FB;
4598
4599         /* default mac retry limits */
4600         wlc->SRL = RETRY_SHORT_DEF;
4601         wlc->LRL = RETRY_LONG_DEF;
4602
4603         /* WME QoS mode is Auto by default */
4604         wlc->pub->_ampdu = AMPDU_AGG_HOST;
4605         wlc->pub->bcmerror = 0;
4606
4607         /* initialize mpc delay */
4608         wlc->mpc_delay_off = wlc->mpc_dlycnt = BRCMS_MPC_MIN_DELAYCNT;
4609 }
4610
4611 static bool brcms_c_state_bmac_sync(struct brcms_c_info *wlc)
4612 {
4613         struct brcms_b_state state_bmac = {0};
4614
4615         if (brcms_b_state_get(wlc->hw, &state_bmac) != 0)
4616                 return false;
4617
4618         wlc->machwcap = state_bmac.machwcap;
4619         brcms_c_protection_upd(wlc, BRCMS_PROT_N_PAM_OVR,
4620                            (s8) state_bmac.preamble_ovr);
4621
4622         return true;
4623 }
4624
4625 static uint brcms_c_attach_module(struct brcms_c_info *wlc)
4626 {
4627         uint err = 0;
4628         uint unit;
4629         unit = wlc->pub->unit;
4630
4631         wlc->asi = brcms_c_antsel_attach(wlc);
4632         if (wlc->asi == NULL) {
4633                 wiphy_err(wlc->wiphy, "wl%d: attach: antsel_attach "
4634                           "failed\n", unit);
4635                 err = 44;
4636                 goto fail;
4637         }
4638
4639         wlc->ampdu = brcms_c_ampdu_attach(wlc);
4640         if (wlc->ampdu == NULL) {
4641                 wiphy_err(wlc->wiphy, "wl%d: attach: ampdu_attach "
4642                           "failed\n", unit);
4643                 err = 50;
4644                 goto fail;
4645         }
4646
4647         if ((brcms_c_stf_attach(wlc) != 0)) {
4648                 wiphy_err(wlc->wiphy, "wl%d: attach: stf_attach "
4649                           "failed\n", unit);
4650                 err = 68;
4651                 goto fail;
4652         }
4653  fail:
4654         return err;
4655 }
4656
4657 struct brcms_pub *brcms_c_pub(struct brcms_c_info *wlc)
4658 {
4659         return wlc->pub;
4660 }
4661
4662 /* low level attach
4663  *    run backplane attach, init nvram
4664  *    run phy attach
4665  *    initialize software state for each core and band
4666  *    put the whole chip in reset(driver down state), no clock
4667  */
4668 static int brcms_b_attach(struct brcms_c_info *wlc, u16 vendor, u16 device,
4669                           uint unit, bool piomode, void *regsva,
4670                           struct pci_dev *btparam)
4671 {
4672         struct brcms_hardware *wlc_hw;
4673         struct d11regs *regs;
4674         char *macaddr = NULL;
4675         char *vars;
4676         uint err = 0;
4677         uint j;
4678         bool wme = false;
4679         struct shared_phy_params sha_params;
4680         struct wiphy *wiphy = wlc->wiphy;
4681         char *var;
4682         unsigned long res;
4683
4684         BCMMSG(wlc->wiphy, "wl%d: vendor 0x%x device 0x%x\n", unit, vendor,
4685                 device);
4686
4687         wme = true;
4688
4689         wlc_hw = wlc->hw;
4690         wlc_hw->wlc = wlc;
4691         wlc_hw->unit = unit;
4692         wlc_hw->band = wlc_hw->bandstate[0];
4693         wlc_hw->_piomode = piomode;
4694
4695         /* populate struct brcms_hardware with default values  */
4696         brcms_b_info_init(wlc_hw);
4697
4698         /*
4699          * Do the hardware portion of the attach. Also initialize software
4700          * state that depends on the particular hardware we are running.
4701          */
4702         wlc_hw->sih = ai_attach(regsva, btparam,
4703                                 &wlc_hw->vars, &wlc_hw->vars_size);
4704         if (wlc_hw->sih == NULL) {
4705                 wiphy_err(wiphy, "wl%d: brcms_b_attach: si_attach failed\n",
4706                           unit);
4707                 err = 11;
4708                 goto fail;
4709         }
4710         vars = wlc_hw->vars;
4711
4712         /*
4713          * Get vendid/devid nvram overwrites, which could be different
4714          * than those the BIOS recognizes for devices on PCMCIA_BUS,
4715          * SDIO_BUS, and SROMless devices on PCI_BUS.
4716          */
4717         var = getvar(vars, "vendid");
4718         if (var && !kstrtoul(var, 0, &res)) {
4719                 vendor = (u16)res;
4720                 wiphy_err(wiphy, "Overriding vendor id = 0x%x\n",
4721                           vendor);
4722         }
4723         var = getvar(vars, "devid");
4724         if (var && !kstrtoul(var, 0, &res)) {
4725                 u16 devid = (u16)res;
4726                 if (devid != 0xffff) {
4727                         device = devid;
4728                         wiphy_err(wiphy, "Overriding device id = 0x%x"
4729                                   "\n", device);
4730                 }
4731         }
4732
4733         /* verify again the device is supported */
4734         if (!brcms_c_chipmatch(vendor, device)) {
4735                 wiphy_err(wiphy, "wl%d: brcms_b_attach: Unsupported "
4736                         "vendor/device (0x%x/0x%x)\n",
4737                          unit, vendor, device);
4738                 err = 12;
4739                 goto fail;
4740         }
4741
4742         wlc_hw->vendorid = vendor;
4743         wlc_hw->deviceid = device;
4744
4745         /* set bar0 window to point at D11 core */
4746         wlc_hw->regs = (struct d11regs *) ai_setcore(wlc_hw->sih, D11_CORE_ID,
4747                                                      0);
4748         wlc_hw->corerev = ai_corerev(wlc_hw->sih);
4749
4750         regs = wlc_hw->regs;
4751
4752         wlc->regs = wlc_hw->regs;
4753
4754         /* validate chip, chiprev and corerev */
4755         if (!brcms_c_isgoodchip(wlc_hw)) {
4756                 err = 13;
4757                 goto fail;
4758         }
4759
4760         /* initialize power control registers */
4761         ai_clkctl_init(wlc_hw->sih);
4762
4763         /* request fastclock and force fastclock for the rest of attach
4764          * bring the d11 core out of reset.
4765          *   For PMU chips, the first wlc_clkctl_clk is no-op since core-clk
4766          *   is still false; But it will be called again inside wlc_corereset,
4767          *   after d11 is out of reset.
4768          */
4769         brcms_b_clkctl_clk(wlc_hw, CLK_FAST);
4770         brcms_b_corereset(wlc_hw, BRCMS_USE_COREFLAGS);
4771
4772         if (!brcms_b_validate_chip_access(wlc_hw)) {
4773                 wiphy_err(wiphy, "wl%d: brcms_b_attach: validate_chip_access "
4774                         "failed\n", unit);
4775                 err = 14;
4776                 goto fail;
4777         }
4778
4779         /* get the board rev, used just below */
4780         j = getintvar(vars, "boardrev");
4781         /* promote srom boardrev of 0xFF to 1 */
4782         if (j == BOARDREV_PROMOTABLE)
4783                 j = BOARDREV_PROMOTED;
4784         wlc_hw->boardrev = (u16) j;
4785         if (!brcms_c_validboardtype(wlc_hw)) {
4786                 wiphy_err(wiphy, "wl%d: brcms_b_attach: Unsupported Broadcom "
4787                         "board type (0x%x)" " or revision level (0x%x)\n",
4788                          unit, wlc_hw->sih->boardtype, wlc_hw->boardrev);
4789                 err = 15;
4790                 goto fail;
4791         }
4792         wlc_hw->sromrev = (u8) getintvar(vars, "sromrev");
4793         wlc_hw->boardflags = (u32) getintvar(vars, "boardflags");
4794         wlc_hw->boardflags2 = (u32) getintvar(vars, "boardflags2");
4795
4796         if (wlc_hw->boardflags & BFL_NOPLLDOWN)
4797                 brcms_b_pllreq(wlc_hw, true, BRCMS_PLLREQ_SHARED);
4798
4799         /* check device id(srom, nvram etc.) to set bands */
4800         if (wlc_hw->deviceid == BCM43224_D11N_ID ||
4801             wlc_hw->deviceid == BCM43224_D11N_ID_VEN1)
4802                 /* Dualband boards */
4803                 wlc_hw->_nbands = 2;
4804         else
4805                 wlc_hw->_nbands = 1;
4806
4807         if ((wlc_hw->sih->chip == BCM43225_CHIP_ID))
4808                 wlc_hw->_nbands = 1;
4809
4810         /* BMAC_NOTE: remove init of pub values when brcms_c_attach()
4811          * unconditionally does the init of these values
4812          */
4813         wlc->vendorid = wlc_hw->vendorid;
4814         wlc->deviceid = wlc_hw->deviceid;
4815         wlc->pub->sih = wlc_hw->sih;
4816         wlc->pub->corerev = wlc_hw->corerev;
4817         wlc->pub->sromrev = wlc_hw->sromrev;
4818         wlc->pub->boardrev = wlc_hw->boardrev;
4819         wlc->pub->boardflags = wlc_hw->boardflags;
4820         wlc->pub->boardflags2 = wlc_hw->boardflags2;
4821         wlc->pub->_nbands = wlc_hw->_nbands;
4822
4823         wlc_hw->physhim = wlc_phy_shim_attach(wlc_hw, wlc->wl, wlc);
4824
4825         if (wlc_hw->physhim == NULL) {
4826                 wiphy_err(wiphy, "wl%d: brcms_b_attach: wlc_phy_shim_attach "
4827                         "failed\n", unit);
4828                 err = 25;
4829                 goto fail;
4830         }
4831
4832         /* pass all the parameters to wlc_phy_shared_attach in one struct */
4833         sha_params.sih = wlc_hw->sih;
4834         sha_params.physhim = wlc_hw->physhim;
4835         sha_params.unit = unit;
4836         sha_params.corerev = wlc_hw->corerev;
4837         sha_params.vars = vars;
4838         sha_params.vid = wlc_hw->vendorid;
4839         sha_params.did = wlc_hw->deviceid;
4840         sha_params.chip = wlc_hw->sih->chip;
4841         sha_params.chiprev = wlc_hw->sih->chiprev;
4842         sha_params.chippkg = wlc_hw->sih->chippkg;
4843         sha_params.sromrev = wlc_hw->sromrev;
4844         sha_params.boardtype = wlc_hw->sih->boardtype;
4845         sha_params.boardrev = wlc_hw->boardrev;
4846         sha_params.boardvendor = wlc_hw->sih->boardvendor;
4847         sha_params.boardflags = wlc_hw->boardflags;
4848         sha_params.boardflags2 = wlc_hw->boardflags2;
4849         sha_params.buscorerev = wlc_hw->sih->buscorerev;
4850
4851         /* alloc and save pointer to shared phy state area */
4852         wlc_hw->phy_sh = wlc_phy_shared_attach(&sha_params);
4853         if (!wlc_hw->phy_sh) {
4854                 err = 16;
4855                 goto fail;
4856         }
4857
4858         /* initialize software state for each core and band */
4859         for (j = 0; j < wlc_hw->_nbands; j++) {
4860                 /*
4861                  * band0 is always 2.4Ghz
4862                  * band1, if present, is 5Ghz
4863                  */
4864
4865                 brcms_c_setxband(wlc_hw, j);
4866
4867                 wlc_hw->band->bandunit = j;
4868                 wlc_hw->band->bandtype = j ? BRCM_BAND_5G : BRCM_BAND_2G;
4869                 wlc->band->bandunit = j;
4870                 wlc->band->bandtype = j ? BRCM_BAND_5G : BRCM_BAND_2G;
4871                 wlc->core->coreidx = ai_coreidx(wlc_hw->sih);
4872
4873                 wlc_hw->machwcap = R_REG(&regs->machwcap);
4874                 wlc_hw->machwcap_backup = wlc_hw->machwcap;
4875
4876                 /* init tx fifo size */
4877                 wlc_hw->xmtfifo_sz =
4878                     xmtfifo_sz[(wlc_hw->corerev - XMTFIFOTBL_STARTREV)];
4879
4880                 /* Get a phy for this band */
4881                 wlc_hw->band->pi =
4882                         wlc_phy_attach(wlc_hw->phy_sh, regs,
4883                                        brcms_b_bandtype(wlc_hw), vars,
4884                                        wlc->wiphy);
4885                 if (wlc_hw->band->pi == NULL) {
4886                         wiphy_err(wiphy, "wl%d: brcms_b_attach: wlc_phy_"
4887                                   "attach failed\n", unit);
4888                         err = 17;
4889                         goto fail;
4890                 }
4891
4892                 wlc_phy_machwcap_set(wlc_hw->band->pi, wlc_hw->machwcap);
4893
4894                 wlc_phy_get_phyversion(wlc_hw->band->pi, &wlc_hw->band->phytype,
4895                                        &wlc_hw->band->phyrev,
4896                                        &wlc_hw->band->radioid,
4897                                        &wlc_hw->band->radiorev);
4898                 wlc_hw->band->abgphy_encore =
4899                     wlc_phy_get_encore(wlc_hw->band->pi);
4900                 wlc->band->abgphy_encore = wlc_phy_get_encore(wlc_hw->band->pi);
4901                 wlc_hw->band->core_flags =
4902                     wlc_phy_get_coreflags(wlc_hw->band->pi);
4903
4904                 /* verify good phy_type & supported phy revision */
4905                 if (BRCMS_ISNPHY(wlc_hw->band)) {
4906                         if (NCONF_HAS(wlc_hw->band->phyrev))
4907                                 goto good_phy;
4908                         else
4909                                 goto bad_phy;
4910                 } else if (BRCMS_ISLCNPHY(wlc_hw->band)) {
4911                         if (LCNCONF_HAS(wlc_hw->band->phyrev))
4912                                 goto good_phy;
4913                         else
4914                                 goto bad_phy;
4915                 } else {
4916  bad_phy:
4917                         wiphy_err(wiphy, "wl%d: brcms_b_attach: unsupported "
4918                                   "phy type/rev (%d/%d)\n", unit,
4919                                   wlc_hw->band->phytype, wlc_hw->band->phyrev);
4920                         err = 18;
4921                         goto fail;
4922                 }
4923
4924  good_phy:
4925                 /*
4926                  * BMAC_NOTE: wlc->band->pi should not be set below and should
4927                  * be done in the high level attach. However we can not make
4928                  * that change until all low level access is changed to
4929                  * wlc_hw->band->pi. Instead do the wlc->band->pi init below,
4930                  * keeping wlc_hw->band->pi as well for incremental update of
4931                  * low level fns, and cut over low only init when all fns
4932                  * updated.
4933                  */
4934                 wlc->band->pi = wlc_hw->band->pi;
4935                 wlc->band->phytype = wlc_hw->band->phytype;
4936                 wlc->band->phyrev = wlc_hw->band->phyrev;
4937                 wlc->band->radioid = wlc_hw->band->radioid;
4938                 wlc->band->radiorev = wlc_hw->band->radiorev;
4939
4940                 /* default contention windows size limits */
4941                 wlc_hw->band->CWmin = APHY_CWMIN;
4942                 wlc_hw->band->CWmax = PHY_CWMAX;
4943
4944                 if (!brcms_b_attach_dmapio(wlc, j, wme)) {
4945                         err = 19;
4946                         goto fail;
4947                 }
4948         }
4949
4950         /* disable core to match driver "down" state */
4951         brcms_c_coredisable(wlc_hw);
4952
4953         /* Match driver "down" state */
4954         ai_pci_down(wlc_hw->sih);
4955
4956         /* register sb interrupt callback functions */
4957         ai_register_intr_callback(wlc_hw->sih, (void *)brcms_c_wlintrsoff,
4958                                   (void *)brcms_c_wlintrsrestore, NULL, wlc);
4959
4960         /* turn off pll and xtal to match driver "down" state */
4961         brcms_b_xtal(wlc_hw, OFF);
4962
4963         /* *******************************************************************
4964          * The hardware is in the DOWN state at this point. D11 core
4965          * or cores are in reset with clocks off, and the board PLLs
4966          * are off if possible.
4967          *
4968          * Beyond this point, wlc->sbclk == false and chip registers
4969          * should not be touched.
4970          *********************************************************************
4971          */
4972
4973         /* init etheraddr state variables */
4974         macaddr = brcms_c_get_macaddr(wlc_hw);
4975         if (macaddr == NULL) {
4976                 wiphy_err(wiphy, "wl%d: brcms_b_attach: macaddr not found\n",
4977                           unit);
4978                 err = 21;
4979                 goto fail;
4980         }
4981         if (!mac_pton(macaddr, wlc_hw->etheraddr) ||
4982             is_broadcast_ether_addr(wlc_hw->etheraddr) ||
4983             is_zero_ether_addr(wlc_hw->etheraddr)) {
4984                 wiphy_err(wiphy, "wl%d: brcms_b_attach: bad macaddr %s\n",
4985                           unit, macaddr);
4986                 err = 22;
4987                 goto fail;
4988         }
4989
4990         BCMMSG(wlc->wiphy,
4991                  "deviceid 0x%x nbands %d board 0x%x macaddr: %s\n",
4992                  wlc_hw->deviceid, wlc_hw->_nbands,
4993                  wlc_hw->sih->boardtype, macaddr);
4994
4995         return err;
4996
4997  fail:
4998         wiphy_err(wiphy, "wl%d: brcms_b_attach: failed with err %d\n", unit,
4999                   err);
5000         return err;
5001 }
5002
5003 static void brcms_c_attach_antgain_init(struct brcms_c_info *wlc)
5004 {
5005         uint unit;
5006         unit = wlc->pub->unit;
5007
5008         if ((wlc->band->antgain == -1) && (wlc->pub->sromrev == 1)) {
5009                 /* default antenna gain for srom rev 1 is 2 dBm (8 qdbm) */
5010                 wlc->band->antgain = 8;
5011         } else if (wlc->band->antgain == -1) {
5012                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid antennas available in"
5013                           " srom, using 2dB\n", unit, __func__);
5014                 wlc->band->antgain = 8;
5015         } else {
5016                 s8 gain, fract;
5017                 /* Older sroms specified gain in whole dbm only.  In order
5018                  * be able to specify qdbm granularity and remain backward
5019                  * compatible the whole dbms are now encoded in only
5020                  * low 6 bits and remaining qdbms are encoded in the hi 2 bits.
5021                  * 6 bit signed number ranges from -32 - 31.
5022                  *
5023                  * Examples:
5024                  * 0x1 = 1 db,
5025                  * 0xc1 = 1.75 db (1 + 3 quarters),
5026                  * 0x3f = -1 (-1 + 0 quarters),
5027                  * 0x7f = -.75 (-1 + 1 quarters) = -3 qdbm.
5028                  * 0xbf = -.50 (-1 + 2 quarters) = -2 qdbm.
5029                  */
5030                 gain = wlc->band->antgain & 0x3f;
5031                 gain <<= 2;     /* Sign extend */
5032                 gain >>= 2;
5033                 fract = (wlc->band->antgain & 0xc0) >> 6;
5034                 wlc->band->antgain = 4 * gain + fract;
5035         }
5036 }
5037
5038 static bool brcms_c_attach_stf_ant_init(struct brcms_c_info *wlc)
5039 {
5040         int aa;
5041         uint unit;
5042         char *vars;
5043         int bandtype;
5044
5045         unit = wlc->pub->unit;
5046         vars = wlc->pub->vars;
5047         bandtype = wlc->band->bandtype;
5048
5049         /* get antennas available */
5050         aa = (s8) getintvar(vars, bandtype == BRCM_BAND_5G ? "aa5g" : "aa2g");
5051         if (aa == 0)
5052                 aa = (s8) getintvar(vars,
5053                                     bandtype == BRCM_BAND_5G ? "aa1" : "aa0");
5054         if ((aa < 1) || (aa > 15)) {
5055                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid antennas available in"
5056                           " srom (0x%x), using 3\n", unit, __func__, aa);
5057                 aa = 3;
5058         }
5059
5060         /* reset the defaults if we have a single antenna */
5061         if (aa == 1) {
5062                 wlc->stf->ant_rx_ovr = ANT_RX_DIV_FORCE_0;
5063                 wlc->stf->txant = ANT_TX_FORCE_0;
5064         } else if (aa == 2) {
5065                 wlc->stf->ant_rx_ovr = ANT_RX_DIV_FORCE_1;
5066                 wlc->stf->txant = ANT_TX_FORCE_1;
5067         } else {
5068         }
5069
5070         /* Compute Antenna Gain */
5071         wlc->band->antgain =
5072             (s8) getintvar(vars, bandtype == BRCM_BAND_5G ? "ag1" : "ag0");
5073         brcms_c_attach_antgain_init(wlc);
5074
5075         return true;
5076 }
5077
5078 static void brcms_c_bss_default_init(struct brcms_c_info *wlc)
5079 {
5080         u16 chanspec;
5081         struct brcms_band *band;
5082         struct brcms_bss_info *bi = wlc->default_bss;
5083
5084         /* init default and target BSS with some sane initial values */
5085         memset((char *)(bi), 0, sizeof(struct brcms_bss_info));
5086         bi->beacon_period = BEACON_INTERVAL_DEFAULT;
5087
5088         /* fill the default channel as the first valid channel
5089          * starting from the 2G channels
5090          */
5091         chanspec = ch20mhz_chspec(1);
5092         wlc->home_chanspec = bi->chanspec = chanspec;
5093
5094         /* find the band of our default channel */
5095         band = wlc->band;
5096         if (wlc->pub->_nbands > 1 &&
5097             band->bandunit != chspec_bandunit(chanspec))
5098                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
5099
5100         /* init bss rates to the band specific default rate set */
5101         brcms_c_rateset_default(&bi->rateset, NULL, band->phytype,
5102                 band->bandtype, false, BRCMS_RATE_MASK_FULL,
5103                 (bool) (wlc->pub->_n_enab & SUPPORT_11N),
5104                 brcms_chspec_bw(chanspec), wlc->stf->txstreams);
5105
5106         if (wlc->pub->_n_enab & SUPPORT_11N)
5107                 bi->flags |= BRCMS_BSS_HT;
5108 }
5109
5110 static struct brcms_txq_info *brcms_c_txq_alloc(struct brcms_c_info *wlc)
5111 {
5112         struct brcms_txq_info *qi, *p;
5113
5114         qi = kzalloc(sizeof(struct brcms_txq_info), GFP_ATOMIC);
5115         if (qi != NULL) {
5116                 /*
5117                  * Have enough room for control packets along with HI watermark
5118                  * Also, add room to txq for total psq packets if all the SCBs
5119                  * leave PS mode. The watermark for flowcontrol to OS packets
5120                  * will remain the same
5121                  */
5122                 brcmu_pktq_init(&qi->q, BRCMS_PREC_COUNT,
5123                           2 * BRCMS_DATAHIWAT + PKTQ_LEN_DEFAULT);
5124
5125                 /* add this queue to the the global list */
5126                 p = wlc->tx_queues;
5127                 if (p == NULL) {
5128                         wlc->tx_queues = qi;
5129                 } else {
5130                         while (p->next != NULL)
5131                                 p = p->next;
5132                         p->next = qi;
5133                 }
5134         }
5135         return qi;
5136 }
5137
5138 static void brcms_c_txq_free(struct brcms_c_info *wlc,
5139                              struct brcms_txq_info *qi)
5140 {
5141         struct brcms_txq_info *p;
5142
5143         if (qi == NULL)
5144                 return;
5145
5146         /* remove the queue from the linked list */
5147         p = wlc->tx_queues;
5148         if (p == qi)
5149                 wlc->tx_queues = p->next;
5150         else {
5151                 while (p != NULL && p->next != qi)
5152                         p = p->next;
5153                 if (p != NULL)
5154                         p->next = p->next->next;
5155         }
5156
5157         kfree(qi);
5158 }
5159
5160 static void brcms_c_update_mimo_band_bwcap(struct brcms_c_info *wlc, u8 bwcap)
5161 {
5162         uint i;
5163         struct brcms_band *band;
5164
5165         for (i = 0; i < wlc->pub->_nbands; i++) {
5166                 band = wlc->bandstate[i];
5167                 if (band->bandtype == BRCM_BAND_5G) {
5168                         if ((bwcap == BRCMS_N_BW_40ALL)
5169                             || (bwcap == BRCMS_N_BW_20IN2G_40IN5G))
5170                                 band->mimo_cap_40 = true;
5171                         else
5172                                 band->mimo_cap_40 = false;
5173                 } else {
5174                         if (bwcap == BRCMS_N_BW_40ALL)
5175                                 band->mimo_cap_40 = true;
5176                         else
5177                                 band->mimo_cap_40 = false;
5178                 }
5179         }
5180 }
5181
5182 /*
5183  * The common driver entry routine. Error codes should be unique
5184  */
5185 struct brcms_c_info *
5186 brcms_c_attach(struct brcms_info *wl, u16 vendor, u16 device, uint unit,
5187                bool piomode, void __iomem *regsva, struct pci_dev *btparam,
5188                uint *perr)
5189 {
5190         struct brcms_c_info *wlc;
5191         uint err = 0;
5192         uint i, j;
5193         struct brcms_pub *pub;
5194         uint n_disabled;
5195
5196         /* allocate struct brcms_c_info state and its substructures */
5197         wlc = (struct brcms_c_info *) brcms_c_attach_malloc(unit, &err, device);
5198         if (wlc == NULL)
5199                 goto fail;
5200         wlc->wiphy = wl->wiphy;
5201         pub = wlc->pub;
5202
5203 #if defined(BCMDBG)
5204         wlc_info_dbg = wlc;
5205 #endif
5206
5207         wlc->band = wlc->bandstate[0];
5208         wlc->core = wlc->corestate;
5209         wlc->wl = wl;
5210         pub->unit = unit;
5211         pub->_piomode = piomode;
5212         wlc->bandinit_pending = false;
5213
5214         /* populate struct brcms_c_info with default values  */
5215         brcms_c_info_init(wlc, unit);
5216
5217         /* update sta/ap related parameters */
5218         brcms_c_ap_upd(wlc);
5219
5220         /* 11n_disable nvram */
5221         n_disabled = getintvar(pub->vars, "11n_disable");
5222
5223         /*
5224          * low level attach steps(all hw accesses go
5225          * inside, no more in rest of the attach)
5226          */
5227         err = brcms_b_attach(wlc, vendor, device, unit, piomode, regsva,
5228                              btparam);
5229         if (err)
5230                 goto fail;
5231
5232         /*
5233          * for some states, due to different info pointer(e,g, wlc, wlc_hw) or
5234          * master/slave split, HIGH driver(both monolithic and HIGH_ONLY) needs
5235          * to sync states FROM BMAC portion driver
5236          */
5237         if (!brcms_c_state_bmac_sync(wlc)) {
5238                 err = 20;
5239                 goto fail;
5240         }
5241
5242         pub->phy_11ncapable = BRCMS_PHY_11N_CAP(wlc->band);
5243
5244         /* propagate *vars* from BMAC driver to high driver */
5245         brcms_b_copyfrom_vars(wlc->hw, &pub->vars, &wlc->vars_size);
5246
5247
5248         /* set maximum allowed duty cycle */
5249         wlc->tx_duty_cycle_ofdm =
5250             (u16) getintvar(pub->vars, "tx_duty_cycle_ofdm");
5251         wlc->tx_duty_cycle_cck =
5252             (u16) getintvar(pub->vars, "tx_duty_cycle_cck");
5253
5254         brcms_c_stf_phy_chain_calc(wlc);
5255
5256         /* txchain 1: txant 0, txchain 2: txant 1 */
5257         if (BRCMS_ISNPHY(wlc->band) && (wlc->stf->txstreams == 1))
5258                 wlc->stf->txant = wlc->stf->hw_txchain - 1;
5259
5260         /* push to BMAC driver */
5261         wlc_phy_stf_chain_init(wlc->band->pi, wlc->stf->hw_txchain,
5262                                wlc->stf->hw_rxchain);
5263
5264         /* pull up some info resulting from the low attach */
5265         for (i = 0; i < NFIFO; i++)
5266                 wlc->core->txavail[i] = wlc->hw->txavail[i];
5267
5268         brcms_b_hw_etheraddr(wlc->hw, wlc->perm_etheraddr);
5269
5270         memcpy(&pub->cur_etheraddr, &wlc->perm_etheraddr, ETH_ALEN);
5271
5272         for (j = 0; j < wlc->pub->_nbands; j++) {
5273                 wlc->band = wlc->bandstate[j];
5274
5275                 if (!brcms_c_attach_stf_ant_init(wlc)) {
5276                         err = 24;
5277                         goto fail;
5278                 }
5279
5280                 /* default contention windows size limits */
5281                 wlc->band->CWmin = APHY_CWMIN;
5282                 wlc->band->CWmax = PHY_CWMAX;
5283
5284                 /* init gmode value */
5285                 if (wlc->band->bandtype == BRCM_BAND_2G) {
5286                         wlc->band->gmode = GMODE_AUTO;
5287                         brcms_c_protection_upd(wlc, BRCMS_PROT_G_USER,
5288                                            wlc->band->gmode);
5289                 }
5290
5291                 /* init _n_enab supported mode */
5292                 if (BRCMS_PHY_11N_CAP(wlc->band)) {
5293                         if (n_disabled & WLFEATURE_DISABLE_11N) {
5294                                 pub->_n_enab = OFF;
5295                                 brcms_c_protection_upd(wlc, BRCMS_PROT_N_USER,
5296                                                        OFF);
5297                         } else {
5298                                 pub->_n_enab = SUPPORT_11N;
5299                                 brcms_c_protection_upd(wlc, BRCMS_PROT_N_USER,
5300                                                    ((pub->_n_enab ==
5301                                                      SUPPORT_11N) ? WL_11N_2x2 :
5302                                                     WL_11N_3x3));
5303                         }
5304                 }
5305
5306                 /* init per-band default rateset, depend on band->gmode */
5307                 brcms_default_rateset(wlc, &wlc->band->defrateset);
5308
5309                 /* fill in hw_rateset */
5310                 brcms_c_rateset_filter(&wlc->band->defrateset,
5311                                    &wlc->band->hw_rateset, false,
5312                                    BRCMS_RATES_CCK_OFDM, BRCMS_RATE_MASK,
5313                                    (bool) (wlc->pub->_n_enab & SUPPORT_11N));
5314         }
5315
5316         /*
5317          * update antenna config due to
5318          * wlc->stf->txant/txchain/ant_rx_ovr change
5319          */
5320         brcms_c_stf_phy_txant_upd(wlc);
5321
5322         /* attach each modules */
5323         err = brcms_c_attach_module(wlc);
5324         if (err != 0)
5325                 goto fail;
5326
5327         if (!brcms_c_timers_init(wlc, unit)) {
5328                 wiphy_err(wl->wiphy, "wl%d: %s: init_timer failed\n", unit,
5329                           __func__);
5330                 err = 32;
5331                 goto fail;
5332         }
5333
5334         /* depend on rateset, gmode */
5335         wlc->cmi = brcms_c_channel_mgr_attach(wlc);
5336         if (!wlc->cmi) {
5337                 wiphy_err(wl->wiphy, "wl%d: %s: channel_mgr_attach failed"
5338                           "\n", unit, __func__);
5339                 err = 33;
5340                 goto fail;
5341         }
5342
5343         /* init default when all parameters are ready, i.e. ->rateset */
5344         brcms_c_bss_default_init(wlc);
5345
5346         /*
5347          * Complete the wlc default state initializations..
5348          */
5349
5350         /* allocate our initial queue */
5351         wlc->pkt_queue = brcms_c_txq_alloc(wlc);
5352         if (wlc->pkt_queue == NULL) {
5353                 wiphy_err(wl->wiphy, "wl%d: %s: failed to malloc tx queue\n",
5354                           unit, __func__);
5355                 err = 100;
5356                 goto fail;
5357         }
5358
5359         wlc->bsscfg->_idx = 0;
5360         wlc->bsscfg->wlc = wlc;
5361
5362         wlc->mimoft = FT_HT;
5363         wlc->mimo_40txbw = AUTO;
5364         wlc->ofdm_40txbw = AUTO;
5365         wlc->cck_40txbw = AUTO;
5366         brcms_c_update_mimo_band_bwcap(wlc, BRCMS_N_BW_20IN2G_40IN5G);
5367
5368         /* Set default values of SGI */
5369         if (BRCMS_SGI_CAP_PHY(wlc)) {
5370                 brcms_c_ht_update_sgi_rx(wlc, (BRCMS_N_SGI_20 |
5371                                                BRCMS_N_SGI_40));
5372         } else if (BRCMS_ISSSLPNPHY(wlc->band)) {
5373                 brcms_c_ht_update_sgi_rx(wlc, (BRCMS_N_SGI_20 |
5374                                                BRCMS_N_SGI_40));
5375         } else {
5376                 brcms_c_ht_update_sgi_rx(wlc, 0);
5377         }
5378
5379         /* *******nvram 11n config overrides Start ********* */
5380
5381         if (n_disabled & WLFEATURE_DISABLE_11N_SGI_RX)
5382                 brcms_c_ht_update_sgi_rx(wlc, 0);
5383
5384         /* apply the stbc override from nvram conf */
5385         if (n_disabled & WLFEATURE_DISABLE_11N_STBC_TX) {
5386                 wlc->bandstate[BAND_2G_INDEX]->band_stf_stbc_tx = OFF;
5387                 wlc->bandstate[BAND_5G_INDEX]->band_stf_stbc_tx = OFF;
5388         }
5389         if (n_disabled & WLFEATURE_DISABLE_11N_STBC_RX)
5390                 brcms_c_stf_stbc_rx_set(wlc, HT_CAP_RX_STBC_NO);
5391
5392         /* initialize radio_mpc_disable according to wlc->mpc */
5393         brcms_c_radio_mpc_upd(wlc);
5394         brcms_b_antsel_set(wlc->hw, wlc->asi->antsel_avail);
5395
5396         if (perr)
5397                 *perr = 0;
5398
5399         return wlc;
5400
5401  fail:
5402         wiphy_err(wl->wiphy, "wl%d: %s: failed with err %d\n",
5403                   unit, __func__, err);
5404         if (wlc)
5405                 brcms_c_detach(wlc);
5406
5407         if (perr)
5408                 *perr = err;
5409         return NULL;
5410 }
5411
5412 static void brcms_c_timers_deinit(struct brcms_c_info *wlc)
5413 {
5414         /* free timer state */
5415         if (wlc->wdtimer) {
5416                 brcms_free_timer(wlc->wl, wlc->wdtimer);
5417                 wlc->wdtimer = NULL;
5418         }
5419         if (wlc->radio_timer) {
5420                 brcms_free_timer(wlc->wl, wlc->radio_timer);
5421                 wlc->radio_timer = NULL;
5422         }
5423 }
5424
5425 static void brcms_c_detach_module(struct brcms_c_info *wlc)
5426 {
5427         if (wlc->asi) {
5428                 brcms_c_antsel_detach(wlc->asi);
5429                 wlc->asi = NULL;
5430         }
5431
5432         if (wlc->ampdu) {
5433                 brcms_c_ampdu_detach(wlc->ampdu);
5434                 wlc->ampdu = NULL;
5435         }
5436
5437         brcms_c_stf_detach(wlc);
5438 }
5439
5440 /*
5441  * low level detach
5442  */
5443 static int brcms_b_detach(struct brcms_c_info *wlc)
5444 {
5445         uint i;
5446         struct brcms_hw_band *band;
5447         struct brcms_hardware *wlc_hw = wlc->hw;
5448         int callbacks;
5449
5450         callbacks = 0;
5451
5452         if (wlc_hw->sih) {
5453                 /*
5454                  * detach interrupt sync mechanism since interrupt is disabled
5455                  * and per-port interrupt object may has been freed. this must
5456                  * be done before sb core switch
5457                  */
5458                 ai_deregister_intr_callback(wlc_hw->sih);
5459                 ai_pci_sleep(wlc_hw->sih);
5460         }
5461
5462         brcms_b_detach_dmapio(wlc_hw);
5463
5464         band = wlc_hw->band;
5465         for (i = 0; i < wlc_hw->_nbands; i++) {
5466                 if (band->pi) {
5467                         /* Detach this band's phy */
5468                         wlc_phy_detach(band->pi);
5469                         band->pi = NULL;
5470                 }
5471                 band = wlc_hw->bandstate[OTHERBANDUNIT(wlc)];
5472         }
5473
5474         /* Free shared phy state */
5475         kfree(wlc_hw->phy_sh);
5476
5477         wlc_phy_shim_detach(wlc_hw->physhim);
5478
5479         /* free vars */
5480         kfree(wlc_hw->vars);
5481         wlc_hw->vars = NULL;
5482
5483         if (wlc_hw->sih) {
5484                 ai_detach(wlc_hw->sih);
5485                 wlc_hw->sih = NULL;
5486         }
5487
5488         return callbacks;
5489
5490 }
5491
5492 /*
5493  * Return a count of the number of driver callbacks still pending.
5494  *
5495  * General policy is that brcms_c_detach can only dealloc/free software states.
5496  * It can NOT touch hardware registers since the d11core may be in reset and
5497  * clock may not be available.
5498  * One exception is sb register access, which is possible if crystal is turned
5499  * on after "down" state, driver should avoid software timer with the exception
5500  * of radio_monitor.
5501  */
5502 uint brcms_c_detach(struct brcms_c_info *wlc)
5503 {
5504         uint callbacks = 0;
5505
5506         if (wlc == NULL)
5507                 return 0;
5508
5509         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
5510
5511         callbacks += brcms_b_detach(wlc);
5512
5513         /* delete software timers */
5514         if (!brcms_c_radio_monitor_stop(wlc))
5515                 callbacks++;
5516
5517         brcms_c_channel_mgr_detach(wlc->cmi);
5518
5519         brcms_c_timers_deinit(wlc);
5520
5521         brcms_c_detach_module(wlc);
5522
5523
5524         while (wlc->tx_queues != NULL)
5525                 brcms_c_txq_free(wlc, wlc->tx_queues);
5526
5527         brcms_c_detach_mfree(wlc);
5528         return callbacks;
5529 }
5530
5531 /* update state that depends on the current value of "ap" */
5532 void brcms_c_ap_upd(struct brcms_c_info *wlc)
5533 {
5534         /* STA-BSS; short capable */
5535         wlc->PLCPHdr_override = BRCMS_PLCP_SHORT;
5536
5537         /* fixup mpc */
5538         wlc->mpc = true;
5539 }
5540
5541 /*
5542  * return true if Minimum Power Consumption should
5543  * be entered, false otherwise
5544  */
5545 bool brcms_c_is_non_delay_mpc(struct brcms_c_info *wlc)
5546 {
5547         return false;
5548 }
5549
5550 bool brcms_c_ismpc(struct brcms_c_info *wlc)
5551 {
5552         return (wlc->mpc_delay_off == 0) && (brcms_c_is_non_delay_mpc(wlc));
5553 }
5554
5555 void brcms_c_radio_mpc_upd(struct brcms_c_info *wlc)
5556 {
5557         bool mpc_radio, radio_state;
5558
5559         /*
5560          * Clear the WL_RADIO_MPC_DISABLE bit when mpc feature is disabled
5561          * in case the WL_RADIO_MPC_DISABLE bit was set. Stop the radio
5562          * monitor also when WL_RADIO_MPC_DISABLE is the only reason that
5563          * the radio is going down.
5564          */
5565         if (!wlc->mpc) {
5566                 if (!wlc->pub->radio_disabled)
5567                         return;
5568                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE);
5569                 brcms_c_radio_upd(wlc);
5570                 if (!wlc->pub->radio_disabled)
5571                         brcms_c_radio_monitor_stop(wlc);
5572                 return;
5573         }
5574
5575         /*
5576          * sync ismpc logic with WL_RADIO_MPC_DISABLE bit in
5577          * wlc->pub->radio_disabled to go ON, always call radio_upd
5578          * synchronously to go OFF, postpone radio_upd to later when
5579          * context is safe(e.g. watchdog)
5580          */
5581         radio_state =
5582             (mboolisset(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE) ? OFF :
5583              ON);
5584         mpc_radio = (brcms_c_ismpc(wlc) == true) ? OFF : ON;
5585
5586         if (radio_state == ON && mpc_radio == OFF)
5587                 wlc->mpc_delay_off = wlc->mpc_dlycnt;
5588         else if (radio_state == OFF && mpc_radio == ON) {
5589                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE);
5590                 brcms_c_radio_upd(wlc);
5591                 if (wlc->mpc_offcnt < BRCMS_MPC_THRESHOLD)
5592                         wlc->mpc_dlycnt = BRCMS_MPC_MAX_DELAYCNT;
5593                 else
5594                         wlc->mpc_dlycnt = BRCMS_MPC_MIN_DELAYCNT;
5595         }
5596         /*
5597          * Below logic is meant to capture the transition from mpc off
5598          * to mpc on for reasons other than wlc->mpc_delay_off keeping
5599          * the mpc off. In that case reset wlc->mpc_delay_off to
5600          * wlc->mpc_dlycnt, so that we restart the countdown of mpc_delay_off
5601          */
5602         if ((wlc->prev_non_delay_mpc == false) &&
5603             (brcms_c_is_non_delay_mpc(wlc) == true) && wlc->mpc_delay_off)
5604                 wlc->mpc_delay_off = wlc->mpc_dlycnt;
5605
5606         wlc->prev_non_delay_mpc = brcms_c_is_non_delay_mpc(wlc);
5607 }
5608 /* Initialize just the hardware when coming out of POR or S3/S5 system states */
5609 static void brcms_b_hw_up(struct brcms_hardware *wlc_hw)
5610 {
5611         if (wlc_hw->wlc->pub->hw_up)
5612                 return;
5613
5614         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
5615
5616         /*
5617          * Enable pll and xtal, initialize the power control registers,
5618          * and force fastclock for the remainder of brcms_c_up().
5619          */
5620         brcms_b_xtal(wlc_hw, ON);
5621         ai_clkctl_init(wlc_hw->sih);
5622         brcms_b_clkctl_clk(wlc_hw, CLK_FAST);
5623
5624         ai_pci_fixcfg(wlc_hw->sih);
5625
5626         /*
5627          * AI chip doesn't restore bar0win2 on
5628          * hibernation/resume, need sw fixup
5629          */
5630         if ((wlc_hw->sih->chip == BCM43224_CHIP_ID) ||
5631             (wlc_hw->sih->chip == BCM43225_CHIP_ID))
5632                 wlc_hw->regs = (struct d11regs *)
5633                                 ai_setcore(wlc_hw->sih, D11_CORE_ID, 0);
5634
5635         /*
5636          * Inform phy that a POR reset has occurred so
5637          * it does a complete phy init
5638          */
5639         wlc_phy_por_inform(wlc_hw->band->pi);
5640
5641         wlc_hw->ucode_loaded = false;
5642         wlc_hw->wlc->pub->hw_up = true;
5643
5644         if ((wlc_hw->boardflags & BFL_FEM)
5645             && (wlc_hw->sih->chip == BCM4313_CHIP_ID)) {
5646                 if (!
5647                     (wlc_hw->boardrev >= 0x1250
5648                      && (wlc_hw->boardflags & BFL_FEM_BT)))
5649                         ai_epa_4313war(wlc_hw->sih);
5650         }
5651 }
5652
5653 static int brcms_b_up_prep(struct brcms_hardware *wlc_hw)
5654 {
5655         uint coremask;
5656
5657         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
5658
5659         /*
5660          * Enable pll and xtal, initialize the power control registers,
5661          * and force fastclock for the remainder of brcms_c_up().
5662          */
5663         brcms_b_xtal(wlc_hw, ON);
5664         ai_clkctl_init(wlc_hw->sih);
5665         brcms_b_clkctl_clk(wlc_hw, CLK_FAST);
5666
5667         /*
5668          * Configure pci/pcmcia here instead of in brcms_c_attach()
5669          * to allow mfg hotswap:  down, hotswap (chip power cycle), up.
5670          */
5671         coremask = (1 << wlc_hw->wlc->core->coreidx);
5672
5673         ai_pci_setup(wlc_hw->sih, coremask);
5674
5675         /*
5676          * Need to read the hwradio status here to cover the case where the
5677          * system is loaded with the hw radio disabled. We do not want to
5678          * bring the driver up in this case.
5679          */
5680         if (brcms_b_radio_read_hwdisabled(wlc_hw)) {
5681                 /* put SB PCI in down state again */
5682                 ai_pci_down(wlc_hw->sih);
5683                 brcms_b_xtal(wlc_hw, OFF);
5684                 return -ENOMEDIUM;
5685         }
5686
5687         ai_pci_up(wlc_hw->sih);
5688
5689         /* reset the d11 core */
5690         brcms_b_corereset(wlc_hw, BRCMS_USE_COREFLAGS);
5691
5692         return 0;
5693 }
5694
5695 static int brcms_b_up_finish(struct brcms_hardware *wlc_hw)
5696 {
5697         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
5698
5699         wlc_hw->up = true;
5700         wlc_phy_hw_state_upd(wlc_hw->band->pi, true);
5701
5702         /* FULLY enable dynamic power control and d11 core interrupt */
5703         brcms_b_clkctl_clk(wlc_hw, CLK_DYNAMIC);
5704         brcms_intrson(wlc_hw->wlc->wl);
5705         return 0;
5706 }
5707
5708 /*
5709  * Write WME tunable parameters for retransmit/max rate
5710  * from wlc struct to ucode
5711  */
5712 static void brcms_c_wme_retries_write(struct brcms_c_info *wlc)
5713 {
5714         int ac;
5715
5716         /* Need clock to do this */
5717         if (!wlc->clk)
5718                 return;
5719
5720         for (ac = 0; ac < AC_COUNT; ac++)
5721                 brcms_c_write_shm(wlc, M_AC_TXLMT_ADDR(ac),
5722                                   wlc->wme_retries[ac]);
5723 }
5724
5725 /* make interface operational */
5726 int brcms_c_up(struct brcms_c_info *wlc)
5727 {
5728         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
5729
5730         /* HW is turned off so don't try to access it */
5731         if (wlc->pub->hw_off || brcms_deviceremoved(wlc))
5732                 return -ENOMEDIUM;
5733
5734         if (!wlc->pub->hw_up) {
5735                 brcms_b_hw_up(wlc->hw);
5736                 wlc->pub->hw_up = true;
5737         }
5738
5739         if ((wlc->pub->boardflags & BFL_FEM)
5740             && (wlc->pub->sih->chip == BCM4313_CHIP_ID)) {
5741                 if (wlc->pub->boardrev >= 0x1250
5742                     && (wlc->pub->boardflags & BFL_FEM_BT))
5743                         brcms_c_mhf(wlc, MHF5, MHF5_4313_GPIOCTRL,
5744                                 MHF5_4313_GPIOCTRL, BRCM_BAND_ALL);
5745                 else
5746                         brcms_c_mhf(wlc, MHF4, MHF4_EXTPA_ENABLE,
5747                                     MHF4_EXTPA_ENABLE, BRCM_BAND_ALL);
5748         }
5749
5750         /*
5751          * Need to read the hwradio status here to cover the case where the
5752          * system is loaded with the hw radio disabled. We do not want to bring
5753          * the driver up in this case. If radio is disabled, abort up, lower
5754          * power, start radio timer and return 0(for NDIS) don't call
5755          * radio_update to avoid looping brcms_c_up.
5756          *
5757          * brcms_b_up_prep() returns either 0 or -BCME_RADIOOFF only
5758          */
5759         if (!wlc->pub->radio_disabled) {
5760                 int status = brcms_b_up_prep(wlc->hw);
5761                 if (status == -ENOMEDIUM) {
5762                         if (!mboolisset
5763                             (wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE)) {
5764                                 struct brcms_bss_cfg *bsscfg = wlc->bsscfg;
5765                                 mboolset(wlc->pub->radio_disabled,
5766                                          WL_RADIO_HW_DISABLE);
5767
5768                                 if (bsscfg->enable && bsscfg->BSS)
5769                                         wiphy_err(wlc->wiphy, "wl%d: up"
5770                                                   ": rfdisable -> "
5771                                                   "bsscfg_disable()\n",
5772                                                    wlc->pub->unit);
5773                         }
5774                 }
5775         }
5776
5777         if (wlc->pub->radio_disabled) {
5778                 brcms_c_radio_monitor_start(wlc);
5779                 return 0;
5780         }
5781
5782         /* brcms_b_up_prep has done brcms_c_corereset(). so clk is on, set it */
5783         wlc->clk = true;
5784
5785         brcms_c_radio_monitor_stop(wlc);
5786
5787         /* Set EDCF hostflags */
5788         brcms_c_mhf(wlc, MHF1, MHF1_EDCF, MHF1_EDCF, BRCM_BAND_ALL);
5789
5790         brcms_init(wlc->wl);
5791         wlc->pub->up = true;
5792
5793         if (wlc->bandinit_pending) {
5794                 brcms_c_suspend_mac_and_wait(wlc);
5795                 brcms_c_set_chanspec(wlc, wlc->default_bss->chanspec);
5796                 wlc->bandinit_pending = false;
5797                 brcms_c_enable_mac(wlc);
5798         }
5799
5800         brcms_b_up_finish(wlc->hw);
5801
5802         /* Program the TX wme params with the current settings */
5803         brcms_c_wme_retries_write(wlc);
5804
5805         /* start one second watchdog timer */
5806         brcms_add_timer(wlc->wl, wlc->wdtimer, TIMER_INTERVAL_WATCHDOG, true);
5807         wlc->WDarmed = true;
5808
5809         /* ensure antenna config is up to date */
5810         brcms_c_stf_phy_txant_upd(wlc);
5811         /* ensure LDPC config is in sync */
5812         brcms_c_ht_update_ldpc(wlc, wlc->stf->ldpc);
5813
5814         return 0;
5815 }
5816
5817 static uint brcms_c_down_del_timer(struct brcms_c_info *wlc)
5818 {
5819         uint callbacks = 0;
5820
5821         return callbacks;
5822 }
5823
5824 static int brcms_b_bmac_down_prep(struct brcms_hardware *wlc_hw)
5825 {
5826         bool dev_gone;
5827         uint callbacks = 0;
5828
5829         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
5830
5831         if (!wlc_hw->up)
5832                 return callbacks;
5833
5834         dev_gone = brcms_deviceremoved(wlc_hw->wlc);
5835
5836         /* disable interrupts */
5837         if (dev_gone)
5838                 wlc_hw->wlc->macintmask = 0;
5839         else {
5840                 /* now disable interrupts */
5841                 brcms_intrsoff(wlc_hw->wlc->wl);
5842
5843                 /* ensure we're running on the pll clock again */
5844                 brcms_b_clkctl_clk(wlc_hw, CLK_FAST);
5845         }
5846         /* down phy at the last of this stage */
5847         callbacks += wlc_phy_down(wlc_hw->band->pi);
5848
5849         return callbacks;
5850 }
5851
5852 static int brcms_b_down_finish(struct brcms_hardware *wlc_hw)
5853 {
5854         uint callbacks = 0;
5855         bool dev_gone;
5856
5857         BCMMSG(wlc_hw->wlc->wiphy, "wl%d\n", wlc_hw->unit);
5858
5859         if (!wlc_hw->up)
5860                 return callbacks;
5861
5862         wlc_hw->up = false;
5863         wlc_phy_hw_state_upd(wlc_hw->band->pi, false);
5864
5865         dev_gone = brcms_deviceremoved(wlc_hw->wlc);
5866
5867         if (dev_gone) {
5868                 wlc_hw->sbclk = false;
5869                 wlc_hw->clk = false;
5870                 wlc_phy_hw_clk_state_upd(wlc_hw->band->pi, false);
5871
5872                 /* reclaim any posted packets */
5873                 brcms_c_flushqueues(wlc_hw->wlc);
5874         } else {
5875
5876                 /* Reset and disable the core */
5877                 if (ai_iscoreup(wlc_hw->sih)) {
5878                         if (R_REG(&wlc_hw->regs->maccontrol) &
5879                             MCTL_EN_MAC)
5880                                 brcms_c_suspend_mac_and_wait(wlc_hw->wlc);
5881                         callbacks += brcms_reset(wlc_hw->wlc->wl);
5882                         brcms_c_coredisable(wlc_hw);
5883                 }
5884
5885                 /* turn off primary xtal and pll */
5886                 if (!wlc_hw->noreset) {
5887                         ai_pci_down(wlc_hw->sih);
5888                         brcms_b_xtal(wlc_hw, OFF);
5889                 }
5890         }
5891
5892         return callbacks;
5893 }
5894
5895 /*
5896  * Mark the interface nonoperational, stop the software mechanisms,
5897  * disable the hardware, free any transient buffer state.
5898  * Return a count of the number of driver callbacks still pending.
5899  */
5900 uint brcms_c_down(struct brcms_c_info *wlc)
5901 {
5902
5903         uint callbacks = 0;
5904         int i;
5905         bool dev_gone = false;
5906         struct brcms_txq_info *qi;
5907
5908         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
5909
5910         /* check if we are already in the going down path */
5911         if (wlc->going_down) {
5912                 wiphy_err(wlc->wiphy, "wl%d: %s: Driver going down so return"
5913                           "\n", wlc->pub->unit, __func__);
5914                 return 0;
5915         }
5916         if (!wlc->pub->up)
5917                 return callbacks;
5918
5919         /* in between, mpc could try to bring down again.. */
5920         wlc->going_down = true;
5921
5922         callbacks += brcms_b_bmac_down_prep(wlc->hw);
5923
5924         dev_gone = brcms_deviceremoved(wlc);
5925
5926         /* Call any registered down handlers */
5927         for (i = 0; i < BRCMS_MAXMODULES; i++) {
5928                 if (wlc->modulecb[i].down_fn)
5929                         callbacks +=
5930                             wlc->modulecb[i].down_fn(wlc->modulecb[i].hdl);
5931         }
5932
5933         /* cancel the watchdog timer */
5934         if (wlc->WDarmed) {
5935                 if (!brcms_del_timer(wlc->wl, wlc->wdtimer))
5936                         callbacks++;
5937                 wlc->WDarmed = false;
5938         }
5939         /* cancel all other timers */
5940         callbacks += brcms_c_down_del_timer(wlc);
5941
5942         wlc->pub->up = false;
5943
5944         wlc_phy_mute_upd(wlc->band->pi, false, PHY_MUTE_ALL);
5945
5946         /* clear txq flow control */
5947         brcms_c_txflowcontrol_reset(wlc);
5948
5949         /* flush tx queues */
5950         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next)
5951                 brcmu_pktq_flush(&qi->q, true, NULL, NULL);
5952
5953         callbacks += brcms_b_down_finish(wlc->hw);
5954
5955         /* brcms_b_down_finish has done brcms_c_coredisable(). so clk is off */
5956         wlc->clk = false;
5957
5958         wlc->going_down = false;
5959         return callbacks;
5960 }
5961
5962 /* Set the current gmode configuration */
5963 int brcms_c_set_gmode(struct brcms_c_info *wlc, u8 gmode, bool config)
5964 {
5965         int ret = 0;
5966         uint i;
5967         struct brcms_c_rateset rs;
5968         /* Default to 54g Auto */
5969         /* Advertise and use shortslot (-1/0/1 Auto/Off/On) */
5970         s8 shortslot = BRCMS_SHORTSLOT_AUTO;
5971         bool shortslot_restrict = false; /* Restrict association to stations
5972                                           * that support shortslot
5973                                           */
5974         bool ofdm_basic = false;        /* Make 6, 12, and 24 basic rates */
5975         /* Advertise and use short preambles (-1/0/1 Auto/Off/On) */
5976         int preamble = BRCMS_PLCP_LONG;
5977         bool preamble_restrict = false; /* Restrict association to stations
5978                                          * that support short preambles
5979                                          */
5980         struct brcms_band *band;
5981
5982         /* if N-support is enabled, allow Gmode set as long as requested
5983          * Gmode is not GMODE_LEGACY_B
5984          */
5985         if ((wlc->pub->_n_enab & SUPPORT_11N) && gmode == GMODE_LEGACY_B)
5986                 return -ENOTSUPP;
5987
5988         /* verify that we are dealing with 2G band and grab the band pointer */
5989         if (wlc->band->bandtype == BRCM_BAND_2G)
5990                 band = wlc->band;
5991         else if ((wlc->pub->_nbands > 1) &&
5992                  (wlc->bandstate[OTHERBANDUNIT(wlc)]->bandtype == BRCM_BAND_2G))
5993                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
5994         else
5995                 return -EINVAL;
5996
5997         /* Legacy or bust when no OFDM is supported by regulatory */
5998         if ((brcms_c_channel_locale_flags_in_band(wlc->cmi, band->bandunit) &
5999              BRCMS_NO_OFDM) && (gmode != GMODE_LEGACY_B))
6000                 return -EINVAL;
6001
6002         /* update configuration value */
6003         if (config == true)
6004                 brcms_c_protection_upd(wlc, BRCMS_PROT_G_USER, gmode);
6005
6006         /* Clear rateset override */
6007         memset(&rs, 0, sizeof(struct brcms_c_rateset));
6008
6009         switch (gmode) {
6010         case GMODE_LEGACY_B:
6011                 shortslot = BRCMS_SHORTSLOT_OFF;
6012                 brcms_c_rateset_copy(&gphy_legacy_rates, &rs);
6013
6014                 break;
6015
6016         case GMODE_LRS:
6017                 break;
6018
6019         case GMODE_AUTO:
6020                 /* Accept defaults */
6021                 break;
6022
6023         case GMODE_ONLY:
6024                 ofdm_basic = true;
6025                 preamble = BRCMS_PLCP_SHORT;
6026                 preamble_restrict = true;
6027                 break;
6028
6029         case GMODE_PERFORMANCE:
6030                 shortslot = BRCMS_SHORTSLOT_ON;
6031                 shortslot_restrict = true;
6032                 ofdm_basic = true;
6033                 preamble = BRCMS_PLCP_SHORT;
6034                 preamble_restrict = true;
6035                 break;
6036
6037         default:
6038                 /* Error */
6039                 wiphy_err(wlc->wiphy, "wl%d: %s: invalid gmode %d\n",
6040                           wlc->pub->unit, __func__, gmode);
6041                 return -ENOTSUPP;
6042         }
6043
6044         /*
6045          * If we are switching to gmode == GMODE_LEGACY_B,
6046          * clean up rate info that may refer to OFDM rates.
6047          */
6048         if ((gmode == GMODE_LEGACY_B) && (band->gmode != GMODE_LEGACY_B)) {
6049                 band->gmode = gmode;
6050         }
6051
6052         band->gmode = gmode;
6053
6054         wlc->shortslot_override = shortslot;
6055
6056         /* Use the default 11g rateset */
6057         if (!rs.count)
6058                 brcms_c_rateset_copy(&cck_ofdm_rates, &rs);
6059
6060         if (ofdm_basic) {
6061                 for (i = 0; i < rs.count; i++) {
6062                         if (rs.rates[i] == BRCM_RATE_6M
6063                             || rs.rates[i] == BRCM_RATE_12M
6064                             || rs.rates[i] == BRCM_RATE_24M)
6065                                 rs.rates[i] |= BRCMS_RATE_FLAG;
6066                 }
6067         }
6068
6069         /* Set default bss rateset */
6070         wlc->default_bss->rateset.count = rs.count;
6071         memcpy(wlc->default_bss->rateset.rates, rs.rates,
6072                sizeof(wlc->default_bss->rateset.rates));
6073
6074         return ret;
6075 }
6076
6077 static int brcms_c_nmode_validate(struct brcms_c_info *wlc, s32 nmode)
6078 {
6079         int err = 0;
6080
6081         switch (nmode) {
6082
6083         case OFF:
6084                 break;
6085
6086         case AUTO:
6087         case WL_11N_2x2:
6088         case WL_11N_3x3:
6089                 if (!(BRCMS_PHY_11N_CAP(wlc->band)))
6090                         err = -EINVAL;
6091                 break;
6092
6093         default:
6094                 err = -EINVAL;
6095                 break;
6096         }
6097
6098         return err;
6099 }
6100
6101 int brcms_c_set_nmode(struct brcms_c_info *wlc, s32 nmode)
6102 {
6103         uint i;
6104         int err;
6105
6106         err = brcms_c_nmode_validate(wlc, nmode);
6107         if (err)
6108                 return err;
6109
6110         switch (nmode) {
6111         case OFF:
6112                 wlc->pub->_n_enab = OFF;
6113                 wlc->default_bss->flags &= ~BRCMS_BSS_HT;
6114                 /* delete the mcs rates from the default and hw ratesets */
6115                 brcms_c_rateset_mcs_clear(&wlc->default_bss->rateset);
6116                 for (i = 0; i < wlc->pub->_nbands; i++) {
6117                         memset(wlc->bandstate[i]->hw_rateset.mcs, 0,
6118                                MCSSET_LEN);
6119                 }
6120                 break;
6121
6122         case AUTO:
6123                 if (wlc->stf->txstreams == WL_11N_3x3)
6124                         nmode = WL_11N_3x3;
6125                 else
6126                         nmode = WL_11N_2x2;
6127         case WL_11N_2x2:
6128         case WL_11N_3x3:
6129                 /* force GMODE_AUTO if NMODE is ON */
6130                 brcms_c_set_gmode(wlc, GMODE_AUTO, true);
6131                 if (nmode == WL_11N_3x3)
6132                         wlc->pub->_n_enab = SUPPORT_HT;
6133                 else
6134                         wlc->pub->_n_enab = SUPPORT_11N;
6135                 wlc->default_bss->flags |= BRCMS_BSS_HT;
6136                 /* add the mcs rates to the default and hw ratesets */
6137                 brcms_c_rateset_mcs_build(&wlc->default_bss->rateset,
6138                                       wlc->stf->txstreams);
6139                 for (i = 0; i < wlc->pub->_nbands; i++)
6140                         memcpy(wlc->bandstate[i]->hw_rateset.mcs,
6141                                wlc->default_bss->rateset.mcs, MCSSET_LEN);
6142                 break;
6143
6144         default:
6145                 break;
6146         }
6147
6148         return err;
6149 }
6150
6151 static int
6152 brcms_c_set_internal_rateset(struct brcms_c_info *wlc,
6153                              struct brcms_c_rateset *rs_arg)
6154 {
6155         struct brcms_c_rateset rs, new;
6156         uint bandunit;
6157
6158         memcpy(&rs, rs_arg, sizeof(struct brcms_c_rateset));
6159
6160         /* check for bad count value */
6161         if ((rs.count == 0) || (rs.count > BRCMS_NUMRATES))
6162                 return -EINVAL;
6163
6164         /* try the current band */
6165         bandunit = wlc->band->bandunit;
6166         memcpy(&new, &rs, sizeof(struct brcms_c_rateset));
6167         if (brcms_c_rate_hwrs_filter_sort_validate
6168             (&new, &wlc->bandstate[bandunit]->hw_rateset, true,
6169              wlc->stf->txstreams))
6170                 goto good;
6171
6172         /* try the other band */
6173         if (brcms_is_mband_unlocked(wlc)) {
6174                 bandunit = OTHERBANDUNIT(wlc);
6175                 memcpy(&new, &rs, sizeof(struct brcms_c_rateset));
6176                 if (brcms_c_rate_hwrs_filter_sort_validate(&new,
6177                                                        &wlc->
6178                                                        bandstate[bandunit]->
6179                                                        hw_rateset, true,
6180                                                        wlc->stf->txstreams))
6181                         goto good;
6182         }
6183
6184         return -EBADE;
6185
6186  good:
6187         /* apply new rateset */
6188         memcpy(&wlc->default_bss->rateset, &new,
6189                sizeof(struct brcms_c_rateset));
6190         memcpy(&wlc->bandstate[bandunit]->defrateset, &new,
6191                sizeof(struct brcms_c_rateset));
6192         return 0;
6193 }
6194
6195 static void brcms_c_ofdm_rateset_war(struct brcms_c_info *wlc)
6196 {
6197         u8 r;
6198         bool war = false;
6199
6200         if (wlc->bsscfg->associated)
6201                 r = wlc->bsscfg->current_bss->rateset.rates[0];
6202         else
6203                 r = wlc->default_bss->rateset.rates[0];
6204
6205         wlc_phy_ofdm_rateset_war(wlc->band->pi, war);
6206
6207         return;
6208 }
6209
6210 int brcms_c_set_channel(struct brcms_c_info *wlc, u16 channel)
6211 {
6212         u16 chspec = ch20mhz_chspec(channel);
6213
6214         if (channel < 0 || channel > MAXCHANNEL)
6215                 return -EINVAL;
6216
6217         if (!brcms_c_valid_chanspec_db(wlc->cmi, chspec))
6218                 return -EINVAL;
6219
6220
6221         if (!wlc->pub->up && brcms_is_mband_unlocked(wlc)) {
6222                 if (wlc->band->bandunit != chspec_bandunit(chspec))
6223                         wlc->bandinit_pending = true;
6224                 else
6225                         wlc->bandinit_pending = false;
6226         }
6227
6228         wlc->default_bss->chanspec = chspec;
6229         /* brcms_c_BSSinit() will sanitize the rateset before
6230          * using it.. */
6231         if (wlc->pub->up && (wlc_phy_chanspec_get(wlc->band->pi) != chspec)) {
6232                 brcms_c_set_home_chanspec(wlc, chspec);
6233                 brcms_c_suspend_mac_and_wait(wlc);
6234                 brcms_c_set_chanspec(wlc, chspec);
6235                 brcms_c_enable_mac(wlc);
6236         }
6237         return 0;
6238 }
6239
6240 int brcms_c_set_rate_limit(struct brcms_c_info *wlc, u16 srl, u16 lrl)
6241 {
6242         int ac;
6243
6244         if (srl < 1 || srl > RETRY_SHORT_MAX ||
6245             lrl < 1 || lrl > RETRY_SHORT_MAX)
6246                 return -EINVAL;
6247
6248         wlc->SRL = srl;
6249         wlc->LRL = lrl;
6250
6251         brcms_b_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
6252
6253         for (ac = 0; ac < AC_COUNT; ac++) {
6254                 wlc->wme_retries[ac] =  SFIELD(wlc->wme_retries[ac],
6255                                                EDCF_SHORT,  wlc->SRL);
6256                 wlc->wme_retries[ac] =  SFIELD(wlc->wme_retries[ac],
6257                                                EDCF_LONG, wlc->LRL);
6258         }
6259         brcms_c_wme_retries_write(wlc);
6260
6261         return 0;
6262 }
6263
6264 void brcms_c_get_current_rateset(struct brcms_c_info *wlc,
6265                                  struct brcm_rateset *currs)
6266 {
6267         struct brcms_c_rateset *rs;
6268
6269         if (wlc->pub->associated)
6270                 rs = &wlc->bsscfg->current_bss->rateset;
6271         else
6272                 rs = &wlc->default_bss->rateset;
6273
6274         /* Copy only legacy rateset section */
6275         currs->count = rs->count;
6276         memcpy(&currs->rates, &rs->rates, rs->count);
6277 }
6278
6279 int brcms_c_set_rateset(struct brcms_c_info *wlc, struct brcm_rateset *rs)
6280 {
6281         struct brcms_c_rateset internal_rs;
6282         int bcmerror;
6283
6284         if (rs->count > BRCMS_NUMRATES)
6285                 return -ENOBUFS;
6286
6287         memset(&internal_rs, 0, sizeof(struct brcms_c_rateset));
6288
6289         /* Copy only legacy rateset section */
6290         internal_rs.count = rs->count;
6291         memcpy(&internal_rs.rates, &rs->rates, internal_rs.count);
6292
6293         /* merge rateset coming in with the current mcsset */
6294         if (wlc->pub->_n_enab & SUPPORT_11N) {
6295                 struct brcms_bss_info *mcsset_bss;
6296                 if (wlc->bsscfg->associated)
6297                         mcsset_bss = wlc->bsscfg->current_bss;
6298                 else
6299                         mcsset_bss = wlc->default_bss;
6300                 memcpy(internal_rs.mcs, &mcsset_bss->rateset.mcs[0],
6301                        MCSSET_LEN);
6302         }
6303
6304         bcmerror = brcms_c_set_internal_rateset(wlc, &internal_rs);
6305         if (!bcmerror)
6306                 brcms_c_ofdm_rateset_war(wlc);
6307
6308         return bcmerror;
6309 }
6310
6311 int brcms_c_set_beacon_period(struct brcms_c_info *wlc, u16 period)
6312 {
6313         if (period < DOT11_MIN_BEACON_PERIOD ||
6314             period > DOT11_MAX_BEACON_PERIOD)
6315                 return -EINVAL;
6316
6317         wlc->default_bss->beacon_period = period;
6318         return 0;
6319 }
6320
6321 u16 brcms_c_get_phy_type(struct brcms_c_info *wlc, int phyidx)
6322 {
6323         return wlc->band->phytype;
6324 }
6325
6326 void brcms_c_set_shortslot_override(struct brcms_c_info *wlc, s8 sslot_override)
6327 {
6328         wlc->shortslot_override = sslot_override;
6329
6330         /*
6331          * shortslot is an 11g feature, so no more work if we are
6332          * currently on the 5G band
6333          */
6334         if (wlc->band->bandtype == BRCM_BAND_5G)
6335                 return;
6336
6337         if (wlc->pub->up && wlc->pub->associated) {
6338                 /* let watchdog or beacon processing update shortslot */
6339         } else if (wlc->pub->up) {
6340                 /* unassociated shortslot is off */
6341                 brcms_c_switch_shortslot(wlc, false);
6342         } else {
6343                 /* driver is down, so just update the brcms_c_info
6344                  * value */
6345                 if (wlc->shortslot_override == BRCMS_SHORTSLOT_AUTO)
6346                         wlc->shortslot = false;
6347                 else
6348                         wlc->shortslot =
6349                             (wlc->shortslot_override ==
6350                              BRCMS_SHORTSLOT_ON);
6351         }
6352 }
6353
6354 /*
6355  * register watchdog and down handlers.
6356  */
6357 int brcms_c_module_register(struct brcms_pub *pub,
6358                             const char *name, struct brcms_info *hdl,
6359                             int (*d_fn)(void *handle))
6360 {
6361         struct brcms_c_info *wlc = (struct brcms_c_info *) pub->wlc;
6362         int i;
6363
6364         /* find an empty entry and just add, no duplication check! */
6365         for (i = 0; i < BRCMS_MAXMODULES; i++) {
6366                 if (wlc->modulecb[i].name[0] == '\0') {
6367                         strncpy(wlc->modulecb[i].name, name,
6368                                 sizeof(wlc->modulecb[i].name) - 1);
6369                         wlc->modulecb[i].hdl = hdl;
6370                         wlc->modulecb[i].down_fn = d_fn;
6371                         return 0;
6372                 }
6373         }
6374
6375         return -ENOSR;
6376 }
6377
6378 /* unregister module callbacks */
6379 int brcms_c_module_unregister(struct brcms_pub *pub, const char *name,
6380                               struct brcms_info *hdl)
6381 {
6382         struct brcms_c_info *wlc = (struct brcms_c_info *) pub->wlc;
6383         int i;
6384
6385         if (wlc == NULL)
6386                 return -ENODATA;
6387
6388         for (i = 0; i < BRCMS_MAXMODULES; i++) {
6389                 if (!strcmp(wlc->modulecb[i].name, name) &&
6390                     (wlc->modulecb[i].hdl == hdl)) {
6391                         memset(&wlc->modulecb[i], 0, sizeof(struct modulecb));
6392                         return 0;
6393                 }
6394         }
6395
6396         /* table not found! */
6397         return -ENODATA;
6398 }
6399
6400 #ifdef BCMDBG
6401 static const char * const supr_reason[] = {
6402         "None", "PMQ Entry", "Flush request",
6403         "Previous frag failure", "Channel mismatch",
6404         "Lifetime Expiry", "Underflow"
6405 };
6406
6407 static void brcms_c_print_txs_status(u16 s)
6408 {
6409         printk(KERN_DEBUG "[15:12]  %d  frame attempts\n",
6410                (s & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT);
6411         printk(KERN_DEBUG " [11:8]  %d  rts attempts\n",
6412                (s & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT);
6413         printk(KERN_DEBUG "    [7]  %d  PM mode indicated\n",
6414                ((s & TX_STATUS_PMINDCTD) ? 1 : 0));
6415         printk(KERN_DEBUG "    [6]  %d  intermediate status\n",
6416                ((s & TX_STATUS_INTERMEDIATE) ? 1 : 0));
6417         printk(KERN_DEBUG "    [5]  %d  AMPDU\n",
6418                (s & TX_STATUS_AMPDU) ? 1 : 0);
6419         printk(KERN_DEBUG "  [4:2]  %d  Frame Suppressed Reason (%s)\n",
6420                ((s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT),
6421                supr_reason[(s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT]);
6422         printk(KERN_DEBUG "    [1]  %d  acked\n",
6423                ((s & TX_STATUS_ACK_RCV) ? 1 : 0));
6424 }
6425 #endif                          /* BCMDBG */
6426
6427 void brcms_c_print_txstatus(struct tx_status *txs)
6428 {
6429 #if defined(BCMDBG)
6430         u16 s = txs->status;
6431         u16 ackphyrxsh = txs->ackphyrxsh;
6432
6433         printk(KERN_DEBUG "\ntxpkt (MPDU) Complete\n");
6434
6435         printk(KERN_DEBUG "FrameID: %04x   ", txs->frameid);
6436         printk(KERN_DEBUG "TxStatus: %04x", s);
6437         printk(KERN_DEBUG "\n");
6438
6439         brcms_c_print_txs_status(s);
6440
6441         printk(KERN_DEBUG "LastTxTime: %04x ", txs->lasttxtime);
6442         printk(KERN_DEBUG "Seq: %04x ", txs->sequence);
6443         printk(KERN_DEBUG "PHYTxStatus: %04x ", txs->phyerr);
6444         printk(KERN_DEBUG "RxAckRSSI: %04x ",
6445                (ackphyrxsh & PRXS1_JSSI_MASK) >> PRXS1_JSSI_SHIFT);
6446         printk(KERN_DEBUG "RxAckSQ: %04x",
6447                (ackphyrxsh & PRXS1_SQ_MASK) >> PRXS1_SQ_SHIFT);
6448         printk(KERN_DEBUG "\n");
6449 #endif                          /* defined(BCMDBG) */
6450 }
6451
6452 void brcms_c_statsupd(struct brcms_c_info *wlc)
6453 {
6454         int i;
6455         struct macstat macstats;
6456 #ifdef BCMDBG
6457         u16 delta;
6458         u16 rxf0ovfl;
6459         u16 txfunfl[NFIFO];
6460 #endif                          /* BCMDBG */
6461
6462         /* if driver down, make no sense to update stats */
6463         if (!wlc->pub->up)
6464                 return;
6465
6466 #ifdef BCMDBG
6467         /* save last rx fifo 0 overflow count */
6468         rxf0ovfl = wlc->core->macstat_snapshot->rxf0ovfl;
6469
6470         /* save last tx fifo  underflow count */
6471         for (i = 0; i < NFIFO; i++)
6472                 txfunfl[i] = wlc->core->macstat_snapshot->txfunfl[i];
6473 #endif                          /* BCMDBG */
6474
6475         /* Read mac stats from contiguous shared memory */
6476         brcms_b_copyfrom_objmem(wlc->hw, M_UCODE_MACSTAT, &macstats,
6477                                 sizeof(struct macstat), OBJADDR_SHM_SEL);
6478
6479 #ifdef BCMDBG
6480         /* check for rx fifo 0 overflow */
6481         delta = (u16) (wlc->core->macstat_snapshot->rxf0ovfl - rxf0ovfl);
6482         if (delta)
6483                 wiphy_err(wlc->wiphy, "wl%d: %u rx fifo 0 overflows!\n",
6484                           wlc->pub->unit, delta);
6485
6486         /* check for tx fifo underflows */
6487         for (i = 0; i < NFIFO; i++) {
6488                 delta =
6489                     (u16) (wlc->core->macstat_snapshot->txfunfl[i] -
6490                               txfunfl[i]);
6491                 if (delta)
6492                         wiphy_err(wlc->wiphy, "wl%d: %u tx fifo %d underflows!"
6493                                   "\n", wlc->pub->unit, delta, i);
6494         }
6495 #endif                          /* BCMDBG */
6496
6497         /* merge counters from dma module */
6498         for (i = 0; i < NFIFO; i++) {
6499                 if (wlc->hw->di[i])
6500                         dma_counterreset(wlc->hw->di[i]);
6501         }
6502 }
6503
6504 bool brcms_c_chipmatch(u16 vendor, u16 device)
6505 {
6506         if (vendor != PCI_VENDOR_ID_BROADCOM) {
6507                 pr_err("chipmatch: unknown vendor id %04x\n", vendor);
6508                 return false;
6509         }
6510
6511         if (device == BCM43224_D11N_ID_VEN1)
6512                 return true;
6513         if ((device == BCM43224_D11N_ID) || (device == BCM43225_D11N2G_ID))
6514                 return true;
6515         if (device == BCM4313_D11N2G_ID)
6516                 return true;
6517         if ((device == BCM43236_D11N_ID) || (device == BCM43236_D11N2G_ID))
6518                 return true;
6519
6520         pr_err("chipmatch: unknown device id %04x\n", device);
6521         return false;
6522 }
6523
6524 #if defined(BCMDBG)
6525 void brcms_c_print_txdesc(struct d11txh *txh)
6526 {
6527         u16 mtcl = le16_to_cpu(txh->MacTxControlLow);
6528         u16 mtch = le16_to_cpu(txh->MacTxControlHigh);
6529         u16 mfc = le16_to_cpu(txh->MacFrameControl);
6530         u16 tfest = le16_to_cpu(txh->TxFesTimeNormal);
6531         u16 ptcw = le16_to_cpu(txh->PhyTxControlWord);
6532         u16 ptcw_1 = le16_to_cpu(txh->PhyTxControlWord_1);
6533         u16 ptcw_1_Fbr = le16_to_cpu(txh->PhyTxControlWord_1_Fbr);
6534         u16 ptcw_1_Rts = le16_to_cpu(txh->PhyTxControlWord_1_Rts);
6535         u16 ptcw_1_FbrRts = le16_to_cpu(txh->PhyTxControlWord_1_FbrRts);
6536         u16 mainrates = le16_to_cpu(txh->MainRates);
6537         u16 xtraft = le16_to_cpu(txh->XtraFrameTypes);
6538         u8 *iv = txh->IV;
6539         u8 *ra = txh->TxFrameRA;
6540         u16 tfestfb = le16_to_cpu(txh->TxFesTimeFallback);
6541         u8 *rtspfb = txh->RTSPLCPFallback;
6542         u16 rtsdfb = le16_to_cpu(txh->RTSDurFallback);
6543         u8 *fragpfb = txh->FragPLCPFallback;
6544         u16 fragdfb = le16_to_cpu(txh->FragDurFallback);
6545         u16 mmodelen = le16_to_cpu(txh->MModeLen);
6546         u16 mmodefbrlen = le16_to_cpu(txh->MModeFbrLen);
6547         u16 tfid = le16_to_cpu(txh->TxFrameID);
6548         u16 txs = le16_to_cpu(txh->TxStatus);
6549         u16 mnmpdu = le16_to_cpu(txh->MaxNMpdus);
6550         u16 mabyte = le16_to_cpu(txh->MaxABytes_MRT);
6551         u16 mabyte_f = le16_to_cpu(txh->MaxABytes_FBR);
6552         u16 mmbyte = le16_to_cpu(txh->MinMBytes);
6553
6554         u8 *rtsph = txh->RTSPhyHeader;
6555         struct ieee80211_rts rts = txh->rts_frame;
6556         char hexbuf[256];
6557
6558         /* add plcp header along with txh descriptor */
6559         printk(KERN_DEBUG "Raw TxDesc + plcp header:\n");
6560         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
6561                              txh, sizeof(struct d11txh) + 48);
6562
6563         printk(KERN_DEBUG "TxCtlLow: %04x ", mtcl);
6564         printk(KERN_DEBUG "TxCtlHigh: %04x ", mtch);
6565         printk(KERN_DEBUG "FC: %04x ", mfc);
6566         printk(KERN_DEBUG "FES Time: %04x\n", tfest);
6567         printk(KERN_DEBUG "PhyCtl: %04x%s ", ptcw,
6568                (ptcw & PHY_TXC_SHORT_HDR) ? " short" : "");
6569         printk(KERN_DEBUG "PhyCtl_1: %04x ", ptcw_1);
6570         printk(KERN_DEBUG "PhyCtl_1_Fbr: %04x\n", ptcw_1_Fbr);
6571         printk(KERN_DEBUG "PhyCtl_1_Rts: %04x ", ptcw_1_Rts);
6572         printk(KERN_DEBUG "PhyCtl_1_Fbr_Rts: %04x\n", ptcw_1_FbrRts);
6573         printk(KERN_DEBUG "MainRates: %04x ", mainrates);
6574         printk(KERN_DEBUG "XtraFrameTypes: %04x ", xtraft);
6575         printk(KERN_DEBUG "\n");
6576
6577         brcmu_format_hex(hexbuf, iv, sizeof(txh->IV));
6578         printk(KERN_DEBUG "SecIV:       %s\n", hexbuf);
6579         brcmu_format_hex(hexbuf, ra, sizeof(txh->TxFrameRA));
6580         printk(KERN_DEBUG "RA:          %s\n", hexbuf);
6581
6582         printk(KERN_DEBUG "Fb FES Time: %04x ", tfestfb);
6583         brcmu_format_hex(hexbuf, rtspfb, sizeof(txh->RTSPLCPFallback));
6584         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
6585         printk(KERN_DEBUG "RTS DUR: %04x ", rtsdfb);
6586         brcmu_format_hex(hexbuf, fragpfb, sizeof(txh->FragPLCPFallback));
6587         printk(KERN_DEBUG "PLCP: %s ", hexbuf);
6588         printk(KERN_DEBUG "DUR: %04x", fragdfb);
6589         printk(KERN_DEBUG "\n");
6590
6591         printk(KERN_DEBUG "MModeLen: %04x ", mmodelen);
6592         printk(KERN_DEBUG "MModeFbrLen: %04x\n", mmodefbrlen);
6593
6594         printk(KERN_DEBUG "FrameID:     %04x\n", tfid);
6595         printk(KERN_DEBUG "TxStatus:    %04x\n", txs);
6596
6597         printk(KERN_DEBUG "MaxNumMpdu:  %04x\n", mnmpdu);
6598         printk(KERN_DEBUG "MaxAggbyte:  %04x\n", mabyte);
6599         printk(KERN_DEBUG "MaxAggbyte_fb:  %04x\n", mabyte_f);
6600         printk(KERN_DEBUG "MinByte:     %04x\n", mmbyte);
6601
6602         brcmu_format_hex(hexbuf, rtsph, sizeof(txh->RTSPhyHeader));
6603         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
6604         brcmu_format_hex(hexbuf, (u8 *) &rts, sizeof(txh->rts_frame));
6605         printk(KERN_DEBUG "RTS Frame: %s", hexbuf);
6606         printk(KERN_DEBUG "\n");
6607 }
6608 #endif                          /* defined(BCMDBG) */
6609
6610 #if defined(BCMDBG)
6611 void brcms_c_print_rxh(struct d11rxhdr *rxh)
6612 {
6613         u16 len = rxh->RxFrameSize;
6614         u16 phystatus_0 = rxh->PhyRxStatus_0;
6615         u16 phystatus_1 = rxh->PhyRxStatus_1;
6616         u16 phystatus_2 = rxh->PhyRxStatus_2;
6617         u16 phystatus_3 = rxh->PhyRxStatus_3;
6618         u16 macstatus1 = rxh->RxStatus1;
6619         u16 macstatus2 = rxh->RxStatus2;
6620         char flagstr[64];
6621         char lenbuf[20];
6622         static const struct brcmu_bit_desc macstat_flags[] = {
6623                 {RXS_FCSERR, "FCSErr"},
6624                 {RXS_RESPFRAMETX, "Reply"},
6625                 {RXS_PBPRES, "PADDING"},
6626                 {RXS_DECATMPT, "DeCr"},
6627                 {RXS_DECERR, "DeCrErr"},
6628                 {RXS_BCNSENT, "Bcn"},
6629                 {0, NULL}
6630         };
6631
6632         printk(KERN_DEBUG "Raw RxDesc:\n");
6633         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, rxh,
6634                              sizeof(struct d11rxhdr));
6635
6636         brcmu_format_flags(macstat_flags, macstatus1, flagstr, 64);
6637
6638         snprintf(lenbuf, sizeof(lenbuf), "0x%x", len);
6639
6640         printk(KERN_DEBUG "RxFrameSize:     %6s (%d)%s\n", lenbuf, len,
6641                (rxh->PhyRxStatus_0 & PRXS0_SHORTH) ? " short preamble" : "");
6642         printk(KERN_DEBUG "RxPHYStatus:     %04x %04x %04x %04x\n",
6643                phystatus_0, phystatus_1, phystatus_2, phystatus_3);
6644         printk(KERN_DEBUG "RxMACStatus:     %x %s\n", macstatus1, flagstr);
6645         printk(KERN_DEBUG "RXMACaggtype:    %x\n",
6646                (macstatus2 & RXS_AGGTYPE_MASK));
6647         printk(KERN_DEBUG "RxTSFTime:       %04x\n", rxh->RxTSFTime);
6648 }
6649 #endif                          /* defined(BCMDBG) */
6650
6651 u16 brcms_b_rate_shm_offset(struct brcms_hardware *wlc_hw, u8 rate)
6652 {
6653         u16 table_ptr;
6654         u8 phy_rate, index;
6655
6656         /* get the phy specific rate encoding for the PLCP SIGNAL field */
6657         if (is_ofdm_rate(rate))
6658                 table_ptr = M_RT_DIRMAP_A;
6659         else
6660                 table_ptr = M_RT_DIRMAP_B;
6661
6662         /* for a given rate, the LS-nibble of the PLCP SIGNAL field is
6663          * the index into the rate table.
6664          */
6665         phy_rate = rate_info[rate] & BRCMS_RATE_MASK;
6666         index = phy_rate & 0xf;
6667
6668         /* Find the SHM pointer to the rate table entry by looking in the
6669          * Direct-map Table
6670          */
6671         return 2 * brcms_b_read_shm(wlc_hw, table_ptr + (index * 2));
6672 }
6673
6674 static u16 brcms_c_rate_shm_offset(struct brcms_c_info *wlc, u8 rate)
6675 {
6676         return brcms_b_rate_shm_offset(wlc->hw, rate);
6677 }
6678
6679 /* Callback for device removed */
6680
6681 /*
6682  * Attempts to queue a packet onto a multiple-precedence queue,
6683  * if necessary evicting a lower precedence packet from the queue.
6684  *
6685  * 'prec' is the precedence number that has already been mapped
6686  * from the packet priority.
6687  *
6688  * Returns true if packet consumed (queued), false if not.
6689  */
6690 static bool brcms_c_prec_enq(struct brcms_c_info *wlc, struct pktq *q,
6691                       struct sk_buff *pkt, int prec)
6692 {
6693         return brcms_c_prec_enq_head(wlc, q, pkt, prec, false);
6694 }
6695
6696 bool
6697 brcms_c_prec_enq_head(struct brcms_c_info *wlc, struct pktq *q,
6698                       struct sk_buff *pkt, int prec, bool head)
6699 {
6700         struct sk_buff *p;
6701         int eprec = -1;         /* precedence to evict from */
6702
6703         /* Determine precedence from which to evict packet, if any */
6704         if (pktq_pfull(q, prec))
6705                 eprec = prec;
6706         else if (pktq_full(q)) {
6707                 p = brcmu_pktq_peek_tail(q, &eprec);
6708                 if (eprec > prec) {
6709                         wiphy_err(wlc->wiphy, "%s: Failing: eprec %d > prec %d"
6710                                   "\n", __func__, eprec, prec);
6711                         return false;
6712                 }
6713         }
6714
6715         /* Evict if needed */
6716         if (eprec >= 0) {
6717                 bool discard_oldest;
6718
6719                 discard_oldest = ac_bitmap_tst(0, eprec);
6720
6721                 /* Refuse newer packet unless configured to discard oldest */
6722                 if (eprec == prec && !discard_oldest) {
6723                         wiphy_err(wlc->wiphy, "%s: No where to go, prec == %d"
6724                                   "\n", __func__, prec);
6725                         return false;
6726                 }
6727
6728                 /* Evict packet according to discard policy */
6729                 p = discard_oldest ? brcmu_pktq_pdeq(q, eprec) :
6730                         brcmu_pktq_pdeq_tail(q, eprec);
6731                 brcmu_pkt_buf_free_skb(p);
6732         }
6733
6734         /* Enqueue */
6735         if (head)
6736                 p = brcmu_pktq_penq_head(q, prec, pkt);
6737         else
6738                 p = brcmu_pktq_penq(q, prec, pkt);
6739
6740         return true;
6741 }
6742
6743 void brcms_c_txq_enq(struct brcms_c_info *wlc, struct scb *scb,
6744                      struct sk_buff *sdu, uint prec)
6745 {
6746         struct brcms_txq_info *qi = wlc->pkt_queue;     /* Check me */
6747         struct pktq *q = &qi->q;
6748         int prio;
6749
6750         prio = sdu->priority;
6751
6752         if (!brcms_c_prec_enq(wlc, q, sdu, prec)) {
6753                 /*
6754                  * we might hit this condtion in case
6755                  * packet flooding from mac80211 stack
6756                  */
6757                 brcmu_pkt_buf_free_skb(sdu);
6758         }
6759 }
6760
6761 /*
6762  * bcmc_fid_generate:
6763  * Generate frame ID for a BCMC packet.  The frag field is not used
6764  * for MC frames so is used as part of the sequence number.
6765  */
6766 static inline u16
6767 bcmc_fid_generate(struct brcms_c_info *wlc, struct brcms_bss_cfg *bsscfg,
6768                   struct d11txh *txh)
6769 {
6770         u16 frameid;
6771
6772         frameid = le16_to_cpu(txh->TxFrameID) & ~(TXFID_SEQ_MASK |
6773                                                   TXFID_QUEUE_MASK);
6774         frameid |=
6775             (((wlc->
6776                mc_fid_counter++) << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
6777             TX_BCMC_FIFO;
6778
6779         return frameid;
6780 }
6781
6782 static uint
6783 brcms_c_calc_ack_time(struct brcms_c_info *wlc, u32 rspec,
6784                       u8 preamble_type)
6785 {
6786         uint dur = 0;
6787
6788         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d\n",
6789                 wlc->pub->unit, rspec, preamble_type);
6790         /*
6791          * Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that
6792          * is less than or equal to the rate of the immediately previous
6793          * frame in the FES
6794          */
6795         rspec = brcms_basic_rate(wlc, rspec);
6796         /* ACK frame len == 14 == 2(fc) + 2(dur) + 6(ra) + 4(fcs) */
6797         dur =
6798             brcms_c_calc_frame_time(wlc, rspec, preamble_type,
6799                                 (DOT11_ACK_LEN + FCS_LEN));
6800         return dur;
6801 }
6802
6803 static uint
6804 brcms_c_calc_cts_time(struct brcms_c_info *wlc, u32 rspec,
6805                       u8 preamble_type)
6806 {
6807         BCMMSG(wlc->wiphy, "wl%d: ratespec 0x%x, preamble_type %d\n",
6808                 wlc->pub->unit, rspec, preamble_type);
6809         return brcms_c_calc_ack_time(wlc, rspec, preamble_type);
6810 }
6811
6812 static uint
6813 brcms_c_calc_ba_time(struct brcms_c_info *wlc, u32 rspec,
6814                      u8 preamble_type)
6815 {
6816         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, "
6817                  "preamble_type %d\n", wlc->pub->unit, rspec, preamble_type);
6818         /*
6819          * Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that
6820          * is less than or equal to the rate of the immediately previous
6821          * frame in the FES
6822          */
6823         rspec = brcms_basic_rate(wlc, rspec);
6824         /* BA len == 32 == 16(ctl hdr) + 4(ba len) + 8(bitmap) + 4(fcs) */
6825         return brcms_c_calc_frame_time(wlc, rspec, preamble_type,
6826                                    (DOT11_BA_LEN + DOT11_BA_BITMAP_LEN +
6827                                     FCS_LEN));
6828 }
6829
6830 /* brcms_c_compute_frame_dur()
6831  *
6832  * Calculate the 802.11 MAC header DUR field for MPDU
6833  * DUR for a single frame = 1 SIFS + 1 ACK
6834  * DUR for a frame with following frags = 3 SIFS + 2 ACK + next frag time
6835  *
6836  * rate                 MPDU rate in unit of 500kbps
6837  * next_frag_len        next MPDU length in bytes
6838  * preamble_type        use short/GF or long/MM PLCP header
6839  */
6840 static u16
6841 brcms_c_compute_frame_dur(struct brcms_c_info *wlc, u32 rate,
6842                       u8 preamble_type, uint next_frag_len)
6843 {
6844         u16 dur, sifs;
6845
6846         sifs = get_sifs(wlc->band);
6847
6848         dur = sifs;
6849         dur += (u16) brcms_c_calc_ack_time(wlc, rate, preamble_type);
6850
6851         if (next_frag_len) {
6852                 /* Double the current DUR to get 2 SIFS + 2 ACKs */
6853                 dur *= 2;
6854                 /* add another SIFS and the frag time */
6855                 dur += sifs;
6856                 dur +=
6857                     (u16) brcms_c_calc_frame_time(wlc, rate, preamble_type,
6858                                                  next_frag_len);
6859         }
6860         return dur;
6861 }
6862
6863 /* The opposite of brcms_c_calc_frame_time */
6864 static uint
6865 brcms_c_calc_frame_len(struct brcms_c_info *wlc, u32 ratespec,
6866                    u8 preamble_type, uint dur)
6867 {
6868         uint nsyms, mac_len, Ndps, kNdps;
6869         uint rate = rspec2rate(ratespec);
6870
6871         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d, dur %d\n",
6872                  wlc->pub->unit, ratespec, preamble_type, dur);
6873
6874         if (is_mcs_rate(ratespec)) {
6875                 uint mcs = ratespec & RSPEC_RATE_MASK;
6876                 int tot_streams = mcs_2_txstreams(mcs) + rspec_stc(ratespec);
6877                 dur -= PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
6878                 /* payload calculation matches that of regular ofdm */
6879                 if (wlc->band->bandtype == BRCM_BAND_2G)
6880                         dur -= DOT11_OFDM_SIGNAL_EXTENSION;
6881                 /* kNdbps = kbps * 4 */
6882                 kNdps = mcs_2_rate(mcs, rspec_is40mhz(ratespec),
6883                                    rspec_issgi(ratespec)) * 4;
6884                 nsyms = dur / APHY_SYMBOL_TIME;
6885                 mac_len =
6886                     ((nsyms * kNdps) -
6887                      ((APHY_SERVICE_NBITS + APHY_TAIL_NBITS) * 1000)) / 8000;
6888         } else if (is_ofdm_rate(ratespec)) {
6889                 dur -= APHY_PREAMBLE_TIME;
6890                 dur -= APHY_SIGNAL_TIME;
6891                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
6892                 Ndps = rate * 2;
6893                 nsyms = dur / APHY_SYMBOL_TIME;
6894                 mac_len =
6895                     ((nsyms * Ndps) -
6896                      (APHY_SERVICE_NBITS + APHY_TAIL_NBITS)) / 8;
6897         } else {
6898                 if (preamble_type & BRCMS_SHORT_PREAMBLE)
6899                         dur -= BPHY_PLCP_SHORT_TIME;
6900                 else
6901                         dur -= BPHY_PLCP_TIME;
6902                 mac_len = dur * rate;
6903                 /* divide out factor of 2 in rate (1/2 mbps) */
6904                 mac_len = mac_len / 8 / 2;
6905         }
6906         return mac_len;
6907 }
6908
6909 static u32
6910 mac80211_wlc_set_nrate(struct brcms_c_info *wlc, struct brcms_band *cur_band,
6911                        u32 int_val)
6912 {
6913         u8 stf = (int_val & NRATE_STF_MASK) >> NRATE_STF_SHIFT;
6914         u8 rate = int_val & NRATE_RATE_MASK;
6915         u32 rspec;
6916         bool ismcs = ((int_val & NRATE_MCS_INUSE) == NRATE_MCS_INUSE);
6917         bool issgi = ((int_val & NRATE_SGI_MASK) >> NRATE_SGI_SHIFT);
6918         bool override_mcs_only = ((int_val & NRATE_OVERRIDE_MCS_ONLY)
6919                                   == NRATE_OVERRIDE_MCS_ONLY);
6920         int bcmerror = 0;
6921
6922         if (!ismcs)
6923                 return (u32) rate;
6924
6925         /* validate the combination of rate/mcs/stf is allowed */
6926         if ((wlc->pub->_n_enab & SUPPORT_11N) && ismcs) {
6927                 /* mcs only allowed when nmode */
6928                 if (stf > PHY_TXC1_MODE_SDM) {
6929                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid stf\n",
6930                                   wlc->pub->unit, __func__);
6931                         bcmerror = -EINVAL;
6932                         goto done;
6933                 }
6934
6935                 /* mcs 32 is a special case, DUP mode 40 only */
6936                 if (rate == 32) {
6937                         if (!CHSPEC_IS40(wlc->home_chanspec) ||
6938                             ((stf != PHY_TXC1_MODE_SISO)
6939                              && (stf != PHY_TXC1_MODE_CDD))) {
6940                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid mcs "
6941                                           "32\n", wlc->pub->unit, __func__);
6942                                 bcmerror = -EINVAL;
6943                                 goto done;
6944                         }
6945                         /* mcs > 7 must use stf SDM */
6946                 } else if (rate > HIGHEST_SINGLE_STREAM_MCS) {
6947                         /* mcs > 7 must use stf SDM */
6948                         if (stf != PHY_TXC1_MODE_SDM) {
6949                                 BCMMSG(wlc->wiphy, "wl%d: enabling "
6950                                        "SDM mode for mcs %d\n",
6951                                        wlc->pub->unit, rate);
6952                                 stf = PHY_TXC1_MODE_SDM;
6953                         }
6954                 } else {
6955                         /*
6956                          * MCS 0-7 may use SISO, CDD, and for
6957                          * phy_rev >= 3 STBC
6958                          */
6959                         if ((stf > PHY_TXC1_MODE_STBC) ||
6960                             (!BRCMS_STBC_CAP_PHY(wlc)
6961                              && (stf == PHY_TXC1_MODE_STBC))) {
6962                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid STBC"
6963                                           "\n", wlc->pub->unit, __func__);
6964                                 bcmerror = -EINVAL;
6965                                 goto done;
6966                         }
6967                 }
6968         } else if (is_ofdm_rate(rate)) {
6969                 if ((stf != PHY_TXC1_MODE_CDD) && (stf != PHY_TXC1_MODE_SISO)) {
6970                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid OFDM\n",
6971                                   wlc->pub->unit, __func__);
6972                         bcmerror = -EINVAL;
6973                         goto done;
6974                 }
6975         } else if (is_cck_rate(rate)) {
6976                 if ((cur_band->bandtype != BRCM_BAND_2G)
6977                     || (stf != PHY_TXC1_MODE_SISO)) {
6978                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid CCK\n",
6979                                   wlc->pub->unit, __func__);
6980                         bcmerror = -EINVAL;
6981                         goto done;
6982                 }
6983         } else {
6984                 wiphy_err(wlc->wiphy, "wl%d: %s: Unknown rate type\n",
6985                           wlc->pub->unit, __func__);
6986                 bcmerror = -EINVAL;
6987                 goto done;
6988         }
6989         /* make sure multiple antennae are available for non-siso rates */
6990         if ((stf != PHY_TXC1_MODE_SISO) && (wlc->stf->txstreams == 1)) {
6991                 wiphy_err(wlc->wiphy, "wl%d: %s: SISO antenna but !SISO "
6992                           "request\n", wlc->pub->unit, __func__);
6993                 bcmerror = -EINVAL;
6994                 goto done;
6995         }
6996
6997         rspec = rate;
6998         if (ismcs) {
6999                 rspec |= RSPEC_MIMORATE;
7000                 /* For STBC populate the STC field of the ratespec */
7001                 if (stf == PHY_TXC1_MODE_STBC) {
7002                         u8 stc;
7003                         stc = 1;        /* Nss for single stream is always 1 */
7004                         rspec |= (stc << RSPEC_STC_SHIFT);
7005                 }
7006         }
7007
7008         rspec |= (stf << RSPEC_STF_SHIFT);
7009
7010         if (override_mcs_only)
7011                 rspec |= RSPEC_OVERRIDE_MCS_ONLY;
7012
7013         if (issgi)
7014                 rspec |= RSPEC_SHORT_GI;
7015
7016         if ((rate != 0)
7017             && !brcms_c_valid_rate(wlc, rspec, cur_band->bandtype, true))
7018                 return rate;
7019
7020         return rspec;
7021 done:
7022         return rate;
7023 }
7024
7025 /*
7026  * Add struct d11txh, struct cck_phy_hdr.
7027  *
7028  * 'p' data must start with 802.11 MAC header
7029  * 'p' must allow enough bytes of local headers to be "pushed" onto the packet
7030  *
7031  * headroom == D11_PHY_HDR_LEN + D11_TXH_LEN (D11_TXH_LEN is now 104 bytes)
7032  *
7033  */
7034 static u16
7035 brcms_c_d11hdrs_mac80211(struct brcms_c_info *wlc, struct ieee80211_hw *hw,
7036                      struct sk_buff *p, struct scb *scb, uint frag,
7037                      uint nfrags, uint queue, uint next_frag_len)
7038 {
7039         struct ieee80211_hdr *h;
7040         struct d11txh *txh;
7041         u8 *plcp, plcp_fallback[D11_PHY_HDR_LEN];
7042         int len, phylen, rts_phylen;
7043         u16 mch, phyctl, xfts, mainrates;
7044         u16 seq = 0, mcl = 0, status = 0, frameid = 0;
7045         u32 rspec[2] = { BRCM_RATE_1M, BRCM_RATE_1M };
7046         u32 rts_rspec[2] = { BRCM_RATE_1M, BRCM_RATE_1M };
7047         bool use_rts = false;
7048         bool use_cts = false;
7049         bool use_rifs = false;
7050         bool short_preamble[2] = { false, false };
7051         u8 preamble_type[2] = { BRCMS_LONG_PREAMBLE, BRCMS_LONG_PREAMBLE };
7052         u8 rts_preamble_type[2] = { BRCMS_LONG_PREAMBLE, BRCMS_LONG_PREAMBLE };
7053         u8 *rts_plcp, rts_plcp_fallback[D11_PHY_HDR_LEN];
7054         struct ieee80211_rts *rts = NULL;
7055         bool qos;
7056         uint ac;
7057         u32 rate_val[2];
7058         bool hwtkmic = false;
7059         u16 mimo_ctlchbw = PHY_TXC1_BW_20MHZ;
7060 #define ANTCFG_NONE 0xFF
7061         u8 antcfg = ANTCFG_NONE;
7062         u8 fbantcfg = ANTCFG_NONE;
7063         uint phyctl1_stf = 0;
7064         u16 durid = 0;
7065         struct ieee80211_tx_rate *txrate[2];
7066         int k;
7067         struct ieee80211_tx_info *tx_info;
7068         bool is_mcs[2];
7069         u16 mimo_txbw;
7070         u8 mimo_preamble_type;
7071
7072         /* locate 802.11 MAC header */
7073         h = (struct ieee80211_hdr *)(p->data);
7074         qos = ieee80211_is_data_qos(h->frame_control);
7075
7076         /* compute length of frame in bytes for use in PLCP computations */
7077         len = brcmu_pkttotlen(p);
7078         phylen = len + FCS_LEN;
7079
7080         /* Get tx_info */
7081         tx_info = IEEE80211_SKB_CB(p);
7082
7083         /* add PLCP */
7084         plcp = skb_push(p, D11_PHY_HDR_LEN);
7085
7086         /* add Broadcom tx descriptor header */
7087         txh = (struct d11txh *) skb_push(p, D11_TXH_LEN);
7088         memset(txh, 0, D11_TXH_LEN);
7089
7090         /* setup frameid */
7091         if (tx_info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
7092                 /* non-AP STA should never use BCMC queue */
7093                 if (queue == TX_BCMC_FIFO) {
7094                         wiphy_err(wlc->wiphy, "wl%d: %s: ASSERT queue == "
7095                                   "TX_BCMC!\n", wlc->pub->unit, __func__);
7096                         frameid = bcmc_fid_generate(wlc, NULL, txh);
7097                 } else {
7098                         /* Increment the counter for first fragment */
7099                         if (tx_info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT)
7100                                 scb->seqnum[p->priority]++;
7101
7102                         /* extract fragment number from frame first */
7103                         seq = le16_to_cpu(h->seq_ctrl) & FRAGNUM_MASK;
7104                         seq |= (scb->seqnum[p->priority] << SEQNUM_SHIFT);
7105                         h->seq_ctrl = cpu_to_le16(seq);
7106
7107                         frameid = ((seq << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
7108                             (queue & TXFID_QUEUE_MASK);
7109                 }
7110         }
7111         frameid |= queue & TXFID_QUEUE_MASK;
7112
7113         /* set the ignpmq bit for all pkts tx'd in PS mode and for beacons */
7114         if (ieee80211_is_beacon(h->frame_control))
7115                 mcl |= TXC_IGNOREPMQ;
7116
7117         txrate[0] = tx_info->control.rates;
7118         txrate[1] = txrate[0] + 1;
7119
7120         /*
7121          * if rate control algorithm didn't give us a fallback
7122          * rate, use the primary rate
7123          */
7124         if (txrate[1]->idx < 0)
7125                 txrate[1] = txrate[0];
7126
7127         for (k = 0; k < hw->max_rates; k++) {
7128                 is_mcs[k] =
7129                     txrate[k]->flags & IEEE80211_TX_RC_MCS ? true : false;
7130                 if (!is_mcs[k]) {
7131                         if ((txrate[k]->idx >= 0)
7132                             && (txrate[k]->idx <
7133                                 hw->wiphy->bands[tx_info->band]->n_bitrates)) {
7134                                 rate_val[k] =
7135                                     hw->wiphy->bands[tx_info->band]->
7136                                     bitrates[txrate[k]->idx].hw_value;
7137                                 short_preamble[k] =
7138                                     txrate[k]->
7139                                     flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE ?
7140                                     true : false;
7141                         } else {
7142                                 rate_val[k] = BRCM_RATE_1M;
7143                         }
7144                 } else {
7145                         rate_val[k] = txrate[k]->idx;
7146                 }
7147
7148                 /*
7149                  * Currently only support same setting for primay and
7150                  * fallback rates. Unify flags for each rate into a
7151                  * single value for the frame
7152                  */
7153                 use_rts |=
7154                     txrate[k]->
7155                     flags & IEEE80211_TX_RC_USE_RTS_CTS ? true : false;
7156                 use_cts |=
7157                     txrate[k]->
7158                     flags & IEEE80211_TX_RC_USE_CTS_PROTECT ? true : false;
7159
7160                 if (is_mcs[k])
7161                         rate_val[k] |= NRATE_MCS_INUSE;
7162
7163                 rspec[k] = mac80211_wlc_set_nrate(wlc, wlc->band, rate_val[k]);
7164
7165                 /*
7166                  * (1) RATE:
7167                  *   determine and validate primary rate
7168                  *   and fallback rates
7169                  */
7170                 if (!rspec_active(rspec[k])) {
7171                         rspec[k] = BRCM_RATE_1M;
7172                 } else {
7173                         if (!is_multicast_ether_addr(h->addr1)) {
7174                                 /* set tx antenna config */
7175                                 brcms_c_antsel_antcfg_get(wlc->asi, false,
7176                                         false, 0, 0, &antcfg, &fbantcfg);
7177                         }
7178                 }
7179         }
7180
7181         phyctl1_stf = wlc->stf->ss_opmode;
7182
7183         if (wlc->pub->_n_enab & SUPPORT_11N) {
7184                 for (k = 0; k < hw->max_rates; k++) {
7185                         /*
7186                          * apply siso/cdd to single stream mcs's or ofdm
7187                          * if rspec is auto selected
7188                          */
7189                         if (((is_mcs_rate(rspec[k]) &&
7190                               is_single_stream(rspec[k] & RSPEC_RATE_MASK)) ||
7191                              is_ofdm_rate(rspec[k]))
7192                             && ((rspec[k] & RSPEC_OVERRIDE_MCS_ONLY)
7193                                 || !(rspec[k] & RSPEC_OVERRIDE))) {
7194                                 rspec[k] &= ~(RSPEC_STF_MASK | RSPEC_STC_MASK);
7195
7196                                 /* For SISO MCS use STBC if possible */
7197                                 if (is_mcs_rate(rspec[k])
7198                                     && BRCMS_STF_SS_STBC_TX(wlc, scb)) {
7199                                         u8 stc;
7200
7201                                         /* Nss for single stream is always 1 */
7202                                         stc = 1;
7203                                         rspec[k] |= (PHY_TXC1_MODE_STBC <<
7204                                                         RSPEC_STF_SHIFT) |
7205                                                     (stc << RSPEC_STC_SHIFT);
7206                                 } else
7207                                         rspec[k] |=
7208                                             (phyctl1_stf << RSPEC_STF_SHIFT);
7209                         }
7210
7211                         /*
7212                          * Is the phy configured to use 40MHZ frames? If
7213                          * so then pick the desired txbw
7214                          */
7215                         if (brcms_chspec_bw(wlc->chanspec) == BRCMS_40_MHZ) {
7216                                 /* default txbw is 20in40 SB */
7217                                 mimo_ctlchbw = mimo_txbw =
7218                                    CHSPEC_SB_UPPER(wlc_phy_chanspec_get(
7219                                                                  wlc->band->pi))
7220                                    ? PHY_TXC1_BW_20MHZ_UP : PHY_TXC1_BW_20MHZ;
7221
7222                                 if (is_mcs_rate(rspec[k])) {
7223                                         /* mcs 32 must be 40b/w DUP */
7224                                         if ((rspec[k] & RSPEC_RATE_MASK)
7225                                             == 32) {
7226                                                 mimo_txbw =
7227                                                     PHY_TXC1_BW_40MHZ_DUP;
7228                                                 /* use override */
7229                                         } else if (wlc->mimo_40txbw != AUTO)
7230                                                 mimo_txbw = wlc->mimo_40txbw;
7231                                         /* else check if dst is using 40 Mhz */
7232                                         else if (scb->flags & SCB_IS40)
7233                                                 mimo_txbw = PHY_TXC1_BW_40MHZ;
7234                                 } else if (is_ofdm_rate(rspec[k])) {
7235                                         if (wlc->ofdm_40txbw != AUTO)
7236                                                 mimo_txbw = wlc->ofdm_40txbw;
7237                                 } else if (wlc->cck_40txbw != AUTO) {
7238                                         mimo_txbw = wlc->cck_40txbw;
7239                                 }
7240                         } else {
7241                                 /*
7242                                  * mcs32 is 40 b/w only.
7243                                  * This is possible for probe packets on
7244                                  * a STA during SCAN
7245                                  */
7246                                 if ((rspec[k] & RSPEC_RATE_MASK) == 32)
7247                                         /* mcs 0 */
7248                                         rspec[k] = RSPEC_MIMORATE;
7249
7250                                 mimo_txbw = PHY_TXC1_BW_20MHZ;
7251                         }
7252
7253                         /* Set channel width */
7254                         rspec[k] &= ~RSPEC_BW_MASK;
7255                         if ((k == 0) || ((k > 0) && is_mcs_rate(rspec[k])))
7256                                 rspec[k] |= (mimo_txbw << RSPEC_BW_SHIFT);
7257                         else
7258                                 rspec[k] |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
7259
7260                         /* Disable short GI, not supported yet */
7261                         rspec[k] &= ~RSPEC_SHORT_GI;
7262
7263                         mimo_preamble_type = BRCMS_MM_PREAMBLE;
7264                         if (txrate[k]->flags & IEEE80211_TX_RC_GREEN_FIELD)
7265                                 mimo_preamble_type = BRCMS_GF_PREAMBLE;
7266
7267                         if ((txrate[k]->flags & IEEE80211_TX_RC_MCS)
7268                             && (!is_mcs_rate(rspec[k]))) {
7269                                 wiphy_err(wlc->wiphy, "wl%d: %s: IEEE80211_TX_"
7270                                           "RC_MCS != is_mcs_rate(rspec)\n",
7271                                           wlc->pub->unit, __func__);
7272                         }
7273
7274                         if (is_mcs_rate(rspec[k])) {
7275                                 preamble_type[k] = mimo_preamble_type;
7276
7277                                 /*
7278                                  * if SGI is selected, then forced mm
7279                                  * for single stream
7280                                  */
7281                                 if ((rspec[k] & RSPEC_SHORT_GI)
7282                                     && is_single_stream(rspec[k] &
7283                                                         RSPEC_RATE_MASK))
7284                                         preamble_type[k] = BRCMS_MM_PREAMBLE;
7285                         }
7286
7287                         /* should be better conditionalized */
7288                         if (!is_mcs_rate(rspec[0])
7289                             && (tx_info->control.rates[0].
7290                                 flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE))
7291                                 preamble_type[k] = BRCMS_SHORT_PREAMBLE;
7292                 }
7293         } else {
7294                 for (k = 0; k < hw->max_rates; k++) {
7295                         /* Set ctrlchbw as 20Mhz */
7296                         rspec[k] &= ~RSPEC_BW_MASK;
7297                         rspec[k] |= (PHY_TXC1_BW_20MHZ << RSPEC_BW_SHIFT);
7298
7299                         /* for nphy, stf of ofdm frames must follow policies */
7300                         if (BRCMS_ISNPHY(wlc->band) && is_ofdm_rate(rspec[k])) {
7301                                 rspec[k] &= ~RSPEC_STF_MASK;
7302                                 rspec[k] |= phyctl1_stf << RSPEC_STF_SHIFT;
7303                         }
7304                 }
7305         }
7306
7307         /* Reset these for use with AMPDU's */
7308         txrate[0]->count = 0;
7309         txrate[1]->count = 0;
7310
7311         /* (2) PROTECTION, may change rspec */
7312         if ((ieee80211_is_data(h->frame_control) ||
7313             ieee80211_is_mgmt(h->frame_control)) &&
7314             (phylen > wlc->RTSThresh) && !is_multicast_ether_addr(h->addr1))
7315                 use_rts = true;
7316
7317         /* (3) PLCP: determine PLCP header and MAC duration,
7318          * fill struct d11txh */
7319         brcms_c_compute_plcp(wlc, rspec[0], phylen, plcp);
7320         brcms_c_compute_plcp(wlc, rspec[1], phylen, plcp_fallback);
7321         memcpy(&txh->FragPLCPFallback,
7322                plcp_fallback, sizeof(txh->FragPLCPFallback));
7323
7324         /* Length field now put in CCK FBR CRC field */
7325         if (is_cck_rate(rspec[1])) {
7326                 txh->FragPLCPFallback[4] = phylen & 0xff;
7327                 txh->FragPLCPFallback[5] = (phylen & 0xff00) >> 8;
7328         }
7329
7330         /* MIMO-RATE: need validation ?? */
7331         mainrates = is_ofdm_rate(rspec[0]) ?
7332                         D11A_PHY_HDR_GRATE((struct ofdm_phy_hdr *) plcp) :
7333                         plcp[0];
7334
7335         /* DUR field for main rate */
7336         if (!ieee80211_is_pspoll(h->frame_control) &&
7337             !is_multicast_ether_addr(h->addr1) && !use_rifs) {
7338                 durid =
7339                     brcms_c_compute_frame_dur(wlc, rspec[0], preamble_type[0],
7340                                           next_frag_len);
7341                 h->duration_id = cpu_to_le16(durid);
7342         } else if (use_rifs) {
7343                 /* NAV protect to end of next max packet size */
7344                 durid =
7345                     (u16) brcms_c_calc_frame_time(wlc, rspec[0],
7346                                                  preamble_type[0],
7347                                                  DOT11_MAX_FRAG_LEN);
7348                 durid += RIFS_11N_TIME;
7349                 h->duration_id = cpu_to_le16(durid);
7350         }
7351
7352         /* DUR field for fallback rate */
7353         if (ieee80211_is_pspoll(h->frame_control))
7354                 txh->FragDurFallback = h->duration_id;
7355         else if (is_multicast_ether_addr(h->addr1) || use_rifs)
7356                 txh->FragDurFallback = 0;
7357         else {
7358                 durid = brcms_c_compute_frame_dur(wlc, rspec[1],
7359                                               preamble_type[1], next_frag_len);
7360                 txh->FragDurFallback = cpu_to_le16(durid);
7361         }
7362
7363         /* (4) MAC-HDR: MacTxControlLow */
7364         if (frag == 0)
7365                 mcl |= TXC_STARTMSDU;
7366
7367         if (!is_multicast_ether_addr(h->addr1))
7368                 mcl |= TXC_IMMEDACK;
7369
7370         if (wlc->band->bandtype == BRCM_BAND_5G)
7371                 mcl |= TXC_FREQBAND_5G;
7372
7373         if (CHSPEC_IS40(wlc_phy_chanspec_get(wlc->band->pi)))
7374                 mcl |= TXC_BW_40;
7375
7376         /* set AMIC bit if using hardware TKIP MIC */
7377         if (hwtkmic)
7378                 mcl |= TXC_AMIC;
7379
7380         txh->MacTxControlLow = cpu_to_le16(mcl);
7381
7382         /* MacTxControlHigh */
7383         mch = 0;
7384
7385         /* Set fallback rate preamble type */
7386         if ((preamble_type[1] == BRCMS_SHORT_PREAMBLE) ||
7387             (preamble_type[1] == BRCMS_GF_PREAMBLE)) {
7388                 if (rspec2rate(rspec[1]) != BRCM_RATE_1M)
7389                         mch |= TXC_PREAMBLE_DATA_FB_SHORT;
7390         }
7391
7392         /* MacFrameControl */
7393         memcpy(&txh->MacFrameControl, &h->frame_control, sizeof(u16));
7394         txh->TxFesTimeNormal = cpu_to_le16(0);
7395
7396         txh->TxFesTimeFallback = cpu_to_le16(0);
7397
7398         /* TxFrameRA */
7399         memcpy(&txh->TxFrameRA, &h->addr1, ETH_ALEN);
7400
7401         /* TxFrameID */
7402         txh->TxFrameID = cpu_to_le16(frameid);
7403
7404         /*
7405          * TxStatus, Note the case of recreating the first frag of a suppressed
7406          * frame then we may need to reset the retry cnt's via the status reg
7407          */
7408         txh->TxStatus = cpu_to_le16(status);
7409
7410         /*
7411          * extra fields for ucode AMPDU aggregation, the new fields are added to
7412          * the END of previous structure so that it's compatible in driver.
7413          */
7414         txh->MaxNMpdus = cpu_to_le16(0);
7415         txh->MaxABytes_MRT = cpu_to_le16(0);
7416         txh->MaxABytes_FBR = cpu_to_le16(0);
7417         txh->MinMBytes = cpu_to_le16(0);
7418
7419         /* (5) RTS/CTS: determine RTS/CTS PLCP header and MAC duration,
7420          * furnish struct d11txh */
7421         /* RTS PLCP header and RTS frame */
7422         if (use_rts || use_cts) {
7423                 if (use_rts && use_cts)
7424                         use_cts = false;
7425
7426                 for (k = 0; k < 2; k++) {
7427                         rts_rspec[k] = brcms_c_rspec_to_rts_rspec(wlc, rspec[k],
7428                                                               false,
7429                                                               mimo_ctlchbw);
7430                 }
7431
7432                 if (!is_ofdm_rate(rts_rspec[0]) &&
7433                     !((rspec2rate(rts_rspec[0]) == BRCM_RATE_1M) ||
7434                       (wlc->PLCPHdr_override == BRCMS_PLCP_LONG))) {
7435                         rts_preamble_type[0] = BRCMS_SHORT_PREAMBLE;
7436                         mch |= TXC_PREAMBLE_RTS_MAIN_SHORT;
7437                 }
7438
7439                 if (!is_ofdm_rate(rts_rspec[1]) &&
7440                     !((rspec2rate(rts_rspec[1]) == BRCM_RATE_1M) ||
7441                       (wlc->PLCPHdr_override == BRCMS_PLCP_LONG))) {
7442                         rts_preamble_type[1] = BRCMS_SHORT_PREAMBLE;
7443                         mch |= TXC_PREAMBLE_RTS_FB_SHORT;
7444                 }
7445
7446                 /* RTS/CTS additions to MacTxControlLow */
7447                 if (use_cts) {
7448                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDCTS);
7449                 } else {
7450                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDRTS);
7451                         txh->MacTxControlLow |= cpu_to_le16(TXC_LONGFRAME);
7452                 }
7453
7454                 /* RTS PLCP header */
7455                 rts_plcp = txh->RTSPhyHeader;
7456                 if (use_cts)
7457                         rts_phylen = DOT11_CTS_LEN + FCS_LEN;
7458                 else
7459                         rts_phylen = DOT11_RTS_LEN + FCS_LEN;
7460
7461                 brcms_c_compute_plcp(wlc, rts_rspec[0], rts_phylen, rts_plcp);
7462
7463                 /* fallback rate version of RTS PLCP header */
7464                 brcms_c_compute_plcp(wlc, rts_rspec[1], rts_phylen,
7465                                  rts_plcp_fallback);
7466                 memcpy(&txh->RTSPLCPFallback, rts_plcp_fallback,
7467                        sizeof(txh->RTSPLCPFallback));
7468
7469                 /* RTS frame fields... */
7470                 rts = (struct ieee80211_rts *)&txh->rts_frame;
7471
7472                 durid = brcms_c_compute_rtscts_dur(wlc, use_cts, rts_rspec[0],
7473                                                rspec[0], rts_preamble_type[0],
7474                                                preamble_type[0], phylen, false);
7475                 rts->duration = cpu_to_le16(durid);
7476                 /* fallback rate version of RTS DUR field */
7477                 durid = brcms_c_compute_rtscts_dur(wlc, use_cts,
7478                                                rts_rspec[1], rspec[1],
7479                                                rts_preamble_type[1],
7480                                                preamble_type[1], phylen, false);
7481                 txh->RTSDurFallback = cpu_to_le16(durid);
7482
7483                 if (use_cts) {
7484                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
7485                                                          IEEE80211_STYPE_CTS);
7486
7487                         memcpy(&rts->ra, &h->addr2, ETH_ALEN);
7488                 } else {
7489                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
7490                                                          IEEE80211_STYPE_RTS);
7491
7492                         memcpy(&rts->ra, &h->addr1, 2 * ETH_ALEN);
7493                 }
7494
7495                 /* mainrate
7496                  *    low 8 bits: main frag rate/mcs,
7497                  *    high 8 bits: rts/cts rate/mcs
7498                  */
7499                 mainrates |= (is_ofdm_rate(rts_rspec[0]) ?
7500                                 D11A_PHY_HDR_GRATE(
7501                                         (struct ofdm_phy_hdr *) rts_plcp) :
7502                                 rts_plcp[0]) << 8;
7503         } else {
7504                 memset((char *)txh->RTSPhyHeader, 0, D11_PHY_HDR_LEN);
7505                 memset((char *)&txh->rts_frame, 0,
7506                         sizeof(struct ieee80211_rts));
7507                 memset((char *)txh->RTSPLCPFallback, 0,
7508                       sizeof(txh->RTSPLCPFallback));
7509                 txh->RTSDurFallback = 0;
7510         }
7511
7512 #ifdef SUPPORT_40MHZ
7513         /* add null delimiter count */
7514         if ((tx_info->flags & IEEE80211_TX_CTL_AMPDU) && is_mcs_rate(rspec))
7515                 txh->RTSPLCPFallback[AMPDU_FBR_NULL_DELIM] =
7516                    brcm_c_ampdu_null_delim_cnt(wlc->ampdu, scb, rspec, phylen);
7517
7518 #endif
7519
7520         /*
7521          * Now that RTS/RTS FB preamble types are updated, write
7522          * the final value
7523          */
7524         txh->MacTxControlHigh = cpu_to_le16(mch);
7525
7526         /*
7527          * MainRates (both the rts and frag plcp rates have
7528          * been calculated now)
7529          */
7530         txh->MainRates = cpu_to_le16(mainrates);
7531
7532         /* XtraFrameTypes */
7533         xfts = frametype(rspec[1], wlc->mimoft);
7534         xfts |= (frametype(rts_rspec[0], wlc->mimoft) << XFTS_RTS_FT_SHIFT);
7535         xfts |= (frametype(rts_rspec[1], wlc->mimoft) << XFTS_FBRRTS_FT_SHIFT);
7536         xfts |= CHSPEC_CHANNEL(wlc_phy_chanspec_get(wlc->band->pi)) <<
7537                                                              XFTS_CHANNEL_SHIFT;
7538         txh->XtraFrameTypes = cpu_to_le16(xfts);
7539
7540         /* PhyTxControlWord */
7541         phyctl = frametype(rspec[0], wlc->mimoft);
7542         if ((preamble_type[0] == BRCMS_SHORT_PREAMBLE) ||
7543             (preamble_type[0] == BRCMS_GF_PREAMBLE)) {
7544                 if (rspec2rate(rspec[0]) != BRCM_RATE_1M)
7545                         phyctl |= PHY_TXC_SHORT_HDR;
7546         }
7547
7548         /* phytxant is properly bit shifted */
7549         phyctl |= brcms_c_stf_d11hdrs_phyctl_txant(wlc, rspec[0]);
7550         txh->PhyTxControlWord = cpu_to_le16(phyctl);
7551
7552         /* PhyTxControlWord_1 */
7553         if (BRCMS_PHY_11N_CAP(wlc->band)) {
7554                 u16 phyctl1 = 0;
7555
7556                 phyctl1 = brcms_c_phytxctl1_calc(wlc, rspec[0]);
7557                 txh->PhyTxControlWord_1 = cpu_to_le16(phyctl1);
7558                 phyctl1 = brcms_c_phytxctl1_calc(wlc, rspec[1]);
7559                 txh->PhyTxControlWord_1_Fbr = cpu_to_le16(phyctl1);
7560
7561                 if (use_rts || use_cts) {
7562                         phyctl1 = brcms_c_phytxctl1_calc(wlc, rts_rspec[0]);
7563                         txh->PhyTxControlWord_1_Rts = cpu_to_le16(phyctl1);
7564                         phyctl1 = brcms_c_phytxctl1_calc(wlc, rts_rspec[1]);
7565                         txh->PhyTxControlWord_1_FbrRts = cpu_to_le16(phyctl1);
7566                 }
7567
7568                 /*
7569                  * For mcs frames, if mixedmode(overloaded with long preamble)
7570                  * is going to be set, fill in non-zero MModeLen and/or
7571                  * MModeFbrLen it will be unnecessary if they are separated
7572                  */
7573                 if (is_mcs_rate(rspec[0]) &&
7574                     (preamble_type[0] == BRCMS_MM_PREAMBLE)) {
7575                         u16 mmodelen =
7576                             brcms_c_calc_lsig_len(wlc, rspec[0], phylen);
7577                         txh->MModeLen = cpu_to_le16(mmodelen);
7578                 }
7579
7580                 if (is_mcs_rate(rspec[1]) &&
7581                     (preamble_type[1] == BRCMS_MM_PREAMBLE)) {
7582                         u16 mmodefbrlen =
7583                             brcms_c_calc_lsig_len(wlc, rspec[1], phylen);
7584                         txh->MModeFbrLen = cpu_to_le16(mmodefbrlen);
7585                 }
7586         }
7587
7588         ac = skb_get_queue_mapping(p);
7589         if ((scb->flags & SCB_WMECAP) && qos && wlc->edcf_txop[ac]) {
7590                 uint frag_dur, dur, dur_fallback;
7591
7592                 /* WME: Update TXOP threshold */
7593                 if (!(tx_info->flags & IEEE80211_TX_CTL_AMPDU) && frag == 0) {
7594                         frag_dur =
7595                             brcms_c_calc_frame_time(wlc, rspec[0],
7596                                         preamble_type[0], phylen);
7597
7598                         if (rts) {
7599                                 /* 1 RTS or CTS-to-self frame */
7600                                 dur =
7601                                     brcms_c_calc_cts_time(wlc, rts_rspec[0],
7602                                                       rts_preamble_type[0]);
7603                                 dur_fallback =
7604                                     brcms_c_calc_cts_time(wlc, rts_rspec[1],
7605                                                       rts_preamble_type[1]);
7606                                 /* (SIFS + CTS) + SIFS + frame + SIFS + ACK */
7607                                 dur += le16_to_cpu(rts->duration);
7608                                 dur_fallback +=
7609                                         le16_to_cpu(txh->RTSDurFallback);
7610                         } else if (use_rifs) {
7611                                 dur = frag_dur;
7612                                 dur_fallback = 0;
7613                         } else {
7614                                 /* frame + SIFS + ACK */
7615                                 dur = frag_dur;
7616                                 dur +=
7617                                     brcms_c_compute_frame_dur(wlc, rspec[0],
7618                                                           preamble_type[0], 0);
7619
7620                                 dur_fallback =
7621                                     brcms_c_calc_frame_time(wlc, rspec[1],
7622                                                         preamble_type[1],
7623                                                         phylen);
7624                                 dur_fallback +=
7625                                     brcms_c_compute_frame_dur(wlc, rspec[1],
7626                                                           preamble_type[1], 0);
7627                         }
7628                         /* NEED to set TxFesTimeNormal (hard) */
7629                         txh->TxFesTimeNormal = cpu_to_le16((u16) dur);
7630                         /*
7631                          * NEED to set fallback rate version of
7632                          * TxFesTimeNormal (hard)
7633                          */
7634                         txh->TxFesTimeFallback =
7635                                 cpu_to_le16((u16) dur_fallback);
7636
7637                         /*
7638                          * update txop byte threshold (txop minus intraframe
7639                          * overhead)
7640                          */
7641                         if (wlc->edcf_txop[ac] >= (dur - frag_dur)) {
7642                                 uint newfragthresh;
7643
7644                                 newfragthresh =
7645                                     brcms_c_calc_frame_len(wlc,
7646                                         rspec[0], preamble_type[0],
7647                                         (wlc->edcf_txop[ac] -
7648                                                 (dur - frag_dur)));
7649                                 /* range bound the fragthreshold */
7650                                 if (newfragthresh < DOT11_MIN_FRAG_LEN)
7651                                         newfragthresh =
7652                                             DOT11_MIN_FRAG_LEN;
7653                                 else if (newfragthresh >
7654                                          wlc->usr_fragthresh)
7655                                         newfragthresh =
7656                                             wlc->usr_fragthresh;
7657                                 /* update the fragthresh and do txc update */
7658                                 if (wlc->fragthresh[queue] !=
7659                                     (u16) newfragthresh)
7660                                         wlc->fragthresh[queue] =
7661                                             (u16) newfragthresh;
7662                         } else {
7663                                 wiphy_err(wlc->wiphy, "wl%d: %s txop invalid "
7664                                           "for rate %d\n",
7665                                           wlc->pub->unit, fifo_names[queue],
7666                                           rspec2rate(rspec[0]));
7667                         }
7668
7669                         if (dur > wlc->edcf_txop[ac])
7670                                 wiphy_err(wlc->wiphy, "wl%d: %s: %s txop "
7671                                           "exceeded phylen %d/%d dur %d/%d\n",
7672                                           wlc->pub->unit, __func__,
7673                                           fifo_names[queue],
7674                                           phylen, wlc->fragthresh[queue],
7675                                           dur, wlc->edcf_txop[ac]);
7676                 }
7677         }
7678
7679         return 0;
7680 }
7681
7682 void brcms_c_sendpkt_mac80211(struct brcms_c_info *wlc, struct sk_buff *sdu,
7683                               struct ieee80211_hw *hw)
7684 {
7685         u8 prio;
7686         uint fifo;
7687         struct scb *scb = &global_scb;
7688         struct ieee80211_hdr *d11_header = (struct ieee80211_hdr *)(sdu->data);
7689
7690         /*
7691          * 802.11 standard requires management traffic
7692          * to go at highest priority
7693          */
7694         prio = ieee80211_is_data(d11_header->frame_control) ? sdu->priority :
7695                 MAXPRIO;
7696         fifo = prio2fifo[prio];
7697         if (brcms_c_d11hdrs_mac80211(wlc, hw, sdu, scb, 0, 1, fifo, 0))
7698                 return;
7699         brcms_c_txq_enq(wlc, scb, sdu, BRCMS_PRIO_TO_PREC(prio));
7700         brcms_c_send_q(wlc);
7701 }
7702
7703 void brcms_c_send_q(struct brcms_c_info *wlc)
7704 {
7705         struct sk_buff *pkt[DOT11_MAXNUMFRAGS];
7706         int prec;
7707         u16 prec_map;
7708         int err = 0, i, count;
7709         uint fifo;
7710         struct brcms_txq_info *qi = wlc->pkt_queue;
7711         struct pktq *q = &qi->q;
7712         struct ieee80211_tx_info *tx_info;
7713
7714         if (in_send_q)
7715                 return;
7716         else
7717                 in_send_q = true;
7718
7719         prec_map = wlc->tx_prec_map;
7720
7721         /* Send all the enq'd pkts that we can.
7722          * Dequeue packets with precedence with empty HW fifo only
7723          */
7724         while (prec_map && (pkt[0] = brcmu_pktq_mdeq(q, prec_map, &prec))) {
7725                 tx_info = IEEE80211_SKB_CB(pkt[0]);
7726                 if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
7727                         err = brcms_c_sendampdu(wlc->ampdu, qi, pkt, prec);
7728                 } else {
7729                         count = 1;
7730                         err = brcms_c_prep_pdu(wlc, pkt[0], &fifo);
7731                         if (!err) {
7732                                 for (i = 0; i < count; i++)
7733                                         brcms_c_txfifo(wlc, fifo, pkt[i], true,
7734                                                        1);
7735                         }
7736                 }
7737
7738                 if (err == -EBUSY) {
7739                         brcmu_pktq_penq_head(q, prec, pkt[0]);
7740                         /*
7741                          * If send failed due to any other reason than a
7742                          * change in HW FIFO condition, quit. Otherwise,
7743                          * read the new prec_map!
7744                          */
7745                         if (prec_map == wlc->tx_prec_map)
7746                                 break;
7747                         prec_map = wlc->tx_prec_map;
7748                 }
7749         }
7750
7751         in_send_q = false;
7752 }
7753
7754 void
7755 brcms_c_txfifo(struct brcms_c_info *wlc, uint fifo, struct sk_buff *p,
7756                bool commit, s8 txpktpend)
7757 {
7758         u16 frameid = INVALIDFID;
7759         struct d11txh *txh;
7760
7761         txh = (struct d11txh *) (p->data);
7762
7763         /* When a BC/MC frame is being committed to the BCMC fifo
7764          * via DMA (NOT PIO), update ucode or BSS info as appropriate.
7765          */
7766         if (fifo == TX_BCMC_FIFO)
7767                 frameid = le16_to_cpu(txh->TxFrameID);
7768
7769         /*
7770          * Bump up pending count for if not using rpc. If rpc is
7771          * used, this will be handled in brcms_b_txfifo()
7772          */
7773         if (commit) {
7774                 wlc->core->txpktpend[fifo] += txpktpend;
7775                 BCMMSG(wlc->wiphy, "pktpend inc %d to %d\n",
7776                          txpktpend, wlc->core->txpktpend[fifo]);
7777         }
7778
7779         /* Commit BCMC sequence number in the SHM frame ID location */
7780         if (frameid != INVALIDFID) {
7781                 /*
7782                  * To inform the ucode of the last mcast frame posted
7783                  * so that it can clear moredata bit
7784                  */
7785                 brcms_b_write_shm(wlc->hw, M_BCMC_FID, frameid);
7786         }
7787
7788         if (dma_txfast(wlc->hw->di[fifo], p, commit) < 0)
7789                 wiphy_err(wlc->wiphy, "txfifo: fatal, toss frames !!!\n");
7790 }
7791
7792 /*
7793  * Compute PLCP, but only requires actual rate and length of pkt.
7794  * Rate is given in the driver standard multiple of 500 kbps.
7795  * le is set for 11 Mbps rate if necessary.
7796  * Broken out for PRQ.
7797  */
7798
7799 static void brcms_c_cck_plcp_set(struct brcms_c_info *wlc, int rate_500,
7800                              uint length, u8 *plcp)
7801 {
7802         u16 usec = 0;
7803         u8 le = 0;
7804
7805         switch (rate_500) {
7806         case BRCM_RATE_1M:
7807                 usec = length << 3;
7808                 break;
7809         case BRCM_RATE_2M:
7810                 usec = length << 2;
7811                 break;
7812         case BRCM_RATE_5M5:
7813                 usec = (length << 4) / 11;
7814                 if ((length << 4) - (usec * 11) > 0)
7815                         usec++;
7816                 break;
7817         case BRCM_RATE_11M:
7818                 usec = (length << 3) / 11;
7819                 if ((length << 3) - (usec * 11) > 0) {
7820                         usec++;
7821                         if ((usec * 11) - (length << 3) >= 8)
7822                                 le = D11B_PLCP_SIGNAL_LE;
7823                 }
7824                 break;
7825
7826         default:
7827                 wiphy_err(wlc->wiphy,
7828                           "brcms_c_cck_plcp_set: unsupported rate %d\n",
7829                           rate_500);
7830                 rate_500 = BRCM_RATE_1M;
7831                 usec = length << 3;
7832                 break;
7833         }
7834         /* PLCP signal byte */
7835         plcp[0] = rate_500 * 5; /* r (500kbps) * 5 == r (100kbps) */
7836         /* PLCP service byte */
7837         plcp[1] = (u8) (le | D11B_PLCP_SIGNAL_LOCKED);
7838         /* PLCP length u16, little endian */
7839         plcp[2] = usec & 0xff;
7840         plcp[3] = (usec >> 8) & 0xff;
7841         /* PLCP CRC16 */
7842         plcp[4] = 0;
7843         plcp[5] = 0;
7844 }
7845
7846 /* Rate: 802.11 rate code, length: PSDU length in octets */
7847 static void brcms_c_compute_mimo_plcp(u32 rspec, uint length, u8 *plcp)
7848 {
7849         u8 mcs = (u8) (rspec & RSPEC_RATE_MASK);
7850         plcp[0] = mcs;
7851         if (rspec_is40mhz(rspec) || (mcs == 32))
7852                 plcp[0] |= MIMO_PLCP_40MHZ;
7853         BRCMS_SET_MIMO_PLCP_LEN(plcp, length);
7854         plcp[3] = rspec_mimoplcp3(rspec); /* rspec already holds this byte */
7855         plcp[3] |= 0x7; /* set smoothing, not sounding ppdu & reserved */
7856         plcp[4] = 0; /* number of extension spatial streams bit 0 & 1 */
7857         plcp[5] = 0;
7858 }
7859
7860 /* Rate: 802.11 rate code, length: PSDU length in octets */
7861 static void
7862 brcms_c_compute_ofdm_plcp(u32 rspec, u32 length, u8 *plcp)
7863 {
7864         u8 rate_signal;
7865         u32 tmp = 0;
7866         int rate = rspec2rate(rspec);
7867
7868         /*
7869          * encode rate per 802.11a-1999 sec 17.3.4.1, with lsb
7870          * transmitted first
7871          */
7872         rate_signal = rate_info[rate] & BRCMS_RATE_MASK;
7873         memset(plcp, 0, D11_PHY_HDR_LEN);
7874         D11A_PHY_HDR_SRATE((struct ofdm_phy_hdr *) plcp, rate_signal);
7875
7876         tmp = (length & 0xfff) << 5;
7877         plcp[2] |= (tmp >> 16) & 0xff;
7878         plcp[1] |= (tmp >> 8) & 0xff;
7879         plcp[0] |= tmp & 0xff;
7880
7881         return;
7882 }
7883
7884 /* Rate: 802.11 rate code, length: PSDU length in octets */
7885 static void brcms_c_compute_cck_plcp(struct brcms_c_info *wlc, u32 rspec,
7886                                  uint length, u8 *plcp)
7887 {
7888         int rate = rspec2rate(rspec);
7889
7890         brcms_c_cck_plcp_set(wlc, rate, length, plcp);
7891 }
7892
7893 void
7894 brcms_c_compute_plcp(struct brcms_c_info *wlc, u32 rspec,
7895                      uint length, u8 *plcp)
7896 {
7897         if (is_mcs_rate(rspec))
7898                 brcms_c_compute_mimo_plcp(rspec, length, plcp);
7899         else if (is_ofdm_rate(rspec))
7900                 brcms_c_compute_ofdm_plcp(rspec, length, plcp);
7901         else
7902                 brcms_c_compute_cck_plcp(wlc, rspec, length, plcp);
7903         return;
7904 }
7905
7906 /* brcms_c_compute_rtscts_dur()
7907  *
7908  * Calculate the 802.11 MAC header DUR field for an RTS or CTS frame
7909  * DUR for normal RTS/CTS w/ frame = 3 SIFS + 1 CTS + next frame time + 1 ACK
7910  * DUR for CTS-TO-SELF w/ frame    = 2 SIFS         + next frame time + 1 ACK
7911  *
7912  * cts                  cts-to-self or rts/cts
7913  * rts_rate             rts or cts rate in unit of 500kbps
7914  * rate                 next MPDU rate in unit of 500kbps
7915  * frame_len            next MPDU frame length in bytes
7916  */
7917 u16
7918 brcms_c_compute_rtscts_dur(struct brcms_c_info *wlc, bool cts_only,
7919                            u32 rts_rate,
7920                            u32 frame_rate, u8 rts_preamble_type,
7921                            u8 frame_preamble_type, uint frame_len, bool ba)
7922 {
7923         u16 dur, sifs;
7924
7925         sifs = get_sifs(wlc->band);
7926
7927         if (!cts_only) {
7928                 /* RTS/CTS */
7929                 dur = 3 * sifs;
7930                 dur +=
7931                     (u16) brcms_c_calc_cts_time(wlc, rts_rate,
7932                                                rts_preamble_type);
7933         } else {
7934                 /* CTS-TO-SELF */
7935                 dur = 2 * sifs;
7936         }
7937
7938         dur +=
7939             (u16) brcms_c_calc_frame_time(wlc, frame_rate, frame_preamble_type,
7940                                          frame_len);
7941         if (ba)
7942                 dur +=
7943                     (u16) brcms_c_calc_ba_time(wlc, frame_rate,
7944                                               BRCMS_SHORT_PREAMBLE);
7945         else
7946                 dur +=
7947                     (u16) brcms_c_calc_ack_time(wlc, frame_rate,
7948                                                frame_preamble_type);
7949         return dur;
7950 }
7951
7952 u16 brcms_c_phytxctl1_calc(struct brcms_c_info *wlc, u32 rspec)
7953 {
7954         u16 phyctl1 = 0;
7955         u16 bw;
7956
7957         if (BRCMS_ISLCNPHY(wlc->band)) {
7958                 bw = PHY_TXC1_BW_20MHZ;
7959         } else {
7960                 bw = rspec_get_bw(rspec);
7961                 /* 10Mhz is not supported yet */
7962                 if (bw < PHY_TXC1_BW_20MHZ) {
7963                         wiphy_err(wlc->wiphy, "phytxctl1_calc: bw %d is "
7964                                   "not supported yet, set to 20L\n", bw);
7965                         bw = PHY_TXC1_BW_20MHZ;
7966                 }
7967         }
7968
7969         if (is_mcs_rate(rspec)) {
7970                 uint mcs = rspec & RSPEC_RATE_MASK;
7971
7972                 /* bw, stf, coding-type is part of rspec_phytxbyte2 returns */
7973                 phyctl1 = rspec_phytxbyte2(rspec);
7974                 /* set the upper byte of phyctl1 */
7975                 phyctl1 |= (mcs_table[mcs].tx_phy_ctl3 << 8);
7976         } else if (is_cck_rate(rspec) && !BRCMS_ISLCNPHY(wlc->band)
7977                    && !BRCMS_ISSSLPNPHY(wlc->band)) {
7978                 /*
7979                  * In CCK mode LPPHY overloads OFDM Modulation bits with CCK
7980                  * Data Rate. Eventually MIMOPHY would also be converted to
7981                  * this format
7982                  */
7983                 /* 0 = 1Mbps; 1 = 2Mbps; 2 = 5.5Mbps; 3 = 11Mbps */
7984                 phyctl1 = (bw | (rspec_stf(rspec) << PHY_TXC1_MODE_SHIFT));
7985         } else {                /* legacy OFDM/CCK */
7986                 s16 phycfg;
7987                 /* get the phyctl byte from rate phycfg table */
7988                 phycfg = brcms_c_rate_legacy_phyctl(rspec2rate(rspec));
7989                 if (phycfg == -1) {
7990                         wiphy_err(wlc->wiphy, "phytxctl1_calc: wrong "
7991                                   "legacy OFDM/CCK rate\n");
7992                         phycfg = 0;
7993                 }
7994                 /* set the upper byte of phyctl1 */
7995                 phyctl1 =
7996                     (bw | (phycfg << 8) |
7997                      (rspec_stf(rspec) << PHY_TXC1_MODE_SHIFT));
7998         }
7999         return phyctl1;
8000 }
8001
8002 u32
8003 brcms_c_rspec_to_rts_rspec(struct brcms_c_info *wlc, u32 rspec,
8004                            bool use_rspec, u16 mimo_ctlchbw)
8005 {
8006         u32 rts_rspec = 0;
8007
8008         if (use_rspec)
8009                 /* use frame rate as rts rate */
8010                 rts_rspec = rspec;
8011         else if (wlc->band->gmode && wlc->protection->_g && !is_cck_rate(rspec))
8012                 /* Use 11Mbps as the g protection RTS target rate and fallback.
8013                  * Use the brcms_basic_rate() lookup to find the best basic rate
8014                  * under the target in case 11 Mbps is not Basic.
8015                  * 6 and 9 Mbps are not usually selected by rate selection, but
8016                  * even if the OFDM rate we are protecting is 6 or 9 Mbps, 11
8017                  * is more robust.
8018                  */
8019                 rts_rspec = brcms_basic_rate(wlc, BRCM_RATE_11M);
8020         else
8021                 /* calculate RTS rate and fallback rate based on the frame rate
8022                  * RTS must be sent at a basic rate since it is a
8023                  * control frame, sec 9.6 of 802.11 spec
8024                  */
8025                 rts_rspec = brcms_basic_rate(wlc, rspec);
8026
8027         if (BRCMS_PHY_11N_CAP(wlc->band)) {
8028                 /* set rts txbw to correct side band */
8029                 rts_rspec &= ~RSPEC_BW_MASK;
8030
8031                 /*
8032                  * if rspec/rspec_fallback is 40MHz, then send RTS on both
8033                  * 20MHz channel (DUP), otherwise send RTS on control channel
8034                  */
8035                 if (rspec_is40mhz(rspec) && !is_cck_rate(rts_rspec))
8036                         rts_rspec |= (PHY_TXC1_BW_40MHZ_DUP << RSPEC_BW_SHIFT);
8037                 else
8038                         rts_rspec |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
8039
8040                 /* pick siso/cdd as default for ofdm */
8041                 if (is_ofdm_rate(rts_rspec)) {
8042                         rts_rspec &= ~RSPEC_STF_MASK;
8043                         rts_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
8044                 }
8045         }
8046         return rts_rspec;
8047 }
8048
8049 void brcms_c_tbtt(struct brcms_c_info *wlc)
8050 {
8051         if (!wlc->bsscfg->BSS)
8052                 /*
8053                  * DirFrmQ is now valid...defer setting until end
8054                  * of ATIM window
8055                  */
8056                 wlc->qvalid |= MCMD_DIRFRMQVAL;
8057 }
8058
8059 void
8060 brcms_c_txfifo_complete(struct brcms_c_info *wlc, uint fifo, s8 txpktpend)
8061 {
8062         wlc->core->txpktpend[fifo] -= txpktpend;
8063         BCMMSG(wlc->wiphy, "pktpend dec %d to %d\n", txpktpend,
8064                wlc->core->txpktpend[fifo]);
8065
8066         /* There is more room; mark precedences related to this FIFO sendable */
8067         wlc->tx_prec_map |= wlc->fifo2prec_map[fifo];
8068
8069         /* figure out which bsscfg is being worked on... */
8070 }
8071
8072 /* Update beacon listen interval in shared memory */
8073 void brcms_c_bcn_li_upd(struct brcms_c_info *wlc)
8074 {
8075         /* wake up every DTIM is the default */
8076         if (wlc->bcn_li_dtim == 1)
8077                 brcms_c_write_shm(wlc, M_BCN_LI, 0);
8078         else
8079                 brcms_c_write_shm(wlc, M_BCN_LI,
8080                               (wlc->bcn_li_dtim << 8) | wlc->bcn_li_bcn);
8081 }
8082
8083 static void
8084 brcms_b_read_tsf(struct brcms_hardware *wlc_hw, u32 *tsf_l_ptr,
8085                   u32 *tsf_h_ptr)
8086 {
8087         struct d11regs *regs = wlc_hw->regs;
8088
8089         /* read the tsf timer low, then high to get an atomic read */
8090         *tsf_l_ptr = R_REG(&regs->tsf_timerlow);
8091         *tsf_h_ptr = R_REG(&regs->tsf_timerhigh);
8092
8093         return;
8094 }
8095
8096 /*
8097  * recover 64bit TSF value from the 16bit TSF value in the rx header
8098  * given the assumption that the TSF passed in header is within 65ms
8099  * of the current tsf.
8100  *
8101  * 6       5       4       4       3       2       1
8102  * 3.......6.......8.......0.......2.......4.......6.......8......0
8103  * |<---------- tsf_h ----------->||<--- tsf_l -->||<-RxTSFTime ->|
8104  *
8105  * The RxTSFTime are the lowest 16 bits and provided by the ucode. The
8106  * tsf_l is filled in by brcms_b_recv, which is done earlier in the
8107  * receive call sequence after rx interrupt. Only the higher 16 bits
8108  * are used. Finally, the tsf_h is read from the tsf register.
8109  */
8110 static u64 brcms_c_recover_tsf64(struct brcms_c_info *wlc,
8111                                  struct brcms_d11rxhdr *rxh)
8112 {
8113         u32 tsf_h, tsf_l;
8114         u16 rx_tsf_0_15, rx_tsf_16_31;
8115
8116         brcms_b_read_tsf(wlc->hw, &tsf_l, &tsf_h);
8117
8118         rx_tsf_16_31 = (u16)(tsf_l >> 16);
8119         rx_tsf_0_15 = rxh->rxhdr.RxTSFTime;
8120
8121         /*
8122          * a greater tsf time indicates the low 16 bits of
8123          * tsf_l wrapped, so decrement the high 16 bits.
8124          */
8125         if ((u16)tsf_l < rx_tsf_0_15) {
8126                 rx_tsf_16_31 -= 1;
8127                 if (rx_tsf_16_31 == 0xffff)
8128                         tsf_h -= 1;
8129         }
8130
8131         return ((u64)tsf_h << 32) | (((u32)rx_tsf_16_31 << 16) + rx_tsf_0_15);
8132 }
8133
8134 static void
8135 prep_mac80211_status(struct brcms_c_info *wlc, struct d11rxhdr *rxh,
8136                      struct sk_buff *p,
8137                      struct ieee80211_rx_status *rx_status)
8138 {
8139         struct brcms_d11rxhdr *wlc_rxh = (struct brcms_d11rxhdr *) rxh;
8140         int preamble;
8141         int channel;
8142         u32 rspec;
8143         unsigned char *plcp;
8144
8145         /* fill in TSF and flag its presence */
8146         rx_status->mactime = brcms_c_recover_tsf64(wlc, wlc_rxh);
8147         rx_status->flag |= RX_FLAG_MACTIME_MPDU;
8148
8149         channel = BRCMS_CHAN_CHANNEL(rxh->RxChan);
8150
8151         if (channel > 14) {
8152                 rx_status->band = IEEE80211_BAND_5GHZ;
8153                 rx_status->freq = ieee80211_ofdm_chan_to_freq(
8154                                         WF_CHAN_FACTOR_5_G/2, channel);
8155
8156         } else {
8157                 rx_status->band = IEEE80211_BAND_2GHZ;
8158                 rx_status->freq = ieee80211_dsss_chan_to_freq(channel);
8159         }
8160
8161         rx_status->signal = wlc_rxh->rssi;
8162
8163         /* noise */
8164         /* qual */
8165         rx_status->antenna =
8166                 (rxh->PhyRxStatus_0 & PRXS0_RXANT_UPSUBBAND) ? 1 : 0;
8167
8168         plcp = p->data;
8169
8170         rspec = brcms_c_compute_rspec(rxh, plcp);
8171         if (is_mcs_rate(rspec)) {
8172                 rx_status->rate_idx = rspec & RSPEC_RATE_MASK;
8173                 rx_status->flag |= RX_FLAG_HT;
8174                 if (rspec_is40mhz(rspec))
8175                         rx_status->flag |= RX_FLAG_40MHZ;
8176         } else {
8177                 switch (rspec2rate(rspec)) {
8178                 case BRCM_RATE_1M:
8179                         rx_status->rate_idx = 0;
8180                         break;
8181                 case BRCM_RATE_2M:
8182                         rx_status->rate_idx = 1;
8183                         break;
8184                 case BRCM_RATE_5M5:
8185                         rx_status->rate_idx = 2;
8186                         break;
8187                 case BRCM_RATE_11M:
8188                         rx_status->rate_idx = 3;
8189                         break;
8190                 case BRCM_RATE_6M:
8191                         rx_status->rate_idx = 4;
8192                         break;
8193                 case BRCM_RATE_9M:
8194                         rx_status->rate_idx = 5;
8195                         break;
8196                 case BRCM_RATE_12M:
8197                         rx_status->rate_idx = 6;
8198                         break;
8199                 case BRCM_RATE_18M:
8200                         rx_status->rate_idx = 7;
8201                         break;
8202                 case BRCM_RATE_24M:
8203                         rx_status->rate_idx = 8;
8204                         break;
8205                 case BRCM_RATE_36M:
8206                         rx_status->rate_idx = 9;
8207                         break;
8208                 case BRCM_RATE_48M:
8209                         rx_status->rate_idx = 10;
8210                         break;
8211                 case BRCM_RATE_54M:
8212                         rx_status->rate_idx = 11;
8213                         break;
8214                 default:
8215                         wiphy_err(wlc->wiphy, "%s: Unknown rate\n", __func__);
8216                 }
8217
8218                 /*
8219                  * For 5GHz, we should decrease the index as it is
8220                  * a subset of the 2.4G rates. See bitrates field
8221                  * of brcms_band_5GHz_nphy (in mac80211_if.c).
8222                  */
8223                 if (rx_status->band == IEEE80211_BAND_5GHZ)
8224                         rx_status->rate_idx -= BRCMS_LEGACY_5G_RATE_OFFSET;
8225
8226                 /* Determine short preamble and rate_idx */
8227                 preamble = 0;
8228                 if (is_cck_rate(rspec)) {
8229                         if (rxh->PhyRxStatus_0 & PRXS0_SHORTH)
8230                                 rx_status->flag |= RX_FLAG_SHORTPRE;
8231                 } else if (is_ofdm_rate(rspec)) {
8232                         rx_status->flag |= RX_FLAG_SHORTPRE;
8233                 } else {
8234                         wiphy_err(wlc->wiphy, "%s: Unknown modulation\n",
8235                                   __func__);
8236                 }
8237         }
8238
8239         if (plcp3_issgi(plcp[3]))
8240                 rx_status->flag |= RX_FLAG_SHORT_GI;
8241
8242         if (rxh->RxStatus1 & RXS_DECERR) {
8243                 rx_status->flag |= RX_FLAG_FAILED_PLCP_CRC;
8244                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_PLCP_CRC\n",
8245                           __func__);
8246         }
8247         if (rxh->RxStatus1 & RXS_FCSERR) {
8248                 rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
8249                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_FCS_CRC\n",
8250                           __func__);
8251         }
8252 }
8253
8254 static void
8255 brcms_c_recvctl(struct brcms_c_info *wlc, struct d11rxhdr *rxh,
8256                 struct sk_buff *p)
8257 {
8258         int len_mpdu;
8259         struct ieee80211_rx_status rx_status;
8260
8261         memset(&rx_status, 0, sizeof(rx_status));
8262         prep_mac80211_status(wlc, rxh, p, &rx_status);
8263
8264         /* mac header+body length, exclude CRC and plcp header */
8265         len_mpdu = p->len - D11_PHY_HDR_LEN - FCS_LEN;
8266         skb_pull(p, D11_PHY_HDR_LEN);
8267         __skb_trim(p, len_mpdu);
8268
8269         memcpy(IEEE80211_SKB_RXCB(p), &rx_status, sizeof(rx_status));
8270         ieee80211_rx_irqsafe(wlc->pub->ieee_hw, p);
8271         return;
8272 }
8273
8274 /* Process received frames */
8275 /*
8276  * Return true if more frames need to be processed. false otherwise.
8277  * Param 'bound' indicates max. # frames to process before break out.
8278  */
8279 void brcms_c_recv(struct brcms_c_info *wlc, struct sk_buff *p)
8280 {
8281         struct d11rxhdr *rxh;
8282         struct ieee80211_hdr *h;
8283         uint len;
8284         bool is_amsdu;
8285
8286         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
8287
8288         /* frame starts with rxhdr */
8289         rxh = (struct d11rxhdr *) (p->data);
8290
8291         /* strip off rxhdr */
8292         skb_pull(p, BRCMS_HWRXOFF);
8293
8294         /* fixup rx header endianness */
8295         rxh->RxFrameSize = le16_to_cpu(rxh->RxFrameSize);
8296         rxh->PhyRxStatus_0 = le16_to_cpu(rxh->PhyRxStatus_0);
8297         rxh->PhyRxStatus_1 = le16_to_cpu(rxh->PhyRxStatus_1);
8298         rxh->PhyRxStatus_2 = le16_to_cpu(rxh->PhyRxStatus_2);
8299         rxh->PhyRxStatus_3 = le16_to_cpu(rxh->PhyRxStatus_3);
8300         rxh->PhyRxStatus_4 = le16_to_cpu(rxh->PhyRxStatus_4);
8301         rxh->PhyRxStatus_5 = le16_to_cpu(rxh->PhyRxStatus_5);
8302         rxh->RxStatus1 = le16_to_cpu(rxh->RxStatus1);
8303         rxh->RxStatus2 = le16_to_cpu(rxh->RxStatus2);
8304         rxh->RxTSFTime = le16_to_cpu(rxh->RxTSFTime);
8305         rxh->RxChan = le16_to_cpu(rxh->RxChan);
8306
8307         /* MAC inserts 2 pad bytes for a4 headers or QoS or A-MSDU subframes */
8308         if (rxh->RxStatus1 & RXS_PBPRES) {
8309                 if (p->len < 2) {
8310                         wiphy_err(wlc->wiphy, "wl%d: recv: rcvd runt of "
8311                                   "len %d\n", wlc->pub->unit, p->len);
8312                         goto toss;
8313                 }
8314                 skb_pull(p, 2);
8315         }
8316
8317         h = (struct ieee80211_hdr *)(p->data + D11_PHY_HDR_LEN);
8318         len = p->len;
8319
8320         if (rxh->RxStatus1 & RXS_FCSERR) {
8321                 if (wlc->pub->mac80211_state & MAC80211_PROMISC_BCNS) {
8322                         wiphy_err(wlc->wiphy, "FCSERR while scanning******* -"
8323                                   " tossing\n");
8324                         goto toss;
8325                 } else {
8326                         wiphy_err(wlc->wiphy, "RCSERR!!!\n");
8327                         goto toss;
8328                 }
8329         }
8330
8331         /* check received pkt has at least frame control field */
8332         if (len < D11_PHY_HDR_LEN + sizeof(h->frame_control))
8333                 goto toss;
8334
8335         is_amsdu = rxh->RxStatus2 & RXS_AMSDU_MASK;
8336
8337         /* explicitly test bad src address to avoid sending bad deauth */
8338         if (!is_amsdu) {
8339                 /* CTS and ACK CTL frames are w/o a2 */
8340
8341                 if (ieee80211_is_data(h->frame_control) ||
8342                     ieee80211_is_mgmt(h->frame_control)) {
8343                         if ((is_zero_ether_addr(h->addr2) ||
8344                              is_multicast_ether_addr(h->addr2))) {
8345                                 wiphy_err(wlc->wiphy, "wl%d: %s: dropping a "
8346                                           "frame with invalid src mac address,"
8347                                           " a2: %pM\n",
8348                                          wlc->pub->unit, __func__, h->addr2);
8349                                 goto toss;
8350                         }
8351                 }
8352         }
8353
8354         /* due to sheer numbers, toss out probe reqs for now */
8355         if (ieee80211_is_probe_req(h->frame_control))
8356                 goto toss;
8357
8358         if (is_amsdu)
8359                 goto toss;
8360
8361         brcms_c_recvctl(wlc, rxh, p);
8362         return;
8363
8364  toss:
8365         brcmu_pkt_buf_free_skb(p);
8366 }
8367
8368 /* calculate frame duration for Mixed-mode L-SIG spoofing, return
8369  * number of bytes goes in the length field
8370  *
8371  * Formula given by HT PHY Spec v 1.13
8372  *   len = 3(nsyms + nstream + 3) - 3
8373  */
8374 u16
8375 brcms_c_calc_lsig_len(struct brcms_c_info *wlc, u32 ratespec,
8376                       uint mac_len)
8377 {
8378         uint nsyms, len = 0, kNdps;
8379
8380         BCMMSG(wlc->wiphy, "wl%d: rate %d, len%d\n",
8381                  wlc->pub->unit, rspec2rate(ratespec), mac_len);
8382
8383         if (is_mcs_rate(ratespec)) {
8384                 uint mcs = ratespec & RSPEC_RATE_MASK;
8385                 int tot_streams = (mcs_2_txstreams(mcs) + 1) +
8386                                   rspec_stc(ratespec);
8387
8388                 /*
8389                  * the payload duration calculation matches that
8390                  * of regular ofdm
8391                  */
8392                 /* 1000Ndbps = kbps * 4 */
8393                 kNdps = mcs_2_rate(mcs, rspec_is40mhz(ratespec),
8394                                    rspec_issgi(ratespec)) * 4;
8395
8396                 if (rspec_stc(ratespec) == 0)
8397                         nsyms =
8398                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
8399                                   APHY_TAIL_NBITS) * 1000, kNdps);
8400                 else
8401                         /* STBC needs to have even number of symbols */
8402                         nsyms =
8403                             2 *
8404                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
8405                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
8406
8407                 /* (+3) account for HT-SIG(2) and HT-STF(1) */
8408                 nsyms += (tot_streams + 3);
8409                 /*
8410                  * 3 bytes/symbol @ legacy 6Mbps rate
8411                  * (-3) excluding service bits and tail bits
8412                  */
8413                 len = (3 * nsyms) - 3;
8414         }
8415
8416         return (u16) len;
8417 }
8418
8419 /*
8420  * calculate frame duration of a given rate and length, return
8421  * time in usec unit
8422  */
8423 uint
8424 brcms_c_calc_frame_time(struct brcms_c_info *wlc, u32 ratespec,
8425                         u8 preamble_type, uint mac_len)
8426 {
8427         uint nsyms, dur = 0, Ndps, kNdps;
8428         uint rate = rspec2rate(ratespec);
8429
8430         if (rate == 0) {
8431                 wiphy_err(wlc->wiphy, "wl%d: WAR: using rate of 1 mbps\n",
8432                           wlc->pub->unit);
8433                 rate = BRCM_RATE_1M;
8434         }
8435
8436         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d, len%d\n",
8437                  wlc->pub->unit, ratespec, preamble_type, mac_len);
8438
8439         if (is_mcs_rate(ratespec)) {
8440                 uint mcs = ratespec & RSPEC_RATE_MASK;
8441                 int tot_streams = mcs_2_txstreams(mcs) + rspec_stc(ratespec);
8442
8443                 dur = PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
8444                 if (preamble_type == BRCMS_MM_PREAMBLE)
8445                         dur += PREN_MM_EXT;
8446                 /* 1000Ndbps = kbps * 4 */
8447                 kNdps = mcs_2_rate(mcs, rspec_is40mhz(ratespec),
8448                                    rspec_issgi(ratespec)) * 4;
8449
8450                 if (rspec_stc(ratespec) == 0)
8451                         nsyms =
8452                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
8453                                   APHY_TAIL_NBITS) * 1000, kNdps);
8454                 else
8455                         /* STBC needs to have even number of symbols */
8456                         nsyms =
8457                             2 *
8458                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
8459                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
8460
8461                 dur += APHY_SYMBOL_TIME * nsyms;
8462                 if (wlc->band->bandtype == BRCM_BAND_2G)
8463                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
8464         } else if (is_ofdm_rate(rate)) {
8465                 dur = APHY_PREAMBLE_TIME;
8466                 dur += APHY_SIGNAL_TIME;
8467                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
8468                 Ndps = rate * 2;
8469                 /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
8470                 nsyms =
8471                     CEIL((APHY_SERVICE_NBITS + 8 * mac_len + APHY_TAIL_NBITS),
8472                          Ndps);
8473                 dur += APHY_SYMBOL_TIME * nsyms;
8474                 if (wlc->band->bandtype == BRCM_BAND_2G)
8475                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
8476         } else {
8477                 /*
8478                  * calc # bits * 2 so factor of 2 in rate (1/2 mbps)
8479                  * will divide out
8480                  */
8481                 mac_len = mac_len * 8 * 2;
8482                 /* calc ceiling of bits/rate = microseconds of air time */
8483                 dur = (mac_len + rate - 1) / rate;
8484                 if (preamble_type & BRCMS_SHORT_PREAMBLE)
8485                         dur += BPHY_PLCP_SHORT_TIME;
8486                 else
8487                         dur += BPHY_PLCP_TIME;
8488         }
8489         return dur;
8490 }
8491
8492 /* derive wlc->band->basic_rate[] table from 'rateset' */
8493 void brcms_c_rate_lookup_init(struct brcms_c_info *wlc,
8494                               struct brcms_c_rateset *rateset)
8495 {
8496         u8 rate;
8497         u8 mandatory;
8498         u8 cck_basic = 0;
8499         u8 ofdm_basic = 0;
8500         u8 *br = wlc->band->basic_rate;
8501         uint i;
8502
8503         /* incoming rates are in 500kbps units as in 802.11 Supported Rates */
8504         memset(br, 0, BRCM_MAXRATE + 1);
8505
8506         /* For each basic rate in the rates list, make an entry in the
8507          * best basic lookup.
8508          */
8509         for (i = 0; i < rateset->count; i++) {
8510                 /* only make an entry for a basic rate */
8511                 if (!(rateset->rates[i] & BRCMS_RATE_FLAG))
8512                         continue;
8513
8514                 /* mask off basic bit */
8515                 rate = (rateset->rates[i] & BRCMS_RATE_MASK);
8516
8517                 if (rate > BRCM_MAXRATE) {
8518                         wiphy_err(wlc->wiphy, "brcms_c_rate_lookup_init: "
8519                                   "invalid rate 0x%X in rate set\n",
8520                                   rateset->rates[i]);
8521                         continue;
8522                 }
8523
8524                 br[rate] = rate;
8525         }
8526
8527         /* The rate lookup table now has non-zero entries for each
8528          * basic rate, equal to the basic rate: br[basicN] = basicN
8529          *
8530          * To look up the best basic rate corresponding to any
8531          * particular rate, code can use the basic_rate table
8532          * like this
8533          *
8534          * basic_rate = wlc->band->basic_rate[tx_rate]
8535          *
8536          * Make sure there is a best basic rate entry for
8537          * every rate by walking up the table from low rates
8538          * to high, filling in holes in the lookup table
8539          */
8540
8541         for (i = 0; i < wlc->band->hw_rateset.count; i++) {
8542                 rate = wlc->band->hw_rateset.rates[i];
8543
8544                 if (br[rate] != 0) {
8545                         /* This rate is a basic rate.
8546                          * Keep track of the best basic rate so far by
8547                          * modulation type.
8548                          */
8549                         if (is_ofdm_rate(rate))
8550                                 ofdm_basic = rate;
8551                         else
8552                                 cck_basic = rate;
8553
8554                         continue;
8555                 }
8556
8557                 /* This rate is not a basic rate so figure out the
8558                  * best basic rate less than this rate and fill in
8559                  * the hole in the table
8560                  */
8561
8562                 br[rate] = is_ofdm_rate(rate) ? ofdm_basic : cck_basic;
8563
8564                 if (br[rate] != 0)
8565                         continue;
8566
8567                 if (is_ofdm_rate(rate)) {
8568                         /*
8569                          * In 11g and 11a, the OFDM mandatory rates
8570                          * are 6, 12, and 24 Mbps
8571                          */
8572                         if (rate >= BRCM_RATE_24M)
8573                                 mandatory = BRCM_RATE_24M;
8574                         else if (rate >= BRCM_RATE_12M)
8575                                 mandatory = BRCM_RATE_12M;
8576                         else
8577                                 mandatory = BRCM_RATE_6M;
8578                 } else {
8579                         /* In 11b, all CCK rates are mandatory 1 - 11 Mbps */
8580                         mandatory = rate;
8581                 }
8582
8583                 br[rate] = mandatory;
8584         }
8585 }
8586
8587 static void brcms_c_write_rate_shm(struct brcms_c_info *wlc, u8 rate,
8588                                    u8 basic_rate)
8589 {
8590         u8 phy_rate, index;
8591         u8 basic_phy_rate, basic_index;
8592         u16 dir_table, basic_table;
8593         u16 basic_ptr;
8594
8595         /* Shared memory address for the table we are reading */
8596         dir_table = is_ofdm_rate(basic_rate) ? M_RT_DIRMAP_A : M_RT_DIRMAP_B;
8597
8598         /* Shared memory address for the table we are writing */
8599         basic_table = is_ofdm_rate(rate) ? M_RT_BBRSMAP_A : M_RT_BBRSMAP_B;
8600
8601         /*
8602          * for a given rate, the LS-nibble of the PLCP SIGNAL field is
8603          * the index into the rate table.
8604          */
8605         phy_rate = rate_info[rate] & BRCMS_RATE_MASK;
8606         basic_phy_rate = rate_info[basic_rate] & BRCMS_RATE_MASK;
8607         index = phy_rate & 0xf;
8608         basic_index = basic_phy_rate & 0xf;
8609
8610         /* Find the SHM pointer to the ACK rate entry by looking in the
8611          * Direct-map Table
8612          */
8613         basic_ptr = brcms_c_read_shm(wlc, (dir_table + basic_index * 2));
8614
8615         /* Update the SHM BSS-basic-rate-set mapping table with the pointer
8616          * to the correct basic rate for the given incoming rate
8617          */
8618         brcms_c_write_shm(wlc, (basic_table + index * 2), basic_ptr);
8619 }
8620
8621 static const struct brcms_c_rateset *
8622 brcms_c_rateset_get_hwrs(struct brcms_c_info *wlc)
8623 {
8624         const struct brcms_c_rateset *rs_dflt;
8625
8626         if (BRCMS_PHY_11N_CAP(wlc->band)) {
8627                 if (wlc->band->bandtype == BRCM_BAND_5G)
8628                         rs_dflt = &ofdm_mimo_rates;
8629                 else
8630                         rs_dflt = &cck_ofdm_mimo_rates;
8631         } else if (wlc->band->gmode)
8632                 rs_dflt = &cck_ofdm_rates;
8633         else
8634                 rs_dflt = &cck_rates;
8635
8636         return rs_dflt;
8637 }
8638
8639 void brcms_c_set_ratetable(struct brcms_c_info *wlc)
8640 {
8641         const struct brcms_c_rateset *rs_dflt;
8642         struct brcms_c_rateset rs;
8643         u8 rate, basic_rate;
8644         uint i;
8645
8646         rs_dflt = brcms_c_rateset_get_hwrs(wlc);
8647
8648         brcms_c_rateset_copy(rs_dflt, &rs);
8649         brcms_c_rateset_mcs_upd(&rs, wlc->stf->txstreams);
8650
8651         /* walk the phy rate table and update SHM basic rate lookup table */
8652         for (i = 0; i < rs.count; i++) {
8653                 rate = rs.rates[i] & BRCMS_RATE_MASK;
8654
8655                 /* for a given rate brcms_basic_rate returns the rate at
8656                  * which a response ACK/CTS should be sent.
8657                  */
8658                 basic_rate = brcms_basic_rate(wlc, rate);
8659                 if (basic_rate == 0)
8660                         /* This should only happen if we are using a
8661                          * restricted rateset.
8662                          */
8663                         basic_rate = rs.rates[0] & BRCMS_RATE_MASK;
8664
8665                 brcms_c_write_rate_shm(wlc, rate, basic_rate);
8666         }
8667 }
8668
8669 /*
8670  * Return true if the specified rate is supported by the specified band.
8671  * BRCM_BAND_AUTO indicates the current band.
8672  */
8673 bool brcms_c_valid_rate(struct brcms_c_info *wlc, u32 rspec, int band,
8674                     bool verbose)
8675 {
8676         struct brcms_c_rateset *hw_rateset;
8677         uint i;
8678
8679         if ((band == BRCM_BAND_AUTO) || (band == wlc->band->bandtype))
8680                 hw_rateset = &wlc->band->hw_rateset;
8681         else if (wlc->pub->_nbands > 1)
8682                 hw_rateset = &wlc->bandstate[OTHERBANDUNIT(wlc)]->hw_rateset;
8683         else
8684                 /* other band specified and we are a single band device */
8685                 return false;
8686
8687         /* check if this is a mimo rate */
8688         if (is_mcs_rate(rspec)) {
8689                 if ((rspec & RSPEC_RATE_MASK) >= MCS_TABLE_SIZE)
8690                         goto error;
8691
8692                 return isset(hw_rateset->mcs, (rspec & RSPEC_RATE_MASK));
8693         }
8694
8695         for (i = 0; i < hw_rateset->count; i++)
8696                 if (hw_rateset->rates[i] == rspec2rate(rspec))
8697                         return true;
8698  error:
8699         if (verbose)
8700                 wiphy_err(wlc->wiphy, "wl%d: valid_rate: rate spec 0x%x "
8701                           "not in hw_rateset\n", wlc->pub->unit, rspec);
8702
8703         return false;
8704 }
8705
8706 void brcms_c_mod_prb_rsp_rate_table(struct brcms_c_info *wlc, uint frame_len)
8707 {
8708         const struct brcms_c_rateset *rs_dflt;
8709         struct brcms_c_rateset rs;
8710         u8 rate;
8711         u16 entry_ptr;
8712         u8 plcp[D11_PHY_HDR_LEN];
8713         u16 dur, sifs;
8714         uint i;
8715
8716         sifs = get_sifs(wlc->band);
8717
8718         rs_dflt = brcms_c_rateset_get_hwrs(wlc);
8719
8720         brcms_c_rateset_copy(rs_dflt, &rs);
8721         brcms_c_rateset_mcs_upd(&rs, wlc->stf->txstreams);
8722
8723         /*
8724          * walk the phy rate table and update MAC core SHM
8725          * basic rate table entries
8726          */
8727         for (i = 0; i < rs.count; i++) {
8728                 rate = rs.rates[i] & BRCMS_RATE_MASK;
8729
8730                 entry_ptr = brcms_c_rate_shm_offset(wlc, rate);
8731
8732                 /* Calculate the Probe Response PLCP for the given rate */
8733                 brcms_c_compute_plcp(wlc, rate, frame_len, plcp);
8734
8735                 /*
8736                  * Calculate the duration of the Probe Response
8737                  * frame plus SIFS for the MAC
8738                  */
8739                 dur = (u16) brcms_c_calc_frame_time(wlc, rate,
8740                                                 BRCMS_LONG_PREAMBLE, frame_len);
8741                 dur += sifs;
8742
8743                 /* Update the SHM Rate Table entry Probe Response values */
8744                 brcms_c_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS,
8745                               (u16) (plcp[0] + (plcp[1] << 8)));
8746                 brcms_c_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS + 2,
8747                               (u16) (plcp[2] + (plcp[3] << 8)));
8748                 brcms_c_write_shm(wlc, entry_ptr + M_RT_PRS_DUR_POS, dur);
8749         }
8750 }
8751
8752 /*      Max buffering needed for beacon template/prb resp template is 142 bytes.
8753  *
8754  *      PLCP header is 6 bytes.
8755  *      802.11 A3 header is 24 bytes.
8756  *      Max beacon frame body template length is 112 bytes.
8757  *      Max probe resp frame body template length is 110 bytes.
8758  *
8759  *      *len on input contains the max length of the packet available.
8760  *
8761  *      The *len value is set to the number of bytes in buf used, and starts
8762  *      with the PLCP and included up to, but not including, the 4 byte FCS.
8763  */
8764 static void
8765 brcms_c_bcn_prb_template(struct brcms_c_info *wlc, u16 type,
8766                          u32 bcn_rspec,
8767                          struct brcms_bss_cfg *cfg, u16 *buf, int *len)
8768 {
8769         static const u8 ether_bcast[ETH_ALEN] = {255, 255, 255, 255, 255, 255};
8770         struct cck_phy_hdr *plcp;
8771         struct ieee80211_mgmt *h;
8772         int hdr_len, body_len;
8773
8774         hdr_len = D11_PHY_HDR_LEN + DOT11_MAC_HDR_LEN;
8775
8776         /* calc buffer size provided for frame body */
8777         body_len = *len - hdr_len;
8778         /* return actual size */
8779         *len = hdr_len + body_len;
8780
8781         /* format PHY and MAC headers */
8782         memset((char *)buf, 0, hdr_len);
8783
8784         plcp = (struct cck_phy_hdr *) buf;
8785
8786         /*
8787          * PLCP for Probe Response frames are filled in from
8788          * core's rate table
8789          */
8790         if (type == IEEE80211_STYPE_BEACON)
8791                 /* fill in PLCP */
8792                 brcms_c_compute_plcp(wlc, bcn_rspec,
8793                                  (DOT11_MAC_HDR_LEN + body_len + FCS_LEN),
8794                                  (u8 *) plcp);
8795
8796         /* "Regular" and 16 MBSS but not for 4 MBSS */
8797         /* Update the phytxctl for the beacon based on the rspec */
8798         brcms_c_beacon_phytxctl_txant_upd(wlc, bcn_rspec);
8799
8800         h = (struct ieee80211_mgmt *)&plcp[1];
8801
8802         /* fill in 802.11 header */
8803         h->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | type);
8804
8805         /* DUR is 0 for multicast bcn, or filled in by MAC for prb resp */
8806         /* A1 filled in by MAC for prb resp, broadcast for bcn */
8807         if (type == IEEE80211_STYPE_BEACON)
8808                 memcpy(&h->da, &ether_bcast, ETH_ALEN);
8809         memcpy(&h->sa, &cfg->cur_etheraddr, ETH_ALEN);
8810         memcpy(&h->bssid, &cfg->BSSID, ETH_ALEN);
8811
8812         /* SEQ filled in by MAC */
8813
8814         return;
8815 }
8816
8817 int brcms_c_get_header_len(void)
8818 {
8819         return TXOFF;
8820 }
8821
8822 /* mac is assumed to be suspended at this point */
8823 static void
8824 brcms_b_write_hw_bcntemplates(struct brcms_hardware *wlc_hw, u16 bcn[],
8825                               int len, bool both)
8826 {
8827         struct d11regs *regs = wlc_hw->regs;
8828
8829         if (both) {
8830                 brcms_c_write_hw_bcntemplate0(wlc_hw, bcn, len);
8831                 brcms_c_write_hw_bcntemplate1(wlc_hw, bcn, len);
8832         } else {
8833                 /* bcn 0 */
8834                 if (!(R_REG(&regs->maccommand) & MCMD_BCN0VLD))
8835                         brcms_c_write_hw_bcntemplate0(wlc_hw, bcn, len);
8836                 /* bcn 1 */
8837                 else if (!
8838                          (R_REG(&regs->maccommand) & MCMD_BCN1VLD))
8839                         brcms_c_write_hw_bcntemplate1(wlc_hw, bcn, len);
8840         }
8841 }
8842
8843 static void brcms_c_write_hw_bcntemplates(struct brcms_c_info *wlc, u16 bcn[],
8844                                           int len, bool both)
8845 {
8846         brcms_b_write_hw_bcntemplates(wlc->hw, bcn, len, both);
8847 }
8848
8849 /*
8850  * Update a beacon for a particular BSS
8851  * For MBSS, this updates the software template and sets "latest" to
8852  * the index of the template updated. Otherwise, it updates the hardware
8853  * template.
8854  */
8855 void brcms_c_bss_update_beacon(struct brcms_c_info *wlc,
8856                                struct brcms_bss_cfg *cfg)
8857 {
8858         int len = BCN_TMPL_LEN;
8859
8860         /* Clear the soft intmask */
8861         wlc->defmacintmask &= ~MI_BCNTPL;
8862
8863         if (!cfg->up)
8864                 /* Only allow updates on an UP bss */
8865                 return;
8866
8867         /* Optimize:  Some of if/else could be combined */
8868         if ((cfg->flags & BRCMS_BSSCFG_HW_BCN) != 0) {
8869                 /* Hardware beaconing for this config */
8870                 u16 bcn[BCN_TMPL_LEN / 2];
8871                 u32 both_valid = MCMD_BCN0VLD | MCMD_BCN1VLD;
8872                 struct d11regs *regs = wlc->regs;
8873
8874                 /* Check if both templates are in use, if so sched. an interrupt
8875                  *      that will call back into this routine
8876                  */
8877                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid)
8878                         /* clear any previous status */
8879                         W_REG(&regs->macintstatus, MI_BCNTPL);
8880
8881                 /* Check that after scheduling the interrupt both of the
8882                  *      templates are still busy. if not clear the int. & remask
8883                  */
8884                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
8885                         wlc->defmacintmask |= MI_BCNTPL;
8886                         return;
8887                 }
8888
8889                 wlc->bcn_rspec =
8890                     brcms_c_lowest_basic_rspec(wlc, &cfg->current_bss->rateset);
8891                 /* update the template and ucode shm */
8892                 brcms_c_bcn_prb_template(wlc, IEEE80211_STYPE_BEACON,
8893                                      wlc->bcn_rspec, cfg, bcn, &len);
8894                 brcms_c_write_hw_bcntemplates(wlc, bcn, len, false);
8895         }
8896 }
8897
8898 /*
8899  * Update all beacons for the system.
8900  */
8901 void brcms_c_update_beacon(struct brcms_c_info *wlc)
8902 {
8903         struct brcms_bss_cfg *bsscfg = wlc->bsscfg;
8904
8905         if (bsscfg->up && !bsscfg->BSS)
8906                 brcms_c_bss_update_beacon(wlc, bsscfg);
8907 }
8908
8909 /* Write ssid into shared memory */
8910 void brcms_c_shm_ssid_upd(struct brcms_c_info *wlc, struct brcms_bss_cfg *cfg)
8911 {
8912         u8 *ssidptr = cfg->SSID;
8913         u16 base = M_SSID;
8914         u8 ssidbuf[IEEE80211_MAX_SSID_LEN];
8915
8916         /* padding the ssid with zero and copy it into shm */
8917         memset(ssidbuf, 0, IEEE80211_MAX_SSID_LEN);
8918         memcpy(ssidbuf, ssidptr, cfg->SSID_len);
8919
8920         brcms_c_copyto_shm(wlc, base, ssidbuf, IEEE80211_MAX_SSID_LEN);
8921         brcms_c_write_shm(wlc, M_SSIDLEN, (u16) cfg->SSID_len);
8922 }
8923
8924 void brcms_c_update_probe_resp(struct brcms_c_info *wlc, bool suspend)
8925 {
8926         struct brcms_bss_cfg *bsscfg = wlc->bsscfg;
8927
8928         /* update AP or IBSS probe responses */
8929         if (bsscfg->up && !bsscfg->BSS)
8930                 brcms_c_bss_update_probe_resp(wlc, bsscfg, suspend);
8931 }
8932
8933 void
8934 brcms_c_bss_update_probe_resp(struct brcms_c_info *wlc,
8935                               struct brcms_bss_cfg *cfg,
8936                               bool suspend)
8937 {
8938         u16 prb_resp[BCN_TMPL_LEN / 2];
8939         int len = BCN_TMPL_LEN;
8940
8941         /*
8942          * write the probe response to hardware, or save in
8943          * the config structure
8944          */
8945
8946         /* create the probe response template */
8947         brcms_c_bcn_prb_template(wlc, IEEE80211_STYPE_PROBE_RESP, 0,
8948                                  cfg, prb_resp, &len);
8949
8950         if (suspend)
8951                 brcms_c_suspend_mac_and_wait(wlc);
8952
8953         /* write the probe response into the template region */
8954         brcms_b_write_template_ram(wlc->hw, T_PRS_TPL_BASE,
8955                                     (len + 3) & ~3, prb_resp);
8956
8957         /* write the length of the probe response frame (+PLCP/-FCS) */
8958         brcms_c_write_shm(wlc, M_PRB_RESP_FRM_LEN, (u16) len);
8959
8960         /* write the SSID and SSID length */
8961         brcms_c_shm_ssid_upd(wlc, cfg);
8962
8963         /*
8964          * Write PLCP headers and durations for probe response frames
8965          * at all rates. Use the actual frame length covered by the
8966          * PLCP header for the call to brcms_c_mod_prb_rsp_rate_table()
8967          * by subtracting the PLCP len and adding the FCS.
8968          */
8969         len += (-D11_PHY_HDR_LEN + FCS_LEN);
8970         brcms_c_mod_prb_rsp_rate_table(wlc, (u16) len);
8971
8972         if (suspend)
8973                 brcms_c_enable_mac(wlc);
8974 }
8975
8976 /* prepares pdu for transmission. returns BCM error codes */
8977 int brcms_c_prep_pdu(struct brcms_c_info *wlc, struct sk_buff *pdu, uint *fifop)
8978 {
8979         uint fifo;
8980         struct d11txh *txh;
8981         struct ieee80211_hdr *h;
8982         struct scb *scb;
8983
8984         txh = (struct d11txh *) (pdu->data);
8985         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
8986
8987         /* get the pkt queue info. This was put at brcms_c_sendctl or
8988          * brcms_c_send for PDU */
8989         fifo = le16_to_cpu(txh->TxFrameID) & TXFID_QUEUE_MASK;
8990
8991         scb = NULL;
8992
8993         *fifop = fifo;
8994
8995         /* return if insufficient dma resources */
8996         if (*wlc->core->txavail[fifo] < MAX_DMA_SEGS) {
8997                 /* Mark precedences related to this FIFO, unsendable */
8998                 /* A fifo is full. Clear precedences related to that FIFO */
8999                 wlc->tx_prec_map &= ~(wlc->fifo2prec_map[fifo]);
9000                 return -EBUSY;
9001         }
9002         return 0;
9003 }
9004
9005 /* init tx reported rate mechanism */
9006 void brcms_c_reprate_init(struct brcms_c_info *wlc)
9007 {
9008         brcms_c_bsscfg_reprate_init(wlc->bsscfg);
9009 }
9010
9011 /* per bsscfg init tx reported rate mechanism */
9012 void brcms_c_bsscfg_reprate_init(struct brcms_bss_cfg *bsscfg)
9013 {
9014         bsscfg->txrspecidx = 0;
9015         memset((char *)bsscfg->txrspec, 0, sizeof(bsscfg->txrspec));
9016 }
9017
9018 void brcms_default_rateset(struct brcms_c_info *wlc, struct brcms_c_rateset *rs)
9019 {
9020         brcms_c_rateset_default(rs, NULL, wlc->band->phytype,
9021                 wlc->band->bandtype, false, BRCMS_RATE_MASK_FULL,
9022                 (bool) (wlc->pub->_n_enab & SUPPORT_11N),
9023                 brcms_chspec_bw(wlc->default_bss->chanspec),
9024                 wlc->stf->txstreams);
9025 }
9026
9027 /* Read a single u16 from shared memory.
9028  * SHM 'offset' needs to be an even address
9029  */
9030 u16 brcms_c_read_shm(struct brcms_c_info *wlc, uint offset)
9031 {
9032         return brcms_b_read_shm(wlc->hw, offset);
9033 }
9034
9035 /* Write a single u16 to shared memory.
9036  * SHM 'offset' needs to be an even address
9037  */
9038 void brcms_c_write_shm(struct brcms_c_info *wlc, uint offset, u16 v)
9039 {
9040         brcms_b_write_shm(wlc->hw, offset, v);
9041 }
9042
9043 /* Copy a buffer to shared memory.
9044  * SHM 'offset' needs to be an even address and
9045  * Buffer length 'len' must be an even number of bytes
9046  */
9047 void brcms_c_copyto_shm(struct brcms_c_info *wlc, uint offset, const void *buf,
9048                         int len)
9049 {
9050         /* offset and len need to be even */
9051         if (len <= 0 || (offset & 1) || (len & 1))
9052                 return;
9053
9054         brcms_b_copyto_objmem(wlc->hw, offset, buf, len, OBJADDR_SHM_SEL);
9055
9056 }
9057
9058 /* wrapper BMAC functions to for HIGH driver access */
9059 void brcms_c_mctrl(struct brcms_c_info *wlc, u32 mask, u32 val)
9060 {
9061         brcms_b_mctrl(wlc->hw, mask, val);
9062 }
9063
9064 void brcms_c_mhf(struct brcms_c_info *wlc, u8 idx, u16 mask, u16 val, int bands)
9065 {
9066         brcms_b_mhf(wlc->hw, idx, mask, val, bands);
9067 }
9068
9069 static int brcms_b_xmtfifo_sz_get(struct brcms_hardware *wlc_hw, uint fifo,
9070                            uint *blocks)
9071 {
9072         if (fifo >= NFIFO)
9073                 return -EINVAL;
9074
9075         *blocks = wlc_hw->xmtfifo_sz[fifo];
9076
9077         return 0;
9078 }
9079
9080 int brcms_c_xmtfifo_sz_get(struct brcms_c_info *wlc, uint fifo, uint *blocks)
9081 {
9082         return brcms_b_xmtfifo_sz_get(wlc->hw, fifo, blocks);
9083 }
9084
9085 void brcms_c_write_template_ram(struct brcms_c_info *wlc, int offset, int len,
9086                             void *buf)
9087 {
9088         brcms_b_write_template_ram(wlc->hw, offset, len, buf);
9089 }
9090
9091 void
9092 brcms_c_set_addrmatch(struct brcms_c_info *wlc, int match_reg_offset,
9093                   const u8 *addr)
9094 {
9095         brcms_b_set_addrmatch(wlc->hw, match_reg_offset, addr);
9096         if (match_reg_offset == RCM_BSSID_OFFSET)
9097                 memcpy(wlc->bsscfg->BSSID, addr, ETH_ALEN);
9098 }
9099
9100 void brcms_c_pllreq(struct brcms_c_info *wlc, bool set, u32 req_bit)
9101 {
9102         brcms_b_pllreq(wlc->hw, set, req_bit);
9103 }
9104
9105 void brcms_c_reset_bmac_done(struct brcms_c_info *wlc)
9106 {
9107 }
9108
9109 /* check for the particular priority flow control bit being set */
9110 bool
9111 brcms_c_txflowcontrol_prio_isset(struct brcms_c_info *wlc,
9112                                  struct brcms_txq_info *q,
9113                                  int prio)
9114 {
9115         uint prio_mask;
9116
9117         if (prio == ALLPRIO)
9118                 prio_mask = TXQ_STOP_FOR_PRIOFC_MASK;
9119         else
9120                 prio_mask = NBITVAL(prio);
9121
9122         return (q->stopped & prio_mask) == prio_mask;
9123 }
9124
9125 /* propagate the flow control to all interfaces using the given tx queue */
9126 void brcms_c_txflowcontrol(struct brcms_c_info *wlc,
9127                            struct brcms_txq_info *qi,
9128                            bool on, int prio)
9129 {
9130         uint prio_bits;
9131         uint cur_bits;
9132
9133         BCMMSG(wlc->wiphy, "flow control kicks in\n");
9134
9135         if (prio == ALLPRIO)
9136                 prio_bits = TXQ_STOP_FOR_PRIOFC_MASK;
9137         else
9138                 prio_bits = NBITVAL(prio);
9139
9140         cur_bits = qi->stopped & prio_bits;
9141
9142         /* Check for the case of no change and return early
9143          * Otherwise update the bit and continue
9144          */
9145         if (on) {
9146                 if (cur_bits == prio_bits)
9147                         return;
9148
9149                 mboolset(qi->stopped, prio_bits);
9150         } else {
9151                 if (cur_bits == 0)
9152                         return;
9153
9154                 mboolclr(qi->stopped, prio_bits);
9155         }
9156
9157         /* If there is a flow control override we will not change the external
9158          * flow control state.
9159          */
9160         if (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK)
9161                 return;
9162
9163         brcms_c_txflowcontrol_signal(wlc, qi, on, prio);
9164 }
9165
9166 void
9167 brcms_c_txflowcontrol_override(struct brcms_c_info *wlc,
9168                                struct brcms_txq_info *qi,
9169                                bool on, uint override)
9170 {
9171         uint prev_override;
9172
9173         prev_override = (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK);
9174
9175         /* Update the flow control bits and do an early return if there is
9176          * no change in the external flow control state.
9177          */
9178         if (on) {
9179                 mboolset(qi->stopped, override);
9180                 /* if there was a previous override bit on, then setting this
9181                  * makes no difference.
9182                  */
9183                 if (prev_override)
9184                         return;
9185
9186                 brcms_c_txflowcontrol_signal(wlc, qi, ON, ALLPRIO);
9187         } else {
9188                 mboolclr(qi->stopped, override);
9189                 /* clearing an override bit will only make a difference for
9190                  * flow control if it was the only bit set. For any other
9191                  * override setting, just return
9192                  */
9193                 if (prev_override != override)
9194                         return;
9195
9196                 if (qi->stopped == 0) {
9197                         brcms_c_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
9198                 } else {
9199                         int prio;
9200
9201                         for (prio = MAXPRIO; prio >= 0; prio--) {
9202                                 if (!mboolisset(qi->stopped, NBITVAL(prio)))
9203                                         brcms_c_txflowcontrol_signal(
9204                                                 wlc, qi, OFF, prio);
9205                         }
9206                 }
9207         }
9208 }
9209
9210 /*
9211  * Flag 'scan in progress' to withhold dynamic phy calibration
9212  */
9213 void brcms_c_scan_start(struct brcms_c_info *wlc)
9214 {
9215         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, true);
9216 }
9217
9218 void brcms_c_scan_stop(struct brcms_c_info *wlc)
9219 {
9220         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, false);
9221 }
9222
9223 void brcms_c_associate_upd(struct brcms_c_info *wlc, bool state)
9224 {
9225         wlc->pub->associated = state;
9226         wlc->bsscfg->associated = state;
9227 }
9228
9229 /*
9230  * When a remote STA/AP is removed by Mac80211, or when it can no longer accept
9231  * AMPDU traffic, packets pending in hardware have to be invalidated so that
9232  * when later on hardware releases them, they can be handled appropriately.
9233  */
9234 void brcms_c_inval_dma_pkts(struct brcms_hardware *hw,
9235                                struct ieee80211_sta *sta,
9236                                void (*dma_callback_fn))
9237 {
9238         struct dma_pub *dmah;
9239         int i;
9240         for (i = 0; i < NFIFO; i++) {
9241                 dmah = hw->di[i];
9242                 if (dmah != NULL)
9243                         dma_walk_packets(dmah, dma_callback_fn, sta);
9244         }
9245 }
9246
9247 int brcms_c_get_curband(struct brcms_c_info *wlc)
9248 {
9249         return wlc->band->bandunit;
9250 }
9251
9252 void brcms_c_wait_for_tx_completion(struct brcms_c_info *wlc, bool drop)
9253 {
9254         /* flush packet queue when requested */
9255         if (drop)
9256                 brcmu_pktq_flush(&wlc->pkt_queue->q, false, NULL, NULL);
9257
9258         /* wait for queue and DMA fifos to run dry */
9259         while (!pktq_empty(&wlc->pkt_queue->q) || brcms_txpktpendtot(wlc) > 0)
9260                 brcms_msleep(wlc->wl, 1);
9261 }
9262
9263 void brcms_c_set_beacon_listen_interval(struct brcms_c_info *wlc, u8 interval)
9264 {
9265         wlc->bcn_li_bcn = interval;
9266         if (wlc->pub->up)
9267                 brcms_c_bcn_li_upd(wlc);
9268 }
9269
9270 int brcms_c_set_tx_power(struct brcms_c_info *wlc, int txpwr)
9271 {
9272         uint qdbm;
9273
9274         /* Remove override bit and clip to max qdbm value */
9275         qdbm = min_t(uint, txpwr * BRCMS_TXPWR_DB_FACTOR, 0xff);
9276         return wlc_phy_txpower_set(wlc->band->pi, qdbm, false);
9277 }
9278
9279 int brcms_c_get_tx_power(struct brcms_c_info *wlc)
9280 {
9281         uint qdbm;
9282         bool override;
9283
9284         wlc_phy_txpower_get(wlc->band->pi, &qdbm, &override);
9285
9286         /* Return qdbm units */
9287         return (int)(qdbm / BRCMS_TXPWR_DB_FACTOR);
9288 }
9289
9290 void brcms_c_set_radio_mpc(struct brcms_c_info *wlc, bool mpc)
9291 {
9292         wlc->mpc = mpc;
9293         brcms_c_radio_mpc_upd(wlc);
9294 }
9295
9296 /*
9297  * Search the name=value vars for a specific one and return its value.
9298  * Returns NULL if not found.
9299  */
9300 char *getvar(char *vars, const char *name)
9301 {
9302         char *s;
9303         int len;
9304
9305         if (!name)
9306                 return NULL;
9307
9308         len = strlen(name);
9309         if (len == 0)
9310                 return NULL;
9311
9312         /* first look in vars[] */
9313         for (s = vars; s && *s;) {
9314                 if ((memcmp(s, name, len) == 0) && (s[len] == '='))
9315                         return &s[len + 1];
9316
9317                 while (*s++)
9318                         ;
9319         }
9320         /* nothing found */
9321         return NULL;
9322 }
9323
9324 /*
9325  * Search the vars for a specific one and return its value as
9326  * an integer. Returns 0 if not found.
9327  */
9328 int getintvar(char *vars, const char *name)
9329 {
9330         char *val;
9331         unsigned long res;
9332
9333         val = getvar(vars, name);
9334         if (val && !kstrtoul(val, 0, &res))
9335                 return res;
9336
9337         return 0;
9338 }