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