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