]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/staging/brcm80211/brcmsmac/wlc_main.c
staging: brcm80211: moved sbdma.h into brcmsmac/bcmdma.h
[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 wl_msg_level =
195 #if defined(BCMDBG)
196     WL_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         wl_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 = wl_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 = wl_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 wl_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                 wl_free_timer(wlc->wl, wlc->wdtimer);
1673                 wlc->wdtimer = NULL;
1674         }
1675         if (wlc->radio_timer) {
1676                 wl_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         wl_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         wl_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                 wl_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         wl_add_timer(wlc->wl, wlc->radio_timer, TIMER_INTERVAL_RADIOCHK, true);
1905         return true;
1906 }
1907
1908 bool wlc_radio_monitor_stop(struct wlc_info *wlc)
1909 {
1910         if (!wlc->radio_monitor)
1911                 return true;
1912
1913         wlc->radio_monitor = false;
1914         wlc_pllreq(wlc, false, WLC_PLLREQ_RADIO_MON);
1915         return wl_del_timer(wlc->wl, wlc->radio_timer);
1916 }
1917
1918 static void wlc_watchdog_by_timer(void *arg)
1919 {
1920         wlc_watchdog(arg);
1921 }
1922
1923 /* common watchdog code */
1924 static void wlc_watchdog(void *arg)
1925 {
1926         struct wlc_info *wlc = (struct wlc_info *) arg;
1927         int i;
1928         struct wlc_bsscfg *cfg;
1929
1930         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
1931
1932         if (!wlc->pub->up)
1933                 return;
1934
1935         if (DEVICEREMOVED(wlc)) {
1936                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
1937                           __func__);
1938                 wl_down(wlc->wl);
1939                 return;
1940         }
1941
1942         /* increment second count */
1943         wlc->pub->now++;
1944
1945         /* delay radio disable */
1946         if (wlc->mpc_delay_off) {
1947                 if (--wlc->mpc_delay_off == 0) {
1948                         mboolset(wlc->pub->radio_disabled,
1949                                  WL_RADIO_MPC_DISABLE);
1950                         if (wlc->mpc && wlc_ismpc(wlc))
1951                                 wlc->mpc_offcnt = 0;
1952                         wlc->mpc_laston_ts = OSL_SYSUPTIME();
1953                 }
1954         }
1955
1956         /* mpc sync */
1957         wlc_radio_mpc_upd(wlc);
1958         /* radio sync: sw/hw/mpc --> radio_disable/radio_enable */
1959         wlc_radio_hwdisable_upd(wlc);
1960         wlc_radio_upd(wlc);
1961         /* if radio is disable, driver may be down, quit here */
1962         if (wlc->pub->radio_disabled)
1963                 return;
1964
1965         wlc_bmac_watchdog(wlc);
1966
1967         /* occasionally sample mac stat counters to detect 16-bit counter wrap */
1968         if ((wlc->pub->now % SW_TIMER_MAC_STAT_UPD) == 0)
1969                 wlc_statsupd(wlc);
1970
1971         /* Manage TKIP countermeasures timers */
1972         FOREACH_BSS(wlc, i, cfg) {
1973                 if (cfg->tk_cm_dt) {
1974                         cfg->tk_cm_dt--;
1975                 }
1976                 if (cfg->tk_cm_bt) {
1977                         cfg->tk_cm_bt--;
1978                 }
1979         }
1980
1981         /* Call any registered watchdog handlers */
1982         for (i = 0; i < WLC_MAXMODULES; i++) {
1983                 if (wlc->modulecb[i].watchdog_fn)
1984                         wlc->modulecb[i].watchdog_fn(wlc->modulecb[i].hdl);
1985         }
1986
1987         if (WLCISNPHY(wlc->band) && !wlc->pub->tempsense_disable &&
1988             ((wlc->pub->now - wlc->tempsense_lasttime) >=
1989              WLC_TEMPSENSE_PERIOD)) {
1990                 wlc->tempsense_lasttime = wlc->pub->now;
1991                 wlc_tempsense_upd(wlc);
1992         }
1993 }
1994
1995 /* make interface operational */
1996 int wlc_up(struct wlc_info *wlc)
1997 {
1998         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
1999
2000         /* HW is turned off so don't try to access it */
2001         if (wlc->pub->hw_off || DEVICEREMOVED(wlc))
2002                 return -ENOMEDIUM;
2003
2004         if (!wlc->pub->hw_up) {
2005                 wlc_bmac_hw_up(wlc->hw);
2006                 wlc->pub->hw_up = true;
2007         }
2008
2009         if ((wlc->pub->boardflags & BFL_FEM)
2010             && (wlc->pub->sih->chip == BCM4313_CHIP_ID)) {
2011                 if (wlc->pub->boardrev >= 0x1250
2012                     && (wlc->pub->boardflags & BFL_FEM_BT)) {
2013                         wlc_mhf(wlc, MHF5, MHF5_4313_GPIOCTRL,
2014                                 MHF5_4313_GPIOCTRL, WLC_BAND_ALL);
2015                 } else {
2016                         wlc_mhf(wlc, MHF4, MHF4_EXTPA_ENABLE, MHF4_EXTPA_ENABLE,
2017                                 WLC_BAND_ALL);
2018                 }
2019         }
2020
2021         /*
2022          * Need to read the hwradio status here to cover the case where the system
2023          * is loaded with the hw radio disabled. We do not want to bring the driver up in this case.
2024          * if radio is disabled, abort up, lower power, start radio timer and return 0(for NDIS)
2025          * don't call radio_update to avoid looping wlc_up.
2026          *
2027          * wlc_bmac_up_prep() returns either 0 or -BCME_RADIOOFF only
2028          */
2029         if (!wlc->pub->radio_disabled) {
2030                 int status = wlc_bmac_up_prep(wlc->hw);
2031                 if (status == -ENOMEDIUM) {
2032                         if (!mboolisset
2033                             (wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE)) {
2034                                 int idx;
2035                                 struct wlc_bsscfg *bsscfg;
2036                                 mboolset(wlc->pub->radio_disabled,
2037                                          WL_RADIO_HW_DISABLE);
2038
2039                                 FOREACH_BSS(wlc, idx, bsscfg) {
2040                                         if (!BSSCFG_STA(bsscfg)
2041                                             || !bsscfg->enable || !bsscfg->BSS)
2042                                                 continue;
2043                                         wiphy_err(wlc->wiphy, "wl%d.%d: wlc_up"
2044                                                   ": rfdisable -> "
2045                                                   "wlc_bsscfg_disable()\n",
2046                                                    wlc->pub->unit, idx);
2047                                 }
2048                         }
2049                 }
2050         }
2051
2052         if (wlc->pub->radio_disabled) {
2053                 wlc_radio_monitor_start(wlc);
2054                 return 0;
2055         }
2056
2057         /* wlc_bmac_up_prep has done wlc_corereset(). so clk is on, set it */
2058         wlc->clk = true;
2059
2060         wlc_radio_monitor_stop(wlc);
2061
2062         /* Set EDCF hostflags */
2063         if (EDCF_ENAB(wlc->pub)) {
2064                 wlc_mhf(wlc, MHF1, MHF1_EDCF, MHF1_EDCF, WLC_BAND_ALL);
2065         } else {
2066                 wlc_mhf(wlc, MHF1, MHF1_EDCF, 0, WLC_BAND_ALL);
2067         }
2068
2069         if (WLC_WAR16165(wlc))
2070                 wlc_mhf(wlc, MHF2, MHF2_PCISLOWCLKWAR, MHF2_PCISLOWCLKWAR,
2071                         WLC_BAND_ALL);
2072
2073         wl_init(wlc->wl);
2074         wlc->pub->up = true;
2075
2076         if (wlc->bandinit_pending) {
2077                 wlc_suspend_mac_and_wait(wlc);
2078                 wlc_set_chanspec(wlc, wlc->default_bss->chanspec);
2079                 wlc->bandinit_pending = false;
2080                 wlc_enable_mac(wlc);
2081         }
2082
2083         wlc_bmac_up_finish(wlc->hw);
2084
2085         /* other software states up after ISR is running */
2086         /* start APs that were to be brought up but are not up  yet */
2087         /* if (AP_ENAB(wlc->pub)) wlc_restart_ap(wlc->ap); */
2088
2089         /* Program the TX wme params with the current settings */
2090         wlc_wme_retries_write(wlc);
2091
2092         /* start one second watchdog timer */
2093         wl_add_timer(wlc->wl, wlc->wdtimer, TIMER_INTERVAL_WATCHDOG, true);
2094         wlc->WDarmed = true;
2095
2096         /* ensure antenna config is up to date */
2097         wlc_stf_phy_txant_upd(wlc);
2098         /* ensure LDPC config is in sync */
2099         wlc_ht_update_ldpc(wlc, wlc->stf->ldpc);
2100
2101         return 0;
2102 }
2103
2104 /* Initialize the base precedence map for dequeueing from txq based on WME settings */
2105 static void wlc_tx_prec_map_init(struct wlc_info *wlc)
2106 {
2107         wlc->tx_prec_map = WLC_PREC_BMP_ALL;
2108         memset(wlc->fifo2prec_map, 0, NFIFO * sizeof(u16));
2109
2110         /* For non-WME, both fifos have overlapping MAXPRIO. So just disable all precedences
2111          * if either is full.
2112          */
2113         if (!EDCF_ENAB(wlc->pub)) {
2114                 wlc->fifo2prec_map[TX_DATA_FIFO] = WLC_PREC_BMP_ALL;
2115                 wlc->fifo2prec_map[TX_CTL_FIFO] = WLC_PREC_BMP_ALL;
2116         } else {
2117                 wlc->fifo2prec_map[TX_AC_BK_FIFO] = WLC_PREC_BMP_AC_BK;
2118                 wlc->fifo2prec_map[TX_AC_BE_FIFO] = WLC_PREC_BMP_AC_BE;
2119                 wlc->fifo2prec_map[TX_AC_VI_FIFO] = WLC_PREC_BMP_AC_VI;
2120                 wlc->fifo2prec_map[TX_AC_VO_FIFO] = WLC_PREC_BMP_AC_VO;
2121         }
2122 }
2123
2124 static uint wlc_down_del_timer(struct wlc_info *wlc)
2125 {
2126         uint callbacks = 0;
2127
2128         return callbacks;
2129 }
2130
2131 /*
2132  * Mark the interface nonoperational, stop the software mechanisms,
2133  * disable the hardware, free any transient buffer state.
2134  * Return a count of the number of driver callbacks still pending.
2135  */
2136 uint wlc_down(struct wlc_info *wlc)
2137 {
2138
2139         uint callbacks = 0;
2140         int i;
2141         bool dev_gone = false;
2142         struct wlc_txq_info *qi;
2143
2144         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
2145
2146         /* check if we are already in the going down path */
2147         if (wlc->going_down) {
2148                 wiphy_err(wlc->wiphy, "wl%d: %s: Driver going down so return"
2149                           "\n", wlc->pub->unit, __func__);
2150                 return 0;
2151         }
2152         if (!wlc->pub->up)
2153                 return callbacks;
2154
2155         /* in between, mpc could try to bring down again.. */
2156         wlc->going_down = true;
2157
2158         callbacks += wlc_bmac_down_prep(wlc->hw);
2159
2160         dev_gone = DEVICEREMOVED(wlc);
2161
2162         /* Call any registered down handlers */
2163         for (i = 0; i < WLC_MAXMODULES; i++) {
2164                 if (wlc->modulecb[i].down_fn)
2165                         callbacks +=
2166                             wlc->modulecb[i].down_fn(wlc->modulecb[i].hdl);
2167         }
2168
2169         /* cancel the watchdog timer */
2170         if (wlc->WDarmed) {
2171                 if (!wl_del_timer(wlc->wl, wlc->wdtimer))
2172                         callbacks++;
2173                 wlc->WDarmed = false;
2174         }
2175         /* cancel all other timers */
2176         callbacks += wlc_down_del_timer(wlc);
2177
2178         wlc->pub->up = false;
2179
2180         wlc_phy_mute_upd(wlc->band->pi, false, PHY_MUTE_ALL);
2181
2182         /* clear txq flow control */
2183         wlc_txflowcontrol_reset(wlc);
2184
2185         /* flush tx queues */
2186         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
2187                 bcm_pktq_flush(&qi->q, true, NULL, NULL);
2188         }
2189
2190         callbacks += wlc_bmac_down_finish(wlc->hw);
2191
2192         /* wlc_bmac_down_finish has done wlc_coredisable(). so clk is off */
2193         wlc->clk = false;
2194
2195         wlc->going_down = false;
2196         return callbacks;
2197 }
2198
2199 /* Set the current gmode configuration */
2200 int wlc_set_gmode(struct wlc_info *wlc, u8 gmode, bool config)
2201 {
2202         int ret = 0;
2203         uint i;
2204         wlc_rateset_t rs;
2205         /* Default to 54g Auto */
2206         s8 shortslot = WLC_SHORTSLOT_AUTO;      /* Advertise and use shortslot (-1/0/1 Auto/Off/On) */
2207         bool shortslot_restrict = false;        /* Restrict association to stations that support shortslot
2208                                                  */
2209         bool ofdm_basic = false;        /* Make 6, 12, and 24 basic rates */
2210         int preamble = WLC_PLCP_LONG;   /* Advertise and use short preambles (-1/0/1 Auto/Off/On) */
2211         bool preamble_restrict = false; /* Restrict association to stations that support short
2212                                          * preambles
2213                                          */
2214         struct wlcband *band;
2215
2216         /* if N-support is enabled, allow Gmode set as long as requested
2217          * Gmode is not GMODE_LEGACY_B
2218          */
2219         if (N_ENAB(wlc->pub) && gmode == GMODE_LEGACY_B)
2220                 return -ENOTSUPP;
2221
2222         /* verify that we are dealing with 2G band and grab the band pointer */
2223         if (wlc->band->bandtype == WLC_BAND_2G)
2224                 band = wlc->band;
2225         else if ((NBANDS(wlc) > 1) &&
2226                  (wlc->bandstate[OTHERBANDUNIT(wlc)]->bandtype == WLC_BAND_2G))
2227                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
2228         else
2229                 return -EINVAL;
2230
2231         /* Legacy or bust when no OFDM is supported by regulatory */
2232         if ((wlc_channel_locale_flags_in_band(wlc->cmi, band->bandunit) &
2233              WLC_NO_OFDM) && (gmode != GMODE_LEGACY_B))
2234                 return -EINVAL;
2235
2236         /* update configuration value */
2237         if (config == true)
2238                 wlc_protection_upd(wlc, WLC_PROT_G_USER, gmode);
2239
2240         /* Clear supported rates filter */
2241         memset(&wlc->sup_rates_override, 0, sizeof(wlc_rateset_t));
2242
2243         /* Clear rateset override */
2244         memset(&rs, 0, sizeof(wlc_rateset_t));
2245
2246         switch (gmode) {
2247         case GMODE_LEGACY_B:
2248                 shortslot = WLC_SHORTSLOT_OFF;
2249                 wlc_rateset_copy(&gphy_legacy_rates, &rs);
2250
2251                 break;
2252
2253         case GMODE_LRS:
2254                 if (AP_ENAB(wlc->pub))
2255                         wlc_rateset_copy(&cck_rates, &wlc->sup_rates_override);
2256                 break;
2257
2258         case GMODE_AUTO:
2259                 /* Accept defaults */
2260                 break;
2261
2262         case GMODE_ONLY:
2263                 ofdm_basic = true;
2264                 preamble = WLC_PLCP_SHORT;
2265                 preamble_restrict = true;
2266                 break;
2267
2268         case GMODE_PERFORMANCE:
2269                 if (AP_ENAB(wlc->pub))  /* Put all rates into the Supported Rates element */
2270                         wlc_rateset_copy(&cck_ofdm_rates,
2271                                          &wlc->sup_rates_override);
2272
2273                 shortslot = WLC_SHORTSLOT_ON;
2274                 shortslot_restrict = true;
2275                 ofdm_basic = true;
2276                 preamble = WLC_PLCP_SHORT;
2277                 preamble_restrict = true;
2278                 break;
2279
2280         default:
2281                 /* Error */
2282                 wiphy_err(wlc->wiphy, "wl%d: %s: invalid gmode %d\n",
2283                           wlc->pub->unit, __func__, gmode);
2284                 return -ENOTSUPP;
2285         }
2286
2287         /*
2288          * If we are switching to gmode == GMODE_LEGACY_B,
2289          * clean up rate info that may refer to OFDM rates.
2290          */
2291         if ((gmode == GMODE_LEGACY_B) && (band->gmode != GMODE_LEGACY_B)) {
2292                 band->gmode = gmode;
2293                 if (band->rspec_override && !IS_CCK(band->rspec_override)) {
2294                         band->rspec_override = 0;
2295                         wlc_reprate_init(wlc);
2296                 }
2297                 if (band->mrspec_override && !IS_CCK(band->mrspec_override)) {
2298                         band->mrspec_override = 0;
2299                 }
2300         }
2301
2302         band->gmode = gmode;
2303
2304         wlc->shortslot_override = shortslot;
2305
2306         if (AP_ENAB(wlc->pub)) {
2307                 /* wlc->ap->shortslot_restrict = shortslot_restrict; */
2308                 wlc->PLCPHdr_override =
2309                     (preamble !=
2310                      WLC_PLCP_LONG) ? WLC_PLCP_SHORT : WLC_PLCP_AUTO;
2311         }
2312
2313         if ((AP_ENAB(wlc->pub) && preamble != WLC_PLCP_LONG)
2314             || preamble == WLC_PLCP_SHORT)
2315                 wlc->default_bss->capability |= WLAN_CAPABILITY_SHORT_PREAMBLE;
2316         else
2317                 wlc->default_bss->capability &= ~WLAN_CAPABILITY_SHORT_PREAMBLE;
2318
2319         /* Update shortslot capability bit for AP and IBSS */
2320         if ((AP_ENAB(wlc->pub) && shortslot == WLC_SHORTSLOT_AUTO) ||
2321             shortslot == WLC_SHORTSLOT_ON)
2322                 wlc->default_bss->capability |= WLAN_CAPABILITY_SHORT_SLOT_TIME;
2323         else
2324                 wlc->default_bss->capability &=
2325                                         ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
2326
2327         /* Use the default 11g rateset */
2328         if (!rs.count)
2329                 wlc_rateset_copy(&cck_ofdm_rates, &rs);
2330
2331         if (ofdm_basic) {
2332                 for (i = 0; i < rs.count; i++) {
2333                         if (rs.rates[i] == WLC_RATE_6M
2334                             || rs.rates[i] == WLC_RATE_12M
2335                             || rs.rates[i] == WLC_RATE_24M)
2336                                 rs.rates[i] |= WLC_RATE_FLAG;
2337                 }
2338         }
2339
2340         /* Set default bss rateset */
2341         wlc->default_bss->rateset.count = rs.count;
2342         memcpy(wlc->default_bss->rateset.rates, rs.rates, 
2343                sizeof(wlc->default_bss->rateset.rates));
2344
2345         return ret;
2346 }
2347
2348 static int wlc_nmode_validate(struct wlc_info *wlc, s32 nmode)
2349 {
2350         int err = 0;
2351
2352         switch (nmode) {
2353
2354         case OFF:
2355                 break;
2356
2357         case AUTO:
2358         case WL_11N_2x2:
2359         case WL_11N_3x3:
2360                 if (!(WLC_PHY_11N_CAP(wlc->band)))
2361                         err = -EINVAL;
2362                 break;
2363
2364         default:
2365                 err = -EINVAL;
2366                 break;
2367         }
2368
2369         return err;
2370 }
2371
2372 int wlc_set_nmode(struct wlc_info *wlc, s32 nmode)
2373 {
2374         uint i;
2375         int err;
2376
2377         err = wlc_nmode_validate(wlc, nmode);
2378         if (err)
2379                 return err;
2380
2381         switch (nmode) {
2382         case OFF:
2383                 wlc->pub->_n_enab = OFF;
2384                 wlc->default_bss->flags &= ~WLC_BSS_HT;
2385                 /* delete the mcs rates from the default and hw ratesets */
2386                 wlc_rateset_mcs_clear(&wlc->default_bss->rateset);
2387                 for (i = 0; i < NBANDS(wlc); i++) {
2388                         memset(wlc->bandstate[i]->hw_rateset.mcs, 0,
2389                                MCSSET_LEN);
2390                         if (IS_MCS(wlc->band->rspec_override)) {
2391                                 wlc->bandstate[i]->rspec_override = 0;
2392                                 wlc_reprate_init(wlc);
2393                         }
2394                         if (IS_MCS(wlc->band->mrspec_override))
2395                                 wlc->bandstate[i]->mrspec_override = 0;
2396                 }
2397                 break;
2398
2399         case AUTO:
2400                 if (wlc->stf->txstreams == WL_11N_3x3)
2401                         nmode = WL_11N_3x3;
2402                 else
2403                         nmode = WL_11N_2x2;
2404         case WL_11N_2x2:
2405         case WL_11N_3x3:
2406                 /* force GMODE_AUTO if NMODE is ON */
2407                 wlc_set_gmode(wlc, GMODE_AUTO, true);
2408                 if (nmode == WL_11N_3x3)
2409                         wlc->pub->_n_enab = SUPPORT_HT;
2410                 else
2411                         wlc->pub->_n_enab = SUPPORT_11N;
2412                 wlc->default_bss->flags |= WLC_BSS_HT;
2413                 /* add the mcs rates to the default and hw ratesets */
2414                 wlc_rateset_mcs_build(&wlc->default_bss->rateset,
2415                                       wlc->stf->txstreams);
2416                 for (i = 0; i < NBANDS(wlc); i++)
2417                         memcpy(wlc->bandstate[i]->hw_rateset.mcs,
2418                                wlc->default_bss->rateset.mcs, MCSSET_LEN);
2419                 break;
2420
2421         default:
2422                 break;
2423         }
2424
2425         return err;
2426 }
2427
2428 static int wlc_set_rateset(struct wlc_info *wlc, wlc_rateset_t *rs_arg)
2429 {
2430         wlc_rateset_t rs, new;
2431         uint bandunit;
2432
2433         memcpy(&rs, rs_arg, sizeof(wlc_rateset_t));
2434
2435         /* check for bad count value */
2436         if ((rs.count == 0) || (rs.count > WLC_NUMRATES))
2437                 return -EINVAL;
2438
2439         /* try the current band */
2440         bandunit = wlc->band->bandunit;
2441         memcpy(&new, &rs, sizeof(wlc_rateset_t));
2442         if (wlc_rate_hwrs_filter_sort_validate
2443             (&new, &wlc->bandstate[bandunit]->hw_rateset, true,
2444              wlc->stf->txstreams))
2445                 goto good;
2446
2447         /* try the other band */
2448         if (IS_MBAND_UNLOCKED(wlc)) {
2449                 bandunit = OTHERBANDUNIT(wlc);
2450                 memcpy(&new, &rs, sizeof(wlc_rateset_t));
2451                 if (wlc_rate_hwrs_filter_sort_validate(&new,
2452                                                        &wlc->
2453                                                        bandstate[bandunit]->
2454                                                        hw_rateset, true,
2455                                                        wlc->stf->txstreams))
2456                         goto good;
2457         }
2458
2459         return -EBADE;
2460
2461  good:
2462         /* apply new rateset */
2463         memcpy(&wlc->default_bss->rateset, &new, sizeof(wlc_rateset_t));
2464         memcpy(&wlc->bandstate[bandunit]->defrateset, &new,
2465                sizeof(wlc_rateset_t));
2466         return 0;
2467 }
2468
2469 /* simplified integer set interface for common ioctl handler */
2470 int wlc_set(struct wlc_info *wlc, int cmd, int arg)
2471 {
2472         return wlc_ioctl(wlc, cmd, (void *)&arg, sizeof(arg), NULL);
2473 }
2474
2475 /* simplified integer get interface for common ioctl handler */
2476 int wlc_get(struct wlc_info *wlc, int cmd, int *arg)
2477 {
2478         return wlc_ioctl(wlc, cmd, arg, sizeof(int), NULL);
2479 }
2480
2481 static void wlc_ofdm_rateset_war(struct wlc_info *wlc)
2482 {
2483         u8 r;
2484         bool war = false;
2485
2486         if (wlc->cfg->associated)
2487                 r = wlc->cfg->current_bss->rateset.rates[0];
2488         else
2489                 r = wlc->default_bss->rateset.rates[0];
2490
2491         wlc_phy_ofdm_rateset_war(wlc->band->pi, war);
2492
2493         return;
2494 }
2495
2496 int
2497 wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
2498           struct wlc_if *wlcif)
2499 {
2500         return _wlc_ioctl(wlc, cmd, arg, len, wlcif);
2501 }
2502
2503 /* common ioctl handler. return: 0=ok, -1=error, positive=particular error */
2504 static int
2505 _wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
2506            struct wlc_if *wlcif)
2507 {
2508         int val, *pval;
2509         bool bool_val;
2510         int bcmerror;
2511         d11regs_t *regs;
2512         struct scb *nextscb;
2513         bool ta_ok;
2514         uint band;
2515         struct wlc_bsscfg *bsscfg;
2516         wlc_bss_info_t *current_bss;
2517
2518         /* update bsscfg pointer */
2519         bsscfg = wlc->cfg;
2520         current_bss = bsscfg->current_bss;
2521
2522         /* initialize the following to get rid of compiler warning */
2523         nextscb = NULL;
2524         ta_ok = false;
2525         band = 0;
2526
2527         /* If the device is turned off, then it's not "removed" */
2528         if (!wlc->pub->hw_off && DEVICEREMOVED(wlc)) {
2529                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
2530                           __func__);
2531                 wl_down(wlc->wl);
2532                 return -EBADE;
2533         }
2534
2535         /* default argument is generic integer */
2536         pval = arg ? (int *)arg:NULL;
2537
2538         /* This will prevent the misaligned access */
2539         if (pval && (u32) len >= sizeof(val))
2540                 memcpy(&val, pval, sizeof(val));
2541         else
2542                 val = 0;
2543
2544         /* bool conversion to avoid duplication below */
2545         bool_val = val != 0;
2546         bcmerror = 0;
2547         regs = wlc->regs;
2548
2549         if ((arg == NULL) || (len <= 0)) {
2550                 wiphy_err(wlc->wiphy, "wl%d: %s: Command %d needs arguments\n",
2551                           wlc->pub->unit, __func__, cmd);
2552                 bcmerror = -EINVAL;
2553                 goto done;
2554         }
2555
2556         switch (cmd) {
2557
2558         case WLC_SET_CHANNEL:{
2559                         chanspec_t chspec = CH20MHZ_CHSPEC(val);
2560
2561                         if (val < 0 || val > MAXCHANNEL) {
2562                                 bcmerror = -EINVAL;
2563                                 break;
2564                         }
2565
2566                         if (!wlc_valid_chanspec_db(wlc->cmi, chspec)) {
2567                                 bcmerror = -EINVAL;
2568                                 break;
2569                         }
2570
2571                         if (!wlc->pub->up && IS_MBAND_UNLOCKED(wlc)) {
2572                                 if (wlc->band->bandunit !=
2573                                     CHSPEC_WLCBANDUNIT(chspec))
2574                                         wlc->bandinit_pending = true;
2575                                 else
2576                                         wlc->bandinit_pending = false;
2577                         }
2578
2579                         wlc->default_bss->chanspec = chspec;
2580                         /* wlc_BSSinit() will sanitize the rateset before using it.. */
2581                         if (wlc->pub->up &&
2582                             (WLC_BAND_PI_RADIO_CHANSPEC != chspec)) {
2583                                 wlc_set_home_chanspec(wlc, chspec);
2584                                 wlc_suspend_mac_and_wait(wlc);
2585                                 wlc_set_chanspec(wlc, chspec);
2586                                 wlc_enable_mac(wlc);
2587                         }
2588                         break;
2589                 }
2590
2591         case WLC_SET_SRL:
2592                 if (val >= 1 && val <= RETRY_SHORT_MAX) {
2593                         int ac;
2594                         wlc->SRL = (u16) val;
2595
2596                         wlc_bmac_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
2597
2598                         for (ac = 0; ac < AC_COUNT; ac++) {
2599                                 WLC_WME_RETRY_SHORT_SET(wlc, ac, wlc->SRL);
2600                         }
2601                         wlc_wme_retries_write(wlc);
2602                 } else
2603                         bcmerror = -EINVAL;
2604                 break;
2605
2606         case WLC_SET_LRL:
2607                 if (val >= 1 && val <= 255) {
2608                         int ac;
2609                         wlc->LRL = (u16) val;
2610
2611                         wlc_bmac_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
2612
2613                         for (ac = 0; ac < AC_COUNT; ac++) {
2614                                 WLC_WME_RETRY_LONG_SET(wlc, ac, wlc->LRL);
2615                         }
2616                         wlc_wme_retries_write(wlc);
2617                 } else
2618                         bcmerror = -EINVAL;
2619                 break;
2620
2621         case WLC_GET_CURR_RATESET:{
2622                         wl_rateset_t *ret_rs = (wl_rateset_t *) arg;
2623                         wlc_rateset_t *rs;
2624
2625                         if (wlc->pub->associated)
2626                                 rs = &current_bss->rateset;
2627                         else
2628                                 rs = &wlc->default_bss->rateset;
2629
2630                         if (len < (int)(rs->count + sizeof(rs->count))) {
2631                                 bcmerror = -EOVERFLOW;
2632                                 break;
2633                         }
2634
2635                         /* Copy only legacy rateset section */
2636                         ret_rs->count = rs->count;
2637                         memcpy(&ret_rs->rates, &rs->rates, rs->count);
2638                         break;
2639                 }
2640
2641         case WLC_SET_RATESET:{
2642                         wlc_rateset_t rs;
2643                         wl_rateset_t *in_rs = (wl_rateset_t *) arg;
2644
2645                         if (len < (int)(in_rs->count + sizeof(in_rs->count))) {
2646                                 bcmerror = -EOVERFLOW;
2647                                 break;
2648                         }
2649
2650                         if (in_rs->count > WLC_NUMRATES) {
2651                                 bcmerror = -ENOBUFS;
2652                                 break;
2653                         }
2654
2655                         memset(&rs, 0, sizeof(wlc_rateset_t));
2656
2657                         /* Copy only legacy rateset section */
2658                         rs.count = in_rs->count;
2659                         memcpy(&rs.rates, &in_rs->rates, rs.count);
2660
2661                         /* merge rateset coming in with the current mcsset */
2662                         if (N_ENAB(wlc->pub)) {
2663                                 if (bsscfg->associated)
2664                                         memcpy(rs.mcs,
2665                                                &current_bss->rateset.mcs[0],
2666                                                MCSSET_LEN);
2667                                 else
2668                                         memcpy(rs.mcs,
2669                                                &wlc->default_bss->rateset.mcs[0],
2670                                                MCSSET_LEN);
2671                         }
2672
2673                         bcmerror = wlc_set_rateset(wlc, &rs);
2674
2675                         if (!bcmerror)
2676                                 wlc_ofdm_rateset_war(wlc);
2677
2678                         break;
2679                 }
2680
2681         case WLC_SET_BCNPRD:
2682                 /* range [1, 0xffff] */
2683                 if (val >= DOT11_MIN_BEACON_PERIOD
2684                     && val <= DOT11_MAX_BEACON_PERIOD) {
2685                         wlc->default_bss->beacon_period = (u16) val;
2686                 } else
2687                         bcmerror = -EINVAL;
2688                 break;
2689
2690         case WLC_GET_PHYLIST:
2691                 {
2692                         unsigned char *cp = arg;
2693                         if (len < 3) {
2694                                 bcmerror = -EOVERFLOW;
2695                                 break;
2696                         }
2697
2698                         if (WLCISNPHY(wlc->band)) {
2699                                 *cp++ = 'n';
2700                         } else if (WLCISLCNPHY(wlc->band)) {
2701                                 *cp++ = 'c';
2702                         } else if (WLCISSSLPNPHY(wlc->band)) {
2703                                 *cp++ = 's';
2704                         }
2705                         *cp = '\0';
2706                         break;
2707                 }
2708
2709         case WLC_SET_SHORTSLOT_OVERRIDE:
2710                 if ((val != WLC_SHORTSLOT_AUTO) &&
2711                     (val != WLC_SHORTSLOT_OFF) && (val != WLC_SHORTSLOT_ON)) {
2712                         bcmerror = -EINVAL;
2713                         break;
2714                 }
2715
2716                 wlc->shortslot_override = (s8) val;
2717
2718                 /* shortslot is an 11g feature, so no more work if we are
2719                  * currently on the 5G band
2720                  */
2721                 if (BAND_5G(wlc->band->bandtype))
2722                         break;
2723
2724                 if (wlc->pub->up && wlc->pub->associated) {
2725                         /* let watchdog or beacon processing update shortslot */
2726                 } else if (wlc->pub->up) {
2727                         /* unassociated shortslot is off */
2728                         wlc_switch_shortslot(wlc, false);
2729                 } else {
2730                         /* driver is down, so just update the wlc_info value */
2731                         if (wlc->shortslot_override == WLC_SHORTSLOT_AUTO) {
2732                                 wlc->shortslot = false;
2733                         } else {
2734                                 wlc->shortslot =
2735                                     (wlc->shortslot_override ==
2736                                      WLC_SHORTSLOT_ON);
2737                         }
2738                 }
2739
2740                 break;
2741
2742         }
2743  done:
2744
2745         if (bcmerror)
2746                 wlc->pub->bcmerror = bcmerror;
2747
2748         return bcmerror;
2749 }
2750
2751 /*
2752  * register watchdog and down handlers.
2753  */
2754 int wlc_module_register(struct wlc_pub *pub,
2755                         const char *name, void *hdl,
2756                         watchdog_fn_t w_fn, down_fn_t d_fn)
2757 {
2758         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
2759         int i;
2760
2761         /* find an empty entry and just add, no duplication check! */
2762         for (i = 0; i < WLC_MAXMODULES; i++) {
2763                 if (wlc->modulecb[i].name[0] == '\0') {
2764                         strncpy(wlc->modulecb[i].name, name,
2765                                 sizeof(wlc->modulecb[i].name) - 1);
2766                         wlc->modulecb[i].hdl = hdl;
2767                         wlc->modulecb[i].watchdog_fn = w_fn;
2768                         wlc->modulecb[i].down_fn = d_fn;
2769                         return 0;
2770                 }
2771         }
2772
2773         return -ENOSR;
2774 }
2775
2776 /* unregister module callbacks */
2777 int wlc_module_unregister(struct wlc_pub *pub, const char *name, void *hdl)
2778 {
2779         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
2780         int i;
2781
2782         if (wlc == NULL)
2783                 return -ENODATA;
2784
2785         for (i = 0; i < WLC_MAXMODULES; i++) {
2786                 if (!strcmp(wlc->modulecb[i].name, name) &&
2787                     (wlc->modulecb[i].hdl == hdl)) {
2788                         memset(&wlc->modulecb[i], 0, sizeof(struct modulecb));
2789                         return 0;
2790                 }
2791         }
2792
2793         /* table not found! */
2794         return -ENODATA;
2795 }
2796
2797 /* Write WME tunable parameters for retransmit/max rate from wlc struct to ucode */
2798 static void wlc_wme_retries_write(struct wlc_info *wlc)
2799 {
2800         int ac;
2801
2802         /* Need clock to do this */
2803         if (!wlc->clk)
2804                 return;
2805
2806         for (ac = 0; ac < AC_COUNT; ac++) {
2807                 wlc_write_shm(wlc, M_AC_TXLMT_ADDR(ac), wlc->wme_retries[ac]);
2808         }
2809 }
2810
2811 #ifdef BCMDBG
2812 static const char *supr_reason[] = {
2813         "None", "PMQ Entry", "Flush request",
2814         "Previous frag failure", "Channel mismatch",
2815         "Lifetime Expiry", "Underflow"
2816 };
2817
2818 static void wlc_print_txs_status(u16 s)
2819 {
2820         printk(KERN_DEBUG "[15:12]  %d  frame attempts\n",
2821                (s & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT);
2822         printk(KERN_DEBUG " [11:8]  %d  rts attempts\n",
2823                (s & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT);
2824         printk(KERN_DEBUG "    [7]  %d  PM mode indicated\n",
2825                ((s & TX_STATUS_PMINDCTD) ? 1 : 0));
2826         printk(KERN_DEBUG "    [6]  %d  intermediate status\n",
2827                ((s & TX_STATUS_INTERMEDIATE) ? 1 : 0));
2828         printk(KERN_DEBUG "    [5]  %d  AMPDU\n",
2829                (s & TX_STATUS_AMPDU) ? 1 : 0);
2830         printk(KERN_DEBUG "  [4:2]  %d  Frame Suppressed Reason (%s)\n",
2831                ((s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT),
2832                supr_reason[(s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT]);
2833         printk(KERN_DEBUG "    [1]  %d  acked\n",
2834                ((s & TX_STATUS_ACK_RCV) ? 1 : 0));
2835 }
2836 #endif                          /* BCMDBG */
2837
2838 void wlc_print_txstatus(tx_status_t *txs)
2839 {
2840 #if defined(BCMDBG)
2841         u16 s = txs->status;
2842         u16 ackphyrxsh = txs->ackphyrxsh;
2843
2844         printk(KERN_DEBUG "\ntxpkt (MPDU) Complete\n");
2845
2846         printk(KERN_DEBUG "FrameID: %04x   ", txs->frameid);
2847         printk(KERN_DEBUG "TxStatus: %04x", s);
2848         printk(KERN_DEBUG "\n");
2849
2850         wlc_print_txs_status(s);
2851
2852         printk(KERN_DEBUG "LastTxTime: %04x ", txs->lasttxtime);
2853         printk(KERN_DEBUG "Seq: %04x ", txs->sequence);
2854         printk(KERN_DEBUG "PHYTxStatus: %04x ", txs->phyerr);
2855         printk(KERN_DEBUG "RxAckRSSI: %04x ",
2856                (ackphyrxsh & PRXS1_JSSI_MASK) >> PRXS1_JSSI_SHIFT);
2857         printk(KERN_DEBUG "RxAckSQ: %04x",
2858                (ackphyrxsh & PRXS1_SQ_MASK) >> PRXS1_SQ_SHIFT);
2859         printk(KERN_DEBUG "\n");
2860 #endif                          /* defined(BCMDBG) */
2861 }
2862
2863 void wlc_statsupd(struct wlc_info *wlc)
2864 {
2865         int i;
2866         macstat_t macstats;
2867 #ifdef BCMDBG
2868         u16 delta;
2869         u16 rxf0ovfl;
2870         u16 txfunfl[NFIFO];
2871 #endif                          /* BCMDBG */
2872
2873         /* if driver down, make no sense to update stats */
2874         if (!wlc->pub->up)
2875                 return;
2876
2877 #ifdef BCMDBG
2878         /* save last rx fifo 0 overflow count */
2879         rxf0ovfl = wlc->core->macstat_snapshot->rxf0ovfl;
2880
2881         /* save last tx fifo  underflow count */
2882         for (i = 0; i < NFIFO; i++)
2883                 txfunfl[i] = wlc->core->macstat_snapshot->txfunfl[i];
2884 #endif                          /* BCMDBG */
2885
2886         /* Read mac stats from contiguous shared memory */
2887         wlc_bmac_copyfrom_shm(wlc->hw, M_UCODE_MACSTAT,
2888                               &macstats, sizeof(macstat_t));
2889
2890 #ifdef BCMDBG
2891         /* check for rx fifo 0 overflow */
2892         delta = (u16) (wlc->core->macstat_snapshot->rxf0ovfl - rxf0ovfl);
2893         if (delta)
2894                 wiphy_err(wlc->wiphy, "wl%d: %u rx fifo 0 overflows!\n",
2895                           wlc->pub->unit, delta);
2896
2897         /* check for tx fifo underflows */
2898         for (i = 0; i < NFIFO; i++) {
2899                 delta =
2900                     (u16) (wlc->core->macstat_snapshot->txfunfl[i] -
2901                               txfunfl[i]);
2902                 if (delta)
2903                         wiphy_err(wlc->wiphy, "wl%d: %u tx fifo %d underflows!"
2904                                   "\n", wlc->pub->unit, delta, i);
2905         }
2906 #endif                          /* BCMDBG */
2907
2908         /* merge counters from dma module */
2909         for (i = 0; i < NFIFO; i++) {
2910                 if (wlc->hw->di[i]) {
2911                         dma_counterreset(wlc->hw->di[i]);
2912                 }
2913         }
2914 }
2915
2916 bool wlc_chipmatch(u16 vendor, u16 device)
2917 {
2918         if (vendor != PCI_VENDOR_ID_BROADCOM) {
2919                 pr_err("wlc_chipmatch: unknown vendor id %04x\n", vendor);
2920                 return false;
2921         }
2922
2923         if (device == BCM43224_D11N_ID_VEN1)
2924                 return true;
2925         if ((device == BCM43224_D11N_ID) || (device == BCM43225_D11N2G_ID))
2926                 return true;
2927         if (device == BCM4313_D11N2G_ID)
2928                 return true;
2929         if ((device == BCM43236_D11N_ID) || (device == BCM43236_D11N2G_ID))
2930                 return true;
2931
2932         pr_err("wlc_chipmatch: unknown device id %04x\n", device);
2933         return false;
2934 }
2935
2936 #if defined(BCMDBG)
2937 void wlc_print_txdesc(d11txh_t *txh)
2938 {
2939         u16 mtcl = le16_to_cpu(txh->MacTxControlLow);
2940         u16 mtch = le16_to_cpu(txh->MacTxControlHigh);
2941         u16 mfc = le16_to_cpu(txh->MacFrameControl);
2942         u16 tfest = le16_to_cpu(txh->TxFesTimeNormal);
2943         u16 ptcw = le16_to_cpu(txh->PhyTxControlWord);
2944         u16 ptcw_1 = le16_to_cpu(txh->PhyTxControlWord_1);
2945         u16 ptcw_1_Fbr = le16_to_cpu(txh->PhyTxControlWord_1_Fbr);
2946         u16 ptcw_1_Rts = le16_to_cpu(txh->PhyTxControlWord_1_Rts);
2947         u16 ptcw_1_FbrRts = le16_to_cpu(txh->PhyTxControlWord_1_FbrRts);
2948         u16 mainrates = le16_to_cpu(txh->MainRates);
2949         u16 xtraft = le16_to_cpu(txh->XtraFrameTypes);
2950         u8 *iv = txh->IV;
2951         u8 *ra = txh->TxFrameRA;
2952         u16 tfestfb = le16_to_cpu(txh->TxFesTimeFallback);
2953         u8 *rtspfb = txh->RTSPLCPFallback;
2954         u16 rtsdfb = le16_to_cpu(txh->RTSDurFallback);
2955         u8 *fragpfb = txh->FragPLCPFallback;
2956         u16 fragdfb = le16_to_cpu(txh->FragDurFallback);
2957         u16 mmodelen = le16_to_cpu(txh->MModeLen);
2958         u16 mmodefbrlen = le16_to_cpu(txh->MModeFbrLen);
2959         u16 tfid = le16_to_cpu(txh->TxFrameID);
2960         u16 txs = le16_to_cpu(txh->TxStatus);
2961         u16 mnmpdu = le16_to_cpu(txh->MaxNMpdus);
2962         u16 mabyte = le16_to_cpu(txh->MaxABytes_MRT);
2963         u16 mabyte_f = le16_to_cpu(txh->MaxABytes_FBR);
2964         u16 mmbyte = le16_to_cpu(txh->MinMBytes);
2965
2966         u8 *rtsph = txh->RTSPhyHeader;
2967         struct ieee80211_rts rts = txh->rts_frame;
2968         char hexbuf[256];
2969
2970         /* add plcp header along with txh descriptor */
2971         printk(KERN_DEBUG "Raw TxDesc + plcp header:\n");
2972         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
2973                              txh, sizeof(d11txh_t) + 48);
2974
2975         printk(KERN_DEBUG "TxCtlLow: %04x ", mtcl);
2976         printk(KERN_DEBUG "TxCtlHigh: %04x ", mtch);
2977         printk(KERN_DEBUG "FC: %04x ", mfc);
2978         printk(KERN_DEBUG "FES Time: %04x\n", tfest);
2979         printk(KERN_DEBUG "PhyCtl: %04x%s ", ptcw,
2980                (ptcw & PHY_TXC_SHORT_HDR) ? " short" : "");
2981         printk(KERN_DEBUG "PhyCtl_1: %04x ", ptcw_1);
2982         printk(KERN_DEBUG "PhyCtl_1_Fbr: %04x\n", ptcw_1_Fbr);
2983         printk(KERN_DEBUG "PhyCtl_1_Rts: %04x ", ptcw_1_Rts);
2984         printk(KERN_DEBUG "PhyCtl_1_Fbr_Rts: %04x\n", ptcw_1_FbrRts);
2985         printk(KERN_DEBUG "MainRates: %04x ", mainrates);
2986         printk(KERN_DEBUG "XtraFrameTypes: %04x ", xtraft);
2987         printk(KERN_DEBUG "\n");
2988
2989         bcm_format_hex(hexbuf, iv, sizeof(txh->IV));
2990         printk(KERN_DEBUG "SecIV:       %s\n", hexbuf);
2991         bcm_format_hex(hexbuf, ra, sizeof(txh->TxFrameRA));
2992         printk(KERN_DEBUG "RA:          %s\n", hexbuf);
2993
2994         printk(KERN_DEBUG "Fb FES Time: %04x ", tfestfb);
2995         bcm_format_hex(hexbuf, rtspfb, sizeof(txh->RTSPLCPFallback));
2996         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
2997         printk(KERN_DEBUG "RTS DUR: %04x ", rtsdfb);
2998         bcm_format_hex(hexbuf, fragpfb, sizeof(txh->FragPLCPFallback));
2999         printk(KERN_DEBUG "PLCP: %s ", hexbuf);
3000         printk(KERN_DEBUG "DUR: %04x", fragdfb);
3001         printk(KERN_DEBUG "\n");
3002
3003         printk(KERN_DEBUG "MModeLen: %04x ", mmodelen);
3004         printk(KERN_DEBUG "MModeFbrLen: %04x\n", mmodefbrlen);
3005
3006         printk(KERN_DEBUG "FrameID:     %04x\n", tfid);
3007         printk(KERN_DEBUG "TxStatus:    %04x\n", txs);
3008
3009         printk(KERN_DEBUG "MaxNumMpdu:  %04x\n", mnmpdu);
3010         printk(KERN_DEBUG "MaxAggbyte:  %04x\n", mabyte);
3011         printk(KERN_DEBUG "MaxAggbyte_fb:  %04x\n", mabyte_f);
3012         printk(KERN_DEBUG "MinByte:     %04x\n", mmbyte);
3013
3014         bcm_format_hex(hexbuf, rtsph, sizeof(txh->RTSPhyHeader));
3015         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
3016         bcm_format_hex(hexbuf, (u8 *) &rts, sizeof(txh->rts_frame));
3017         printk(KERN_DEBUG "RTS Frame: %s", hexbuf);
3018         printk(KERN_DEBUG "\n");
3019 }
3020 #endif                          /* defined(BCMDBG) */
3021
3022 #if defined(BCMDBG)
3023 void wlc_print_rxh(d11rxhdr_t *rxh)
3024 {
3025         u16 len = rxh->RxFrameSize;
3026         u16 phystatus_0 = rxh->PhyRxStatus_0;
3027         u16 phystatus_1 = rxh->PhyRxStatus_1;
3028         u16 phystatus_2 = rxh->PhyRxStatus_2;
3029         u16 phystatus_3 = rxh->PhyRxStatus_3;
3030         u16 macstatus1 = rxh->RxStatus1;
3031         u16 macstatus2 = rxh->RxStatus2;
3032         char flagstr[64];
3033         char lenbuf[20];
3034         static const bcm_bit_desc_t macstat_flags[] = {
3035                 {RXS_FCSERR, "FCSErr"},
3036                 {RXS_RESPFRAMETX, "Reply"},
3037                 {RXS_PBPRES, "PADDING"},
3038                 {RXS_DECATMPT, "DeCr"},
3039                 {RXS_DECERR, "DeCrErr"},
3040                 {RXS_BCNSENT, "Bcn"},
3041                 {0, NULL}
3042         };
3043
3044         printk(KERN_DEBUG "Raw RxDesc:\n");
3045         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, rxh, sizeof(d11rxhdr_t));
3046
3047         bcm_format_flags(macstat_flags, macstatus1, flagstr, 64);
3048
3049         snprintf(lenbuf, sizeof(lenbuf), "0x%x", len);
3050
3051         printk(KERN_DEBUG "RxFrameSize:     %6s (%d)%s\n", lenbuf, len,
3052                (rxh->PhyRxStatus_0 & PRXS0_SHORTH) ? " short preamble" : "");
3053         printk(KERN_DEBUG "RxPHYStatus:     %04x %04x %04x %04x\n",
3054                phystatus_0, phystatus_1, phystatus_2, phystatus_3);
3055         printk(KERN_DEBUG "RxMACStatus:     %x %s\n", macstatus1, flagstr);
3056         printk(KERN_DEBUG "RXMACaggtype:    %x\n",
3057                (macstatus2 & RXS_AGGTYPE_MASK));
3058         printk(KERN_DEBUG "RxTSFTime:       %04x\n", rxh->RxTSFTime);
3059 }
3060 #endif                          /* defined(BCMDBG) */
3061
3062 static u16 wlc_rate_shm_offset(struct wlc_info *wlc, u8 rate)
3063 {
3064         return wlc_bmac_rate_shm_offset(wlc->hw, rate);
3065 }
3066
3067 /* Callback for device removed */
3068
3069 /*
3070  * Attempts to queue a packet onto a multiple-precedence queue,
3071  * if necessary evicting a lower precedence packet from the queue.
3072  *
3073  * 'prec' is the precedence number that has already been mapped
3074  * from the packet priority.
3075  *
3076  * Returns true if packet consumed (queued), false if not.
3077  */
3078 bool
3079 wlc_prec_enq(struct wlc_info *wlc, struct pktq *q, void *pkt, int prec)
3080 {
3081         return wlc_prec_enq_head(wlc, q, pkt, prec, false);
3082 }
3083
3084 bool
3085 wlc_prec_enq_head(struct wlc_info *wlc, struct pktq *q, struct sk_buff *pkt,
3086                   int prec, bool head)
3087 {
3088         struct sk_buff *p;
3089         int eprec = -1;         /* precedence to evict from */
3090
3091         /* Determine precedence from which to evict packet, if any */
3092         if (pktq_pfull(q, prec))
3093                 eprec = prec;
3094         else if (pktq_full(q)) {
3095                 p = bcm_pktq_peek_tail(q, &eprec);
3096                 if (eprec > prec) {
3097                         wiphy_err(wlc->wiphy, "%s: Failing: eprec %d > prec %d"
3098                                   "\n", __func__, eprec, prec);
3099                         return false;
3100                 }
3101         }
3102
3103         /* Evict if needed */
3104         if (eprec >= 0) {
3105                 bool discard_oldest;
3106
3107                 discard_oldest = AC_BITMAP_TST(wlc->wme_dp, eprec);
3108
3109                 /* Refuse newer packet unless configured to discard oldest */
3110                 if (eprec == prec && !discard_oldest) {
3111                         wiphy_err(wlc->wiphy, "%s: No where to go, prec == %d"
3112                                   "\n", __func__, prec);
3113                         return false;
3114                 }
3115
3116                 /* Evict packet according to discard policy */
3117                 p = discard_oldest ? bcm_pktq_pdeq(q, eprec) :
3118                         bcm_pktq_pdeq_tail(q, eprec);
3119                 bcm_pkt_buf_free_skb(p);
3120         }
3121
3122         /* Enqueue */
3123         if (head)
3124                 p = bcm_pktq_penq_head(q, prec, pkt);
3125         else
3126                 p = bcm_pktq_penq(q, prec, pkt);
3127
3128         return true;
3129 }
3130
3131 void wlc_txq_enq(void *ctx, struct scb *scb, struct sk_buff *sdu,
3132                              uint prec)
3133 {
3134         struct wlc_info *wlc = (struct wlc_info *) ctx;
3135         struct wlc_txq_info *qi = wlc->pkt_queue;       /* Check me */
3136         struct pktq *q = &qi->q;
3137         int prio;
3138
3139         prio = sdu->priority;
3140
3141         if (!wlc_prec_enq(wlc, q, sdu, prec)) {
3142                 if (!EDCF_ENAB(wlc->pub)
3143                     || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL))
3144                         wiphy_err(wlc->wiphy, "wl%d: wlc_txq_enq: txq overflow"
3145                                   "\n", wlc->pub->unit);
3146
3147                 /*
3148                  * XXX we might hit this condtion in case
3149                  * packet flooding from mac80211 stack
3150                  */
3151                 bcm_pkt_buf_free_skb(sdu);
3152         }
3153
3154         /* Check if flow control needs to be turned on after enqueuing the packet
3155          *   Don't turn on flow control if EDCF is enabled. Driver would make the decision on what
3156          *   to drop instead of relying on stack to make the right decision
3157          */
3158         if (!EDCF_ENAB(wlc->pub)
3159             || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL)) {
3160                 if (pktq_len(q) >= wlc->pub->tunables->datahiwat) {
3161                         wlc_txflowcontrol(wlc, qi, ON, ALLPRIO);
3162                 }
3163         } else if (wlc->pub->_priofc) {
3164                 if (pktq_plen(q, wlc_prio2prec_map[prio]) >=
3165                     wlc->pub->tunables->datahiwat) {
3166                         wlc_txflowcontrol(wlc, qi, ON, prio);
3167                 }
3168         }
3169 }
3170
3171 bool
3172 wlc_sendpkt_mac80211(struct wlc_info *wlc, struct sk_buff *sdu,
3173                      struct ieee80211_hw *hw)
3174 {
3175         u8 prio;
3176         uint fifo;
3177         void *pkt;
3178         struct scb *scb = &global_scb;
3179         struct ieee80211_hdr *d11_header = (struct ieee80211_hdr *)(sdu->data);
3180
3181         /* 802.11 standard requires management traffic to go at highest priority */
3182         prio = ieee80211_is_data(d11_header->frame_control) ? sdu->priority :
3183                 MAXPRIO;
3184         fifo = prio2fifo[prio];
3185         pkt = sdu;
3186         if (unlikely
3187             (wlc_d11hdrs_mac80211(wlc, hw, pkt, scb, 0, 1, fifo, 0, NULL, 0)))
3188                 return -EINVAL;
3189         wlc_txq_enq(wlc, scb, pkt, WLC_PRIO_TO_PREC(prio));
3190         wlc_send_q(wlc);
3191         return 0;
3192 }
3193
3194 void wlc_send_q(struct wlc_info *wlc)
3195 {
3196         struct sk_buff *pkt[DOT11_MAXNUMFRAGS];
3197         int prec;
3198         u16 prec_map;
3199         int err = 0, i, count;
3200         uint fifo;
3201         struct wlc_txq_info *qi = wlc->pkt_queue;
3202         struct pktq *q = &qi->q;
3203         struct ieee80211_tx_info *tx_info;
3204
3205         if (in_send_q)
3206                 return;
3207         else
3208                 in_send_q = true;
3209
3210         prec_map = wlc->tx_prec_map;
3211
3212         /* Send all the enq'd pkts that we can.
3213          * Dequeue packets with precedence with empty HW fifo only
3214          */
3215         while (prec_map && (pkt[0] = bcm_pktq_mdeq(q, prec_map, &prec))) {
3216                 tx_info = IEEE80211_SKB_CB(pkt[0]);
3217                 if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
3218                         err = wlc_sendampdu(wlc->ampdu, qi, pkt, prec);
3219                 } else {
3220                         count = 1;
3221                         err = wlc_prep_pdu(wlc, pkt[0], &fifo);
3222                         if (!err) {
3223                                 for (i = 0; i < count; i++) {
3224                                         wlc_txfifo(wlc, fifo, pkt[i], true, 1);
3225                                 }
3226                         }
3227                 }
3228
3229                 if (err == -EBUSY) {
3230                         bcm_pktq_penq_head(q, prec, pkt[0]);
3231                         /* If send failed due to any other reason than a change in
3232                          * HW FIFO condition, quit. Otherwise, read the new prec_map!
3233                          */
3234                         if (prec_map == wlc->tx_prec_map)
3235                                 break;
3236                         prec_map = wlc->tx_prec_map;
3237                 }
3238         }
3239
3240         /* Check if flow control needs to be turned off after sending the packet */
3241         if (!EDCF_ENAB(wlc->pub)
3242             || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL)) {
3243                 if (wlc_txflowcontrol_prio_isset(wlc, qi, ALLPRIO)
3244                     && (pktq_len(q) < wlc->pub->tunables->datahiwat / 2)) {
3245                         wlc_txflowcontrol(wlc, qi, OFF, ALLPRIO);
3246                 }
3247         } else if (wlc->pub->_priofc) {
3248                 int prio;
3249                 for (prio = MAXPRIO; prio >= 0; prio--) {
3250                         if (wlc_txflowcontrol_prio_isset(wlc, qi, prio) &&
3251                             (pktq_plen(q, wlc_prio2prec_map[prio]) <
3252                              wlc->pub->tunables->datahiwat / 2)) {
3253                                 wlc_txflowcontrol(wlc, qi, OFF, prio);
3254                         }
3255                 }
3256         }
3257         in_send_q = false;
3258 }
3259
3260 /*
3261  * bcmc_fid_generate:
3262  * Generate frame ID for a BCMC packet.  The frag field is not used
3263  * for MC frames so is used as part of the sequence number.
3264  */
3265 static inline u16
3266 bcmc_fid_generate(struct wlc_info *wlc, struct wlc_bsscfg *bsscfg,
3267                   d11txh_t *txh)
3268 {
3269         u16 frameid;
3270
3271         frameid = le16_to_cpu(txh->TxFrameID) & ~(TXFID_SEQ_MASK |
3272                                                   TXFID_QUEUE_MASK);
3273         frameid |=
3274             (((wlc->
3275                mc_fid_counter++) << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
3276             TX_BCMC_FIFO;
3277
3278         return frameid;
3279 }
3280
3281 void
3282 wlc_txfifo(struct wlc_info *wlc, uint fifo, struct sk_buff *p, bool commit,
3283            s8 txpktpend)
3284 {
3285         u16 frameid = INVALIDFID;
3286         d11txh_t *txh;
3287
3288         txh = (d11txh_t *) (p->data);
3289
3290         /* When a BC/MC frame is being committed to the BCMC fifo via DMA (NOT PIO), update
3291          * ucode or BSS info as appropriate.
3292          */
3293         if (fifo == TX_BCMC_FIFO) {
3294                 frameid = le16_to_cpu(txh->TxFrameID);
3295
3296         }
3297
3298         if (WLC_WAR16165(wlc))
3299                 wlc_war16165(wlc, true);
3300
3301
3302         /* Bump up pending count for if not using rpc. If rpc is used, this will be handled
3303          * in wlc_bmac_txfifo()
3304          */
3305         if (commit) {
3306                 TXPKTPENDINC(wlc, fifo, txpktpend);
3307                 BCMMSG(wlc->wiphy, "pktpend inc %d to %d\n",
3308                          txpktpend, TXPKTPENDGET(wlc, fifo));
3309         }
3310
3311         /* Commit BCMC sequence number in the SHM frame ID location */
3312         if (frameid != INVALIDFID)
3313                 BCMCFID(wlc, frameid);
3314
3315         if (dma_txfast(wlc->hw->di[fifo], p, commit) < 0) {
3316                 wiphy_err(wlc->wiphy, "wlc_txfifo: fatal, toss frames !!!\n");
3317         }
3318 }
3319
3320 void
3321 wlc_compute_plcp(struct wlc_info *wlc, ratespec_t rspec, uint length, u8 *plcp)
3322 {
3323         if (IS_MCS(rspec)) {
3324                 wlc_compute_mimo_plcp(rspec, length, plcp);
3325         } else if (IS_OFDM(rspec)) {
3326                 wlc_compute_ofdm_plcp(rspec, length, plcp);
3327         } else {
3328                 wlc_compute_cck_plcp(wlc, rspec, length, plcp);
3329         }
3330         return;
3331 }
3332
3333 /* Rate: 802.11 rate code, length: PSDU length in octets */
3334 static void wlc_compute_mimo_plcp(ratespec_t rspec, uint length, u8 *plcp)
3335 {
3336         u8 mcs = (u8) (rspec & RSPEC_RATE_MASK);
3337         plcp[0] = mcs;
3338         if (RSPEC_IS40MHZ(rspec) || (mcs == 32))
3339                 plcp[0] |= MIMO_PLCP_40MHZ;
3340         WLC_SET_MIMO_PLCP_LEN(plcp, length);
3341         plcp[3] = RSPEC_MIMOPLCP3(rspec);       /* rspec already holds this byte */
3342         plcp[3] |= 0x7;         /* set smoothing, not sounding ppdu & reserved */
3343         plcp[4] = 0;            /* number of extension spatial streams bit 0 & 1 */
3344         plcp[5] = 0;
3345 }
3346
3347 /* Rate: 802.11 rate code, length: PSDU length in octets */
3348 static void
3349 wlc_compute_ofdm_plcp(ratespec_t rspec, u32 length, u8 *plcp)
3350 {
3351         u8 rate_signal;
3352         u32 tmp = 0;
3353         int rate = RSPEC2RATE(rspec);
3354
3355         /* encode rate per 802.11a-1999 sec 17.3.4.1, with lsb transmitted first */
3356         rate_signal = rate_info[rate] & WLC_RATE_MASK;
3357         memset(plcp, 0, D11_PHY_HDR_LEN);
3358         D11A_PHY_HDR_SRATE((ofdm_phy_hdr_t *) plcp, rate_signal);
3359
3360         tmp = (length & 0xfff) << 5;
3361         plcp[2] |= (tmp >> 16) & 0xff;
3362         plcp[1] |= (tmp >> 8) & 0xff;
3363         plcp[0] |= tmp & 0xff;
3364
3365         return;
3366 }
3367
3368 /*
3369  * Compute PLCP, but only requires actual rate and length of pkt.
3370  * Rate is given in the driver standard multiple of 500 kbps.
3371  * le is set for 11 Mbps rate if necessary.
3372  * Broken out for PRQ.
3373  */
3374
3375 static void wlc_cck_plcp_set(struct wlc_info *wlc, int rate_500, uint length,
3376                              u8 *plcp)
3377 {
3378         u16 usec = 0;
3379         u8 le = 0;
3380
3381         switch (rate_500) {
3382         case WLC_RATE_1M:
3383                 usec = length << 3;
3384                 break;
3385         case WLC_RATE_2M:
3386                 usec = length << 2;
3387                 break;
3388         case WLC_RATE_5M5:
3389                 usec = (length << 4) / 11;
3390                 if ((length << 4) - (usec * 11) > 0)
3391                         usec++;
3392                 break;
3393         case WLC_RATE_11M:
3394                 usec = (length << 3) / 11;
3395                 if ((length << 3) - (usec * 11) > 0) {
3396                         usec++;
3397                         if ((usec * 11) - (length << 3) >= 8)
3398                                 le = D11B_PLCP_SIGNAL_LE;
3399                 }
3400                 break;
3401
3402         default:
3403                 wiphy_err(wlc->wiphy, "wlc_cck_plcp_set: unsupported rate %d"
3404                           "\n", rate_500);
3405                 rate_500 = WLC_RATE_1M;
3406                 usec = length << 3;
3407                 break;
3408         }
3409         /* PLCP signal byte */
3410         plcp[0] = rate_500 * 5; /* r (500kbps) * 5 == r (100kbps) */
3411         /* PLCP service byte */
3412         plcp[1] = (u8) (le | D11B_PLCP_SIGNAL_LOCKED);
3413         /* PLCP length u16, little endian */
3414         plcp[2] = usec & 0xff;
3415         plcp[3] = (usec >> 8) & 0xff;
3416         /* PLCP CRC16 */
3417         plcp[4] = 0;
3418         plcp[5] = 0;
3419 }
3420
3421 /* Rate: 802.11 rate code, length: PSDU length in octets */
3422 static void wlc_compute_cck_plcp(struct wlc_info *wlc, ratespec_t rspec,
3423                                  uint length, u8 *plcp)
3424 {
3425         int rate = RSPEC2RATE(rspec);
3426
3427         wlc_cck_plcp_set(wlc, rate, length, plcp);
3428 }
3429
3430 /* wlc_compute_frame_dur()
3431  *
3432  * Calculate the 802.11 MAC header DUR field for MPDU
3433  * DUR for a single frame = 1 SIFS + 1 ACK
3434  * DUR for a frame with following frags = 3 SIFS + 2 ACK + next frag time
3435  *
3436  * rate                 MPDU rate in unit of 500kbps
3437  * next_frag_len        next MPDU length in bytes
3438  * preamble_type        use short/GF or long/MM PLCP header
3439  */
3440 static u16
3441 wlc_compute_frame_dur(struct wlc_info *wlc, ratespec_t rate, u8 preamble_type,
3442                       uint next_frag_len)
3443 {
3444         u16 dur, sifs;
3445
3446         sifs = SIFS(wlc->band);
3447
3448         dur = sifs;
3449         dur += (u16) wlc_calc_ack_time(wlc, rate, preamble_type);
3450
3451         if (next_frag_len) {
3452                 /* Double the current DUR to get 2 SIFS + 2 ACKs */
3453                 dur *= 2;
3454                 /* add another SIFS and the frag time */
3455                 dur += sifs;
3456                 dur +=
3457                     (u16) wlc_calc_frame_time(wlc, rate, preamble_type,
3458                                                  next_frag_len);
3459         }
3460         return dur;
3461 }
3462
3463 /* wlc_compute_rtscts_dur()
3464  *
3465  * Calculate the 802.11 MAC header DUR field for an RTS or CTS frame
3466  * DUR for normal RTS/CTS w/ frame = 3 SIFS + 1 CTS + next frame time + 1 ACK
3467  * DUR for CTS-TO-SELF w/ frame    = 2 SIFS         + next frame time + 1 ACK
3468  *
3469  * cts                  cts-to-self or rts/cts
3470  * rts_rate             rts or cts rate in unit of 500kbps
3471  * rate                 next MPDU rate in unit of 500kbps
3472  * frame_len            next MPDU frame length in bytes
3473  */
3474 u16
3475 wlc_compute_rtscts_dur(struct wlc_info *wlc, bool cts_only, ratespec_t rts_rate,
3476                        ratespec_t frame_rate, u8 rts_preamble_type,
3477                        u8 frame_preamble_type, uint frame_len, bool ba)
3478 {
3479         u16 dur, sifs;
3480
3481         sifs = SIFS(wlc->band);
3482
3483         if (!cts_only) {        /* RTS/CTS */
3484                 dur = 3 * sifs;
3485                 dur +=
3486                     (u16) wlc_calc_cts_time(wlc, rts_rate,
3487                                                rts_preamble_type);
3488         } else {                /* CTS-TO-SELF */
3489                 dur = 2 * sifs;
3490         }
3491
3492         dur +=
3493             (u16) wlc_calc_frame_time(wlc, frame_rate, frame_preamble_type,
3494                                          frame_len);
3495         if (ba)
3496                 dur +=
3497                     (u16) wlc_calc_ba_time(wlc, frame_rate,
3498                                               WLC_SHORT_PREAMBLE);
3499         else
3500                 dur +=
3501                     (u16) wlc_calc_ack_time(wlc, frame_rate,
3502                                                frame_preamble_type);
3503         return dur;
3504 }
3505
3506 u16 wlc_phytxctl1_calc(struct wlc_info *wlc, ratespec_t rspec)
3507 {
3508         u16 phyctl1 = 0;
3509         u16 bw;
3510
3511         if (WLCISLCNPHY(wlc->band)) {
3512                 bw = PHY_TXC1_BW_20MHZ;
3513         } else {
3514                 bw = RSPEC_GET_BW(rspec);
3515                 /* 10Mhz is not supported yet */
3516                 if (bw < PHY_TXC1_BW_20MHZ) {
3517                         wiphy_err(wlc->wiphy, "wlc_phytxctl1_calc: bw %d is "
3518                                   "not supported yet, set to 20L\n", bw);
3519                         bw = PHY_TXC1_BW_20MHZ;
3520                 }
3521         }
3522
3523         if (IS_MCS(rspec)) {
3524                 uint mcs = rspec & RSPEC_RATE_MASK;
3525
3526                 /* bw, stf, coding-type is part of RSPEC_PHYTXBYTE2 returns */
3527                 phyctl1 = RSPEC_PHYTXBYTE2(rspec);
3528                 /* set the upper byte of phyctl1 */
3529                 phyctl1 |= (mcs_table[mcs].tx_phy_ctl3 << 8);
3530         } else if (IS_CCK(rspec) && !WLCISLCNPHY(wlc->band)
3531                    && !WLCISSSLPNPHY(wlc->band)) {
3532                 /* In CCK mode LPPHY overloads OFDM Modulation bits with CCK Data Rate */
3533                 /* Eventually MIMOPHY would also be converted to this format */
3534                 /* 0 = 1Mbps; 1 = 2Mbps; 2 = 5.5Mbps; 3 = 11Mbps */
3535                 phyctl1 = (bw | (RSPEC_STF(rspec) << PHY_TXC1_MODE_SHIFT));
3536         } else {                /* legacy OFDM/CCK */
3537                 s16 phycfg;
3538                 /* get the phyctl byte from rate phycfg table */
3539                 phycfg = wlc_rate_legacy_phyctl(RSPEC2RATE(rspec));
3540                 if (phycfg == -1) {
3541                         wiphy_err(wlc->wiphy, "wlc_phytxctl1_calc: wrong "
3542                                   "legacy OFDM/CCK rate\n");
3543                         phycfg = 0;
3544                 }
3545                 /* set the upper byte of phyctl1 */
3546                 phyctl1 =
3547                     (bw | (phycfg << 8) |
3548                      (RSPEC_STF(rspec) << PHY_TXC1_MODE_SHIFT));
3549         }
3550         return phyctl1;
3551 }
3552
3553 ratespec_t
3554 wlc_rspec_to_rts_rspec(struct wlc_info *wlc, ratespec_t rspec, bool use_rspec,
3555                        u16 mimo_ctlchbw)
3556 {
3557         ratespec_t rts_rspec = 0;
3558
3559         if (use_rspec) {
3560                 /* use frame rate as rts rate */
3561                 rts_rspec = rspec;
3562
3563         } else if (wlc->band->gmode && wlc->protection->_g && !IS_CCK(rspec)) {
3564                 /* Use 11Mbps as the g protection RTS target rate and fallback.
3565                  * Use the WLC_BASIC_RATE() lookup to find the best basic rate under the
3566                  * target in case 11 Mbps is not Basic.
3567                  * 6 and 9 Mbps are not usually selected by rate selection, but even
3568                  * if the OFDM rate we are protecting is 6 or 9 Mbps, 11 is more robust.
3569                  */
3570                 rts_rspec = WLC_BASIC_RATE(wlc, WLC_RATE_11M);
3571         } else {
3572                 /* calculate RTS rate and fallback rate based on the frame rate
3573                  * RTS must be sent at a basic rate since it is a
3574                  * control frame, sec 9.6 of 802.11 spec
3575                  */
3576                 rts_rspec = WLC_BASIC_RATE(wlc, rspec);
3577         }
3578
3579         if (WLC_PHY_11N_CAP(wlc->band)) {
3580                 /* set rts txbw to correct side band */
3581                 rts_rspec &= ~RSPEC_BW_MASK;
3582
3583                 /* if rspec/rspec_fallback is 40MHz, then send RTS on both 20MHz channel
3584                  * (DUP), otherwise send RTS on control channel
3585                  */
3586                 if (RSPEC_IS40MHZ(rspec) && !IS_CCK(rts_rspec))
3587                         rts_rspec |= (PHY_TXC1_BW_40MHZ_DUP << RSPEC_BW_SHIFT);
3588                 else
3589                         rts_rspec |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
3590
3591                 /* pick siso/cdd as default for ofdm */
3592                 if (IS_OFDM(rts_rspec)) {
3593                         rts_rspec &= ~RSPEC_STF_MASK;
3594                         rts_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
3595                 }
3596         }
3597         return rts_rspec;
3598 }
3599
3600 /*
3601  * Add d11txh_t, cck_phy_hdr_t.
3602  *
3603  * 'p' data must start with 802.11 MAC header
3604  * 'p' must allow enough bytes of local headers to be "pushed" onto the packet
3605  *
3606  * headroom == D11_PHY_HDR_LEN + D11_TXH_LEN (D11_TXH_LEN is now 104 bytes)
3607  *
3608  */
3609 static u16
3610 wlc_d11hdrs_mac80211(struct wlc_info *wlc, struct ieee80211_hw *hw,
3611                      struct sk_buff *p, struct scb *scb, uint frag,
3612                      uint nfrags, uint queue, uint next_frag_len,
3613                      wsec_key_t *key, ratespec_t rspec_override)
3614 {
3615         struct ieee80211_hdr *h;
3616         d11txh_t *txh;
3617         u8 *plcp, plcp_fallback[D11_PHY_HDR_LEN];
3618         int len, phylen, rts_phylen;
3619         u16 mch, phyctl, xfts, mainrates;
3620         u16 seq = 0, mcl = 0, status = 0, frameid = 0;
3621         ratespec_t rspec[2] = { WLC_RATE_1M, WLC_RATE_1M }, rts_rspec[2] = {
3622         WLC_RATE_1M, WLC_RATE_1M};
3623         bool use_rts = false;
3624         bool use_cts = false;
3625         bool use_rifs = false;
3626         bool short_preamble[2] = { false, false };
3627         u8 preamble_type[2] = { WLC_LONG_PREAMBLE, WLC_LONG_PREAMBLE };
3628         u8 rts_preamble_type[2] = { WLC_LONG_PREAMBLE, WLC_LONG_PREAMBLE };
3629         u8 *rts_plcp, rts_plcp_fallback[D11_PHY_HDR_LEN];
3630         struct ieee80211_rts *rts = NULL;
3631         bool qos;
3632         uint ac;
3633         u32 rate_val[2];
3634         bool hwtkmic = false;
3635         u16 mimo_ctlchbw = PHY_TXC1_BW_20MHZ;
3636 #define ANTCFG_NONE 0xFF
3637         u8 antcfg = ANTCFG_NONE;
3638         u8 fbantcfg = ANTCFG_NONE;
3639         uint phyctl1_stf = 0;
3640         u16 durid = 0;
3641         struct ieee80211_tx_rate *txrate[2];
3642         int k;
3643         struct ieee80211_tx_info *tx_info;
3644         bool is_mcs[2];
3645         u16 mimo_txbw;
3646         u8 mimo_preamble_type;
3647
3648         /* locate 802.11 MAC header */
3649         h = (struct ieee80211_hdr *)(p->data);
3650         qos = ieee80211_is_data_qos(h->frame_control);
3651
3652         /* compute length of frame in bytes for use in PLCP computations */
3653         len = bcm_pkttotlen(p);
3654         phylen = len + FCS_LEN;
3655
3656         /* If WEP enabled, add room in phylen for the additional bytes of
3657          * ICV which MAC generates.  We do NOT add the additional bytes to
3658          * the packet itself, thus phylen = packet length + ICV_LEN + FCS_LEN
3659          * in this case
3660          */
3661         if (key) {
3662                 phylen += key->icv_len;
3663         }
3664
3665         /* Get tx_info */
3666         tx_info = IEEE80211_SKB_CB(p);
3667
3668         /* add PLCP */
3669         plcp = skb_push(p, D11_PHY_HDR_LEN);
3670
3671         /* add Broadcom tx descriptor header */
3672         txh = (d11txh_t *) skb_push(p, D11_TXH_LEN);
3673         memset(txh, 0, D11_TXH_LEN);
3674
3675         /* setup frameid */
3676         if (tx_info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
3677                 /* non-AP STA should never use BCMC queue */
3678                 if (queue == TX_BCMC_FIFO) {
3679                         wiphy_err(wlc->wiphy, "wl%d: %s: ASSERT queue == "
3680                                   "TX_BCMC!\n", WLCWLUNIT(wlc), __func__);
3681                         frameid = bcmc_fid_generate(wlc, NULL, txh);
3682                 } else {
3683                         /* Increment the counter for first fragment */
3684                         if (tx_info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT) {
3685                                 SCB_SEQNUM(scb, p->priority)++;
3686                         }
3687
3688                         /* extract fragment number from frame first */
3689                         seq = le16_to_cpu(seq) & FRAGNUM_MASK;
3690                         seq |= (SCB_SEQNUM(scb, p->priority) << SEQNUM_SHIFT);
3691                         h->seq_ctrl = cpu_to_le16(seq);
3692
3693                         frameid = ((seq << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
3694                             (queue & TXFID_QUEUE_MASK);
3695                 }
3696         }
3697         frameid |= queue & TXFID_QUEUE_MASK;
3698
3699         /* set the ignpmq bit for all pkts tx'd in PS mode and for beacons */
3700         if (SCB_PS(scb) || ieee80211_is_beacon(h->frame_control))
3701                 mcl |= TXC_IGNOREPMQ;
3702
3703         txrate[0] = tx_info->control.rates;
3704         txrate[1] = txrate[0] + 1;
3705
3706         /* if rate control algorithm didn't give us a fallback rate, use the primary rate */
3707         if (txrate[1]->idx < 0) {
3708                 txrate[1] = txrate[0];
3709         }
3710
3711         for (k = 0; k < hw->max_rates; k++) {
3712                 is_mcs[k] =
3713                     txrate[k]->flags & IEEE80211_TX_RC_MCS ? true : false;
3714                 if (!is_mcs[k]) {
3715                         if ((txrate[k]->idx >= 0)
3716                             && (txrate[k]->idx <
3717                                 hw->wiphy->bands[tx_info->band]->n_bitrates)) {
3718                                 rate_val[k] =
3719                                     hw->wiphy->bands[tx_info->band]->
3720                                     bitrates[txrate[k]->idx].hw_value;
3721                                 short_preamble[k] =
3722                                     txrate[k]->
3723                                     flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE ?
3724                                     true : false;
3725                         } else {
3726                                 rate_val[k] = WLC_RATE_1M;
3727                         }
3728                 } else {
3729                         rate_val[k] = txrate[k]->idx;
3730                 }
3731                 /* Currently only support same setting for primay and fallback rates.
3732                  * Unify flags for each rate into a single value for the frame
3733                  */
3734                 use_rts |=
3735                     txrate[k]->
3736                     flags & IEEE80211_TX_RC_USE_RTS_CTS ? true : false;
3737                 use_cts |=
3738                     txrate[k]->
3739                     flags & IEEE80211_TX_RC_USE_CTS_PROTECT ? true : false;
3740
3741                 if (is_mcs[k])
3742                         rate_val[k] |= NRATE_MCS_INUSE;
3743
3744                 rspec[k] = mac80211_wlc_set_nrate(wlc, wlc->band, rate_val[k]);
3745
3746                 /* (1) RATE: determine and validate primary rate and fallback rates */
3747                 if (!RSPEC_ACTIVE(rspec[k])) {
3748                         rspec[k] = WLC_RATE_1M;
3749                 } else {
3750                         if (!is_multicast_ether_addr(h->addr1)) {
3751                                 /* set tx antenna config */
3752                                 wlc_antsel_antcfg_get(wlc->asi, false, false, 0,
3753                                                       0, &antcfg, &fbantcfg);
3754                         }
3755                 }
3756         }
3757
3758         phyctl1_stf = wlc->stf->ss_opmode;
3759
3760         if (N_ENAB(wlc->pub)) {
3761                 for (k = 0; k < hw->max_rates; k++) {
3762                         /* apply siso/cdd to single stream mcs's or ofdm if rspec is auto selected */
3763                         if (((IS_MCS(rspec[k]) &&
3764                               IS_SINGLE_STREAM(rspec[k] & RSPEC_RATE_MASK)) ||
3765                              IS_OFDM(rspec[k]))
3766                             && ((rspec[k] & RSPEC_OVERRIDE_MCS_ONLY)
3767                                 || !(rspec[k] & RSPEC_OVERRIDE))) {
3768                                 rspec[k] &= ~(RSPEC_STF_MASK | RSPEC_STC_MASK);
3769
3770                                 /* For SISO MCS use STBC if possible */
3771                                 if (IS_MCS(rspec[k])
3772                                     && WLC_STF_SS_STBC_TX(wlc, scb)) {
3773                                         u8 stc;
3774
3775                                         stc = 1;        /* Nss for single stream is always 1 */
3776                                         rspec[k] |=
3777                                             (PHY_TXC1_MODE_STBC <<
3778                                              RSPEC_STF_SHIFT) | (stc <<
3779                                                                  RSPEC_STC_SHIFT);
3780                                 } else
3781                                         rspec[k] |=
3782                                             (phyctl1_stf << RSPEC_STF_SHIFT);
3783                         }
3784
3785                         /* Is the phy configured to use 40MHZ frames? If so then pick the desired txbw */
3786                         if (CHSPEC_WLC_BW(wlc->chanspec) == WLC_40_MHZ) {
3787                                 /* default txbw is 20in40 SB */
3788                                 mimo_ctlchbw = mimo_txbw =
3789                                     CHSPEC_SB_UPPER(WLC_BAND_PI_RADIO_CHANSPEC)
3790                                     ? PHY_TXC1_BW_20MHZ_UP : PHY_TXC1_BW_20MHZ;
3791
3792                                 if (IS_MCS(rspec[k])) {
3793                                         /* mcs 32 must be 40b/w DUP */
3794                                         if ((rspec[k] & RSPEC_RATE_MASK) == 32) {
3795                                                 mimo_txbw =
3796                                                     PHY_TXC1_BW_40MHZ_DUP;
3797                                                 /* use override */
3798                                         } else if (wlc->mimo_40txbw != AUTO)
3799                                                 mimo_txbw = wlc->mimo_40txbw;
3800                                         /* else check if dst is using 40 Mhz */
3801                                         else if (scb->flags & SCB_IS40)
3802                                                 mimo_txbw = PHY_TXC1_BW_40MHZ;
3803                                 } else if (IS_OFDM(rspec[k])) {
3804                                         if (wlc->ofdm_40txbw != AUTO)
3805                                                 mimo_txbw = wlc->ofdm_40txbw;
3806                                 } else {
3807                                         if (wlc->cck_40txbw != AUTO)
3808                                                 mimo_txbw = wlc->cck_40txbw;
3809                                 }
3810                         } else {
3811                                 /* mcs32 is 40 b/w only.
3812                                  * This is possible for probe packets on a STA during SCAN
3813                                  */
3814                                 if ((rspec[k] & RSPEC_RATE_MASK) == 32) {
3815                                         /* mcs 0 */
3816                                         rspec[k] = RSPEC_MIMORATE;
3817                                 }
3818                                 mimo_txbw = PHY_TXC1_BW_20MHZ;
3819                         }
3820
3821                         /* Set channel width */
3822                         rspec[k] &= ~RSPEC_BW_MASK;
3823                         if ((k == 0) || ((k > 0) && IS_MCS(rspec[k])))
3824                                 rspec[k] |= (mimo_txbw << RSPEC_BW_SHIFT);
3825                         else
3826                                 rspec[k] |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
3827
3828                         /* Set Short GI */
3829 #ifdef NOSGIYET
3830                         if (IS_MCS(rspec[k])
3831                             && (txrate[k]->flags & IEEE80211_TX_RC_SHORT_GI))
3832                                 rspec[k] |= RSPEC_SHORT_GI;
3833                         else if (!(txrate[k]->flags & IEEE80211_TX_RC_SHORT_GI))
3834                                 rspec[k] &= ~RSPEC_SHORT_GI;
3835 #else
3836                         rspec[k] &= ~RSPEC_SHORT_GI;
3837 #endif
3838
3839                         mimo_preamble_type = WLC_MM_PREAMBLE;
3840                         if (txrate[k]->flags & IEEE80211_TX_RC_GREEN_FIELD)
3841                                 mimo_preamble_type = WLC_GF_PREAMBLE;
3842
3843                         if ((txrate[k]->flags & IEEE80211_TX_RC_MCS)
3844                             && (!IS_MCS(rspec[k]))) {
3845                                 wiphy_err(wlc->wiphy, "wl%d: %s: IEEE80211_TX_"
3846                                           "RC_MCS != IS_MCS(rspec)\n",
3847                                           WLCWLUNIT(wlc), __func__);
3848                         }
3849
3850                         if (IS_MCS(rspec[k])) {
3851                                 preamble_type[k] = mimo_preamble_type;
3852
3853                                 /* if SGI is selected, then forced mm for single stream */
3854                                 if ((rspec[k] & RSPEC_SHORT_GI)
3855                                     && IS_SINGLE_STREAM(rspec[k] &
3856                                                         RSPEC_RATE_MASK)) {
3857                                         preamble_type[k] = WLC_MM_PREAMBLE;
3858                                 }
3859                         }
3860
3861                         /* should be better conditionalized */
3862                         if (!IS_MCS(rspec[0])
3863                             && (tx_info->control.rates[0].
3864                                 flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE))
3865                                 preamble_type[k] = WLC_SHORT_PREAMBLE;
3866                 }
3867         } else {
3868                 for (k = 0; k < hw->max_rates; k++) {
3869                         /* Set ctrlchbw as 20Mhz */
3870                         rspec[k] &= ~RSPEC_BW_MASK;
3871                         rspec[k] |= (PHY_TXC1_BW_20MHZ << RSPEC_BW_SHIFT);
3872
3873                         /* for nphy, stf of ofdm frames must follow policies */
3874                         if (WLCISNPHY(wlc->band) && IS_OFDM(rspec[k])) {
3875                                 rspec[k] &= ~RSPEC_STF_MASK;
3876                                 rspec[k] |= phyctl1_stf << RSPEC_STF_SHIFT;
3877                         }
3878                 }
3879         }
3880
3881         /* Reset these for use with AMPDU's */
3882         txrate[0]->count = 0;
3883         txrate[1]->count = 0;
3884
3885         /* (2) PROTECTION, may change rspec */
3886         if ((ieee80211_is_data(h->frame_control) ||
3887             ieee80211_is_mgmt(h->frame_control)) &&
3888             (phylen > wlc->RTSThresh) && !is_multicast_ether_addr(h->addr1))
3889                 use_rts = true;
3890
3891         /* (3) PLCP: determine PLCP header and MAC duration, fill d11txh_t */
3892         wlc_compute_plcp(wlc, rspec[0], phylen, plcp);
3893         wlc_compute_plcp(wlc, rspec[1], phylen, plcp_fallback);
3894         memcpy(&txh->FragPLCPFallback,
3895                plcp_fallback, sizeof(txh->FragPLCPFallback));
3896
3897         /* Length field now put in CCK FBR CRC field */
3898         if (IS_CCK(rspec[1])) {
3899                 txh->FragPLCPFallback[4] = phylen & 0xff;
3900                 txh->FragPLCPFallback[5] = (phylen & 0xff00) >> 8;
3901         }
3902
3903         /* MIMO-RATE: need validation ?? */
3904         mainrates =
3905             IS_OFDM(rspec[0]) ? D11A_PHY_HDR_GRATE((ofdm_phy_hdr_t *) plcp) :
3906             plcp[0];
3907
3908         /* DUR field for main rate */
3909         if (!ieee80211_is_pspoll(h->frame_control) &&
3910             !is_multicast_ether_addr(h->addr1) && !use_rifs) {
3911                 durid =
3912                     wlc_compute_frame_dur(wlc, rspec[0], preamble_type[0],
3913                                           next_frag_len);
3914                 h->duration_id = cpu_to_le16(durid);
3915         } else if (use_rifs) {
3916                 /* NAV protect to end of next max packet size */
3917                 durid =
3918                     (u16) wlc_calc_frame_time(wlc, rspec[0],
3919                                                  preamble_type[0],
3920                                                  DOT11_MAX_FRAG_LEN);
3921                 durid += RIFS_11N_TIME;
3922                 h->duration_id = cpu_to_le16(durid);
3923         }
3924
3925         /* DUR field for fallback rate */
3926         if (ieee80211_is_pspoll(h->frame_control))
3927                 txh->FragDurFallback = h->duration_id;
3928         else if (is_multicast_ether_addr(h->addr1) || use_rifs)
3929                 txh->FragDurFallback = 0;
3930         else {
3931                 durid = wlc_compute_frame_dur(wlc, rspec[1],
3932                                               preamble_type[1], next_frag_len);
3933                 txh->FragDurFallback = cpu_to_le16(durid);
3934         }
3935
3936         /* (4) MAC-HDR: MacTxControlLow */
3937         if (frag == 0)
3938                 mcl |= TXC_STARTMSDU;
3939
3940         if (!is_multicast_ether_addr(h->addr1))
3941                 mcl |= TXC_IMMEDACK;
3942
3943         if (BAND_5G(wlc->band->bandtype))
3944                 mcl |= TXC_FREQBAND_5G;
3945
3946         if (CHSPEC_IS40(WLC_BAND_PI_RADIO_CHANSPEC))
3947                 mcl |= TXC_BW_40;
3948
3949         /* set AMIC bit if using hardware TKIP MIC */
3950         if (hwtkmic)
3951                 mcl |= TXC_AMIC;
3952
3953         txh->MacTxControlLow = cpu_to_le16(mcl);
3954
3955         /* MacTxControlHigh */
3956         mch = 0;
3957
3958         /* Set fallback rate preamble type */
3959         if ((preamble_type[1] == WLC_SHORT_PREAMBLE) ||
3960             (preamble_type[1] == WLC_GF_PREAMBLE)) {
3961                 if (RSPEC2RATE(rspec[1]) != WLC_RATE_1M)
3962                         mch |= TXC_PREAMBLE_DATA_FB_SHORT;
3963         }
3964
3965         /* MacFrameControl */
3966         memcpy(&txh->MacFrameControl, &h->frame_control, sizeof(u16));
3967         txh->TxFesTimeNormal = cpu_to_le16(0);
3968
3969         txh->TxFesTimeFallback = cpu_to_le16(0);
3970
3971         /* TxFrameRA */
3972         memcpy(&txh->TxFrameRA, &h->addr1, ETH_ALEN);
3973
3974         /* TxFrameID */
3975         txh->TxFrameID = cpu_to_le16(frameid);
3976
3977         /* TxStatus, Note the case of recreating the first frag of a suppressed frame
3978          * then we may need to reset the retry cnt's via the status reg
3979          */
3980         txh->TxStatus = cpu_to_le16(status);
3981
3982         /* extra fields for ucode AMPDU aggregation, the new fields are added to
3983          * the END of previous structure so that it's compatible in driver.
3984          */
3985         txh->MaxNMpdus = cpu_to_le16(0);
3986         txh->MaxABytes_MRT = cpu_to_le16(0);
3987         txh->MaxABytes_FBR = cpu_to_le16(0);
3988         txh->MinMBytes = cpu_to_le16(0);
3989
3990         /* (5) RTS/CTS: determine RTS/CTS PLCP header and MAC duration, furnish d11txh_t */
3991         /* RTS PLCP header and RTS frame */
3992         if (use_rts || use_cts) {
3993                 if (use_rts && use_cts)
3994                         use_cts = false;
3995
3996                 for (k = 0; k < 2; k++) {
3997                         rts_rspec[k] = wlc_rspec_to_rts_rspec(wlc, rspec[k],
3998                                                               false,
3999                                                               mimo_ctlchbw);
4000                 }
4001
4002                 if (!IS_OFDM(rts_rspec[0]) &&
4003                     !((RSPEC2RATE(rts_rspec[0]) == WLC_RATE_1M) ||
4004                       (wlc->PLCPHdr_override == WLC_PLCP_LONG))) {
4005                         rts_preamble_type[0] = WLC_SHORT_PREAMBLE;
4006                         mch |= TXC_PREAMBLE_RTS_MAIN_SHORT;
4007                 }
4008
4009                 if (!IS_OFDM(rts_rspec[1]) &&
4010                     !((RSPEC2RATE(rts_rspec[1]) == WLC_RATE_1M) ||
4011                       (wlc->PLCPHdr_override == WLC_PLCP_LONG))) {
4012                         rts_preamble_type[1] = WLC_SHORT_PREAMBLE;
4013                         mch |= TXC_PREAMBLE_RTS_FB_SHORT;
4014                 }
4015
4016                 /* RTS/CTS additions to MacTxControlLow */
4017                 if (use_cts) {
4018                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDCTS);
4019                 } else {
4020                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDRTS);
4021                         txh->MacTxControlLow |= cpu_to_le16(TXC_LONGFRAME);
4022                 }
4023
4024                 /* RTS PLCP header */
4025                 rts_plcp = txh->RTSPhyHeader;
4026                 if (use_cts)
4027                         rts_phylen = DOT11_CTS_LEN + FCS_LEN;
4028                 else
4029                         rts_phylen = DOT11_RTS_LEN + FCS_LEN;
4030
4031                 wlc_compute_plcp(wlc, rts_rspec[0], rts_phylen, rts_plcp);
4032
4033                 /* fallback rate version of RTS PLCP header */
4034                 wlc_compute_plcp(wlc, rts_rspec[1], rts_phylen,
4035                                  rts_plcp_fallback);
4036                 memcpy(&txh->RTSPLCPFallback, rts_plcp_fallback,
4037                        sizeof(txh->RTSPLCPFallback));
4038
4039                 /* RTS frame fields... */
4040                 rts = (struct ieee80211_rts *)&txh->rts_frame;
4041
4042                 durid = wlc_compute_rtscts_dur(wlc, use_cts, rts_rspec[0],
4043                                                rspec[0], rts_preamble_type[0],
4044                                                preamble_type[0], phylen, false);
4045                 rts->duration = cpu_to_le16(durid);
4046                 /* fallback rate version of RTS DUR field */
4047                 durid = wlc_compute_rtscts_dur(wlc, use_cts,
4048                                                rts_rspec[1], rspec[1],
4049                                                rts_preamble_type[1],
4050                                                preamble_type[1], phylen, false);
4051                 txh->RTSDurFallback = cpu_to_le16(durid);
4052
4053                 if (use_cts) {
4054                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
4055                                                          IEEE80211_STYPE_CTS);
4056
4057                         memcpy(&rts->ra, &h->addr2, ETH_ALEN);
4058                 } else {
4059                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
4060                                                          IEEE80211_STYPE_RTS);
4061
4062                         memcpy(&rts->ra, &h->addr1, 2 * ETH_ALEN);
4063                 }
4064
4065                 /* mainrate
4066                  *    low 8 bits: main frag rate/mcs,
4067                  *    high 8 bits: rts/cts rate/mcs
4068                  */
4069                 mainrates |= (IS_OFDM(rts_rspec[0]) ?
4070                               D11A_PHY_HDR_GRATE((ofdm_phy_hdr_t *) rts_plcp) :
4071                               rts_plcp[0]) << 8;
4072         } else {
4073                 memset((char *)txh->RTSPhyHeader, 0, D11_PHY_HDR_LEN);
4074                 memset((char *)&txh->rts_frame, 0,
4075                         sizeof(struct ieee80211_rts));
4076                 memset((char *)txh->RTSPLCPFallback, 0,
4077                       sizeof(txh->RTSPLCPFallback));
4078                 txh->RTSDurFallback = 0;
4079         }
4080
4081 #ifdef SUPPORT_40MHZ
4082         /* add null delimiter count */
4083         if ((tx_info->flags & IEEE80211_TX_CTL_AMPDU) && IS_MCS(rspec)) {
4084                 txh->RTSPLCPFallback[AMPDU_FBR_NULL_DELIM] =
4085                     wlc_ampdu_null_delim_cnt(wlc->ampdu, scb, rspec, phylen);
4086         }
4087 #endif
4088
4089         /* Now that RTS/RTS FB preamble types are updated, write the final value */
4090         txh->MacTxControlHigh = cpu_to_le16(mch);
4091
4092         /* MainRates (both the rts and frag plcp rates have been calculated now) */
4093         txh->MainRates = cpu_to_le16(mainrates);
4094
4095         /* XtraFrameTypes */
4096         xfts = FRAMETYPE(rspec[1], wlc->mimoft);
4097         xfts |= (FRAMETYPE(rts_rspec[0], wlc->mimoft) << XFTS_RTS_FT_SHIFT);
4098         xfts |= (FRAMETYPE(rts_rspec[1], wlc->mimoft) << XFTS_FBRRTS_FT_SHIFT);
4099         xfts |=
4100             CHSPEC_CHANNEL(WLC_BAND_PI_RADIO_CHANSPEC) << XFTS_CHANNEL_SHIFT;
4101         txh->XtraFrameTypes = cpu_to_le16(xfts);
4102
4103         /* PhyTxControlWord */
4104         phyctl = FRAMETYPE(rspec[0], wlc->mimoft);
4105         if ((preamble_type[0] == WLC_SHORT_PREAMBLE) ||
4106             (preamble_type[0] == WLC_GF_PREAMBLE)) {
4107                 if (RSPEC2RATE(rspec[0]) != WLC_RATE_1M)
4108                         phyctl |= PHY_TXC_SHORT_HDR;
4109         }
4110
4111         /* phytxant is properly bit shifted */
4112         phyctl |= wlc_stf_d11hdrs_phyctl_txant(wlc, rspec[0]);
4113         txh->PhyTxControlWord = cpu_to_le16(phyctl);
4114
4115         /* PhyTxControlWord_1 */
4116         if (WLC_PHY_11N_CAP(wlc->band)) {
4117                 u16 phyctl1 = 0;
4118
4119                 phyctl1 = wlc_phytxctl1_calc(wlc, rspec[0]);
4120                 txh->PhyTxControlWord_1 = cpu_to_le16(phyctl1);
4121                 phyctl1 = wlc_phytxctl1_calc(wlc, rspec[1]);
4122                 txh->PhyTxControlWord_1_Fbr = cpu_to_le16(phyctl1);
4123
4124                 if (use_rts || use_cts) {
4125                         phyctl1 = wlc_phytxctl1_calc(wlc, rts_rspec[0]);
4126                         txh->PhyTxControlWord_1_Rts = cpu_to_le16(phyctl1);
4127                         phyctl1 = wlc_phytxctl1_calc(wlc, rts_rspec[1]);
4128                         txh->PhyTxControlWord_1_FbrRts = cpu_to_le16(phyctl1);
4129                 }
4130
4131                 /*
4132                  * For mcs frames, if mixedmode(overloaded with long preamble) is going to be set,
4133                  * fill in non-zero MModeLen and/or MModeFbrLen
4134                  *  it will be unnecessary if they are separated
4135                  */
4136                 if (IS_MCS(rspec[0]) && (preamble_type[0] == WLC_MM_PREAMBLE)) {
4137                         u16 mmodelen =
4138                             wlc_calc_lsig_len(wlc, rspec[0], phylen);
4139                         txh->MModeLen = cpu_to_le16(mmodelen);
4140                 }
4141
4142                 if (IS_MCS(rspec[1]) && (preamble_type[1] == WLC_MM_PREAMBLE)) {
4143                         u16 mmodefbrlen =
4144                             wlc_calc_lsig_len(wlc, rspec[1], phylen);
4145                         txh->MModeFbrLen = cpu_to_le16(mmodefbrlen);
4146                 }
4147         }
4148
4149         ac = skb_get_queue_mapping(p);
4150         if (SCB_WME(scb) && qos && wlc->edcf_txop[ac]) {
4151                 uint frag_dur, dur, dur_fallback;
4152
4153                 /* WME: Update TXOP threshold */
4154                 if ((!(tx_info->flags & IEEE80211_TX_CTL_AMPDU)) && (frag == 0)) {
4155                         frag_dur =
4156                             wlc_calc_frame_time(wlc, rspec[0], preamble_type[0],
4157                                                 phylen);
4158
4159                         if (rts) {
4160                                 /* 1 RTS or CTS-to-self frame */
4161                                 dur =
4162                                     wlc_calc_cts_time(wlc, rts_rspec[0],
4163                                                       rts_preamble_type[0]);
4164                                 dur_fallback =
4165                                     wlc_calc_cts_time(wlc, rts_rspec[1],
4166                                                       rts_preamble_type[1]);
4167                                 /* (SIFS + CTS) + SIFS + frame + SIFS + ACK */
4168                                 dur += le16_to_cpu(rts->duration);
4169                                 dur_fallback +=
4170                                         le16_to_cpu(txh->RTSDurFallback);
4171                         } else if (use_rifs) {
4172                                 dur = frag_dur;
4173                                 dur_fallback = 0;
4174                         } else {
4175                                 /* frame + SIFS + ACK */
4176                                 dur = frag_dur;
4177                                 dur +=
4178                                     wlc_compute_frame_dur(wlc, rspec[0],
4179                                                           preamble_type[0], 0);
4180
4181                                 dur_fallback =
4182                                     wlc_calc_frame_time(wlc, rspec[1],
4183                                                         preamble_type[1],
4184                                                         phylen);
4185                                 dur_fallback +=
4186                                     wlc_compute_frame_dur(wlc, rspec[1],
4187                                                           preamble_type[1], 0);
4188                         }
4189                         /* NEED to set TxFesTimeNormal (hard) */
4190                         txh->TxFesTimeNormal = cpu_to_le16((u16) dur);
4191                         /* NEED to set fallback rate version of TxFesTimeNormal (hard) */
4192                         txh->TxFesTimeFallback =
4193                                 cpu_to_le16((u16) dur_fallback);
4194
4195                         /* update txop byte threshold (txop minus intraframe overhead) */
4196                         if (wlc->edcf_txop[ac] >= (dur - frag_dur)) {
4197                                 {
4198                                         uint newfragthresh;
4199
4200                                         newfragthresh =
4201                                             wlc_calc_frame_len(wlc, rspec[0],
4202                                                                preamble_type[0],
4203                                                                (wlc->
4204                                                                 edcf_txop[ac] -
4205                                                                 (dur -
4206                                                                  frag_dur)));
4207                                         /* range bound the fragthreshold */
4208                                         if (newfragthresh < DOT11_MIN_FRAG_LEN)
4209                                                 newfragthresh =
4210                                                     DOT11_MIN_FRAG_LEN;
4211                                         else if (newfragthresh >
4212                                                  wlc->usr_fragthresh)
4213                                                 newfragthresh =
4214                                                     wlc->usr_fragthresh;
4215                                         /* update the fragthresh and do txc update */
4216                                         if (wlc->fragthresh[queue] !=
4217                                             (u16) newfragthresh) {
4218                                                 wlc->fragthresh[queue] =
4219                                                     (u16) newfragthresh;
4220                                         }
4221                                 }
4222                         } else
4223                                 wiphy_err(wlc->wiphy, "wl%d: %s txop invalid "
4224                                           "for rate %d\n",
4225                                           wlc->pub->unit, fifo_names[queue],
4226                                           RSPEC2RATE(rspec[0]));
4227
4228                         if (dur > wlc->edcf_txop[ac])
4229                                 wiphy_err(wlc->wiphy, "wl%d: %s: %s txop "
4230                                           "exceeded phylen %d/%d dur %d/%d\n",
4231                                           wlc->pub->unit, __func__,
4232                                           fifo_names[queue],
4233                                           phylen, wlc->fragthresh[queue],
4234                                           dur, wlc->edcf_txop[ac]);
4235                 }
4236         }
4237
4238         return 0;
4239 }
4240
4241 void wlc_tbtt(struct wlc_info *wlc, d11regs_t *regs)
4242 {
4243         struct wlc_bsscfg *cfg = wlc->cfg;
4244
4245         if (!cfg->BSS) {
4246                 /* DirFrmQ is now valid...defer setting until end of ATIM window */
4247                 wlc->qvalid |= MCMD_DIRFRMQVAL;
4248         }
4249 }
4250
4251 static void wlc_war16165(struct wlc_info *wlc, bool tx)
4252 {
4253         if (tx) {
4254                 /* the post-increment is used in STAY_AWAKE macro */
4255                 if (wlc->txpend16165war++ == 0)
4256                         wlc_set_ps_ctrl(wlc);
4257         } else {
4258                 wlc->txpend16165war--;
4259                 if (wlc->txpend16165war == 0)
4260                         wlc_set_ps_ctrl(wlc);
4261         }
4262 }
4263
4264 /* process an individual tx_status_t */
4265 /* WLC_HIGH_API */
4266 bool
4267 wlc_dotxstatus(struct wlc_info *wlc, tx_status_t *txs, u32 frm_tx2)
4268 {
4269         struct sk_buff *p;
4270         uint queue;
4271         d11txh_t *txh;
4272         struct scb *scb = NULL;
4273         bool free_pdu;
4274         int tx_rts, tx_frame_count, tx_rts_count;
4275         uint totlen, supr_status;
4276         bool lastframe;
4277         struct ieee80211_hdr *h;
4278         u16 mcl;
4279         struct ieee80211_tx_info *tx_info;
4280         struct ieee80211_tx_rate *txrate;
4281         int i;
4282
4283         (void)(frm_tx2);        /* Compiler reference to avoid unused variable warning */
4284
4285         /* discard intermediate indications for ucode with one legitimate case:
4286          *   e.g. if "useRTS" is set. ucode did a successful rts/cts exchange, but the subsequent
4287          *   tx of DATA failed. so it will start rts/cts from the beginning (resetting the rts
4288          *   transmission count)
4289          */
4290         if (!(txs->status & TX_STATUS_AMPDU)
4291             && (txs->status & TX_STATUS_INTERMEDIATE)) {
4292                 wiphy_err(wlc->wiphy, "%s: INTERMEDIATE but not AMPDU\n",
4293                           __func__);
4294                 return false;
4295         }
4296
4297         queue = txs->frameid & TXFID_QUEUE_MASK;
4298         if (queue >= NFIFO) {
4299                 p = NULL;
4300                 goto fatal;
4301         }
4302
4303         p = GETNEXTTXP(wlc, queue);
4304         if (WLC_WAR16165(wlc))
4305                 wlc_war16165(wlc, false);
4306         if (p == NULL)
4307                 goto fatal;
4308
4309         txh = (d11txh_t *) (p->data);
4310         mcl = le16_to_cpu(txh->MacTxControlLow);
4311
4312         if (txs->phyerr) {
4313                 if (WL_ERROR_ON()) {
4314                         wiphy_err(wlc->wiphy, "phyerr 0x%x, rate 0x%x\n",
4315                                   txs->phyerr, txh->MainRates);
4316                         wlc_print_txdesc(txh);
4317                 }
4318                 wlc_print_txstatus(txs);
4319         }
4320
4321         if (txs->frameid != cpu_to_le16(txh->TxFrameID))
4322                 goto fatal;
4323         tx_info = IEEE80211_SKB_CB(p);
4324         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
4325
4326         if (tx_info->control.sta)
4327                 scb = (struct scb *)tx_info->control.sta->drv_priv;
4328
4329         if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
4330                 wlc_ampdu_dotxstatus(wlc->ampdu, scb, p, txs);
4331                 return false;
4332         }
4333
4334         supr_status = txs->status & TX_STATUS_SUPR_MASK;
4335         if (supr_status == TX_STATUS_SUPR_BADCH)
4336                 BCMMSG(wlc->wiphy,
4337                        "%s: Pkt tx suppressed, possibly channel %d\n",
4338                        __func__, CHSPEC_CHANNEL(wlc->default_bss->chanspec));
4339
4340         tx_rts = cpu_to_le16(txh->MacTxControlLow) & TXC_SENDRTS;
4341         tx_frame_count =
4342             (txs->status & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT;
4343         tx_rts_count =
4344             (txs->status & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT;
4345
4346         lastframe = !ieee80211_has_morefrags(h->frame_control);
4347
4348         if (!lastframe) {
4349                 wiphy_err(wlc->wiphy, "Not last frame!\n");
4350         } else {
4351                 u16 sfbl, lfbl;
4352                 ieee80211_tx_info_clear_status(tx_info);
4353                 if (queue < AC_COUNT) {
4354                         sfbl = WLC_WME_RETRY_SFB_GET(wlc, wme_fifo2ac[queue]);
4355                         lfbl = WLC_WME_RETRY_LFB_GET(wlc, wme_fifo2ac[queue]);
4356                 } else {
4357                         sfbl = wlc->SFBL;
4358                         lfbl = wlc->LFBL;
4359                 }
4360
4361                 txrate = tx_info->status.rates;
4362                 /* FIXME: this should use a combination of sfbl, lfbl depending on frame length and RTS setting */
4363                 if ((tx_frame_count > sfbl) && (txrate[1].idx >= 0)) {
4364                         /* rate selection requested a fallback rate and we used it */
4365                         txrate->count = lfbl;
4366                         txrate[1].count = tx_frame_count - lfbl;
4367                 } else {
4368                         /* rate selection did not request fallback rate, or we didn't need it */
4369                         txrate->count = tx_frame_count;
4370                         /* rc80211_minstrel.c:minstrel_tx_status() expects unused rates to be marked with idx = -1 */
4371                         txrate[1].idx = -1;
4372                         txrate[1].count = 0;
4373                 }
4374
4375                 /* clear the rest of the rates */
4376                 for (i = 2; i < IEEE80211_TX_MAX_RATES; i++) {
4377                         txrate[i].idx = -1;
4378                         txrate[i].count = 0;
4379                 }
4380
4381                 if (txs->status & TX_STATUS_ACK_RCV)
4382                         tx_info->flags |= IEEE80211_TX_STAT_ACK;
4383         }
4384
4385         totlen = bcm_pkttotlen(p);
4386         free_pdu = true;
4387
4388         wlc_txfifo_complete(wlc, queue, 1);
4389
4390         if (lastframe) {
4391                 p->next = NULL;
4392                 p->prev = NULL;
4393                 /* remove PLCP & Broadcom tx descriptor header */
4394                 skb_pull(p, D11_PHY_HDR_LEN);
4395                 skb_pull(p, D11_TXH_LEN);
4396                 ieee80211_tx_status_irqsafe(wlc->pub->ieee_hw, p);
4397         } else {
4398                 wiphy_err(wlc->wiphy, "%s: Not last frame => not calling "
4399                           "tx_status\n", __func__);
4400         }
4401
4402         return false;
4403
4404  fatal:
4405         if (p)
4406                 bcm_pkt_buf_free_skb(p);
4407
4408         return true;
4409
4410 }
4411
4412 void
4413 wlc_txfifo_complete(struct wlc_info *wlc, uint fifo, s8 txpktpend)
4414 {
4415         TXPKTPENDDEC(wlc, fifo, txpktpend);
4416         BCMMSG(wlc->wiphy, "pktpend dec %d to %d\n", txpktpend,
4417                 TXPKTPENDGET(wlc, fifo));
4418
4419         /* There is more room; mark precedences related to this FIFO sendable */
4420         WLC_TX_FIFO_ENAB(wlc, fifo);
4421
4422         /* Clear MHF2_TXBCMC_NOW flag if BCMC fifo has drained */
4423         if (AP_ENAB(wlc->pub) &&
4424             !TXPKTPENDGET(wlc, TX_BCMC_FIFO)) {
4425                 wlc_mhf(wlc, MHF2, MHF2_TXBCMC_NOW, 0, WLC_BAND_AUTO);
4426         }
4427
4428         /* figure out which bsscfg is being worked on... */
4429 }
4430
4431 /* Update beacon listen interval in shared memory */
4432 void wlc_bcn_li_upd(struct wlc_info *wlc)
4433 {
4434         if (AP_ENAB(wlc->pub))
4435                 return;
4436
4437         /* wake up every DTIM is the default */
4438         if (wlc->bcn_li_dtim == 1)
4439                 wlc_write_shm(wlc, M_BCN_LI, 0);
4440         else
4441                 wlc_write_shm(wlc, M_BCN_LI,
4442                               (wlc->bcn_li_dtim << 8) | wlc->bcn_li_bcn);
4443 }
4444
4445 /*
4446  * recover 64bit TSF value from the 16bit TSF value in the rx header
4447  * given the assumption that the TSF passed in header is within 65ms
4448  * of the current tsf.
4449  *
4450  * 6       5       4       4       3       2       1
4451  * 3.......6.......8.......0.......2.......4.......6.......8......0
4452  * |<---------- tsf_h ----------->||<--- tsf_l -->||<-RxTSFTime ->|
4453  *
4454  * The RxTSFTime are the lowest 16 bits and provided by the ucode. The
4455  * tsf_l is filled in by wlc_bmac_recv, which is done earlier in the
4456  * receive call sequence after rx interrupt. Only the higher 16 bits
4457  * are used. Finally, the tsf_h is read from the tsf register.
4458  */
4459 static u64 wlc_recover_tsf64(struct wlc_info *wlc, struct wlc_d11rxhdr *rxh)
4460 {
4461         u32 tsf_h, tsf_l;
4462         u16 rx_tsf_0_15, rx_tsf_16_31;
4463
4464         wlc_bmac_read_tsf(wlc->hw, &tsf_l, &tsf_h);
4465
4466         rx_tsf_16_31 = (u16)(tsf_l >> 16);
4467         rx_tsf_0_15 = rxh->rxhdr.RxTSFTime;
4468
4469         /*
4470          * a greater tsf time indicates the low 16 bits of
4471          * tsf_l wrapped, so decrement the high 16 bits.
4472          */
4473         if ((u16)tsf_l < rx_tsf_0_15) {
4474                 rx_tsf_16_31 -= 1;
4475                 if (rx_tsf_16_31 == 0xffff)
4476                         tsf_h -= 1;
4477         }
4478
4479         return ((u64)tsf_h << 32) | (((u32)rx_tsf_16_31 << 16) + rx_tsf_0_15);
4480 }
4481
4482 static void
4483 prep_mac80211_status(struct wlc_info *wlc, d11rxhdr_t *rxh, struct sk_buff *p,
4484                      struct ieee80211_rx_status *rx_status)
4485 {
4486         wlc_d11rxhdr_t *wlc_rxh = (wlc_d11rxhdr_t *) rxh;
4487         int preamble;
4488         int channel;
4489         ratespec_t rspec;
4490         unsigned char *plcp;
4491
4492         /* fill in TSF and flag its presence */
4493         rx_status->mactime = wlc_recover_tsf64(wlc, wlc_rxh);
4494         rx_status->flag |= RX_FLAG_MACTIME_MPDU;
4495
4496         channel = WLC_CHAN_CHANNEL(rxh->RxChan);
4497
4498         if (channel > 14) {
4499                 rx_status->band = IEEE80211_BAND_5GHZ;
4500                 rx_status->freq = ieee80211_ofdm_chan_to_freq(
4501                                         WF_CHAN_FACTOR_5_G/2, channel);
4502
4503         } else {
4504                 rx_status->band = IEEE80211_BAND_2GHZ;
4505                 rx_status->freq = ieee80211_dsss_chan_to_freq(channel);
4506         }
4507
4508         rx_status->signal = wlc_rxh->rssi;      /* signal */
4509
4510         /* noise */
4511         /* qual */
4512         rx_status->antenna = (rxh->PhyRxStatus_0 & PRXS0_RXANT_UPSUBBAND) ? 1 : 0;      /* ant */
4513
4514         plcp = p->data;
4515
4516         rspec = wlc_compute_rspec(rxh, plcp);
4517         if (IS_MCS(rspec)) {
4518                 rx_status->rate_idx = rspec & RSPEC_RATE_MASK;
4519                 rx_status->flag |= RX_FLAG_HT;
4520                 if (RSPEC_IS40MHZ(rspec))
4521                         rx_status->flag |= RX_FLAG_40MHZ;
4522         } else {
4523                 switch (RSPEC2RATE(rspec)) {
4524                 case WLC_RATE_1M:
4525                         rx_status->rate_idx = 0;
4526                         break;
4527                 case WLC_RATE_2M:
4528                         rx_status->rate_idx = 1;
4529                         break;
4530                 case WLC_RATE_5M5:
4531                         rx_status->rate_idx = 2;
4532                         break;
4533                 case WLC_RATE_11M:
4534                         rx_status->rate_idx = 3;
4535                         break;
4536                 case WLC_RATE_6M:
4537                         rx_status->rate_idx = 4;
4538                         break;
4539                 case WLC_RATE_9M:
4540                         rx_status->rate_idx = 5;
4541                         break;
4542                 case WLC_RATE_12M:
4543                         rx_status->rate_idx = 6;
4544                         break;
4545                 case WLC_RATE_18M:
4546                         rx_status->rate_idx = 7;
4547                         break;
4548                 case WLC_RATE_24M:
4549                         rx_status->rate_idx = 8;
4550                         break;
4551                 case WLC_RATE_36M:
4552                         rx_status->rate_idx = 9;
4553                         break;
4554                 case WLC_RATE_48M:
4555                         rx_status->rate_idx = 10;
4556                         break;
4557                 case WLC_RATE_54M:
4558                         rx_status->rate_idx = 11;
4559                         break;
4560                 default:
4561                         wiphy_err(wlc->wiphy, "%s: Unknown rate\n", __func__);
4562                 }
4563
4564                 /* Determine short preamble and rate_idx */
4565                 preamble = 0;
4566                 if (IS_CCK(rspec)) {
4567                         if (rxh->PhyRxStatus_0 & PRXS0_SHORTH)
4568                                 rx_status->flag |= RX_FLAG_SHORTPRE;
4569                 } else if (IS_OFDM(rspec)) {
4570                         rx_status->flag |= RX_FLAG_SHORTPRE;
4571                 } else {
4572                         wiphy_err(wlc->wiphy, "%s: Unknown modulation\n",
4573                                   __func__);
4574                 }
4575         }
4576
4577         if (PLCP3_ISSGI(plcp[3]))
4578                 rx_status->flag |= RX_FLAG_SHORT_GI;
4579
4580         if (rxh->RxStatus1 & RXS_DECERR) {
4581                 rx_status->flag |= RX_FLAG_FAILED_PLCP_CRC;
4582                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_PLCP_CRC\n",
4583                           __func__);
4584         }
4585         if (rxh->RxStatus1 & RXS_FCSERR) {
4586                 rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
4587                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_FCS_CRC\n",
4588                           __func__);
4589         }
4590 }
4591
4592 static void
4593 wlc_recvctl(struct wlc_info *wlc, d11rxhdr_t *rxh, struct sk_buff *p)
4594 {
4595         int len_mpdu;
4596         struct ieee80211_rx_status rx_status;
4597
4598         memset(&rx_status, 0, sizeof(rx_status));
4599         prep_mac80211_status(wlc, rxh, p, &rx_status);
4600
4601         /* mac header+body length, exclude CRC and plcp header */
4602         len_mpdu = p->len - D11_PHY_HDR_LEN - FCS_LEN;
4603         skb_pull(p, D11_PHY_HDR_LEN);
4604         __skb_trim(p, len_mpdu);
4605
4606         memcpy(IEEE80211_SKB_RXCB(p), &rx_status, sizeof(rx_status));
4607         ieee80211_rx_irqsafe(wlc->pub->ieee_hw, p);
4608         return;
4609 }
4610
4611 /* Process received frames */
4612 /*
4613  * Return true if more frames need to be processed. false otherwise.
4614  * Param 'bound' indicates max. # frames to process before break out.
4615  */
4616 /* WLC_HIGH_API */
4617 void wlc_recv(struct wlc_info *wlc, struct sk_buff *p)
4618 {
4619         d11rxhdr_t *rxh;
4620         struct ieee80211_hdr *h;
4621         uint len;
4622         bool is_amsdu;
4623
4624         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
4625
4626         /* frame starts with rxhdr */
4627         rxh = (d11rxhdr_t *) (p->data);
4628
4629         /* strip off rxhdr */
4630         skb_pull(p, WL_HWRXOFF);
4631
4632         /* fixup rx header endianness */
4633         rxh->RxFrameSize = le16_to_cpu(rxh->RxFrameSize);
4634         rxh->PhyRxStatus_0 = le16_to_cpu(rxh->PhyRxStatus_0);
4635         rxh->PhyRxStatus_1 = le16_to_cpu(rxh->PhyRxStatus_1);
4636         rxh->PhyRxStatus_2 = le16_to_cpu(rxh->PhyRxStatus_2);
4637         rxh->PhyRxStatus_3 = le16_to_cpu(rxh->PhyRxStatus_3);
4638         rxh->PhyRxStatus_4 = le16_to_cpu(rxh->PhyRxStatus_4);
4639         rxh->PhyRxStatus_5 = le16_to_cpu(rxh->PhyRxStatus_5);
4640         rxh->RxStatus1 = le16_to_cpu(rxh->RxStatus1);
4641         rxh->RxStatus2 = le16_to_cpu(rxh->RxStatus2);
4642         rxh->RxTSFTime = le16_to_cpu(rxh->RxTSFTime);
4643         rxh->RxChan = le16_to_cpu(rxh->RxChan);
4644
4645         /* MAC inserts 2 pad bytes for a4 headers or QoS or A-MSDU subframes */
4646         if (rxh->RxStatus1 & RXS_PBPRES) {
4647                 if (p->len < 2) {
4648                         wiphy_err(wlc->wiphy, "wl%d: wlc_recv: rcvd runt of "
4649                                   "len %d\n", wlc->pub->unit, p->len);
4650                         goto toss;
4651                 }
4652                 skb_pull(p, 2);
4653         }
4654
4655         h = (struct ieee80211_hdr *)(p->data + D11_PHY_HDR_LEN);
4656         len = p->len;
4657
4658         if (rxh->RxStatus1 & RXS_FCSERR) {
4659                 if (wlc->pub->mac80211_state & MAC80211_PROMISC_BCNS) {
4660                         wiphy_err(wlc->wiphy, "FCSERR while scanning******* -"
4661                                   " tossing\n");
4662                         goto toss;
4663                 } else {
4664                         wiphy_err(wlc->wiphy, "RCSERR!!!\n");
4665                         goto toss;
4666                 }
4667         }
4668
4669         /* check received pkt has at least frame control field */
4670         if (len < D11_PHY_HDR_LEN + sizeof(h->frame_control)) {
4671                 goto toss;
4672         }
4673
4674         is_amsdu = rxh->RxStatus2 & RXS_AMSDU_MASK;
4675
4676         /* explicitly test bad src address to avoid sending bad deauth */
4677         if (!is_amsdu) {
4678                 /* CTS and ACK CTL frames are w/o a2 */
4679
4680                 if (ieee80211_is_data(h->frame_control) ||
4681                     ieee80211_is_mgmt(h->frame_control)) {
4682                         if ((is_zero_ether_addr(h->addr2) ||
4683                              is_multicast_ether_addr(h->addr2))) {
4684                                 wiphy_err(wlc->wiphy, "wl%d: %s: dropping a "
4685                                           "frame with invalid src mac address,"
4686                                           " a2: %pM\n",
4687                                          wlc->pub->unit, __func__, h->addr2);
4688                                 goto toss;
4689                         }
4690                 }
4691         }
4692
4693         /* due to sheer numbers, toss out probe reqs for now */
4694         if (ieee80211_is_probe_req(h->frame_control))
4695                 goto toss;
4696
4697         if (is_amsdu)
4698                 goto toss;
4699
4700         wlc_recvctl(wlc, rxh, p);
4701         return;
4702
4703  toss:
4704         bcm_pkt_buf_free_skb(p);
4705 }
4706
4707 /* calculate frame duration for Mixed-mode L-SIG spoofing, return
4708  * number of bytes goes in the length field
4709  *
4710  * Formula given by HT PHY Spec v 1.13
4711  *   len = 3(nsyms + nstream + 3) - 3
4712  */
4713 u16
4714 wlc_calc_lsig_len(struct wlc_info *wlc, ratespec_t ratespec, uint mac_len)
4715 {
4716         uint nsyms, len = 0, kNdps;
4717
4718         BCMMSG(wlc->wiphy, "wl%d: rate %d, len%d\n",
4719                  wlc->pub->unit, RSPEC2RATE(ratespec), mac_len);
4720
4721         if (IS_MCS(ratespec)) {
4722                 uint mcs = ratespec & RSPEC_RATE_MASK;
4723                 /* MCS_TXS(mcs) returns num tx streams - 1 */
4724                 int tot_streams = (MCS_TXS(mcs) + 1) + RSPEC_STC(ratespec);
4725
4726                 /* the payload duration calculation matches that of regular ofdm */
4727                 /* 1000Ndbps = kbps * 4 */
4728                 kNdps =
4729                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4730                              RSPEC_ISSGI(ratespec)) * 4;
4731
4732                 if (RSPEC_STC(ratespec) == 0)
4733                         /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4734                         nsyms =
4735                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4736                                   APHY_TAIL_NBITS) * 1000, kNdps);
4737                 else
4738                         /* STBC needs to have even number of symbols */
4739                         nsyms =
4740                             2 *
4741                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4742                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
4743
4744                 nsyms += (tot_streams + 3);     /* (+3) account for HT-SIG(2) and HT-STF(1) */
4745                 /* 3 bytes/symbol @ legacy 6Mbps rate */
4746                 len = (3 * nsyms) - 3;  /* (-3) excluding service bits and tail bits */
4747         }
4748
4749         return (u16) len;
4750 }
4751
4752 /* calculate frame duration of a given rate and length, return time in usec unit */
4753 uint
4754 wlc_calc_frame_time(struct wlc_info *wlc, ratespec_t ratespec, u8 preamble_type,
4755                     uint mac_len)
4756 {
4757         uint nsyms, dur = 0, Ndps, kNdps;
4758         uint rate = RSPEC2RATE(ratespec);
4759
4760         if (rate == 0) {
4761                 wiphy_err(wlc->wiphy, "wl%d: WAR: using rate of 1 mbps\n",
4762                           wlc->pub->unit);
4763                 rate = WLC_RATE_1M;
4764         }
4765
4766         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d, len%d\n",
4767                  wlc->pub->unit, ratespec, preamble_type, mac_len);
4768
4769         if (IS_MCS(ratespec)) {
4770                 uint mcs = ratespec & RSPEC_RATE_MASK;
4771                 int tot_streams = MCS_TXS(mcs) + RSPEC_STC(ratespec);
4772
4773                 dur = PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
4774                 if (preamble_type == WLC_MM_PREAMBLE)
4775                         dur += PREN_MM_EXT;
4776                 /* 1000Ndbps = kbps * 4 */
4777                 kNdps =
4778                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4779                              RSPEC_ISSGI(ratespec)) * 4;
4780
4781                 if (RSPEC_STC(ratespec) == 0)
4782                         /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4783                         nsyms =
4784                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4785                                   APHY_TAIL_NBITS) * 1000, kNdps);
4786                 else
4787                         /* STBC needs to have even number of symbols */
4788                         nsyms =
4789                             2 *
4790                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4791                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
4792
4793                 dur += APHY_SYMBOL_TIME * nsyms;
4794                 if (BAND_2G(wlc->band->bandtype))
4795                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
4796         } else if (IS_OFDM(rate)) {
4797                 dur = APHY_PREAMBLE_TIME;
4798                 dur += APHY_SIGNAL_TIME;
4799                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
4800                 Ndps = rate * 2;
4801                 /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4802                 nsyms =
4803                     CEIL((APHY_SERVICE_NBITS + 8 * mac_len + APHY_TAIL_NBITS),
4804                          Ndps);
4805                 dur += APHY_SYMBOL_TIME * nsyms;
4806                 if (BAND_2G(wlc->band->bandtype))
4807                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
4808         } else {
4809                 /* calc # bits * 2 so factor of 2 in rate (1/2 mbps) will divide out */
4810                 mac_len = mac_len * 8 * 2;
4811                 /* calc ceiling of bits/rate = microseconds of air time */
4812                 dur = (mac_len + rate - 1) / rate;
4813                 if (preamble_type & WLC_SHORT_PREAMBLE)
4814                         dur += BPHY_PLCP_SHORT_TIME;
4815                 else
4816                         dur += BPHY_PLCP_TIME;
4817         }
4818         return dur;
4819 }
4820
4821 /* The opposite of wlc_calc_frame_time */
4822 static uint
4823 wlc_calc_frame_len(struct wlc_info *wlc, ratespec_t ratespec, u8 preamble_type,
4824                    uint dur)
4825 {
4826         uint nsyms, mac_len, Ndps, kNdps;
4827         uint rate = RSPEC2RATE(ratespec);
4828
4829         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d, dur %d\n",
4830                  wlc->pub->unit, ratespec, preamble_type, dur);
4831
4832         if (IS_MCS(ratespec)) {
4833                 uint mcs = ratespec & RSPEC_RATE_MASK;
4834                 int tot_streams = MCS_TXS(mcs) + RSPEC_STC(ratespec);
4835                 dur -= PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
4836                 /* payload calculation matches that of regular ofdm */
4837                 if (BAND_2G(wlc->band->bandtype))
4838                         dur -= DOT11_OFDM_SIGNAL_EXTENSION;
4839                 /* kNdbps = kbps * 4 */
4840                 kNdps =
4841                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4842                              RSPEC_ISSGI(ratespec)) * 4;
4843                 nsyms = dur / APHY_SYMBOL_TIME;
4844                 mac_len =
4845                     ((nsyms * kNdps) -
4846                      ((APHY_SERVICE_NBITS + APHY_TAIL_NBITS) * 1000)) / 8000;
4847         } else if (IS_OFDM(ratespec)) {
4848                 dur -= APHY_PREAMBLE_TIME;
4849                 dur -= APHY_SIGNAL_TIME;
4850                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
4851                 Ndps = rate * 2;
4852                 nsyms = dur / APHY_SYMBOL_TIME;
4853                 mac_len =
4854                     ((nsyms * Ndps) -
4855                      (APHY_SERVICE_NBITS + APHY_TAIL_NBITS)) / 8;
4856         } else {
4857                 if (preamble_type & WLC_SHORT_PREAMBLE)
4858                         dur -= BPHY_PLCP_SHORT_TIME;
4859                 else
4860                         dur -= BPHY_PLCP_TIME;
4861                 mac_len = dur * rate;
4862                 /* divide out factor of 2 in rate (1/2 mbps) */
4863                 mac_len = mac_len / 8 / 2;
4864         }
4865         return mac_len;
4866 }
4867
4868 static uint
4869 wlc_calc_ba_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4870 {
4871         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, "
4872                  "preamble_type %d\n", wlc->pub->unit, rspec, preamble_type);
4873         /* Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that is less than
4874          * or equal to the rate of the immediately previous frame in the FES
4875          */
4876         rspec = WLC_BASIC_RATE(wlc, rspec);
4877         /* BA len == 32 == 16(ctl hdr) + 4(ba len) + 8(bitmap) + 4(fcs) */
4878         return wlc_calc_frame_time(wlc, rspec, preamble_type,
4879                                    (DOT11_BA_LEN + DOT11_BA_BITMAP_LEN +
4880                                     FCS_LEN));
4881 }
4882
4883 static uint
4884 wlc_calc_ack_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4885 {
4886         uint dur = 0;
4887
4888         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d\n",
4889                 wlc->pub->unit, rspec, preamble_type);
4890         /* Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that is less than
4891          * or equal to the rate of the immediately previous frame in the FES
4892          */
4893         rspec = WLC_BASIC_RATE(wlc, rspec);
4894         /* ACK frame len == 14 == 2(fc) + 2(dur) + 6(ra) + 4(fcs) */
4895         dur =
4896             wlc_calc_frame_time(wlc, rspec, preamble_type,
4897                                 (DOT11_ACK_LEN + FCS_LEN));
4898         return dur;
4899 }
4900
4901 static uint
4902 wlc_calc_cts_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4903 {
4904         BCMMSG(wlc->wiphy, "wl%d: ratespec 0x%x, preamble_type %d\n",
4905                 wlc->pub->unit, rspec, preamble_type);
4906         return wlc_calc_ack_time(wlc, rspec, preamble_type);
4907 }
4908
4909 /* derive wlc->band->basic_rate[] table from 'rateset' */
4910 void wlc_rate_lookup_init(struct wlc_info *wlc, wlc_rateset_t *rateset)
4911 {
4912         u8 rate;
4913         u8 mandatory;
4914         u8 cck_basic = 0;
4915         u8 ofdm_basic = 0;
4916         u8 *br = wlc->band->basic_rate;
4917         uint i;
4918
4919         /* incoming rates are in 500kbps units as in 802.11 Supported Rates */
4920         memset(br, 0, WLC_MAXRATE + 1);
4921
4922         /* For each basic rate in the rates list, make an entry in the
4923          * best basic lookup.
4924          */
4925         for (i = 0; i < rateset->count; i++) {
4926                 /* only make an entry for a basic rate */
4927                 if (!(rateset->rates[i] & WLC_RATE_FLAG))
4928                         continue;
4929
4930                 /* mask off basic bit */
4931                 rate = (rateset->rates[i] & WLC_RATE_MASK);
4932
4933                 if (rate > WLC_MAXRATE) {
4934                         wiphy_err(wlc->wiphy, "wlc_rate_lookup_init: invalid "
4935                                   "rate 0x%X in rate set\n",
4936                                   rateset->rates[i]);
4937                         continue;
4938                 }
4939
4940                 br[rate] = rate;
4941         }
4942
4943         /* The rate lookup table now has non-zero entries for each
4944          * basic rate, equal to the basic rate: br[basicN] = basicN
4945          *
4946          * To look up the best basic rate corresponding to any
4947          * particular rate, code can use the basic_rate table
4948          * like this
4949          *
4950          * basic_rate = wlc->band->basic_rate[tx_rate]
4951          *
4952          * Make sure there is a best basic rate entry for
4953          * every rate by walking up the table from low rates
4954          * to high, filling in holes in the lookup table
4955          */
4956
4957         for (i = 0; i < wlc->band->hw_rateset.count; i++) {
4958                 rate = wlc->band->hw_rateset.rates[i];
4959
4960                 if (br[rate] != 0) {
4961                         /* This rate is a basic rate.
4962                          * Keep track of the best basic rate so far by
4963                          * modulation type.
4964                          */
4965                         if (IS_OFDM(rate))
4966                                 ofdm_basic = rate;
4967                         else
4968                                 cck_basic = rate;
4969
4970                         continue;
4971                 }
4972
4973                 /* This rate is not a basic rate so figure out the
4974                  * best basic rate less than this rate and fill in
4975                  * the hole in the table
4976                  */
4977
4978                 br[rate] = IS_OFDM(rate) ? ofdm_basic : cck_basic;
4979
4980                 if (br[rate] != 0)
4981                         continue;
4982
4983                 if (IS_OFDM(rate)) {
4984                         /* In 11g and 11a, the OFDM mandatory rates are 6, 12, and 24 Mbps */
4985                         if (rate >= WLC_RATE_24M)
4986                                 mandatory = WLC_RATE_24M;
4987                         else if (rate >= WLC_RATE_12M)
4988                                 mandatory = WLC_RATE_12M;
4989                         else
4990                                 mandatory = WLC_RATE_6M;
4991                 } else {
4992                         /* In 11b, all the CCK rates are mandatory 1 - 11 Mbps */
4993                         mandatory = rate;
4994                 }
4995
4996                 br[rate] = mandatory;
4997         }
4998 }
4999
5000 static void wlc_write_rate_shm(struct wlc_info *wlc, u8 rate, u8 basic_rate)
5001 {
5002         u8 phy_rate, index;
5003         u8 basic_phy_rate, basic_index;
5004         u16 dir_table, basic_table;
5005         u16 basic_ptr;
5006
5007         /* Shared memory address for the table we are reading */
5008         dir_table = IS_OFDM(basic_rate) ? M_RT_DIRMAP_A : M_RT_DIRMAP_B;
5009
5010         /* Shared memory address for the table we are writing */
5011         basic_table = IS_OFDM(rate) ? M_RT_BBRSMAP_A : M_RT_BBRSMAP_B;
5012
5013         /*
5014          * for a given rate, the LS-nibble of the PLCP SIGNAL field is
5015          * the index into the rate table.
5016          */
5017         phy_rate = rate_info[rate] & WLC_RATE_MASK;
5018         basic_phy_rate = rate_info[basic_rate] & WLC_RATE_MASK;
5019         index = phy_rate & 0xf;
5020         basic_index = basic_phy_rate & 0xf;
5021
5022         /* Find the SHM pointer to the ACK rate entry by looking in the
5023          * Direct-map Table
5024          */
5025         basic_ptr = wlc_read_shm(wlc, (dir_table + basic_index * 2));
5026
5027         /* Update the SHM BSS-basic-rate-set mapping table with the pointer
5028          * to the correct basic rate for the given incoming rate
5029          */
5030         wlc_write_shm(wlc, (basic_table + index * 2), basic_ptr);
5031 }
5032
5033 static const wlc_rateset_t *wlc_rateset_get_hwrs(struct wlc_info *wlc)
5034 {
5035         const wlc_rateset_t *rs_dflt;
5036
5037         if (WLC_PHY_11N_CAP(wlc->band)) {
5038                 if (BAND_5G(wlc->band->bandtype))
5039                         rs_dflt = &ofdm_mimo_rates;
5040                 else
5041                         rs_dflt = &cck_ofdm_mimo_rates;
5042         } else if (wlc->band->gmode)
5043                 rs_dflt = &cck_ofdm_rates;
5044         else
5045                 rs_dflt = &cck_rates;
5046
5047         return rs_dflt;
5048 }
5049
5050 void wlc_set_ratetable(struct wlc_info *wlc)
5051 {
5052         const wlc_rateset_t *rs_dflt;
5053         wlc_rateset_t rs;
5054         u8 rate, basic_rate;
5055         uint i;
5056
5057         rs_dflt = wlc_rateset_get_hwrs(wlc);
5058
5059         wlc_rateset_copy(rs_dflt, &rs);
5060         wlc_rateset_mcs_upd(&rs, wlc->stf->txstreams);
5061
5062         /* walk the phy rate table and update SHM basic rate lookup table */
5063         for (i = 0; i < rs.count; i++) {
5064                 rate = rs.rates[i] & WLC_RATE_MASK;
5065
5066                 /* for a given rate WLC_BASIC_RATE returns the rate at
5067                  * which a response ACK/CTS should be sent.
5068                  */
5069                 basic_rate = WLC_BASIC_RATE(wlc, rate);
5070                 if (basic_rate == 0) {
5071                         /* This should only happen if we are using a
5072                          * restricted rateset.
5073                          */
5074                         basic_rate = rs.rates[0] & WLC_RATE_MASK;
5075                 }
5076
5077                 wlc_write_rate_shm(wlc, rate, basic_rate);
5078         }
5079 }
5080
5081 /*
5082  * Return true if the specified rate is supported by the specified band.
5083  * WLC_BAND_AUTO indicates the current band.
5084  */
5085 bool wlc_valid_rate(struct wlc_info *wlc, ratespec_t rspec, int band,
5086                     bool verbose)
5087 {
5088         wlc_rateset_t *hw_rateset;
5089         uint i;
5090
5091         if ((band == WLC_BAND_AUTO) || (band == wlc->band->bandtype)) {
5092                 hw_rateset = &wlc->band->hw_rateset;
5093         } else if (NBANDS(wlc) > 1) {
5094                 hw_rateset = &wlc->bandstate[OTHERBANDUNIT(wlc)]->hw_rateset;
5095         } else {
5096                 /* other band specified and we are a single band device */
5097                 return false;
5098         }
5099
5100         /* check if this is a mimo rate */
5101         if (IS_MCS(rspec)) {
5102                 if (!VALID_MCS((rspec & RSPEC_RATE_MASK)))
5103                         goto error;
5104
5105                 return isset(hw_rateset->mcs, (rspec & RSPEC_RATE_MASK));
5106         }
5107
5108         for (i = 0; i < hw_rateset->count; i++)
5109                 if (hw_rateset->rates[i] == RSPEC2RATE(rspec))
5110                         return true;
5111  error:
5112         if (verbose) {
5113                 wiphy_err(wlc->wiphy, "wl%d: wlc_valid_rate: rate spec 0x%x "
5114                           "not in hw_rateset\n", wlc->pub->unit, rspec);
5115         }
5116
5117         return false;
5118 }
5119
5120 static void wlc_update_mimo_band_bwcap(struct wlc_info *wlc, u8 bwcap)
5121 {
5122         uint i;
5123         struct wlcband *band;
5124
5125         for (i = 0; i < NBANDS(wlc); i++) {
5126                 if (IS_SINGLEBAND_5G(wlc->deviceid))
5127                         i = BAND_5G_INDEX;
5128                 band = wlc->bandstate[i];
5129                 if (band->bandtype == WLC_BAND_5G) {
5130                         if ((bwcap == WLC_N_BW_40ALL)
5131                             || (bwcap == WLC_N_BW_20IN2G_40IN5G))
5132                                 band->mimo_cap_40 = true;
5133                         else
5134                                 band->mimo_cap_40 = false;
5135                 } else {
5136                         if (bwcap == WLC_N_BW_40ALL)
5137                                 band->mimo_cap_40 = true;
5138                         else
5139                                 band->mimo_cap_40 = false;
5140                 }
5141         }
5142 }
5143
5144 void wlc_mod_prb_rsp_rate_table(struct wlc_info *wlc, uint frame_len)
5145 {
5146         const wlc_rateset_t *rs_dflt;
5147         wlc_rateset_t rs;
5148         u8 rate;
5149         u16 entry_ptr;
5150         u8 plcp[D11_PHY_HDR_LEN];
5151         u16 dur, sifs;
5152         uint i;
5153
5154         sifs = SIFS(wlc->band);
5155
5156         rs_dflt = wlc_rateset_get_hwrs(wlc);
5157
5158         wlc_rateset_copy(rs_dflt, &rs);
5159         wlc_rateset_mcs_upd(&rs, wlc->stf->txstreams);
5160
5161         /* walk the phy rate table and update MAC core SHM basic rate table entries */
5162         for (i = 0; i < rs.count; i++) {
5163                 rate = rs.rates[i] & WLC_RATE_MASK;
5164
5165                 entry_ptr = wlc_rate_shm_offset(wlc, rate);
5166
5167                 /* Calculate the Probe Response PLCP for the given rate */
5168                 wlc_compute_plcp(wlc, rate, frame_len, plcp);
5169
5170                 /* Calculate the duration of the Probe Response frame plus SIFS for the MAC */
5171                 dur =
5172                     (u16) wlc_calc_frame_time(wlc, rate, WLC_LONG_PREAMBLE,
5173                                                  frame_len);
5174                 dur += sifs;
5175
5176                 /* Update the SHM Rate Table entry Probe Response values */
5177                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS,
5178                               (u16) (plcp[0] + (plcp[1] << 8)));
5179                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS + 2,
5180                               (u16) (plcp[2] + (plcp[3] << 8)));
5181                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_DUR_POS, dur);
5182         }
5183 }
5184
5185 /*      Max buffering needed for beacon template/prb resp template is 142 bytes.
5186  *
5187  *      PLCP header is 6 bytes.
5188  *      802.11 A3 header is 24 bytes.
5189  *      Max beacon frame body template length is 112 bytes.
5190  *      Max probe resp frame body template length is 110 bytes.
5191  *
5192  *      *len on input contains the max length of the packet available.
5193  *
5194  *      The *len value is set to the number of bytes in buf used, and starts with the PLCP
5195  *      and included up to, but not including, the 4 byte FCS.
5196  */
5197 static void
5198 wlc_bcn_prb_template(struct wlc_info *wlc, u16 type, ratespec_t bcn_rspec,
5199                      struct wlc_bsscfg *cfg, u16 *buf, int *len)
5200 {
5201         static const u8 ether_bcast[ETH_ALEN] = {255, 255, 255, 255, 255, 255};
5202         cck_phy_hdr_t *plcp;
5203         struct ieee80211_mgmt *h;
5204         int hdr_len, body_len;
5205
5206         if (MBSS_BCN_ENAB(cfg) && type == IEEE80211_STYPE_BEACON)
5207                 hdr_len = DOT11_MAC_HDR_LEN;
5208         else
5209                 hdr_len = D11_PHY_HDR_LEN + DOT11_MAC_HDR_LEN;
5210         body_len = *len - hdr_len;      /* calc buffer size provided for frame body */
5211
5212         *len = hdr_len + body_len;      /* return actual size */
5213
5214         /* format PHY and MAC headers */
5215         memset((char *)buf, 0, hdr_len);
5216
5217         plcp = (cck_phy_hdr_t *) buf;
5218
5219         /* PLCP for Probe Response frames are filled in from core's rate table */
5220         if (type == IEEE80211_STYPE_BEACON && !MBSS_BCN_ENAB(cfg)) {
5221                 /* fill in PLCP */
5222                 wlc_compute_plcp(wlc, bcn_rspec,
5223                                  (DOT11_MAC_HDR_LEN + body_len + FCS_LEN),
5224                                  (u8 *) plcp);
5225
5226         }
5227         /* "Regular" and 16 MBSS but not for 4 MBSS */
5228         /* Update the phytxctl for the beacon based on the rspec */
5229         if (!SOFTBCN_ENAB(cfg))
5230                 wlc_beacon_phytxctl_txant_upd(wlc, bcn_rspec);
5231
5232         if (MBSS_BCN_ENAB(cfg) && type == IEEE80211_STYPE_BEACON)
5233                 h = (struct ieee80211_mgmt *)&plcp[0];
5234         else
5235                 h = (struct ieee80211_mgmt *)&plcp[1];
5236
5237         /* fill in 802.11 header */
5238         h->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | type);
5239
5240         /* DUR is 0 for multicast bcn, or filled in by MAC for prb resp */
5241         /* A1 filled in by MAC for prb resp, broadcast for bcn */
5242         if (type == IEEE80211_STYPE_BEACON)
5243                 memcpy(&h->da, &ether_bcast, ETH_ALEN);
5244         memcpy(&h->sa, &cfg->cur_etheraddr, ETH_ALEN);
5245         memcpy(&h->bssid, &cfg->BSSID, ETH_ALEN);
5246
5247         /* SEQ filled in by MAC */
5248
5249         return;
5250 }
5251
5252 int wlc_get_header_len()
5253 {
5254         return TXOFF;
5255 }
5256
5257 /* Update a beacon for a particular BSS
5258  * For MBSS, this updates the software template and sets "latest" to the index of the
5259  * template updated.
5260  * Otherwise, it updates the hardware template.
5261  */
5262 void wlc_bss_update_beacon(struct wlc_info *wlc, struct wlc_bsscfg *cfg)
5263 {
5264         int len = BCN_TMPL_LEN;
5265
5266         /* Clear the soft intmask */
5267         wlc->defmacintmask &= ~MI_BCNTPL;
5268
5269         if (!cfg->up) {         /* Only allow updates on an UP bss */
5270                 return;
5271         }
5272
5273         /* Optimize:  Some of if/else could be combined */
5274         if (!MBSS_BCN_ENAB(cfg) && HWBCN_ENAB(cfg)) {
5275                 /* Hardware beaconing for this config */
5276                 u16 bcn[BCN_TMPL_LEN / 2];
5277                 u32 both_valid = MCMD_BCN0VLD | MCMD_BCN1VLD;
5278                 d11regs_t *regs = wlc->regs;
5279
5280                 /* Check if both templates are in use, if so sched. an interrupt
5281                  *      that will call back into this routine
5282                  */
5283                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
5284                         /* clear any previous status */
5285                         W_REG(&regs->macintstatus, MI_BCNTPL);
5286                 }
5287                 /* Check that after scheduling the interrupt both of the
5288                  *      templates are still busy. if not clear the int. & remask
5289                  */
5290                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
5291                         wlc->defmacintmask |= MI_BCNTPL;
5292                         return;
5293                 }
5294
5295                 wlc->bcn_rspec =
5296                     wlc_lowest_basic_rspec(wlc, &cfg->current_bss->rateset);
5297                 /* update the template and ucode shm */
5298                 wlc_bcn_prb_template(wlc, IEEE80211_STYPE_BEACON,
5299                                      wlc->bcn_rspec, cfg, bcn, &len);
5300                 wlc_write_hw_bcntemplates(wlc, bcn, len, false);
5301         }
5302 }
5303
5304 /*
5305  * Update all beacons for the system.
5306  */
5307 void wlc_update_beacon(struct wlc_info *wlc)
5308 {
5309         int idx;
5310         struct wlc_bsscfg *bsscfg;
5311
5312         /* update AP or IBSS beacons */
5313         FOREACH_BSS(wlc, idx, bsscfg) {
5314                 if (bsscfg->up && (BSSCFG_AP(bsscfg) || !bsscfg->BSS))
5315                         wlc_bss_update_beacon(wlc, bsscfg);
5316         }
5317 }
5318
5319 /* Write ssid into shared memory */
5320 void wlc_shm_ssid_upd(struct wlc_info *wlc, struct wlc_bsscfg *cfg)
5321 {
5322         u8 *ssidptr = cfg->SSID;
5323         u16 base = M_SSID;
5324         u8 ssidbuf[IEEE80211_MAX_SSID_LEN];
5325
5326         /* padding the ssid with zero and copy it into shm */
5327         memset(ssidbuf, 0, IEEE80211_MAX_SSID_LEN);
5328         memcpy(ssidbuf, ssidptr, cfg->SSID_len);
5329
5330         wlc_copyto_shm(wlc, base, ssidbuf, IEEE80211_MAX_SSID_LEN);
5331
5332         if (!MBSS_BCN_ENAB(cfg))
5333                 wlc_write_shm(wlc, M_SSIDLEN, (u16) cfg->SSID_len);
5334 }
5335
5336 void wlc_update_probe_resp(struct wlc_info *wlc, bool suspend)
5337 {
5338         int idx;
5339         struct wlc_bsscfg *bsscfg;
5340
5341         /* update AP or IBSS probe responses */
5342         FOREACH_BSS(wlc, idx, bsscfg) {
5343                 if (bsscfg->up && (BSSCFG_AP(bsscfg) || !bsscfg->BSS))
5344                         wlc_bss_update_probe_resp(wlc, bsscfg, suspend);
5345         }
5346 }
5347
5348 void
5349 wlc_bss_update_probe_resp(struct wlc_info *wlc, struct wlc_bsscfg *cfg,
5350                           bool suspend)
5351 {
5352         u16 prb_resp[BCN_TMPL_LEN / 2];
5353         int len = BCN_TMPL_LEN;
5354
5355         /* write the probe response to hardware, or save in the config structure */
5356         if (!MBSS_PRB_ENAB(cfg)) {
5357
5358                 /* create the probe response template */
5359                 wlc_bcn_prb_template(wlc, IEEE80211_STYPE_PROBE_RESP, 0, cfg,
5360                                      prb_resp, &len);
5361
5362                 if (suspend)
5363                         wlc_suspend_mac_and_wait(wlc);
5364
5365                 /* write the probe response into the template region */
5366                 wlc_bmac_write_template_ram(wlc->hw, T_PRS_TPL_BASE,
5367                                             (len + 3) & ~3, prb_resp);
5368
5369                 /* write the length of the probe response frame (+PLCP/-FCS) */
5370                 wlc_write_shm(wlc, M_PRB_RESP_FRM_LEN, (u16) len);
5371
5372                 /* write the SSID and SSID length */
5373                 wlc_shm_ssid_upd(wlc, cfg);
5374
5375                 /*
5376                  * Write PLCP headers and durations for probe response frames at all rates.
5377                  * Use the actual frame length covered by the PLCP header for the call to
5378                  * wlc_mod_prb_rsp_rate_table() by subtracting the PLCP len and adding the FCS.
5379                  */
5380                 len += (-D11_PHY_HDR_LEN + FCS_LEN);
5381                 wlc_mod_prb_rsp_rate_table(wlc, (u16) len);
5382
5383                 if (suspend)
5384                         wlc_enable_mac(wlc);
5385         } else {                /* Generating probe resp in sw; update local template */
5386                 /* error: No software probe response support without MBSS */
5387         }
5388 }
5389
5390 /* prepares pdu for transmission. returns BCM error codes */
5391 int wlc_prep_pdu(struct wlc_info *wlc, struct sk_buff *pdu, uint *fifop)
5392 {
5393         uint fifo;
5394         d11txh_t *txh;
5395         struct ieee80211_hdr *h;
5396         struct scb *scb;
5397
5398         txh = (d11txh_t *) (pdu->data);
5399         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
5400
5401         /* get the pkt queue info. This was put at wlc_sendctl or wlc_send for PDU */
5402         fifo = le16_to_cpu(txh->TxFrameID) & TXFID_QUEUE_MASK;
5403
5404         scb = NULL;
5405
5406         *fifop = fifo;
5407
5408         /* return if insufficient dma resources */
5409         if (TXAVAIL(wlc, fifo) < MAX_DMA_SEGS) {
5410                 /* Mark precedences related to this FIFO, unsendable */
5411                 WLC_TX_FIFO_CLEAR(wlc, fifo);
5412                 return -EBUSY;
5413         }
5414         return 0;
5415 }
5416
5417 /* init tx reported rate mechanism */
5418 void wlc_reprate_init(struct wlc_info *wlc)
5419 {
5420         int i;
5421         struct wlc_bsscfg *bsscfg;
5422
5423         FOREACH_BSS(wlc, i, bsscfg) {
5424                 wlc_bsscfg_reprate_init(bsscfg);
5425         }
5426 }
5427
5428 /* per bsscfg init tx reported rate mechanism */
5429 void wlc_bsscfg_reprate_init(struct wlc_bsscfg *bsscfg)
5430 {
5431         bsscfg->txrspecidx = 0;
5432         memset((char *)bsscfg->txrspec, 0, sizeof(bsscfg->txrspec));
5433 }
5434
5435 void wlc_default_rateset(struct wlc_info *wlc, wlc_rateset_t *rs)
5436 {
5437         wlc_rateset_default(rs, NULL, wlc->band->phytype, wlc->band->bandtype,
5438                             false, WLC_RATE_MASK_FULL, (bool) N_ENAB(wlc->pub),
5439                             CHSPEC_WLC_BW(wlc->default_bss->chanspec),
5440                             wlc->stf->txstreams);
5441 }
5442
5443 static void wlc_bss_default_init(struct wlc_info *wlc)
5444 {
5445         chanspec_t chanspec;
5446         struct wlcband *band;
5447         wlc_bss_info_t *bi = wlc->default_bss;
5448
5449         /* init default and target BSS with some sane initial values */
5450         memset((char *)(bi), 0, sizeof(wlc_bss_info_t));
5451         bi->beacon_period = ISSIM_ENAB(wlc->pub->sih) ? BEACON_INTERVAL_DEF_QT :
5452             BEACON_INTERVAL_DEFAULT;
5453         bi->dtim_period = ISSIM_ENAB(wlc->pub->sih) ? DTIM_INTERVAL_DEF_QT :
5454             DTIM_INTERVAL_DEFAULT;
5455
5456         /* fill the default channel as the first valid channel
5457          * starting from the 2G channels
5458          */
5459         chanspec = CH20MHZ_CHSPEC(1);
5460         wlc->home_chanspec = bi->chanspec = chanspec;
5461
5462         /* find the band of our default channel */
5463         band = wlc->band;
5464         if (NBANDS(wlc) > 1 && band->bandunit != CHSPEC_WLCBANDUNIT(chanspec))
5465                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
5466
5467         /* init bss rates to the band specific default rate set */
5468         wlc_rateset_default(&bi->rateset, NULL, band->phytype, band->bandtype,
5469                             false, WLC_RATE_MASK_FULL, (bool) N_ENAB(wlc->pub),
5470                             CHSPEC_WLC_BW(chanspec), wlc->stf->txstreams);
5471
5472         if (N_ENAB(wlc->pub))
5473                 bi->flags |= WLC_BSS_HT;
5474 }
5475
5476 static ratespec_t
5477 mac80211_wlc_set_nrate(struct wlc_info *wlc, struct wlcband *cur_band,
5478                        u32 int_val)
5479 {
5480         u8 stf = (int_val & NRATE_STF_MASK) >> NRATE_STF_SHIFT;
5481         u8 rate = int_val & NRATE_RATE_MASK;
5482         ratespec_t rspec;
5483         bool ismcs = ((int_val & NRATE_MCS_INUSE) == NRATE_MCS_INUSE);
5484         bool issgi = ((int_val & NRATE_SGI_MASK) >> NRATE_SGI_SHIFT);
5485         bool override_mcs_only = ((int_val & NRATE_OVERRIDE_MCS_ONLY)
5486                                   == NRATE_OVERRIDE_MCS_ONLY);
5487         int bcmerror = 0;
5488
5489         if (!ismcs) {
5490                 return (ratespec_t) rate;
5491         }
5492
5493         /* validate the combination of rate/mcs/stf is allowed */
5494         if (N_ENAB(wlc->pub) && ismcs) {
5495                 /* mcs only allowed when nmode */
5496                 if (stf > PHY_TXC1_MODE_SDM) {
5497                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid stf\n",
5498                                  WLCWLUNIT(wlc), __func__);
5499                         bcmerror = -EINVAL;
5500                         goto done;
5501                 }
5502
5503                 /* mcs 32 is a special case, DUP mode 40 only */
5504                 if (rate == 32) {
5505                         if (!CHSPEC_IS40(wlc->home_chanspec) ||
5506                             ((stf != PHY_TXC1_MODE_SISO)
5507                              && (stf != PHY_TXC1_MODE_CDD))) {
5508                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid mcs "
5509                                           "32\n", WLCWLUNIT(wlc), __func__);
5510                                 bcmerror = -EINVAL;
5511                                 goto done;
5512                         }
5513                         /* mcs > 7 must use stf SDM */
5514                 } else if (rate > HIGHEST_SINGLE_STREAM_MCS) {
5515                         /* mcs > 7 must use stf SDM */
5516                         if (stf != PHY_TXC1_MODE_SDM) {
5517                                 BCMMSG(wlc->wiphy, "wl%d: enabling "
5518                                          "SDM mode for mcs %d\n",
5519                                          WLCWLUNIT(wlc), rate);
5520                                 stf = PHY_TXC1_MODE_SDM;
5521                         }
5522                 } else {
5523                         /* MCS 0-7 may use SISO, CDD, and for phy_rev >= 3 STBC */
5524                         if ((stf > PHY_TXC1_MODE_STBC) ||
5525                             (!WLC_STBC_CAP_PHY(wlc)
5526                              && (stf == PHY_TXC1_MODE_STBC))) {
5527                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid STBC"
5528                                           "\n", WLCWLUNIT(wlc), __func__);
5529                                 bcmerror = -EINVAL;
5530                                 goto done;
5531                         }
5532                 }
5533         } else if (IS_OFDM(rate)) {
5534                 if ((stf != PHY_TXC1_MODE_CDD) && (stf != PHY_TXC1_MODE_SISO)) {
5535                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid OFDM\n",
5536                                   WLCWLUNIT(wlc), __func__);
5537                         bcmerror = -EINVAL;
5538                         goto done;
5539                 }
5540         } else if (IS_CCK(rate)) {
5541                 if ((cur_band->bandtype != WLC_BAND_2G)
5542                     || (stf != PHY_TXC1_MODE_SISO)) {
5543                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid CCK\n",
5544                                   WLCWLUNIT(wlc), __func__);
5545                         bcmerror = -EINVAL;
5546                         goto done;
5547                 }
5548         } else {
5549                 wiphy_err(wlc->wiphy, "wl%d: %s: Unknown rate type\n",
5550                           WLCWLUNIT(wlc), __func__);
5551                 bcmerror = -EINVAL;
5552                 goto done;
5553         }
5554         /* make sure multiple antennae are available for non-siso rates */
5555         if ((stf != PHY_TXC1_MODE_SISO) && (wlc->stf->txstreams == 1)) {
5556                 wiphy_err(wlc->wiphy, "wl%d: %s: SISO antenna but !SISO "
5557                           "request\n", WLCWLUNIT(wlc), __func__);
5558                 bcmerror = -EINVAL;
5559                 goto done;
5560         }
5561
5562         rspec = rate;
5563         if (ismcs) {
5564                 rspec |= RSPEC_MIMORATE;
5565                 /* For STBC populate the STC field of the ratespec */
5566                 if (stf == PHY_TXC1_MODE_STBC) {
5567                         u8 stc;
5568                         stc = 1;        /* Nss for single stream is always 1 */
5569                         rspec |= (stc << RSPEC_STC_SHIFT);
5570                 }
5571         }
5572
5573         rspec |= (stf << RSPEC_STF_SHIFT);
5574
5575         if (override_mcs_only)
5576                 rspec |= RSPEC_OVERRIDE_MCS_ONLY;
5577
5578         if (issgi)
5579                 rspec |= RSPEC_SHORT_GI;
5580
5581         if ((rate != 0)
5582             && !wlc_valid_rate(wlc, rspec, cur_band->bandtype, true)) {
5583                 return rate;
5584         }
5585
5586         return rspec;
5587 done:
5588         return rate;
5589 }
5590
5591 /* formula:  IDLE_BUSY_RATIO_X_16 = (100-duty_cycle)/duty_cycle*16 */
5592 static int
5593 wlc_duty_cycle_set(struct wlc_info *wlc, int duty_cycle, bool isOFDM,
5594                    bool writeToShm)
5595 {
5596         int idle_busy_ratio_x_16 = 0;
5597         uint offset =
5598             isOFDM ? M_TX_IDLE_BUSY_RATIO_X_16_OFDM :
5599             M_TX_IDLE_BUSY_RATIO_X_16_CCK;
5600         if (duty_cycle > 100 || duty_cycle < 0) {
5601                 wiphy_err(wlc->wiphy, "wl%d:  duty cycle value off limit\n",
5602                           wlc->pub->unit);
5603                 return -EINVAL;
5604         }
5605         if (duty_cycle)
5606                 idle_busy_ratio_x_16 = (100 - duty_cycle) * 16 / duty_cycle;
5607         /* Only write to shared memory  when wl is up */
5608         if (writeToShm)
5609                 wlc_write_shm(wlc, offset, (u16) idle_busy_ratio_x_16);
5610
5611         if (isOFDM)
5612                 wlc->tx_duty_cycle_ofdm = (u16) duty_cycle;
5613         else
5614                 wlc->tx_duty_cycle_cck = (u16) duty_cycle;
5615
5616         return 0;
5617 }
5618
5619 /* Read a single u16 from shared memory.
5620  * SHM 'offset' needs to be an even address
5621  */
5622 u16 wlc_read_shm(struct wlc_info *wlc, uint offset)
5623 {
5624         return wlc_bmac_read_shm(wlc->hw, offset);
5625 }
5626
5627 /* Write a single u16 to shared memory.
5628  * SHM 'offset' needs to be an even address
5629  */
5630 void wlc_write_shm(struct wlc_info *wlc, uint offset, u16 v)
5631 {
5632         wlc_bmac_write_shm(wlc->hw, offset, v);
5633 }
5634
5635 /* Copy a buffer to shared memory.
5636  * SHM 'offset' needs to be an even address and
5637  * Buffer length 'len' must be an even number of bytes
5638  */
5639 void wlc_copyto_shm(struct wlc_info *wlc, uint offset, const void *buf, int len)
5640 {
5641         /* offset and len need to be even */
5642         if (len <= 0 || (offset & 1) || (len & 1))
5643                 return;
5644
5645         wlc_bmac_copyto_objmem(wlc->hw, offset, buf, len, OBJADDR_SHM_SEL);
5646
5647 }
5648
5649 /* wrapper BMAC functions to for HIGH driver access */
5650 void wlc_mctrl(struct wlc_info *wlc, u32 mask, u32 val)
5651 {
5652         wlc_bmac_mctrl(wlc->hw, mask, val);
5653 }
5654
5655 void wlc_mhf(struct wlc_info *wlc, u8 idx, u16 mask, u16 val, int bands)
5656 {
5657         wlc_bmac_mhf(wlc->hw, idx, mask, val, bands);
5658 }
5659
5660 int wlc_xmtfifo_sz_get(struct wlc_info *wlc, uint fifo, uint *blocks)
5661 {
5662         return wlc_bmac_xmtfifo_sz_get(wlc->hw, fifo, blocks);
5663 }
5664
5665 void wlc_write_template_ram(struct wlc_info *wlc, int offset, int len,
5666                             void *buf)
5667 {
5668         wlc_bmac_write_template_ram(wlc->hw, offset, len, buf);
5669 }
5670
5671 void wlc_write_hw_bcntemplates(struct wlc_info *wlc, void *bcn, int len,
5672                                bool both)
5673 {
5674         wlc_bmac_write_hw_bcntemplates(wlc->hw, bcn, len, both);
5675 }
5676
5677 void
5678 wlc_set_addrmatch(struct wlc_info *wlc, int match_reg_offset,
5679                   const u8 *addr)
5680 {
5681         wlc_bmac_set_addrmatch(wlc->hw, match_reg_offset, addr);
5682         if (match_reg_offset == RCM_BSSID_OFFSET)
5683                 memcpy(wlc->cfg->BSSID, addr, ETH_ALEN);
5684 }
5685
5686 void wlc_pllreq(struct wlc_info *wlc, bool set, mbool req_bit)
5687 {
5688         wlc_bmac_pllreq(wlc->hw, set, req_bit);
5689 }
5690
5691 void wlc_reset_bmac_done(struct wlc_info *wlc)
5692 {
5693 }
5694
5695 /* check for the particular priority flow control bit being set */
5696 bool
5697 wlc_txflowcontrol_prio_isset(struct wlc_info *wlc, struct wlc_txq_info *q,
5698                              int prio)
5699 {
5700         uint prio_mask;
5701
5702         if (prio == ALLPRIO) {
5703                 prio_mask = TXQ_STOP_FOR_PRIOFC_MASK;
5704         } else {
5705                 prio_mask = NBITVAL(prio);
5706         }
5707
5708         return (q->stopped & prio_mask) == prio_mask;
5709 }
5710
5711 /* propagate the flow control to all interfaces using the given tx queue */
5712 void wlc_txflowcontrol(struct wlc_info *wlc, struct wlc_txq_info *qi,
5713                        bool on, int prio)
5714 {
5715         uint prio_bits;
5716         uint cur_bits;
5717
5718         BCMMSG(wlc->wiphy, "flow control kicks in\n");
5719
5720         if (prio == ALLPRIO) {
5721                 prio_bits = TXQ_STOP_FOR_PRIOFC_MASK;
5722         } else {
5723                 prio_bits = NBITVAL(prio);
5724         }
5725
5726         cur_bits = qi->stopped & prio_bits;
5727
5728         /* Check for the case of no change and return early
5729          * Otherwise update the bit and continue
5730          */
5731         if (on) {
5732                 if (cur_bits == prio_bits) {
5733                         return;
5734                 }
5735                 mboolset(qi->stopped, prio_bits);
5736         } else {
5737                 if (cur_bits == 0) {
5738                         return;
5739                 }
5740                 mboolclr(qi->stopped, prio_bits);
5741         }
5742
5743         /* If there is a flow control override we will not change the external
5744          * flow control state.
5745          */
5746         if (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK) {
5747                 return;
5748         }
5749
5750         wlc_txflowcontrol_signal(wlc, qi, on, prio);
5751 }
5752
5753 void
5754 wlc_txflowcontrol_override(struct wlc_info *wlc, struct wlc_txq_info *qi,
5755                            bool on, uint override)
5756 {
5757         uint prev_override;
5758
5759         prev_override = (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK);
5760
5761         /* Update the flow control bits and do an early return if there is
5762          * no change in the external flow control state.
5763          */
5764         if (on) {
5765                 mboolset(qi->stopped, override);
5766                 /* if there was a previous override bit on, then setting this
5767                  * makes no difference.
5768                  */
5769                 if (prev_override) {
5770                         return;
5771                 }
5772
5773                 wlc_txflowcontrol_signal(wlc, qi, ON, ALLPRIO);
5774         } else {
5775                 mboolclr(qi->stopped, override);
5776                 /* clearing an override bit will only make a difference for
5777                  * flow control if it was the only bit set. For any other
5778                  * override setting, just return
5779                  */
5780                 if (prev_override != override) {
5781                         return;
5782                 }
5783
5784                 if (qi->stopped == 0) {
5785                         wlc_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
5786                 } else {
5787                         int prio;
5788
5789                         for (prio = MAXPRIO; prio >= 0; prio--) {
5790                                 if (!mboolisset(qi->stopped, NBITVAL(prio)))
5791                                         wlc_txflowcontrol_signal(wlc, qi, OFF,
5792                                                                  prio);
5793                         }
5794                 }
5795         }
5796 }
5797
5798 static void wlc_txflowcontrol_reset(struct wlc_info *wlc)
5799 {
5800         struct wlc_txq_info *qi;
5801
5802         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
5803                 if (qi->stopped) {
5804                         wlc_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
5805                         qi->stopped = 0;
5806                 }
5807         }
5808 }
5809
5810 static void
5811 wlc_txflowcontrol_signal(struct wlc_info *wlc, struct wlc_txq_info *qi, bool on,
5812                          int prio)
5813 {
5814 #ifdef NON_FUNCTIONAL
5815         /* wlcif_list is never filled so this function is not functional */
5816         struct wlc_if *wlcif;
5817
5818         for (wlcif = wlc->wlcif_list; wlcif != NULL; wlcif = wlcif->next) {
5819                 if (wlcif->qi == qi && wlcif->flags & WLC_IF_LINKED)
5820                         wl_txflowcontrol(wlc->wl, wlcif->wlif, on, prio);
5821         }
5822 #endif
5823 }
5824
5825 static struct wlc_txq_info *wlc_txq_alloc(struct wlc_info *wlc)
5826 {
5827         struct wlc_txq_info *qi, *p;
5828
5829         qi = kzalloc(sizeof(struct wlc_txq_info), GFP_ATOMIC);
5830         if (qi != NULL) {
5831                 /*
5832                  * Have enough room for control packets along with HI watermark
5833                  * Also, add room to txq for total psq packets if all the SCBs
5834                  * leave PS mode. The watermark for flowcontrol to OS packets
5835                  * will remain the same
5836                  */
5837                 bcm_pktq_init(&qi->q, WLC_PREC_COUNT,
5838                           (2 * wlc->pub->tunables->datahiwat) + PKTQ_LEN_DEFAULT
5839                           + wlc->pub->psq_pkts_total);
5840
5841                 /* add this queue to the the global list */
5842                 p = wlc->tx_queues;
5843                 if (p == NULL) {
5844                         wlc->tx_queues = qi;
5845                 } else {
5846                         while (p->next != NULL)
5847                                 p = p->next;
5848                         p->next = qi;
5849                 }
5850         }
5851         return qi;
5852 }
5853
5854 static void wlc_txq_free(struct wlc_info *wlc, struct wlc_txq_info *qi)
5855 {
5856         struct wlc_txq_info *p;
5857
5858         if (qi == NULL)
5859                 return;
5860
5861         /* remove the queue from the linked list */
5862         p = wlc->tx_queues;
5863         if (p == qi)
5864                 wlc->tx_queues = p->next;
5865         else {
5866                 while (p != NULL && p->next != qi)
5867                         p = p->next;
5868                 if (p != NULL)
5869                         p->next = p->next->next;
5870         }
5871
5872         kfree(qi);
5873 }
5874
5875 /*
5876  * Flag 'scan in progress' to withhold dynamic phy calibration
5877  */
5878 void wlc_scan_start(struct wlc_info *wlc)
5879 {
5880         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, true);
5881 }
5882
5883 void wlc_scan_stop(struct wlc_info *wlc)
5884 {
5885         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, false);
5886 }
5887
5888 void wlc_associate_upd(struct wlc_info *wlc, bool state)
5889 {
5890         wlc->pub->associated = state;
5891         wlc->cfg->associated = state;
5892 }
5893
5894 /*
5895  * When a remote STA/AP is removed by Mac80211, or when it can no longer accept
5896  * AMPDU traffic, packets pending in hardware have to be invalidated so that
5897  * when later on hardware releases them, they can be handled appropriately.
5898  */
5899 void wlc_inval_dma_pkts(struct wlc_hw_info *hw,
5900                                struct ieee80211_sta *sta,
5901                                void (*dma_callback_fn))
5902 {
5903         struct dma_pub *dmah;
5904         int i;
5905         for (i = 0; i < NFIFO; i++) {
5906                 dmah = hw->di[i];
5907                 if (dmah != NULL)
5908                         dma_walk_packets(dmah, dma_callback_fn, sta);
5909         }
5910 }
5911
5912 int wlc_get_curband(struct wlc_info *wlc)
5913 {
5914         return wlc->band->bandunit;
5915 }
5916
5917 void wlc_wait_for_tx_completion(struct wlc_info *wlc, bool drop)
5918 {
5919         /* flush packet queue when requested */
5920         if (drop)
5921                 bcm_pktq_flush(&wlc->pkt_queue->q, false, NULL, NULL);
5922
5923         /* wait for queue and DMA fifos to run dry */
5924         while (!pktq_empty(&wlc->pkt_queue->q) ||
5925                TXPKTPENDTOT(wlc) > 0) {
5926                 wl_msleep(wlc->wl, 1);
5927         }
5928 }
5929
5930 int wlc_set_par(struct wlc_info *wlc, enum wlc_par_id par_id, int int_val)
5931 {
5932         int err = 0;
5933
5934         switch (par_id) {
5935         case IOV_BCN_LI_BCN:
5936                 wlc->bcn_li_bcn = (u8) int_val;
5937                 if (wlc->pub->up)
5938                         wlc_bcn_li_upd(wlc);
5939                 break;
5940                 /* As long as override is false, this only sets the *user*
5941                    targets. User can twiddle this all he wants with no harm.
5942                    wlc_phy_txpower_set() explicitly sets override to false if
5943                    not internal or test.
5944                  */
5945         case IOV_QTXPOWER:{
5946                 u8 qdbm;
5947                 bool override;
5948
5949                 /* Remove override bit and clip to max qdbm value */
5950                 qdbm = (u8)min_t(u32, (int_val & ~WL_TXPWR_OVERRIDE), 0xff);
5951                 /* Extract override setting */
5952                 override = (int_val & WL_TXPWR_OVERRIDE) ? true : false;
5953                 err =
5954                     wlc_phy_txpower_set(wlc->band->pi, qdbm, override);
5955                 break;
5956                 }
5957         case IOV_MPC:
5958                 wlc->mpc = (bool)int_val;
5959                 wlc_radio_mpc_upd(wlc);
5960                 break;
5961         default:
5962                 err = -ENOTSUPP;
5963         }
5964         return err;
5965 }
5966
5967 int wlc_get_par(struct wlc_info *wlc, enum wlc_par_id par_id, int *ret_int_ptr)
5968 {
5969         int err = 0;
5970
5971         switch (par_id) {
5972         case IOV_BCN_LI_BCN:
5973                 *ret_int_ptr = wlc->bcn_li_bcn;
5974                 break;
5975         case IOV_QTXPOWER: {
5976                 uint qdbm;
5977                 bool override;
5978
5979                 err = wlc_phy_txpower_get(wlc->band->pi, &qdbm,
5980                         &override);
5981                 if (err != 0)
5982                         return err;
5983
5984                 /* Return qdbm units */
5985                 *ret_int_ptr =
5986                     qdbm | (override ? WL_TXPWR_OVERRIDE : 0);
5987                 break;
5988                 }
5989         case IOV_MPC:
5990                 *ret_int_ptr = (s32) wlc->mpc;
5991                 break;
5992         default:
5993                 err = -ENOTSUPP;
5994         }
5995         return err;
5996 }