]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/staging/brcm80211/brcmsmac/wlc_main.c
staging: brcm80211: removed wl_ (vendor specific acronym)
[mv-sheeva.git] / drivers / staging / brcm80211 / brcmsmac / wlc_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 #include <linux/kernel.h>
17 #include <linux/ctype.h>
18 #include <linux/etherdevice.h>
19 #include <linux/pci_ids.h>
20 #include <net/mac80211.h>
21
22 #include <bcmdefs.h>
23 #include <bcmdevs.h>
24 #include <bcmutils.h>
25 #include <bcmwifi.h>
26 #include <bcmnvram.h>
27 #include <aiutils.h>
28 #include <bcmsrom.h>
29 #include "bcmdma.h"
30 #include <bcmdma.h>
31
32 #include "wlc_pmu.h"
33 #include "d11.h"
34 #include "wlc_types.h"
35 #include "wlc_cfg.h"
36 #include "wlc_rate.h"
37 #include "wlc_scb.h"
38 #include "wlc_pub.h"
39 #include "wlc_key.h"
40 #include "wlc_bsscfg.h"
41 #include "phy/wlc_phy_hal.h"
42 #include "wlc_channel.h"
43 #include "wlc_main.h"
44 #include "wlc_bmac.h"
45 #include "wlc_phy_hal.h"
46 #include "wlc_antsel.h"
47 #include "wlc_stf.h"
48 #include "wlc_ampdu.h"
49 #include "wl_export.h"
50 #include "wlc_alloc.h"
51 #include "wl_dbg.h"
52 #include "wl_mac80211.h"
53
54 /*
55  * WPA(2) definitions
56  */
57 #define RSN_CAP_4_REPLAY_CNTRS          2
58 #define RSN_CAP_16_REPLAY_CNTRS         3
59
60 #define WPA_CAP_4_REPLAY_CNTRS          RSN_CAP_4_REPLAY_CNTRS
61 #define WPA_CAP_16_REPLAY_CNTRS         RSN_CAP_16_REPLAY_CNTRS
62
63 /*
64  * Indication for txflowcontrol that all priority bits in
65  * TXQ_STOP_FOR_PRIOFC_MASK are to be considered.
66  */
67 #define ALLPRIO         -1
68
69 /*
70  * 32 SSID chars, max of 4 chars for each SSID char "\xFF", plus NULL.
71  */
72 #define SSID_FMT_BUF_LEN        ((4 * IEEE80211_MAX_SSID_LEN) + 1)
73
74 #define TIMER_INTERVAL_WATCHDOG 1000    /* watchdog timer, in unit of ms */
75 #define TIMER_INTERVAL_RADIOCHK 800     /* radio monitor timer, in unit of ms */
76
77 #ifndef WLC_MPC_MAX_DELAYCNT
78 #define WLC_MPC_MAX_DELAYCNT    10      /* Max MPC timeout, in unit of watchdog */
79 #endif
80 #define WLC_MPC_MIN_DELAYCNT    1       /* Min MPC timeout, in unit of watchdog */
81 #define WLC_MPC_THRESHOLD       3       /* MPC count threshold level */
82
83 #define BEACON_INTERVAL_DEFAULT 100     /* beacon interval, in unit of 1024TU */
84 #define DTIM_INTERVAL_DEFAULT   3       /* DTIM interval, in unit of beacon interval */
85
86 /* Scale down delays to accommodate QT slow speed */
87 #define BEACON_INTERVAL_DEF_QT  20      /* beacon interval, in unit of 1024TU */
88 #define DTIM_INTERVAL_DEF_QT    1       /* DTIM interval, in unit of beacon interval */
89
90 #define TBTT_ALIGN_LEEWAY_US    100     /* min leeway before first TBTT in us */
91
92 /* Software feature flag defines used by wlfeatureflag */
93 #define WL_SWFL_NOHWRADIO       0x0004
94 #define WL_SWFL_FLOWCONTROL     0x0008  /* Enable backpressure to OS stack */
95 #define WL_SWFL_WLBSSSORT       0x0010  /* Per-port supports sorting of BSS */
96
97 /* n-mode support capability */
98 /* 2x2 includes both 1x1 & 2x2 devices
99  * reserved #define 2 for future when we want to separate 1x1 & 2x2 and
100  * control it independently
101  */
102 #define WL_11N_2x2                      1
103 #define WL_11N_3x3                      3
104 #define WL_11N_4x4                      4
105
106 /* define 11n feature disable flags */
107 #define WLFEATURE_DISABLE_11N           0x00000001
108 #define WLFEATURE_DISABLE_11N_STBC_TX   0x00000002
109 #define WLFEATURE_DISABLE_11N_STBC_RX   0x00000004
110 #define WLFEATURE_DISABLE_11N_SGI_TX    0x00000008
111 #define WLFEATURE_DISABLE_11N_SGI_RX    0x00000010
112 #define WLFEATURE_DISABLE_11N_AMPDU_TX  0x00000020
113 #define WLFEATURE_DISABLE_11N_AMPDU_RX  0x00000040
114 #define WLFEATURE_DISABLE_11N_GF        0x00000080
115
116 #define EDCF_ACI_MASK                0x60
117 #define EDCF_ACI_SHIFT               5
118 #define EDCF_ECWMIN_MASK             0x0f
119 #define EDCF_ECWMAX_SHIFT            4
120 #define EDCF_AIFSN_MASK              0x0f
121 #define EDCF_AIFSN_MAX               15
122 #define EDCF_ECWMAX_MASK             0xf0
123
124 #define EDCF_AC_BE_TXOP_STA          0x0000
125 #define EDCF_AC_BK_TXOP_STA          0x0000
126 #define EDCF_AC_VO_ACI_STA           0x62
127 #define EDCF_AC_VO_ECW_STA           0x32
128 #define EDCF_AC_VI_ACI_STA           0x42
129 #define EDCF_AC_VI_ECW_STA           0x43
130 #define EDCF_AC_BK_ECW_STA           0xA4
131 #define EDCF_AC_VI_TXOP_STA          0x005e
132 #define EDCF_AC_VO_TXOP_STA          0x002f
133 #define EDCF_AC_BE_ACI_STA           0x03
134 #define EDCF_AC_BE_ECW_STA           0xA4
135 #define EDCF_AC_BK_ACI_STA           0x27
136 #define EDCF_AC_VO_TXOP_AP           0x002f
137
138 #define EDCF_TXOP2USEC(txop)         ((txop) << 5)
139 #define EDCF_ECW2CW(exp)             ((1 << (exp)) - 1)
140
141 #define APHY_SYMBOL_TIME        4
142 #define APHY_PREAMBLE_TIME      16
143 #define APHY_SIGNAL_TIME        4
144 #define APHY_SIFS_TIME          16
145 #define APHY_SERVICE_NBITS      16
146 #define APHY_TAIL_NBITS         6
147 #define BPHY_SIFS_TIME          10
148 #define BPHY_PLCP_SHORT_TIME    96
149
150 #define PREN_PREAMBLE           24
151 #define PREN_MM_EXT             12
152 #define PREN_PREAMBLE_EXT       4
153
154 #define DOT11_MAC_HDR_LEN               24
155 #define DOT11_ACK_LEN           10
156 #define DOT11_BA_LEN            4
157 #define DOT11_OFDM_SIGNAL_EXTENSION     6
158 #define DOT11_MIN_FRAG_LEN              256
159 #define DOT11_RTS_LEN           16
160 #define DOT11_CTS_LEN           10
161 #define DOT11_BA_BITMAP_LEN             128
162 #define DOT11_MIN_BEACON_PERIOD         1
163 #define DOT11_MAX_BEACON_PERIOD         0xFFFF
164 #define DOT11_MAXNUMFRAGS       16
165 #define DOT11_MAX_FRAG_LEN              2346
166
167 #define BPHY_PLCP_TIME          192
168 #define RIFS_11N_TIME           2
169
170 #define WME_VER                 1
171 #define WME_SUBTYPE_PARAM_IE    1
172 #define WME_TYPE                2
173 #define WME_OUI                 "\x00\x50\xf2"
174
175 #define AC_BE                   0
176 #define AC_BK                   1
177 #define AC_VI                   2
178 #define AC_VO                   3
179
180 /*
181  * driver maintains internal 'tick'(wlc->pub->now) which increments in 1s OS timer(soft
182  * watchdog) it is not a wall clock and won't increment when driver is in "down" state
183  * this low resolution driver tick can be used for maintenance tasks such as phy
184  * calibration and scb update
185  */
186
187 /* To inform the ucode of the last mcast frame posted so that it can clear moredata bit */
188 #define BCMCFID(wlc, fid) wlc_bmac_write_shm((wlc)->hw, M_BCMC_FID, (fid))
189
190 #define WLC_WAR16165(wlc) (wlc->pub->sih->bustype == PCI_BUS && \
191                                 (!AP_ENAB(wlc->pub)) && (wlc->war16165))
192
193 /* debug/trace */
194 uint brcm_msg_level =
195 #if defined(BCMDBG)
196         LOG_ERROR_VAL;
197 #else
198         0;
199 #endif                          /* BCMDBG */
200
201 /* Find basic rate for a given rate */
202 #define WLC_BASIC_RATE(wlc, rspec)      (IS_MCS(rspec) ? \
203                         (wlc)->band->basic_rate[mcs_table[rspec & RSPEC_RATE_MASK].leg_ofdm] : \
204                         (wlc)->band->basic_rate[rspec & RSPEC_RATE_MASK])
205
206 #define FRAMETYPE(r, mimoframe) (IS_MCS(r) ? mimoframe  : (IS_CCK(r) ? FT_CCK : FT_OFDM))
207
208 #define RFDISABLE_DEFAULT       10000000        /* rfdisable delay timer 500 ms, runs of ALP clock */
209
210 #define WLC_TEMPSENSE_PERIOD            10      /* 10 second timeout */
211
212 #define SCAN_IN_PROGRESS(x)     0
213
214 #define EPI_VERSION_NUM         0x054b0b00
215
216 #ifdef BCMDBG
217 /* pointer to most recently allocated wl/wlc */
218 static struct wlc_info *wlc_info_dbg = (struct wlc_info *) (NULL);
219 #endif
220
221 const u8 prio2fifo[NUMPRIO] = {
222         TX_AC_BE_FIFO,          /* 0    BE      AC_BE   Best Effort */
223         TX_AC_BK_FIFO,          /* 1    BK      AC_BK   Background */
224         TX_AC_BK_FIFO,          /* 2    --      AC_BK   Background */
225         TX_AC_BE_FIFO,          /* 3    EE      AC_BE   Best Effort */
226         TX_AC_VI_FIFO,          /* 4    CL      AC_VI   Video */
227         TX_AC_VI_FIFO,          /* 5    VI      AC_VI   Video */
228         TX_AC_VO_FIFO,          /* 6    VO      AC_VO   Voice */
229         TX_AC_VO_FIFO           /* 7    NC      AC_VO   Voice */
230 };
231
232 /* precedences numbers for wlc queues. These are twice as may levels as
233  * 802.1D priorities.
234  * Odd numbers are used for HI priority traffic at same precedence levels
235  * These constants are used ONLY by wlc_prio2prec_map.  Do not use them elsewhere.
236  */
237 #define _WLC_PREC_NONE          0       /* None = - */
238 #define _WLC_PREC_BK            2       /* BK - Background */
239 #define _WLC_PREC_BE            4       /* BE - Best-effort */
240 #define _WLC_PREC_EE            6       /* EE - Excellent-effort */
241 #define _WLC_PREC_CL            8       /* CL - Controlled Load */
242 #define _WLC_PREC_VI            10      /* Vi - Video */
243 #define _WLC_PREC_VO            12      /* Vo - Voice */
244 #define _WLC_PREC_NC            14      /* NC - Network Control */
245
246 /* 802.1D Priority to precedence queue mapping */
247 const u8 wlc_prio2prec_map[] = {
248         _WLC_PREC_BE,           /* 0 BE - Best-effort */
249         _WLC_PREC_BK,           /* 1 BK - Background */
250         _WLC_PREC_NONE,         /* 2 None = - */
251         _WLC_PREC_EE,           /* 3 EE - Excellent-effort */
252         _WLC_PREC_CL,           /* 4 CL - Controlled Load */
253         _WLC_PREC_VI,           /* 5 Vi - Video */
254         _WLC_PREC_VO,           /* 6 Vo - Voice */
255         _WLC_PREC_NC,           /* 7 NC - Network Control */
256 };
257
258 /* Sanity check for tx_prec_map and fifo synchup
259  * Either there are some packets pending for the fifo, else if fifo is empty then
260  * all the corresponding precmap bits should be set
261  */
262 #define WLC_TX_FIFO_CHECK(wlc, fifo) (TXPKTPENDGET((wlc), (fifo)) ||    \
263         (TXPKTPENDGET((wlc), (fifo)) == 0 && \
264         ((wlc)->tx_prec_map & (wlc)->fifo2prec_map[(fifo)]) == \
265         (wlc)->fifo2prec_map[(fifo)]))
266
267 /* TX FIFO number to WME/802.1E Access Category */
268 const u8 wme_fifo2ac[] = { AC_BK, AC_BE, AC_VI, AC_VO, AC_BE, AC_BE };
269
270 /* WME/802.1E Access Category to TX FIFO number */
271 static const u8 wme_ac2fifo[] = { 1, 0, 2, 3 };
272
273 static bool in_send_q = false;
274
275 /* Shared memory location index for various AC params */
276 #define wme_shmemacindex(ac)    wme_ac2fifo[ac]
277
278 #ifdef BCMDBG
279 static const char *fifo_names[] = {
280         "AC_BK", "AC_BE", "AC_VI", "AC_VO", "BCMC", "ATIM" };
281 #else
282 static const char fifo_names[6][0];
283 #endif
284
285 static const u8 acbitmap2maxprio[] = {
286         PRIO_8021D_BE, PRIO_8021D_BE, PRIO_8021D_BK, PRIO_8021D_BK,
287         PRIO_8021D_VI, PRIO_8021D_VI, PRIO_8021D_VI, PRIO_8021D_VI,
288         PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO,
289         PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO
290 };
291
292 /* currently the best mechanism for determining SIFS is the band in use */
293 #define SIFS(band) ((band)->bandtype == WLC_BAND_5G ? APHY_SIFS_TIME : BPHY_SIFS_TIME);
294
295 /* value for # replay counters currently supported */
296 #define WLC_REPLAY_CNTRS_VALUE  WPA_CAP_16_REPLAY_CNTRS
297
298 /* local prototypes */
299 static u16 wlc_d11hdrs_mac80211(struct wlc_info *wlc,
300                                                struct ieee80211_hw *hw,
301                                                struct sk_buff *p,
302                                                struct scb *scb, uint frag,
303                                                uint nfrags, uint queue,
304                                                uint next_frag_len,
305                                                wsec_key_t *key,
306                                                ratespec_t rspec_override);
307 static void wlc_bss_default_init(struct wlc_info *wlc);
308 static void wlc_ucode_mac_upd(struct wlc_info *wlc);
309 static ratespec_t mac80211_wlc_set_nrate(struct wlc_info *wlc,
310                                          struct wlcband *cur_band, u32 int_val);
311 static void wlc_tx_prec_map_init(struct wlc_info *wlc);
312 static void wlc_watchdog(void *arg);
313 static void wlc_watchdog_by_timer(void *arg);
314 static u16 wlc_rate_shm_offset(struct wlc_info *wlc, u8 rate);
315 static int wlc_set_rateset(struct wlc_info *wlc, wlc_rateset_t *rs_arg);
316 static u8 wlc_local_constraint_qdbm(struct wlc_info *wlc);
317
318 /* send and receive */
319 static struct wlc_txq_info *wlc_txq_alloc(struct wlc_info *wlc);
320 static void wlc_txq_free(struct wlc_info *wlc,
321                          struct wlc_txq_info *qi);
322 static void wlc_txflowcontrol_signal(struct wlc_info *wlc,
323                                      struct wlc_txq_info *qi,
324                                      bool on, int prio);
325 static void wlc_txflowcontrol_reset(struct wlc_info *wlc);
326 static void wlc_compute_cck_plcp(struct wlc_info *wlc, ratespec_t rate,
327                                  uint length, u8 *plcp);
328 static void wlc_compute_ofdm_plcp(ratespec_t rate, uint length, u8 *plcp);
329 static void wlc_compute_mimo_plcp(ratespec_t rate, uint length, u8 *plcp);
330 static u16 wlc_compute_frame_dur(struct wlc_info *wlc, ratespec_t rate,
331                                     u8 preamble_type, uint next_frag_len);
332 static u64 wlc_recover_tsf64(struct wlc_info *wlc, struct wlc_d11rxhdr *rxh);
333 static void wlc_recvctl(struct wlc_info *wlc,
334                         d11rxhdr_t *rxh, struct sk_buff *p);
335 static uint wlc_calc_frame_len(struct wlc_info *wlc, ratespec_t rate,
336                                u8 preamble_type, uint dur);
337 static uint wlc_calc_ack_time(struct wlc_info *wlc, ratespec_t rate,
338                               u8 preamble_type);
339 static uint wlc_calc_cts_time(struct wlc_info *wlc, ratespec_t rate,
340                               u8 preamble_type);
341 /* interrupt, up/down, band */
342 static void wlc_setband(struct wlc_info *wlc, uint bandunit);
343 static chanspec_t wlc_init_chanspec(struct wlc_info *wlc);
344 static void wlc_bandinit_ordered(struct wlc_info *wlc, chanspec_t chanspec);
345 static void wlc_bsinit(struct wlc_info *wlc);
346 static int wlc_duty_cycle_set(struct wlc_info *wlc, int duty_cycle, bool isOFDM,
347                               bool writeToShm);
348 static void wlc_radio_hwdisable_upd(struct wlc_info *wlc);
349 static bool wlc_radio_monitor_start(struct wlc_info *wlc);
350 static void wlc_radio_timer(void *arg);
351 static void wlc_radio_enable(struct wlc_info *wlc);
352 static void wlc_radio_upd(struct wlc_info *wlc);
353
354 /* scan, association, BSS */
355 static uint wlc_calc_ba_time(struct wlc_info *wlc, ratespec_t rate,
356                              u8 preamble_type);
357 static void wlc_update_mimo_band_bwcap(struct wlc_info *wlc, u8 bwcap);
358 static void wlc_ht_update_sgi_rx(struct wlc_info *wlc, int val);
359 static void wlc_ht_update_ldpc(struct wlc_info *wlc, s8 val);
360 static void wlc_war16165(struct wlc_info *wlc, bool tx);
361
362 static void wlc_wme_retries_write(struct wlc_info *wlc);
363 static bool wlc_attach_stf_ant_init(struct wlc_info *wlc);
364 static uint wlc_attach_module(struct wlc_info *wlc);
365 static void wlc_detach_module(struct wlc_info *wlc);
366 static void wlc_timers_deinit(struct wlc_info *wlc);
367 static void wlc_down_led_upd(struct wlc_info *wlc);
368 static uint wlc_down_del_timer(struct wlc_info *wlc);
369 static void wlc_ofdm_rateset_war(struct wlc_info *wlc);
370 static int _wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
371                       struct wlc_if *wlcif);
372
373 /* conditions under which the PM bit should be set in outgoing frames and STAY_AWAKE is meaningful
374  */
375 bool wlc_ps_allowed(struct wlc_info *wlc)
376 {
377         int idx;
378         struct wlc_bsscfg *cfg;
379
380         /* disallow PS when one of the following global conditions meets */
381         if (!wlc->pub->associated)
382                 return false;
383
384         /* disallow PS when one of these meets when not scanning */
385         if (AP_ACTIVE(wlc) || wlc->monitor)
386                 return false;
387
388         FOREACH_AS_STA(wlc, idx, cfg) {
389                 /* disallow PS when one of the following bsscfg specific conditions meets */
390                 if (!cfg->BSS || !WLC_PORTOPEN(cfg))
391                         return false;
392
393                 if (!cfg->dtim_programmed)
394                         return false;
395         }
396
397         return true;
398 }
399
400 void wlc_reset(struct wlc_info *wlc)
401 {
402         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
403
404         /* slurp up hw mac counters before core reset */
405         wlc_statsupd(wlc);
406
407         /* reset our snapshot of macstat counters */
408         memset((char *)wlc->core->macstat_snapshot, 0,
409                 sizeof(macstat_t));
410
411         wlc_bmac_reset(wlc->hw);
412 }
413
414 void wlc_fatal_error(struct wlc_info *wlc)
415 {
416         wiphy_err(wlc->wiphy, "wl%d: fatal error, reinitializing\n",
417                   wlc->pub->unit);
418         brcms_init(wlc->wl);
419 }
420
421 /* Return the channel the driver should initialize during wlc_init.
422  * the channel may have to be changed from the currently configured channel
423  * if other configurations are in conflict (bandlocked, 11n mode disabled,
424  * invalid channel for current country, etc.)
425  */
426 static chanspec_t wlc_init_chanspec(struct wlc_info *wlc)
427 {
428         chanspec_t chanspec =
429             1 | WL_CHANSPEC_BW_20 | WL_CHANSPEC_CTL_SB_NONE |
430             WL_CHANSPEC_BAND_2G;
431
432         return chanspec;
433 }
434
435 struct scb global_scb;
436
437 static void wlc_init_scb(struct wlc_info *wlc, struct scb *scb)
438 {
439         int i;
440         scb->flags = SCB_WMECAP | SCB_HTCAP;
441         for (i = 0; i < NUMPRIO; i++)
442                 scb->seqnum[i] = 0;
443 }
444
445 void wlc_init(struct wlc_info *wlc)
446 {
447         d11regs_t *regs;
448         chanspec_t chanspec;
449         int i;
450         struct wlc_bsscfg *bsscfg;
451         bool mute = false;
452
453         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
454
455         regs = wlc->regs;
456
457         /* This will happen if a big-hammer was executed. In that case, we want to go back
458          * to the channel that we were on and not new channel
459          */
460         if (wlc->pub->associated)
461                 chanspec = wlc->home_chanspec;
462         else
463                 chanspec = wlc_init_chanspec(wlc);
464
465         wlc_bmac_init(wlc->hw, chanspec, mute);
466
467         /* update beacon listen interval */
468         wlc_bcn_li_upd(wlc);
469
470         /* the world is new again, so is our reported rate */
471         wlc_reprate_init(wlc);
472
473         /* write ethernet address to core */
474         FOREACH_BSS(wlc, i, bsscfg) {
475                 wlc_set_mac(bsscfg);
476                 wlc_set_bssid(bsscfg);
477         }
478
479         /* Update tsf_cfprep if associated and up */
480         if (wlc->pub->associated) {
481                 FOREACH_BSS(wlc, i, bsscfg) {
482                         if (bsscfg->up) {
483                                 u32 bi;
484
485                                 /* get beacon period and convert to uS */
486                                 bi = bsscfg->current_bss->beacon_period << 10;
487                                 /*
488                                  * update since init path would reset
489                                  * to default value
490                                  */
491                                 W_REG(&regs->tsf_cfprep,
492                                       (bi << CFPREP_CBI_SHIFT));
493
494                                 /* Update maccontrol PM related bits */
495                                 wlc_set_ps_ctrl(wlc);
496
497                                 break;
498                         }
499                 }
500         }
501
502         wlc_key_hw_init_all(wlc);
503
504         wlc_bandinit_ordered(wlc, chanspec);
505
506         wlc_init_scb(wlc, &global_scb);
507
508         /* init probe response timeout */
509         wlc_write_shm(wlc, M_PRS_MAXTIME, wlc->prb_resp_timeout);
510
511         /* init max burst txop (framebursting) */
512         wlc_write_shm(wlc, M_MBURST_TXOP,
513                       (wlc->
514                        _rifs ? (EDCF_AC_VO_TXOP_AP << 5) : MAXFRAMEBURST_TXOP));
515
516         /* initialize maximum allowed duty cycle */
517         wlc_duty_cycle_set(wlc, wlc->tx_duty_cycle_ofdm, true, true);
518         wlc_duty_cycle_set(wlc, wlc->tx_duty_cycle_cck, false, true);
519
520         /* Update some shared memory locations related to max AMPDU size allowed to received */
521         wlc_ampdu_shm_upd(wlc->ampdu);
522
523         /* band-specific inits */
524         wlc_bsinit(wlc);
525
526         /* Enable EDCF mode (while the MAC is suspended) */
527         if (EDCF_ENAB(wlc->pub)) {
528                 OR_REG(&regs->ifs_ctl, IFS_USEEDCF);
529                 wlc_edcf_setparams(wlc, false);
530         }
531
532         /* Init precedence maps for empty FIFOs */
533         wlc_tx_prec_map_init(wlc);
534
535         /* read the ucode version if we have not yet done so */
536         if (wlc->ucode_rev == 0) {
537                 wlc->ucode_rev =
538                     wlc_read_shm(wlc, M_BOM_REV_MAJOR) << NBITS(u16);
539                 wlc->ucode_rev |= wlc_read_shm(wlc, M_BOM_REV_MINOR);
540         }
541
542         /* ..now really unleash hell (allow the MAC out of suspend) */
543         wlc_enable_mac(wlc);
544
545         /* clear tx flow control */
546         wlc_txflowcontrol_reset(wlc);
547
548         /* clear tx data fifo suspends */
549         wlc->tx_suspended = false;
550
551         /* enable the RF Disable Delay timer */
552         W_REG(&wlc->regs->rfdisabledly, RFDISABLE_DEFAULT);
553
554         /* initialize mpc delay */
555         wlc->mpc_delay_off = wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
556
557         /*
558          * Initialize WME parameters; if they haven't been set by some other
559          * mechanism (IOVar, etc) then read them from the hardware.
560          */
561         if (WLC_WME_RETRY_SHORT_GET(wlc, 0) == 0) {     /* Uninitialized; read from HW */
562                 int ac;
563
564                 for (ac = 0; ac < AC_COUNT; ac++) {
565                         wlc->wme_retries[ac] =
566                             wlc_read_shm(wlc, M_AC_TXLMT_ADDR(ac));
567                 }
568         }
569 }
570
571 void wlc_mac_bcn_promisc_change(struct wlc_info *wlc, bool promisc)
572 {
573         wlc->bcnmisc_monitor = promisc;
574         wlc_mac_bcn_promisc(wlc);
575 }
576
577 void wlc_mac_bcn_promisc(struct wlc_info *wlc)
578 {
579         if ((AP_ENAB(wlc->pub) && (N_ENAB(wlc->pub) || wlc->band->gmode)) ||
580             wlc->bcnmisc_ibss || wlc->bcnmisc_scan || wlc->bcnmisc_monitor)
581                 wlc_mctrl(wlc, MCTL_BCNS_PROMISC, MCTL_BCNS_PROMISC);
582         else
583                 wlc_mctrl(wlc, MCTL_BCNS_PROMISC, 0);
584 }
585
586 /* set or clear maccontrol bits MCTL_PROMISC and MCTL_KEEPCONTROL */
587 void wlc_mac_promisc(struct wlc_info *wlc)
588 {
589         u32 promisc_bits = 0;
590
591         /* promiscuous mode just sets MCTL_PROMISC
592          * Note: APs get all BSS traffic without the need to set the MCTL_PROMISC bit
593          * since all BSS data traffic is directed at the AP
594          */
595         if (PROMISC_ENAB(wlc->pub) && !AP_ENAB(wlc->pub))
596                 promisc_bits |= MCTL_PROMISC;
597
598         /* monitor mode needs both MCTL_PROMISC and MCTL_KEEPCONTROL
599          * Note: monitor mode also needs MCTL_BCNS_PROMISC, but that is
600          * handled in wlc_mac_bcn_promisc()
601          */
602         if (MONITOR_ENAB(wlc))
603                 promisc_bits |= MCTL_PROMISC | MCTL_KEEPCONTROL;
604
605         wlc_mctrl(wlc, MCTL_PROMISC | MCTL_KEEPCONTROL, promisc_bits);
606 }
607
608 /* push sw hps and wake state through hardware */
609 void wlc_set_ps_ctrl(struct wlc_info *wlc)
610 {
611         u32 v1, v2;
612         bool hps;
613         bool awake_before;
614
615         hps = PS_ALLOWED(wlc);
616
617         BCMMSG(wlc->wiphy, "wl%d: hps %d\n", wlc->pub->unit, hps);
618
619         v1 = R_REG(&wlc->regs->maccontrol);
620         v2 = MCTL_WAKE;
621         if (hps)
622                 v2 |= MCTL_HPS;
623
624         wlc_mctrl(wlc, MCTL_WAKE | MCTL_HPS, v2);
625
626         awake_before = ((v1 & MCTL_WAKE) || ((v1 & MCTL_HPS) == 0));
627
628         if (!awake_before)
629                 wlc_bmac_wait_for_wake(wlc->hw);
630
631 }
632
633 /*
634  * Write this BSS config's MAC address to core.
635  * Updates RXE match engine.
636  */
637 int wlc_set_mac(struct wlc_bsscfg *cfg)
638 {
639         int err = 0;
640         struct wlc_info *wlc = cfg->wlc;
641
642         if (cfg == wlc->cfg) {
643                 /* enter the MAC addr into the RXE match registers */
644                 wlc_set_addrmatch(wlc, RCM_MAC_OFFSET, cfg->cur_etheraddr);
645         }
646
647         wlc_ampdu_macaddr_upd(wlc);
648
649         return err;
650 }
651
652 /* Write the BSS config's BSSID address to core (set_bssid in d11procs.tcl).
653  * Updates RXE match engine.
654  */
655 void wlc_set_bssid(struct wlc_bsscfg *cfg)
656 {
657         struct wlc_info *wlc = cfg->wlc;
658
659         /* if primary config, we need to update BSSID in RXE match registers */
660         if (cfg == wlc->cfg) {
661                 wlc_set_addrmatch(wlc, RCM_BSSID_OFFSET, cfg->BSSID);
662         }
663 #ifdef SUPPORT_HWKEYS
664         else if (BSSCFG_STA(cfg) && cfg->BSS) {
665                 wlc_rcmta_add_bssid(wlc, cfg);
666         }
667 #endif
668 }
669
670 /*
671  * Suspend the the MAC and update the slot timing
672  * for standard 11b/g (20us slots) or shortslot 11g (9us slots).
673  */
674 void wlc_switch_shortslot(struct wlc_info *wlc, bool shortslot)
675 {
676         int idx;
677         struct wlc_bsscfg *cfg;
678
679         /* use the override if it is set */
680         if (wlc->shortslot_override != WLC_SHORTSLOT_AUTO)
681                 shortslot = (wlc->shortslot_override == WLC_SHORTSLOT_ON);
682
683         if (wlc->shortslot == shortslot)
684                 return;
685
686         wlc->shortslot = shortslot;
687
688         /* update the capability based on current shortslot mode */
689         FOREACH_BSS(wlc, idx, cfg) {
690                 if (!cfg->associated)
691                         continue;
692                 cfg->current_bss->capability &=
693                                         ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
694                 if (wlc->shortslot)
695                         cfg->current_bss->capability |=
696                                         WLAN_CAPABILITY_SHORT_SLOT_TIME;
697         }
698
699         wlc_bmac_set_shortslot(wlc->hw, shortslot);
700 }
701
702 static u8 wlc_local_constraint_qdbm(struct wlc_info *wlc)
703 {
704         u8 local;
705         s16 local_max;
706
707         local = WLC_TXPWR_MAX;
708         if (wlc->pub->associated &&
709             (bcm_chspec_ctlchan(wlc->chanspec) ==
710              bcm_chspec_ctlchan(wlc->home_chanspec))) {
711
712                 /* get the local power constraint if we are on the AP's
713                  * channel [802.11h, 7.3.2.13]
714                  */
715                 /* Clamp the value between 0 and WLC_TXPWR_MAX w/o overflowing the target */
716                 local_max =
717                     (wlc->txpwr_local_max -
718                      wlc->txpwr_local_constraint) * WLC_TXPWR_DB_FACTOR;
719                 if (local_max > 0 && local_max < WLC_TXPWR_MAX)
720                         return (u8) local_max;
721                 if (local_max < 0)
722                         return 0;
723         }
724
725         return local;
726 }
727
728 /* propagate home chanspec to all bsscfgs in case bsscfg->current_bss->chanspec is referenced */
729 void wlc_set_home_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
730 {
731         if (wlc->home_chanspec != chanspec) {
732                 int idx;
733                 struct wlc_bsscfg *cfg;
734
735                 wlc->home_chanspec = chanspec;
736
737                 FOREACH_BSS(wlc, idx, cfg) {
738                         if (!cfg->associated)
739                                 continue;
740
741                         cfg->current_bss->chanspec = chanspec;
742                 }
743
744         }
745 }
746
747 static void wlc_set_phy_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
748 {
749         /* Save our copy of the chanspec */
750         wlc->chanspec = chanspec;
751
752         /* Set the chanspec and power limits for this locale after computing
753          * any 11h local tx power constraints.
754          */
755         wlc_channel_set_chanspec(wlc->cmi, chanspec,
756                                  wlc_local_constraint_qdbm(wlc));
757
758         if (wlc->stf->ss_algosel_auto)
759                 wlc_stf_ss_algo_channel_get(wlc, &wlc->stf->ss_algo_channel,
760                                             chanspec);
761
762         wlc_stf_ss_update(wlc, wlc->band);
763
764 }
765
766 void wlc_set_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
767 {
768         uint bandunit;
769         bool switchband = false;
770         chanspec_t old_chanspec = wlc->chanspec;
771
772         if (!wlc_valid_chanspec_db(wlc->cmi, chanspec)) {
773                 wiphy_err(wlc->wiphy, "wl%d: %s: Bad channel %d\n",
774                           wlc->pub->unit, __func__, CHSPEC_CHANNEL(chanspec));
775                 return;
776         }
777
778         /* Switch bands if necessary */
779         if (NBANDS(wlc) > 1) {
780                 bandunit = CHSPEC_WLCBANDUNIT(chanspec);
781                 if (wlc->band->bandunit != bandunit || wlc->bandinit_pending) {
782                         switchband = true;
783                         if (wlc->bandlocked) {
784                                 wiphy_err(wlc->wiphy, "wl%d: %s: chspec %d "
785                                           "band is locked!\n",
786                                           wlc->pub->unit, __func__,
787                                           CHSPEC_CHANNEL(chanspec));
788                                 return;
789                         }
790                         /* BMAC_NOTE: should the setband call come after the wlc_bmac_chanspec() ?
791                          * if the setband updates (wlc_bsinit) use low level calls to inspect and
792                          * set state, the state inspected may be from the wrong band, or the
793                          * following wlc_bmac_set_chanspec() may undo the work.
794                          */
795                         wlc_setband(wlc, bandunit);
796                 }
797         }
798
799         /* sync up phy/radio chanspec */
800         wlc_set_phy_chanspec(wlc, chanspec);
801
802         /* init antenna selection */
803         if (CHSPEC_WLC_BW(old_chanspec) != CHSPEC_WLC_BW(chanspec)) {
804                 wlc_antsel_init(wlc->asi);
805
806                 /* Fix the hardware rateset based on bw.
807                  * Mainly add MCS32 for 40Mhz, remove MCS 32 for 20Mhz
808                  */
809                 wlc_rateset_bw_mcs_filter(&wlc->band->hw_rateset,
810                                           wlc->band->
811                                           mimo_cap_40 ? CHSPEC_WLC_BW(chanspec)
812                                           : 0);
813         }
814
815         /* update some mac configuration since chanspec changed */
816         wlc_ucode_mac_upd(wlc);
817 }
818
819 ratespec_t wlc_lowest_basic_rspec(struct wlc_info *wlc, wlc_rateset_t *rs)
820 {
821         ratespec_t lowest_basic_rspec;
822         uint i;
823
824         /* Use the lowest basic rate */
825         lowest_basic_rspec = rs->rates[0] & WLC_RATE_MASK;
826         for (i = 0; i < rs->count; i++) {
827                 if (rs->rates[i] & WLC_RATE_FLAG) {
828                         lowest_basic_rspec = rs->rates[i] & WLC_RATE_MASK;
829                         break;
830                 }
831         }
832 #if NCONF
833         /* pick siso/cdd as default for OFDM (note no basic rate MCSs are supported yet) */
834         if (IS_OFDM(lowest_basic_rspec)) {
835                 lowest_basic_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
836         }
837 #endif
838
839         return lowest_basic_rspec;
840 }
841
842 /* This function changes the phytxctl for beacon based on current beacon ratespec AND txant
843  * setting as per this table:
844  *  ratespec     CCK            ant = wlc->stf->txant
845  *              OFDM            ant = 3
846  */
847 void wlc_beacon_phytxctl_txant_upd(struct wlc_info *wlc, ratespec_t bcn_rspec)
848 {
849         u16 phyctl;
850         u16 phytxant = wlc->stf->phytxant;
851         u16 mask = PHY_TXC_ANT_MASK;
852
853         /* for non-siso rates or default setting, use the available chains */
854         if (WLC_PHY_11N_CAP(wlc->band)) {
855                 phytxant = wlc_stf_phytxchain_sel(wlc, bcn_rspec);
856         }
857
858         phyctl = wlc_read_shm(wlc, M_BCN_PCTLWD);
859         phyctl = (phyctl & ~mask) | phytxant;
860         wlc_write_shm(wlc, M_BCN_PCTLWD, phyctl);
861 }
862
863 /* centralized protection config change function to simplify debugging, no consistency checking
864  * this should be called only on changes to avoid overhead in periodic function
865 */
866 void wlc_protection_upd(struct wlc_info *wlc, uint idx, int val)
867 {
868         BCMMSG(wlc->wiphy, "idx %d, val %d\n", idx, val);
869
870         switch (idx) {
871         case WLC_PROT_G_SPEC:
872                 wlc->protection->_g = (bool) val;
873                 break;
874         case WLC_PROT_G_OVR:
875                 wlc->protection->g_override = (s8) val;
876                 break;
877         case WLC_PROT_G_USER:
878                 wlc->protection->gmode_user = (u8) val;
879                 break;
880         case WLC_PROT_OVERLAP:
881                 wlc->protection->overlap = (s8) val;
882                 break;
883         case WLC_PROT_N_USER:
884                 wlc->protection->nmode_user = (s8) val;
885                 break;
886         case WLC_PROT_N_CFG:
887                 wlc->protection->n_cfg = (s8) val;
888                 break;
889         case WLC_PROT_N_CFG_OVR:
890                 wlc->protection->n_cfg_override = (s8) val;
891                 break;
892         case WLC_PROT_N_NONGF:
893                 wlc->protection->nongf = (bool) val;
894                 break;
895         case WLC_PROT_N_NONGF_OVR:
896                 wlc->protection->nongf_override = (s8) val;
897                 break;
898         case WLC_PROT_N_PAM_OVR:
899                 wlc->protection->n_pam_override = (s8) val;
900                 break;
901         case WLC_PROT_N_OBSS:
902                 wlc->protection->n_obss = (bool) val;
903                 break;
904
905         default:
906                 break;
907         }
908
909 }
910
911 static void wlc_ht_update_sgi_rx(struct wlc_info *wlc, int val)
912 {
913         wlc->ht_cap.cap_info &= ~(IEEE80211_HT_CAP_SGI_20 |
914                                         IEEE80211_HT_CAP_SGI_40);
915         wlc->ht_cap.cap_info |= (val & WLC_N_SGI_20) ?
916                                         IEEE80211_HT_CAP_SGI_20 : 0;
917         wlc->ht_cap.cap_info |= (val & WLC_N_SGI_40) ?
918                                         IEEE80211_HT_CAP_SGI_40 : 0;
919
920         if (wlc->pub->up) {
921                 wlc_update_beacon(wlc);
922                 wlc_update_probe_resp(wlc, true);
923         }
924 }
925
926 static void wlc_ht_update_ldpc(struct wlc_info *wlc, s8 val)
927 {
928         wlc->stf->ldpc = val;
929
930         wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_LDPC_CODING;
931         if (wlc->stf->ldpc != OFF)
932                 wlc->ht_cap.cap_info |= IEEE80211_HT_CAP_LDPC_CODING;
933
934         if (wlc->pub->up) {
935                 wlc_update_beacon(wlc);
936                 wlc_update_probe_resp(wlc, true);
937                 wlc_phy_ldpc_override_set(wlc->band->pi, (val ? true : false));
938         }
939 }
940
941 /*
942  * ucode, hwmac update
943  *    Channel dependent updates for ucode and hw
944  */
945 static void wlc_ucode_mac_upd(struct wlc_info *wlc)
946 {
947         /* enable or disable any active IBSSs depending on whether or not
948          * we are on the home channel
949          */
950         if (wlc->home_chanspec == WLC_BAND_PI_RADIO_CHANSPEC) {
951                 if (wlc->pub->associated) {
952                         /* BMAC_NOTE: This is something that should be fixed in ucode inits.
953                          * I think that the ucode inits set up the bcn templates and shm values
954                          * with a bogus beacon. This should not be done in the inits. If ucode needs
955                          * to set up a beacon for testing, the test routines should write it down,
956                          * not expect the inits to populate a bogus beacon.
957                          */
958                         if (WLC_PHY_11N_CAP(wlc->band)) {
959                                 wlc_write_shm(wlc, M_BCN_TXTSF_OFFSET,
960                                               wlc->band->bcntsfoff);
961                         }
962                 }
963         } else {
964                 /* disable an active IBSS if we are not on the home channel */
965         }
966
967         /* update the various promisc bits */
968         wlc_mac_bcn_promisc(wlc);
969         wlc_mac_promisc(wlc);
970 }
971
972 static void wlc_bandinit_ordered(struct wlc_info *wlc, chanspec_t chanspec)
973 {
974         wlc_rateset_t default_rateset;
975         uint parkband;
976         uint i, band_order[2];
977
978         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
979         /*
980          * We might have been bandlocked during down and the chip power-cycled (hibernate).
981          * figure out the right band to park on
982          */
983         if (wlc->bandlocked || NBANDS(wlc) == 1) {
984                 parkband = wlc->band->bandunit; /* updated in wlc_bandlock() */
985                 band_order[0] = band_order[1] = parkband;
986         } else {
987                 /* park on the band of the specified chanspec */
988                 parkband = CHSPEC_WLCBANDUNIT(chanspec);
989
990                 /* order so that parkband initialize last */
991                 band_order[0] = parkband ^ 1;
992                 band_order[1] = parkband;
993         }
994
995         /* make each band operational, software state init */
996         for (i = 0; i < NBANDS(wlc); i++) {
997                 uint j = band_order[i];
998
999                 wlc->band = wlc->bandstate[j];
1000
1001                 wlc_default_rateset(wlc, &default_rateset);
1002
1003                 /* fill in hw_rate */
1004                 wlc_rateset_filter(&default_rateset, &wlc->band->hw_rateset,
1005                                    false, WLC_RATES_CCK_OFDM, WLC_RATE_MASK,
1006                                    (bool) N_ENAB(wlc->pub));
1007
1008                 /* init basic rate lookup */
1009                 wlc_rate_lookup_init(wlc, &default_rateset);
1010         }
1011
1012         /* sync up phy/radio chanspec */
1013         wlc_set_phy_chanspec(wlc, chanspec);
1014 }
1015
1016 /* band-specific init */
1017 static void WLBANDINITFN(wlc_bsinit) (struct wlc_info *wlc)
1018 {
1019         BCMMSG(wlc->wiphy, "wl%d: bandunit %d\n",
1020                  wlc->pub->unit, wlc->band->bandunit);
1021
1022         /* write ucode ACK/CTS rate table */
1023         wlc_set_ratetable(wlc);
1024
1025         /* update some band specific mac configuration */
1026         wlc_ucode_mac_upd(wlc);
1027
1028         /* init antenna selection */
1029         wlc_antsel_init(wlc->asi);
1030
1031 }
1032
1033 /* switch to and initialize new band */
1034 static void WLBANDINITFN(wlc_setband) (struct wlc_info *wlc, uint bandunit)
1035 {
1036         int idx;
1037         struct wlc_bsscfg *cfg;
1038
1039         wlc->band = wlc->bandstate[bandunit];
1040
1041         if (!wlc->pub->up)
1042                 return;
1043
1044         /* wait for at least one beacon before entering sleeping state */
1045         FOREACH_AS_STA(wlc, idx, cfg)
1046             cfg->PMawakebcn = true;
1047         wlc_set_ps_ctrl(wlc);
1048
1049         /* band-specific initializations */
1050         wlc_bsinit(wlc);
1051 }
1052
1053 /* Initialize a WME Parameter Info Element with default STA parameters from WMM Spec, Table 12 */
1054 void wlc_wme_initparams_sta(struct wlc_info *wlc, wme_param_ie_t *pe)
1055 {
1056         static const wme_param_ie_t stadef = {
1057                 WME_OUI,
1058                 WME_TYPE,
1059                 WME_SUBTYPE_PARAM_IE,
1060                 WME_VER,
1061                 0,
1062                 0,
1063                 {
1064                  {EDCF_AC_BE_ACI_STA, EDCF_AC_BE_ECW_STA,
1065                   cpu_to_le16(EDCF_AC_BE_TXOP_STA)},
1066                  {EDCF_AC_BK_ACI_STA, EDCF_AC_BK_ECW_STA,
1067                   cpu_to_le16(EDCF_AC_BK_TXOP_STA)},
1068                  {EDCF_AC_VI_ACI_STA, EDCF_AC_VI_ECW_STA,
1069                   cpu_to_le16(EDCF_AC_VI_TXOP_STA)},
1070                  {EDCF_AC_VO_ACI_STA, EDCF_AC_VO_ECW_STA,
1071                   cpu_to_le16(EDCF_AC_VO_TXOP_STA)}
1072                  }
1073         };
1074         memcpy(pe, &stadef, sizeof(*pe));
1075 }
1076
1077 void wlc_wme_setparams(struct wlc_info *wlc, u16 aci,
1078                        const struct ieee80211_tx_queue_params *params,
1079                        bool suspend)
1080 {
1081         int i;
1082         shm_acparams_t acp_shm;
1083         u16 *shm_entry;
1084
1085         /* Only apply params if the core is out of reset and has clocks */
1086         if (!wlc->clk) {
1087                 wiphy_err(wlc->wiphy, "wl%d: %s : no-clock\n", wlc->pub->unit,
1088                           __func__);
1089                 return;
1090         }
1091
1092         do {
1093                 memset((char *)&acp_shm, 0, sizeof(shm_acparams_t));
1094                 /* fill in shm ac params struct */
1095                 acp_shm.txop = le16_to_cpu(params->txop);
1096                 /* convert from units of 32us to us for ucode */
1097                 wlc->edcf_txop[aci & 0x3] = acp_shm.txop =
1098                     EDCF_TXOP2USEC(acp_shm.txop);
1099                 acp_shm.aifs = (params->aifs & EDCF_AIFSN_MASK);
1100
1101                 if (aci == AC_VI && acp_shm.txop == 0
1102                     && acp_shm.aifs < EDCF_AIFSN_MAX)
1103                         acp_shm.aifs++;
1104
1105                 if (acp_shm.aifs < EDCF_AIFSN_MIN
1106                     || acp_shm.aifs > EDCF_AIFSN_MAX) {
1107                         wiphy_err(wlc->wiphy, "wl%d: wlc_edcf_setparams: bad "
1108                                   "aifs %d\n", wlc->pub->unit, acp_shm.aifs);
1109                         continue;
1110                 }
1111
1112                 acp_shm.cwmin = params->cw_min;
1113                 acp_shm.cwmax = params->cw_max;
1114                 acp_shm.cwcur = acp_shm.cwmin;
1115                 acp_shm.bslots =
1116                     R_REG(&wlc->regs->tsf_random) & acp_shm.cwcur;
1117                 acp_shm.reggap = acp_shm.bslots + acp_shm.aifs;
1118                 /* Indicate the new params to the ucode */
1119                 acp_shm.status = wlc_read_shm(wlc, (M_EDCF_QINFO +
1120                                                     wme_shmemacindex(aci) *
1121                                                     M_EDCF_QLEN +
1122                                                     M_EDCF_STATUS_OFF));
1123                 acp_shm.status |= WME_STATUS_NEWAC;
1124
1125                 /* Fill in shm acparam table */
1126                 shm_entry = (u16 *) &acp_shm;
1127                 for (i = 0; i < (int)sizeof(shm_acparams_t); i += 2)
1128                         wlc_write_shm(wlc,
1129                                       M_EDCF_QINFO +
1130                                       wme_shmemacindex(aci) * M_EDCF_QLEN + i,
1131                                       *shm_entry++);
1132
1133         } while (0);
1134
1135         if (suspend)
1136                 wlc_suspend_mac_and_wait(wlc);
1137
1138         if (suspend)
1139                 wlc_enable_mac(wlc);
1140
1141 }
1142
1143 void wlc_edcf_setparams(struct wlc_info *wlc, bool suspend)
1144 {
1145         u16 aci;
1146         int i_ac;
1147         edcf_acparam_t *edcf_acp;
1148
1149         struct ieee80211_tx_queue_params txq_pars;
1150         struct ieee80211_tx_queue_params *params = &txq_pars;
1151
1152         /*
1153          * AP uses AC params from wme_param_ie_ap.
1154          * AP advertises AC params from wme_param_ie.
1155          * STA uses AC params from wme_param_ie.
1156          */
1157
1158         edcf_acp = (edcf_acparam_t *) &wlc->wme_param_ie.acparam[0];
1159
1160         for (i_ac = 0; i_ac < AC_COUNT; i_ac++, edcf_acp++) {
1161                 /* find out which ac this set of params applies to */
1162                 aci = (edcf_acp->ACI & EDCF_ACI_MASK) >> EDCF_ACI_SHIFT;
1163
1164                 /* fill in shm ac params struct */
1165                 params->txop = edcf_acp->TXOP;
1166                 params->aifs = edcf_acp->ACI;
1167
1168                 /* CWmin = 2^(ECWmin) - 1 */
1169                 params->cw_min = EDCF_ECW2CW(edcf_acp->ECW & EDCF_ECWMIN_MASK);
1170                 /* CWmax = 2^(ECWmax) - 1 */
1171                 params->cw_max = EDCF_ECW2CW((edcf_acp->ECW & EDCF_ECWMAX_MASK)
1172                                             >> EDCF_ECWMAX_SHIFT);
1173                 wlc_wme_setparams(wlc, aci, params, suspend);
1174         }
1175
1176         if (suspend)
1177                 wlc_suspend_mac_and_wait(wlc);
1178
1179         if (AP_ENAB(wlc->pub) && WME_ENAB(wlc->pub)) {
1180                 wlc_update_beacon(wlc);
1181                 wlc_update_probe_resp(wlc, false);
1182         }
1183
1184         if (suspend)
1185                 wlc_enable_mac(wlc);
1186
1187 }
1188
1189 bool wlc_timers_init(struct wlc_info *wlc, int unit)
1190 {
1191         wlc->wdtimer = brcms_init_timer(wlc->wl, wlc_watchdog_by_timer,
1192                 wlc, "watchdog");
1193         if (!wlc->wdtimer) {
1194                 wiphy_err(wlc->wiphy, "wl%d:  wl_init_timer for wdtimer "
1195                           "failed\n", unit);
1196                 goto fail;
1197         }
1198
1199         wlc->radio_timer = brcms_init_timer(wlc->wl, wlc_radio_timer,
1200                 wlc, "radio");
1201         if (!wlc->radio_timer) {
1202                 wiphy_err(wlc->wiphy, "wl%d:  wl_init_timer for radio_timer "
1203                           "failed\n", unit);
1204                 goto fail;
1205         }
1206
1207         return true;
1208
1209  fail:
1210         return false;
1211 }
1212
1213 /*
1214  * Initialize wlc_info default values ...
1215  * may get overrides later in this function
1216  */
1217 void wlc_info_init(struct wlc_info *wlc, int unit)
1218 {
1219         int i;
1220         /* Assume the device is there until proven otherwise */
1221         wlc->device_present = true;
1222
1223         /* Save our copy of the chanspec */
1224         wlc->chanspec = CH20MHZ_CHSPEC(1);
1225
1226         /* various 802.11g modes */
1227         wlc->shortslot = false;
1228         wlc->shortslot_override = WLC_SHORTSLOT_AUTO;
1229
1230         wlc_protection_upd(wlc, WLC_PROT_G_OVR, WLC_PROTECTION_AUTO);
1231         wlc_protection_upd(wlc, WLC_PROT_G_SPEC, false);
1232
1233         wlc_protection_upd(wlc, WLC_PROT_N_CFG_OVR, WLC_PROTECTION_AUTO);
1234         wlc_protection_upd(wlc, WLC_PROT_N_CFG, WLC_N_PROTECTION_OFF);
1235         wlc_protection_upd(wlc, WLC_PROT_N_NONGF_OVR, WLC_PROTECTION_AUTO);
1236         wlc_protection_upd(wlc, WLC_PROT_N_NONGF, false);
1237         wlc_protection_upd(wlc, WLC_PROT_N_PAM_OVR, AUTO);
1238
1239         wlc_protection_upd(wlc, WLC_PROT_OVERLAP, WLC_PROTECTION_CTL_OVERLAP);
1240
1241         /* 802.11g draft 4.0 NonERP elt advertisement */
1242         wlc->include_legacy_erp = true;
1243
1244         wlc->stf->ant_rx_ovr = ANT_RX_DIV_DEF;
1245         wlc->stf->txant = ANT_TX_DEF;
1246
1247         wlc->prb_resp_timeout = WLC_PRB_RESP_TIMEOUT;
1248
1249         wlc->usr_fragthresh = DOT11_DEFAULT_FRAG_LEN;
1250         for (i = 0; i < NFIFO; i++)
1251                 wlc->fragthresh[i] = DOT11_DEFAULT_FRAG_LEN;
1252         wlc->RTSThresh = DOT11_DEFAULT_RTS_LEN;
1253
1254         /* default rate fallback retry limits */
1255         wlc->SFBL = RETRY_SHORT_FB;
1256         wlc->LFBL = RETRY_LONG_FB;
1257
1258         /* default mac retry limits */
1259         wlc->SRL = RETRY_SHORT_DEF;
1260         wlc->LRL = RETRY_LONG_DEF;
1261
1262         /* Set flag to indicate that hw keys should be used when available. */
1263         wlc->wsec_swkeys = false;
1264
1265         /* init the 4 static WEP default keys */
1266         for (i = 0; i < WSEC_MAX_DEFAULT_KEYS; i++) {
1267                 wlc->wsec_keys[i] = wlc->wsec_def_keys[i];
1268                 wlc->wsec_keys[i]->idx = (u8) i;
1269         }
1270
1271         /* WME QoS mode is Auto by default */
1272         wlc->pub->_wme = AUTO;
1273
1274 #ifdef BCMSDIODEV_ENABLED
1275         wlc->pub->_priofc = true;       /* enable priority flow control for sdio dongle */
1276 #endif
1277
1278         wlc->pub->_ampdu = AMPDU_AGG_HOST;
1279         wlc->pub->bcmerror = 0;
1280         wlc->pub->_coex = ON;
1281
1282         /* initialize mpc delay */
1283         wlc->mpc_delay_off = wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
1284 }
1285
1286 static bool wlc_state_bmac_sync(struct wlc_info *wlc)
1287 {
1288         wlc_bmac_state_t state_bmac;
1289
1290         if (wlc_bmac_state_get(wlc->hw, &state_bmac) != 0)
1291                 return false;
1292
1293         wlc->machwcap = state_bmac.machwcap;
1294         wlc_protection_upd(wlc, WLC_PROT_N_PAM_OVR,
1295                            (s8) state_bmac.preamble_ovr);
1296
1297         return true;
1298 }
1299
1300 static uint wlc_attach_module(struct wlc_info *wlc)
1301 {
1302         uint err = 0;
1303         uint unit;
1304         unit = wlc->pub->unit;
1305
1306         wlc->asi = wlc_antsel_attach(wlc);
1307         if (wlc->asi == NULL) {
1308                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_antsel_attach "
1309                           "failed\n", unit);
1310                 err = 44;
1311                 goto fail;
1312         }
1313
1314         wlc->ampdu = wlc_ampdu_attach(wlc);
1315         if (wlc->ampdu == NULL) {
1316                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_ampdu_attach "
1317                           "failed\n", unit);
1318                 err = 50;
1319                 goto fail;
1320         }
1321
1322         if ((wlc_stf_attach(wlc) != 0)) {
1323                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_stf_attach "
1324                           "failed\n", unit);
1325                 err = 68;
1326                 goto fail;
1327         }
1328  fail:
1329         return err;
1330 }
1331
1332 struct wlc_pub *wlc_pub(void *wlc)
1333 {
1334         return ((struct wlc_info *) wlc)->pub;
1335 }
1336
1337 #define CHIP_SUPPORTS_11N(wlc)  1
1338
1339 /*
1340  * The common driver entry routine. Error codes should be unique
1341  */
1342 void *wlc_attach(struct brcms_info *wl, u16 vendor, u16 device, uint unit,
1343                  bool piomode, void *regsva, uint bustype, void *btparam,
1344                  uint *perr)
1345 {
1346         struct wlc_info *wlc;
1347         uint err = 0;
1348         uint j;
1349         struct wlc_pub *pub;
1350         uint n_disabled;
1351
1352         /* allocate struct wlc_info state and its substructures */
1353         wlc = (struct wlc_info *) wlc_attach_malloc(unit, &err, device);
1354         if (wlc == NULL)
1355                 goto fail;
1356         wlc->wiphy = wl->wiphy;
1357         pub = wlc->pub;
1358
1359 #if defined(BCMDBG)
1360         wlc_info_dbg = wlc;
1361 #endif
1362
1363         wlc->band = wlc->bandstate[0];
1364         wlc->core = wlc->corestate;
1365         wlc->wl = wl;
1366         pub->unit = unit;
1367         pub->_piomode = piomode;
1368         wlc->bandinit_pending = false;
1369
1370         /* populate struct wlc_info with default values  */
1371         wlc_info_init(wlc, unit);
1372
1373         /* update sta/ap related parameters */
1374         wlc_ap_upd(wlc);
1375
1376         /* 11n_disable nvram */
1377         n_disabled = getintvar(pub->vars, "11n_disable");
1378
1379         /*
1380          * low level attach steps(all hw accesses go
1381          * inside, no more in rest of the attach)
1382          */
1383         err = wlc_bmac_attach(wlc, vendor, device, unit, piomode, regsva,
1384                               bustype, btparam);
1385         if (err)
1386                 goto fail;
1387
1388         /* for some states, due to different info pointer(e,g, wlc, wlc_hw) or master/slave split,
1389          * HIGH driver(both monolithic and HIGH_ONLY) needs to sync states FROM BMAC portion driver
1390          */
1391         if (!wlc_state_bmac_sync(wlc)) {
1392                 err = 20;
1393                 goto fail;
1394         }
1395
1396         pub->phy_11ncapable = WLC_PHY_11N_CAP(wlc->band);
1397
1398         /* propagate *vars* from BMAC driver to high driver */
1399         wlc_bmac_copyfrom_vars(wlc->hw, &pub->vars, &wlc->vars_size);
1400
1401
1402         /* set maximum allowed duty cycle */
1403         wlc->tx_duty_cycle_ofdm =
1404             (u16) getintvar(pub->vars, "tx_duty_cycle_ofdm");
1405         wlc->tx_duty_cycle_cck =
1406             (u16) getintvar(pub->vars, "tx_duty_cycle_cck");
1407
1408         wlc_stf_phy_chain_calc(wlc);
1409
1410         /* txchain 1: txant 0, txchain 2: txant 1 */
1411         if (WLCISNPHY(wlc->band) && (wlc->stf->txstreams == 1))
1412                 wlc->stf->txant = wlc->stf->hw_txchain - 1;
1413
1414         /* push to BMAC driver */
1415         wlc_phy_stf_chain_init(wlc->band->pi, wlc->stf->hw_txchain,
1416                                wlc->stf->hw_rxchain);
1417
1418         /* pull up some info resulting from the low attach */
1419         {
1420                 int i;
1421                 for (i = 0; i < NFIFO; i++)
1422                         wlc->core->txavail[i] = wlc->hw->txavail[i];
1423         }
1424
1425         wlc_bmac_hw_etheraddr(wlc->hw, wlc->perm_etheraddr);
1426
1427         memcpy(&pub->cur_etheraddr, &wlc->perm_etheraddr, ETH_ALEN);
1428
1429         for (j = 0; j < NBANDS(wlc); j++) {
1430                 /* Use band 1 for single band 11a */
1431                 if (IS_SINGLEBAND_5G(wlc->deviceid))
1432                         j = BAND_5G_INDEX;
1433
1434                 wlc->band = wlc->bandstate[j];
1435
1436                 if (!wlc_attach_stf_ant_init(wlc)) {
1437                         err = 24;
1438                         goto fail;
1439                 }
1440
1441                 /* default contention windows size limits */
1442                 wlc->band->CWmin = APHY_CWMIN;
1443                 wlc->band->CWmax = PHY_CWMAX;
1444
1445                 /* init gmode value */
1446                 if (BAND_2G(wlc->band->bandtype)) {
1447                         wlc->band->gmode = GMODE_AUTO;
1448                         wlc_protection_upd(wlc, WLC_PROT_G_USER,
1449                                            wlc->band->gmode);
1450                 }
1451
1452                 /* init _n_enab supported mode */
1453                 if (WLC_PHY_11N_CAP(wlc->band) && CHIP_SUPPORTS_11N(wlc)) {
1454                         if (n_disabled & WLFEATURE_DISABLE_11N) {
1455                                 pub->_n_enab = OFF;
1456                                 wlc_protection_upd(wlc, WLC_PROT_N_USER, OFF);
1457                         } else {
1458                                 pub->_n_enab = SUPPORT_11N;
1459                                 wlc_protection_upd(wlc, WLC_PROT_N_USER,
1460                                                    ((pub->_n_enab ==
1461                                                      SUPPORT_11N) ? WL_11N_2x2 :
1462                                                     WL_11N_3x3));
1463                         }
1464                 }
1465
1466                 /* init per-band default rateset, depend on band->gmode */
1467                 wlc_default_rateset(wlc, &wlc->band->defrateset);
1468
1469                 /* fill in hw_rateset (used early by WLC_SET_RATESET) */
1470                 wlc_rateset_filter(&wlc->band->defrateset,
1471                                    &wlc->band->hw_rateset, false,
1472                                    WLC_RATES_CCK_OFDM, WLC_RATE_MASK,
1473                                    (bool) N_ENAB(wlc->pub));
1474         }
1475
1476         /* update antenna config due to wlc->stf->txant/txchain/ant_rx_ovr change */
1477         wlc_stf_phy_txant_upd(wlc);
1478
1479         /* attach each modules */
1480         err = wlc_attach_module(wlc);
1481         if (err != 0)
1482                 goto fail;
1483
1484         if (!wlc_timers_init(wlc, unit)) {
1485                 wiphy_err(wl->wiphy, "wl%d: %s: wlc_init_timer failed\n", unit,
1486                           __func__);
1487                 err = 32;
1488                 goto fail;
1489         }
1490
1491         /* depend on rateset, gmode */
1492         wlc->cmi = wlc_channel_mgr_attach(wlc);
1493         if (!wlc->cmi) {
1494                 wiphy_err(wl->wiphy, "wl%d: %s: wlc_channel_mgr_attach failed"
1495                           "\n", unit, __func__);
1496                 err = 33;
1497                 goto fail;
1498         }
1499
1500         /* init default when all parameters are ready, i.e. ->rateset */
1501         wlc_bss_default_init(wlc);
1502
1503         /*
1504          * Complete the wlc default state initializations..
1505          */
1506
1507         /* allocate our initial queue */
1508         wlc->pkt_queue = wlc_txq_alloc(wlc);
1509         if (wlc->pkt_queue == NULL) {
1510                 wiphy_err(wl->wiphy, "wl%d: %s: failed to malloc tx queue\n",
1511                           unit, __func__);
1512                 err = 100;
1513                 goto fail;
1514         }
1515
1516         wlc->bsscfg[0] = wlc->cfg;
1517         wlc->cfg->_idx = 0;
1518         wlc->cfg->wlc = wlc;
1519         pub->txmaxpkts = MAXTXPKTS;
1520
1521         wlc_wme_initparams_sta(wlc, &wlc->wme_param_ie);
1522
1523         wlc->mimoft = FT_HT;
1524         wlc->ht_cap.cap_info = HT_CAP;
1525         if (HT_ENAB(wlc->pub))
1526                 wlc->stf->ldpc = AUTO;
1527
1528         wlc->mimo_40txbw = AUTO;
1529         wlc->ofdm_40txbw = AUTO;
1530         wlc->cck_40txbw = AUTO;
1531         wlc_update_mimo_band_bwcap(wlc, WLC_N_BW_20IN2G_40IN5G);
1532
1533         /* Set default values of SGI */
1534         if (WLC_SGI_CAP_PHY(wlc)) {
1535                 wlc_ht_update_sgi_rx(wlc, (WLC_N_SGI_20 | WLC_N_SGI_40));
1536                 wlc->sgi_tx = AUTO;
1537         } else if (WLCISSSLPNPHY(wlc->band)) {
1538                 wlc_ht_update_sgi_rx(wlc, (WLC_N_SGI_20 | WLC_N_SGI_40));
1539                 wlc->sgi_tx = AUTO;
1540         } else {
1541                 wlc_ht_update_sgi_rx(wlc, 0);
1542                 wlc->sgi_tx = OFF;
1543         }
1544
1545         /* *******nvram 11n config overrides Start ********* */
1546
1547         /* apply the sgi override from nvram conf */
1548         if (n_disabled & WLFEATURE_DISABLE_11N_SGI_TX)
1549                 wlc->sgi_tx = OFF;
1550
1551         if (n_disabled & WLFEATURE_DISABLE_11N_SGI_RX)
1552                 wlc_ht_update_sgi_rx(wlc, 0);
1553
1554         /* apply the stbc override from nvram conf */
1555         if (n_disabled & WLFEATURE_DISABLE_11N_STBC_TX) {
1556                 wlc->bandstate[BAND_2G_INDEX]->band_stf_stbc_tx = OFF;
1557                 wlc->bandstate[BAND_5G_INDEX]->band_stf_stbc_tx = OFF;
1558                 wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_TX_STBC;
1559         }
1560         if (n_disabled & WLFEATURE_DISABLE_11N_STBC_RX)
1561                 wlc_stf_stbc_rx_set(wlc, HT_CAP_RX_STBC_NO);
1562
1563         /* apply the GF override from nvram conf */
1564         if (n_disabled & WLFEATURE_DISABLE_11N_GF)
1565                 wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_GRN_FLD;
1566
1567         /* initialize radio_mpc_disable according to wlc->mpc */
1568         wlc_radio_mpc_upd(wlc);
1569
1570         if ((wlc->pub->sih->chip) == BCM43235_CHIP_ID) {
1571                 if ((getintvar(wlc->pub->vars, "aa2g") == 7) ||
1572                     (getintvar(wlc->pub->vars, "aa5g") == 7)) {
1573                         wlc_bmac_antsel_set(wlc->hw, 1);
1574                 }
1575         } else {
1576                 wlc_bmac_antsel_set(wlc->hw, wlc->asi->antsel_avail);
1577         }
1578
1579         if (perr)
1580                 *perr = 0;
1581
1582         return (void *)wlc;
1583
1584  fail:
1585         wiphy_err(wl->wiphy, "wl%d: %s: failed with err %d\n",
1586                   unit, __func__, err);
1587         if (wlc)
1588                 wlc_detach(wlc);
1589
1590         if (perr)
1591                 *perr = err;
1592         return NULL;
1593 }
1594
1595 static void wlc_attach_antgain_init(struct wlc_info *wlc)
1596 {
1597         uint unit;
1598         unit = wlc->pub->unit;
1599
1600         if ((wlc->band->antgain == -1) && (wlc->pub->sromrev == 1)) {
1601                 /* default antenna gain for srom rev 1 is 2 dBm (8 qdbm) */
1602                 wlc->band->antgain = 8;
1603         } else if (wlc->band->antgain == -1) {
1604                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid antennas available in"
1605                           " srom, using 2dB\n", unit, __func__);
1606                 wlc->band->antgain = 8;
1607         } else {
1608                 s8 gain, fract;
1609                 /* Older sroms specified gain in whole dbm only.  In order
1610                  * be able to specify qdbm granularity and remain backward compatible
1611                  * the whole dbms are now encoded in only low 6 bits and remaining qdbms
1612                  * are encoded in the hi 2 bits. 6 bit signed number ranges from
1613                  * -32 - 31. Examples: 0x1 = 1 db,
1614                  * 0xc1 = 1.75 db (1 + 3 quarters),
1615                  * 0x3f = -1 (-1 + 0 quarters),
1616                  * 0x7f = -.75 (-1 in low 6 bits + 1 quarters in hi 2 bits) = -3 qdbm.
1617                  * 0xbf = -.50 (-1 in low 6 bits + 2 quarters in hi 2 bits) = -2 qdbm.
1618                  */
1619                 gain = wlc->band->antgain & 0x3f;
1620                 gain <<= 2;     /* Sign extend */
1621                 gain >>= 2;
1622                 fract = (wlc->band->antgain & 0xc0) >> 6;
1623                 wlc->band->antgain = 4 * gain + fract;
1624         }
1625 }
1626
1627 static bool wlc_attach_stf_ant_init(struct wlc_info *wlc)
1628 {
1629         int aa;
1630         uint unit;
1631         char *vars;
1632         int bandtype;
1633
1634         unit = wlc->pub->unit;
1635         vars = wlc->pub->vars;
1636         bandtype = wlc->band->bandtype;
1637
1638         /* get antennas available */
1639         aa = (s8) getintvar(vars, (BAND_5G(bandtype) ? "aa5g" : "aa2g"));
1640         if (aa == 0)
1641                 aa = (s8) getintvar(vars,
1642                                       (BAND_5G(bandtype) ? "aa1" : "aa0"));
1643         if ((aa < 1) || (aa > 15)) {
1644                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid antennas available in"
1645                           " srom (0x%x), using 3\n", unit, __func__, aa);
1646                 aa = 3;
1647         }
1648
1649         /* reset the defaults if we have a single antenna */
1650         if (aa == 1) {
1651                 wlc->stf->ant_rx_ovr = ANT_RX_DIV_FORCE_0;
1652                 wlc->stf->txant = ANT_TX_FORCE_0;
1653         } else if (aa == 2) {
1654                 wlc->stf->ant_rx_ovr = ANT_RX_DIV_FORCE_1;
1655                 wlc->stf->txant = ANT_TX_FORCE_1;
1656         } else {
1657         }
1658
1659         /* Compute Antenna Gain */
1660         wlc->band->antgain =
1661             (s8) getintvar(vars, (BAND_5G(bandtype) ? "ag1" : "ag0"));
1662         wlc_attach_antgain_init(wlc);
1663
1664         return true;
1665 }
1666
1667
1668 static void wlc_timers_deinit(struct wlc_info *wlc)
1669 {
1670         /* free timer state */
1671         if (wlc->wdtimer) {
1672                 brcms_free_timer(wlc->wl, wlc->wdtimer);
1673                 wlc->wdtimer = NULL;
1674         }
1675         if (wlc->radio_timer) {
1676                 brcms_free_timer(wlc->wl, wlc->radio_timer);
1677                 wlc->radio_timer = NULL;
1678         }
1679 }
1680
1681 static void wlc_detach_module(struct wlc_info *wlc)
1682 {
1683         if (wlc->asi) {
1684                 wlc_antsel_detach(wlc->asi);
1685                 wlc->asi = NULL;
1686         }
1687
1688         if (wlc->ampdu) {
1689                 wlc_ampdu_detach(wlc->ampdu);
1690                 wlc->ampdu = NULL;
1691         }
1692
1693         wlc_stf_detach(wlc);
1694 }
1695
1696 /*
1697  * Return a count of the number of driver callbacks still pending.
1698  *
1699  * General policy is that wlc_detach can only dealloc/free software states. It can NOT
1700  *  touch hardware registers since the d11core may be in reset and clock may not be available.
1701  *    One exception is sb register access, which is possible if crystal is turned on
1702  * After "down" state, driver should avoid software timer with the exception of radio_monitor.
1703  */
1704 uint wlc_detach(struct wlc_info *wlc)
1705 {
1706         uint callbacks = 0;
1707
1708         if (wlc == NULL)
1709                 return 0;
1710
1711         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
1712
1713         callbacks += wlc_bmac_detach(wlc);
1714
1715         /* delete software timers */
1716         if (!wlc_radio_monitor_stop(wlc))
1717                 callbacks++;
1718
1719         wlc_channel_mgr_detach(wlc->cmi);
1720
1721         wlc_timers_deinit(wlc);
1722
1723         wlc_detach_module(wlc);
1724
1725
1726         while (wlc->tx_queues != NULL)
1727                 wlc_txq_free(wlc, wlc->tx_queues);
1728
1729         wlc_detach_mfree(wlc);
1730         return callbacks;
1731 }
1732
1733 /* update state that depends on the current value of "ap" */
1734 void wlc_ap_upd(struct wlc_info *wlc)
1735 {
1736         if (AP_ENAB(wlc->pub))
1737                 wlc->PLCPHdr_override = WLC_PLCP_AUTO;  /* AP: short not allowed, but not enforced */
1738         else
1739                 wlc->PLCPHdr_override = WLC_PLCP_SHORT; /* STA-BSS; short capable */
1740
1741         /* fixup mpc */
1742         wlc->mpc = true;
1743 }
1744
1745 /* read hwdisable state and propagate to wlc flag */
1746 static void wlc_radio_hwdisable_upd(struct wlc_info *wlc)
1747 {
1748         if (wlc->pub->wlfeatureflag & WL_SWFL_NOHWRADIO || wlc->pub->hw_off)
1749                 return;
1750
1751         if (wlc_bmac_radio_read_hwdisabled(wlc->hw)) {
1752                 mboolset(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE);
1753         } else {
1754                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE);
1755         }
1756 }
1757
1758 /* return true if Minimum Power Consumption should be entered, false otherwise */
1759 bool wlc_is_non_delay_mpc(struct wlc_info *wlc)
1760 {
1761         return false;
1762 }
1763
1764 bool wlc_ismpc(struct wlc_info *wlc)
1765 {
1766         return (wlc->mpc_delay_off == 0) && (wlc_is_non_delay_mpc(wlc));
1767 }
1768
1769 void wlc_radio_mpc_upd(struct wlc_info *wlc)
1770 {
1771         bool mpc_radio, radio_state;
1772
1773         /*
1774          * Clear the WL_RADIO_MPC_DISABLE bit when mpc feature is disabled
1775          * in case the WL_RADIO_MPC_DISABLE bit was set. Stop the radio
1776          * monitor also when WL_RADIO_MPC_DISABLE is the only reason that
1777          * the radio is going down.
1778          */
1779         if (!wlc->mpc) {
1780                 if (!wlc->pub->radio_disabled)
1781                         return;
1782                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE);
1783                 wlc_radio_upd(wlc);
1784                 if (!wlc->pub->radio_disabled)
1785                         wlc_radio_monitor_stop(wlc);
1786                 return;
1787         }
1788
1789         /*
1790          * sync ismpc logic with WL_RADIO_MPC_DISABLE bit in wlc->pub->radio_disabled
1791          * to go ON, always call radio_upd synchronously
1792          * to go OFF, postpone radio_upd to later when context is safe(e.g. watchdog)
1793          */
1794         radio_state =
1795             (mboolisset(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE) ? OFF :
1796              ON);
1797         mpc_radio = (wlc_ismpc(wlc) == true) ? OFF : ON;
1798
1799         if (radio_state == ON && mpc_radio == OFF)
1800                 wlc->mpc_delay_off = wlc->mpc_dlycnt;
1801         else if (radio_state == OFF && mpc_radio == ON) {
1802                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE);
1803                 wlc_radio_upd(wlc);
1804                 if (wlc->mpc_offcnt < WLC_MPC_THRESHOLD) {
1805                         wlc->mpc_dlycnt = WLC_MPC_MAX_DELAYCNT;
1806                 } else
1807                         wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
1808                 wlc->mpc_dur += OSL_SYSUPTIME() - wlc->mpc_laston_ts;
1809         }
1810         /* Below logic is meant to capture the transition from mpc off to mpc on for reasons
1811          * other than wlc->mpc_delay_off keeping the mpc off. In that case reset
1812          * wlc->mpc_delay_off to wlc->mpc_dlycnt, so that we restart the countdown of mpc_delay_off
1813          */
1814         if ((wlc->prev_non_delay_mpc == false) &&
1815             (wlc_is_non_delay_mpc(wlc) == true) && wlc->mpc_delay_off) {
1816                 wlc->mpc_delay_off = wlc->mpc_dlycnt;
1817         }
1818         wlc->prev_non_delay_mpc = wlc_is_non_delay_mpc(wlc);
1819 }
1820
1821 /*
1822  * centralized radio disable/enable function,
1823  * invoke radio enable/disable after updating hwradio status
1824  */
1825 static void wlc_radio_upd(struct wlc_info *wlc)
1826 {
1827         if (wlc->pub->radio_disabled) {
1828                 wlc_radio_disable(wlc);
1829         } else {
1830                 wlc_radio_enable(wlc);
1831         }
1832 }
1833
1834 /* maintain LED behavior in down state */
1835 static void wlc_down_led_upd(struct wlc_info *wlc)
1836 {
1837         /* maintain LEDs while in down state, turn on sbclk if not available yet */
1838         /* turn on sbclk if necessary */
1839         if (!AP_ENAB(wlc->pub)) {
1840                 wlc_pllreq(wlc, true, WLC_PLLREQ_FLIP);
1841
1842                 wlc_pllreq(wlc, false, WLC_PLLREQ_FLIP);
1843         }
1844 }
1845
1846 /* update hwradio status and return it */
1847 bool wlc_check_radio_disabled(struct wlc_info *wlc)
1848 {
1849         wlc_radio_hwdisable_upd(wlc);
1850
1851         return mboolisset(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE) ? true : false;
1852 }
1853
1854 void wlc_radio_disable(struct wlc_info *wlc)
1855 {
1856         if (!wlc->pub->up) {
1857                 wlc_down_led_upd(wlc);
1858                 return;
1859         }
1860
1861         wlc_radio_monitor_start(wlc);
1862         brcms_down(wlc->wl);
1863 }
1864
1865 static void wlc_radio_enable(struct wlc_info *wlc)
1866 {
1867         if (wlc->pub->up)
1868                 return;
1869
1870         if (DEVICEREMOVED(wlc))
1871                 return;
1872
1873         brcms_up(wlc->wl);
1874 }
1875
1876 /* periodical query hw radio button while driver is "down" */
1877 static void wlc_radio_timer(void *arg)
1878 {
1879         struct wlc_info *wlc = (struct wlc_info *) arg;
1880
1881         if (DEVICEREMOVED(wlc)) {
1882                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
1883                         __func__);
1884                 brcms_down(wlc->wl);
1885                 return;
1886         }
1887
1888         /* cap mpc off count */
1889         if (wlc->mpc_offcnt < WLC_MPC_MAX_DELAYCNT)
1890                 wlc->mpc_offcnt++;
1891
1892         wlc_radio_hwdisable_upd(wlc);
1893         wlc_radio_upd(wlc);
1894 }
1895
1896 static bool wlc_radio_monitor_start(struct wlc_info *wlc)
1897 {
1898         /* Don't start the timer if HWRADIO feature is disabled */
1899         if (wlc->radio_monitor || (wlc->pub->wlfeatureflag & WL_SWFL_NOHWRADIO))
1900                 return true;
1901
1902         wlc->radio_monitor = true;
1903         wlc_pllreq(wlc, true, WLC_PLLREQ_RADIO_MON);
1904         brcms_add_timer(wlc->wl, wlc->radio_timer, TIMER_INTERVAL_RADIOCHK,
1905                         true);
1906         return true;
1907 }
1908
1909 bool wlc_radio_monitor_stop(struct wlc_info *wlc)
1910 {
1911         if (!wlc->radio_monitor)
1912                 return true;
1913
1914         wlc->radio_monitor = false;
1915         wlc_pllreq(wlc, false, WLC_PLLREQ_RADIO_MON);
1916         return brcms_del_timer(wlc->wl, wlc->radio_timer);
1917 }
1918
1919 static void wlc_watchdog_by_timer(void *arg)
1920 {
1921         wlc_watchdog(arg);
1922 }
1923
1924 /* common watchdog code */
1925 static void wlc_watchdog(void *arg)
1926 {
1927         struct wlc_info *wlc = (struct wlc_info *) arg;
1928         int i;
1929         struct wlc_bsscfg *cfg;
1930
1931         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
1932
1933         if (!wlc->pub->up)
1934                 return;
1935
1936         if (DEVICEREMOVED(wlc)) {
1937                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
1938                           __func__);
1939                 brcms_down(wlc->wl);
1940                 return;
1941         }
1942
1943         /* increment second count */
1944         wlc->pub->now++;
1945
1946         /* delay radio disable */
1947         if (wlc->mpc_delay_off) {
1948                 if (--wlc->mpc_delay_off == 0) {
1949                         mboolset(wlc->pub->radio_disabled,
1950                                  WL_RADIO_MPC_DISABLE);
1951                         if (wlc->mpc && wlc_ismpc(wlc))
1952                                 wlc->mpc_offcnt = 0;
1953                         wlc->mpc_laston_ts = OSL_SYSUPTIME();
1954                 }
1955         }
1956
1957         /* mpc sync */
1958         wlc_radio_mpc_upd(wlc);
1959         /* radio sync: sw/hw/mpc --> radio_disable/radio_enable */
1960         wlc_radio_hwdisable_upd(wlc);
1961         wlc_radio_upd(wlc);
1962         /* if radio is disable, driver may be down, quit here */
1963         if (wlc->pub->radio_disabled)
1964                 return;
1965
1966         wlc_bmac_watchdog(wlc);
1967
1968         /* occasionally sample mac stat counters to detect 16-bit counter wrap */
1969         if ((wlc->pub->now % SW_TIMER_MAC_STAT_UPD) == 0)
1970                 wlc_statsupd(wlc);
1971
1972         /* Manage TKIP countermeasures timers */
1973         FOREACH_BSS(wlc, i, cfg) {
1974                 if (cfg->tk_cm_dt) {
1975                         cfg->tk_cm_dt--;
1976                 }
1977                 if (cfg->tk_cm_bt) {
1978                         cfg->tk_cm_bt--;
1979                 }
1980         }
1981
1982         /* Call any registered watchdog handlers */
1983         for (i = 0; i < WLC_MAXMODULES; i++) {
1984                 if (wlc->modulecb[i].watchdog_fn)
1985                         wlc->modulecb[i].watchdog_fn(wlc->modulecb[i].hdl);
1986         }
1987
1988         if (WLCISNPHY(wlc->band) && !wlc->pub->tempsense_disable &&
1989             ((wlc->pub->now - wlc->tempsense_lasttime) >=
1990              WLC_TEMPSENSE_PERIOD)) {
1991                 wlc->tempsense_lasttime = wlc->pub->now;
1992                 wlc_tempsense_upd(wlc);
1993         }
1994 }
1995
1996 /* make interface operational */
1997 int wlc_up(struct wlc_info *wlc)
1998 {
1999         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
2000
2001         /* HW is turned off so don't try to access it */
2002         if (wlc->pub->hw_off || DEVICEREMOVED(wlc))
2003                 return -ENOMEDIUM;
2004
2005         if (!wlc->pub->hw_up) {
2006                 wlc_bmac_hw_up(wlc->hw);
2007                 wlc->pub->hw_up = true;
2008         }
2009
2010         if ((wlc->pub->boardflags & BFL_FEM)
2011             && (wlc->pub->sih->chip == BCM4313_CHIP_ID)) {
2012                 if (wlc->pub->boardrev >= 0x1250
2013                     && (wlc->pub->boardflags & BFL_FEM_BT)) {
2014                         wlc_mhf(wlc, MHF5, MHF5_4313_GPIOCTRL,
2015                                 MHF5_4313_GPIOCTRL, WLC_BAND_ALL);
2016                 } else {
2017                         wlc_mhf(wlc, MHF4, MHF4_EXTPA_ENABLE, MHF4_EXTPA_ENABLE,
2018                                 WLC_BAND_ALL);
2019                 }
2020         }
2021
2022         /*
2023          * Need to read the hwradio status here to cover the case where the system
2024          * is loaded with the hw radio disabled. We do not want to bring the driver up in this case.
2025          * if radio is disabled, abort up, lower power, start radio timer and return 0(for NDIS)
2026          * don't call radio_update to avoid looping wlc_up.
2027          *
2028          * wlc_bmac_up_prep() returns either 0 or -BCME_RADIOOFF only
2029          */
2030         if (!wlc->pub->radio_disabled) {
2031                 int status = wlc_bmac_up_prep(wlc->hw);
2032                 if (status == -ENOMEDIUM) {
2033                         if (!mboolisset
2034                             (wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE)) {
2035                                 int idx;
2036                                 struct wlc_bsscfg *bsscfg;
2037                                 mboolset(wlc->pub->radio_disabled,
2038                                          WL_RADIO_HW_DISABLE);
2039
2040                                 FOREACH_BSS(wlc, idx, bsscfg) {
2041                                         if (!BSSCFG_STA(bsscfg)
2042                                             || !bsscfg->enable || !bsscfg->BSS)
2043                                                 continue;
2044                                         wiphy_err(wlc->wiphy, "wl%d.%d: wlc_up"
2045                                                   ": rfdisable -> "
2046                                                   "wlc_bsscfg_disable()\n",
2047                                                    wlc->pub->unit, idx);
2048                                 }
2049                         }
2050                 }
2051         }
2052
2053         if (wlc->pub->radio_disabled) {
2054                 wlc_radio_monitor_start(wlc);
2055                 return 0;
2056         }
2057
2058         /* wlc_bmac_up_prep has done wlc_corereset(). so clk is on, set it */
2059         wlc->clk = true;
2060
2061         wlc_radio_monitor_stop(wlc);
2062
2063         /* Set EDCF hostflags */
2064         if (EDCF_ENAB(wlc->pub)) {
2065                 wlc_mhf(wlc, MHF1, MHF1_EDCF, MHF1_EDCF, WLC_BAND_ALL);
2066         } else {
2067                 wlc_mhf(wlc, MHF1, MHF1_EDCF, 0, WLC_BAND_ALL);
2068         }
2069
2070         if (WLC_WAR16165(wlc))
2071                 wlc_mhf(wlc, MHF2, MHF2_PCISLOWCLKWAR, MHF2_PCISLOWCLKWAR,
2072                         WLC_BAND_ALL);
2073
2074         brcms_init(wlc->wl);
2075         wlc->pub->up = true;
2076
2077         if (wlc->bandinit_pending) {
2078                 wlc_suspend_mac_and_wait(wlc);
2079                 wlc_set_chanspec(wlc, wlc->default_bss->chanspec);
2080                 wlc->bandinit_pending = false;
2081                 wlc_enable_mac(wlc);
2082         }
2083
2084         wlc_bmac_up_finish(wlc->hw);
2085
2086         /* other software states up after ISR is running */
2087         /* start APs that were to be brought up but are not up  yet */
2088         /* if (AP_ENAB(wlc->pub)) wlc_restart_ap(wlc->ap); */
2089
2090         /* Program the TX wme params with the current settings */
2091         wlc_wme_retries_write(wlc);
2092
2093         /* start one second watchdog timer */
2094         brcms_add_timer(wlc->wl, wlc->wdtimer, TIMER_INTERVAL_WATCHDOG, true);
2095         wlc->WDarmed = true;
2096
2097         /* ensure antenna config is up to date */
2098         wlc_stf_phy_txant_upd(wlc);
2099         /* ensure LDPC config is in sync */
2100         wlc_ht_update_ldpc(wlc, wlc->stf->ldpc);
2101
2102         return 0;
2103 }
2104
2105 /* Initialize the base precedence map for dequeueing from txq based on WME settings */
2106 static void wlc_tx_prec_map_init(struct wlc_info *wlc)
2107 {
2108         wlc->tx_prec_map = WLC_PREC_BMP_ALL;
2109         memset(wlc->fifo2prec_map, 0, NFIFO * sizeof(u16));
2110
2111         /* For non-WME, both fifos have overlapping MAXPRIO. So just disable all precedences
2112          * if either is full.
2113          */
2114         if (!EDCF_ENAB(wlc->pub)) {
2115                 wlc->fifo2prec_map[TX_DATA_FIFO] = WLC_PREC_BMP_ALL;
2116                 wlc->fifo2prec_map[TX_CTL_FIFO] = WLC_PREC_BMP_ALL;
2117         } else {
2118                 wlc->fifo2prec_map[TX_AC_BK_FIFO] = WLC_PREC_BMP_AC_BK;
2119                 wlc->fifo2prec_map[TX_AC_BE_FIFO] = WLC_PREC_BMP_AC_BE;
2120                 wlc->fifo2prec_map[TX_AC_VI_FIFO] = WLC_PREC_BMP_AC_VI;
2121                 wlc->fifo2prec_map[TX_AC_VO_FIFO] = WLC_PREC_BMP_AC_VO;
2122         }
2123 }
2124
2125 static uint wlc_down_del_timer(struct wlc_info *wlc)
2126 {
2127         uint callbacks = 0;
2128
2129         return callbacks;
2130 }
2131
2132 /*
2133  * Mark the interface nonoperational, stop the software mechanisms,
2134  * disable the hardware, free any transient buffer state.
2135  * Return a count of the number of driver callbacks still pending.
2136  */
2137 uint wlc_down(struct wlc_info *wlc)
2138 {
2139
2140         uint callbacks = 0;
2141         int i;
2142         bool dev_gone = false;
2143         struct wlc_txq_info *qi;
2144
2145         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
2146
2147         /* check if we are already in the going down path */
2148         if (wlc->going_down) {
2149                 wiphy_err(wlc->wiphy, "wl%d: %s: Driver going down so return"
2150                           "\n", wlc->pub->unit, __func__);
2151                 return 0;
2152         }
2153         if (!wlc->pub->up)
2154                 return callbacks;
2155
2156         /* in between, mpc could try to bring down again.. */
2157         wlc->going_down = true;
2158
2159         callbacks += wlc_bmac_down_prep(wlc->hw);
2160
2161         dev_gone = DEVICEREMOVED(wlc);
2162
2163         /* Call any registered down handlers */
2164         for (i = 0; i < WLC_MAXMODULES; i++) {
2165                 if (wlc->modulecb[i].down_fn)
2166                         callbacks +=
2167                             wlc->modulecb[i].down_fn(wlc->modulecb[i].hdl);
2168         }
2169
2170         /* cancel the watchdog timer */
2171         if (wlc->WDarmed) {
2172                 if (!brcms_del_timer(wlc->wl, wlc->wdtimer))
2173                         callbacks++;
2174                 wlc->WDarmed = false;
2175         }
2176         /* cancel all other timers */
2177         callbacks += wlc_down_del_timer(wlc);
2178
2179         wlc->pub->up = false;
2180
2181         wlc_phy_mute_upd(wlc->band->pi, false, PHY_MUTE_ALL);
2182
2183         /* clear txq flow control */
2184         wlc_txflowcontrol_reset(wlc);
2185
2186         /* flush tx queues */
2187         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
2188                 bcm_pktq_flush(&qi->q, true, NULL, NULL);
2189         }
2190
2191         callbacks += wlc_bmac_down_finish(wlc->hw);
2192
2193         /* wlc_bmac_down_finish has done wlc_coredisable(). so clk is off */
2194         wlc->clk = false;
2195
2196         wlc->going_down = false;
2197         return callbacks;
2198 }
2199
2200 /* Set the current gmode configuration */
2201 int wlc_set_gmode(struct wlc_info *wlc, u8 gmode, bool config)
2202 {
2203         int ret = 0;
2204         uint i;
2205         wlc_rateset_t rs;
2206         /* Default to 54g Auto */
2207         s8 shortslot = WLC_SHORTSLOT_AUTO;      /* Advertise and use shortslot (-1/0/1 Auto/Off/On) */
2208         bool shortslot_restrict = false;        /* Restrict association to stations that support shortslot
2209                                                  */
2210         bool ofdm_basic = false;        /* Make 6, 12, and 24 basic rates */
2211         int preamble = WLC_PLCP_LONG;   /* Advertise and use short preambles (-1/0/1 Auto/Off/On) */
2212         bool preamble_restrict = false; /* Restrict association to stations that support short
2213                                          * preambles
2214                                          */
2215         struct wlcband *band;
2216
2217         /* if N-support is enabled, allow Gmode set as long as requested
2218          * Gmode is not GMODE_LEGACY_B
2219          */
2220         if (N_ENAB(wlc->pub) && gmode == GMODE_LEGACY_B)
2221                 return -ENOTSUPP;
2222
2223         /* verify that we are dealing with 2G band and grab the band pointer */
2224         if (wlc->band->bandtype == WLC_BAND_2G)
2225                 band = wlc->band;
2226         else if ((NBANDS(wlc) > 1) &&
2227                  (wlc->bandstate[OTHERBANDUNIT(wlc)]->bandtype == WLC_BAND_2G))
2228                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
2229         else
2230                 return -EINVAL;
2231
2232         /* Legacy or bust when no OFDM is supported by regulatory */
2233         if ((wlc_channel_locale_flags_in_band(wlc->cmi, band->bandunit) &
2234              WLC_NO_OFDM) && (gmode != GMODE_LEGACY_B))
2235                 return -EINVAL;
2236
2237         /* update configuration value */
2238         if (config == true)
2239                 wlc_protection_upd(wlc, WLC_PROT_G_USER, gmode);
2240
2241         /* Clear supported rates filter */
2242         memset(&wlc->sup_rates_override, 0, sizeof(wlc_rateset_t));
2243
2244         /* Clear rateset override */
2245         memset(&rs, 0, sizeof(wlc_rateset_t));
2246
2247         switch (gmode) {
2248         case GMODE_LEGACY_B:
2249                 shortslot = WLC_SHORTSLOT_OFF;
2250                 wlc_rateset_copy(&gphy_legacy_rates, &rs);
2251
2252                 break;
2253
2254         case GMODE_LRS:
2255                 if (AP_ENAB(wlc->pub))
2256                         wlc_rateset_copy(&cck_rates, &wlc->sup_rates_override);
2257                 break;
2258
2259         case GMODE_AUTO:
2260                 /* Accept defaults */
2261                 break;
2262
2263         case GMODE_ONLY:
2264                 ofdm_basic = true;
2265                 preamble = WLC_PLCP_SHORT;
2266                 preamble_restrict = true;
2267                 break;
2268
2269         case GMODE_PERFORMANCE:
2270                 if (AP_ENAB(wlc->pub))  /* Put all rates into the Supported Rates element */
2271                         wlc_rateset_copy(&cck_ofdm_rates,
2272                                          &wlc->sup_rates_override);
2273
2274                 shortslot = WLC_SHORTSLOT_ON;
2275                 shortslot_restrict = true;
2276                 ofdm_basic = true;
2277                 preamble = WLC_PLCP_SHORT;
2278                 preamble_restrict = true;
2279                 break;
2280
2281         default:
2282                 /* Error */
2283                 wiphy_err(wlc->wiphy, "wl%d: %s: invalid gmode %d\n",
2284                           wlc->pub->unit, __func__, gmode);
2285                 return -ENOTSUPP;
2286         }
2287
2288         /*
2289          * If we are switching to gmode == GMODE_LEGACY_B,
2290          * clean up rate info that may refer to OFDM rates.
2291          */
2292         if ((gmode == GMODE_LEGACY_B) && (band->gmode != GMODE_LEGACY_B)) {
2293                 band->gmode = gmode;
2294                 if (band->rspec_override && !IS_CCK(band->rspec_override)) {
2295                         band->rspec_override = 0;
2296                         wlc_reprate_init(wlc);
2297                 }
2298                 if (band->mrspec_override && !IS_CCK(band->mrspec_override)) {
2299                         band->mrspec_override = 0;
2300                 }
2301         }
2302
2303         band->gmode = gmode;
2304
2305         wlc->shortslot_override = shortslot;
2306
2307         if (AP_ENAB(wlc->pub)) {
2308                 /* wlc->ap->shortslot_restrict = shortslot_restrict; */
2309                 wlc->PLCPHdr_override =
2310                     (preamble !=
2311                      WLC_PLCP_LONG) ? WLC_PLCP_SHORT : WLC_PLCP_AUTO;
2312         }
2313
2314         if ((AP_ENAB(wlc->pub) && preamble != WLC_PLCP_LONG)
2315             || preamble == WLC_PLCP_SHORT)
2316                 wlc->default_bss->capability |= WLAN_CAPABILITY_SHORT_PREAMBLE;
2317         else
2318                 wlc->default_bss->capability &= ~WLAN_CAPABILITY_SHORT_PREAMBLE;
2319
2320         /* Update shortslot capability bit for AP and IBSS */
2321         if ((AP_ENAB(wlc->pub) && shortslot == WLC_SHORTSLOT_AUTO) ||
2322             shortslot == WLC_SHORTSLOT_ON)
2323                 wlc->default_bss->capability |= WLAN_CAPABILITY_SHORT_SLOT_TIME;
2324         else
2325                 wlc->default_bss->capability &=
2326                                         ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
2327
2328         /* Use the default 11g rateset */
2329         if (!rs.count)
2330                 wlc_rateset_copy(&cck_ofdm_rates, &rs);
2331
2332         if (ofdm_basic) {
2333                 for (i = 0; i < rs.count; i++) {
2334                         if (rs.rates[i] == WLC_RATE_6M
2335                             || rs.rates[i] == WLC_RATE_12M
2336                             || rs.rates[i] == WLC_RATE_24M)
2337                                 rs.rates[i] |= WLC_RATE_FLAG;
2338                 }
2339         }
2340
2341         /* Set default bss rateset */
2342         wlc->default_bss->rateset.count = rs.count;
2343         memcpy(wlc->default_bss->rateset.rates, rs.rates, 
2344                sizeof(wlc->default_bss->rateset.rates));
2345
2346         return ret;
2347 }
2348
2349 static int wlc_nmode_validate(struct wlc_info *wlc, s32 nmode)
2350 {
2351         int err = 0;
2352
2353         switch (nmode) {
2354
2355         case OFF:
2356                 break;
2357
2358         case AUTO:
2359         case WL_11N_2x2:
2360         case WL_11N_3x3:
2361                 if (!(WLC_PHY_11N_CAP(wlc->band)))
2362                         err = -EINVAL;
2363                 break;
2364
2365         default:
2366                 err = -EINVAL;
2367                 break;
2368         }
2369
2370         return err;
2371 }
2372
2373 int wlc_set_nmode(struct wlc_info *wlc, s32 nmode)
2374 {
2375         uint i;
2376         int err;
2377
2378         err = wlc_nmode_validate(wlc, nmode);
2379         if (err)
2380                 return err;
2381
2382         switch (nmode) {
2383         case OFF:
2384                 wlc->pub->_n_enab = OFF;
2385                 wlc->default_bss->flags &= ~WLC_BSS_HT;
2386                 /* delete the mcs rates from the default and hw ratesets */
2387                 wlc_rateset_mcs_clear(&wlc->default_bss->rateset);
2388                 for (i = 0; i < NBANDS(wlc); i++) {
2389                         memset(wlc->bandstate[i]->hw_rateset.mcs, 0,
2390                                MCSSET_LEN);
2391                         if (IS_MCS(wlc->band->rspec_override)) {
2392                                 wlc->bandstate[i]->rspec_override = 0;
2393                                 wlc_reprate_init(wlc);
2394                         }
2395                         if (IS_MCS(wlc->band->mrspec_override))
2396                                 wlc->bandstate[i]->mrspec_override = 0;
2397                 }
2398                 break;
2399
2400         case AUTO:
2401                 if (wlc->stf->txstreams == WL_11N_3x3)
2402                         nmode = WL_11N_3x3;
2403                 else
2404                         nmode = WL_11N_2x2;
2405         case WL_11N_2x2:
2406         case WL_11N_3x3:
2407                 /* force GMODE_AUTO if NMODE is ON */
2408                 wlc_set_gmode(wlc, GMODE_AUTO, true);
2409                 if (nmode == WL_11N_3x3)
2410                         wlc->pub->_n_enab = SUPPORT_HT;
2411                 else
2412                         wlc->pub->_n_enab = SUPPORT_11N;
2413                 wlc->default_bss->flags |= WLC_BSS_HT;
2414                 /* add the mcs rates to the default and hw ratesets */
2415                 wlc_rateset_mcs_build(&wlc->default_bss->rateset,
2416                                       wlc->stf->txstreams);
2417                 for (i = 0; i < NBANDS(wlc); i++)
2418                         memcpy(wlc->bandstate[i]->hw_rateset.mcs,
2419                                wlc->default_bss->rateset.mcs, MCSSET_LEN);
2420                 break;
2421
2422         default:
2423                 break;
2424         }
2425
2426         return err;
2427 }
2428
2429 static int wlc_set_rateset(struct wlc_info *wlc, wlc_rateset_t *rs_arg)
2430 {
2431         wlc_rateset_t rs, new;
2432         uint bandunit;
2433
2434         memcpy(&rs, rs_arg, sizeof(wlc_rateset_t));
2435
2436         /* check for bad count value */
2437         if ((rs.count == 0) || (rs.count > WLC_NUMRATES))
2438                 return -EINVAL;
2439
2440         /* try the current band */
2441         bandunit = wlc->band->bandunit;
2442         memcpy(&new, &rs, sizeof(wlc_rateset_t));
2443         if (wlc_rate_hwrs_filter_sort_validate
2444             (&new, &wlc->bandstate[bandunit]->hw_rateset, true,
2445              wlc->stf->txstreams))
2446                 goto good;
2447
2448         /* try the other band */
2449         if (IS_MBAND_UNLOCKED(wlc)) {
2450                 bandunit = OTHERBANDUNIT(wlc);
2451                 memcpy(&new, &rs, sizeof(wlc_rateset_t));
2452                 if (wlc_rate_hwrs_filter_sort_validate(&new,
2453                                                        &wlc->
2454                                                        bandstate[bandunit]->
2455                                                        hw_rateset, true,
2456                                                        wlc->stf->txstreams))
2457                         goto good;
2458         }
2459
2460         return -EBADE;
2461
2462  good:
2463         /* apply new rateset */
2464         memcpy(&wlc->default_bss->rateset, &new, sizeof(wlc_rateset_t));
2465         memcpy(&wlc->bandstate[bandunit]->defrateset, &new,
2466                sizeof(wlc_rateset_t));
2467         return 0;
2468 }
2469
2470 /* simplified integer set interface for common ioctl handler */
2471 int wlc_set(struct wlc_info *wlc, int cmd, int arg)
2472 {
2473         return wlc_ioctl(wlc, cmd, (void *)&arg, sizeof(arg), NULL);
2474 }
2475
2476 /* simplified integer get interface for common ioctl handler */
2477 int wlc_get(struct wlc_info *wlc, int cmd, int *arg)
2478 {
2479         return wlc_ioctl(wlc, cmd, arg, sizeof(int), NULL);
2480 }
2481
2482 static void wlc_ofdm_rateset_war(struct wlc_info *wlc)
2483 {
2484         u8 r;
2485         bool war = false;
2486
2487         if (wlc->cfg->associated)
2488                 r = wlc->cfg->current_bss->rateset.rates[0];
2489         else
2490                 r = wlc->default_bss->rateset.rates[0];
2491
2492         wlc_phy_ofdm_rateset_war(wlc->band->pi, war);
2493
2494         return;
2495 }
2496
2497 int
2498 wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
2499           struct wlc_if *wlcif)
2500 {
2501         return _wlc_ioctl(wlc, cmd, arg, len, wlcif);
2502 }
2503
2504 /* common ioctl handler. return: 0=ok, -1=error, positive=particular error */
2505 static int
2506 _wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
2507            struct wlc_if *wlcif)
2508 {
2509         int val, *pval;
2510         bool bool_val;
2511         int bcmerror;
2512         d11regs_t *regs;
2513         struct scb *nextscb;
2514         bool ta_ok;
2515         uint band;
2516         struct wlc_bsscfg *bsscfg;
2517         wlc_bss_info_t *current_bss;
2518
2519         /* update bsscfg pointer */
2520         bsscfg = wlc->cfg;
2521         current_bss = bsscfg->current_bss;
2522
2523         /* initialize the following to get rid of compiler warning */
2524         nextscb = NULL;
2525         ta_ok = false;
2526         band = 0;
2527
2528         /* If the device is turned off, then it's not "removed" */
2529         if (!wlc->pub->hw_off && DEVICEREMOVED(wlc)) {
2530                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
2531                           __func__);
2532                 brcms_down(wlc->wl);
2533                 return -EBADE;
2534         }
2535
2536         /* default argument is generic integer */
2537         pval = arg ? (int *)arg:NULL;
2538
2539         /* This will prevent the misaligned access */
2540         if (pval && (u32) len >= sizeof(val))
2541                 memcpy(&val, pval, sizeof(val));
2542         else
2543                 val = 0;
2544
2545         /* bool conversion to avoid duplication below */
2546         bool_val = val != 0;
2547         bcmerror = 0;
2548         regs = wlc->regs;
2549
2550         if ((arg == NULL) || (len <= 0)) {
2551                 wiphy_err(wlc->wiphy, "wl%d: %s: Command %d needs arguments\n",
2552                           wlc->pub->unit, __func__, cmd);
2553                 bcmerror = -EINVAL;
2554                 goto done;
2555         }
2556
2557         switch (cmd) {
2558
2559         case WLC_SET_CHANNEL:{
2560                         chanspec_t chspec = CH20MHZ_CHSPEC(val);
2561
2562                         if (val < 0 || val > MAXCHANNEL) {
2563                                 bcmerror = -EINVAL;
2564                                 break;
2565                         }
2566
2567                         if (!wlc_valid_chanspec_db(wlc->cmi, chspec)) {
2568                                 bcmerror = -EINVAL;
2569                                 break;
2570                         }
2571
2572                         if (!wlc->pub->up && IS_MBAND_UNLOCKED(wlc)) {
2573                                 if (wlc->band->bandunit !=
2574                                     CHSPEC_WLCBANDUNIT(chspec))
2575                                         wlc->bandinit_pending = true;
2576                                 else
2577                                         wlc->bandinit_pending = false;
2578                         }
2579
2580                         wlc->default_bss->chanspec = chspec;
2581                         /* wlc_BSSinit() will sanitize the rateset before using it.. */
2582                         if (wlc->pub->up &&
2583                             (WLC_BAND_PI_RADIO_CHANSPEC != chspec)) {
2584                                 wlc_set_home_chanspec(wlc, chspec);
2585                                 wlc_suspend_mac_and_wait(wlc);
2586                                 wlc_set_chanspec(wlc, chspec);
2587                                 wlc_enable_mac(wlc);
2588                         }
2589                         break;
2590                 }
2591
2592         case WLC_SET_SRL:
2593                 if (val >= 1 && val <= RETRY_SHORT_MAX) {
2594                         int ac;
2595                         wlc->SRL = (u16) val;
2596
2597                         wlc_bmac_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
2598
2599                         for (ac = 0; ac < AC_COUNT; ac++) {
2600                                 WLC_WME_RETRY_SHORT_SET(wlc, ac, wlc->SRL);
2601                         }
2602                         wlc_wme_retries_write(wlc);
2603                 } else
2604                         bcmerror = -EINVAL;
2605                 break;
2606
2607         case WLC_SET_LRL:
2608                 if (val >= 1 && val <= 255) {
2609                         int ac;
2610                         wlc->LRL = (u16) val;
2611
2612                         wlc_bmac_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
2613
2614                         for (ac = 0; ac < AC_COUNT; ac++) {
2615                                 WLC_WME_RETRY_LONG_SET(wlc, ac, wlc->LRL);
2616                         }
2617                         wlc_wme_retries_write(wlc);
2618                 } else
2619                         bcmerror = -EINVAL;
2620                 break;
2621
2622         case WLC_GET_CURR_RATESET:{
2623                         wl_rateset_t *ret_rs = (wl_rateset_t *) arg;
2624                         wlc_rateset_t *rs;
2625
2626                         if (wlc->pub->associated)
2627                                 rs = &current_bss->rateset;
2628                         else
2629                                 rs = &wlc->default_bss->rateset;
2630
2631                         if (len < (int)(rs->count + sizeof(rs->count))) {
2632                                 bcmerror = -EOVERFLOW;
2633                                 break;
2634                         }
2635
2636                         /* Copy only legacy rateset section */
2637                         ret_rs->count = rs->count;
2638                         memcpy(&ret_rs->rates, &rs->rates, rs->count);
2639                         break;
2640                 }
2641
2642         case WLC_SET_RATESET:{
2643                         wlc_rateset_t rs;
2644                         wl_rateset_t *in_rs = (wl_rateset_t *) arg;
2645
2646                         if (len < (int)(in_rs->count + sizeof(in_rs->count))) {
2647                                 bcmerror = -EOVERFLOW;
2648                                 break;
2649                         }
2650
2651                         if (in_rs->count > WLC_NUMRATES) {
2652                                 bcmerror = -ENOBUFS;
2653                                 break;
2654                         }
2655
2656                         memset(&rs, 0, sizeof(wlc_rateset_t));
2657
2658                         /* Copy only legacy rateset section */
2659                         rs.count = in_rs->count;
2660                         memcpy(&rs.rates, &in_rs->rates, rs.count);
2661
2662                         /* merge rateset coming in with the current mcsset */
2663                         if (N_ENAB(wlc->pub)) {
2664                                 if (bsscfg->associated)
2665                                         memcpy(rs.mcs,
2666                                                &current_bss->rateset.mcs[0],
2667                                                MCSSET_LEN);
2668                                 else
2669                                         memcpy(rs.mcs,
2670                                                &wlc->default_bss->rateset.mcs[0],
2671                                                MCSSET_LEN);
2672                         }
2673
2674                         bcmerror = wlc_set_rateset(wlc, &rs);
2675
2676                         if (!bcmerror)
2677                                 wlc_ofdm_rateset_war(wlc);
2678
2679                         break;
2680                 }
2681
2682         case WLC_SET_BCNPRD:
2683                 /* range [1, 0xffff] */
2684                 if (val >= DOT11_MIN_BEACON_PERIOD
2685                     && val <= DOT11_MAX_BEACON_PERIOD) {
2686                         wlc->default_bss->beacon_period = (u16) val;
2687                 } else
2688                         bcmerror = -EINVAL;
2689                 break;
2690
2691         case WLC_GET_PHYLIST:
2692                 {
2693                         unsigned char *cp = arg;
2694                         if (len < 3) {
2695                                 bcmerror = -EOVERFLOW;
2696                                 break;
2697                         }
2698
2699                         if (WLCISNPHY(wlc->band)) {
2700                                 *cp++ = 'n';
2701                         } else if (WLCISLCNPHY(wlc->band)) {
2702                                 *cp++ = 'c';
2703                         } else if (WLCISSSLPNPHY(wlc->band)) {
2704                                 *cp++ = 's';
2705                         }
2706                         *cp = '\0';
2707                         break;
2708                 }
2709
2710         case WLC_SET_SHORTSLOT_OVERRIDE:
2711                 if ((val != WLC_SHORTSLOT_AUTO) &&
2712                     (val != WLC_SHORTSLOT_OFF) && (val != WLC_SHORTSLOT_ON)) {
2713                         bcmerror = -EINVAL;
2714                         break;
2715                 }
2716
2717                 wlc->shortslot_override = (s8) val;
2718
2719                 /* shortslot is an 11g feature, so no more work if we are
2720                  * currently on the 5G band
2721                  */
2722                 if (BAND_5G(wlc->band->bandtype))
2723                         break;
2724
2725                 if (wlc->pub->up && wlc->pub->associated) {
2726                         /* let watchdog or beacon processing update shortslot */
2727                 } else if (wlc->pub->up) {
2728                         /* unassociated shortslot is off */
2729                         wlc_switch_shortslot(wlc, false);
2730                 } else {
2731                         /* driver is down, so just update the wlc_info value */
2732                         if (wlc->shortslot_override == WLC_SHORTSLOT_AUTO) {
2733                                 wlc->shortslot = false;
2734                         } else {
2735                                 wlc->shortslot =
2736                                     (wlc->shortslot_override ==
2737                                      WLC_SHORTSLOT_ON);
2738                         }
2739                 }
2740
2741                 break;
2742
2743         }
2744  done:
2745
2746         if (bcmerror)
2747                 wlc->pub->bcmerror = bcmerror;
2748
2749         return bcmerror;
2750 }
2751
2752 /*
2753  * register watchdog and down handlers.
2754  */
2755 int wlc_module_register(struct wlc_pub *pub,
2756                         const char *name, void *hdl,
2757                         watchdog_fn_t w_fn, down_fn_t d_fn)
2758 {
2759         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
2760         int i;
2761
2762         /* find an empty entry and just add, no duplication check! */
2763         for (i = 0; i < WLC_MAXMODULES; i++) {
2764                 if (wlc->modulecb[i].name[0] == '\0') {
2765                         strncpy(wlc->modulecb[i].name, name,
2766                                 sizeof(wlc->modulecb[i].name) - 1);
2767                         wlc->modulecb[i].hdl = hdl;
2768                         wlc->modulecb[i].watchdog_fn = w_fn;
2769                         wlc->modulecb[i].down_fn = d_fn;
2770                         return 0;
2771                 }
2772         }
2773
2774         return -ENOSR;
2775 }
2776
2777 /* unregister module callbacks */
2778 int wlc_module_unregister(struct wlc_pub *pub, const char *name, void *hdl)
2779 {
2780         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
2781         int i;
2782
2783         if (wlc == NULL)
2784                 return -ENODATA;
2785
2786         for (i = 0; i < WLC_MAXMODULES; i++) {
2787                 if (!strcmp(wlc->modulecb[i].name, name) &&
2788                     (wlc->modulecb[i].hdl == hdl)) {
2789                         memset(&wlc->modulecb[i], 0, sizeof(struct modulecb));
2790                         return 0;
2791                 }
2792         }
2793
2794         /* table not found! */
2795         return -ENODATA;
2796 }
2797
2798 /* Write WME tunable parameters for retransmit/max rate from wlc struct to ucode */
2799 static void wlc_wme_retries_write(struct wlc_info *wlc)
2800 {
2801         int ac;
2802
2803         /* Need clock to do this */
2804         if (!wlc->clk)
2805                 return;
2806
2807         for (ac = 0; ac < AC_COUNT; ac++) {
2808                 wlc_write_shm(wlc, M_AC_TXLMT_ADDR(ac), wlc->wme_retries[ac]);
2809         }
2810 }
2811
2812 #ifdef BCMDBG
2813 static const char *supr_reason[] = {
2814         "None", "PMQ Entry", "Flush request",
2815         "Previous frag failure", "Channel mismatch",
2816         "Lifetime Expiry", "Underflow"
2817 };
2818
2819 static void wlc_print_txs_status(u16 s)
2820 {
2821         printk(KERN_DEBUG "[15:12]  %d  frame attempts\n",
2822                (s & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT);
2823         printk(KERN_DEBUG " [11:8]  %d  rts attempts\n",
2824                (s & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT);
2825         printk(KERN_DEBUG "    [7]  %d  PM mode indicated\n",
2826                ((s & TX_STATUS_PMINDCTD) ? 1 : 0));
2827         printk(KERN_DEBUG "    [6]  %d  intermediate status\n",
2828                ((s & TX_STATUS_INTERMEDIATE) ? 1 : 0));
2829         printk(KERN_DEBUG "    [5]  %d  AMPDU\n",
2830                (s & TX_STATUS_AMPDU) ? 1 : 0);
2831         printk(KERN_DEBUG "  [4:2]  %d  Frame Suppressed Reason (%s)\n",
2832                ((s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT),
2833                supr_reason[(s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT]);
2834         printk(KERN_DEBUG "    [1]  %d  acked\n",
2835                ((s & TX_STATUS_ACK_RCV) ? 1 : 0));
2836 }
2837 #endif                          /* BCMDBG */
2838
2839 void wlc_print_txstatus(tx_status_t *txs)
2840 {
2841 #if defined(BCMDBG)
2842         u16 s = txs->status;
2843         u16 ackphyrxsh = txs->ackphyrxsh;
2844
2845         printk(KERN_DEBUG "\ntxpkt (MPDU) Complete\n");
2846
2847         printk(KERN_DEBUG "FrameID: %04x   ", txs->frameid);
2848         printk(KERN_DEBUG "TxStatus: %04x", s);
2849         printk(KERN_DEBUG "\n");
2850
2851         wlc_print_txs_status(s);
2852
2853         printk(KERN_DEBUG "LastTxTime: %04x ", txs->lasttxtime);
2854         printk(KERN_DEBUG "Seq: %04x ", txs->sequence);
2855         printk(KERN_DEBUG "PHYTxStatus: %04x ", txs->phyerr);
2856         printk(KERN_DEBUG "RxAckRSSI: %04x ",
2857                (ackphyrxsh & PRXS1_JSSI_MASK) >> PRXS1_JSSI_SHIFT);
2858         printk(KERN_DEBUG "RxAckSQ: %04x",
2859                (ackphyrxsh & PRXS1_SQ_MASK) >> PRXS1_SQ_SHIFT);
2860         printk(KERN_DEBUG "\n");
2861 #endif                          /* defined(BCMDBG) */
2862 }
2863
2864 void wlc_statsupd(struct wlc_info *wlc)
2865 {
2866         int i;
2867         macstat_t macstats;
2868 #ifdef BCMDBG
2869         u16 delta;
2870         u16 rxf0ovfl;
2871         u16 txfunfl[NFIFO];
2872 #endif                          /* BCMDBG */
2873
2874         /* if driver down, make no sense to update stats */
2875         if (!wlc->pub->up)
2876                 return;
2877
2878 #ifdef BCMDBG
2879         /* save last rx fifo 0 overflow count */
2880         rxf0ovfl = wlc->core->macstat_snapshot->rxf0ovfl;
2881
2882         /* save last tx fifo  underflow count */
2883         for (i = 0; i < NFIFO; i++)
2884                 txfunfl[i] = wlc->core->macstat_snapshot->txfunfl[i];
2885 #endif                          /* BCMDBG */
2886
2887         /* Read mac stats from contiguous shared memory */
2888         wlc_bmac_copyfrom_shm(wlc->hw, M_UCODE_MACSTAT,
2889                               &macstats, sizeof(macstat_t));
2890
2891 #ifdef BCMDBG
2892         /* check for rx fifo 0 overflow */
2893         delta = (u16) (wlc->core->macstat_snapshot->rxf0ovfl - rxf0ovfl);
2894         if (delta)
2895                 wiphy_err(wlc->wiphy, "wl%d: %u rx fifo 0 overflows!\n",
2896                           wlc->pub->unit, delta);
2897
2898         /* check for tx fifo underflows */
2899         for (i = 0; i < NFIFO; i++) {
2900                 delta =
2901                     (u16) (wlc->core->macstat_snapshot->txfunfl[i] -
2902                               txfunfl[i]);
2903                 if (delta)
2904                         wiphy_err(wlc->wiphy, "wl%d: %u tx fifo %d underflows!"
2905                                   "\n", wlc->pub->unit, delta, i);
2906         }
2907 #endif                          /* BCMDBG */
2908
2909         /* merge counters from dma module */
2910         for (i = 0; i < NFIFO; i++) {
2911                 if (wlc->hw->di[i]) {
2912                         dma_counterreset(wlc->hw->di[i]);
2913                 }
2914         }
2915 }
2916
2917 bool wlc_chipmatch(u16 vendor, u16 device)
2918 {
2919         if (vendor != PCI_VENDOR_ID_BROADCOM) {
2920                 pr_err("wlc_chipmatch: unknown vendor id %04x\n", vendor);
2921                 return false;
2922         }
2923
2924         if (device == BCM43224_D11N_ID_VEN1)
2925                 return true;
2926         if ((device == BCM43224_D11N_ID) || (device == BCM43225_D11N2G_ID))
2927                 return true;
2928         if (device == BCM4313_D11N2G_ID)
2929                 return true;
2930         if ((device == BCM43236_D11N_ID) || (device == BCM43236_D11N2G_ID))
2931                 return true;
2932
2933         pr_err("wlc_chipmatch: unknown device id %04x\n", device);
2934         return false;
2935 }
2936
2937 #if defined(BCMDBG)
2938 void wlc_print_txdesc(d11txh_t *txh)
2939 {
2940         u16 mtcl = le16_to_cpu(txh->MacTxControlLow);
2941         u16 mtch = le16_to_cpu(txh->MacTxControlHigh);
2942         u16 mfc = le16_to_cpu(txh->MacFrameControl);
2943         u16 tfest = le16_to_cpu(txh->TxFesTimeNormal);
2944         u16 ptcw = le16_to_cpu(txh->PhyTxControlWord);
2945         u16 ptcw_1 = le16_to_cpu(txh->PhyTxControlWord_1);
2946         u16 ptcw_1_Fbr = le16_to_cpu(txh->PhyTxControlWord_1_Fbr);
2947         u16 ptcw_1_Rts = le16_to_cpu(txh->PhyTxControlWord_1_Rts);
2948         u16 ptcw_1_FbrRts = le16_to_cpu(txh->PhyTxControlWord_1_FbrRts);
2949         u16 mainrates = le16_to_cpu(txh->MainRates);
2950         u16 xtraft = le16_to_cpu(txh->XtraFrameTypes);
2951         u8 *iv = txh->IV;
2952         u8 *ra = txh->TxFrameRA;
2953         u16 tfestfb = le16_to_cpu(txh->TxFesTimeFallback);
2954         u8 *rtspfb = txh->RTSPLCPFallback;
2955         u16 rtsdfb = le16_to_cpu(txh->RTSDurFallback);
2956         u8 *fragpfb = txh->FragPLCPFallback;
2957         u16 fragdfb = le16_to_cpu(txh->FragDurFallback);
2958         u16 mmodelen = le16_to_cpu(txh->MModeLen);
2959         u16 mmodefbrlen = le16_to_cpu(txh->MModeFbrLen);
2960         u16 tfid = le16_to_cpu(txh->TxFrameID);
2961         u16 txs = le16_to_cpu(txh->TxStatus);
2962         u16 mnmpdu = le16_to_cpu(txh->MaxNMpdus);
2963         u16 mabyte = le16_to_cpu(txh->MaxABytes_MRT);
2964         u16 mabyte_f = le16_to_cpu(txh->MaxABytes_FBR);
2965         u16 mmbyte = le16_to_cpu(txh->MinMBytes);
2966
2967         u8 *rtsph = txh->RTSPhyHeader;
2968         struct ieee80211_rts rts = txh->rts_frame;
2969         char hexbuf[256];
2970
2971         /* add plcp header along with txh descriptor */
2972         printk(KERN_DEBUG "Raw TxDesc + plcp header:\n");
2973         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
2974                              txh, sizeof(d11txh_t) + 48);
2975
2976         printk(KERN_DEBUG "TxCtlLow: %04x ", mtcl);
2977         printk(KERN_DEBUG "TxCtlHigh: %04x ", mtch);
2978         printk(KERN_DEBUG "FC: %04x ", mfc);
2979         printk(KERN_DEBUG "FES Time: %04x\n", tfest);
2980         printk(KERN_DEBUG "PhyCtl: %04x%s ", ptcw,
2981                (ptcw & PHY_TXC_SHORT_HDR) ? " short" : "");
2982         printk(KERN_DEBUG "PhyCtl_1: %04x ", ptcw_1);
2983         printk(KERN_DEBUG "PhyCtl_1_Fbr: %04x\n", ptcw_1_Fbr);
2984         printk(KERN_DEBUG "PhyCtl_1_Rts: %04x ", ptcw_1_Rts);
2985         printk(KERN_DEBUG "PhyCtl_1_Fbr_Rts: %04x\n", ptcw_1_FbrRts);
2986         printk(KERN_DEBUG "MainRates: %04x ", mainrates);
2987         printk(KERN_DEBUG "XtraFrameTypes: %04x ", xtraft);
2988         printk(KERN_DEBUG "\n");
2989
2990         bcm_format_hex(hexbuf, iv, sizeof(txh->IV));
2991         printk(KERN_DEBUG "SecIV:       %s\n", hexbuf);
2992         bcm_format_hex(hexbuf, ra, sizeof(txh->TxFrameRA));
2993         printk(KERN_DEBUG "RA:          %s\n", hexbuf);
2994
2995         printk(KERN_DEBUG "Fb FES Time: %04x ", tfestfb);
2996         bcm_format_hex(hexbuf, rtspfb, sizeof(txh->RTSPLCPFallback));
2997         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
2998         printk(KERN_DEBUG "RTS DUR: %04x ", rtsdfb);
2999         bcm_format_hex(hexbuf, fragpfb, sizeof(txh->FragPLCPFallback));
3000         printk(KERN_DEBUG "PLCP: %s ", hexbuf);
3001         printk(KERN_DEBUG "DUR: %04x", fragdfb);
3002         printk(KERN_DEBUG "\n");
3003
3004         printk(KERN_DEBUG "MModeLen: %04x ", mmodelen);
3005         printk(KERN_DEBUG "MModeFbrLen: %04x\n", mmodefbrlen);
3006
3007         printk(KERN_DEBUG "FrameID:     %04x\n", tfid);
3008         printk(KERN_DEBUG "TxStatus:    %04x\n", txs);
3009
3010         printk(KERN_DEBUG "MaxNumMpdu:  %04x\n", mnmpdu);
3011         printk(KERN_DEBUG "MaxAggbyte:  %04x\n", mabyte);
3012         printk(KERN_DEBUG "MaxAggbyte_fb:  %04x\n", mabyte_f);
3013         printk(KERN_DEBUG "MinByte:     %04x\n", mmbyte);
3014
3015         bcm_format_hex(hexbuf, rtsph, sizeof(txh->RTSPhyHeader));
3016         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
3017         bcm_format_hex(hexbuf, (u8 *) &rts, sizeof(txh->rts_frame));
3018         printk(KERN_DEBUG "RTS Frame: %s", hexbuf);
3019         printk(KERN_DEBUG "\n");
3020 }
3021 #endif                          /* defined(BCMDBG) */
3022
3023 #if defined(BCMDBG)
3024 void wlc_print_rxh(d11rxhdr_t *rxh)
3025 {
3026         u16 len = rxh->RxFrameSize;
3027         u16 phystatus_0 = rxh->PhyRxStatus_0;
3028         u16 phystatus_1 = rxh->PhyRxStatus_1;
3029         u16 phystatus_2 = rxh->PhyRxStatus_2;
3030         u16 phystatus_3 = rxh->PhyRxStatus_3;
3031         u16 macstatus1 = rxh->RxStatus1;
3032         u16 macstatus2 = rxh->RxStatus2;
3033         char flagstr[64];
3034         char lenbuf[20];
3035         static const bcm_bit_desc_t macstat_flags[] = {
3036                 {RXS_FCSERR, "FCSErr"},
3037                 {RXS_RESPFRAMETX, "Reply"},
3038                 {RXS_PBPRES, "PADDING"},
3039                 {RXS_DECATMPT, "DeCr"},
3040                 {RXS_DECERR, "DeCrErr"},
3041                 {RXS_BCNSENT, "Bcn"},
3042                 {0, NULL}
3043         };
3044
3045         printk(KERN_DEBUG "Raw RxDesc:\n");
3046         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, rxh, sizeof(d11rxhdr_t));
3047
3048         bcm_format_flags(macstat_flags, macstatus1, flagstr, 64);
3049
3050         snprintf(lenbuf, sizeof(lenbuf), "0x%x", len);
3051
3052         printk(KERN_DEBUG "RxFrameSize:     %6s (%d)%s\n", lenbuf, len,
3053                (rxh->PhyRxStatus_0 & PRXS0_SHORTH) ? " short preamble" : "");
3054         printk(KERN_DEBUG "RxPHYStatus:     %04x %04x %04x %04x\n",
3055                phystatus_0, phystatus_1, phystatus_2, phystatus_3);
3056         printk(KERN_DEBUG "RxMACStatus:     %x %s\n", macstatus1, flagstr);
3057         printk(KERN_DEBUG "RXMACaggtype:    %x\n",
3058                (macstatus2 & RXS_AGGTYPE_MASK));
3059         printk(KERN_DEBUG "RxTSFTime:       %04x\n", rxh->RxTSFTime);
3060 }
3061 #endif                          /* defined(BCMDBG) */
3062
3063 static u16 wlc_rate_shm_offset(struct wlc_info *wlc, u8 rate)
3064 {
3065         return wlc_bmac_rate_shm_offset(wlc->hw, rate);
3066 }
3067
3068 /* Callback for device removed */
3069
3070 /*
3071  * Attempts to queue a packet onto a multiple-precedence queue,
3072  * if necessary evicting a lower precedence packet from the queue.
3073  *
3074  * 'prec' is the precedence number that has already been mapped
3075  * from the packet priority.
3076  *
3077  * Returns true if packet consumed (queued), false if not.
3078  */
3079 bool
3080 wlc_prec_enq(struct wlc_info *wlc, struct pktq *q, void *pkt, int prec)
3081 {
3082         return wlc_prec_enq_head(wlc, q, pkt, prec, false);
3083 }
3084
3085 bool
3086 wlc_prec_enq_head(struct wlc_info *wlc, struct pktq *q, struct sk_buff *pkt,
3087                   int prec, bool head)
3088 {
3089         struct sk_buff *p;
3090         int eprec = -1;         /* precedence to evict from */
3091
3092         /* Determine precedence from which to evict packet, if any */
3093         if (pktq_pfull(q, prec))
3094                 eprec = prec;
3095         else if (pktq_full(q)) {
3096                 p = bcm_pktq_peek_tail(q, &eprec);
3097                 if (eprec > prec) {
3098                         wiphy_err(wlc->wiphy, "%s: Failing: eprec %d > prec %d"
3099                                   "\n", __func__, eprec, prec);
3100                         return false;
3101                 }
3102         }
3103
3104         /* Evict if needed */
3105         if (eprec >= 0) {
3106                 bool discard_oldest;
3107
3108                 discard_oldest = AC_BITMAP_TST(wlc->wme_dp, eprec);
3109
3110                 /* Refuse newer packet unless configured to discard oldest */
3111                 if (eprec == prec && !discard_oldest) {
3112                         wiphy_err(wlc->wiphy, "%s: No where to go, prec == %d"
3113                                   "\n", __func__, prec);
3114                         return false;
3115                 }
3116
3117                 /* Evict packet according to discard policy */
3118                 p = discard_oldest ? bcm_pktq_pdeq(q, eprec) :
3119                         bcm_pktq_pdeq_tail(q, eprec);
3120                 bcm_pkt_buf_free_skb(p);
3121         }
3122
3123         /* Enqueue */
3124         if (head)
3125                 p = bcm_pktq_penq_head(q, prec, pkt);
3126         else
3127                 p = bcm_pktq_penq(q, prec, pkt);
3128
3129         return true;
3130 }
3131
3132 void wlc_txq_enq(void *ctx, struct scb *scb, struct sk_buff *sdu,
3133                              uint prec)
3134 {
3135         struct wlc_info *wlc = (struct wlc_info *) ctx;
3136         struct wlc_txq_info *qi = wlc->pkt_queue;       /* Check me */
3137         struct pktq *q = &qi->q;
3138         int prio;
3139
3140         prio = sdu->priority;
3141
3142         if (!wlc_prec_enq(wlc, q, sdu, prec)) {
3143                 if (!EDCF_ENAB(wlc->pub)
3144                     || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL))
3145                         wiphy_err(wlc->wiphy, "wl%d: wlc_txq_enq: txq overflow"
3146                                   "\n", wlc->pub->unit);
3147
3148                 /*
3149                  * XXX we might hit this condtion in case
3150                  * packet flooding from mac80211 stack
3151                  */
3152                 bcm_pkt_buf_free_skb(sdu);
3153         }
3154
3155         /* Check if flow control needs to be turned on after enqueuing the packet
3156          *   Don't turn on flow control if EDCF is enabled. Driver would make the decision on what
3157          *   to drop instead of relying on stack to make the right decision
3158          */
3159         if (!EDCF_ENAB(wlc->pub)
3160             || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL)) {
3161                 if (pktq_len(q) >= wlc->pub->tunables->datahiwat) {
3162                         wlc_txflowcontrol(wlc, qi, ON, ALLPRIO);
3163                 }
3164         } else if (wlc->pub->_priofc) {
3165                 if (pktq_plen(q, wlc_prio2prec_map[prio]) >=
3166                     wlc->pub->tunables->datahiwat) {
3167                         wlc_txflowcontrol(wlc, qi, ON, prio);
3168                 }
3169         }
3170 }
3171
3172 bool
3173 wlc_sendpkt_mac80211(struct wlc_info *wlc, struct sk_buff *sdu,
3174                      struct ieee80211_hw *hw)
3175 {
3176         u8 prio;
3177         uint fifo;
3178         void *pkt;
3179         struct scb *scb = &global_scb;
3180         struct ieee80211_hdr *d11_header = (struct ieee80211_hdr *)(sdu->data);
3181
3182         /* 802.11 standard requires management traffic to go at highest priority */
3183         prio = ieee80211_is_data(d11_header->frame_control) ? sdu->priority :
3184                 MAXPRIO;
3185         fifo = prio2fifo[prio];
3186         pkt = sdu;
3187         if (unlikely
3188             (wlc_d11hdrs_mac80211(wlc, hw, pkt, scb, 0, 1, fifo, 0, NULL, 0)))
3189                 return -EINVAL;
3190         wlc_txq_enq(wlc, scb, pkt, WLC_PRIO_TO_PREC(prio));
3191         wlc_send_q(wlc);
3192         return 0;
3193 }
3194
3195 void wlc_send_q(struct wlc_info *wlc)
3196 {
3197         struct sk_buff *pkt[DOT11_MAXNUMFRAGS];
3198         int prec;
3199         u16 prec_map;
3200         int err = 0, i, count;
3201         uint fifo;
3202         struct wlc_txq_info *qi = wlc->pkt_queue;
3203         struct pktq *q = &qi->q;
3204         struct ieee80211_tx_info *tx_info;
3205
3206         if (in_send_q)
3207                 return;
3208         else
3209                 in_send_q = true;
3210
3211         prec_map = wlc->tx_prec_map;
3212
3213         /* Send all the enq'd pkts that we can.
3214          * Dequeue packets with precedence with empty HW fifo only
3215          */
3216         while (prec_map && (pkt[0] = bcm_pktq_mdeq(q, prec_map, &prec))) {
3217                 tx_info = IEEE80211_SKB_CB(pkt[0]);
3218                 if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
3219                         err = wlc_sendampdu(wlc->ampdu, qi, pkt, prec);
3220                 } else {
3221                         count = 1;
3222                         err = wlc_prep_pdu(wlc, pkt[0], &fifo);
3223                         if (!err) {
3224                                 for (i = 0; i < count; i++) {
3225                                         wlc_txfifo(wlc, fifo, pkt[i], true, 1);
3226                                 }
3227                         }
3228                 }
3229
3230                 if (err == -EBUSY) {
3231                         bcm_pktq_penq_head(q, prec, pkt[0]);
3232                         /* If send failed due to any other reason than a change in
3233                          * HW FIFO condition, quit. Otherwise, read the new prec_map!
3234                          */
3235                         if (prec_map == wlc->tx_prec_map)
3236                                 break;
3237                         prec_map = wlc->tx_prec_map;
3238                 }
3239         }
3240
3241         /* Check if flow control needs to be turned off after sending the packet */
3242         if (!EDCF_ENAB(wlc->pub)
3243             || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL)) {
3244                 if (wlc_txflowcontrol_prio_isset(wlc, qi, ALLPRIO)
3245                     && (pktq_len(q) < wlc->pub->tunables->datahiwat / 2)) {
3246                         wlc_txflowcontrol(wlc, qi, OFF, ALLPRIO);
3247                 }
3248         } else if (wlc->pub->_priofc) {
3249                 int prio;
3250                 for (prio = MAXPRIO; prio >= 0; prio--) {
3251                         if (wlc_txflowcontrol_prio_isset(wlc, qi, prio) &&
3252                             (pktq_plen(q, wlc_prio2prec_map[prio]) <
3253                              wlc->pub->tunables->datahiwat / 2)) {
3254                                 wlc_txflowcontrol(wlc, qi, OFF, prio);
3255                         }
3256                 }
3257         }
3258         in_send_q = false;
3259 }
3260
3261 /*
3262  * bcmc_fid_generate:
3263  * Generate frame ID for a BCMC packet.  The frag field is not used
3264  * for MC frames so is used as part of the sequence number.
3265  */
3266 static inline u16
3267 bcmc_fid_generate(struct wlc_info *wlc, struct wlc_bsscfg *bsscfg,
3268                   d11txh_t *txh)
3269 {
3270         u16 frameid;
3271
3272         frameid = le16_to_cpu(txh->TxFrameID) & ~(TXFID_SEQ_MASK |
3273                                                   TXFID_QUEUE_MASK);
3274         frameid |=
3275             (((wlc->
3276                mc_fid_counter++) << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
3277             TX_BCMC_FIFO;
3278
3279         return frameid;
3280 }
3281
3282 void
3283 wlc_txfifo(struct wlc_info *wlc, uint fifo, struct sk_buff *p, bool commit,
3284            s8 txpktpend)
3285 {
3286         u16 frameid = INVALIDFID;
3287         d11txh_t *txh;
3288
3289         txh = (d11txh_t *) (p->data);
3290
3291         /* When a BC/MC frame is being committed to the BCMC fifo via DMA (NOT PIO), update
3292          * ucode or BSS info as appropriate.
3293          */
3294         if (fifo == TX_BCMC_FIFO) {
3295                 frameid = le16_to_cpu(txh->TxFrameID);
3296
3297         }
3298
3299         if (WLC_WAR16165(wlc))
3300                 wlc_war16165(wlc, true);
3301
3302
3303         /* Bump up pending count for if not using rpc. If rpc is used, this will be handled
3304          * in wlc_bmac_txfifo()
3305          */
3306         if (commit) {
3307                 TXPKTPENDINC(wlc, fifo, txpktpend);
3308                 BCMMSG(wlc->wiphy, "pktpend inc %d to %d\n",
3309                          txpktpend, TXPKTPENDGET(wlc, fifo));
3310         }
3311
3312         /* Commit BCMC sequence number in the SHM frame ID location */
3313         if (frameid != INVALIDFID)
3314                 BCMCFID(wlc, frameid);
3315
3316         if (dma_txfast(wlc->hw->di[fifo], p, commit) < 0) {
3317                 wiphy_err(wlc->wiphy, "wlc_txfifo: fatal, toss frames !!!\n");
3318         }
3319 }
3320
3321 void
3322 wlc_compute_plcp(struct wlc_info *wlc, ratespec_t rspec, uint length, u8 *plcp)
3323 {
3324         if (IS_MCS(rspec)) {
3325                 wlc_compute_mimo_plcp(rspec, length, plcp);
3326         } else if (IS_OFDM(rspec)) {
3327                 wlc_compute_ofdm_plcp(rspec, length, plcp);
3328         } else {
3329                 wlc_compute_cck_plcp(wlc, rspec, length, plcp);
3330         }
3331         return;
3332 }
3333
3334 /* Rate: 802.11 rate code, length: PSDU length in octets */
3335 static void wlc_compute_mimo_plcp(ratespec_t rspec, uint length, u8 *plcp)
3336 {
3337         u8 mcs = (u8) (rspec & RSPEC_RATE_MASK);
3338         plcp[0] = mcs;
3339         if (RSPEC_IS40MHZ(rspec) || (mcs == 32))
3340                 plcp[0] |= MIMO_PLCP_40MHZ;
3341         WLC_SET_MIMO_PLCP_LEN(plcp, length);
3342         plcp[3] = RSPEC_MIMOPLCP3(rspec);       /* rspec already holds this byte */
3343         plcp[3] |= 0x7;         /* set smoothing, not sounding ppdu & reserved */
3344         plcp[4] = 0;            /* number of extension spatial streams bit 0 & 1 */
3345         plcp[5] = 0;
3346 }
3347
3348 /* Rate: 802.11 rate code, length: PSDU length in octets */
3349 static void
3350 wlc_compute_ofdm_plcp(ratespec_t rspec, u32 length, u8 *plcp)
3351 {
3352         u8 rate_signal;
3353         u32 tmp = 0;
3354         int rate = RSPEC2RATE(rspec);
3355
3356         /* encode rate per 802.11a-1999 sec 17.3.4.1, with lsb transmitted first */
3357         rate_signal = rate_info[rate] & WLC_RATE_MASK;
3358         memset(plcp, 0, D11_PHY_HDR_LEN);
3359         D11A_PHY_HDR_SRATE((ofdm_phy_hdr_t *) plcp, rate_signal);
3360
3361         tmp = (length & 0xfff) << 5;
3362         plcp[2] |= (tmp >> 16) & 0xff;
3363         plcp[1] |= (tmp >> 8) & 0xff;
3364         plcp[0] |= tmp & 0xff;
3365
3366         return;
3367 }
3368
3369 /*
3370  * Compute PLCP, but only requires actual rate and length of pkt.
3371  * Rate is given in the driver standard multiple of 500 kbps.
3372  * le is set for 11 Mbps rate if necessary.
3373  * Broken out for PRQ.
3374  */
3375
3376 static void wlc_cck_plcp_set(struct wlc_info *wlc, int rate_500, uint length,
3377                              u8 *plcp)
3378 {
3379         u16 usec = 0;
3380         u8 le = 0;
3381
3382         switch (rate_500) {
3383         case WLC_RATE_1M:
3384                 usec = length << 3;
3385                 break;
3386         case WLC_RATE_2M:
3387                 usec = length << 2;
3388                 break;
3389         case WLC_RATE_5M5:
3390                 usec = (length << 4) / 11;
3391                 if ((length << 4) - (usec * 11) > 0)
3392                         usec++;
3393                 break;
3394         case WLC_RATE_11M:
3395                 usec = (length << 3) / 11;
3396                 if ((length << 3) - (usec * 11) > 0) {
3397                         usec++;
3398                         if ((usec * 11) - (length << 3) >= 8)
3399                                 le = D11B_PLCP_SIGNAL_LE;
3400                 }
3401                 break;
3402
3403         default:
3404                 wiphy_err(wlc->wiphy, "wlc_cck_plcp_set: unsupported rate %d"
3405                           "\n", rate_500);
3406                 rate_500 = WLC_RATE_1M;
3407                 usec = length << 3;
3408                 break;
3409         }
3410         /* PLCP signal byte */
3411         plcp[0] = rate_500 * 5; /* r (500kbps) * 5 == r (100kbps) */
3412         /* PLCP service byte */
3413         plcp[1] = (u8) (le | D11B_PLCP_SIGNAL_LOCKED);
3414         /* PLCP length u16, little endian */
3415         plcp[2] = usec & 0xff;
3416         plcp[3] = (usec >> 8) & 0xff;
3417         /* PLCP CRC16 */
3418         plcp[4] = 0;
3419         plcp[5] = 0;
3420 }
3421
3422 /* Rate: 802.11 rate code, length: PSDU length in octets */
3423 static void wlc_compute_cck_plcp(struct wlc_info *wlc, ratespec_t rspec,
3424                                  uint length, u8 *plcp)
3425 {
3426         int rate = RSPEC2RATE(rspec);
3427
3428         wlc_cck_plcp_set(wlc, rate, length, plcp);
3429 }
3430
3431 /* wlc_compute_frame_dur()
3432  *
3433  * Calculate the 802.11 MAC header DUR field for MPDU
3434  * DUR for a single frame = 1 SIFS + 1 ACK
3435  * DUR for a frame with following frags = 3 SIFS + 2 ACK + next frag time
3436  *
3437  * rate                 MPDU rate in unit of 500kbps
3438  * next_frag_len        next MPDU length in bytes
3439  * preamble_type        use short/GF or long/MM PLCP header
3440  */
3441 static u16
3442 wlc_compute_frame_dur(struct wlc_info *wlc, ratespec_t rate, u8 preamble_type,
3443                       uint next_frag_len)
3444 {
3445         u16 dur, sifs;
3446
3447         sifs = SIFS(wlc->band);
3448
3449         dur = sifs;
3450         dur += (u16) wlc_calc_ack_time(wlc, rate, preamble_type);
3451
3452         if (next_frag_len) {
3453                 /* Double the current DUR to get 2 SIFS + 2 ACKs */
3454                 dur *= 2;
3455                 /* add another SIFS and the frag time */
3456                 dur += sifs;
3457                 dur +=
3458                     (u16) wlc_calc_frame_time(wlc, rate, preamble_type,
3459                                                  next_frag_len);
3460         }
3461         return dur;
3462 }
3463
3464 /* wlc_compute_rtscts_dur()
3465  *
3466  * Calculate the 802.11 MAC header DUR field for an RTS or CTS frame
3467  * DUR for normal RTS/CTS w/ frame = 3 SIFS + 1 CTS + next frame time + 1 ACK
3468  * DUR for CTS-TO-SELF w/ frame    = 2 SIFS         + next frame time + 1 ACK
3469  *
3470  * cts                  cts-to-self or rts/cts
3471  * rts_rate             rts or cts rate in unit of 500kbps
3472  * rate                 next MPDU rate in unit of 500kbps
3473  * frame_len            next MPDU frame length in bytes
3474  */
3475 u16
3476 wlc_compute_rtscts_dur(struct wlc_info *wlc, bool cts_only, ratespec_t rts_rate,
3477                        ratespec_t frame_rate, u8 rts_preamble_type,
3478                        u8 frame_preamble_type, uint frame_len, bool ba)
3479 {
3480         u16 dur, sifs;
3481
3482         sifs = SIFS(wlc->band);
3483
3484         if (!cts_only) {        /* RTS/CTS */
3485                 dur = 3 * sifs;
3486                 dur +=
3487                     (u16) wlc_calc_cts_time(wlc, rts_rate,
3488                                                rts_preamble_type);
3489         } else {                /* CTS-TO-SELF */
3490                 dur = 2 * sifs;
3491         }
3492
3493         dur +=
3494             (u16) wlc_calc_frame_time(wlc, frame_rate, frame_preamble_type,
3495                                          frame_len);
3496         if (ba)
3497                 dur +=
3498                     (u16) wlc_calc_ba_time(wlc, frame_rate,
3499                                               WLC_SHORT_PREAMBLE);
3500         else
3501                 dur +=
3502                     (u16) wlc_calc_ack_time(wlc, frame_rate,
3503                                                frame_preamble_type);
3504         return dur;
3505 }
3506
3507 u16 wlc_phytxctl1_calc(struct wlc_info *wlc, ratespec_t rspec)
3508 {
3509         u16 phyctl1 = 0;
3510         u16 bw;
3511
3512         if (WLCISLCNPHY(wlc->band)) {
3513                 bw = PHY_TXC1_BW_20MHZ;
3514         } else {
3515                 bw = RSPEC_GET_BW(rspec);
3516                 /* 10Mhz is not supported yet */
3517                 if (bw < PHY_TXC1_BW_20MHZ) {
3518                         wiphy_err(wlc->wiphy, "wlc_phytxctl1_calc: bw %d is "
3519                                   "not supported yet, set to 20L\n", bw);
3520                         bw = PHY_TXC1_BW_20MHZ;
3521                 }
3522         }
3523
3524         if (IS_MCS(rspec)) {
3525                 uint mcs = rspec & RSPEC_RATE_MASK;
3526
3527                 /* bw, stf, coding-type is part of RSPEC_PHYTXBYTE2 returns */
3528                 phyctl1 = RSPEC_PHYTXBYTE2(rspec);
3529                 /* set the upper byte of phyctl1 */
3530                 phyctl1 |= (mcs_table[mcs].tx_phy_ctl3 << 8);
3531         } else if (IS_CCK(rspec) && !WLCISLCNPHY(wlc->band)
3532                    && !WLCISSSLPNPHY(wlc->band)) {
3533                 /* In CCK mode LPPHY overloads OFDM Modulation bits with CCK Data Rate */
3534                 /* Eventually MIMOPHY would also be converted to this format */
3535                 /* 0 = 1Mbps; 1 = 2Mbps; 2 = 5.5Mbps; 3 = 11Mbps */
3536                 phyctl1 = (bw | (RSPEC_STF(rspec) << PHY_TXC1_MODE_SHIFT));
3537         } else {                /* legacy OFDM/CCK */
3538                 s16 phycfg;
3539                 /* get the phyctl byte from rate phycfg table */
3540                 phycfg = wlc_rate_legacy_phyctl(RSPEC2RATE(rspec));
3541                 if (phycfg == -1) {
3542                         wiphy_err(wlc->wiphy, "wlc_phytxctl1_calc: wrong "
3543                                   "legacy OFDM/CCK rate\n");
3544                         phycfg = 0;
3545                 }
3546                 /* set the upper byte of phyctl1 */
3547                 phyctl1 =
3548                     (bw | (phycfg << 8) |
3549                      (RSPEC_STF(rspec) << PHY_TXC1_MODE_SHIFT));
3550         }
3551         return phyctl1;
3552 }
3553
3554 ratespec_t
3555 wlc_rspec_to_rts_rspec(struct wlc_info *wlc, ratespec_t rspec, bool use_rspec,
3556                        u16 mimo_ctlchbw)
3557 {
3558         ratespec_t rts_rspec = 0;
3559
3560         if (use_rspec) {
3561                 /* use frame rate as rts rate */
3562                 rts_rspec = rspec;
3563
3564         } else if (wlc->band->gmode && wlc->protection->_g && !IS_CCK(rspec)) {
3565                 /* Use 11Mbps as the g protection RTS target rate and fallback.
3566                  * Use the WLC_BASIC_RATE() lookup to find the best basic rate under the
3567                  * target in case 11 Mbps is not Basic.
3568                  * 6 and 9 Mbps are not usually selected by rate selection, but even
3569                  * if the OFDM rate we are protecting is 6 or 9 Mbps, 11 is more robust.
3570                  */
3571                 rts_rspec = WLC_BASIC_RATE(wlc, WLC_RATE_11M);
3572         } else {
3573                 /* calculate RTS rate and fallback rate based on the frame rate
3574                  * RTS must be sent at a basic rate since it is a
3575                  * control frame, sec 9.6 of 802.11 spec
3576                  */
3577                 rts_rspec = WLC_BASIC_RATE(wlc, rspec);
3578         }
3579
3580         if (WLC_PHY_11N_CAP(wlc->band)) {
3581                 /* set rts txbw to correct side band */
3582                 rts_rspec &= ~RSPEC_BW_MASK;
3583
3584                 /* if rspec/rspec_fallback is 40MHz, then send RTS on both 20MHz channel
3585                  * (DUP), otherwise send RTS on control channel
3586                  */
3587                 if (RSPEC_IS40MHZ(rspec) && !IS_CCK(rts_rspec))
3588                         rts_rspec |= (PHY_TXC1_BW_40MHZ_DUP << RSPEC_BW_SHIFT);
3589                 else
3590                         rts_rspec |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
3591
3592                 /* pick siso/cdd as default for ofdm */
3593                 if (IS_OFDM(rts_rspec)) {
3594                         rts_rspec &= ~RSPEC_STF_MASK;
3595                         rts_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
3596                 }
3597         }
3598         return rts_rspec;
3599 }
3600
3601 /*
3602  * Add d11txh_t, cck_phy_hdr_t.
3603  *
3604  * 'p' data must start with 802.11 MAC header
3605  * 'p' must allow enough bytes of local headers to be "pushed" onto the packet
3606  *
3607  * headroom == D11_PHY_HDR_LEN + D11_TXH_LEN (D11_TXH_LEN is now 104 bytes)
3608  *
3609  */
3610 static u16
3611 wlc_d11hdrs_mac80211(struct wlc_info *wlc, struct ieee80211_hw *hw,
3612                      struct sk_buff *p, struct scb *scb, uint frag,
3613                      uint nfrags, uint queue, uint next_frag_len,
3614                      wsec_key_t *key, ratespec_t rspec_override)
3615 {
3616         struct ieee80211_hdr *h;
3617         d11txh_t *txh;
3618         u8 *plcp, plcp_fallback[D11_PHY_HDR_LEN];
3619         int len, phylen, rts_phylen;
3620         u16 mch, phyctl, xfts, mainrates;
3621         u16 seq = 0, mcl = 0, status = 0, frameid = 0;
3622         ratespec_t rspec[2] = { WLC_RATE_1M, WLC_RATE_1M }, rts_rspec[2] = {
3623         WLC_RATE_1M, WLC_RATE_1M};
3624         bool use_rts = false;
3625         bool use_cts = false;
3626         bool use_rifs = false;
3627         bool short_preamble[2] = { false, false };
3628         u8 preamble_type[2] = { WLC_LONG_PREAMBLE, WLC_LONG_PREAMBLE };
3629         u8 rts_preamble_type[2] = { WLC_LONG_PREAMBLE, WLC_LONG_PREAMBLE };
3630         u8 *rts_plcp, rts_plcp_fallback[D11_PHY_HDR_LEN];
3631         struct ieee80211_rts *rts = NULL;
3632         bool qos;
3633         uint ac;
3634         u32 rate_val[2];
3635         bool hwtkmic = false;
3636         u16 mimo_ctlchbw = PHY_TXC1_BW_20MHZ;
3637 #define ANTCFG_NONE 0xFF
3638         u8 antcfg = ANTCFG_NONE;
3639         u8 fbantcfg = ANTCFG_NONE;
3640         uint phyctl1_stf = 0;
3641         u16 durid = 0;
3642         struct ieee80211_tx_rate *txrate[2];
3643         int k;
3644         struct ieee80211_tx_info *tx_info;
3645         bool is_mcs[2];
3646         u16 mimo_txbw;
3647         u8 mimo_preamble_type;
3648
3649         /* locate 802.11 MAC header */
3650         h = (struct ieee80211_hdr *)(p->data);
3651         qos = ieee80211_is_data_qos(h->frame_control);
3652
3653         /* compute length of frame in bytes for use in PLCP computations */
3654         len = bcm_pkttotlen(p);
3655         phylen = len + FCS_LEN;
3656
3657         /* If WEP enabled, add room in phylen for the additional bytes of
3658          * ICV which MAC generates.  We do NOT add the additional bytes to
3659          * the packet itself, thus phylen = packet length + ICV_LEN + FCS_LEN
3660          * in this case
3661          */
3662         if (key) {
3663                 phylen += key->icv_len;
3664         }
3665
3666         /* Get tx_info */
3667         tx_info = IEEE80211_SKB_CB(p);
3668
3669         /* add PLCP */
3670         plcp = skb_push(p, D11_PHY_HDR_LEN);
3671
3672         /* add Broadcom tx descriptor header */
3673         txh = (d11txh_t *) skb_push(p, D11_TXH_LEN);
3674         memset(txh, 0, D11_TXH_LEN);
3675
3676         /* setup frameid */
3677         if (tx_info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
3678                 /* non-AP STA should never use BCMC queue */
3679                 if (queue == TX_BCMC_FIFO) {
3680                         wiphy_err(wlc->wiphy, "wl%d: %s: ASSERT queue == "
3681                                   "TX_BCMC!\n", WLCWLUNIT(wlc), __func__);
3682                         frameid = bcmc_fid_generate(wlc, NULL, txh);
3683                 } else {
3684                         /* Increment the counter for first fragment */
3685                         if (tx_info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT) {
3686                                 SCB_SEQNUM(scb, p->priority)++;
3687                         }
3688
3689                         /* extract fragment number from frame first */
3690                         seq = le16_to_cpu(seq) & FRAGNUM_MASK;
3691                         seq |= (SCB_SEQNUM(scb, p->priority) << SEQNUM_SHIFT);
3692                         h->seq_ctrl = cpu_to_le16(seq);
3693
3694                         frameid = ((seq << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
3695                             (queue & TXFID_QUEUE_MASK);
3696                 }
3697         }
3698         frameid |= queue & TXFID_QUEUE_MASK;
3699
3700         /* set the ignpmq bit for all pkts tx'd in PS mode and for beacons */
3701         if (SCB_PS(scb) || ieee80211_is_beacon(h->frame_control))
3702                 mcl |= TXC_IGNOREPMQ;
3703
3704         txrate[0] = tx_info->control.rates;
3705         txrate[1] = txrate[0] + 1;
3706
3707         /* if rate control algorithm didn't give us a fallback rate, use the primary rate */
3708         if (txrate[1]->idx < 0) {
3709                 txrate[1] = txrate[0];
3710         }
3711
3712         for (k = 0; k < hw->max_rates; k++) {
3713                 is_mcs[k] =
3714                     txrate[k]->flags & IEEE80211_TX_RC_MCS ? true : false;
3715                 if (!is_mcs[k]) {
3716                         if ((txrate[k]->idx >= 0)
3717                             && (txrate[k]->idx <
3718                                 hw->wiphy->bands[tx_info->band]->n_bitrates)) {
3719                                 rate_val[k] =
3720                                     hw->wiphy->bands[tx_info->band]->
3721                                     bitrates[txrate[k]->idx].hw_value;
3722                                 short_preamble[k] =
3723                                     txrate[k]->
3724                                     flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE ?
3725                                     true : false;
3726                         } else {
3727                                 rate_val[k] = WLC_RATE_1M;
3728                         }
3729                 } else {
3730                         rate_val[k] = txrate[k]->idx;
3731                 }
3732                 /* Currently only support same setting for primay and fallback rates.
3733                  * Unify flags for each rate into a single value for the frame
3734                  */
3735                 use_rts |=
3736                     txrate[k]->
3737                     flags & IEEE80211_TX_RC_USE_RTS_CTS ? true : false;
3738                 use_cts |=
3739                     txrate[k]->
3740                     flags & IEEE80211_TX_RC_USE_CTS_PROTECT ? true : false;
3741
3742                 if (is_mcs[k])
3743                         rate_val[k] |= NRATE_MCS_INUSE;
3744
3745                 rspec[k] = mac80211_wlc_set_nrate(wlc, wlc->band, rate_val[k]);
3746
3747                 /* (1) RATE: determine and validate primary rate and fallback rates */
3748                 if (!RSPEC_ACTIVE(rspec[k])) {
3749                         rspec[k] = WLC_RATE_1M;
3750                 } else {
3751                         if (!is_multicast_ether_addr(h->addr1)) {
3752                                 /* set tx antenna config */
3753                                 wlc_antsel_antcfg_get(wlc->asi, false, false, 0,
3754                                                       0, &antcfg, &fbantcfg);
3755                         }
3756                 }
3757         }
3758
3759         phyctl1_stf = wlc->stf->ss_opmode;
3760
3761         if (N_ENAB(wlc->pub)) {
3762                 for (k = 0; k < hw->max_rates; k++) {
3763                         /* apply siso/cdd to single stream mcs's or ofdm if rspec is auto selected */
3764                         if (((IS_MCS(rspec[k]) &&
3765                               IS_SINGLE_STREAM(rspec[k] & RSPEC_RATE_MASK)) ||
3766                              IS_OFDM(rspec[k]))
3767                             && ((rspec[k] & RSPEC_OVERRIDE_MCS_ONLY)
3768                                 || !(rspec[k] & RSPEC_OVERRIDE))) {
3769                                 rspec[k] &= ~(RSPEC_STF_MASK | RSPEC_STC_MASK);
3770
3771                                 /* For SISO MCS use STBC if possible */
3772                                 if (IS_MCS(rspec[k])
3773                                     && WLC_STF_SS_STBC_TX(wlc, scb)) {
3774                                         u8 stc;
3775
3776                                         stc = 1;        /* Nss for single stream is always 1 */
3777                                         rspec[k] |=
3778                                             (PHY_TXC1_MODE_STBC <<
3779                                              RSPEC_STF_SHIFT) | (stc <<
3780                                                                  RSPEC_STC_SHIFT);
3781                                 } else
3782                                         rspec[k] |=
3783                                             (phyctl1_stf << RSPEC_STF_SHIFT);
3784                         }
3785
3786                         /* Is the phy configured to use 40MHZ frames? If so then pick the desired txbw */
3787                         if (CHSPEC_WLC_BW(wlc->chanspec) == WLC_40_MHZ) {
3788                                 /* default txbw is 20in40 SB */
3789                                 mimo_ctlchbw = mimo_txbw =
3790                                     CHSPEC_SB_UPPER(WLC_BAND_PI_RADIO_CHANSPEC)
3791                                     ? PHY_TXC1_BW_20MHZ_UP : PHY_TXC1_BW_20MHZ;
3792
3793                                 if (IS_MCS(rspec[k])) {
3794                                         /* mcs 32 must be 40b/w DUP */
3795                                         if ((rspec[k] & RSPEC_RATE_MASK) == 32) {
3796                                                 mimo_txbw =
3797                                                     PHY_TXC1_BW_40MHZ_DUP;
3798                                                 /* use override */
3799                                         } else if (wlc->mimo_40txbw != AUTO)
3800                                                 mimo_txbw = wlc->mimo_40txbw;
3801                                         /* else check if dst is using 40 Mhz */
3802                                         else if (scb->flags & SCB_IS40)
3803                                                 mimo_txbw = PHY_TXC1_BW_40MHZ;
3804                                 } else if (IS_OFDM(rspec[k])) {
3805                                         if (wlc->ofdm_40txbw != AUTO)
3806                                                 mimo_txbw = wlc->ofdm_40txbw;
3807                                 } else {
3808                                         if (wlc->cck_40txbw != AUTO)
3809                                                 mimo_txbw = wlc->cck_40txbw;
3810                                 }
3811                         } else {
3812                                 /* mcs32 is 40 b/w only.
3813                                  * This is possible for probe packets on a STA during SCAN
3814                                  */
3815                                 if ((rspec[k] & RSPEC_RATE_MASK) == 32) {
3816                                         /* mcs 0 */
3817                                         rspec[k] = RSPEC_MIMORATE;
3818                                 }
3819                                 mimo_txbw = PHY_TXC1_BW_20MHZ;
3820                         }
3821
3822                         /* Set channel width */
3823                         rspec[k] &= ~RSPEC_BW_MASK;
3824                         if ((k == 0) || ((k > 0) && IS_MCS(rspec[k])))
3825                                 rspec[k] |= (mimo_txbw << RSPEC_BW_SHIFT);
3826                         else
3827                                 rspec[k] |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
3828
3829                         /* Set Short GI */
3830 #ifdef NOSGIYET
3831                         if (IS_MCS(rspec[k])
3832                             && (txrate[k]->flags & IEEE80211_TX_RC_SHORT_GI))
3833                                 rspec[k] |= RSPEC_SHORT_GI;
3834                         else if (!(txrate[k]->flags & IEEE80211_TX_RC_SHORT_GI))
3835                                 rspec[k] &= ~RSPEC_SHORT_GI;
3836 #else
3837                         rspec[k] &= ~RSPEC_SHORT_GI;
3838 #endif
3839
3840                         mimo_preamble_type = WLC_MM_PREAMBLE;
3841                         if (txrate[k]->flags & IEEE80211_TX_RC_GREEN_FIELD)
3842                                 mimo_preamble_type = WLC_GF_PREAMBLE;
3843
3844                         if ((txrate[k]->flags & IEEE80211_TX_RC_MCS)
3845                             && (!IS_MCS(rspec[k]))) {
3846                                 wiphy_err(wlc->wiphy, "wl%d: %s: IEEE80211_TX_"
3847                                           "RC_MCS != IS_MCS(rspec)\n",
3848                                           WLCWLUNIT(wlc), __func__);
3849                         }
3850
3851                         if (IS_MCS(rspec[k])) {
3852                                 preamble_type[k] = mimo_preamble_type;
3853
3854                                 /* if SGI is selected, then forced mm for single stream */
3855                                 if ((rspec[k] & RSPEC_SHORT_GI)
3856                                     && IS_SINGLE_STREAM(rspec[k] &
3857                                                         RSPEC_RATE_MASK)) {
3858                                         preamble_type[k] = WLC_MM_PREAMBLE;
3859                                 }
3860                         }
3861
3862                         /* should be better conditionalized */
3863                         if (!IS_MCS(rspec[0])
3864                             && (tx_info->control.rates[0].
3865                                 flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE))
3866                                 preamble_type[k] = WLC_SHORT_PREAMBLE;
3867                 }
3868         } else {
3869                 for (k = 0; k < hw->max_rates; k++) {
3870                         /* Set ctrlchbw as 20Mhz */
3871                         rspec[k] &= ~RSPEC_BW_MASK;
3872                         rspec[k] |= (PHY_TXC1_BW_20MHZ << RSPEC_BW_SHIFT);
3873
3874                         /* for nphy, stf of ofdm frames must follow policies */
3875                         if (WLCISNPHY(wlc->band) && IS_OFDM(rspec[k])) {
3876                                 rspec[k] &= ~RSPEC_STF_MASK;
3877                                 rspec[k] |= phyctl1_stf << RSPEC_STF_SHIFT;
3878                         }
3879                 }
3880         }
3881
3882         /* Reset these for use with AMPDU's */
3883         txrate[0]->count = 0;
3884         txrate[1]->count = 0;
3885
3886         /* (2) PROTECTION, may change rspec */
3887         if ((ieee80211_is_data(h->frame_control) ||
3888             ieee80211_is_mgmt(h->frame_control)) &&
3889             (phylen > wlc->RTSThresh) && !is_multicast_ether_addr(h->addr1))
3890                 use_rts = true;
3891
3892         /* (3) PLCP: determine PLCP header and MAC duration, fill d11txh_t */
3893         wlc_compute_plcp(wlc, rspec[0], phylen, plcp);
3894         wlc_compute_plcp(wlc, rspec[1], phylen, plcp_fallback);
3895         memcpy(&txh->FragPLCPFallback,
3896                plcp_fallback, sizeof(txh->FragPLCPFallback));
3897
3898         /* Length field now put in CCK FBR CRC field */
3899         if (IS_CCK(rspec[1])) {
3900                 txh->FragPLCPFallback[4] = phylen & 0xff;
3901                 txh->FragPLCPFallback[5] = (phylen & 0xff00) >> 8;
3902         }
3903
3904         /* MIMO-RATE: need validation ?? */
3905         mainrates =
3906             IS_OFDM(rspec[0]) ? D11A_PHY_HDR_GRATE((ofdm_phy_hdr_t *) plcp) :
3907             plcp[0];
3908
3909         /* DUR field for main rate */
3910         if (!ieee80211_is_pspoll(h->frame_control) &&
3911             !is_multicast_ether_addr(h->addr1) && !use_rifs) {
3912                 durid =
3913                     wlc_compute_frame_dur(wlc, rspec[0], preamble_type[0],
3914                                           next_frag_len);
3915                 h->duration_id = cpu_to_le16(durid);
3916         } else if (use_rifs) {
3917                 /* NAV protect to end of next max packet size */
3918                 durid =
3919                     (u16) wlc_calc_frame_time(wlc, rspec[0],
3920                                                  preamble_type[0],
3921                                                  DOT11_MAX_FRAG_LEN);
3922                 durid += RIFS_11N_TIME;
3923                 h->duration_id = cpu_to_le16(durid);
3924         }
3925
3926         /* DUR field for fallback rate */
3927         if (ieee80211_is_pspoll(h->frame_control))
3928                 txh->FragDurFallback = h->duration_id;
3929         else if (is_multicast_ether_addr(h->addr1) || use_rifs)
3930                 txh->FragDurFallback = 0;
3931         else {
3932                 durid = wlc_compute_frame_dur(wlc, rspec[1],
3933                                               preamble_type[1], next_frag_len);
3934                 txh->FragDurFallback = cpu_to_le16(durid);
3935         }
3936
3937         /* (4) MAC-HDR: MacTxControlLow */
3938         if (frag == 0)
3939                 mcl |= TXC_STARTMSDU;
3940
3941         if (!is_multicast_ether_addr(h->addr1))
3942                 mcl |= TXC_IMMEDACK;
3943
3944         if (BAND_5G(wlc->band->bandtype))
3945                 mcl |= TXC_FREQBAND_5G;
3946
3947         if (CHSPEC_IS40(WLC_BAND_PI_RADIO_CHANSPEC))
3948                 mcl |= TXC_BW_40;
3949
3950         /* set AMIC bit if using hardware TKIP MIC */
3951         if (hwtkmic)
3952                 mcl |= TXC_AMIC;
3953
3954         txh->MacTxControlLow = cpu_to_le16(mcl);
3955
3956         /* MacTxControlHigh */
3957         mch = 0;
3958
3959         /* Set fallback rate preamble type */
3960         if ((preamble_type[1] == WLC_SHORT_PREAMBLE) ||
3961             (preamble_type[1] == WLC_GF_PREAMBLE)) {
3962                 if (RSPEC2RATE(rspec[1]) != WLC_RATE_1M)
3963                         mch |= TXC_PREAMBLE_DATA_FB_SHORT;
3964         }
3965
3966         /* MacFrameControl */
3967         memcpy(&txh->MacFrameControl, &h->frame_control, sizeof(u16));
3968         txh->TxFesTimeNormal = cpu_to_le16(0);
3969
3970         txh->TxFesTimeFallback = cpu_to_le16(0);
3971
3972         /* TxFrameRA */
3973         memcpy(&txh->TxFrameRA, &h->addr1, ETH_ALEN);
3974
3975         /* TxFrameID */
3976         txh->TxFrameID = cpu_to_le16(frameid);
3977
3978         /* TxStatus, Note the case of recreating the first frag of a suppressed frame
3979          * then we may need to reset the retry cnt's via the status reg
3980          */
3981         txh->TxStatus = cpu_to_le16(status);
3982
3983         /* extra fields for ucode AMPDU aggregation, the new fields are added to
3984          * the END of previous structure so that it's compatible in driver.
3985          */
3986         txh->MaxNMpdus = cpu_to_le16(0);
3987         txh->MaxABytes_MRT = cpu_to_le16(0);
3988         txh->MaxABytes_FBR = cpu_to_le16(0);
3989         txh->MinMBytes = cpu_to_le16(0);
3990
3991         /* (5) RTS/CTS: determine RTS/CTS PLCP header and MAC duration, furnish d11txh_t */
3992         /* RTS PLCP header and RTS frame */
3993         if (use_rts || use_cts) {
3994                 if (use_rts && use_cts)
3995                         use_cts = false;
3996
3997                 for (k = 0; k < 2; k++) {
3998                         rts_rspec[k] = wlc_rspec_to_rts_rspec(wlc, rspec[k],
3999                                                               false,
4000                                                               mimo_ctlchbw);
4001                 }
4002
4003                 if (!IS_OFDM(rts_rspec[0]) &&
4004                     !((RSPEC2RATE(rts_rspec[0]) == WLC_RATE_1M) ||
4005                       (wlc->PLCPHdr_override == WLC_PLCP_LONG))) {
4006                         rts_preamble_type[0] = WLC_SHORT_PREAMBLE;
4007                         mch |= TXC_PREAMBLE_RTS_MAIN_SHORT;
4008                 }
4009
4010                 if (!IS_OFDM(rts_rspec[1]) &&
4011                     !((RSPEC2RATE(rts_rspec[1]) == WLC_RATE_1M) ||
4012                       (wlc->PLCPHdr_override == WLC_PLCP_LONG))) {
4013                         rts_preamble_type[1] = WLC_SHORT_PREAMBLE;
4014                         mch |= TXC_PREAMBLE_RTS_FB_SHORT;
4015                 }
4016
4017                 /* RTS/CTS additions to MacTxControlLow */
4018                 if (use_cts) {
4019                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDCTS);
4020                 } else {
4021                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDRTS);
4022                         txh->MacTxControlLow |= cpu_to_le16(TXC_LONGFRAME);
4023                 }
4024
4025                 /* RTS PLCP header */
4026                 rts_plcp = txh->RTSPhyHeader;
4027                 if (use_cts)
4028                         rts_phylen = DOT11_CTS_LEN + FCS_LEN;
4029                 else
4030                         rts_phylen = DOT11_RTS_LEN + FCS_LEN;
4031
4032                 wlc_compute_plcp(wlc, rts_rspec[0], rts_phylen, rts_plcp);
4033
4034                 /* fallback rate version of RTS PLCP header */
4035                 wlc_compute_plcp(wlc, rts_rspec[1], rts_phylen,
4036                                  rts_plcp_fallback);
4037                 memcpy(&txh->RTSPLCPFallback, rts_plcp_fallback,
4038                        sizeof(txh->RTSPLCPFallback));
4039
4040                 /* RTS frame fields... */
4041                 rts = (struct ieee80211_rts *)&txh->rts_frame;
4042
4043                 durid = wlc_compute_rtscts_dur(wlc, use_cts, rts_rspec[0],
4044                                                rspec[0], rts_preamble_type[0],
4045                                                preamble_type[0], phylen, false);
4046                 rts->duration = cpu_to_le16(durid);
4047                 /* fallback rate version of RTS DUR field */
4048                 durid = wlc_compute_rtscts_dur(wlc, use_cts,
4049                                                rts_rspec[1], rspec[1],
4050                                                rts_preamble_type[1],
4051                                                preamble_type[1], phylen, false);
4052                 txh->RTSDurFallback = cpu_to_le16(durid);
4053
4054                 if (use_cts) {
4055                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
4056                                                          IEEE80211_STYPE_CTS);
4057
4058                         memcpy(&rts->ra, &h->addr2, ETH_ALEN);
4059                 } else {
4060                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
4061                                                          IEEE80211_STYPE_RTS);
4062
4063                         memcpy(&rts->ra, &h->addr1, 2 * ETH_ALEN);
4064                 }
4065
4066                 /* mainrate
4067                  *    low 8 bits: main frag rate/mcs,
4068                  *    high 8 bits: rts/cts rate/mcs
4069                  */
4070                 mainrates |= (IS_OFDM(rts_rspec[0]) ?
4071                               D11A_PHY_HDR_GRATE((ofdm_phy_hdr_t *) rts_plcp) :
4072                               rts_plcp[0]) << 8;
4073         } else {
4074                 memset((char *)txh->RTSPhyHeader, 0, D11_PHY_HDR_LEN);
4075                 memset((char *)&txh->rts_frame, 0,
4076                         sizeof(struct ieee80211_rts));
4077                 memset((char *)txh->RTSPLCPFallback, 0,
4078                       sizeof(txh->RTSPLCPFallback));
4079                 txh->RTSDurFallback = 0;
4080         }
4081
4082 #ifdef SUPPORT_40MHZ
4083         /* add null delimiter count */
4084         if ((tx_info->flags & IEEE80211_TX_CTL_AMPDU) && IS_MCS(rspec)) {
4085                 txh->RTSPLCPFallback[AMPDU_FBR_NULL_DELIM] =
4086                     wlc_ampdu_null_delim_cnt(wlc->ampdu, scb, rspec, phylen);
4087         }
4088 #endif
4089
4090         /* Now that RTS/RTS FB preamble types are updated, write the final value */
4091         txh->MacTxControlHigh = cpu_to_le16(mch);
4092
4093         /* MainRates (both the rts and frag plcp rates have been calculated now) */
4094         txh->MainRates = cpu_to_le16(mainrates);
4095
4096         /* XtraFrameTypes */
4097         xfts = FRAMETYPE(rspec[1], wlc->mimoft);
4098         xfts |= (FRAMETYPE(rts_rspec[0], wlc->mimoft) << XFTS_RTS_FT_SHIFT);
4099         xfts |= (FRAMETYPE(rts_rspec[1], wlc->mimoft) << XFTS_FBRRTS_FT_SHIFT);
4100         xfts |=
4101             CHSPEC_CHANNEL(WLC_BAND_PI_RADIO_CHANSPEC) << XFTS_CHANNEL_SHIFT;
4102         txh->XtraFrameTypes = cpu_to_le16(xfts);
4103
4104         /* PhyTxControlWord */
4105         phyctl = FRAMETYPE(rspec[0], wlc->mimoft);
4106         if ((preamble_type[0] == WLC_SHORT_PREAMBLE) ||
4107             (preamble_type[0] == WLC_GF_PREAMBLE)) {
4108                 if (RSPEC2RATE(rspec[0]) != WLC_RATE_1M)
4109                         phyctl |= PHY_TXC_SHORT_HDR;
4110         }
4111
4112         /* phytxant is properly bit shifted */
4113         phyctl |= wlc_stf_d11hdrs_phyctl_txant(wlc, rspec[0]);
4114         txh->PhyTxControlWord = cpu_to_le16(phyctl);
4115
4116         /* PhyTxControlWord_1 */
4117         if (WLC_PHY_11N_CAP(wlc->band)) {
4118                 u16 phyctl1 = 0;
4119
4120                 phyctl1 = wlc_phytxctl1_calc(wlc, rspec[0]);
4121                 txh->PhyTxControlWord_1 = cpu_to_le16(phyctl1);
4122                 phyctl1 = wlc_phytxctl1_calc(wlc, rspec[1]);
4123                 txh->PhyTxControlWord_1_Fbr = cpu_to_le16(phyctl1);
4124
4125                 if (use_rts || use_cts) {
4126                         phyctl1 = wlc_phytxctl1_calc(wlc, rts_rspec[0]);
4127                         txh->PhyTxControlWord_1_Rts = cpu_to_le16(phyctl1);
4128                         phyctl1 = wlc_phytxctl1_calc(wlc, rts_rspec[1]);
4129                         txh->PhyTxControlWord_1_FbrRts = cpu_to_le16(phyctl1);
4130                 }
4131
4132                 /*
4133                  * For mcs frames, if mixedmode(overloaded with long preamble) is going to be set,
4134                  * fill in non-zero MModeLen and/or MModeFbrLen
4135                  *  it will be unnecessary if they are separated
4136                  */
4137                 if (IS_MCS(rspec[0]) && (preamble_type[0] == WLC_MM_PREAMBLE)) {
4138                         u16 mmodelen =
4139                             wlc_calc_lsig_len(wlc, rspec[0], phylen);
4140                         txh->MModeLen = cpu_to_le16(mmodelen);
4141                 }
4142
4143                 if (IS_MCS(rspec[1]) && (preamble_type[1] == WLC_MM_PREAMBLE)) {
4144                         u16 mmodefbrlen =
4145                             wlc_calc_lsig_len(wlc, rspec[1], phylen);
4146                         txh->MModeFbrLen = cpu_to_le16(mmodefbrlen);
4147                 }
4148         }
4149
4150         ac = skb_get_queue_mapping(p);
4151         if (SCB_WME(scb) && qos && wlc->edcf_txop[ac]) {
4152                 uint frag_dur, dur, dur_fallback;
4153
4154                 /* WME: Update TXOP threshold */
4155                 if ((!(tx_info->flags & IEEE80211_TX_CTL_AMPDU)) && (frag == 0)) {
4156                         frag_dur =
4157                             wlc_calc_frame_time(wlc, rspec[0], preamble_type[0],
4158                                                 phylen);
4159
4160                         if (rts) {
4161                                 /* 1 RTS or CTS-to-self frame */
4162                                 dur =
4163                                     wlc_calc_cts_time(wlc, rts_rspec[0],
4164                                                       rts_preamble_type[0]);
4165                                 dur_fallback =
4166                                     wlc_calc_cts_time(wlc, rts_rspec[1],
4167                                                       rts_preamble_type[1]);
4168                                 /* (SIFS + CTS) + SIFS + frame + SIFS + ACK */
4169                                 dur += le16_to_cpu(rts->duration);
4170                                 dur_fallback +=
4171                                         le16_to_cpu(txh->RTSDurFallback);
4172                         } else if (use_rifs) {
4173                                 dur = frag_dur;
4174                                 dur_fallback = 0;
4175                         } else {
4176                                 /* frame + SIFS + ACK */
4177                                 dur = frag_dur;
4178                                 dur +=
4179                                     wlc_compute_frame_dur(wlc, rspec[0],
4180                                                           preamble_type[0], 0);
4181
4182                                 dur_fallback =
4183                                     wlc_calc_frame_time(wlc, rspec[1],
4184                                                         preamble_type[1],
4185                                                         phylen);
4186                                 dur_fallback +=
4187                                     wlc_compute_frame_dur(wlc, rspec[1],
4188                                                           preamble_type[1], 0);
4189                         }
4190                         /* NEED to set TxFesTimeNormal (hard) */
4191                         txh->TxFesTimeNormal = cpu_to_le16((u16) dur);
4192                         /* NEED to set fallback rate version of TxFesTimeNormal (hard) */
4193                         txh->TxFesTimeFallback =
4194                                 cpu_to_le16((u16) dur_fallback);
4195
4196                         /* update txop byte threshold (txop minus intraframe overhead) */
4197                         if (wlc->edcf_txop[ac] >= (dur - frag_dur)) {
4198                                 {
4199                                         uint newfragthresh;
4200
4201                                         newfragthresh =
4202                                             wlc_calc_frame_len(wlc, rspec[0],
4203                                                                preamble_type[0],
4204                                                                (wlc->
4205                                                                 edcf_txop[ac] -
4206                                                                 (dur -
4207                                                                  frag_dur)));
4208                                         /* range bound the fragthreshold */
4209                                         if (newfragthresh < DOT11_MIN_FRAG_LEN)
4210                                                 newfragthresh =
4211                                                     DOT11_MIN_FRAG_LEN;
4212                                         else if (newfragthresh >
4213                                                  wlc->usr_fragthresh)
4214                                                 newfragthresh =
4215                                                     wlc->usr_fragthresh;
4216                                         /* update the fragthresh and do txc update */
4217                                         if (wlc->fragthresh[queue] !=
4218                                             (u16) newfragthresh) {
4219                                                 wlc->fragthresh[queue] =
4220                                                     (u16) newfragthresh;
4221                                         }
4222                                 }
4223                         } else
4224                                 wiphy_err(wlc->wiphy, "wl%d: %s txop invalid "
4225                                           "for rate %d\n",
4226                                           wlc->pub->unit, fifo_names[queue],
4227                                           RSPEC2RATE(rspec[0]));
4228
4229                         if (dur > wlc->edcf_txop[ac])
4230                                 wiphy_err(wlc->wiphy, "wl%d: %s: %s txop "
4231                                           "exceeded phylen %d/%d dur %d/%d\n",
4232                                           wlc->pub->unit, __func__,
4233                                           fifo_names[queue],
4234                                           phylen, wlc->fragthresh[queue],
4235                                           dur, wlc->edcf_txop[ac]);
4236                 }
4237         }
4238
4239         return 0;
4240 }
4241
4242 void wlc_tbtt(struct wlc_info *wlc, d11regs_t *regs)
4243 {
4244         struct wlc_bsscfg *cfg = wlc->cfg;
4245
4246         if (!cfg->BSS) {
4247                 /* DirFrmQ is now valid...defer setting until end of ATIM window */
4248                 wlc->qvalid |= MCMD_DIRFRMQVAL;
4249         }
4250 }
4251
4252 static void wlc_war16165(struct wlc_info *wlc, bool tx)
4253 {
4254         if (tx) {
4255                 /* the post-increment is used in STAY_AWAKE macro */
4256                 if (wlc->txpend16165war++ == 0)
4257                         wlc_set_ps_ctrl(wlc);
4258         } else {
4259                 wlc->txpend16165war--;
4260                 if (wlc->txpend16165war == 0)
4261                         wlc_set_ps_ctrl(wlc);
4262         }
4263 }
4264
4265 /* process an individual tx_status_t */
4266 /* WLC_HIGH_API */
4267 bool
4268 wlc_dotxstatus(struct wlc_info *wlc, tx_status_t *txs, u32 frm_tx2)
4269 {
4270         struct sk_buff *p;
4271         uint queue;
4272         d11txh_t *txh;
4273         struct scb *scb = NULL;
4274         bool free_pdu;
4275         int tx_rts, tx_frame_count, tx_rts_count;
4276         uint totlen, supr_status;
4277         bool lastframe;
4278         struct ieee80211_hdr *h;
4279         u16 mcl;
4280         struct ieee80211_tx_info *tx_info;
4281         struct ieee80211_tx_rate *txrate;
4282         int i;
4283
4284         (void)(frm_tx2);        /* Compiler reference to avoid unused variable warning */
4285
4286         /* discard intermediate indications for ucode with one legitimate case:
4287          *   e.g. if "useRTS" is set. ucode did a successful rts/cts exchange, but the subsequent
4288          *   tx of DATA failed. so it will start rts/cts from the beginning (resetting the rts
4289          *   transmission count)
4290          */
4291         if (!(txs->status & TX_STATUS_AMPDU)
4292             && (txs->status & TX_STATUS_INTERMEDIATE)) {
4293                 wiphy_err(wlc->wiphy, "%s: INTERMEDIATE but not AMPDU\n",
4294                           __func__);
4295                 return false;
4296         }
4297
4298         queue = txs->frameid & TXFID_QUEUE_MASK;
4299         if (queue >= NFIFO) {
4300                 p = NULL;
4301                 goto fatal;
4302         }
4303
4304         p = GETNEXTTXP(wlc, queue);
4305         if (WLC_WAR16165(wlc))
4306                 wlc_war16165(wlc, false);
4307         if (p == NULL)
4308                 goto fatal;
4309
4310         txh = (d11txh_t *) (p->data);
4311         mcl = le16_to_cpu(txh->MacTxControlLow);
4312
4313         if (txs->phyerr) {
4314                 if (WL_ERROR_ON()) {
4315                         wiphy_err(wlc->wiphy, "phyerr 0x%x, rate 0x%x\n",
4316                                   txs->phyerr, txh->MainRates);
4317                         wlc_print_txdesc(txh);
4318                 }
4319                 wlc_print_txstatus(txs);
4320         }
4321
4322         if (txs->frameid != cpu_to_le16(txh->TxFrameID))
4323                 goto fatal;
4324         tx_info = IEEE80211_SKB_CB(p);
4325         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
4326
4327         if (tx_info->control.sta)
4328                 scb = (struct scb *)tx_info->control.sta->drv_priv;
4329
4330         if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
4331                 wlc_ampdu_dotxstatus(wlc->ampdu, scb, p, txs);
4332                 return false;
4333         }
4334
4335         supr_status = txs->status & TX_STATUS_SUPR_MASK;
4336         if (supr_status == TX_STATUS_SUPR_BADCH)
4337                 BCMMSG(wlc->wiphy,
4338                        "%s: Pkt tx suppressed, possibly channel %d\n",
4339                        __func__, CHSPEC_CHANNEL(wlc->default_bss->chanspec));
4340
4341         tx_rts = cpu_to_le16(txh->MacTxControlLow) & TXC_SENDRTS;
4342         tx_frame_count =
4343             (txs->status & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT;
4344         tx_rts_count =
4345             (txs->status & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT;
4346
4347         lastframe = !ieee80211_has_morefrags(h->frame_control);
4348
4349         if (!lastframe) {
4350                 wiphy_err(wlc->wiphy, "Not last frame!\n");
4351         } else {
4352                 u16 sfbl, lfbl;
4353                 ieee80211_tx_info_clear_status(tx_info);
4354                 if (queue < AC_COUNT) {
4355                         sfbl = WLC_WME_RETRY_SFB_GET(wlc, wme_fifo2ac[queue]);
4356                         lfbl = WLC_WME_RETRY_LFB_GET(wlc, wme_fifo2ac[queue]);
4357                 } else {
4358                         sfbl = wlc->SFBL;
4359                         lfbl = wlc->LFBL;
4360                 }
4361
4362                 txrate = tx_info->status.rates;
4363                 /* FIXME: this should use a combination of sfbl, lfbl depending on frame length and RTS setting */
4364                 if ((tx_frame_count > sfbl) && (txrate[1].idx >= 0)) {
4365                         /* rate selection requested a fallback rate and we used it */
4366                         txrate->count = lfbl;
4367                         txrate[1].count = tx_frame_count - lfbl;
4368                 } else {
4369                         /* rate selection did not request fallback rate, or we didn't need it */
4370                         txrate->count = tx_frame_count;
4371                         /* rc80211_minstrel.c:minstrel_tx_status() expects unused rates to be marked with idx = -1 */
4372                         txrate[1].idx = -1;
4373                         txrate[1].count = 0;
4374                 }
4375
4376                 /* clear the rest of the rates */
4377                 for (i = 2; i < IEEE80211_TX_MAX_RATES; i++) {
4378                         txrate[i].idx = -1;
4379                         txrate[i].count = 0;
4380                 }
4381
4382                 if (txs->status & TX_STATUS_ACK_RCV)
4383                         tx_info->flags |= IEEE80211_TX_STAT_ACK;
4384         }
4385
4386         totlen = bcm_pkttotlen(p);
4387         free_pdu = true;
4388
4389         wlc_txfifo_complete(wlc, queue, 1);
4390
4391         if (lastframe) {
4392                 p->next = NULL;
4393                 p->prev = NULL;
4394                 /* remove PLCP & Broadcom tx descriptor header */
4395                 skb_pull(p, D11_PHY_HDR_LEN);
4396                 skb_pull(p, D11_TXH_LEN);
4397                 ieee80211_tx_status_irqsafe(wlc->pub->ieee_hw, p);
4398         } else {
4399                 wiphy_err(wlc->wiphy, "%s: Not last frame => not calling "
4400                           "tx_status\n", __func__);
4401         }
4402
4403         return false;
4404
4405  fatal:
4406         if (p)
4407                 bcm_pkt_buf_free_skb(p);
4408
4409         return true;
4410
4411 }
4412
4413 void
4414 wlc_txfifo_complete(struct wlc_info *wlc, uint fifo, s8 txpktpend)
4415 {
4416         TXPKTPENDDEC(wlc, fifo, txpktpend);
4417         BCMMSG(wlc->wiphy, "pktpend dec %d to %d\n", txpktpend,
4418                 TXPKTPENDGET(wlc, fifo));
4419
4420         /* There is more room; mark precedences related to this FIFO sendable */
4421         WLC_TX_FIFO_ENAB(wlc, fifo);
4422
4423         /* Clear MHF2_TXBCMC_NOW flag if BCMC fifo has drained */
4424         if (AP_ENAB(wlc->pub) &&
4425             !TXPKTPENDGET(wlc, TX_BCMC_FIFO)) {
4426                 wlc_mhf(wlc, MHF2, MHF2_TXBCMC_NOW, 0, WLC_BAND_AUTO);
4427         }
4428
4429         /* figure out which bsscfg is being worked on... */
4430 }
4431
4432 /* Update beacon listen interval in shared memory */
4433 void wlc_bcn_li_upd(struct wlc_info *wlc)
4434 {
4435         if (AP_ENAB(wlc->pub))
4436                 return;
4437
4438         /* wake up every DTIM is the default */
4439         if (wlc->bcn_li_dtim == 1)
4440                 wlc_write_shm(wlc, M_BCN_LI, 0);
4441         else
4442                 wlc_write_shm(wlc, M_BCN_LI,
4443                               (wlc->bcn_li_dtim << 8) | wlc->bcn_li_bcn);
4444 }
4445
4446 /*
4447  * recover 64bit TSF value from the 16bit TSF value in the rx header
4448  * given the assumption that the TSF passed in header is within 65ms
4449  * of the current tsf.
4450  *
4451  * 6       5       4       4       3       2       1
4452  * 3.......6.......8.......0.......2.......4.......6.......8......0
4453  * |<---------- tsf_h ----------->||<--- tsf_l -->||<-RxTSFTime ->|
4454  *
4455  * The RxTSFTime are the lowest 16 bits and provided by the ucode. The
4456  * tsf_l is filled in by wlc_bmac_recv, which is done earlier in the
4457  * receive call sequence after rx interrupt. Only the higher 16 bits
4458  * are used. Finally, the tsf_h is read from the tsf register.
4459  */
4460 static u64 wlc_recover_tsf64(struct wlc_info *wlc, struct wlc_d11rxhdr *rxh)
4461 {
4462         u32 tsf_h, tsf_l;
4463         u16 rx_tsf_0_15, rx_tsf_16_31;
4464
4465         wlc_bmac_read_tsf(wlc->hw, &tsf_l, &tsf_h);
4466
4467         rx_tsf_16_31 = (u16)(tsf_l >> 16);
4468         rx_tsf_0_15 = rxh->rxhdr.RxTSFTime;
4469
4470         /*
4471          * a greater tsf time indicates the low 16 bits of
4472          * tsf_l wrapped, so decrement the high 16 bits.
4473          */
4474         if ((u16)tsf_l < rx_tsf_0_15) {
4475                 rx_tsf_16_31 -= 1;
4476                 if (rx_tsf_16_31 == 0xffff)
4477                         tsf_h -= 1;
4478         }
4479
4480         return ((u64)tsf_h << 32) | (((u32)rx_tsf_16_31 << 16) + rx_tsf_0_15);
4481 }
4482
4483 static void
4484 prep_mac80211_status(struct wlc_info *wlc, d11rxhdr_t *rxh, struct sk_buff *p,
4485                      struct ieee80211_rx_status *rx_status)
4486 {
4487         wlc_d11rxhdr_t *wlc_rxh = (wlc_d11rxhdr_t *) rxh;
4488         int preamble;
4489         int channel;
4490         ratespec_t rspec;
4491         unsigned char *plcp;
4492
4493         /* fill in TSF and flag its presence */
4494         rx_status->mactime = wlc_recover_tsf64(wlc, wlc_rxh);
4495         rx_status->flag |= RX_FLAG_MACTIME_MPDU;
4496
4497         channel = WLC_CHAN_CHANNEL(rxh->RxChan);
4498
4499         if (channel > 14) {
4500                 rx_status->band = IEEE80211_BAND_5GHZ;
4501                 rx_status->freq = ieee80211_ofdm_chan_to_freq(
4502                                         WF_CHAN_FACTOR_5_G/2, channel);
4503
4504         } else {
4505                 rx_status->band = IEEE80211_BAND_2GHZ;
4506                 rx_status->freq = ieee80211_dsss_chan_to_freq(channel);
4507         }
4508
4509         rx_status->signal = wlc_rxh->rssi;      /* signal */
4510
4511         /* noise */
4512         /* qual */
4513         rx_status->antenna = (rxh->PhyRxStatus_0 & PRXS0_RXANT_UPSUBBAND) ? 1 : 0;      /* ant */
4514
4515         plcp = p->data;
4516
4517         rspec = wlc_compute_rspec(rxh, plcp);
4518         if (IS_MCS(rspec)) {
4519                 rx_status->rate_idx = rspec & RSPEC_RATE_MASK;
4520                 rx_status->flag |= RX_FLAG_HT;
4521                 if (RSPEC_IS40MHZ(rspec))
4522                         rx_status->flag |= RX_FLAG_40MHZ;
4523         } else {
4524                 switch (RSPEC2RATE(rspec)) {
4525                 case WLC_RATE_1M:
4526                         rx_status->rate_idx = 0;
4527                         break;
4528                 case WLC_RATE_2M:
4529                         rx_status->rate_idx = 1;
4530                         break;
4531                 case WLC_RATE_5M5:
4532                         rx_status->rate_idx = 2;
4533                         break;
4534                 case WLC_RATE_11M:
4535                         rx_status->rate_idx = 3;
4536                         break;
4537                 case WLC_RATE_6M:
4538                         rx_status->rate_idx = 4;
4539                         break;
4540                 case WLC_RATE_9M:
4541                         rx_status->rate_idx = 5;
4542                         break;
4543                 case WLC_RATE_12M:
4544                         rx_status->rate_idx = 6;
4545                         break;
4546                 case WLC_RATE_18M:
4547                         rx_status->rate_idx = 7;
4548                         break;
4549                 case WLC_RATE_24M:
4550                         rx_status->rate_idx = 8;
4551                         break;
4552                 case WLC_RATE_36M:
4553                         rx_status->rate_idx = 9;
4554                         break;
4555                 case WLC_RATE_48M:
4556                         rx_status->rate_idx = 10;
4557                         break;
4558                 case WLC_RATE_54M:
4559                         rx_status->rate_idx = 11;
4560                         break;
4561                 default:
4562                         wiphy_err(wlc->wiphy, "%s: Unknown rate\n", __func__);
4563                 }
4564
4565                 /* Determine short preamble and rate_idx */
4566                 preamble = 0;
4567                 if (IS_CCK(rspec)) {
4568                         if (rxh->PhyRxStatus_0 & PRXS0_SHORTH)
4569                                 rx_status->flag |= RX_FLAG_SHORTPRE;
4570                 } else if (IS_OFDM(rspec)) {
4571                         rx_status->flag |= RX_FLAG_SHORTPRE;
4572                 } else {
4573                         wiphy_err(wlc->wiphy, "%s: Unknown modulation\n",
4574                                   __func__);
4575                 }
4576         }
4577
4578         if (PLCP3_ISSGI(plcp[3]))
4579                 rx_status->flag |= RX_FLAG_SHORT_GI;
4580
4581         if (rxh->RxStatus1 & RXS_DECERR) {
4582                 rx_status->flag |= RX_FLAG_FAILED_PLCP_CRC;
4583                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_PLCP_CRC\n",
4584                           __func__);
4585         }
4586         if (rxh->RxStatus1 & RXS_FCSERR) {
4587                 rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
4588                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_FCS_CRC\n",
4589                           __func__);
4590         }
4591 }
4592
4593 static void
4594 wlc_recvctl(struct wlc_info *wlc, d11rxhdr_t *rxh, struct sk_buff *p)
4595 {
4596         int len_mpdu;
4597         struct ieee80211_rx_status rx_status;
4598
4599         memset(&rx_status, 0, sizeof(rx_status));
4600         prep_mac80211_status(wlc, rxh, p, &rx_status);
4601
4602         /* mac header+body length, exclude CRC and plcp header */
4603         len_mpdu = p->len - D11_PHY_HDR_LEN - FCS_LEN;
4604         skb_pull(p, D11_PHY_HDR_LEN);
4605         __skb_trim(p, len_mpdu);
4606
4607         memcpy(IEEE80211_SKB_RXCB(p), &rx_status, sizeof(rx_status));
4608         ieee80211_rx_irqsafe(wlc->pub->ieee_hw, p);
4609         return;
4610 }
4611
4612 /* Process received frames */
4613 /*
4614  * Return true if more frames need to be processed. false otherwise.
4615  * Param 'bound' indicates max. # frames to process before break out.
4616  */
4617 /* WLC_HIGH_API */
4618 void wlc_recv(struct wlc_info *wlc, struct sk_buff *p)
4619 {
4620         d11rxhdr_t *rxh;
4621         struct ieee80211_hdr *h;
4622         uint len;
4623         bool is_amsdu;
4624
4625         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
4626
4627         /* frame starts with rxhdr */
4628         rxh = (d11rxhdr_t *) (p->data);
4629
4630         /* strip off rxhdr */
4631         skb_pull(p, WL_HWRXOFF);
4632
4633         /* fixup rx header endianness */
4634         rxh->RxFrameSize = le16_to_cpu(rxh->RxFrameSize);
4635         rxh->PhyRxStatus_0 = le16_to_cpu(rxh->PhyRxStatus_0);
4636         rxh->PhyRxStatus_1 = le16_to_cpu(rxh->PhyRxStatus_1);
4637         rxh->PhyRxStatus_2 = le16_to_cpu(rxh->PhyRxStatus_2);
4638         rxh->PhyRxStatus_3 = le16_to_cpu(rxh->PhyRxStatus_3);
4639         rxh->PhyRxStatus_4 = le16_to_cpu(rxh->PhyRxStatus_4);
4640         rxh->PhyRxStatus_5 = le16_to_cpu(rxh->PhyRxStatus_5);
4641         rxh->RxStatus1 = le16_to_cpu(rxh->RxStatus1);
4642         rxh->RxStatus2 = le16_to_cpu(rxh->RxStatus2);
4643         rxh->RxTSFTime = le16_to_cpu(rxh->RxTSFTime);
4644         rxh->RxChan = le16_to_cpu(rxh->RxChan);
4645
4646         /* MAC inserts 2 pad bytes for a4 headers or QoS or A-MSDU subframes */
4647         if (rxh->RxStatus1 & RXS_PBPRES) {
4648                 if (p->len < 2) {
4649                         wiphy_err(wlc->wiphy, "wl%d: wlc_recv: rcvd runt of "
4650                                   "len %d\n", wlc->pub->unit, p->len);
4651                         goto toss;
4652                 }
4653                 skb_pull(p, 2);
4654         }
4655
4656         h = (struct ieee80211_hdr *)(p->data + D11_PHY_HDR_LEN);
4657         len = p->len;
4658
4659         if (rxh->RxStatus1 & RXS_FCSERR) {
4660                 if (wlc->pub->mac80211_state & MAC80211_PROMISC_BCNS) {
4661                         wiphy_err(wlc->wiphy, "FCSERR while scanning******* -"
4662                                   " tossing\n");
4663                         goto toss;
4664                 } else {
4665                         wiphy_err(wlc->wiphy, "RCSERR!!!\n");
4666                         goto toss;
4667                 }
4668         }
4669
4670         /* check received pkt has at least frame control field */
4671         if (len < D11_PHY_HDR_LEN + sizeof(h->frame_control)) {
4672                 goto toss;
4673         }
4674
4675         is_amsdu = rxh->RxStatus2 & RXS_AMSDU_MASK;
4676
4677         /* explicitly test bad src address to avoid sending bad deauth */
4678         if (!is_amsdu) {
4679                 /* CTS and ACK CTL frames are w/o a2 */
4680
4681                 if (ieee80211_is_data(h->frame_control) ||
4682                     ieee80211_is_mgmt(h->frame_control)) {
4683                         if ((is_zero_ether_addr(h->addr2) ||
4684                              is_multicast_ether_addr(h->addr2))) {
4685                                 wiphy_err(wlc->wiphy, "wl%d: %s: dropping a "
4686                                           "frame with invalid src mac address,"
4687                                           " a2: %pM\n",
4688                                          wlc->pub->unit, __func__, h->addr2);
4689                                 goto toss;
4690                         }
4691                 }
4692         }
4693
4694         /* due to sheer numbers, toss out probe reqs for now */
4695         if (ieee80211_is_probe_req(h->frame_control))
4696                 goto toss;
4697
4698         if (is_amsdu)
4699                 goto toss;
4700
4701         wlc_recvctl(wlc, rxh, p);
4702         return;
4703
4704  toss:
4705         bcm_pkt_buf_free_skb(p);
4706 }
4707
4708 /* calculate frame duration for Mixed-mode L-SIG spoofing, return
4709  * number of bytes goes in the length field
4710  *
4711  * Formula given by HT PHY Spec v 1.13
4712  *   len = 3(nsyms + nstream + 3) - 3
4713  */
4714 u16
4715 wlc_calc_lsig_len(struct wlc_info *wlc, ratespec_t ratespec, uint mac_len)
4716 {
4717         uint nsyms, len = 0, kNdps;
4718
4719         BCMMSG(wlc->wiphy, "wl%d: rate %d, len%d\n",
4720                  wlc->pub->unit, RSPEC2RATE(ratespec), mac_len);
4721
4722         if (IS_MCS(ratespec)) {
4723                 uint mcs = ratespec & RSPEC_RATE_MASK;
4724                 /* MCS_TXS(mcs) returns num tx streams - 1 */
4725                 int tot_streams = (MCS_TXS(mcs) + 1) + RSPEC_STC(ratespec);
4726
4727                 /* the payload duration calculation matches that of regular ofdm */
4728                 /* 1000Ndbps = kbps * 4 */
4729                 kNdps =
4730                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4731                              RSPEC_ISSGI(ratespec)) * 4;
4732
4733                 if (RSPEC_STC(ratespec) == 0)
4734                         /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4735                         nsyms =
4736                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4737                                   APHY_TAIL_NBITS) * 1000, kNdps);
4738                 else
4739                         /* STBC needs to have even number of symbols */
4740                         nsyms =
4741                             2 *
4742                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4743                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
4744
4745                 nsyms += (tot_streams + 3);     /* (+3) account for HT-SIG(2) and HT-STF(1) */
4746                 /* 3 bytes/symbol @ legacy 6Mbps rate */
4747                 len = (3 * nsyms) - 3;  /* (-3) excluding service bits and tail bits */
4748         }
4749
4750         return (u16) len;
4751 }
4752
4753 /* calculate frame duration of a given rate and length, return time in usec unit */
4754 uint
4755 wlc_calc_frame_time(struct wlc_info *wlc, ratespec_t ratespec, u8 preamble_type,
4756                     uint mac_len)
4757 {
4758         uint nsyms, dur = 0, Ndps, kNdps;
4759         uint rate = RSPEC2RATE(ratespec);
4760
4761         if (rate == 0) {
4762                 wiphy_err(wlc->wiphy, "wl%d: WAR: using rate of 1 mbps\n",
4763                           wlc->pub->unit);
4764                 rate = WLC_RATE_1M;
4765         }
4766
4767         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d, len%d\n",
4768                  wlc->pub->unit, ratespec, preamble_type, mac_len);
4769
4770         if (IS_MCS(ratespec)) {
4771                 uint mcs = ratespec & RSPEC_RATE_MASK;
4772                 int tot_streams = MCS_TXS(mcs) + RSPEC_STC(ratespec);
4773
4774                 dur = PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
4775                 if (preamble_type == WLC_MM_PREAMBLE)
4776                         dur += PREN_MM_EXT;
4777                 /* 1000Ndbps = kbps * 4 */
4778                 kNdps =
4779                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4780                              RSPEC_ISSGI(ratespec)) * 4;
4781
4782                 if (RSPEC_STC(ratespec) == 0)
4783                         /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4784                         nsyms =
4785                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4786                                   APHY_TAIL_NBITS) * 1000, kNdps);
4787                 else
4788                         /* STBC needs to have even number of symbols */
4789                         nsyms =
4790                             2 *
4791                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4792                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
4793
4794                 dur += APHY_SYMBOL_TIME * nsyms;
4795                 if (BAND_2G(wlc->band->bandtype))
4796                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
4797         } else if (IS_OFDM(rate)) {
4798                 dur = APHY_PREAMBLE_TIME;
4799                 dur += APHY_SIGNAL_TIME;
4800                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
4801                 Ndps = rate * 2;
4802                 /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4803                 nsyms =
4804                     CEIL((APHY_SERVICE_NBITS + 8 * mac_len + APHY_TAIL_NBITS),
4805                          Ndps);
4806                 dur += APHY_SYMBOL_TIME * nsyms;
4807                 if (BAND_2G(wlc->band->bandtype))
4808                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
4809         } else {
4810                 /* calc # bits * 2 so factor of 2 in rate (1/2 mbps) will divide out */
4811                 mac_len = mac_len * 8 * 2;
4812                 /* calc ceiling of bits/rate = microseconds of air time */
4813                 dur = (mac_len + rate - 1) / rate;
4814                 if (preamble_type & WLC_SHORT_PREAMBLE)
4815                         dur += BPHY_PLCP_SHORT_TIME;
4816                 else
4817                         dur += BPHY_PLCP_TIME;
4818         }
4819         return dur;
4820 }
4821
4822 /* The opposite of wlc_calc_frame_time */
4823 static uint
4824 wlc_calc_frame_len(struct wlc_info *wlc, ratespec_t ratespec, u8 preamble_type,
4825                    uint dur)
4826 {
4827         uint nsyms, mac_len, Ndps, kNdps;
4828         uint rate = RSPEC2RATE(ratespec);
4829
4830         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d, dur %d\n",
4831                  wlc->pub->unit, ratespec, preamble_type, dur);
4832
4833         if (IS_MCS(ratespec)) {
4834                 uint mcs = ratespec & RSPEC_RATE_MASK;
4835                 int tot_streams = MCS_TXS(mcs) + RSPEC_STC(ratespec);
4836                 dur -= PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
4837                 /* payload calculation matches that of regular ofdm */
4838                 if (BAND_2G(wlc->band->bandtype))
4839                         dur -= DOT11_OFDM_SIGNAL_EXTENSION;
4840                 /* kNdbps = kbps * 4 */
4841                 kNdps =
4842                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4843                              RSPEC_ISSGI(ratespec)) * 4;
4844                 nsyms = dur / APHY_SYMBOL_TIME;
4845                 mac_len =
4846                     ((nsyms * kNdps) -
4847                      ((APHY_SERVICE_NBITS + APHY_TAIL_NBITS) * 1000)) / 8000;
4848         } else if (IS_OFDM(ratespec)) {
4849                 dur -= APHY_PREAMBLE_TIME;
4850                 dur -= APHY_SIGNAL_TIME;
4851                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
4852                 Ndps = rate * 2;
4853                 nsyms = dur / APHY_SYMBOL_TIME;
4854                 mac_len =
4855                     ((nsyms * Ndps) -
4856                      (APHY_SERVICE_NBITS + APHY_TAIL_NBITS)) / 8;
4857         } else {
4858                 if (preamble_type & WLC_SHORT_PREAMBLE)
4859                         dur -= BPHY_PLCP_SHORT_TIME;
4860                 else
4861                         dur -= BPHY_PLCP_TIME;
4862                 mac_len = dur * rate;
4863                 /* divide out factor of 2 in rate (1/2 mbps) */
4864                 mac_len = mac_len / 8 / 2;
4865         }
4866         return mac_len;
4867 }
4868
4869 static uint
4870 wlc_calc_ba_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4871 {
4872         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, "
4873                  "preamble_type %d\n", wlc->pub->unit, rspec, preamble_type);
4874         /* Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that is less than
4875          * or equal to the rate of the immediately previous frame in the FES
4876          */
4877         rspec = WLC_BASIC_RATE(wlc, rspec);
4878         /* BA len == 32 == 16(ctl hdr) + 4(ba len) + 8(bitmap) + 4(fcs) */
4879         return wlc_calc_frame_time(wlc, rspec, preamble_type,
4880                                    (DOT11_BA_LEN + DOT11_BA_BITMAP_LEN +
4881                                     FCS_LEN));
4882 }
4883
4884 static uint
4885 wlc_calc_ack_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4886 {
4887         uint dur = 0;
4888
4889         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d\n",
4890                 wlc->pub->unit, rspec, preamble_type);
4891         /* Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that is less than
4892          * or equal to the rate of the immediately previous frame in the FES
4893          */
4894         rspec = WLC_BASIC_RATE(wlc, rspec);
4895         /* ACK frame len == 14 == 2(fc) + 2(dur) + 6(ra) + 4(fcs) */
4896         dur =
4897             wlc_calc_frame_time(wlc, rspec, preamble_type,
4898                                 (DOT11_ACK_LEN + FCS_LEN));
4899         return dur;
4900 }
4901
4902 static uint
4903 wlc_calc_cts_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4904 {
4905         BCMMSG(wlc->wiphy, "wl%d: ratespec 0x%x, preamble_type %d\n",
4906                 wlc->pub->unit, rspec, preamble_type);
4907         return wlc_calc_ack_time(wlc, rspec, preamble_type);
4908 }
4909
4910 /* derive wlc->band->basic_rate[] table from 'rateset' */
4911 void wlc_rate_lookup_init(struct wlc_info *wlc, wlc_rateset_t *rateset)
4912 {
4913         u8 rate;
4914         u8 mandatory;
4915         u8 cck_basic = 0;
4916         u8 ofdm_basic = 0;
4917         u8 *br = wlc->band->basic_rate;
4918         uint i;
4919
4920         /* incoming rates are in 500kbps units as in 802.11 Supported Rates */
4921         memset(br, 0, WLC_MAXRATE + 1);
4922
4923         /* For each basic rate in the rates list, make an entry in the
4924          * best basic lookup.
4925          */
4926         for (i = 0; i < rateset->count; i++) {
4927                 /* only make an entry for a basic rate */
4928                 if (!(rateset->rates[i] & WLC_RATE_FLAG))
4929                         continue;
4930
4931                 /* mask off basic bit */
4932                 rate = (rateset->rates[i] & WLC_RATE_MASK);
4933
4934                 if (rate > WLC_MAXRATE) {
4935                         wiphy_err(wlc->wiphy, "wlc_rate_lookup_init: invalid "
4936                                   "rate 0x%X in rate set\n",
4937                                   rateset->rates[i]);
4938                         continue;
4939                 }
4940
4941                 br[rate] = rate;
4942         }
4943
4944         /* The rate lookup table now has non-zero entries for each
4945          * basic rate, equal to the basic rate: br[basicN] = basicN
4946          *
4947          * To look up the best basic rate corresponding to any
4948          * particular rate, code can use the basic_rate table
4949          * like this
4950          *
4951          * basic_rate = wlc->band->basic_rate[tx_rate]
4952          *
4953          * Make sure there is a best basic rate entry for
4954          * every rate by walking up the table from low rates
4955          * to high, filling in holes in the lookup table
4956          */
4957
4958         for (i = 0; i < wlc->band->hw_rateset.count; i++) {
4959                 rate = wlc->band->hw_rateset.rates[i];
4960
4961                 if (br[rate] != 0) {
4962                         /* This rate is a basic rate.
4963                          * Keep track of the best basic rate so far by
4964                          * modulation type.
4965                          */
4966                         if (IS_OFDM(rate))
4967                                 ofdm_basic = rate;
4968                         else
4969                                 cck_basic = rate;
4970
4971                         continue;
4972                 }
4973
4974                 /* This rate is not a basic rate so figure out the
4975                  * best basic rate less than this rate and fill in
4976                  * the hole in the table
4977                  */
4978
4979                 br[rate] = IS_OFDM(rate) ? ofdm_basic : cck_basic;
4980
4981                 if (br[rate] != 0)
4982                         continue;
4983
4984                 if (IS_OFDM(rate)) {
4985                         /* In 11g and 11a, the OFDM mandatory rates are 6, 12, and 24 Mbps */
4986                         if (rate >= WLC_RATE_24M)
4987                                 mandatory = WLC_RATE_24M;
4988                         else if (rate >= WLC_RATE_12M)
4989                                 mandatory = WLC_RATE_12M;
4990                         else
4991                                 mandatory = WLC_RATE_6M;
4992                 } else {
4993                         /* In 11b, all the CCK rates are mandatory 1 - 11 Mbps */
4994                         mandatory = rate;
4995                 }
4996
4997                 br[rate] = mandatory;
4998         }
4999 }
5000
5001 static void wlc_write_rate_shm(struct wlc_info *wlc, u8 rate, u8 basic_rate)
5002 {
5003         u8 phy_rate, index;
5004         u8 basic_phy_rate, basic_index;
5005         u16 dir_table, basic_table;
5006         u16 basic_ptr;
5007
5008         /* Shared memory address for the table we are reading */
5009         dir_table = IS_OFDM(basic_rate) ? M_RT_DIRMAP_A : M_RT_DIRMAP_B;
5010
5011         /* Shared memory address for the table we are writing */
5012         basic_table = IS_OFDM(rate) ? M_RT_BBRSMAP_A : M_RT_BBRSMAP_B;
5013
5014         /*
5015          * for a given rate, the LS-nibble of the PLCP SIGNAL field is
5016          * the index into the rate table.
5017          */
5018         phy_rate = rate_info[rate] & WLC_RATE_MASK;
5019         basic_phy_rate = rate_info[basic_rate] & WLC_RATE_MASK;
5020         index = phy_rate & 0xf;
5021         basic_index = basic_phy_rate & 0xf;
5022
5023         /* Find the SHM pointer to the ACK rate entry by looking in the
5024          * Direct-map Table
5025          */
5026         basic_ptr = wlc_read_shm(wlc, (dir_table + basic_index * 2));
5027
5028         /* Update the SHM BSS-basic-rate-set mapping table with the pointer
5029          * to the correct basic rate for the given incoming rate
5030          */
5031         wlc_write_shm(wlc, (basic_table + index * 2), basic_ptr);
5032 }
5033
5034 static const wlc_rateset_t *wlc_rateset_get_hwrs(struct wlc_info *wlc)
5035 {
5036         const wlc_rateset_t *rs_dflt;
5037
5038         if (WLC_PHY_11N_CAP(wlc->band)) {
5039                 if (BAND_5G(wlc->band->bandtype))
5040                         rs_dflt = &ofdm_mimo_rates;
5041                 else
5042                         rs_dflt = &cck_ofdm_mimo_rates;
5043         } else if (wlc->band->gmode)
5044                 rs_dflt = &cck_ofdm_rates;
5045         else
5046                 rs_dflt = &cck_rates;
5047
5048         return rs_dflt;
5049 }
5050
5051 void wlc_set_ratetable(struct wlc_info *wlc)
5052 {
5053         const wlc_rateset_t *rs_dflt;
5054         wlc_rateset_t rs;
5055         u8 rate, basic_rate;
5056         uint i;
5057
5058         rs_dflt = wlc_rateset_get_hwrs(wlc);
5059
5060         wlc_rateset_copy(rs_dflt, &rs);
5061         wlc_rateset_mcs_upd(&rs, wlc->stf->txstreams);
5062
5063         /* walk the phy rate table and update SHM basic rate lookup table */
5064         for (i = 0; i < rs.count; i++) {
5065                 rate = rs.rates[i] & WLC_RATE_MASK;
5066
5067                 /* for a given rate WLC_BASIC_RATE returns the rate at
5068                  * which a response ACK/CTS should be sent.
5069                  */
5070                 basic_rate = WLC_BASIC_RATE(wlc, rate);
5071                 if (basic_rate == 0) {
5072                         /* This should only happen if we are using a
5073                          * restricted rateset.
5074                          */
5075                         basic_rate = rs.rates[0] & WLC_RATE_MASK;
5076                 }
5077
5078                 wlc_write_rate_shm(wlc, rate, basic_rate);
5079         }
5080 }
5081
5082 /*
5083  * Return true if the specified rate is supported by the specified band.
5084  * WLC_BAND_AUTO indicates the current band.
5085  */
5086 bool wlc_valid_rate(struct wlc_info *wlc, ratespec_t rspec, int band,
5087                     bool verbose)
5088 {
5089         wlc_rateset_t *hw_rateset;
5090         uint i;
5091
5092         if ((band == WLC_BAND_AUTO) || (band == wlc->band->bandtype)) {
5093                 hw_rateset = &wlc->band->hw_rateset;
5094         } else if (NBANDS(wlc) > 1) {
5095                 hw_rateset = &wlc->bandstate[OTHERBANDUNIT(wlc)]->hw_rateset;
5096         } else {
5097                 /* other band specified and we are a single band device */
5098                 return false;
5099         }
5100
5101         /* check if this is a mimo rate */
5102         if (IS_MCS(rspec)) {
5103                 if (!VALID_MCS((rspec & RSPEC_RATE_MASK)))
5104                         goto error;
5105
5106                 return isset(hw_rateset->mcs, (rspec & RSPEC_RATE_MASK));
5107         }
5108
5109         for (i = 0; i < hw_rateset->count; i++)
5110                 if (hw_rateset->rates[i] == RSPEC2RATE(rspec))
5111                         return true;
5112  error:
5113         if (verbose) {
5114                 wiphy_err(wlc->wiphy, "wl%d: wlc_valid_rate: rate spec 0x%x "
5115                           "not in hw_rateset\n", wlc->pub->unit, rspec);
5116         }
5117
5118         return false;
5119 }
5120
5121 static void wlc_update_mimo_band_bwcap(struct wlc_info *wlc, u8 bwcap)
5122 {
5123         uint i;
5124         struct wlcband *band;
5125
5126         for (i = 0; i < NBANDS(wlc); i++) {
5127                 if (IS_SINGLEBAND_5G(wlc->deviceid))
5128                         i = BAND_5G_INDEX;
5129                 band = wlc->bandstate[i];
5130                 if (band->bandtype == WLC_BAND_5G) {
5131                         if ((bwcap == WLC_N_BW_40ALL)
5132                             || (bwcap == WLC_N_BW_20IN2G_40IN5G))
5133                                 band->mimo_cap_40 = true;
5134                         else
5135                                 band->mimo_cap_40 = false;
5136                 } else {
5137                         if (bwcap == WLC_N_BW_40ALL)
5138                                 band->mimo_cap_40 = true;
5139                         else
5140                                 band->mimo_cap_40 = false;
5141                 }
5142         }
5143 }
5144
5145 void wlc_mod_prb_rsp_rate_table(struct wlc_info *wlc, uint frame_len)
5146 {
5147         const wlc_rateset_t *rs_dflt;
5148         wlc_rateset_t rs;
5149         u8 rate;
5150         u16 entry_ptr;
5151         u8 plcp[D11_PHY_HDR_LEN];
5152         u16 dur, sifs;
5153         uint i;
5154
5155         sifs = SIFS(wlc->band);
5156
5157         rs_dflt = wlc_rateset_get_hwrs(wlc);
5158
5159         wlc_rateset_copy(rs_dflt, &rs);
5160         wlc_rateset_mcs_upd(&rs, wlc->stf->txstreams);
5161
5162         /* walk the phy rate table and update MAC core SHM basic rate table entries */
5163         for (i = 0; i < rs.count; i++) {
5164                 rate = rs.rates[i] & WLC_RATE_MASK;
5165
5166                 entry_ptr = wlc_rate_shm_offset(wlc, rate);
5167
5168                 /* Calculate the Probe Response PLCP for the given rate */
5169                 wlc_compute_plcp(wlc, rate, frame_len, plcp);
5170
5171                 /* Calculate the duration of the Probe Response frame plus SIFS for the MAC */
5172                 dur =
5173                     (u16) wlc_calc_frame_time(wlc, rate, WLC_LONG_PREAMBLE,
5174                                                  frame_len);
5175                 dur += sifs;
5176
5177                 /* Update the SHM Rate Table entry Probe Response values */
5178                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS,
5179                               (u16) (plcp[0] + (plcp[1] << 8)));
5180                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS + 2,
5181                               (u16) (plcp[2] + (plcp[3] << 8)));
5182                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_DUR_POS, dur);
5183         }
5184 }
5185
5186 /*      Max buffering needed for beacon template/prb resp template is 142 bytes.
5187  *
5188  *      PLCP header is 6 bytes.
5189  *      802.11 A3 header is 24 bytes.
5190  *      Max beacon frame body template length is 112 bytes.
5191  *      Max probe resp frame body template length is 110 bytes.
5192  *
5193  *      *len on input contains the max length of the packet available.
5194  *
5195  *      The *len value is set to the number of bytes in buf used, and starts with the PLCP
5196  *      and included up to, but not including, the 4 byte FCS.
5197  */
5198 static void
5199 wlc_bcn_prb_template(struct wlc_info *wlc, u16 type, ratespec_t bcn_rspec,
5200                      struct wlc_bsscfg *cfg, u16 *buf, int *len)
5201 {
5202         static const u8 ether_bcast[ETH_ALEN] = {255, 255, 255, 255, 255, 255};
5203         cck_phy_hdr_t *plcp;
5204         struct ieee80211_mgmt *h;
5205         int hdr_len, body_len;
5206
5207         if (MBSS_BCN_ENAB(cfg) && type == IEEE80211_STYPE_BEACON)
5208                 hdr_len = DOT11_MAC_HDR_LEN;
5209         else
5210                 hdr_len = D11_PHY_HDR_LEN + DOT11_MAC_HDR_LEN;
5211         body_len = *len - hdr_len;      /* calc buffer size provided for frame body */
5212
5213         *len = hdr_len + body_len;      /* return actual size */
5214
5215         /* format PHY and MAC headers */
5216         memset((char *)buf, 0, hdr_len);
5217
5218         plcp = (cck_phy_hdr_t *) buf;
5219
5220         /* PLCP for Probe Response frames are filled in from core's rate table */
5221         if (type == IEEE80211_STYPE_BEACON && !MBSS_BCN_ENAB(cfg)) {
5222                 /* fill in PLCP */
5223                 wlc_compute_plcp(wlc, bcn_rspec,
5224                                  (DOT11_MAC_HDR_LEN + body_len + FCS_LEN),
5225                                  (u8 *) plcp);
5226
5227         }
5228         /* "Regular" and 16 MBSS but not for 4 MBSS */
5229         /* Update the phytxctl for the beacon based on the rspec */
5230         if (!SOFTBCN_ENAB(cfg))
5231                 wlc_beacon_phytxctl_txant_upd(wlc, bcn_rspec);
5232
5233         if (MBSS_BCN_ENAB(cfg) && type == IEEE80211_STYPE_BEACON)
5234                 h = (struct ieee80211_mgmt *)&plcp[0];
5235         else
5236                 h = (struct ieee80211_mgmt *)&plcp[1];
5237
5238         /* fill in 802.11 header */
5239         h->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | type);
5240
5241         /* DUR is 0 for multicast bcn, or filled in by MAC for prb resp */
5242         /* A1 filled in by MAC for prb resp, broadcast for bcn */
5243         if (type == IEEE80211_STYPE_BEACON)
5244                 memcpy(&h->da, &ether_bcast, ETH_ALEN);
5245         memcpy(&h->sa, &cfg->cur_etheraddr, ETH_ALEN);
5246         memcpy(&h->bssid, &cfg->BSSID, ETH_ALEN);
5247
5248         /* SEQ filled in by MAC */
5249
5250         return;
5251 }
5252
5253 int wlc_get_header_len()
5254 {
5255         return TXOFF;
5256 }
5257
5258 /* Update a beacon for a particular BSS
5259  * For MBSS, this updates the software template and sets "latest" to the index of the
5260  * template updated.
5261  * Otherwise, it updates the hardware template.
5262  */
5263 void wlc_bss_update_beacon(struct wlc_info *wlc, struct wlc_bsscfg *cfg)
5264 {
5265         int len = BCN_TMPL_LEN;
5266
5267         /* Clear the soft intmask */
5268         wlc->defmacintmask &= ~MI_BCNTPL;
5269
5270         if (!cfg->up) {         /* Only allow updates on an UP bss */
5271                 return;
5272         }
5273
5274         /* Optimize:  Some of if/else could be combined */
5275         if (!MBSS_BCN_ENAB(cfg) && HWBCN_ENAB(cfg)) {
5276                 /* Hardware beaconing for this config */
5277                 u16 bcn[BCN_TMPL_LEN / 2];
5278                 u32 both_valid = MCMD_BCN0VLD | MCMD_BCN1VLD;
5279                 d11regs_t *regs = wlc->regs;
5280
5281                 /* Check if both templates are in use, if so sched. an interrupt
5282                  *      that will call back into this routine
5283                  */
5284                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
5285                         /* clear any previous status */
5286                         W_REG(&regs->macintstatus, MI_BCNTPL);
5287                 }
5288                 /* Check that after scheduling the interrupt both of the
5289                  *      templates are still busy. if not clear the int. & remask
5290                  */
5291                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
5292                         wlc->defmacintmask |= MI_BCNTPL;
5293                         return;
5294                 }
5295
5296                 wlc->bcn_rspec =
5297                     wlc_lowest_basic_rspec(wlc, &cfg->current_bss->rateset);
5298                 /* update the template and ucode shm */
5299                 wlc_bcn_prb_template(wlc, IEEE80211_STYPE_BEACON,
5300                                      wlc->bcn_rspec, cfg, bcn, &len);
5301                 wlc_write_hw_bcntemplates(wlc, bcn, len, false);
5302         }
5303 }
5304
5305 /*
5306  * Update all beacons for the system.
5307  */
5308 void wlc_update_beacon(struct wlc_info *wlc)
5309 {
5310         int idx;
5311         struct wlc_bsscfg *bsscfg;
5312
5313         /* update AP or IBSS beacons */
5314         FOREACH_BSS(wlc, idx, bsscfg) {
5315                 if (bsscfg->up && (BSSCFG_AP(bsscfg) || !bsscfg->BSS))
5316                         wlc_bss_update_beacon(wlc, bsscfg);
5317         }
5318 }
5319
5320 /* Write ssid into shared memory */
5321 void wlc_shm_ssid_upd(struct wlc_info *wlc, struct wlc_bsscfg *cfg)
5322 {
5323         u8 *ssidptr = cfg->SSID;
5324         u16 base = M_SSID;
5325         u8 ssidbuf[IEEE80211_MAX_SSID_LEN];
5326
5327         /* padding the ssid with zero and copy it into shm */
5328         memset(ssidbuf, 0, IEEE80211_MAX_SSID_LEN);
5329         memcpy(ssidbuf, ssidptr, cfg->SSID_len);
5330
5331         wlc_copyto_shm(wlc, base, ssidbuf, IEEE80211_MAX_SSID_LEN);
5332
5333         if (!MBSS_BCN_ENAB(cfg))
5334                 wlc_write_shm(wlc, M_SSIDLEN, (u16) cfg->SSID_len);
5335 }
5336
5337 void wlc_update_probe_resp(struct wlc_info *wlc, bool suspend)
5338 {
5339         int idx;
5340         struct wlc_bsscfg *bsscfg;
5341
5342         /* update AP or IBSS probe responses */
5343         FOREACH_BSS(wlc, idx, bsscfg) {
5344                 if (bsscfg->up && (BSSCFG_AP(bsscfg) || !bsscfg->BSS))
5345                         wlc_bss_update_probe_resp(wlc, bsscfg, suspend);
5346         }
5347 }
5348
5349 void
5350 wlc_bss_update_probe_resp(struct wlc_info *wlc, struct wlc_bsscfg *cfg,
5351                           bool suspend)
5352 {
5353         u16 prb_resp[BCN_TMPL_LEN / 2];
5354         int len = BCN_TMPL_LEN;
5355
5356         /* write the probe response to hardware, or save in the config structure */
5357         if (!MBSS_PRB_ENAB(cfg)) {
5358
5359                 /* create the probe response template */
5360                 wlc_bcn_prb_template(wlc, IEEE80211_STYPE_PROBE_RESP, 0, cfg,
5361                                      prb_resp, &len);
5362
5363                 if (suspend)
5364                         wlc_suspend_mac_and_wait(wlc);
5365
5366                 /* write the probe response into the template region */
5367                 wlc_bmac_write_template_ram(wlc->hw, T_PRS_TPL_BASE,
5368                                             (len + 3) & ~3, prb_resp);
5369
5370                 /* write the length of the probe response frame (+PLCP/-FCS) */
5371                 wlc_write_shm(wlc, M_PRB_RESP_FRM_LEN, (u16) len);
5372
5373                 /* write the SSID and SSID length */
5374                 wlc_shm_ssid_upd(wlc, cfg);
5375
5376                 /*
5377                  * Write PLCP headers and durations for probe response frames at all rates.
5378                  * Use the actual frame length covered by the PLCP header for the call to
5379                  * wlc_mod_prb_rsp_rate_table() by subtracting the PLCP len and adding the FCS.
5380                  */
5381                 len += (-D11_PHY_HDR_LEN + FCS_LEN);
5382                 wlc_mod_prb_rsp_rate_table(wlc, (u16) len);
5383
5384                 if (suspend)
5385                         wlc_enable_mac(wlc);
5386         } else {                /* Generating probe resp in sw; update local template */
5387                 /* error: No software probe response support without MBSS */
5388         }
5389 }
5390
5391 /* prepares pdu for transmission. returns BCM error codes */
5392 int wlc_prep_pdu(struct wlc_info *wlc, struct sk_buff *pdu, uint *fifop)
5393 {
5394         uint fifo;
5395         d11txh_t *txh;
5396         struct ieee80211_hdr *h;
5397         struct scb *scb;
5398
5399         txh = (d11txh_t *) (pdu->data);
5400         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
5401
5402         /* get the pkt queue info. This was put at wlc_sendctl or wlc_send for PDU */
5403         fifo = le16_to_cpu(txh->TxFrameID) & TXFID_QUEUE_MASK;
5404
5405         scb = NULL;
5406
5407         *fifop = fifo;
5408
5409         /* return if insufficient dma resources */
5410         if (TXAVAIL(wlc, fifo) < MAX_DMA_SEGS) {
5411                 /* Mark precedences related to this FIFO, unsendable */
5412                 WLC_TX_FIFO_CLEAR(wlc, fifo);
5413                 return -EBUSY;
5414         }
5415         return 0;
5416 }
5417
5418 /* init tx reported rate mechanism */
5419 void wlc_reprate_init(struct wlc_info *wlc)
5420 {
5421         int i;
5422         struct wlc_bsscfg *bsscfg;
5423
5424         FOREACH_BSS(wlc, i, bsscfg) {
5425                 wlc_bsscfg_reprate_init(bsscfg);
5426         }
5427 }
5428
5429 /* per bsscfg init tx reported rate mechanism */
5430 void wlc_bsscfg_reprate_init(struct wlc_bsscfg *bsscfg)
5431 {
5432         bsscfg->txrspecidx = 0;
5433         memset((char *)bsscfg->txrspec, 0, sizeof(bsscfg->txrspec));
5434 }
5435
5436 void wlc_default_rateset(struct wlc_info *wlc, wlc_rateset_t *rs)
5437 {
5438         wlc_rateset_default(rs, NULL, wlc->band->phytype, wlc->band->bandtype,
5439                             false, WLC_RATE_MASK_FULL, (bool) N_ENAB(wlc->pub),
5440                             CHSPEC_WLC_BW(wlc->default_bss->chanspec),
5441                             wlc->stf->txstreams);
5442 }
5443
5444 static void wlc_bss_default_init(struct wlc_info *wlc)
5445 {
5446         chanspec_t chanspec;
5447         struct wlcband *band;
5448         wlc_bss_info_t *bi = wlc->default_bss;
5449
5450         /* init default and target BSS with some sane initial values */
5451         memset((char *)(bi), 0, sizeof(wlc_bss_info_t));
5452         bi->beacon_period = ISSIM_ENAB(wlc->pub->sih) ? BEACON_INTERVAL_DEF_QT :
5453             BEACON_INTERVAL_DEFAULT;
5454         bi->dtim_period = ISSIM_ENAB(wlc->pub->sih) ? DTIM_INTERVAL_DEF_QT :
5455             DTIM_INTERVAL_DEFAULT;
5456
5457         /* fill the default channel as the first valid channel
5458          * starting from the 2G channels
5459          */
5460         chanspec = CH20MHZ_CHSPEC(1);
5461         wlc->home_chanspec = bi->chanspec = chanspec;
5462
5463         /* find the band of our default channel */
5464         band = wlc->band;
5465         if (NBANDS(wlc) > 1 && band->bandunit != CHSPEC_WLCBANDUNIT(chanspec))
5466                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
5467
5468         /* init bss rates to the band specific default rate set */
5469         wlc_rateset_default(&bi->rateset, NULL, band->phytype, band->bandtype,
5470                             false, WLC_RATE_MASK_FULL, (bool) N_ENAB(wlc->pub),
5471                             CHSPEC_WLC_BW(chanspec), wlc->stf->txstreams);
5472
5473         if (N_ENAB(wlc->pub))
5474                 bi->flags |= WLC_BSS_HT;
5475 }
5476
5477 static ratespec_t
5478 mac80211_wlc_set_nrate(struct wlc_info *wlc, struct wlcband *cur_band,
5479                        u32 int_val)
5480 {
5481         u8 stf = (int_val & NRATE_STF_MASK) >> NRATE_STF_SHIFT;
5482         u8 rate = int_val & NRATE_RATE_MASK;
5483         ratespec_t rspec;
5484         bool ismcs = ((int_val & NRATE_MCS_INUSE) == NRATE_MCS_INUSE);
5485         bool issgi = ((int_val & NRATE_SGI_MASK) >> NRATE_SGI_SHIFT);
5486         bool override_mcs_only = ((int_val & NRATE_OVERRIDE_MCS_ONLY)
5487                                   == NRATE_OVERRIDE_MCS_ONLY);
5488         int bcmerror = 0;
5489
5490         if (!ismcs) {
5491                 return (ratespec_t) rate;
5492         }
5493
5494         /* validate the combination of rate/mcs/stf is allowed */
5495         if (N_ENAB(wlc->pub) && ismcs) {
5496                 /* mcs only allowed when nmode */
5497                 if (stf > PHY_TXC1_MODE_SDM) {
5498                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid stf\n",
5499                                  WLCWLUNIT(wlc), __func__);
5500                         bcmerror = -EINVAL;
5501                         goto done;
5502                 }
5503
5504                 /* mcs 32 is a special case, DUP mode 40 only */
5505                 if (rate == 32) {
5506                         if (!CHSPEC_IS40(wlc->home_chanspec) ||
5507                             ((stf != PHY_TXC1_MODE_SISO)
5508                              && (stf != PHY_TXC1_MODE_CDD))) {
5509                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid mcs "
5510                                           "32\n", WLCWLUNIT(wlc), __func__);
5511                                 bcmerror = -EINVAL;
5512                                 goto done;
5513                         }
5514                         /* mcs > 7 must use stf SDM */
5515                 } else if (rate > HIGHEST_SINGLE_STREAM_MCS) {
5516                         /* mcs > 7 must use stf SDM */
5517                         if (stf != PHY_TXC1_MODE_SDM) {
5518                                 BCMMSG(wlc->wiphy, "wl%d: enabling "
5519                                          "SDM mode for mcs %d\n",
5520                                          WLCWLUNIT(wlc), rate);
5521                                 stf = PHY_TXC1_MODE_SDM;
5522                         }
5523                 } else {
5524                         /* MCS 0-7 may use SISO, CDD, and for phy_rev >= 3 STBC */
5525                         if ((stf > PHY_TXC1_MODE_STBC) ||
5526                             (!WLC_STBC_CAP_PHY(wlc)
5527                              && (stf == PHY_TXC1_MODE_STBC))) {
5528                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid STBC"
5529                                           "\n", WLCWLUNIT(wlc), __func__);
5530                                 bcmerror = -EINVAL;
5531                                 goto done;
5532                         }
5533                 }
5534         } else if (IS_OFDM(rate)) {
5535                 if ((stf != PHY_TXC1_MODE_CDD) && (stf != PHY_TXC1_MODE_SISO)) {
5536                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid OFDM\n",
5537                                   WLCWLUNIT(wlc), __func__);
5538                         bcmerror = -EINVAL;
5539                         goto done;
5540                 }
5541         } else if (IS_CCK(rate)) {
5542                 if ((cur_band->bandtype != WLC_BAND_2G)
5543                     || (stf != PHY_TXC1_MODE_SISO)) {
5544                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid CCK\n",
5545                                   WLCWLUNIT(wlc), __func__);
5546                         bcmerror = -EINVAL;
5547                         goto done;
5548                 }
5549         } else {
5550                 wiphy_err(wlc->wiphy, "wl%d: %s: Unknown rate type\n",
5551                           WLCWLUNIT(wlc), __func__);
5552                 bcmerror = -EINVAL;
5553                 goto done;
5554         }
5555         /* make sure multiple antennae are available for non-siso rates */
5556         if ((stf != PHY_TXC1_MODE_SISO) && (wlc->stf->txstreams == 1)) {
5557                 wiphy_err(wlc->wiphy, "wl%d: %s: SISO antenna but !SISO "
5558                           "request\n", WLCWLUNIT(wlc), __func__);
5559                 bcmerror = -EINVAL;
5560                 goto done;
5561         }
5562
5563         rspec = rate;
5564         if (ismcs) {
5565                 rspec |= RSPEC_MIMORATE;
5566                 /* For STBC populate the STC field of the ratespec */
5567                 if (stf == PHY_TXC1_MODE_STBC) {
5568                         u8 stc;
5569                         stc = 1;        /* Nss for single stream is always 1 */
5570                         rspec |= (stc << RSPEC_STC_SHIFT);
5571                 }
5572         }
5573
5574         rspec |= (stf << RSPEC_STF_SHIFT);
5575
5576         if (override_mcs_only)
5577                 rspec |= RSPEC_OVERRIDE_MCS_ONLY;
5578
5579         if (issgi)
5580                 rspec |= RSPEC_SHORT_GI;
5581
5582         if ((rate != 0)
5583             && !wlc_valid_rate(wlc, rspec, cur_band->bandtype, true)) {
5584                 return rate;
5585         }
5586
5587         return rspec;
5588 done:
5589         return rate;
5590 }
5591
5592 /* formula:  IDLE_BUSY_RATIO_X_16 = (100-duty_cycle)/duty_cycle*16 */
5593 static int
5594 wlc_duty_cycle_set(struct wlc_info *wlc, int duty_cycle, bool isOFDM,
5595                    bool writeToShm)
5596 {
5597         int idle_busy_ratio_x_16 = 0;
5598         uint offset =
5599             isOFDM ? M_TX_IDLE_BUSY_RATIO_X_16_OFDM :
5600             M_TX_IDLE_BUSY_RATIO_X_16_CCK;
5601         if (duty_cycle > 100 || duty_cycle < 0) {
5602                 wiphy_err(wlc->wiphy, "wl%d:  duty cycle value off limit\n",
5603                           wlc->pub->unit);
5604                 return -EINVAL;
5605         }
5606         if (duty_cycle)
5607                 idle_busy_ratio_x_16 = (100 - duty_cycle) * 16 / duty_cycle;
5608         /* Only write to shared memory  when wl is up */
5609         if (writeToShm)
5610                 wlc_write_shm(wlc, offset, (u16) idle_busy_ratio_x_16);
5611
5612         if (isOFDM)
5613                 wlc->tx_duty_cycle_ofdm = (u16) duty_cycle;
5614         else
5615                 wlc->tx_duty_cycle_cck = (u16) duty_cycle;
5616
5617         return 0;
5618 }
5619
5620 /* Read a single u16 from shared memory.
5621  * SHM 'offset' needs to be an even address
5622  */
5623 u16 wlc_read_shm(struct wlc_info *wlc, uint offset)
5624 {
5625         return wlc_bmac_read_shm(wlc->hw, offset);
5626 }
5627
5628 /* Write a single u16 to shared memory.
5629  * SHM 'offset' needs to be an even address
5630  */
5631 void wlc_write_shm(struct wlc_info *wlc, uint offset, u16 v)
5632 {
5633         wlc_bmac_write_shm(wlc->hw, offset, v);
5634 }
5635
5636 /* Copy a buffer to shared memory.
5637  * SHM 'offset' needs to be an even address and
5638  * Buffer length 'len' must be an even number of bytes
5639  */
5640 void wlc_copyto_shm(struct wlc_info *wlc, uint offset, const void *buf, int len)
5641 {
5642         /* offset and len need to be even */
5643         if (len <= 0 || (offset & 1) || (len & 1))
5644                 return;
5645
5646         wlc_bmac_copyto_objmem(wlc->hw, offset, buf, len, OBJADDR_SHM_SEL);
5647
5648 }
5649
5650 /* wrapper BMAC functions to for HIGH driver access */
5651 void wlc_mctrl(struct wlc_info *wlc, u32 mask, u32 val)
5652 {
5653         wlc_bmac_mctrl(wlc->hw, mask, val);
5654 }
5655
5656 void wlc_mhf(struct wlc_info *wlc, u8 idx, u16 mask, u16 val, int bands)
5657 {
5658         wlc_bmac_mhf(wlc->hw, idx, mask, val, bands);
5659 }
5660
5661 int wlc_xmtfifo_sz_get(struct wlc_info *wlc, uint fifo, uint *blocks)
5662 {
5663         return wlc_bmac_xmtfifo_sz_get(wlc->hw, fifo, blocks);
5664 }
5665
5666 void wlc_write_template_ram(struct wlc_info *wlc, int offset, int len,
5667                             void *buf)
5668 {
5669         wlc_bmac_write_template_ram(wlc->hw, offset, len, buf);
5670 }
5671
5672 void wlc_write_hw_bcntemplates(struct wlc_info *wlc, void *bcn, int len,
5673                                bool both)
5674 {
5675         wlc_bmac_write_hw_bcntemplates(wlc->hw, bcn, len, both);
5676 }
5677
5678 void
5679 wlc_set_addrmatch(struct wlc_info *wlc, int match_reg_offset,
5680                   const u8 *addr)
5681 {
5682         wlc_bmac_set_addrmatch(wlc->hw, match_reg_offset, addr);
5683         if (match_reg_offset == RCM_BSSID_OFFSET)
5684                 memcpy(wlc->cfg->BSSID, addr, ETH_ALEN);
5685 }
5686
5687 void wlc_pllreq(struct wlc_info *wlc, bool set, mbool req_bit)
5688 {
5689         wlc_bmac_pllreq(wlc->hw, set, req_bit);
5690 }
5691
5692 void wlc_reset_bmac_done(struct wlc_info *wlc)
5693 {
5694 }
5695
5696 /* check for the particular priority flow control bit being set */
5697 bool
5698 wlc_txflowcontrol_prio_isset(struct wlc_info *wlc, struct wlc_txq_info *q,
5699                              int prio)
5700 {
5701         uint prio_mask;
5702
5703         if (prio == ALLPRIO) {
5704                 prio_mask = TXQ_STOP_FOR_PRIOFC_MASK;
5705         } else {
5706                 prio_mask = NBITVAL(prio);
5707         }
5708
5709         return (q->stopped & prio_mask) == prio_mask;
5710 }
5711
5712 /* propagate the flow control to all interfaces using the given tx queue */
5713 void wlc_txflowcontrol(struct wlc_info *wlc, struct wlc_txq_info *qi,
5714                        bool on, int prio)
5715 {
5716         uint prio_bits;
5717         uint cur_bits;
5718
5719         BCMMSG(wlc->wiphy, "flow control kicks in\n");
5720
5721         if (prio == ALLPRIO) {
5722                 prio_bits = TXQ_STOP_FOR_PRIOFC_MASK;
5723         } else {
5724                 prio_bits = NBITVAL(prio);
5725         }
5726
5727         cur_bits = qi->stopped & prio_bits;
5728
5729         /* Check for the case of no change and return early
5730          * Otherwise update the bit and continue
5731          */
5732         if (on) {
5733                 if (cur_bits == prio_bits) {
5734                         return;
5735                 }
5736                 mboolset(qi->stopped, prio_bits);
5737         } else {
5738                 if (cur_bits == 0) {
5739                         return;
5740                 }
5741                 mboolclr(qi->stopped, prio_bits);
5742         }
5743
5744         /* If there is a flow control override we will not change the external
5745          * flow control state.
5746          */
5747         if (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK) {
5748                 return;
5749         }
5750
5751         wlc_txflowcontrol_signal(wlc, qi, on, prio);
5752 }
5753
5754 void
5755 wlc_txflowcontrol_override(struct wlc_info *wlc, struct wlc_txq_info *qi,
5756                            bool on, uint override)
5757 {
5758         uint prev_override;
5759
5760         prev_override = (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK);
5761
5762         /* Update the flow control bits and do an early return if there is
5763          * no change in the external flow control state.
5764          */
5765         if (on) {
5766                 mboolset(qi->stopped, override);
5767                 /* if there was a previous override bit on, then setting this
5768                  * makes no difference.
5769                  */
5770                 if (prev_override) {
5771                         return;
5772                 }
5773
5774                 wlc_txflowcontrol_signal(wlc, qi, ON, ALLPRIO);
5775         } else {
5776                 mboolclr(qi->stopped, override);
5777                 /* clearing an override bit will only make a difference for
5778                  * flow control if it was the only bit set. For any other
5779                  * override setting, just return
5780                  */
5781                 if (prev_override != override) {
5782                         return;
5783                 }
5784
5785                 if (qi->stopped == 0) {
5786                         wlc_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
5787                 } else {
5788                         int prio;
5789
5790                         for (prio = MAXPRIO; prio >= 0; prio--) {
5791                                 if (!mboolisset(qi->stopped, NBITVAL(prio)))
5792                                         wlc_txflowcontrol_signal(wlc, qi, OFF,
5793                                                                  prio);
5794                         }
5795                 }
5796         }
5797 }
5798
5799 static void wlc_txflowcontrol_reset(struct wlc_info *wlc)
5800 {
5801         struct wlc_txq_info *qi;
5802
5803         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
5804                 if (qi->stopped) {
5805                         wlc_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
5806                         qi->stopped = 0;
5807                 }
5808         }
5809 }
5810
5811 static void
5812 wlc_txflowcontrol_signal(struct wlc_info *wlc, struct wlc_txq_info *qi, bool on,
5813                          int prio)
5814 {
5815 #ifdef NON_FUNCTIONAL
5816         /* wlcif_list is never filled so this function is not functional */
5817         struct wlc_if *wlcif;
5818
5819         for (wlcif = wlc->wlcif_list; wlcif != NULL; wlcif = wlcif->next) {
5820                 if (wlcif->qi == qi && wlcif->flags & WLC_IF_LINKED)
5821                         brcms_txflowcontrol(wlc->wl, wlcif->wlif, on, prio);
5822         }
5823 #endif
5824 }
5825
5826 static struct wlc_txq_info *wlc_txq_alloc(struct wlc_info *wlc)
5827 {
5828         struct wlc_txq_info *qi, *p;
5829
5830         qi = kzalloc(sizeof(struct wlc_txq_info), GFP_ATOMIC);
5831         if (qi != NULL) {
5832                 /*
5833                  * Have enough room for control packets along with HI watermark
5834                  * Also, add room to txq for total psq packets if all the SCBs
5835                  * leave PS mode. The watermark for flowcontrol to OS packets
5836                  * will remain the same
5837                  */
5838                 bcm_pktq_init(&qi->q, WLC_PREC_COUNT,
5839                           (2 * wlc->pub->tunables->datahiwat) + PKTQ_LEN_DEFAULT
5840                           + wlc->pub->psq_pkts_total);
5841
5842                 /* add this queue to the the global list */
5843                 p = wlc->tx_queues;
5844                 if (p == NULL) {
5845                         wlc->tx_queues = qi;
5846                 } else {
5847                         while (p->next != NULL)
5848                                 p = p->next;
5849                         p->next = qi;
5850                 }
5851         }
5852         return qi;
5853 }
5854
5855 static void wlc_txq_free(struct wlc_info *wlc, struct wlc_txq_info *qi)
5856 {
5857         struct wlc_txq_info *p;
5858
5859         if (qi == NULL)
5860                 return;
5861
5862         /* remove the queue from the linked list */
5863         p = wlc->tx_queues;
5864         if (p == qi)
5865                 wlc->tx_queues = p->next;
5866         else {
5867                 while (p != NULL && p->next != qi)
5868                         p = p->next;
5869                 if (p != NULL)
5870                         p->next = p->next->next;
5871         }
5872
5873         kfree(qi);
5874 }
5875
5876 /*
5877  * Flag 'scan in progress' to withhold dynamic phy calibration
5878  */
5879 void wlc_scan_start(struct wlc_info *wlc)
5880 {
5881         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, true);
5882 }
5883
5884 void wlc_scan_stop(struct wlc_info *wlc)
5885 {
5886         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, false);
5887 }
5888
5889 void wlc_associate_upd(struct wlc_info *wlc, bool state)
5890 {
5891         wlc->pub->associated = state;
5892         wlc->cfg->associated = state;
5893 }
5894
5895 /*
5896  * When a remote STA/AP is removed by Mac80211, or when it can no longer accept
5897  * AMPDU traffic, packets pending in hardware have to be invalidated so that
5898  * when later on hardware releases them, they can be handled appropriately.
5899  */
5900 void wlc_inval_dma_pkts(struct wlc_hw_info *hw,
5901                                struct ieee80211_sta *sta,
5902                                void (*dma_callback_fn))
5903 {
5904         struct dma_pub *dmah;
5905         int i;
5906         for (i = 0; i < NFIFO; i++) {
5907                 dmah = hw->di[i];
5908                 if (dmah != NULL)
5909                         dma_walk_packets(dmah, dma_callback_fn, sta);
5910         }
5911 }
5912
5913 int wlc_get_curband(struct wlc_info *wlc)
5914 {
5915         return wlc->band->bandunit;
5916 }
5917
5918 void wlc_wait_for_tx_completion(struct wlc_info *wlc, bool drop)
5919 {
5920         /* flush packet queue when requested */
5921         if (drop)
5922                 bcm_pktq_flush(&wlc->pkt_queue->q, false, NULL, NULL);
5923
5924         /* wait for queue and DMA fifos to run dry */
5925         while (!pktq_empty(&wlc->pkt_queue->q) ||
5926                TXPKTPENDTOT(wlc) > 0) {
5927                 brcms_msleep(wlc->wl, 1);
5928         }
5929 }
5930
5931 int wlc_set_par(struct wlc_info *wlc, enum wlc_par_id par_id, int int_val)
5932 {
5933         int err = 0;
5934
5935         switch (par_id) {
5936         case IOV_BCN_LI_BCN:
5937                 wlc->bcn_li_bcn = (u8) int_val;
5938                 if (wlc->pub->up)
5939                         wlc_bcn_li_upd(wlc);
5940                 break;
5941                 /* As long as override is false, this only sets the *user*
5942                    targets. User can twiddle this all he wants with no harm.
5943                    wlc_phy_txpower_set() explicitly sets override to false if
5944                    not internal or test.
5945                  */
5946         case IOV_QTXPOWER:{
5947                 u8 qdbm;
5948                 bool override;
5949
5950                 /* Remove override bit and clip to max qdbm value */
5951                 qdbm = (u8)min_t(u32, (int_val & ~WL_TXPWR_OVERRIDE), 0xff);
5952                 /* Extract override setting */
5953                 override = (int_val & WL_TXPWR_OVERRIDE) ? true : false;
5954                 err =
5955                     wlc_phy_txpower_set(wlc->band->pi, qdbm, override);
5956                 break;
5957                 }
5958         case IOV_MPC:
5959                 wlc->mpc = (bool)int_val;
5960                 wlc_radio_mpc_upd(wlc);
5961                 break;
5962         default:
5963                 err = -ENOTSUPP;
5964         }
5965         return err;
5966 }
5967
5968 int wlc_get_par(struct wlc_info *wlc, enum wlc_par_id par_id, int *ret_int_ptr)
5969 {
5970         int err = 0;
5971
5972         switch (par_id) {
5973         case IOV_BCN_LI_BCN:
5974                 *ret_int_ptr = wlc->bcn_li_bcn;
5975                 break;
5976         case IOV_QTXPOWER: {
5977                 uint qdbm;
5978                 bool override;
5979
5980                 err = wlc_phy_txpower_get(wlc->band->pi, &qdbm,
5981                         &override);
5982                 if (err != 0)
5983                         return err;
5984
5985                 /* Return qdbm units */
5986                 *ret_int_ptr =
5987                     qdbm | (override ? WL_TXPWR_OVERRIDE : 0);
5988                 break;
5989                 }
5990         case IOV_MPC:
5991                 *ret_int_ptr = (s32) wlc->mpc;
5992                 break;
5993         default:
5994                 err = -ENOTSUPP;
5995         }
5996         return err;
5997 }