]> Pileus Git - ~andy/linux/blob - drivers/staging/brcm80211/brcmsmac/wlc_main.c
staging: brcm80211: honour basic rate configuration from mac80211
[~andy/linux] / 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 <siutils.h>
27 #include <pcicfg.h>
28 #include <bcmsrom.h>
29 #include <wlioctl.h>
30 #include <sbhnddma.h>
31 #include <hnddma.h>
32 #include <hndpmu.h>
33
34 #include "d11.h"
35 #include "wlc_types.h"
36 #include "wlc_cfg.h"
37 #include "wlc_rate.h"
38 #include "wlc_scb.h"
39 #include "wlc_pub.h"
40 #include "wlc_key.h"
41 #include "wlc_bsscfg.h"
42 #include "phy/wlc_phy_hal.h"
43 #include "wlc_channel.h"
44 #include "wlc_main.h"
45 #include "wlc_bmac.h"
46 #include "wlc_phy_hal.h"
47 #include "wlc_phy_shim.h"
48 #include "wlc_antsel.h"
49 #include "wlc_stf.h"
50 #include "wlc_ampdu.h"
51 #include "wl_export.h"
52 #include "wlc_alloc.h"
53 #include "wl_dbg.h"
54
55 #include "wl_mac80211.h"
56
57 /*
58  *      Disable statistics counting for WME
59  */
60 #define WLCNTSET(a, b)
61 #define WLCNTINCR(a)
62 #define WLCNTADD(a, b)
63
64 /*
65  * WPA(2) definitions
66  */
67 #define RSN_CAP_4_REPLAY_CNTRS          2
68 #define RSN_CAP_16_REPLAY_CNTRS         3
69
70 #define WPA_CAP_4_REPLAY_CNTRS          RSN_CAP_4_REPLAY_CNTRS
71 #define WPA_CAP_16_REPLAY_CNTRS         RSN_CAP_16_REPLAY_CNTRS
72
73 /*
74  * Indication for txflowcontrol that all priority bits in
75  * TXQ_STOP_FOR_PRIOFC_MASK are to be considered.
76  */
77 #define ALLPRIO         -1
78
79 /*
80  * buffer length needed for wlc_format_ssid
81  * 32 SSID chars, max of 4 chars for each SSID char "\xFF", plus NULL.
82  */
83 #define SSID_FMT_BUF_LEN        ((4 * IEEE80211_MAX_SSID_LEN) + 1)
84
85 #define TIMER_INTERVAL_WATCHDOG 1000    /* watchdog timer, in unit of ms */
86 #define TIMER_INTERVAL_RADIOCHK 800     /* radio monitor timer, in unit of ms */
87
88 #ifndef WLC_MPC_MAX_DELAYCNT
89 #define WLC_MPC_MAX_DELAYCNT    10      /* Max MPC timeout, in unit of watchdog */
90 #endif
91 #define WLC_MPC_MIN_DELAYCNT    1       /* Min MPC timeout, in unit of watchdog */
92 #define WLC_MPC_THRESHOLD       3       /* MPC count threshold level */
93
94 #define BEACON_INTERVAL_DEFAULT 100     /* beacon interval, in unit of 1024TU */
95 #define DTIM_INTERVAL_DEFAULT   3       /* DTIM interval, in unit of beacon interval */
96
97 /* Scale down delays to accommodate QT slow speed */
98 #define BEACON_INTERVAL_DEF_QT  20      /* beacon interval, in unit of 1024TU */
99 #define DTIM_INTERVAL_DEF_QT    1       /* DTIM interval, in unit of beacon interval */
100
101 #define TBTT_ALIGN_LEEWAY_US    100     /* min leeway before first TBTT in us */
102
103 /*
104  * driver maintains internal 'tick'(wlc->pub->now) which increments in 1s OS timer(soft
105  * watchdog) it is not a wall clock and won't increment when driver is in "down" state
106  * this low resolution driver tick can be used for maintenance tasks such as phy
107  * calibration and scb update
108  */
109
110 /* watchdog trigger mode: OSL timer or TBTT */
111 #define WLC_WATCHDOG_TBTT(wlc) \
112         (wlc->stas_associated > 0 && wlc->PM != PM_OFF && wlc->pub->align_wd_tbtt)
113
114 /* To inform the ucode of the last mcast frame posted so that it can clear moredata bit */
115 #define BCMCFID(wlc, fid) wlc_bmac_write_shm((wlc)->hw, M_BCMC_FID, (fid))
116
117 #define WLC_WAR16165(wlc) (wlc->pub->sih->bustype == PCI_BUS && \
118                                 (!AP_ENAB(wlc->pub)) && (wlc->war16165))
119
120 /* debug/trace */
121 uint wl_msg_level =
122 #if defined(BCMDBG)
123     WL_ERROR_VAL;
124 #else
125     0;
126 #endif                          /* BCMDBG */
127
128 /* Find basic rate for a given rate */
129 #define WLC_BASIC_RATE(wlc, rspec)      (IS_MCS(rspec) ? \
130                         (wlc)->band->basic_rate[mcs_table[rspec & RSPEC_RATE_MASK].leg_ofdm] : \
131                         (wlc)->band->basic_rate[rspec & RSPEC_RATE_MASK])
132
133 #define FRAMETYPE(r, mimoframe) (IS_MCS(r) ? mimoframe  : (IS_CCK(r) ? FT_CCK : FT_OFDM))
134
135 #define RFDISABLE_DEFAULT       10000000        /* rfdisable delay timer 500 ms, runs of ALP clock */
136
137 #define WLC_TEMPSENSE_PERIOD            10      /* 10 second timeout */
138
139 #define SCAN_IN_PROGRESS(x)     0
140
141 #define EPI_VERSION_NUM         0x054b0b00
142
143 #ifdef BCMDBG
144 /* pointer to most recently allocated wl/wlc */
145 static struct wlc_info *wlc_info_dbg = (struct wlc_info *) (NULL);
146 #endif
147
148 /* IOVar table */
149
150 /* Parameter IDs, for use only internally to wlc -- in the wlc_iovars
151  * table and by the wlc_doiovar() function.  No ordering is imposed:
152  * the table is keyed by name, and the function uses a switch.
153  */
154 enum {
155         IOV_MPC = 1,
156         IOV_RTSTHRESH,
157         IOV_QTXPOWER,
158         IOV_BCN_LI_BCN,         /* Beacon listen interval in # of beacons */
159         IOV_LAST                /* In case of a need to check max ID number */
160 };
161
162 const bcm_iovar_t wlc_iovars[] = {
163         {"mpc", IOV_MPC, (0), IOVT_BOOL, 0},
164         {"rtsthresh", IOV_RTSTHRESH, (IOVF_WHL), IOVT_UINT16, 0},
165         {"qtxpower", IOV_QTXPOWER, (IOVF_WHL), IOVT_UINT32, 0},
166         {"bcn_li_bcn", IOV_BCN_LI_BCN, (0), IOVT_UINT8, 0},
167         {NULL, 0, 0, 0, 0}
168 };
169
170 const u8 prio2fifo[NUMPRIO] = {
171         TX_AC_BE_FIFO,          /* 0    BE      AC_BE   Best Effort */
172         TX_AC_BK_FIFO,          /* 1    BK      AC_BK   Background */
173         TX_AC_BK_FIFO,          /* 2    --      AC_BK   Background */
174         TX_AC_BE_FIFO,          /* 3    EE      AC_BE   Best Effort */
175         TX_AC_VI_FIFO,          /* 4    CL      AC_VI   Video */
176         TX_AC_VI_FIFO,          /* 5    VI      AC_VI   Video */
177         TX_AC_VO_FIFO,          /* 6    VO      AC_VO   Voice */
178         TX_AC_VO_FIFO           /* 7    NC      AC_VO   Voice */
179 };
180
181 /* precedences numbers for wlc queues. These are twice as may levels as
182  * 802.1D priorities.
183  * Odd numbers are used for HI priority traffic at same precedence levels
184  * These constants are used ONLY by wlc_prio2prec_map.  Do not use them elsewhere.
185  */
186 #define _WLC_PREC_NONE          0       /* None = - */
187 #define _WLC_PREC_BK            2       /* BK - Background */
188 #define _WLC_PREC_BE            4       /* BE - Best-effort */
189 #define _WLC_PREC_EE            6       /* EE - Excellent-effort */
190 #define _WLC_PREC_CL            8       /* CL - Controlled Load */
191 #define _WLC_PREC_VI            10      /* Vi - Video */
192 #define _WLC_PREC_VO            12      /* Vo - Voice */
193 #define _WLC_PREC_NC            14      /* NC - Network Control */
194
195 /* 802.1D Priority to precedence queue mapping */
196 const u8 wlc_prio2prec_map[] = {
197         _WLC_PREC_BE,           /* 0 BE - Best-effort */
198         _WLC_PREC_BK,           /* 1 BK - Background */
199         _WLC_PREC_NONE,         /* 2 None = - */
200         _WLC_PREC_EE,           /* 3 EE - Excellent-effort */
201         _WLC_PREC_CL,           /* 4 CL - Controlled Load */
202         _WLC_PREC_VI,           /* 5 Vi - Video */
203         _WLC_PREC_VO,           /* 6 Vo - Voice */
204         _WLC_PREC_NC,           /* 7 NC - Network Control */
205 };
206
207 /* Sanity check for tx_prec_map and fifo synchup
208  * Either there are some packets pending for the fifo, else if fifo is empty then
209  * all the corresponding precmap bits should be set
210  */
211 #define WLC_TX_FIFO_CHECK(wlc, fifo) (TXPKTPENDGET((wlc), (fifo)) ||    \
212         (TXPKTPENDGET((wlc), (fifo)) == 0 && \
213         ((wlc)->tx_prec_map & (wlc)->fifo2prec_map[(fifo)]) == \
214         (wlc)->fifo2prec_map[(fifo)]))
215
216 /* TX FIFO number to WME/802.1E Access Category */
217 const u8 wme_fifo2ac[] = { AC_BK, AC_BE, AC_VI, AC_VO, AC_BE, AC_BE };
218
219 /* WME/802.1E Access Category to TX FIFO number */
220 static const u8 wme_ac2fifo[] = { 1, 0, 2, 3 };
221
222 static bool in_send_q = false;
223
224 /* Shared memory location index for various AC params */
225 #define wme_shmemacindex(ac)    wme_ac2fifo[ac]
226
227 #ifdef BCMDBG
228 static const char *fifo_names[] = {
229         "AC_BK", "AC_BE", "AC_VI", "AC_VO", "BCMC", "ATIM" };
230 #else
231 static const char fifo_names[6][0];
232 #endif
233
234 static const u8 acbitmap2maxprio[] = {
235         PRIO_8021D_BE, PRIO_8021D_BE, PRIO_8021D_BK, PRIO_8021D_BK,
236         PRIO_8021D_VI, PRIO_8021D_VI, PRIO_8021D_VI, PRIO_8021D_VI,
237         PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO,
238         PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO
239 };
240
241 /* currently the best mechanism for determining SIFS is the band in use */
242 #define SIFS(band) ((band)->bandtype == WLC_BAND_5G ? APHY_SIFS_TIME : BPHY_SIFS_TIME);
243
244 /* value for # replay counters currently supported */
245 #define WLC_REPLAY_CNTRS_VALUE  WPA_CAP_16_REPLAY_CNTRS
246
247 /* local prototypes */
248 static u16 BCMFASTPATH wlc_d11hdrs_mac80211(struct wlc_info *wlc,
249                                                struct ieee80211_hw *hw,
250                                                struct sk_buff *p,
251                                                struct scb *scb, uint frag,
252                                                uint nfrags, uint queue,
253                                                uint next_frag_len,
254                                                wsec_key_t *key,
255                                                ratespec_t rspec_override);
256
257 static void wlc_ctrupd_cache(u16 cur_stat, u16 *macstat_snapshot, u32 *macstat);
258 static void wlc_bss_default_init(struct wlc_info *wlc);
259 static void wlc_ucode_mac_upd(struct wlc_info *wlc);
260 static ratespec_t mac80211_wlc_set_nrate(struct wlc_info *wlc,
261                                          struct wlcband *cur_band, u32 int_val);
262 static void wlc_tx_prec_map_init(struct wlc_info *wlc);
263 static void wlc_watchdog(void *arg);
264 static void wlc_watchdog_by_timer(void *arg);
265 static u16 wlc_rate_shm_offset(struct wlc_info *wlc, u8 rate);
266 static int wlc_set_rateset(struct wlc_info *wlc, wlc_rateset_t *rs_arg);
267 static int wlc_iovar_rangecheck(struct wlc_info *wlc, u32 val,
268                                 const bcm_iovar_t *vi);
269 static u8 wlc_local_constraint_qdbm(struct wlc_info *wlc);
270
271 /* send and receive */
272 static struct wlc_txq_info *wlc_txq_alloc(struct wlc_info *wlc);
273 static void wlc_txq_free(struct wlc_info *wlc,
274                          struct wlc_txq_info *qi);
275 static void wlc_txflowcontrol_signal(struct wlc_info *wlc,
276                                      struct wlc_txq_info *qi,
277                                      bool on, int prio);
278 static void wlc_txflowcontrol_reset(struct wlc_info *wlc);
279 static u16 wlc_compute_airtime(struct wlc_info *wlc, ratespec_t rspec,
280                                   uint length);
281 static void wlc_compute_cck_plcp(struct wlc_info *wlc, ratespec_t rate,
282                                  uint length, u8 *plcp);
283 static void wlc_compute_ofdm_plcp(ratespec_t rate, uint length, u8 *plcp);
284 static void wlc_compute_mimo_plcp(ratespec_t rate, uint length, u8 *plcp);
285 static u16 wlc_compute_frame_dur(struct wlc_info *wlc, ratespec_t rate,
286                                     u8 preamble_type, uint next_frag_len);
287 static void wlc_recvctl(struct wlc_info *wlc,
288                         d11rxhdr_t *rxh, struct sk_buff *p);
289 static uint wlc_calc_frame_len(struct wlc_info *wlc, ratespec_t rate,
290                                u8 preamble_type, uint dur);
291 static uint wlc_calc_ack_time(struct wlc_info *wlc, ratespec_t rate,
292                               u8 preamble_type);
293 static uint wlc_calc_cts_time(struct wlc_info *wlc, ratespec_t rate,
294                               u8 preamble_type);
295 /* interrupt, up/down, band */
296 static void wlc_setband(struct wlc_info *wlc, uint bandunit);
297 static chanspec_t wlc_init_chanspec(struct wlc_info *wlc);
298 static void wlc_bandinit_ordered(struct wlc_info *wlc, chanspec_t chanspec);
299 static void wlc_bsinit(struct wlc_info *wlc);
300 static int wlc_duty_cycle_set(struct wlc_info *wlc, int duty_cycle, bool isOFDM,
301                               bool writeToShm);
302 static void wlc_radio_hwdisable_upd(struct wlc_info *wlc);
303 static bool wlc_radio_monitor_start(struct wlc_info *wlc);
304 static void wlc_radio_timer(void *arg);
305 static void wlc_radio_enable(struct wlc_info *wlc);
306 static void wlc_radio_upd(struct wlc_info *wlc);
307
308 /* scan, association, BSS */
309 static uint wlc_calc_ba_time(struct wlc_info *wlc, ratespec_t rate,
310                              u8 preamble_type);
311 static void wlc_update_mimo_band_bwcap(struct wlc_info *wlc, u8 bwcap);
312 static void wlc_ht_update_sgi_rx(struct wlc_info *wlc, int val);
313 static void wlc_ht_update_ldpc(struct wlc_info *wlc, s8 val);
314 static void wlc_war16165(struct wlc_info *wlc, bool tx);
315
316 static void wlc_wme_retries_write(struct wlc_info *wlc);
317 static bool wlc_attach_stf_ant_init(struct wlc_info *wlc);
318 static uint wlc_attach_module(struct wlc_info *wlc);
319 static void wlc_detach_module(struct wlc_info *wlc);
320 static void wlc_timers_deinit(struct wlc_info *wlc);
321 static void wlc_down_led_upd(struct wlc_info *wlc);
322 static uint wlc_down_del_timer(struct wlc_info *wlc);
323 static void wlc_ofdm_rateset_war(struct wlc_info *wlc);
324 static int _wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
325                       struct wlc_if *wlcif);
326
327 #if defined(BCMDBG)
328 void wlc_get_rcmta(struct wlc_info *wlc, int idx, u8 *addr)
329 {
330         d11regs_t *regs = wlc->regs;
331         u32 v32;
332
333         WL_TRACE("wl%d: %s\n", WLCWLUNIT(wlc), __func__);
334
335         W_REG(&regs->objaddr, (OBJADDR_RCMTA_SEL | (idx * 2)));
336         (void)R_REG(&regs->objaddr);
337         v32 = R_REG(&regs->objdata);
338         addr[0] = (u8) v32;
339         addr[1] = (u8) (v32 >> 8);
340         addr[2] = (u8) (v32 >> 16);
341         addr[3] = (u8) (v32 >> 24);
342         W_REG(&regs->objaddr, (OBJADDR_RCMTA_SEL | ((idx * 2) + 1)));
343         (void)R_REG(&regs->objaddr);
344         v32 = R_REG(&regs->objdata);
345         addr[4] = (u8) v32;
346         addr[5] = (u8) (v32 >> 8);
347 }
348 #endif                          /* defined(BCMDBG) */
349
350 /* keep the chip awake if needed */
351 bool wlc_stay_awake(struct wlc_info *wlc)
352 {
353         return true;
354 }
355
356 /* conditions under which the PM bit should be set in outgoing frames and STAY_AWAKE is meaningful
357  */
358 bool wlc_ps_allowed(struct wlc_info *wlc)
359 {
360         int idx;
361         struct wlc_bsscfg *cfg;
362
363         /* disallow PS when one of the following global conditions meets */
364         if (!wlc->pub->associated || !wlc->PMenabled || wlc->PM_override)
365                 return false;
366
367         /* disallow PS when one of these meets when not scanning */
368         if (!wlc->PMblocked) {
369                 if (AP_ACTIVE(wlc) || wlc->monitor)
370                         return false;
371         }
372
373         FOREACH_AS_STA(wlc, idx, cfg) {
374                 /* disallow PS when one of the following bsscfg specific conditions meets */
375                 if (!cfg->BSS || !WLC_PORTOPEN(cfg))
376                         return false;
377
378                 if (!cfg->dtim_programmed)
379                         return false;
380         }
381
382         return true;
383 }
384
385 void wlc_reset(struct wlc_info *wlc)
386 {
387         WL_TRACE("wl%d: wlc_reset\n", wlc->pub->unit);
388
389         wlc->check_for_unaligned_tbtt = false;
390
391         /* slurp up hw mac counters before core reset */
392         wlc_statsupd(wlc);
393
394         /* reset our snapshot of macstat counters */
395         memset((char *)wlc->core->macstat_snapshot, 0,
396                 sizeof(macstat_t));
397
398         wlc_bmac_reset(wlc->hw);
399         wlc_ampdu_reset(wlc->ampdu);
400         wlc->txretried = 0;
401
402 }
403
404 void wlc_fatal_error(struct wlc_info *wlc)
405 {
406         wiphy_err(wlc->wiphy, "wl%d: fatal error, reinitializing\n",
407                   wlc->pub->unit);
408         wl_init(wlc->wl);
409 }
410
411 /* Return the channel the driver should initialize during wlc_init.
412  * the channel may have to be changed from the currently configured channel
413  * if other configurations are in conflict (bandlocked, 11n mode disabled,
414  * invalid channel for current country, etc.)
415  */
416 static chanspec_t wlc_init_chanspec(struct wlc_info *wlc)
417 {
418         chanspec_t chanspec =
419             1 | WL_CHANSPEC_BW_20 | WL_CHANSPEC_CTL_SB_NONE |
420             WL_CHANSPEC_BAND_2G;
421
422         /* make sure the channel is on the supported band if we are band-restricted */
423         if (wlc->bandlocked || NBANDS(wlc) == 1) {
424                 ASSERT(CHSPEC_WLCBANDUNIT(chanspec) == wlc->band->bandunit);
425         }
426         ASSERT(wlc_valid_chanspec_db(wlc->cmi, chanspec));
427         return chanspec;
428 }
429
430 struct scb global_scb;
431
432 static void wlc_init_scb(struct wlc_info *wlc, struct scb *scb)
433 {
434         int i;
435         scb->flags = SCB_WMECAP | SCB_HTCAP;
436         for (i = 0; i < NUMPRIO; i++)
437                 scb->seqnum[i] = 0;
438 }
439
440 void wlc_init(struct wlc_info *wlc)
441 {
442         d11regs_t *regs;
443         chanspec_t chanspec;
444         int i;
445         struct wlc_bsscfg *bsscfg;
446         bool mute = false;
447
448         WL_TRACE("wl%d: wlc_init\n", wlc->pub->unit);
449
450         regs = wlc->regs;
451
452         /* This will happen if a big-hammer was executed. In that case, we want to go back
453          * to the channel that we were on and not new channel
454          */
455         if (wlc->pub->associated)
456                 chanspec = wlc->home_chanspec;
457         else
458                 chanspec = wlc_init_chanspec(wlc);
459
460         wlc_bmac_init(wlc->hw, chanspec, mute);
461
462         wlc->seckeys = wlc_bmac_read_shm(wlc->hw, M_SECRXKEYS_PTR) * 2;
463         if (wlc->machwcap & MCAP_TKIPMIC)
464                 wlc->tkmickeys =
465                     wlc_bmac_read_shm(wlc->hw, M_TKMICKEYS_PTR) * 2;
466
467         /* update beacon listen interval */
468         wlc_bcn_li_upd(wlc);
469         wlc->bcn_wait_prd =
470             (u8) (wlc_bmac_read_shm(wlc->hw, M_NOSLPZNATDTIM) >> 10);
471         ASSERT(wlc->bcn_wait_prd > 0);
472
473         /* the world is new again, so is our reported rate */
474         wlc_reprate_init(wlc);
475
476         /* write ethernet address to core */
477         FOREACH_BSS(wlc, i, bsscfg) {
478                 wlc_set_mac(bsscfg);
479                 wlc_set_bssid(bsscfg);
480         }
481
482         /* Update tsf_cfprep if associated and up */
483         if (wlc->pub->associated) {
484                 FOREACH_BSS(wlc, i, bsscfg) {
485                         if (bsscfg->up) {
486                                 u32 bi;
487
488                                 /* get beacon period and convert to uS */
489                                 bi = bsscfg->current_bss->beacon_period << 10;
490                                 /*
491                                  * update since init path would reset
492                                  * to default value
493                                  */
494                                 W_REG(&regs->tsf_cfprep,
495                                       (bi << CFPREP_CBI_SHIFT));
496
497                                 /* Update maccontrol PM related bits */
498                                 wlc_set_ps_ctrl(wlc);
499
500                                 break;
501                         }
502                 }
503         }
504
505         wlc_key_hw_init_all(wlc);
506
507         wlc_bandinit_ordered(wlc, chanspec);
508
509         wlc_init_scb(wlc, &global_scb);
510
511         /* init probe response timeout */
512         wlc_write_shm(wlc, M_PRS_MAXTIME, wlc->prb_resp_timeout);
513
514         /* init max burst txop (framebursting) */
515         wlc_write_shm(wlc, M_MBURST_TXOP,
516                       (wlc->
517                        _rifs ? (EDCF_AC_VO_TXOP_AP << 5) : MAXFRAMEBURST_TXOP));
518
519         /* initialize maximum allowed duty cycle */
520         wlc_duty_cycle_set(wlc, wlc->tx_duty_cycle_ofdm, true, true);
521         wlc_duty_cycle_set(wlc, wlc->tx_duty_cycle_cck, false, true);
522
523         /* Update some shared memory locations related to max AMPDU size allowed to received */
524         wlc_ampdu_shm_upd(wlc->ampdu);
525
526         /* band-specific inits */
527         wlc_bsinit(wlc);
528
529         /* Enable EDCF mode (while the MAC is suspended) */
530         if (EDCF_ENAB(wlc->pub)) {
531                 OR_REG(&regs->ifs_ctl, IFS_USEEDCF);
532                 wlc_edcf_setparams(wlc, false);
533         }
534
535         /* Init precedence maps for empty FIFOs */
536         wlc_tx_prec_map_init(wlc);
537
538         /* read the ucode version if we have not yet done so */
539         if (wlc->ucode_rev == 0) {
540                 wlc->ucode_rev =
541                     wlc_read_shm(wlc, M_BOM_REV_MAJOR) << NBITS(u16);
542                 wlc->ucode_rev |= wlc_read_shm(wlc, M_BOM_REV_MINOR);
543         }
544
545         /* ..now really unleash hell (allow the MAC out of suspend) */
546         wlc_enable_mac(wlc);
547
548         /* clear tx flow control */
549         wlc_txflowcontrol_reset(wlc);
550
551         /* clear tx data fifo suspends */
552         wlc->tx_suspended = false;
553
554         /* enable the RF Disable Delay timer */
555         W_REG(&wlc->regs->rfdisabledly, RFDISABLE_DEFAULT);
556
557         /* initialize mpc delay */
558         wlc->mpc_delay_off = wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
559
560         /*
561          * Initialize WME parameters; if they haven't been set by some other
562          * mechanism (IOVar, etc) then read them from the hardware.
563          */
564         if (WLC_WME_RETRY_SHORT_GET(wlc, 0) == 0) {     /* Uninitialized; read from HW */
565                 int ac;
566
567                 ASSERT(wlc->clk);
568                 for (ac = 0; ac < AC_COUNT; ac++) {
569                         wlc->wme_retries[ac] =
570                             wlc_read_shm(wlc, M_AC_TXLMT_ADDR(ac));
571                 }
572         }
573 }
574
575 void wlc_mac_bcn_promisc_change(struct wlc_info *wlc, bool promisc)
576 {
577         wlc->bcnmisc_monitor = promisc;
578         wlc_mac_bcn_promisc(wlc);
579 }
580
581 void wlc_mac_bcn_promisc(struct wlc_info *wlc)
582 {
583         if ((AP_ENAB(wlc->pub) && (N_ENAB(wlc->pub) || wlc->band->gmode)) ||
584             wlc->bcnmisc_ibss || wlc->bcnmisc_scan || wlc->bcnmisc_monitor)
585                 wlc_mctrl(wlc, MCTL_BCNS_PROMISC, MCTL_BCNS_PROMISC);
586         else
587                 wlc_mctrl(wlc, MCTL_BCNS_PROMISC, 0);
588 }
589
590 /* set or clear maccontrol bits MCTL_PROMISC and MCTL_KEEPCONTROL */
591 void wlc_mac_promisc(struct wlc_info *wlc)
592 {
593         u32 promisc_bits = 0;
594
595         /* promiscuous mode just sets MCTL_PROMISC
596          * Note: APs get all BSS traffic without the need to set the MCTL_PROMISC bit
597          * since all BSS data traffic is directed at the AP
598          */
599         if (PROMISC_ENAB(wlc->pub) && !AP_ENAB(wlc->pub) && !wlc->wet)
600                 promisc_bits |= MCTL_PROMISC;
601
602         /* monitor mode needs both MCTL_PROMISC and MCTL_KEEPCONTROL
603          * Note: monitor mode also needs MCTL_BCNS_PROMISC, but that is
604          * handled in wlc_mac_bcn_promisc()
605          */
606         if (MONITOR_ENAB(wlc))
607                 promisc_bits |= MCTL_PROMISC | MCTL_KEEPCONTROL;
608
609         wlc_mctrl(wlc, MCTL_PROMISC | MCTL_KEEPCONTROL, promisc_bits);
610 }
611
612 /* check if hps and wake states of sw and hw are in sync */
613 bool wlc_ps_check(struct wlc_info *wlc)
614 {
615         bool res = true;
616         bool hps, wake;
617         bool wake_ok;
618
619         if (!AP_ACTIVE(wlc)) {
620                 u32 tmp;
621                 tmp = R_REG(&wlc->regs->maccontrol);
622
623                 /*
624                  * If deviceremoved is detected, then don't take any action as
625                  * this can be called in any context. Assume that caller will
626                  * take care of the condition. This is just to avoid assert
627                  */
628                 if (tmp == 0xffffffff) {
629                         wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n",
630                                   wlc->pub->unit, __func__);
631                         return DEVICEREMOVED(wlc);
632                 }
633
634                 hps = PS_ALLOWED(wlc);
635
636                 if (hps != ((tmp & MCTL_HPS) != 0)) {
637                         int idx;
638                         struct wlc_bsscfg *cfg;
639                         wiphy_err(wlc->wiphy, "wl%d: hps not sync, sw %d, "
640                                   "maccontrol 0x%x\n",
641                                   wlc->pub->unit, hps, tmp);
642                         FOREACH_BSS(wlc, idx, cfg) {
643                                 if (!BSSCFG_STA(cfg))
644                                         continue;
645                         }
646
647                         res = false;
648                 }
649                 /* For a monolithic build the wake check can be exact since it looks at wake
650                  * override bits. The MCTL_WAKE bit should match the 'wake' value.
651                  */
652                 wake = STAY_AWAKE(wlc) || wlc->hw->wake_override;
653                 wake_ok = (wake == ((tmp & MCTL_WAKE) != 0));
654                 if (hps && !wake_ok) {
655                         wiphy_err(wlc->wiphy, "wl%d: wake not sync, sw %d "
656                                   "maccontrol 0x%x\n",
657                                   wlc->pub->unit, wake, tmp);
658                         res = false;
659                 }
660         }
661         ASSERT(res);
662         return res;
663 }
664
665 /* push sw hps and wake state through hardware */
666 void wlc_set_ps_ctrl(struct wlc_info *wlc)
667 {
668         u32 v1, v2;
669         bool hps, wake;
670         bool awake_before;
671
672         hps = PS_ALLOWED(wlc);
673         wake = hps ? (STAY_AWAKE(wlc)) : true;
674
675         WL_TRACE("wl%d: wlc_set_ps_ctrl: hps %d wake %d\n",
676                  wlc->pub->unit, hps, wake);
677
678         v1 = R_REG(&wlc->regs->maccontrol);
679         v2 = 0;
680         if (hps)
681                 v2 |= MCTL_HPS;
682         if (wake)
683                 v2 |= MCTL_WAKE;
684
685         wlc_mctrl(wlc, MCTL_WAKE | MCTL_HPS, v2);
686
687         awake_before = ((v1 & MCTL_WAKE) || ((v1 & MCTL_HPS) == 0));
688
689         if (wake && !awake_before)
690                 wlc_bmac_wait_for_wake(wlc->hw);
691
692 }
693
694 /*
695  * Write this BSS config's MAC address to core.
696  * Updates RXE match engine.
697  */
698 int wlc_set_mac(struct wlc_bsscfg *cfg)
699 {
700         int err = 0;
701         struct wlc_info *wlc = cfg->wlc;
702
703         if (cfg == wlc->cfg) {
704                 /* enter the MAC addr into the RXE match registers */
705                 wlc_set_addrmatch(wlc, RCM_MAC_OFFSET, cfg->cur_etheraddr);
706         }
707
708         wlc_ampdu_macaddr_upd(wlc);
709
710         return err;
711 }
712
713 /* Write the BSS config's BSSID address to core (set_bssid in d11procs.tcl).
714  * Updates RXE match engine.
715  */
716 void wlc_set_bssid(struct wlc_bsscfg *cfg)
717 {
718         struct wlc_info *wlc = cfg->wlc;
719
720         /* if primary config, we need to update BSSID in RXE match registers */
721         if (cfg == wlc->cfg) {
722                 wlc_set_addrmatch(wlc, RCM_BSSID_OFFSET, cfg->BSSID);
723         }
724 #ifdef SUPPORT_HWKEYS
725         else if (BSSCFG_STA(cfg) && cfg->BSS) {
726                 wlc_rcmta_add_bssid(wlc, cfg);
727         }
728 #endif
729 }
730
731 /*
732  * Suspend the the MAC and update the slot timing
733  * for standard 11b/g (20us slots) or shortslot 11g (9us slots).
734  */
735 void wlc_switch_shortslot(struct wlc_info *wlc, bool shortslot)
736 {
737         int idx;
738         struct wlc_bsscfg *cfg;
739
740         ASSERT(wlc->band->gmode);
741
742         /* use the override if it is set */
743         if (wlc->shortslot_override != WLC_SHORTSLOT_AUTO)
744                 shortslot = (wlc->shortslot_override == WLC_SHORTSLOT_ON);
745
746         if (wlc->shortslot == shortslot)
747                 return;
748
749         wlc->shortslot = shortslot;
750
751         /* update the capability based on current shortslot mode */
752         FOREACH_BSS(wlc, idx, cfg) {
753                 if (!cfg->associated)
754                         continue;
755                 cfg->current_bss->capability &=
756                                         ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
757                 if (wlc->shortslot)
758                         cfg->current_bss->capability |=
759                                         WLAN_CAPABILITY_SHORT_SLOT_TIME;
760         }
761
762         wlc_bmac_set_shortslot(wlc->hw, shortslot);
763 }
764
765 static u8 wlc_local_constraint_qdbm(struct wlc_info *wlc)
766 {
767         u8 local;
768         s16 local_max;
769
770         local = WLC_TXPWR_MAX;
771         if (wlc->pub->associated &&
772             (wf_chspec_ctlchan(wlc->chanspec) ==
773              wf_chspec_ctlchan(wlc->home_chanspec))) {
774
775                 /* get the local power constraint if we are on the AP's
776                  * channel [802.11h, 7.3.2.13]
777                  */
778                 /* Clamp the value between 0 and WLC_TXPWR_MAX w/o overflowing the target */
779                 local_max =
780                     (wlc->txpwr_local_max -
781                      wlc->txpwr_local_constraint) * WLC_TXPWR_DB_FACTOR;
782                 if (local_max > 0 && local_max < WLC_TXPWR_MAX)
783                         return (u8) local_max;
784                 if (local_max < 0)
785                         return 0;
786         }
787
788         return local;
789 }
790
791 /* propagate home chanspec to all bsscfgs in case bsscfg->current_bss->chanspec is referenced */
792 void wlc_set_home_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
793 {
794         if (wlc->home_chanspec != chanspec) {
795                 int idx;
796                 struct wlc_bsscfg *cfg;
797
798                 wlc->home_chanspec = chanspec;
799
800                 FOREACH_BSS(wlc, idx, cfg) {
801                         if (!cfg->associated)
802                                 continue;
803
804                         cfg->current_bss->chanspec = chanspec;
805                 }
806
807         }
808 }
809
810 static void wlc_set_phy_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
811 {
812         /* Save our copy of the chanspec */
813         wlc->chanspec = chanspec;
814
815         /* Set the chanspec and power limits for this locale after computing
816          * any 11h local tx power constraints.
817          */
818         wlc_channel_set_chanspec(wlc->cmi, chanspec,
819                                  wlc_local_constraint_qdbm(wlc));
820
821         if (wlc->stf->ss_algosel_auto)
822                 wlc_stf_ss_algo_channel_get(wlc, &wlc->stf->ss_algo_channel,
823                                             chanspec);
824
825         wlc_stf_ss_update(wlc, wlc->band);
826
827 }
828
829 void wlc_set_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
830 {
831         uint bandunit;
832         bool switchband = false;
833         chanspec_t old_chanspec = wlc->chanspec;
834
835         if (!wlc_valid_chanspec_db(wlc->cmi, chanspec)) {
836                 wiphy_err(wlc->wiphy, "wl%d: %s: Bad channel %d\n",
837                           wlc->pub->unit, __func__, CHSPEC_CHANNEL(chanspec));
838                 ASSERT(wlc_valid_chanspec_db(wlc->cmi, chanspec));
839                 return;
840         }
841
842         /* Switch bands if necessary */
843         if (NBANDS(wlc) > 1) {
844                 bandunit = CHSPEC_WLCBANDUNIT(chanspec);
845                 if (wlc->band->bandunit != bandunit || wlc->bandinit_pending) {
846                         switchband = true;
847                         if (wlc->bandlocked) {
848                                 wiphy_err(wlc->wiphy, "wl%d: %s: chspec %d "
849                                           "band is locked!\n",
850                                           wlc->pub->unit, __func__,
851                                           CHSPEC_CHANNEL(chanspec));
852                                 return;
853                         }
854                         /* BMAC_NOTE: should the setband call come after the wlc_bmac_chanspec() ?
855                          * if the setband updates (wlc_bsinit) use low level calls to inspect and
856                          * set state, the state inspected may be from the wrong band, or the
857                          * following wlc_bmac_set_chanspec() may undo the work.
858                          */
859                         wlc_setband(wlc, bandunit);
860                 }
861         }
862
863         ASSERT(N_ENAB(wlc->pub) || !CHSPEC_IS40(chanspec));
864
865         /* sync up phy/radio chanspec */
866         wlc_set_phy_chanspec(wlc, chanspec);
867
868         /* init antenna selection */
869         if (CHSPEC_WLC_BW(old_chanspec) != CHSPEC_WLC_BW(chanspec)) {
870                 wlc_antsel_init(wlc->asi);
871
872                 /* Fix the hardware rateset based on bw.
873                  * Mainly add MCS32 for 40Mhz, remove MCS 32 for 20Mhz
874                  */
875                 wlc_rateset_bw_mcs_filter(&wlc->band->hw_rateset,
876                                           wlc->band->
877                                           mimo_cap_40 ? CHSPEC_WLC_BW(chanspec)
878                                           : 0);
879         }
880
881         /* update some mac configuration since chanspec changed */
882         wlc_ucode_mac_upd(wlc);
883 }
884
885 #if defined(BCMDBG)
886 static int wlc_get_current_txpwr(struct wlc_info *wlc, void *pwr, uint len)
887 {
888         txpwr_limits_t txpwr;
889         tx_power_t power;
890         tx_power_legacy_t *old_power = NULL;
891         int r, c;
892         uint qdbm;
893         bool override;
894
895         if (len == sizeof(tx_power_legacy_t))
896                 old_power = (tx_power_legacy_t *) pwr;
897         else if (len < sizeof(tx_power_t))
898                 return -BCME_BUFTOOSHORT;
899
900         memset(&power, 0, sizeof(tx_power_t));
901
902         power.chanspec = WLC_BAND_PI_RADIO_CHANSPEC;
903         if (wlc->pub->associated)
904                 power.local_chanspec = wlc->home_chanspec;
905
906         /* Return the user target tx power limits for the various rates.  Note  wlc_phy.c's
907          * public interface only implements getting and setting a single value for all of
908          * rates, so we need to fill the array ourselves.
909          */
910         wlc_phy_txpower_get(wlc->band->pi, &qdbm, &override);
911         for (r = 0; r < WL_TX_POWER_RATES; r++) {
912                 power.user_limit[r] = (u8) qdbm;
913         }
914
915         power.local_max = wlc->txpwr_local_max * WLC_TXPWR_DB_FACTOR;
916         power.local_constraint =
917             wlc->txpwr_local_constraint * WLC_TXPWR_DB_FACTOR;
918
919         power.antgain[0] = wlc->bandstate[BAND_2G_INDEX]->antgain;
920         power.antgain[1] = wlc->bandstate[BAND_5G_INDEX]->antgain;
921
922         wlc_channel_reg_limits(wlc->cmi, power.chanspec, &txpwr);
923
924 #if WL_TX_POWER_CCK_NUM != WLC_NUM_RATES_CCK
925 #error "WL_TX_POWER_CCK_NUM != WLC_NUM_RATES_CCK"
926 #endif
927
928         /* CCK tx power limits */
929         for (c = 0, r = WL_TX_POWER_CCK_FIRST; c < WL_TX_POWER_CCK_NUM;
930              c++, r++)
931                 power.reg_limit[r] = txpwr.cck[c];
932
933 #if WL_TX_POWER_OFDM_NUM != WLC_NUM_RATES_OFDM
934 #error "WL_TX_POWER_OFDM_NUM != WLC_NUM_RATES_OFDM"
935 #endif
936
937         /* 20 MHz OFDM SISO tx power limits */
938         for (c = 0, r = WL_TX_POWER_OFDM_FIRST; c < WL_TX_POWER_OFDM_NUM;
939              c++, r++)
940                 power.reg_limit[r] = txpwr.ofdm[c];
941
942         if (WLC_PHY_11N_CAP(wlc->band)) {
943
944                 /* 20 MHz OFDM CDD tx power limits */
945                 for (c = 0, r = WL_TX_POWER_OFDM20_CDD_FIRST;
946                      c < WL_TX_POWER_OFDM_NUM; c++, r++)
947                         power.reg_limit[r] = txpwr.ofdm_cdd[c];
948
949                 /* 40 MHz OFDM SISO tx power limits */
950                 for (c = 0, r = WL_TX_POWER_OFDM40_SISO_FIRST;
951                      c < WL_TX_POWER_OFDM_NUM; c++, r++)
952                         power.reg_limit[r] = txpwr.ofdm_40_siso[c];
953
954                 /* 40 MHz OFDM CDD tx power limits */
955                 for (c = 0, r = WL_TX_POWER_OFDM40_CDD_FIRST;
956                      c < WL_TX_POWER_OFDM_NUM; c++, r++)
957                         power.reg_limit[r] = txpwr.ofdm_40_cdd[c];
958
959 #if WL_TX_POWER_MCS_1_STREAM_NUM != WLC_NUM_RATES_MCS_1_STREAM
960 #error "WL_TX_POWER_MCS_1_STREAM_NUM != WLC_NUM_RATES_MCS_1_STREAM"
961 #endif
962
963                 /* 20MHz MCS0-7 SISO tx power limits */
964                 for (c = 0, r = WL_TX_POWER_MCS20_SISO_FIRST;
965                      c < WLC_NUM_RATES_MCS_1_STREAM; c++, r++)
966                         power.reg_limit[r] = txpwr.mcs_20_siso[c];
967
968                 /* 20MHz MCS0-7 CDD tx power limits */
969                 for (c = 0, r = WL_TX_POWER_MCS20_CDD_FIRST;
970                      c < WLC_NUM_RATES_MCS_1_STREAM; c++, r++)
971                         power.reg_limit[r] = txpwr.mcs_20_cdd[c];
972
973                 /* 20MHz MCS0-7 STBC tx power limits */
974                 for (c = 0, r = WL_TX_POWER_MCS20_STBC_FIRST;
975                      c < WLC_NUM_RATES_MCS_1_STREAM; c++, r++)
976                         power.reg_limit[r] = txpwr.mcs_20_stbc[c];
977
978                 /* 40MHz MCS0-7 SISO tx power limits */
979                 for (c = 0, r = WL_TX_POWER_MCS40_SISO_FIRST;
980                      c < WLC_NUM_RATES_MCS_1_STREAM; c++, r++)
981                         power.reg_limit[r] = txpwr.mcs_40_siso[c];
982
983                 /* 40MHz MCS0-7 CDD tx power limits */
984                 for (c = 0, r = WL_TX_POWER_MCS40_CDD_FIRST;
985                      c < WLC_NUM_RATES_MCS_1_STREAM; c++, r++)
986                         power.reg_limit[r] = txpwr.mcs_40_cdd[c];
987
988                 /* 40MHz MCS0-7 STBC tx power limits */
989                 for (c = 0, r = WL_TX_POWER_MCS40_STBC_FIRST;
990                      c < WLC_NUM_RATES_MCS_1_STREAM; c++, r++)
991                         power.reg_limit[r] = txpwr.mcs_40_stbc[c];
992
993 #if WL_TX_POWER_MCS_2_STREAM_NUM != WLC_NUM_RATES_MCS_2_STREAM
994 #error "WL_TX_POWER_MCS_2_STREAM_NUM != WLC_NUM_RATES_MCS_2_STREAM"
995 #endif
996
997                 /* 20MHz MCS8-15 SDM tx power limits */
998                 for (c = 0, r = WL_TX_POWER_MCS20_SDM_FIRST;
999                      c < WLC_NUM_RATES_MCS_2_STREAM; c++, r++)
1000                         power.reg_limit[r] = txpwr.mcs_20_mimo[c];
1001
1002                 /* 40MHz MCS8-15 SDM tx power limits */
1003                 for (c = 0, r = WL_TX_POWER_MCS40_SDM_FIRST;
1004                      c < WLC_NUM_RATES_MCS_2_STREAM; c++, r++)
1005                         power.reg_limit[r] = txpwr.mcs_40_mimo[c];
1006
1007                 /* MCS 32 */
1008                 power.reg_limit[WL_TX_POWER_MCS_32] = txpwr.mcs32;
1009         }
1010
1011         wlc_phy_txpower_get_current(wlc->band->pi, &power,
1012                                     CHSPEC_CHANNEL(power.chanspec));
1013
1014         /* copy the tx_power_t struct to the return buffer,
1015          * or convert to a tx_power_legacy_t struct
1016          */
1017         if (!old_power) {
1018                 memcpy(pwr, &power, sizeof(tx_power_t));
1019         } else {
1020                 int band_idx = CHSPEC_IS2G(power.chanspec) ? 0 : 1;
1021
1022                 memset(old_power, 0, sizeof(tx_power_legacy_t));
1023
1024                 old_power->txpwr_local_max = power.local_max;
1025                 old_power->txpwr_local_constraint = power.local_constraint;
1026                 if (CHSPEC_IS2G(power.chanspec)) {
1027                         old_power->txpwr_chan_reg_max = txpwr.cck[0];
1028                         old_power->txpwr_est_Pout[band_idx] =
1029                             power.est_Pout_cck;
1030                         old_power->txpwr_est_Pout_gofdm = power.est_Pout[0];
1031                 } else {
1032                         old_power->txpwr_chan_reg_max = txpwr.ofdm[0];
1033                         old_power->txpwr_est_Pout[band_idx] = power.est_Pout[0];
1034                 }
1035                 old_power->txpwr_antgain[0] = power.antgain[0];
1036                 old_power->txpwr_antgain[1] = power.antgain[1];
1037
1038                 for (r = 0; r < NUM_PWRCTRL_RATES; r++) {
1039                         old_power->txpwr_band_max[r] = power.user_limit[r];
1040                         old_power->txpwr_limit[r] = power.reg_limit[r];
1041                         old_power->txpwr_target[band_idx][r] = power.target[r];
1042                         if (CHSPEC_IS2G(power.chanspec))
1043                                 old_power->txpwr_bphy_cck_max[r] =
1044                                     power.board_limit[r];
1045                         else
1046                                 old_power->txpwr_aphy_max[r] =
1047                                     power.board_limit[r];
1048                 }
1049         }
1050
1051         return 0;
1052 }
1053 #endif                          /* defined(BCMDBG) */
1054
1055 static u32 wlc_watchdog_backup_bi(struct wlc_info *wlc)
1056 {
1057         u32 bi;
1058         bi = 2 * wlc->cfg->current_bss->dtim_period *
1059             wlc->cfg->current_bss->beacon_period;
1060         if (wlc->bcn_li_dtim)
1061                 bi *= wlc->bcn_li_dtim;
1062         else if (wlc->bcn_li_bcn)
1063                 /* recalculate bi based on bcn_li_bcn */
1064                 bi = 2 * wlc->bcn_li_bcn * wlc->cfg->current_bss->beacon_period;
1065
1066         if (bi < 2 * TIMER_INTERVAL_WATCHDOG)
1067                 bi = 2 * TIMER_INTERVAL_WATCHDOG;
1068         return bi;
1069 }
1070
1071 /* Change to run the watchdog either from a periodic timer or from tbtt handler.
1072  * Call watchdog from tbtt handler if tbtt is true, watchdog timer otherwise.
1073  */
1074 void wlc_watchdog_upd(struct wlc_info *wlc, bool tbtt)
1075 {
1076         /* make sure changing watchdog driver is allowed */
1077         if (!wlc->pub->up || !wlc->pub->align_wd_tbtt)
1078                 return;
1079         if (!tbtt && wlc->WDarmed) {
1080                 wl_del_timer(wlc->wl, wlc->wdtimer);
1081                 wlc->WDarmed = false;
1082         }
1083
1084         /* stop watchdog timer and use tbtt interrupt to drive watchdog */
1085         if (tbtt && wlc->WDarmed) {
1086                 wl_del_timer(wlc->wl, wlc->wdtimer);
1087                 wlc->WDarmed = false;
1088                 wlc->WDlast = OSL_SYSUPTIME();
1089         }
1090         /* arm watchdog timer and drive the watchdog there */
1091         else if (!tbtt && !wlc->WDarmed) {
1092                 wl_add_timer(wlc->wl, wlc->wdtimer, TIMER_INTERVAL_WATCHDOG,
1093                              true);
1094                 wlc->WDarmed = true;
1095         }
1096         if (tbtt && !wlc->WDarmed) {
1097                 wl_add_timer(wlc->wl, wlc->wdtimer, wlc_watchdog_backup_bi(wlc),
1098                              true);
1099                 wlc->WDarmed = true;
1100         }
1101 }
1102
1103 ratespec_t wlc_lowest_basic_rspec(struct wlc_info *wlc, wlc_rateset_t *rs)
1104 {
1105         ratespec_t lowest_basic_rspec;
1106         uint i;
1107
1108         /* Use the lowest basic rate */
1109         lowest_basic_rspec = rs->rates[0] & WLC_RATE_MASK;
1110         for (i = 0; i < rs->count; i++) {
1111                 if (rs->rates[i] & WLC_RATE_FLAG) {
1112                         lowest_basic_rspec = rs->rates[i] & WLC_RATE_MASK;
1113                         break;
1114                 }
1115         }
1116 #if NCONF
1117         /* pick siso/cdd as default for OFDM (note no basic rate MCSs are supported yet) */
1118         if (IS_OFDM(lowest_basic_rspec)) {
1119                 lowest_basic_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
1120         }
1121 #endif
1122
1123         return lowest_basic_rspec;
1124 }
1125
1126 /* This function changes the phytxctl for beacon based on current beacon ratespec AND txant
1127  * setting as per this table:
1128  *  ratespec     CCK            ant = wlc->stf->txant
1129  *              OFDM            ant = 3
1130  */
1131 void wlc_beacon_phytxctl_txant_upd(struct wlc_info *wlc, ratespec_t bcn_rspec)
1132 {
1133         u16 phyctl;
1134         u16 phytxant = wlc->stf->phytxant;
1135         u16 mask = PHY_TXC_ANT_MASK;
1136
1137         /* for non-siso rates or default setting, use the available chains */
1138         if (WLC_PHY_11N_CAP(wlc->band)) {
1139                 phytxant = wlc_stf_phytxchain_sel(wlc, bcn_rspec);
1140         }
1141
1142         phyctl = wlc_read_shm(wlc, M_BCN_PCTLWD);
1143         phyctl = (phyctl & ~mask) | phytxant;
1144         wlc_write_shm(wlc, M_BCN_PCTLWD, phyctl);
1145 }
1146
1147 /* centralized protection config change function to simplify debugging, no consistency checking
1148  * this should be called only on changes to avoid overhead in periodic function
1149 */
1150 void wlc_protection_upd(struct wlc_info *wlc, uint idx, int val)
1151 {
1152         WL_TRACE("wlc_protection_upd: idx %d, val %d\n", idx, val);
1153
1154         switch (idx) {
1155         case WLC_PROT_G_SPEC:
1156                 wlc->protection->_g = (bool) val;
1157                 break;
1158         case WLC_PROT_G_OVR:
1159                 wlc->protection->g_override = (s8) val;
1160                 break;
1161         case WLC_PROT_G_USER:
1162                 wlc->protection->gmode_user = (u8) val;
1163                 break;
1164         case WLC_PROT_OVERLAP:
1165                 wlc->protection->overlap = (s8) val;
1166                 break;
1167         case WLC_PROT_N_USER:
1168                 wlc->protection->nmode_user = (s8) val;
1169                 break;
1170         case WLC_PROT_N_CFG:
1171                 wlc->protection->n_cfg = (s8) val;
1172                 break;
1173         case WLC_PROT_N_CFG_OVR:
1174                 wlc->protection->n_cfg_override = (s8) val;
1175                 break;
1176         case WLC_PROT_N_NONGF:
1177                 wlc->protection->nongf = (bool) val;
1178                 break;
1179         case WLC_PROT_N_NONGF_OVR:
1180                 wlc->protection->nongf_override = (s8) val;
1181                 break;
1182         case WLC_PROT_N_PAM_OVR:
1183                 wlc->protection->n_pam_override = (s8) val;
1184                 break;
1185         case WLC_PROT_N_OBSS:
1186                 wlc->protection->n_obss = (bool) val;
1187                 break;
1188
1189         default:
1190                 ASSERT(0);
1191                 break;
1192         }
1193
1194 }
1195
1196 static void wlc_ht_update_sgi_rx(struct wlc_info *wlc, int val)
1197 {
1198         wlc->ht_cap.cap_info &= ~(IEEE80211_HT_CAP_SGI_20 |
1199                                         IEEE80211_HT_CAP_SGI_40);
1200         wlc->ht_cap.cap_info |= (val & WLC_N_SGI_20) ?
1201                                         IEEE80211_HT_CAP_SGI_20 : 0;
1202         wlc->ht_cap.cap_info |= (val & WLC_N_SGI_40) ?
1203                                         IEEE80211_HT_CAP_SGI_40 : 0;
1204
1205         if (wlc->pub->up) {
1206                 wlc_update_beacon(wlc);
1207                 wlc_update_probe_resp(wlc, true);
1208         }
1209 }
1210
1211 static void wlc_ht_update_ldpc(struct wlc_info *wlc, s8 val)
1212 {
1213         wlc->stf->ldpc = val;
1214
1215         wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_LDPC_CODING;
1216         if (wlc->stf->ldpc != OFF)
1217                 wlc->ht_cap.cap_info |= IEEE80211_HT_CAP_LDPC_CODING;
1218
1219         if (wlc->pub->up) {
1220                 wlc_update_beacon(wlc);
1221                 wlc_update_probe_resp(wlc, true);
1222                 wlc_phy_ldpc_override_set(wlc->band->pi, (val ? true : false));
1223         }
1224 }
1225
1226 /*
1227  * ucode, hwmac update
1228  *    Channel dependent updates for ucode and hw
1229  */
1230 static void wlc_ucode_mac_upd(struct wlc_info *wlc)
1231 {
1232         /* enable or disable any active IBSSs depending on whether or not
1233          * we are on the home channel
1234          */
1235         if (wlc->home_chanspec == WLC_BAND_PI_RADIO_CHANSPEC) {
1236                 if (wlc->pub->associated) {
1237                         /* BMAC_NOTE: This is something that should be fixed in ucode inits.
1238                          * I think that the ucode inits set up the bcn templates and shm values
1239                          * with a bogus beacon. This should not be done in the inits. If ucode needs
1240                          * to set up a beacon for testing, the test routines should write it down,
1241                          * not expect the inits to populate a bogus beacon.
1242                          */
1243                         if (WLC_PHY_11N_CAP(wlc->band)) {
1244                                 wlc_write_shm(wlc, M_BCN_TXTSF_OFFSET,
1245                                               wlc->band->bcntsfoff);
1246                         }
1247                 }
1248         } else {
1249                 /* disable an active IBSS if we are not on the home channel */
1250         }
1251
1252         /* update the various promisc bits */
1253         wlc_mac_bcn_promisc(wlc);
1254         wlc_mac_promisc(wlc);
1255 }
1256
1257 static void wlc_bandinit_ordered(struct wlc_info *wlc, chanspec_t chanspec)
1258 {
1259         wlc_rateset_t default_rateset;
1260         uint parkband;
1261         uint i, band_order[2];
1262
1263         WL_TRACE("wl%d: wlc_bandinit_ordered\n", wlc->pub->unit);
1264         /*
1265          * We might have been bandlocked during down and the chip power-cycled (hibernate).
1266          * figure out the right band to park on
1267          */
1268         if (wlc->bandlocked || NBANDS(wlc) == 1) {
1269                 ASSERT(CHSPEC_WLCBANDUNIT(chanspec) == wlc->band->bandunit);
1270
1271                 parkband = wlc->band->bandunit; /* updated in wlc_bandlock() */
1272                 band_order[0] = band_order[1] = parkband;
1273         } else {
1274                 /* park on the band of the specified chanspec */
1275                 parkband = CHSPEC_WLCBANDUNIT(chanspec);
1276
1277                 /* order so that parkband initialize last */
1278                 band_order[0] = parkband ^ 1;
1279                 band_order[1] = parkband;
1280         }
1281
1282         /* make each band operational, software state init */
1283         for (i = 0; i < NBANDS(wlc); i++) {
1284                 uint j = band_order[i];
1285
1286                 wlc->band = wlc->bandstate[j];
1287
1288                 wlc_default_rateset(wlc, &default_rateset);
1289
1290                 /* fill in hw_rate */
1291                 wlc_rateset_filter(&default_rateset, &wlc->band->hw_rateset,
1292                                    false, WLC_RATES_CCK_OFDM, WLC_RATE_MASK,
1293                                    (bool) N_ENAB(wlc->pub));
1294
1295                 /* init basic rate lookup */
1296                 wlc_rate_lookup_init(wlc, &default_rateset);
1297         }
1298
1299         /* sync up phy/radio chanspec */
1300         wlc_set_phy_chanspec(wlc, chanspec);
1301 }
1302
1303 /* band-specific init */
1304 static void WLBANDINITFN(wlc_bsinit) (struct wlc_info *wlc)
1305 {
1306         WL_TRACE("wl%d: wlc_bsinit: bandunit %d\n",
1307                  wlc->pub->unit, wlc->band->bandunit);
1308
1309         /* write ucode ACK/CTS rate table */
1310         wlc_set_ratetable(wlc);
1311
1312         /* update some band specific mac configuration */
1313         wlc_ucode_mac_upd(wlc);
1314
1315         /* init antenna selection */
1316         wlc_antsel_init(wlc->asi);
1317
1318 }
1319
1320 /* switch to and initialize new band */
1321 static void WLBANDINITFN(wlc_setband) (struct wlc_info *wlc, uint bandunit)
1322 {
1323         int idx;
1324         struct wlc_bsscfg *cfg;
1325
1326         ASSERT(NBANDS(wlc) > 1);
1327         ASSERT(!wlc->bandlocked);
1328         ASSERT(bandunit != wlc->band->bandunit || wlc->bandinit_pending);
1329
1330         wlc->band = wlc->bandstate[bandunit];
1331
1332         if (!wlc->pub->up)
1333                 return;
1334
1335         /* wait for at least one beacon before entering sleeping state */
1336         wlc->PMawakebcn = true;
1337         FOREACH_AS_STA(wlc, idx, cfg)
1338             cfg->PMawakebcn = true;
1339         wlc_set_ps_ctrl(wlc);
1340
1341         /* band-specific initializations */
1342         wlc_bsinit(wlc);
1343 }
1344
1345 /* Initialize a WME Parameter Info Element with default STA parameters from WMM Spec, Table 12 */
1346 void wlc_wme_initparams_sta(struct wlc_info *wlc, wme_param_ie_t *pe)
1347 {
1348         static const wme_param_ie_t stadef = {
1349                 WME_OUI,
1350                 WME_TYPE,
1351                 WME_SUBTYPE_PARAM_IE,
1352                 WME_VER,
1353                 0,
1354                 0,
1355                 {
1356                  {EDCF_AC_BE_ACI_STA, EDCF_AC_BE_ECW_STA,
1357                   cpu_to_le16(EDCF_AC_BE_TXOP_STA)},
1358                  {EDCF_AC_BK_ACI_STA, EDCF_AC_BK_ECW_STA,
1359                   cpu_to_le16(EDCF_AC_BK_TXOP_STA)},
1360                  {EDCF_AC_VI_ACI_STA, EDCF_AC_VI_ECW_STA,
1361                   cpu_to_le16(EDCF_AC_VI_TXOP_STA)},
1362                  {EDCF_AC_VO_ACI_STA, EDCF_AC_VO_ECW_STA,
1363                   cpu_to_le16(EDCF_AC_VO_TXOP_STA)}
1364                  }
1365         };
1366         memcpy(pe, &stadef, sizeof(*pe));
1367 }
1368
1369 void wlc_wme_setparams(struct wlc_info *wlc, u16 aci,
1370                        const struct ieee80211_tx_queue_params *params,
1371                        bool suspend)
1372 {
1373         int i;
1374         shm_acparams_t acp_shm;
1375         u16 *shm_entry;
1376
1377         ASSERT(wlc);
1378
1379         /* Only apply params if the core is out of reset and has clocks */
1380         if (!wlc->clk) {
1381                 wiphy_err(wlc->wiphy, "wl%d: %s : no-clock\n", wlc->pub->unit,
1382                           __func__);
1383                 return;
1384         }
1385
1386         wlc->wme_admctl = 0;
1387
1388         do {
1389                 memset((char *)&acp_shm, 0, sizeof(shm_acparams_t));
1390                 /* find out which ac this set of params applies to */
1391                 ASSERT(aci < AC_COUNT);
1392
1393                 /* fill in shm ac params struct */
1394                 acp_shm.txop = le16_to_cpu(params->txop);
1395                 /* convert from units of 32us to us for ucode */
1396                 wlc->edcf_txop[aci & 0x3] = acp_shm.txop =
1397                     EDCF_TXOP2USEC(acp_shm.txop);
1398                 acp_shm.aifs = (params->aifs & EDCF_AIFSN_MASK);
1399
1400                 if (aci == AC_VI && acp_shm.txop == 0
1401                     && acp_shm.aifs < EDCF_AIFSN_MAX)
1402                         acp_shm.aifs++;
1403
1404                 if (acp_shm.aifs < EDCF_AIFSN_MIN
1405                     || acp_shm.aifs > EDCF_AIFSN_MAX) {
1406                         wiphy_err(wlc->wiphy, "wl%d: wlc_edcf_setparams: bad "
1407                                   "aifs %d\n", wlc->pub->unit, acp_shm.aifs);
1408                         continue;
1409                 }
1410
1411                 acp_shm.cwmin = params->cw_min;
1412                 acp_shm.cwmax = params->cw_max;
1413                 acp_shm.cwcur = acp_shm.cwmin;
1414                 acp_shm.bslots =
1415                     R_REG(&wlc->regs->tsf_random) & acp_shm.cwcur;
1416                 acp_shm.reggap = acp_shm.bslots + acp_shm.aifs;
1417                 /* Indicate the new params to the ucode */
1418                 acp_shm.status = wlc_read_shm(wlc, (M_EDCF_QINFO +
1419                                                     wme_shmemacindex(aci) *
1420                                                     M_EDCF_QLEN +
1421                                                     M_EDCF_STATUS_OFF));
1422                 acp_shm.status |= WME_STATUS_NEWAC;
1423
1424                 /* Fill in shm acparam table */
1425                 shm_entry = (u16 *) &acp_shm;
1426                 for (i = 0; i < (int)sizeof(shm_acparams_t); i += 2)
1427                         wlc_write_shm(wlc,
1428                                       M_EDCF_QINFO +
1429                                       wme_shmemacindex(aci) * M_EDCF_QLEN + i,
1430                                       *shm_entry++);
1431
1432         } while (0);
1433
1434         if (suspend)
1435                 wlc_suspend_mac_and_wait(wlc);
1436
1437         if (suspend)
1438                 wlc_enable_mac(wlc);
1439
1440 }
1441
1442 void wlc_edcf_setparams(struct wlc_info *wlc, bool suspend)
1443 {
1444         u16 aci;
1445         int i_ac;
1446         edcf_acparam_t *edcf_acp;
1447
1448         struct ieee80211_tx_queue_params txq_pars;
1449         struct ieee80211_tx_queue_params *params = &txq_pars;
1450
1451         ASSERT(wlc);
1452
1453         /*
1454          * AP uses AC params from wme_param_ie_ap.
1455          * AP advertises AC params from wme_param_ie.
1456          * STA uses AC params from wme_param_ie.
1457          */
1458
1459         edcf_acp = (edcf_acparam_t *) &wlc->wme_param_ie.acparam[0];
1460
1461         for (i_ac = 0; i_ac < AC_COUNT; i_ac++, edcf_acp++) {
1462                 /* find out which ac this set of params applies to */
1463                 aci = (edcf_acp->ACI & EDCF_ACI_MASK) >> EDCF_ACI_SHIFT;
1464                 ASSERT(aci < AC_COUNT);
1465                 /* set the admission control policy for this AC */
1466                 if (edcf_acp->ACI & EDCF_ACM_MASK) {
1467                         wlc->wme_admctl |= 1 << aci;
1468                 }
1469
1470                 /* fill in shm ac params struct */
1471                 params->txop = edcf_acp->TXOP;
1472                 params->aifs = edcf_acp->ACI;
1473
1474                 /* CWmin = 2^(ECWmin) - 1 */
1475                 params->cw_min = EDCF_ECW2CW(edcf_acp->ECW & EDCF_ECWMIN_MASK);
1476                 /* CWmax = 2^(ECWmax) - 1 */
1477                 params->cw_max = EDCF_ECW2CW((edcf_acp->ECW & EDCF_ECWMAX_MASK)
1478                                             >> EDCF_ECWMAX_SHIFT);
1479                 wlc_wme_setparams(wlc, aci, params, suspend);
1480         }
1481
1482         if (suspend)
1483                 wlc_suspend_mac_and_wait(wlc);
1484
1485         if (AP_ENAB(wlc->pub) && WME_ENAB(wlc->pub)) {
1486                 wlc_update_beacon(wlc);
1487                 wlc_update_probe_resp(wlc, false);
1488         }
1489
1490         if (suspend)
1491                 wlc_enable_mac(wlc);
1492
1493 }
1494
1495 bool wlc_timers_init(struct wlc_info *wlc, int unit)
1496 {
1497         wlc->wdtimer = wl_init_timer(wlc->wl, wlc_watchdog_by_timer,
1498                 wlc, "watchdog");
1499         if (!wlc->wdtimer) {
1500                 wiphy_err(wlc->wiphy, "wl%d:  wl_init_timer for wdtimer "
1501                           "failed\n", unit);
1502                 goto fail;
1503         }
1504
1505         wlc->radio_timer = wl_init_timer(wlc->wl, wlc_radio_timer,
1506                 wlc, "radio");
1507         if (!wlc->radio_timer) {
1508                 wiphy_err(wlc->wiphy, "wl%d:  wl_init_timer for radio_timer "
1509                           "failed\n", unit);
1510                 goto fail;
1511         }
1512
1513         return true;
1514
1515  fail:
1516         return false;
1517 }
1518
1519 /*
1520  * Initialize wlc_info default values ...
1521  * may get overrides later in this function
1522  */
1523 void wlc_info_init(struct wlc_info *wlc, int unit)
1524 {
1525         int i;
1526         /* Assume the device is there until proven otherwise */
1527         wlc->device_present = true;
1528
1529         /* set default power output percentage to 100 percent */
1530         wlc->txpwr_percent = 100;
1531
1532         /* Save our copy of the chanspec */
1533         wlc->chanspec = CH20MHZ_CHSPEC(1);
1534
1535         /* initialize CCK preamble mode to unassociated state */
1536         wlc->shortpreamble = false;
1537
1538         wlc->legacy_probe = true;
1539
1540         /* various 802.11g modes */
1541         wlc->shortslot = false;
1542         wlc->shortslot_override = WLC_SHORTSLOT_AUTO;
1543
1544         wlc->barker_overlap_control = true;
1545         wlc->barker_preamble = WLC_BARKER_SHORT_ALLOWED;
1546         wlc->txburst_limit_override = AUTO;
1547
1548         wlc_protection_upd(wlc, WLC_PROT_G_OVR, WLC_PROTECTION_AUTO);
1549         wlc_protection_upd(wlc, WLC_PROT_G_SPEC, false);
1550
1551         wlc_protection_upd(wlc, WLC_PROT_N_CFG_OVR, WLC_PROTECTION_AUTO);
1552         wlc_protection_upd(wlc, WLC_PROT_N_CFG, WLC_N_PROTECTION_OFF);
1553         wlc_protection_upd(wlc, WLC_PROT_N_NONGF_OVR, WLC_PROTECTION_AUTO);
1554         wlc_protection_upd(wlc, WLC_PROT_N_NONGF, false);
1555         wlc_protection_upd(wlc, WLC_PROT_N_PAM_OVR, AUTO);
1556
1557         wlc_protection_upd(wlc, WLC_PROT_OVERLAP, WLC_PROTECTION_CTL_OVERLAP);
1558
1559         /* 802.11g draft 4.0 NonERP elt advertisement */
1560         wlc->include_legacy_erp = true;
1561
1562         wlc->stf->ant_rx_ovr = ANT_RX_DIV_DEF;
1563         wlc->stf->txant = ANT_TX_DEF;
1564
1565         wlc->prb_resp_timeout = WLC_PRB_RESP_TIMEOUT;
1566
1567         wlc->usr_fragthresh = DOT11_DEFAULT_FRAG_LEN;
1568         for (i = 0; i < NFIFO; i++)
1569                 wlc->fragthresh[i] = DOT11_DEFAULT_FRAG_LEN;
1570         wlc->RTSThresh = DOT11_DEFAULT_RTS_LEN;
1571
1572         /* default rate fallback retry limits */
1573         wlc->SFBL = RETRY_SHORT_FB;
1574         wlc->LFBL = RETRY_LONG_FB;
1575
1576         /* default mac retry limits */
1577         wlc->SRL = RETRY_SHORT_DEF;
1578         wlc->LRL = RETRY_LONG_DEF;
1579
1580         /* init PM state */
1581         wlc->PM = PM_OFF;       /* User's setting of PM mode through IOCTL */
1582         wlc->PM_override = false;       /* Prevents from going to PM if our AP is 'ill' */
1583         wlc->PMenabled = false; /* Current PM state */
1584         wlc->PMpending = false; /* Tracks whether STA indicated PM in the last attempt */
1585         wlc->PMblocked = false; /* To allow blocking going into PM during RM and scans */
1586
1587         /* In WMM Auto mode, PM is allowed if association is a UAPSD association */
1588         wlc->WME_PM_blocked = false;
1589
1590         /* Init wme queuing method */
1591         wlc->wme_prec_queuing = false;
1592
1593         /* Overrides for the core to stay awake under zillion conditions Look for STAY_AWAKE */
1594         wlc->wake = false;
1595         /* Are we waiting for a response to PS-Poll that we sent */
1596         wlc->PSpoll = false;
1597
1598         /* APSD defaults */
1599         wlc->wme_apsd = true;
1600         wlc->apsd_sta_usp = false;
1601         wlc->apsd_trigger_timeout = 0;  /* disable the trigger timer */
1602         wlc->apsd_trigger_ac = AC_BITMAP_ALL;
1603
1604         /* Set flag to indicate that hw keys should be used when available. */
1605         wlc->wsec_swkeys = false;
1606
1607         /* init the 4 static WEP default keys */
1608         for (i = 0; i < WSEC_MAX_DEFAULT_KEYS; i++) {
1609                 wlc->wsec_keys[i] = wlc->wsec_def_keys[i];
1610                 wlc->wsec_keys[i]->idx = (u8) i;
1611         }
1612
1613         wlc->_regulatory_domain = false;        /* 802.11d */
1614
1615         /* WME QoS mode is Auto by default */
1616         wlc->pub->_wme = AUTO;
1617
1618 #ifdef BCMSDIODEV_ENABLED
1619         wlc->pub->_priofc = true;       /* enable priority flow control for sdio dongle */
1620 #endif
1621
1622         wlc->pub->_ampdu = AMPDU_AGG_HOST;
1623         wlc->pub->bcmerror = 0;
1624         wlc->ibss_allowed = true;
1625         wlc->ibss_coalesce_allowed = true;
1626         wlc->pub->_coex = ON;
1627
1628         /* initialize mpc delay */
1629         wlc->mpc_delay_off = wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
1630
1631         wlc->pr80838_war = true;
1632 }
1633
1634 static bool wlc_state_bmac_sync(struct wlc_info *wlc)
1635 {
1636         wlc_bmac_state_t state_bmac;
1637
1638         if (wlc_bmac_state_get(wlc->hw, &state_bmac) != 0)
1639                 return false;
1640
1641         wlc->machwcap = state_bmac.machwcap;
1642         wlc_protection_upd(wlc, WLC_PROT_N_PAM_OVR,
1643                            (s8) state_bmac.preamble_ovr);
1644
1645         return true;
1646 }
1647
1648 static uint wlc_attach_module(struct wlc_info *wlc)
1649 {
1650         uint err = 0;
1651         uint unit;
1652         unit = wlc->pub->unit;
1653
1654         wlc->asi = wlc_antsel_attach(wlc);
1655         if (wlc->asi == NULL) {
1656                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_antsel_attach "
1657                           "failed\n", unit);
1658                 err = 44;
1659                 goto fail;
1660         }
1661
1662         wlc->ampdu = wlc_ampdu_attach(wlc);
1663         if (wlc->ampdu == NULL) {
1664                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_ampdu_attach "
1665                           "failed\n", unit);
1666                 err = 50;
1667                 goto fail;
1668         }
1669
1670         if ((wlc_stf_attach(wlc) != 0)) {
1671                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_stf_attach "
1672                           "failed\n", unit);
1673                 err = 68;
1674                 goto fail;
1675         }
1676  fail:
1677         return err;
1678 }
1679
1680 struct wlc_pub *wlc_pub(void *wlc)
1681 {
1682         return ((struct wlc_info *) wlc)->pub;
1683 }
1684
1685 #define CHIP_SUPPORTS_11N(wlc)  1
1686
1687 /*
1688  * The common driver entry routine. Error codes should be unique
1689  */
1690 void *wlc_attach(struct wl_info *wl, u16 vendor, u16 device, uint unit,
1691                  bool piomode, void *regsva, uint bustype, void *btparam,
1692                  uint *perr)
1693 {
1694         struct wlc_info *wlc;
1695         uint err = 0;
1696         uint j;
1697         struct wlc_pub *pub;
1698         struct wlc_txq_info *qi;
1699         uint n_disabled;
1700
1701         /* allocate struct wlc_info state and its substructures */
1702         wlc = (struct wlc_info *) wlc_attach_malloc(unit, &err, device);
1703         if (wlc == NULL)
1704                 goto fail;
1705         wlc->wiphy = wl->wiphy;
1706         pub = wlc->pub;
1707
1708 #if defined(BCMDBG)
1709         wlc_info_dbg = wlc;
1710 #endif
1711
1712         wlc->band = wlc->bandstate[0];
1713         wlc->core = wlc->corestate;
1714         wlc->wl = wl;
1715         pub->unit = unit;
1716         wlc->btparam = btparam;
1717         pub->_piomode = piomode;
1718         wlc->bandinit_pending = false;
1719         /* By default restrict TKIP associations from 11n STA's */
1720         wlc->ht_wsec_restriction = WLC_HT_TKIP_RESTRICT;
1721
1722         /* populate struct wlc_info with default values  */
1723         wlc_info_init(wlc, unit);
1724
1725         /* update sta/ap related parameters */
1726         wlc_ap_upd(wlc);
1727
1728         /* 11n_disable nvram */
1729         n_disabled = getintvar(pub->vars, "11n_disable");
1730
1731         /* register a module (to handle iovars) */
1732         wlc_module_register(wlc->pub, wlc_iovars, "wlc_iovars", wlc,
1733                             wlc_doiovar, NULL, NULL);
1734
1735         /*
1736          * low level attach steps(all hw accesses go
1737          * inside, no more in rest of the attach)
1738          */
1739         err = wlc_bmac_attach(wlc, vendor, device, unit, piomode, regsva,
1740                               bustype, btparam);
1741         if (err)
1742                 goto fail;
1743
1744         /* for some states, due to different info pointer(e,g, wlc, wlc_hw) or master/slave split,
1745          * HIGH driver(both monolithic and HIGH_ONLY) needs to sync states FROM BMAC portion driver
1746          */
1747         if (!wlc_state_bmac_sync(wlc)) {
1748                 err = 20;
1749                 goto fail;
1750         }
1751
1752         pub->phy_11ncapable = WLC_PHY_11N_CAP(wlc->band);
1753
1754         /* propagate *vars* from BMAC driver to high driver */
1755         wlc_bmac_copyfrom_vars(wlc->hw, &pub->vars, &wlc->vars_size);
1756
1757
1758         /* set maximum allowed duty cycle */
1759         wlc->tx_duty_cycle_ofdm =
1760             (u16) getintvar(pub->vars, "tx_duty_cycle_ofdm");
1761         wlc->tx_duty_cycle_cck =
1762             (u16) getintvar(pub->vars, "tx_duty_cycle_cck");
1763
1764         wlc_stf_phy_chain_calc(wlc);
1765
1766         /* txchain 1: txant 0, txchain 2: txant 1 */
1767         if (WLCISNPHY(wlc->band) && (wlc->stf->txstreams == 1))
1768                 wlc->stf->txant = wlc->stf->hw_txchain - 1;
1769
1770         /* push to BMAC driver */
1771         wlc_phy_stf_chain_init(wlc->band->pi, wlc->stf->hw_txchain,
1772                                wlc->stf->hw_rxchain);
1773
1774         /* pull up some info resulting from the low attach */
1775         {
1776                 int i;
1777                 for (i = 0; i < NFIFO; i++)
1778                         wlc->core->txavail[i] = wlc->hw->txavail[i];
1779         }
1780
1781         wlc_bmac_hw_etheraddr(wlc->hw, wlc->perm_etheraddr);
1782
1783         memcpy(&pub->cur_etheraddr, &wlc->perm_etheraddr, ETH_ALEN);
1784
1785         for (j = 0; j < NBANDS(wlc); j++) {
1786                 /* Use band 1 for single band 11a */
1787                 if (IS_SINGLEBAND_5G(wlc->deviceid))
1788                         j = BAND_5G_INDEX;
1789
1790                 wlc->band = wlc->bandstate[j];
1791
1792                 if (!wlc_attach_stf_ant_init(wlc)) {
1793                         err = 24;
1794                         goto fail;
1795                 }
1796
1797                 /* default contention windows size limits */
1798                 wlc->band->CWmin = APHY_CWMIN;
1799                 wlc->band->CWmax = PHY_CWMAX;
1800
1801                 /* init gmode value */
1802                 if (BAND_2G(wlc->band->bandtype)) {
1803                         wlc->band->gmode = GMODE_AUTO;
1804                         wlc_protection_upd(wlc, WLC_PROT_G_USER,
1805                                            wlc->band->gmode);
1806                 }
1807
1808                 /* init _n_enab supported mode */
1809                 if (WLC_PHY_11N_CAP(wlc->band) && CHIP_SUPPORTS_11N(wlc)) {
1810                         if (n_disabled & WLFEATURE_DISABLE_11N) {
1811                                 pub->_n_enab = OFF;
1812                                 wlc_protection_upd(wlc, WLC_PROT_N_USER, OFF);
1813                         } else {
1814                                 pub->_n_enab = SUPPORT_11N;
1815                                 wlc_protection_upd(wlc, WLC_PROT_N_USER,
1816                                                    ((pub->_n_enab ==
1817                                                      SUPPORT_11N) ? WL_11N_2x2 :
1818                                                     WL_11N_3x3));
1819                         }
1820                 }
1821
1822                 /* init per-band default rateset, depend on band->gmode */
1823                 wlc_default_rateset(wlc, &wlc->band->defrateset);
1824
1825                 /* fill in hw_rateset (used early by WLC_SET_RATESET) */
1826                 wlc_rateset_filter(&wlc->band->defrateset,
1827                                    &wlc->band->hw_rateset, false,
1828                                    WLC_RATES_CCK_OFDM, WLC_RATE_MASK,
1829                                    (bool) N_ENAB(wlc->pub));
1830         }
1831
1832         /* update antenna config due to wlc->stf->txant/txchain/ant_rx_ovr change */
1833         wlc_stf_phy_txant_upd(wlc);
1834
1835         /* attach each modules */
1836         err = wlc_attach_module(wlc);
1837         if (err != 0)
1838                 goto fail;
1839
1840         if (!wlc_timers_init(wlc, unit)) {
1841                 wiphy_err(wl->wiphy, "wl%d: %s: wlc_init_timer failed\n", unit,
1842                           __func__);
1843                 err = 32;
1844                 goto fail;
1845         }
1846
1847         /* depend on rateset, gmode */
1848         wlc->cmi = wlc_channel_mgr_attach(wlc);
1849         if (!wlc->cmi) {
1850                 wiphy_err(wl->wiphy, "wl%d: %s: wlc_channel_mgr_attach failed"
1851                           "\n", unit, __func__);
1852                 err = 33;
1853                 goto fail;
1854         }
1855
1856         /* init default when all parameters are ready, i.e. ->rateset */
1857         wlc_bss_default_init(wlc);
1858
1859         /*
1860          * Complete the wlc default state initializations..
1861          */
1862
1863         /* allocate our initial queue */
1864         qi = wlc_txq_alloc(wlc);
1865         if (qi == NULL) {
1866                 wiphy_err(wl->wiphy, "wl%d: %s: failed to malloc tx queue\n",
1867                           unit, __func__);
1868                 err = 100;
1869                 goto fail;
1870         }
1871         wlc->active_queue = qi;
1872
1873         wlc->bsscfg[0] = wlc->cfg;
1874         wlc->cfg->_idx = 0;
1875         wlc->cfg->wlc = wlc;
1876         pub->txmaxpkts = MAXTXPKTS;
1877
1878         pub->_cnt->version = WL_CNT_T_VERSION;
1879         pub->_cnt->length = sizeof(struct wl_cnt);
1880
1881         WLCNTSET(pub->_wme_cnt->version, WL_WME_CNT_VERSION);
1882         WLCNTSET(pub->_wme_cnt->length, sizeof(wl_wme_cnt_t));
1883
1884         wlc_wme_initparams_sta(wlc, &wlc->wme_param_ie);
1885
1886         wlc->mimoft = FT_HT;
1887         wlc->ht_cap.cap_info = HT_CAP;
1888         if (HT_ENAB(wlc->pub))
1889                 wlc->stf->ldpc = AUTO;
1890
1891         wlc->mimo_40txbw = AUTO;
1892         wlc->ofdm_40txbw = AUTO;
1893         wlc->cck_40txbw = AUTO;
1894         wlc_update_mimo_band_bwcap(wlc, WLC_N_BW_20IN2G_40IN5G);
1895
1896         /* Enable setting the RIFS Mode bit by default in HT Info IE */
1897         wlc->rifs_advert = AUTO;
1898
1899         /* Set default values of SGI */
1900         if (WLC_SGI_CAP_PHY(wlc)) {
1901                 wlc_ht_update_sgi_rx(wlc, (WLC_N_SGI_20 | WLC_N_SGI_40));
1902                 wlc->sgi_tx = AUTO;
1903         } else if (WLCISSSLPNPHY(wlc->band)) {
1904                 wlc_ht_update_sgi_rx(wlc, (WLC_N_SGI_20 | WLC_N_SGI_40));
1905                 wlc->sgi_tx = AUTO;
1906         } else {
1907                 wlc_ht_update_sgi_rx(wlc, 0);
1908                 wlc->sgi_tx = OFF;
1909         }
1910
1911         /* *******nvram 11n config overrides Start ********* */
1912
1913         /* apply the sgi override from nvram conf */
1914         if (n_disabled & WLFEATURE_DISABLE_11N_SGI_TX)
1915                 wlc->sgi_tx = OFF;
1916
1917         if (n_disabled & WLFEATURE_DISABLE_11N_SGI_RX)
1918                 wlc_ht_update_sgi_rx(wlc, 0);
1919
1920         /* apply the stbc override from nvram conf */
1921         if (n_disabled & WLFEATURE_DISABLE_11N_STBC_TX) {
1922                 wlc->bandstate[BAND_2G_INDEX]->band_stf_stbc_tx = OFF;
1923                 wlc->bandstate[BAND_5G_INDEX]->band_stf_stbc_tx = OFF;
1924                 wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_TX_STBC;
1925         }
1926         if (n_disabled & WLFEATURE_DISABLE_11N_STBC_RX)
1927                 wlc_stf_stbc_rx_set(wlc, HT_CAP_RX_STBC_NO);
1928
1929         /* apply the GF override from nvram conf */
1930         if (n_disabled & WLFEATURE_DISABLE_11N_GF)
1931                 wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_GRN_FLD;
1932
1933         /* initialize radio_mpc_disable according to wlc->mpc */
1934         wlc_radio_mpc_upd(wlc);
1935
1936         if ((wlc->pub->sih->chip) == BCM43235_CHIP_ID) {
1937                 if ((getintvar(wlc->pub->vars, "aa2g") == 7) ||
1938                     (getintvar(wlc->pub->vars, "aa5g") == 7)) {
1939                         wlc_bmac_antsel_set(wlc->hw, 1);
1940                 }
1941         } else {
1942                 wlc_bmac_antsel_set(wlc->hw, wlc->asi->antsel_avail);
1943         }
1944
1945         if (perr)
1946                 *perr = 0;
1947
1948         return (void *)wlc;
1949
1950  fail:
1951         wiphy_err(wl->wiphy, "wl%d: %s: failed with err %d\n",
1952                   unit, __func__, err);
1953         if (wlc)
1954                 wlc_detach(wlc);
1955
1956         if (perr)
1957                 *perr = err;
1958         return NULL;
1959 }
1960
1961 static void wlc_attach_antgain_init(struct wlc_info *wlc)
1962 {
1963         uint unit;
1964         unit = wlc->pub->unit;
1965
1966         if ((wlc->band->antgain == -1) && (wlc->pub->sromrev == 1)) {
1967                 /* default antenna gain for srom rev 1 is 2 dBm (8 qdbm) */
1968                 wlc->band->antgain = 8;
1969         } else if (wlc->band->antgain == -1) {
1970                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid antennas available in"
1971                           " srom, using 2dB\n", unit, __func__);
1972                 wlc->band->antgain = 8;
1973         } else {
1974                 s8 gain, fract;
1975                 /* Older sroms specified gain in whole dbm only.  In order
1976                  * be able to specify qdbm granularity and remain backward compatible
1977                  * the whole dbms are now encoded in only low 6 bits and remaining qdbms
1978                  * are encoded in the hi 2 bits. 6 bit signed number ranges from
1979                  * -32 - 31. Examples: 0x1 = 1 db,
1980                  * 0xc1 = 1.75 db (1 + 3 quarters),
1981                  * 0x3f = -1 (-1 + 0 quarters),
1982                  * 0x7f = -.75 (-1 in low 6 bits + 1 quarters in hi 2 bits) = -3 qdbm.
1983                  * 0xbf = -.50 (-1 in low 6 bits + 2 quarters in hi 2 bits) = -2 qdbm.
1984                  */
1985                 gain = wlc->band->antgain & 0x3f;
1986                 gain <<= 2;     /* Sign extend */
1987                 gain >>= 2;
1988                 fract = (wlc->band->antgain & 0xc0) >> 6;
1989                 wlc->band->antgain = 4 * gain + fract;
1990         }
1991 }
1992
1993 static bool wlc_attach_stf_ant_init(struct wlc_info *wlc)
1994 {
1995         int aa;
1996         uint unit;
1997         char *vars;
1998         int bandtype;
1999
2000         unit = wlc->pub->unit;
2001         vars = wlc->pub->vars;
2002         bandtype = wlc->band->bandtype;
2003
2004         /* get antennas available */
2005         aa = (s8) getintvar(vars, (BAND_5G(bandtype) ? "aa5g" : "aa2g"));
2006         if (aa == 0)
2007                 aa = (s8) getintvar(vars,
2008                                       (BAND_5G(bandtype) ? "aa1" : "aa0"));
2009         if ((aa < 1) || (aa > 15)) {
2010                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid antennas available in"
2011                           " srom (0x%x), using 3\n", unit, __func__, aa);
2012                 aa = 3;
2013         }
2014
2015         /* reset the defaults if we have a single antenna */
2016         if (aa == 1) {
2017                 wlc->stf->ant_rx_ovr = ANT_RX_DIV_FORCE_0;
2018                 wlc->stf->txant = ANT_TX_FORCE_0;
2019         } else if (aa == 2) {
2020                 wlc->stf->ant_rx_ovr = ANT_RX_DIV_FORCE_1;
2021                 wlc->stf->txant = ANT_TX_FORCE_1;
2022         } else {
2023         }
2024
2025         /* Compute Antenna Gain */
2026         wlc->band->antgain =
2027             (s8) getintvar(vars, (BAND_5G(bandtype) ? "ag1" : "ag0"));
2028         wlc_attach_antgain_init(wlc);
2029
2030         return true;
2031 }
2032
2033
2034 static void wlc_timers_deinit(struct wlc_info *wlc)
2035 {
2036         /* free timer state */
2037         if (wlc->wdtimer) {
2038                 wl_free_timer(wlc->wl, wlc->wdtimer);
2039                 wlc->wdtimer = NULL;
2040         }
2041         if (wlc->radio_timer) {
2042                 wl_free_timer(wlc->wl, wlc->radio_timer);
2043                 wlc->radio_timer = NULL;
2044         }
2045 }
2046
2047 static void wlc_detach_module(struct wlc_info *wlc)
2048 {
2049         if (wlc->asi) {
2050                 wlc_antsel_detach(wlc->asi);
2051                 wlc->asi = NULL;
2052         }
2053
2054         if (wlc->ampdu) {
2055                 wlc_ampdu_detach(wlc->ampdu);
2056                 wlc->ampdu = NULL;
2057         }
2058
2059         wlc_stf_detach(wlc);
2060 }
2061
2062 /*
2063  * Return a count of the number of driver callbacks still pending.
2064  *
2065  * General policy is that wlc_detach can only dealloc/free software states. It can NOT
2066  *  touch hardware registers since the d11core may be in reset and clock may not be available.
2067  *    One exception is sb register access, which is possible if crystal is turned on
2068  * After "down" state, driver should avoid software timer with the exception of radio_monitor.
2069  */
2070 uint wlc_detach(struct wlc_info *wlc)
2071 {
2072         uint i;
2073         uint callbacks = 0;
2074
2075         if (wlc == NULL)
2076                 return 0;
2077
2078         WL_TRACE("wl%d: %s\n", wlc->pub->unit, __func__);
2079
2080         ASSERT(!wlc->pub->up);
2081
2082         callbacks += wlc_bmac_detach(wlc);
2083
2084         /* delete software timers */
2085         if (!wlc_radio_monitor_stop(wlc))
2086                 callbacks++;
2087
2088         wlc_channel_mgr_detach(wlc->cmi);
2089
2090         wlc_timers_deinit(wlc);
2091
2092         wlc_detach_module(wlc);
2093
2094         /* free other state */
2095
2096
2097 #ifdef BCMDBG
2098         kfree(wlc->country_ie_override);
2099         wlc->country_ie_override = NULL;
2100 #endif                          /* BCMDBG */
2101
2102         {
2103                 /* free dumpcb list */
2104                 struct dumpcb_s *prev, *ptr;
2105                 prev = ptr = wlc->dumpcb_head;
2106                 while (ptr) {
2107                         ptr = prev->next;
2108                         kfree(prev);
2109                         prev = ptr;
2110                 }
2111                 wlc->dumpcb_head = NULL;
2112         }
2113
2114         /* Detach from iovar manager */
2115         wlc_module_unregister(wlc->pub, "wlc_iovars", wlc);
2116
2117         while (wlc->tx_queues != NULL)
2118                 wlc_txq_free(wlc, wlc->tx_queues);
2119
2120         /*
2121          * consistency check: wlc_module_register/wlc_module_unregister calls
2122          * should match therefore nothing should be left here.
2123          */
2124         for (i = 0; i < WLC_MAXMODULES; i++)
2125                 ASSERT(wlc->modulecb[i].name[0] == '\0');
2126
2127         wlc_detach_mfree(wlc);
2128         return callbacks;
2129 }
2130
2131 /* update state that depends on the current value of "ap" */
2132 void wlc_ap_upd(struct wlc_info *wlc)
2133 {
2134         if (AP_ENAB(wlc->pub))
2135                 wlc->PLCPHdr_override = WLC_PLCP_AUTO;  /* AP: short not allowed, but not enforced */
2136         else
2137                 wlc->PLCPHdr_override = WLC_PLCP_SHORT; /* STA-BSS; short capable */
2138
2139         /* disable vlan_mode on AP since some legacy STAs cannot rx tagged pkts */
2140         wlc->vlan_mode = AP_ENAB(wlc->pub) ? OFF : AUTO;
2141
2142         /* fixup mpc */
2143         wlc->mpc = true;
2144 }
2145
2146 /* read hwdisable state and propagate to wlc flag */
2147 static void wlc_radio_hwdisable_upd(struct wlc_info *wlc)
2148 {
2149         if (wlc->pub->wlfeatureflag & WL_SWFL_NOHWRADIO || wlc->pub->hw_off)
2150                 return;
2151
2152         if (wlc_bmac_radio_read_hwdisabled(wlc->hw)) {
2153                 mboolset(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE);
2154         } else {
2155                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE);
2156         }
2157 }
2158
2159 /* return true if Minimum Power Consumption should be entered, false otherwise */
2160 bool wlc_is_non_delay_mpc(struct wlc_info *wlc)
2161 {
2162         return false;
2163 }
2164
2165 bool wlc_ismpc(struct wlc_info *wlc)
2166 {
2167         return (wlc->mpc_delay_off == 0) && (wlc_is_non_delay_mpc(wlc));
2168 }
2169
2170 void wlc_radio_mpc_upd(struct wlc_info *wlc)
2171 {
2172         bool mpc_radio, radio_state;
2173
2174         /*
2175          * Clear the WL_RADIO_MPC_DISABLE bit when mpc feature is disabled
2176          * in case the WL_RADIO_MPC_DISABLE bit was set. Stop the radio
2177          * monitor also when WL_RADIO_MPC_DISABLE is the only reason that
2178          * the radio is going down.
2179          */
2180         if (!wlc->mpc) {
2181                 if (!wlc->pub->radio_disabled)
2182                         return;
2183                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE);
2184                 wlc_radio_upd(wlc);
2185                 if (!wlc->pub->radio_disabled)
2186                         wlc_radio_monitor_stop(wlc);
2187                 return;
2188         }
2189
2190         /*
2191          * sync ismpc logic with WL_RADIO_MPC_DISABLE bit in wlc->pub->radio_disabled
2192          * to go ON, always call radio_upd synchronously
2193          * to go OFF, postpone radio_upd to later when context is safe(e.g. watchdog)
2194          */
2195         radio_state =
2196             (mboolisset(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE) ? OFF :
2197              ON);
2198         mpc_radio = (wlc_ismpc(wlc) == true) ? OFF : ON;
2199
2200         if (radio_state == ON && mpc_radio == OFF)
2201                 wlc->mpc_delay_off = wlc->mpc_dlycnt;
2202         else if (radio_state == OFF && mpc_radio == ON) {
2203                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE);
2204                 wlc_radio_upd(wlc);
2205                 if (wlc->mpc_offcnt < WLC_MPC_THRESHOLD) {
2206                         wlc->mpc_dlycnt = WLC_MPC_MAX_DELAYCNT;
2207                 } else
2208                         wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
2209                 wlc->mpc_dur += OSL_SYSUPTIME() - wlc->mpc_laston_ts;
2210         }
2211         /* Below logic is meant to capture the transition from mpc off to mpc on for reasons
2212          * other than wlc->mpc_delay_off keeping the mpc off. In that case reset
2213          * wlc->mpc_delay_off to wlc->mpc_dlycnt, so that we restart the countdown of mpc_delay_off
2214          */
2215         if ((wlc->prev_non_delay_mpc == false) &&
2216             (wlc_is_non_delay_mpc(wlc) == true) && wlc->mpc_delay_off) {
2217                 wlc->mpc_delay_off = wlc->mpc_dlycnt;
2218         }
2219         wlc->prev_non_delay_mpc = wlc_is_non_delay_mpc(wlc);
2220 }
2221
2222 /*
2223  * centralized radio disable/enable function,
2224  * invoke radio enable/disable after updating hwradio status
2225  */
2226 static void wlc_radio_upd(struct wlc_info *wlc)
2227 {
2228         if (wlc->pub->radio_disabled) {
2229                 wlc_radio_disable(wlc);
2230         } else {
2231                 wlc_radio_enable(wlc);
2232         }
2233 }
2234
2235 /* maintain LED behavior in down state */
2236 static void wlc_down_led_upd(struct wlc_info *wlc)
2237 {
2238         ASSERT(!wlc->pub->up);
2239
2240         /* maintain LEDs while in down state, turn on sbclk if not available yet */
2241         /* turn on sbclk if necessary */
2242         if (!AP_ENAB(wlc->pub)) {
2243                 wlc_pllreq(wlc, true, WLC_PLLREQ_FLIP);
2244
2245                 wlc_pllreq(wlc, false, WLC_PLLREQ_FLIP);
2246         }
2247 }
2248
2249 /* update hwradio status and return it */
2250 bool wlc_check_radio_disabled(struct wlc_info *wlc)
2251 {
2252         wlc_radio_hwdisable_upd(wlc);
2253
2254         return mboolisset(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE) ? true : false;
2255 }
2256
2257 void wlc_radio_disable(struct wlc_info *wlc)
2258 {
2259         if (!wlc->pub->up) {
2260                 wlc_down_led_upd(wlc);
2261                 return;
2262         }
2263
2264         wlc_radio_monitor_start(wlc);
2265         wl_down(wlc->wl);
2266 }
2267
2268 static void wlc_radio_enable(struct wlc_info *wlc)
2269 {
2270         if (wlc->pub->up)
2271                 return;
2272
2273         if (DEVICEREMOVED(wlc))
2274                 return;
2275
2276         if (!wlc->down_override) {      /* imposed by wl down/out ioctl */
2277                 wl_up(wlc->wl);
2278         }
2279 }
2280
2281 /* periodical query hw radio button while driver is "down" */
2282 static void wlc_radio_timer(void *arg)
2283 {
2284         struct wlc_info *wlc = (struct wlc_info *) arg;
2285
2286         if (DEVICEREMOVED(wlc)) {
2287                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
2288                         __func__);
2289                 wl_down(wlc->wl);
2290                 return;
2291         }
2292
2293         /* cap mpc off count */
2294         if (wlc->mpc_offcnt < WLC_MPC_MAX_DELAYCNT)
2295                 wlc->mpc_offcnt++;
2296
2297         /* validate all the reasons driver could be down and running this radio_timer */
2298         ASSERT(wlc->pub->radio_disabled || wlc->down_override);
2299         wlc_radio_hwdisable_upd(wlc);
2300         wlc_radio_upd(wlc);
2301 }
2302
2303 static bool wlc_radio_monitor_start(struct wlc_info *wlc)
2304 {
2305         /* Don't start the timer if HWRADIO feature is disabled */
2306         if (wlc->radio_monitor || (wlc->pub->wlfeatureflag & WL_SWFL_NOHWRADIO))
2307                 return true;
2308
2309         wlc->radio_monitor = true;
2310         wlc_pllreq(wlc, true, WLC_PLLREQ_RADIO_MON);
2311         wl_add_timer(wlc->wl, wlc->radio_timer, TIMER_INTERVAL_RADIOCHK, true);
2312         return true;
2313 }
2314
2315 bool wlc_radio_monitor_stop(struct wlc_info *wlc)
2316 {
2317         if (!wlc->radio_monitor)
2318                 return true;
2319
2320         ASSERT((wlc->pub->wlfeatureflag & WL_SWFL_NOHWRADIO) !=
2321                WL_SWFL_NOHWRADIO);
2322
2323         wlc->radio_monitor = false;
2324         wlc_pllreq(wlc, false, WLC_PLLREQ_RADIO_MON);
2325         return wl_del_timer(wlc->wl, wlc->radio_timer);
2326 }
2327
2328 /* bring the driver down, but don't reset hardware */
2329 void wlc_out(struct wlc_info *wlc)
2330 {
2331         wlc_bmac_set_noreset(wlc->hw, true);
2332         wlc_radio_upd(wlc);
2333         wl_down(wlc->wl);
2334         wlc_bmac_set_noreset(wlc->hw, false);
2335
2336         /* core clk is true in BMAC driver due to noreset, need to mirror it in HIGH */
2337         wlc->clk = true;
2338
2339         /* This will make sure that when 'up' is done
2340          * after 'out' it'll restore hardware (especially gpios)
2341          */
2342         wlc->pub->hw_up = false;
2343 }
2344
2345 #if defined(BCMDBG)
2346 /* Verify the sanity of wlc->tx_prec_map. This can be done only by making sure that
2347  * if there is no packet pending for the FIFO, then the corresponding prec bits should be set
2348  * in prec_map. Of course, ignore this rule when block_datafifo is set
2349  */
2350 static bool wlc_tx_prec_map_verify(struct wlc_info *wlc)
2351 {
2352         /* For non-WME, both fifos have overlapping prec_map. So it's an error only if both
2353          * fail the check.
2354          */
2355         if (!EDCF_ENAB(wlc->pub)) {
2356                 if (!(WLC_TX_FIFO_CHECK(wlc, TX_DATA_FIFO) ||
2357                       WLC_TX_FIFO_CHECK(wlc, TX_CTL_FIFO)))
2358                         return false;
2359                 else
2360                         return true;
2361         }
2362
2363         return WLC_TX_FIFO_CHECK(wlc, TX_AC_BK_FIFO)
2364                 && WLC_TX_FIFO_CHECK(wlc, TX_AC_BE_FIFO)
2365                 && WLC_TX_FIFO_CHECK(wlc, TX_AC_VI_FIFO)
2366                 && WLC_TX_FIFO_CHECK(wlc, TX_AC_VO_FIFO);
2367 }
2368 #endif                          /* BCMDBG */
2369
2370 static void wlc_watchdog_by_timer(void *arg)
2371 {
2372         struct wlc_info *wlc = (struct wlc_info *) arg;
2373         wlc_watchdog(arg);
2374         if (WLC_WATCHDOG_TBTT(wlc)) {
2375                 /* set to normal osl watchdog period */
2376                 wl_del_timer(wlc->wl, wlc->wdtimer);
2377                 wl_add_timer(wlc->wl, wlc->wdtimer, TIMER_INTERVAL_WATCHDOG,
2378                              true);
2379         }
2380 }
2381
2382 /* common watchdog code */
2383 static void wlc_watchdog(void *arg)
2384 {
2385         struct wlc_info *wlc = (struct wlc_info *) arg;
2386         int i;
2387         struct wlc_bsscfg *cfg;
2388
2389         WL_TRACE("wl%d: wlc_watchdog\n", wlc->pub->unit);
2390
2391         if (!wlc->pub->up)
2392                 return;
2393
2394         if (DEVICEREMOVED(wlc)) {
2395                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
2396                           __func__);
2397                 wl_down(wlc->wl);
2398                 return;
2399         }
2400
2401         /* increment second count */
2402         wlc->pub->now++;
2403
2404         /* delay radio disable */
2405         if (wlc->mpc_delay_off) {
2406                 if (--wlc->mpc_delay_off == 0) {
2407                         mboolset(wlc->pub->radio_disabled,
2408                                  WL_RADIO_MPC_DISABLE);
2409                         if (wlc->mpc && wlc_ismpc(wlc))
2410                                 wlc->mpc_offcnt = 0;
2411                         wlc->mpc_laston_ts = OSL_SYSUPTIME();
2412                 }
2413         }
2414
2415         /* mpc sync */
2416         wlc_radio_mpc_upd(wlc);
2417         /* radio sync: sw/hw/mpc --> radio_disable/radio_enable */
2418         wlc_radio_hwdisable_upd(wlc);
2419         wlc_radio_upd(wlc);
2420         /* if ismpc, driver should be in down state if up/down is allowed */
2421         if (wlc->mpc && wlc_ismpc(wlc))
2422                 ASSERT(!wlc->pub->up);
2423         /* if radio is disable, driver may be down, quit here */
2424         if (wlc->pub->radio_disabled)
2425                 return;
2426
2427         wlc_bmac_watchdog(wlc);
2428
2429         /* occasionally sample mac stat counters to detect 16-bit counter wrap */
2430         if ((wlc->pub->now % SW_TIMER_MAC_STAT_UPD) == 0)
2431                 wlc_statsupd(wlc);
2432
2433         /* Manage TKIP countermeasures timers */
2434         FOREACH_BSS(wlc, i, cfg) {
2435                 if (cfg->tk_cm_dt) {
2436                         cfg->tk_cm_dt--;
2437                 }
2438                 if (cfg->tk_cm_bt) {
2439                         cfg->tk_cm_bt--;
2440                 }
2441         }
2442
2443         /* Call any registered watchdog handlers */
2444         for (i = 0; i < WLC_MAXMODULES; i++) {
2445                 if (wlc->modulecb[i].watchdog_fn)
2446                         wlc->modulecb[i].watchdog_fn(wlc->modulecb[i].hdl);
2447         }
2448
2449         if (WLCISNPHY(wlc->band) && !wlc->pub->tempsense_disable &&
2450             ((wlc->pub->now - wlc->tempsense_lasttime) >=
2451              WLC_TEMPSENSE_PERIOD)) {
2452                 wlc->tempsense_lasttime = wlc->pub->now;
2453                 wlc_tempsense_upd(wlc);
2454         }
2455         /* BMAC_NOTE: for HIGH_ONLY driver, this seems being called after RPC bus failed */
2456         ASSERT(wlc_bmac_taclear(wlc->hw, true));
2457
2458         /* Verify that tx_prec_map and fifos are in sync to avoid lock ups */
2459         ASSERT(wlc_tx_prec_map_verify(wlc));
2460
2461         ASSERT(wlc_ps_check(wlc));
2462 }
2463
2464 /* make interface operational */
2465 int wlc_up(struct wlc_info *wlc)
2466 {
2467         WL_TRACE("wl%d: %s:\n", wlc->pub->unit, __func__);
2468
2469         /* HW is turned off so don't try to access it */
2470         if (wlc->pub->hw_off || DEVICEREMOVED(wlc))
2471                 return -BCME_RADIOOFF;
2472
2473         if (!wlc->pub->hw_up) {
2474                 wlc_bmac_hw_up(wlc->hw);
2475                 wlc->pub->hw_up = true;
2476         }
2477
2478         if ((wlc->pub->boardflags & BFL_FEM)
2479             && (wlc->pub->sih->chip == BCM4313_CHIP_ID)) {
2480                 if (wlc->pub->boardrev >= 0x1250
2481                     && (wlc->pub->boardflags & BFL_FEM_BT)) {
2482                         wlc_mhf(wlc, MHF5, MHF5_4313_GPIOCTRL,
2483                                 MHF5_4313_GPIOCTRL, WLC_BAND_ALL);
2484                 } else {
2485                         wlc_mhf(wlc, MHF4, MHF4_EXTPA_ENABLE, MHF4_EXTPA_ENABLE,
2486                                 WLC_BAND_ALL);
2487                 }
2488         }
2489
2490         /*
2491          * Need to read the hwradio status here to cover the case where the system
2492          * is loaded with the hw radio disabled. We do not want to bring the driver up in this case.
2493          * if radio is disabled, abort up, lower power, start radio timer and return 0(for NDIS)
2494          * don't call radio_update to avoid looping wlc_up.
2495          *
2496          * wlc_bmac_up_prep() returns either 0 or -BCME_RADIOOFF only
2497          */
2498         if (!wlc->pub->radio_disabled) {
2499                 int status = wlc_bmac_up_prep(wlc->hw);
2500                 if (status == -BCME_RADIOOFF) {
2501                         if (!mboolisset
2502                             (wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE)) {
2503                                 int idx;
2504                                 struct wlc_bsscfg *bsscfg;
2505                                 mboolset(wlc->pub->radio_disabled,
2506                                          WL_RADIO_HW_DISABLE);
2507
2508                                 FOREACH_BSS(wlc, idx, bsscfg) {
2509                                         if (!BSSCFG_STA(bsscfg)
2510                                             || !bsscfg->enable || !bsscfg->BSS)
2511                                                 continue;
2512                                         wiphy_err(wlc->wiphy, "wl%d.%d: wlc_up"
2513                                                   ": rfdisable -> "
2514                                                   "wlc_bsscfg_disable()\n",
2515                                                    wlc->pub->unit, idx);
2516                                 }
2517                         }
2518                 } else
2519                         ASSERT(!status);
2520         }
2521
2522         if (wlc->pub->radio_disabled) {
2523                 wlc_radio_monitor_start(wlc);
2524                 return 0;
2525         }
2526
2527         /* wlc_bmac_up_prep has done wlc_corereset(). so clk is on, set it */
2528         wlc->clk = true;
2529
2530         wlc_radio_monitor_stop(wlc);
2531
2532         /* Set EDCF hostflags */
2533         if (EDCF_ENAB(wlc->pub)) {
2534                 wlc_mhf(wlc, MHF1, MHF1_EDCF, MHF1_EDCF, WLC_BAND_ALL);
2535         } else {
2536                 wlc_mhf(wlc, MHF1, MHF1_EDCF, 0, WLC_BAND_ALL);
2537         }
2538
2539         if (WLC_WAR16165(wlc))
2540                 wlc_mhf(wlc, MHF2, MHF2_PCISLOWCLKWAR, MHF2_PCISLOWCLKWAR,
2541                         WLC_BAND_ALL);
2542
2543         wl_init(wlc->wl);
2544         wlc->pub->up = true;
2545
2546         if (wlc->bandinit_pending) {
2547                 wlc_suspend_mac_and_wait(wlc);
2548                 wlc_set_chanspec(wlc, wlc->default_bss->chanspec);
2549                 wlc->bandinit_pending = false;
2550                 wlc_enable_mac(wlc);
2551         }
2552
2553         wlc_bmac_up_finish(wlc->hw);
2554
2555         /* other software states up after ISR is running */
2556         /* start APs that were to be brought up but are not up  yet */
2557         /* if (AP_ENAB(wlc->pub)) wlc_restart_ap(wlc->ap); */
2558
2559         /* Program the TX wme params with the current settings */
2560         wlc_wme_retries_write(wlc);
2561
2562         /* start one second watchdog timer */
2563         ASSERT(!wlc->WDarmed);
2564         wl_add_timer(wlc->wl, wlc->wdtimer, TIMER_INTERVAL_WATCHDOG, true);
2565         wlc->WDarmed = true;
2566
2567         /* ensure antenna config is up to date */
2568         wlc_stf_phy_txant_upd(wlc);
2569         /* ensure LDPC config is in sync */
2570         wlc_ht_update_ldpc(wlc, wlc->stf->ldpc);
2571
2572         return 0;
2573 }
2574
2575 /* Initialize the base precedence map for dequeueing from txq based on WME settings */
2576 static void wlc_tx_prec_map_init(struct wlc_info *wlc)
2577 {
2578         wlc->tx_prec_map = WLC_PREC_BMP_ALL;
2579         memset(wlc->fifo2prec_map, 0, NFIFO * sizeof(u16));
2580
2581         /* For non-WME, both fifos have overlapping MAXPRIO. So just disable all precedences
2582          * if either is full.
2583          */
2584         if (!EDCF_ENAB(wlc->pub)) {
2585                 wlc->fifo2prec_map[TX_DATA_FIFO] = WLC_PREC_BMP_ALL;
2586                 wlc->fifo2prec_map[TX_CTL_FIFO] = WLC_PREC_BMP_ALL;
2587         } else {
2588                 wlc->fifo2prec_map[TX_AC_BK_FIFO] = WLC_PREC_BMP_AC_BK;
2589                 wlc->fifo2prec_map[TX_AC_BE_FIFO] = WLC_PREC_BMP_AC_BE;
2590                 wlc->fifo2prec_map[TX_AC_VI_FIFO] = WLC_PREC_BMP_AC_VI;
2591                 wlc->fifo2prec_map[TX_AC_VO_FIFO] = WLC_PREC_BMP_AC_VO;
2592         }
2593 }
2594
2595 static uint wlc_down_del_timer(struct wlc_info *wlc)
2596 {
2597         uint callbacks = 0;
2598
2599         return callbacks;
2600 }
2601
2602 /*
2603  * Mark the interface nonoperational, stop the software mechanisms,
2604  * disable the hardware, free any transient buffer state.
2605  * Return a count of the number of driver callbacks still pending.
2606  */
2607 uint wlc_down(struct wlc_info *wlc)
2608 {
2609
2610         uint callbacks = 0;
2611         int i;
2612         bool dev_gone = false;
2613         struct wlc_txq_info *qi;
2614
2615         WL_TRACE("wl%d: %s:\n", wlc->pub->unit, __func__);
2616
2617         /* check if we are already in the going down path */
2618         if (wlc->going_down) {
2619                 wiphy_err(wlc->wiphy, "wl%d: %s: Driver going down so return"
2620                           "\n", wlc->pub->unit, __func__);
2621                 return 0;
2622         }
2623         if (!wlc->pub->up)
2624                 return callbacks;
2625
2626         /* in between, mpc could try to bring down again.. */
2627         wlc->going_down = true;
2628
2629         callbacks += wlc_bmac_down_prep(wlc->hw);
2630
2631         dev_gone = DEVICEREMOVED(wlc);
2632
2633         /* Call any registered down handlers */
2634         for (i = 0; i < WLC_MAXMODULES; i++) {
2635                 if (wlc->modulecb[i].down_fn)
2636                         callbacks +=
2637                             wlc->modulecb[i].down_fn(wlc->modulecb[i].hdl);
2638         }
2639
2640         /* cancel the watchdog timer */
2641         if (wlc->WDarmed) {
2642                 if (!wl_del_timer(wlc->wl, wlc->wdtimer))
2643                         callbacks++;
2644                 wlc->WDarmed = false;
2645         }
2646         /* cancel all other timers */
2647         callbacks += wlc_down_del_timer(wlc);
2648
2649         /* interrupt must have been blocked */
2650         ASSERT((wlc->macintmask == 0) || !wlc->pub->up);
2651
2652         wlc->pub->up = false;
2653
2654         wlc_phy_mute_upd(wlc->band->pi, false, PHY_MUTE_ALL);
2655
2656         /* clear txq flow control */
2657         wlc_txflowcontrol_reset(wlc);
2658
2659         /* flush tx queues */
2660         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
2661                 pktq_flush(&qi->q, true, NULL, 0);
2662                 ASSERT(pktq_empty(&qi->q));
2663         }
2664
2665         callbacks += wlc_bmac_down_finish(wlc->hw);
2666
2667         /* wlc_bmac_down_finish has done wlc_coredisable(). so clk is off */
2668         wlc->clk = false;
2669
2670 #ifdef BCMDBG
2671         /* Since all the packets should have been freed,
2672          * all callbacks should have been called
2673          */
2674         for (i = 1; i <= wlc->pub->tunables->maxpktcb; i++)
2675                 ASSERT(wlc->pkt_callback[i].fn == NULL);
2676 #endif
2677         wlc->going_down = false;
2678         return callbacks;
2679 }
2680
2681 /* Set the current gmode configuration */
2682 int wlc_set_gmode(struct wlc_info *wlc, u8 gmode, bool config)
2683 {
2684         int ret = 0;
2685         uint i;
2686         wlc_rateset_t rs;
2687         /* Default to 54g Auto */
2688         s8 shortslot = WLC_SHORTSLOT_AUTO;      /* Advertise and use shortslot (-1/0/1 Auto/Off/On) */
2689         bool shortslot_restrict = false;        /* Restrict association to stations that support shortslot
2690                                                  */
2691         bool ignore_bcns = true;        /* Ignore legacy beacons on the same channel */
2692         bool ofdm_basic = false;        /* Make 6, 12, and 24 basic rates */
2693         int preamble = WLC_PLCP_LONG;   /* Advertise and use short preambles (-1/0/1 Auto/Off/On) */
2694         bool preamble_restrict = false; /* Restrict association to stations that support short
2695                                          * preambles
2696                                          */
2697         struct wlcband *band;
2698
2699         /* if N-support is enabled, allow Gmode set as long as requested
2700          * Gmode is not GMODE_LEGACY_B
2701          */
2702         if (N_ENAB(wlc->pub) && gmode == GMODE_LEGACY_B)
2703                 return -BCME_UNSUPPORTED;
2704
2705         /* verify that we are dealing with 2G band and grab the band pointer */
2706         if (wlc->band->bandtype == WLC_BAND_2G)
2707                 band = wlc->band;
2708         else if ((NBANDS(wlc) > 1) &&
2709                  (wlc->bandstate[OTHERBANDUNIT(wlc)]->bandtype == WLC_BAND_2G))
2710                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
2711         else
2712                 return -BCME_BADBAND;
2713
2714         /* Legacy or bust when no OFDM is supported by regulatory */
2715         if ((wlc_channel_locale_flags_in_band(wlc->cmi, band->bandunit) &
2716              WLC_NO_OFDM) && (gmode != GMODE_LEGACY_B))
2717                 return -BCME_RANGE;
2718
2719         /* update configuration value */
2720         if (config == true)
2721                 wlc_protection_upd(wlc, WLC_PROT_G_USER, gmode);
2722
2723         /* Clear supported rates filter */
2724         memset(&wlc->sup_rates_override, 0, sizeof(wlc_rateset_t));
2725
2726         /* Clear rateset override */
2727         memset(&rs, 0, sizeof(wlc_rateset_t));
2728
2729         switch (gmode) {
2730         case GMODE_LEGACY_B:
2731                 shortslot = WLC_SHORTSLOT_OFF;
2732                 wlc_rateset_copy(&gphy_legacy_rates, &rs);
2733
2734                 break;
2735
2736         case GMODE_LRS:
2737                 if (AP_ENAB(wlc->pub))
2738                         wlc_rateset_copy(&cck_rates, &wlc->sup_rates_override);
2739                 break;
2740
2741         case GMODE_AUTO:
2742                 /* Accept defaults */
2743                 break;
2744
2745         case GMODE_ONLY:
2746                 ofdm_basic = true;
2747                 preamble = WLC_PLCP_SHORT;
2748                 preamble_restrict = true;
2749                 break;
2750
2751         case GMODE_PERFORMANCE:
2752                 if (AP_ENAB(wlc->pub))  /* Put all rates into the Supported Rates element */
2753                         wlc_rateset_copy(&cck_ofdm_rates,
2754                                          &wlc->sup_rates_override);
2755
2756                 shortslot = WLC_SHORTSLOT_ON;
2757                 shortslot_restrict = true;
2758                 ofdm_basic = true;
2759                 preamble = WLC_PLCP_SHORT;
2760                 preamble_restrict = true;
2761                 break;
2762
2763         default:
2764                 /* Error */
2765                 wiphy_err(wlc->wiphy, "wl%d: %s: invalid gmode %d\n",
2766                           wlc->pub->unit, __func__, gmode);
2767                 return -BCME_UNSUPPORTED;
2768         }
2769
2770         /*
2771          * If we are switching to gmode == GMODE_LEGACY_B,
2772          * clean up rate info that may refer to OFDM rates.
2773          */
2774         if ((gmode == GMODE_LEGACY_B) && (band->gmode != GMODE_LEGACY_B)) {
2775                 band->gmode = gmode;
2776                 if (band->rspec_override && !IS_CCK(band->rspec_override)) {
2777                         band->rspec_override = 0;
2778                         wlc_reprate_init(wlc);
2779                 }
2780                 if (band->mrspec_override && !IS_CCK(band->mrspec_override)) {
2781                         band->mrspec_override = 0;
2782                 }
2783         }
2784
2785         band->gmode = gmode;
2786
2787         wlc->ignore_bcns = ignore_bcns;
2788
2789         wlc->shortslot_override = shortslot;
2790
2791         if (AP_ENAB(wlc->pub)) {
2792                 /* wlc->ap->shortslot_restrict = shortslot_restrict; */
2793                 wlc->PLCPHdr_override =
2794                     (preamble !=
2795                      WLC_PLCP_LONG) ? WLC_PLCP_SHORT : WLC_PLCP_AUTO;
2796         }
2797
2798         if ((AP_ENAB(wlc->pub) && preamble != WLC_PLCP_LONG)
2799             || preamble == WLC_PLCP_SHORT)
2800                 wlc->default_bss->capability |= WLAN_CAPABILITY_SHORT_PREAMBLE;
2801         else
2802                 wlc->default_bss->capability &= ~WLAN_CAPABILITY_SHORT_PREAMBLE;
2803
2804         /* Update shortslot capability bit for AP and IBSS */
2805         if ((AP_ENAB(wlc->pub) && shortslot == WLC_SHORTSLOT_AUTO) ||
2806             shortslot == WLC_SHORTSLOT_ON)
2807                 wlc->default_bss->capability |= WLAN_CAPABILITY_SHORT_SLOT_TIME;
2808         else
2809                 wlc->default_bss->capability &=
2810                                         ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
2811
2812         /* Use the default 11g rateset */
2813         if (!rs.count)
2814                 wlc_rateset_copy(&cck_ofdm_rates, &rs);
2815
2816         if (ofdm_basic) {
2817                 for (i = 0; i < rs.count; i++) {
2818                         if (rs.rates[i] == WLC_RATE_6M
2819                             || rs.rates[i] == WLC_RATE_12M
2820                             || rs.rates[i] == WLC_RATE_24M)
2821                                 rs.rates[i] |= WLC_RATE_FLAG;
2822                 }
2823         }
2824
2825         /* Set default bss rateset */
2826         wlc->default_bss->rateset.count = rs.count;
2827         memcpy(wlc->default_bss->rateset.rates, rs.rates, 
2828                sizeof(wlc->default_bss->rateset.rates));
2829
2830         return ret;
2831 }
2832
2833 static int wlc_nmode_validate(struct wlc_info *wlc, s32 nmode)
2834 {
2835         int err = 0;
2836
2837         switch (nmode) {
2838
2839         case OFF:
2840                 break;
2841
2842         case AUTO:
2843         case WL_11N_2x2:
2844         case WL_11N_3x3:
2845                 if (!(WLC_PHY_11N_CAP(wlc->band)))
2846                         err = -BCME_BADBAND;
2847                 break;
2848
2849         default:
2850                 err = -BCME_RANGE;
2851                 break;
2852         }
2853
2854         return err;
2855 }
2856
2857 int wlc_set_nmode(struct wlc_info *wlc, s32 nmode)
2858 {
2859         uint i;
2860         int err;
2861
2862         err = wlc_nmode_validate(wlc, nmode);
2863         ASSERT(err == 0);
2864         if (err)
2865                 return err;
2866
2867         switch (nmode) {
2868         case OFF:
2869                 wlc->pub->_n_enab = OFF;
2870                 wlc->default_bss->flags &= ~WLC_BSS_HT;
2871                 /* delete the mcs rates from the default and hw ratesets */
2872                 wlc_rateset_mcs_clear(&wlc->default_bss->rateset);
2873                 for (i = 0; i < NBANDS(wlc); i++) {
2874                         memset(wlc->bandstate[i]->hw_rateset.mcs, 0,
2875                                MCSSET_LEN);
2876                         if (IS_MCS(wlc->band->rspec_override)) {
2877                                 wlc->bandstate[i]->rspec_override = 0;
2878                                 wlc_reprate_init(wlc);
2879                         }
2880                         if (IS_MCS(wlc->band->mrspec_override))
2881                                 wlc->bandstate[i]->mrspec_override = 0;
2882                 }
2883                 break;
2884
2885         case AUTO:
2886                 if (wlc->stf->txstreams == WL_11N_3x3)
2887                         nmode = WL_11N_3x3;
2888                 else
2889                         nmode = WL_11N_2x2;
2890         case WL_11N_2x2:
2891         case WL_11N_3x3:
2892                 ASSERT(WLC_PHY_11N_CAP(wlc->band));
2893                 /* force GMODE_AUTO if NMODE is ON */
2894                 wlc_set_gmode(wlc, GMODE_AUTO, true);
2895                 if (nmode == WL_11N_3x3)
2896                         wlc->pub->_n_enab = SUPPORT_HT;
2897                 else
2898                         wlc->pub->_n_enab = SUPPORT_11N;
2899                 wlc->default_bss->flags |= WLC_BSS_HT;
2900                 /* add the mcs rates to the default and hw ratesets */
2901                 wlc_rateset_mcs_build(&wlc->default_bss->rateset,
2902                                       wlc->stf->txstreams);
2903                 for (i = 0; i < NBANDS(wlc); i++)
2904                         memcpy(wlc->bandstate[i]->hw_rateset.mcs,
2905                                wlc->default_bss->rateset.mcs, MCSSET_LEN);
2906                 break;
2907
2908         default:
2909                 ASSERT(0);
2910                 break;
2911         }
2912
2913         return err;
2914 }
2915
2916 static int wlc_set_rateset(struct wlc_info *wlc, wlc_rateset_t *rs_arg)
2917 {
2918         wlc_rateset_t rs, new;
2919         uint bandunit;
2920
2921         memcpy(&rs, rs_arg, sizeof(wlc_rateset_t));
2922
2923         /* check for bad count value */
2924         if ((rs.count == 0) || (rs.count > WLC_NUMRATES))
2925                 return -BCME_BADRATESET;
2926
2927         /* try the current band */
2928         bandunit = wlc->band->bandunit;
2929         memcpy(&new, &rs, sizeof(wlc_rateset_t));
2930         if (wlc_rate_hwrs_filter_sort_validate
2931             (&new, &wlc->bandstate[bandunit]->hw_rateset, true,
2932              wlc->stf->txstreams))
2933                 goto good;
2934
2935         /* try the other band */
2936         if (IS_MBAND_UNLOCKED(wlc)) {
2937                 bandunit = OTHERBANDUNIT(wlc);
2938                 memcpy(&new, &rs, sizeof(wlc_rateset_t));
2939                 if (wlc_rate_hwrs_filter_sort_validate(&new,
2940                                                        &wlc->
2941                                                        bandstate[bandunit]->
2942                                                        hw_rateset, true,
2943                                                        wlc->stf->txstreams))
2944                         goto good;
2945         }
2946
2947         return -BCME_ERROR;
2948
2949  good:
2950         /* apply new rateset */
2951         memcpy(&wlc->default_bss->rateset, &new, sizeof(wlc_rateset_t));
2952         memcpy(&wlc->bandstate[bandunit]->defrateset, &new,
2953                sizeof(wlc_rateset_t));
2954         return 0;
2955 }
2956
2957 /* simplified integer set interface for common ioctl handler */
2958 int wlc_set(struct wlc_info *wlc, int cmd, int arg)
2959 {
2960         return wlc_ioctl(wlc, cmd, (void *)&arg, sizeof(arg), NULL);
2961 }
2962
2963 /* simplified integer get interface for common ioctl handler */
2964 int wlc_get(struct wlc_info *wlc, int cmd, int *arg)
2965 {
2966         return wlc_ioctl(wlc, cmd, arg, sizeof(int), NULL);
2967 }
2968
2969 static void wlc_ofdm_rateset_war(struct wlc_info *wlc)
2970 {
2971         u8 r;
2972         bool war = false;
2973
2974         if (wlc->cfg->associated)
2975                 r = wlc->cfg->current_bss->rateset.rates[0];
2976         else
2977                 r = wlc->default_bss->rateset.rates[0];
2978
2979         wlc_phy_ofdm_rateset_war(wlc->band->pi, war);
2980
2981         return;
2982 }
2983
2984 int
2985 wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
2986           struct wlc_if *wlcif)
2987 {
2988         return _wlc_ioctl(wlc, cmd, arg, len, wlcif);
2989 }
2990
2991 /* common ioctl handler. return: 0=ok, -1=error, positive=particular error */
2992 static int
2993 _wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
2994            struct wlc_if *wlcif)
2995 {
2996         int val, *pval;
2997         bool bool_val;
2998         int bcmerror;
2999         d11regs_t *regs;
3000         uint i;
3001         struct scb *nextscb;
3002         bool ta_ok;
3003         uint band;
3004         rw_reg_t *r;
3005         struct wlc_bsscfg *bsscfg;
3006         wlc_bss_info_t *current_bss;
3007
3008         /* update bsscfg pointer */
3009         bsscfg = wlc->cfg;
3010         current_bss = bsscfg->current_bss;
3011
3012         /* initialize the following to get rid of compiler warning */
3013         nextscb = NULL;
3014         ta_ok = false;
3015         band = 0;
3016         r = NULL;
3017
3018         /* If the device is turned off, then it's not "removed" */
3019         if (!wlc->pub->hw_off && DEVICEREMOVED(wlc)) {
3020                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
3021                           __func__);
3022                 wl_down(wlc->wl);
3023                 return -BCME_ERROR;
3024         }
3025
3026         ASSERT(!(wlc->pub->hw_off && wlc->pub->up));
3027
3028         /* default argument is generic integer */
3029         pval = arg ? (int *)arg:NULL;
3030
3031         /* This will prevent the misaligned access */
3032         if (pval && (u32) len >= sizeof(val))
3033                 memcpy(&val, pval, sizeof(val));
3034         else
3035                 val = 0;
3036
3037         /* bool conversion to avoid duplication below */
3038         bool_val = val != 0;
3039         bcmerror = 0;
3040         regs = wlc->regs;
3041
3042         /* A few commands don't need any arguments; all the others do. */
3043         switch (cmd) {
3044         case WLC_UP:
3045         case WLC_OUT:
3046         case WLC_DOWN:
3047         case WLC_DISASSOC:
3048         case WLC_RESTART:
3049         case WLC_REBOOT:
3050         case WLC_START_CHANNEL_QA:
3051         case WLC_INIT:
3052                 break;
3053
3054         default:
3055                 if ((arg == NULL) || (len <= 0)) {
3056                         wiphy_err(wlc->wiphy, "wl%d: %s: Command %d needs "
3057                                   "arguments\n",
3058                                   wlc->pub->unit, __func__, cmd);
3059                         bcmerror = -BCME_BADARG;
3060                         goto done;
3061                 }
3062         }
3063
3064         switch (cmd) {
3065
3066 #if defined(BCMDBG)
3067         case WLC_GET_MSGLEVEL:
3068                 *pval = wl_msg_level;
3069                 break;
3070
3071         case WLC_SET_MSGLEVEL:
3072                 wl_msg_level = val;
3073                 break;
3074 #endif
3075
3076         case WLC_GET_INSTANCE:
3077                 *pval = wlc->pub->unit;
3078                 break;
3079
3080         case WLC_GET_CHANNEL:{
3081                         channel_info_t *ci = (channel_info_t *) arg;
3082
3083                         ASSERT(len > (int)sizeof(ci));
3084
3085                         ci->hw_channel =
3086                             CHSPEC_CHANNEL(WLC_BAND_PI_RADIO_CHANSPEC);
3087                         ci->target_channel =
3088                             CHSPEC_CHANNEL(wlc->default_bss->chanspec);
3089                         ci->scan_channel = 0;
3090
3091                         break;
3092                 }
3093
3094         case WLC_SET_CHANNEL:{
3095                         chanspec_t chspec = CH20MHZ_CHSPEC(val);
3096
3097                         if (val < 0 || val > MAXCHANNEL) {
3098                                 bcmerror = -BCME_OUTOFRANGECHAN;
3099                                 break;
3100                         }
3101
3102                         if (!wlc_valid_chanspec_db(wlc->cmi, chspec)) {
3103                                 bcmerror = -BCME_BADCHAN;
3104                                 break;
3105                         }
3106
3107                         if (!wlc->pub->up && IS_MBAND_UNLOCKED(wlc)) {
3108                                 if (wlc->band->bandunit !=
3109                                     CHSPEC_WLCBANDUNIT(chspec))
3110                                         wlc->bandinit_pending = true;
3111                                 else
3112                                         wlc->bandinit_pending = false;
3113                         }
3114
3115                         wlc->default_bss->chanspec = chspec;
3116                         /* wlc_BSSinit() will sanitize the rateset before using it.. */
3117                         if (wlc->pub->up &&
3118                             (WLC_BAND_PI_RADIO_CHANSPEC != chspec)) {
3119                                 wlc_set_home_chanspec(wlc, chspec);
3120                                 wlc_suspend_mac_and_wait(wlc);
3121                                 wlc_set_chanspec(wlc, chspec);
3122                                 wlc_enable_mac(wlc);
3123                         }
3124                         break;
3125                 }
3126
3127 #if defined(BCMDBG)
3128         case WLC_GET_UCFLAGS:
3129                 if (!wlc->pub->up) {
3130                         bcmerror = -BCME_NOTUP;
3131                         break;
3132                 }
3133
3134                 /* optional band is stored in the second integer of incoming buffer */
3135                 band =
3136                     (len <
3137                      (int)(2 * sizeof(int))) ? WLC_BAND_AUTO : ((int *)arg)[1];
3138
3139                 /* bcmerror checking */
3140                 bcmerror = wlc_iocregchk(wlc, band);
3141                 if (bcmerror)
3142                         break;
3143
3144                 if (val >= MHFMAX) {
3145                         bcmerror = -BCME_RANGE;
3146                         break;
3147                 }
3148
3149                 *pval = wlc_bmac_mhf_get(wlc->hw, (u8) val, WLC_BAND_AUTO);
3150                 break;
3151
3152         case WLC_SET_UCFLAGS:
3153                 if (!wlc->pub->up) {
3154                         bcmerror = -BCME_NOTUP;
3155                         break;
3156                 }
3157
3158                 /* optional band is stored in the second integer of incoming buffer */
3159                 band =
3160                     (len <
3161                      (int)(2 * sizeof(int))) ? WLC_BAND_AUTO : ((int *)arg)[1];
3162
3163                 /* bcmerror checking */
3164                 bcmerror = wlc_iocregchk(wlc, band);
3165                 if (bcmerror)
3166                         break;
3167
3168                 i = (u16) val;
3169                 if (i >= MHFMAX) {
3170                         bcmerror = -BCME_RANGE;
3171                         break;
3172                 }
3173
3174                 wlc_mhf(wlc, (u8) i, 0xffff, (u16) (val >> NBITS(u16)),
3175                         WLC_BAND_AUTO);
3176                 break;
3177
3178         case WLC_GET_SHMEM:
3179                 ta_ok = true;
3180
3181                 /* optional band is stored in the second integer of incoming buffer */
3182                 band =
3183                     (len <
3184                      (int)(2 * sizeof(int))) ? WLC_BAND_AUTO : ((int *)arg)[1];
3185
3186                 /* bcmerror checking */
3187                 bcmerror = wlc_iocregchk(wlc, band);
3188                 if (bcmerror)
3189                         break;
3190
3191                 if (val & 1) {
3192                         bcmerror = -BCME_BADADDR;
3193                         break;
3194                 }
3195
3196                 *pval = wlc_read_shm(wlc, (u16) val);
3197                 break;
3198
3199         case WLC_SET_SHMEM:
3200                 ta_ok = true;
3201
3202                 /* optional band is stored in the second integer of incoming buffer */
3203                 band =
3204                     (len <
3205                      (int)(2 * sizeof(int))) ? WLC_BAND_AUTO : ((int *)arg)[1];
3206
3207                 /* bcmerror checking */
3208                 bcmerror = wlc_iocregchk(wlc, band);
3209                 if (bcmerror)
3210                         break;
3211
3212                 if (val & 1) {
3213                         bcmerror = -BCME_BADADDR;
3214                         break;
3215                 }
3216
3217                 wlc_write_shm(wlc, (u16) val,
3218                               (u16) (val >> NBITS(u16)));
3219                 break;
3220
3221         case WLC_R_REG: /* MAC registers */
3222                 ta_ok = true;
3223                 r = (rw_reg_t *) arg;
3224                 band = WLC_BAND_AUTO;
3225
3226                 if (len < (int)(sizeof(rw_reg_t) - sizeof(uint))) {
3227                         bcmerror = -BCME_BUFTOOSHORT;
3228                         break;
3229                 }
3230
3231                 if (len >= (int)sizeof(rw_reg_t))
3232                         band = r->band;
3233
3234                 /* bcmerror checking */
3235                 bcmerror = wlc_iocregchk(wlc, band);
3236                 if (bcmerror)
3237                         break;
3238
3239                 if ((r->byteoff + r->size) > sizeof(d11regs_t)) {
3240                         bcmerror = -BCME_BADADDR;
3241                         break;
3242                 }
3243                 if (r->size == sizeof(u32))
3244                         r->val =
3245                             R_REG((u32 *)((unsigned char *)(unsigned long)regs +
3246                                               r->byteoff));
3247                 else if (r->size == sizeof(u16))
3248                         r->val =
3249                             R_REG((u16 *)((unsigned char *)(unsigned long)regs +
3250                                               r->byteoff));
3251                 else
3252                         bcmerror = -BCME_BADADDR;
3253                 break;
3254
3255         case WLC_W_REG:
3256                 ta_ok = true;
3257                 r = (rw_reg_t *) arg;
3258                 band = WLC_BAND_AUTO;
3259
3260                 if (len < (int)(sizeof(rw_reg_t) - sizeof(uint))) {
3261                         bcmerror = -BCME_BUFTOOSHORT;
3262                         break;
3263                 }
3264
3265                 if (len >= (int)sizeof(rw_reg_t))
3266                         band = r->band;
3267
3268                 /* bcmerror checking */
3269                 bcmerror = wlc_iocregchk(wlc, band);
3270                 if (bcmerror)
3271                         break;
3272
3273                 if (r->byteoff + r->size > sizeof(d11regs_t)) {
3274                         bcmerror = -BCME_BADADDR;
3275                         break;
3276                 }
3277                 if (r->size == sizeof(u32))
3278                         W_REG((u32 *)((unsigned char *)(unsigned long) regs +
3279                                           r->byteoff), r->val);
3280                 else if (r->size == sizeof(u16))
3281                         W_REG((u16 *)((unsigned char *)(unsigned long) regs +
3282                                           r->byteoff), r->val);
3283                 else
3284                         bcmerror = -BCME_BADADDR;
3285                 break;
3286 #endif                          /* BCMDBG */
3287
3288         case WLC_GET_TXANT:
3289                 *pval = wlc->stf->txant;
3290                 break;
3291
3292         case WLC_SET_TXANT:
3293                 bcmerror = wlc_stf_ant_txant_validate(wlc, (s8) val);
3294                 if (bcmerror < 0)
3295                         break;
3296
3297                 wlc->stf->txant = (s8) val;
3298
3299                 /* if down, we are done */
3300                 if (!wlc->pub->up)
3301                         break;
3302
3303                 wlc_suspend_mac_and_wait(wlc);
3304
3305                 wlc_stf_phy_txant_upd(wlc);
3306                 wlc_beacon_phytxctl_txant_upd(wlc, wlc->bcn_rspec);
3307
3308                 wlc_enable_mac(wlc);
3309
3310                 break;
3311
3312         case WLC_GET_ANTDIV:{
3313                         u8 phy_antdiv;
3314
3315                         /* return configured value if core is down */
3316                         if (!wlc->pub->up) {
3317                                 *pval = wlc->stf->ant_rx_ovr;
3318
3319                         } else {
3320                                 if (wlc_phy_ant_rxdiv_get
3321                                     (wlc->band->pi, &phy_antdiv))
3322                                         *pval = (int)phy_antdiv;
3323                                 else
3324                                         *pval = (int)wlc->stf->ant_rx_ovr;
3325                         }
3326
3327                         break;
3328                 }
3329         case WLC_SET_ANTDIV:
3330                 /* values are -1=driver default, 0=force0, 1=force1, 2=start1, 3=start0 */
3331                 if ((val < -1) || (val > 3)) {
3332                         bcmerror = -BCME_RANGE;
3333                         break;
3334                 }
3335
3336                 if (val == -1)
3337                         val = ANT_RX_DIV_DEF;
3338
3339                 wlc->stf->ant_rx_ovr = (u8) val;
3340                 wlc_phy_ant_rxdiv_set(wlc->band->pi, (u8) val);
3341                 break;
3342
3343         case WLC_GET_RX_ANT:{   /* get latest used rx antenna */
3344                         u16 rxstatus;
3345
3346                         if (!wlc->pub->up) {
3347                                 bcmerror = -BCME_NOTUP;
3348                                 break;
3349                         }
3350
3351                         rxstatus = R_REG(&wlc->regs->phyrxstatus0);
3352                         if (rxstatus == 0xdead || rxstatus == (u16) -1) {
3353                                 bcmerror = -BCME_ERROR;
3354                                 break;
3355                         }
3356                         *pval = (rxstatus & PRXS0_RXANT_UPSUBBAND) ? 1 : 0;
3357                         break;
3358                 }
3359
3360 #if defined(BCMDBG)
3361         case WLC_GET_UCANTDIV:
3362                 if (!wlc->clk) {
3363                         bcmerror = -BCME_NOCLK;
3364                         break;
3365                 }
3366
3367                 *pval =
3368                     (wlc_bmac_mhf_get(wlc->hw, MHF1, WLC_BAND_AUTO) &
3369                      MHF1_ANTDIV);
3370                 break;
3371
3372         case WLC_SET_UCANTDIV:{
3373                         if (!wlc->pub->up) {
3374                                 bcmerror = -BCME_NOTUP;
3375                                 break;
3376                         }
3377
3378                         /* if multiband, band must be locked */
3379                         if (IS_MBAND_UNLOCKED(wlc)) {
3380                                 bcmerror = -BCME_NOTBANDLOCKED;
3381                                 break;
3382                         }
3383
3384                         wlc_mhf(wlc, MHF1, MHF1_ANTDIV,
3385                                 (val ? MHF1_ANTDIV : 0), WLC_BAND_AUTO);
3386                         break;
3387                 }
3388 #endif                          /* defined(BCMDBG) */
3389
3390         case WLC_GET_SRL:
3391                 *pval = wlc->SRL;
3392                 break;
3393
3394         case WLC_SET_SRL:
3395                 if (val >= 1 && val <= RETRY_SHORT_MAX) {
3396                         int ac;
3397                         wlc->SRL = (u16) val;
3398
3399                         wlc_bmac_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
3400
3401                         for (ac = 0; ac < AC_COUNT; ac++) {
3402                                 WLC_WME_RETRY_SHORT_SET(wlc, ac, wlc->SRL);
3403                         }
3404                         wlc_wme_retries_write(wlc);
3405                 } else
3406                         bcmerror = -BCME_RANGE;
3407                 break;
3408
3409         case WLC_GET_LRL:
3410                 *pval = wlc->LRL;
3411                 break;
3412
3413         case WLC_SET_LRL:
3414                 if (val >= 1 && val <= 255) {
3415                         int ac;
3416                         wlc->LRL = (u16) val;
3417
3418                         wlc_bmac_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
3419
3420                         for (ac = 0; ac < AC_COUNT; ac++) {
3421                                 WLC_WME_RETRY_LONG_SET(wlc, ac, wlc->LRL);
3422                         }
3423                         wlc_wme_retries_write(wlc);
3424                 } else
3425                         bcmerror = -BCME_RANGE;
3426                 break;
3427
3428         case WLC_GET_CWMIN:
3429                 *pval = wlc->band->CWmin;
3430                 break;
3431
3432         case WLC_SET_CWMIN:
3433                 if (!wlc->clk) {
3434                         bcmerror = -BCME_NOCLK;
3435                         break;
3436                 }
3437
3438                 if (val >= 1 && val <= 255) {
3439                         wlc_set_cwmin(wlc, (u16) val);
3440                 } else
3441                         bcmerror = -BCME_RANGE;
3442                 break;
3443
3444         case WLC_GET_CWMAX:
3445                 *pval = wlc->band->CWmax;
3446                 break;
3447
3448         case WLC_SET_CWMAX:
3449                 if (!wlc->clk) {
3450                         bcmerror = -BCME_NOCLK;
3451                         break;
3452                 }
3453
3454                 if (val >= 255 && val <= 2047) {
3455                         wlc_set_cwmax(wlc, (u16) val);
3456                 } else
3457                         bcmerror = -BCME_RANGE;
3458                 break;
3459
3460         case WLC_GET_RADIO:     /* use mask if don't want to expose some internal bits */
3461                 *pval = wlc->pub->radio_disabled;
3462                 break;
3463
3464         case WLC_SET_RADIO:{    /* 32 bits input, higher 16 bits are mask, lower 16 bits are value to
3465                                  * set
3466                                  */
3467                         u16 radiomask, radioval;
3468                         uint validbits =
3469                             WL_RADIO_SW_DISABLE | WL_RADIO_HW_DISABLE;
3470                         mbool new = 0;
3471
3472                         radiomask = (val & 0xffff0000) >> 16;
3473                         radioval = val & 0x0000ffff;
3474
3475                         if ((radiomask == 0) || (radiomask & ~validbits)
3476                             || (radioval & ~validbits)
3477                             || ((radioval & ~radiomask) != 0)) {
3478                                 wiphy_err(wlc->wiphy, "SET_RADIO with wrong "
3479                                           "bits 0x%x\n", val);
3480                                 bcmerror = -BCME_RANGE;
3481                                 break;
3482                         }
3483
3484                         new =
3485                             (wlc->pub->radio_disabled & ~radiomask) | radioval;
3486                         wlc->pub->radio_disabled = new;
3487
3488                         wlc_radio_hwdisable_upd(wlc);
3489                         wlc_radio_upd(wlc);
3490                         break;
3491                 }
3492
3493         case WLC_GET_PHYTYPE:
3494                 *pval = WLC_PHYTYPE(wlc->band->phytype);
3495                 break;
3496
3497 #if defined(BCMDBG)
3498         case WLC_GET_KEY:
3499                 if ((val >= 0) && (val < WLC_MAX_WSEC_KEYS(wlc))) {
3500                         wl_wsec_key_t key;
3501
3502                         wsec_key_t *src_key = wlc->wsec_keys[val];
3503
3504                         if (len < (int)sizeof(key)) {
3505                                 bcmerror = -BCME_BUFTOOSHORT;
3506                                 break;
3507                         }
3508
3509                         memset((char *)&key, 0, sizeof(key));
3510                         if (src_key) {
3511                                 key.index = src_key->id;
3512                                 key.len = src_key->len;
3513                                 memcpy(key.data, src_key->data, key.len);
3514                                 key.algo = src_key->algo;
3515                                 if (WSEC_SOFTKEY(wlc, src_key, bsscfg))
3516                                         key.flags |= WL_SOFT_KEY;
3517                                 if (src_key->flags & WSEC_PRIMARY_KEY)
3518                                         key.flags |= WL_PRIMARY_KEY;
3519
3520                                 memcpy(key.ea, src_key->ea, ETH_ALEN);
3521                         }
3522
3523                         memcpy(arg, &key, sizeof(key));
3524                 } else
3525                         bcmerror = -BCME_BADKEYIDX;
3526                 break;
3527 #endif                          /* defined(BCMDBG) */
3528
3529         case WLC_SET_KEY:
3530                 bcmerror =
3531                     wlc_iovar_op(wlc, "wsec_key", NULL, 0, arg, len, IOV_SET,
3532                                  wlcif);
3533                 break;
3534
3535         case WLC_GET_KEY_SEQ:{
3536                         wsec_key_t *key;
3537
3538                         if (len < DOT11_WPA_KEY_RSC_LEN) {
3539                                 bcmerror = -BCME_BUFTOOSHORT;
3540                                 break;
3541                         }
3542
3543                         /* Return the key's tx iv as an EAPOL sequence counter.
3544                          * This will be used to supply the RSC value to a supplicant.
3545                          * The format is 8 bytes, with least significant in seq[0].
3546                          */
3547
3548                         key = WSEC_KEY(wlc, val);
3549                         if ((val >= 0) && (val < WLC_MAX_WSEC_KEYS(wlc)) &&
3550                                 (key != NULL)) {
3551                                 u8 seq[DOT11_WPA_KEY_RSC_LEN];
3552                                 u16 lo;
3553                                 u32 hi;
3554                                 /* group keys in WPA-NONE (IBSS only, AES and TKIP) use a global TXIV */
3555                                 if ((bsscfg->WPA_auth & WPA_AUTH_NONE) &&
3556                                     is_zero_ether_addr(key->ea)) {
3557                                         lo = bsscfg->wpa_none_txiv.lo;
3558                                         hi = bsscfg->wpa_none_txiv.hi;
3559                                 } else {
3560                                         lo = key->txiv.lo;
3561                                         hi = key->txiv.hi;
3562                                 }
3563
3564                                 /* format the buffer, low to high */
3565                                 seq[0] = lo & 0xff;
3566                                 seq[1] = (lo >> 8) & 0xff;
3567                                 seq[2] = hi & 0xff;
3568                                 seq[3] = (hi >> 8) & 0xff;
3569                                 seq[4] = (hi >> 16) & 0xff;
3570                                 seq[5] = (hi >> 24) & 0xff;
3571                                 seq[6] = 0;
3572                                 seq[7] = 0;
3573
3574                                 memcpy(arg, seq, sizeof(seq));
3575                         } else {
3576                                 bcmerror = -BCME_BADKEYIDX;
3577                         }
3578                         break;
3579                 }
3580
3581         case WLC_GET_CURR_RATESET:{
3582                         wl_rateset_t *ret_rs = (wl_rateset_t *) arg;
3583                         wlc_rateset_t *rs;
3584
3585                         if (wlc->pub->associated)
3586                                 rs = &current_bss->rateset;
3587                         else
3588                                 rs = &wlc->default_bss->rateset;
3589
3590                         if (len < (int)(rs->count + sizeof(rs->count))) {
3591                                 bcmerror = -BCME_BUFTOOSHORT;
3592                                 break;
3593                         }
3594
3595                         /* Copy only legacy rateset section */
3596                         ret_rs->count = rs->count;
3597                         memcpy(&ret_rs->rates, &rs->rates, rs->count);
3598                         break;
3599                 }
3600
3601         case WLC_GET_RATESET:{
3602                         wlc_rateset_t rs;
3603                         wl_rateset_t *ret_rs = (wl_rateset_t *) arg;
3604
3605                         memset(&rs, 0, sizeof(wlc_rateset_t));
3606                         wlc_default_rateset(wlc, (wlc_rateset_t *) &rs);
3607
3608                         if (len < (int)(rs.count + sizeof(rs.count))) {
3609                                 bcmerror = -BCME_BUFTOOSHORT;
3610                                 break;
3611                         }
3612
3613                         /* Copy only legacy rateset section */
3614                         ret_rs->count = rs.count;
3615                         memcpy(&ret_rs->rates, &rs.rates, rs.count);
3616                         break;
3617                 }
3618
3619         case WLC_SET_RATESET:{
3620                         wlc_rateset_t rs;
3621                         wl_rateset_t *in_rs = (wl_rateset_t *) arg;
3622
3623                         if (len < (int)(in_rs->count + sizeof(in_rs->count))) {
3624                                 bcmerror = -BCME_BUFTOOSHORT;
3625                                 break;
3626                         }
3627
3628                         if (in_rs->count > WLC_NUMRATES) {
3629                                 bcmerror = -BCME_BUFTOOLONG;
3630                                 break;
3631                         }
3632
3633                         memset(&rs, 0, sizeof(wlc_rateset_t));
3634
3635                         /* Copy only legacy rateset section */
3636                         rs.count = in_rs->count;
3637                         memcpy(&rs.rates, &in_rs->rates, rs.count);
3638
3639                         /* merge rateset coming in with the current mcsset */
3640                         if (N_ENAB(wlc->pub)) {
3641                                 if (bsscfg->associated)
3642                                         memcpy(rs.mcs,
3643                                                &current_bss->rateset.mcs[0],
3644                                                MCSSET_LEN);
3645                                 else
3646                                         memcpy(rs.mcs,
3647                                                &wlc->default_bss->rateset.mcs[0],
3648                                                MCSSET_LEN);
3649                         }
3650
3651                         bcmerror = wlc_set_rateset(wlc, &rs);
3652
3653                         if (!bcmerror)
3654                                 wlc_ofdm_rateset_war(wlc);
3655
3656                         break;
3657                 }
3658
3659         case WLC_GET_BCNPRD:
3660                 if (BSSCFG_STA(bsscfg) && bsscfg->BSS && bsscfg->associated)
3661                         *pval = current_bss->beacon_period;
3662                 else
3663                         *pval = wlc->default_bss->beacon_period;
3664                 break;
3665
3666         case WLC_SET_BCNPRD:
3667                 /* range [1, 0xffff] */
3668                 if (val >= DOT11_MIN_BEACON_PERIOD
3669                     && val <= DOT11_MAX_BEACON_PERIOD) {
3670                         wlc->default_bss->beacon_period = (u16) val;
3671                 } else
3672                         bcmerror = -BCME_RANGE;
3673                 break;
3674
3675         case WLC_GET_DTIMPRD:
3676                 if (BSSCFG_STA(bsscfg) && bsscfg->BSS && bsscfg->associated)
3677                         *pval = current_bss->dtim_period;
3678                 else
3679                         *pval = wlc->default_bss->dtim_period;
3680                 break;
3681
3682         case WLC_SET_DTIMPRD:
3683                 /* range [1, 0xff] */
3684                 if (val >= DOT11_MIN_DTIM_PERIOD
3685                     && val <= DOT11_MAX_DTIM_PERIOD) {
3686                         wlc->default_bss->dtim_period = (u8) val;
3687                 } else
3688                         bcmerror = -BCME_RANGE;
3689                 break;
3690
3691 #ifdef SUPPORT_PS
3692         case WLC_GET_PM:
3693                 *pval = wlc->PM;
3694                 break;
3695
3696         case WLC_SET_PM:
3697                 if ((val >= PM_OFF) && (val <= PM_MAX)) {
3698                         wlc->PM = (u8) val;
3699                         if (wlc->pub->up) {
3700                         }
3701                         /* Change watchdog driver to align watchdog with tbtt if possible */
3702                         wlc_watchdog_upd(wlc, PS_ALLOWED(wlc));
3703                 } else
3704                         bcmerror = -BCME_ERROR;
3705                 break;
3706 #endif                          /* SUPPORT_PS */
3707
3708 #ifdef SUPPORT_PS
3709 #ifdef BCMDBG
3710         case WLC_GET_WAKE:
3711                 if (AP_ENAB(wlc->pub)) {
3712                         bcmerror = -BCME_NOTSTA;
3713                         break;
3714                 }
3715                 *pval = wlc->wake;
3716                 break;
3717
3718         case WLC_SET_WAKE:
3719                 if (AP_ENAB(wlc->pub)) {
3720                         bcmerror = -BCME_NOTSTA;
3721                         break;
3722                 }
3723
3724                 wlc->wake = val ? true : false;
3725
3726                 /* if down, we're done */
3727                 if (!wlc->pub->up)
3728                         break;
3729
3730                 /* apply to the mac */
3731                 wlc_set_ps_ctrl(wlc);
3732                 break;
3733 #endif                          /* BCMDBG */
3734 #endif                          /* SUPPORT_PS */
3735
3736         case WLC_GET_REVINFO:
3737                 bcmerror = wlc_get_revision_info(wlc, arg, (uint) len);
3738                 break;
3739
3740         case WLC_GET_AP:
3741                 *pval = (int)AP_ENAB(wlc->pub);
3742                 break;
3743
3744         case WLC_GET_ATIM:
3745                 if (bsscfg->associated)
3746                         *pval = (int)current_bss->atim_window;
3747                 else
3748                         *pval = (int)wlc->default_bss->atim_window;
3749                 break;
3750
3751         case WLC_SET_ATIM:
3752                 wlc->default_bss->atim_window = (u32) val;
3753                 break;
3754
3755         case WLC_GET_PKTCNTS:{
3756                         get_pktcnt_t *pktcnt = (get_pktcnt_t *) pval;
3757                         wlc_statsupd(wlc);
3758                         pktcnt->rx_good_pkt = wlc->pub->_cnt->rxframe;
3759                         pktcnt->rx_bad_pkt = wlc->pub->_cnt->rxerror;
3760                         pktcnt->tx_good_pkt =
3761                             wlc->pub->_cnt->txfrmsnt;
3762                         pktcnt->tx_bad_pkt =
3763                             wlc->pub->_cnt->txerror +
3764                             wlc->pub->_cnt->txfail;
3765                         if (len >= (int)sizeof(get_pktcnt_t)) {
3766                                 /* Be backward compatible - only if buffer is large enough  */
3767                                 pktcnt->rx_ocast_good_pkt =
3768                                     wlc->pub->_cnt->rxmfrmocast;
3769                         }
3770                         break;
3771                 }
3772
3773 #ifdef SUPPORT_HWKEY
3774         case WLC_GET_WSEC:
3775                 bcmerror =
3776                     wlc_iovar_op(wlc, "wsec", NULL, 0, arg, len, IOV_GET,
3777                                  wlcif);
3778                 break;
3779
3780         case WLC_SET_WSEC:
3781                 bcmerror =
3782                     wlc_iovar_op(wlc, "wsec", NULL, 0, arg, len, IOV_SET,
3783                                  wlcif);
3784                 break;
3785
3786         case WLC_GET_WPA_AUTH:
3787                 *pval = (int)bsscfg->WPA_auth;
3788                 break;
3789
3790         case WLC_SET_WPA_AUTH:
3791                 /* change of WPA_Auth modifies the PS_ALLOWED state */
3792                 if (BSSCFG_STA(bsscfg)) {
3793                         bsscfg->WPA_auth = (u16) val;
3794                 } else
3795                         bsscfg->WPA_auth = (u16) val;
3796                 break;
3797 #endif                          /* SUPPORT_HWKEY */
3798
3799         case WLC_GET_BANDLIST:
3800                 /* count of number of bands, followed by each band type */
3801                 *pval++ = NBANDS(wlc);
3802                 *pval++ = wlc->band->bandtype;
3803                 if (NBANDS(wlc) > 1)
3804                         *pval++ = wlc->bandstate[OTHERBANDUNIT(wlc)]->bandtype;
3805                 break;
3806
3807         case WLC_GET_BAND:
3808                 *pval = wlc->bandlocked ? wlc->band->bandtype : WLC_BAND_AUTO;
3809                 break;
3810
3811         case WLC_GET_PHYLIST:
3812                 {
3813                         unsigned char *cp = arg;
3814                         if (len < 3) {
3815                                 bcmerror = -BCME_BUFTOOSHORT;
3816                                 break;
3817                         }
3818
3819                         if (WLCISNPHY(wlc->band)) {
3820                                 *cp++ = 'n';
3821                         } else if (WLCISLCNPHY(wlc->band)) {
3822                                 *cp++ = 'c';
3823                         } else if (WLCISSSLPNPHY(wlc->band)) {
3824                                 *cp++ = 's';
3825                         }
3826                         *cp = '\0';
3827                         break;
3828                 }
3829
3830         case WLC_GET_SHORTSLOT:
3831                 *pval = wlc->shortslot;
3832                 break;
3833
3834         case WLC_GET_SHORTSLOT_OVERRIDE:
3835                 *pval = wlc->shortslot_override;
3836                 break;
3837
3838         case WLC_SET_SHORTSLOT_OVERRIDE:
3839                 if ((val != WLC_SHORTSLOT_AUTO) &&
3840                     (val != WLC_SHORTSLOT_OFF) && (val != WLC_SHORTSLOT_ON)) {
3841                         bcmerror = -BCME_RANGE;
3842                         break;
3843                 }
3844
3845                 wlc->shortslot_override = (s8) val;
3846
3847                 /* shortslot is an 11g feature, so no more work if we are
3848                  * currently on the 5G band
3849                  */
3850                 if (BAND_5G(wlc->band->bandtype))
3851                         break;
3852
3853                 if (wlc->pub->up && wlc->pub->associated) {
3854                         /* let watchdog or beacon processing update shortslot */
3855                 } else if (wlc->pub->up) {
3856                         /* unassociated shortslot is off */
3857                         wlc_switch_shortslot(wlc, false);
3858                 } else {
3859                         /* driver is down, so just update the wlc_info value */
3860                         if (wlc->shortslot_override == WLC_SHORTSLOT_AUTO) {
3861                                 wlc->shortslot = false;
3862                         } else {
3863                                 wlc->shortslot =
3864                                     (wlc->shortslot_override ==
3865                                      WLC_SHORTSLOT_ON);
3866                         }
3867                 }
3868
3869                 break;
3870
3871         case WLC_GET_LEGACY_ERP:
3872                 *pval = wlc->include_legacy_erp;
3873                 break;
3874
3875         case WLC_SET_LEGACY_ERP:
3876                 if (wlc->include_legacy_erp == bool_val)
3877                         break;
3878
3879                 wlc->include_legacy_erp = bool_val;
3880
3881                 if (AP_ENAB(wlc->pub) && wlc->clk) {
3882                         wlc_update_beacon(wlc);
3883                         wlc_update_probe_resp(wlc, true);
3884                 }
3885                 break;
3886
3887         case WLC_GET_GMODE:
3888                 if (wlc->band->bandtype == WLC_BAND_2G)
3889                         *pval = wlc->band->gmode;
3890                 else if (NBANDS(wlc) > 1)
3891                         *pval = wlc->bandstate[OTHERBANDUNIT(wlc)]->gmode;
3892                 break;
3893
3894         case WLC_SET_GMODE:
3895                 if (!wlc->pub->associated)
3896                         bcmerror = wlc_set_gmode(wlc, (u8) val, true);
3897                 else {
3898                         bcmerror = -BCME_ASSOCIATED;
3899                         break;
3900                 }
3901                 break;
3902
3903         case WLC_GET_GMODE_PROTECTION:
3904                 *pval = wlc->protection->_g;
3905                 break;
3906
3907         case WLC_GET_PROTECTION_CONTROL:
3908                 *pval = wlc->protection->overlap;
3909                 break;
3910
3911         case WLC_SET_PROTECTION_CONTROL:
3912                 if ((val != WLC_PROTECTION_CTL_OFF) &&
3913                     (val != WLC_PROTECTION_CTL_LOCAL) &&
3914                     (val != WLC_PROTECTION_CTL_OVERLAP)) {
3915                         bcmerror = -BCME_RANGE;
3916                         break;
3917                 }
3918
3919                 wlc_protection_upd(wlc, WLC_PROT_OVERLAP, (s8) val);
3920
3921                 /* Current g_protection will sync up to the specified control alg in watchdog
3922                  * if the driver is up and associated.
3923                  * If the driver is down or not associated, the control setting has no effect.
3924                  */
3925                 break;
3926
3927         case WLC_GET_GMODE_PROTECTION_OVERRIDE:
3928                 *pval = wlc->protection->g_override;
3929                 break;
3930
3931         case WLC_SET_GMODE_PROTECTION_OVERRIDE:
3932                 if ((val != WLC_PROTECTION_AUTO) &&
3933                     (val != WLC_PROTECTION_OFF) && (val != WLC_PROTECTION_ON)) {
3934                         bcmerror = -BCME_RANGE;
3935                         break;
3936                 }
3937
3938                 wlc_protection_upd(wlc, WLC_PROT_G_OVR, (s8) val);
3939
3940                 break;
3941
3942         case WLC_SET_SUP_RATESET_OVERRIDE:{
3943                         wlc_rateset_t rs, new;
3944
3945                         /* copyin */
3946                         if (len < (int)sizeof(wlc_rateset_t)) {
3947                                 bcmerror = -BCME_BUFTOOSHORT;
3948                                 break;
3949                         }
3950                         memcpy(&rs, arg, sizeof(wlc_rateset_t));
3951
3952                         /* check for bad count value */
3953                         if (rs.count > WLC_NUMRATES) {
3954                                 bcmerror = -BCME_BADRATESET;
3955                                 break;
3956                         }
3957
3958                         /* this command is only appropriate for gmode operation */
3959                         if (!(wlc->band->gmode ||
3960                               ((NBANDS(wlc) > 1)
3961                                && wlc->bandstate[OTHERBANDUNIT(wlc)]->gmode))) {
3962                                 /* gmode only command when not in gmode */
3963                                 bcmerror = -BCME_BADBAND;
3964                                 break;
3965                         }
3966
3967                         /* check for an empty rateset to clear the override */
3968                         if (rs.count == 0) {
3969                                 memset(&wlc->sup_rates_override, 0,
3970                                       sizeof(wlc_rateset_t));
3971                                 break;
3972                         }
3973
3974                         /*
3975                          * validate rateset by comparing pre and
3976                          * post sorted against 11g hw rates
3977                          */
3978                         wlc_rateset_filter(&rs, &new, false,
3979                                            WLC_RATES_CCK_OFDM, WLC_RATE_MASK,
3980                                            BSS_N_ENAB(wlc, bsscfg));
3981                         wlc_rate_hwrs_filter_sort_validate(&new,
3982                                                            &cck_ofdm_rates,
3983                                                            false,
3984                                                            wlc->stf->txstreams);
3985                         if (rs.count != new.count) {
3986                                 bcmerror = -BCME_BADRATESET;
3987                                 break;
3988                         }
3989
3990                         /* apply new rateset to the override */
3991                         memcpy(&wlc->sup_rates_override, &new,
3992                               sizeof(wlc_rateset_t));
3993
3994                         /* update bcn and probe resp if needed */
3995                         if (wlc->pub->up && AP_ENAB(wlc->pub)
3996                             && wlc->pub->associated) {
3997                                 wlc_update_beacon(wlc);
3998                                 wlc_update_probe_resp(wlc, true);
3999                         }
4000                         break;
4001                 }
4002
4003         case WLC_GET_SUP_RATESET_OVERRIDE:
4004                 /* this command is only appropriate for gmode operation */
4005                 if (!(wlc->band->gmode ||
4006                       ((NBANDS(wlc) > 1)
4007                        && wlc->bandstate[OTHERBANDUNIT(wlc)]->gmode))) {
4008                         /* gmode only command when not in gmode */
4009                         bcmerror = -BCME_BADBAND;
4010                         break;
4011                 }
4012                 if (len < (int)sizeof(wlc_rateset_t)) {
4013                         bcmerror = -BCME_BUFTOOSHORT;
4014                         break;
4015                 }
4016                 memcpy(arg, &wlc->sup_rates_override, sizeof(wlc_rateset_t));
4017
4018                 break;
4019
4020         case WLC_GET_PRB_RESP_TIMEOUT:
4021                 *pval = wlc->prb_resp_timeout;
4022                 break;
4023
4024         case WLC_SET_PRB_RESP_TIMEOUT:
4025                 if (wlc->pub->up) {
4026                         bcmerror = -BCME_NOTDOWN;
4027                         break;
4028                 }
4029                 if (val < 0 || val >= 0xFFFF) {
4030                         bcmerror = -BCME_RANGE; /* bad value */
4031                         break;
4032                 }
4033                 wlc->prb_resp_timeout = (u16) val;
4034                 break;
4035
4036         case WLC_GET_KEY_PRIMARY:{
4037                         wsec_key_t *key;
4038
4039                         /* treat the 'val' parm as the key id */
4040                         key = WSEC_BSS_DEFAULT_KEY(bsscfg);
4041                         if (key != NULL) {
4042                                 *pval = key->id == val ? true : false;
4043                         } else {
4044                                 bcmerror = -BCME_BADKEYIDX;
4045                         }
4046                         break;
4047                 }
4048
4049         case WLC_SET_KEY_PRIMARY:{
4050                         wsec_key_t *key, *old_key;
4051
4052                         bcmerror = -BCME_BADKEYIDX;
4053
4054                         /* treat the 'val' parm as the key id */
4055                         for (i = 0; i < WSEC_MAX_DEFAULT_KEYS; i++) {
4056                                 key = bsscfg->bss_def_keys[i];
4057                                 if (key != NULL && key->id == val) {
4058                                         old_key = WSEC_BSS_DEFAULT_KEY(bsscfg);
4059                                         if (old_key != NULL)
4060                                                 old_key->flags &=
4061                                                     ~WSEC_PRIMARY_KEY;
4062                                         key->flags |= WSEC_PRIMARY_KEY;
4063                                         bsscfg->wsec_index = i;
4064                                         bcmerror = 0;
4065                                 }
4066                         }
4067                         break;
4068                 }
4069
4070 #ifdef BCMDBG
4071         case WLC_INIT:
4072                 wl_init(wlc->wl);
4073                 break;
4074 #endif
4075
4076         case WLC_SET_VAR:
4077         case WLC_GET_VAR:{
4078                         char *name;
4079                         /* validate the name value */
4080                         name = (char *)arg;
4081                         for (i = 0; i < (uint) len && *name != '\0';
4082                              i++, name++)
4083                                 ;
4084
4085                         if (i == (uint) len) {
4086                                 bcmerror = -BCME_BUFTOOSHORT;
4087                                 break;
4088                         }
4089                         i++;    /* include the null in the string length */
4090
4091                         if (cmd == WLC_GET_VAR) {
4092                                 bcmerror =
4093                                     wlc_iovar_op(wlc, arg,
4094                                                  (void *)((s8 *) arg + i),
4095                                                  len - i, arg, len, IOV_GET,
4096                                                  wlcif);
4097                         } else
4098                                 bcmerror =
4099                                     wlc_iovar_op(wlc, arg, NULL, 0,
4100                                                  (void *)((s8 *) arg + i),
4101                                                  len - i, IOV_SET, wlcif);
4102
4103                         break;
4104                 }
4105
4106         case WLC_SET_WSEC_PMK:
4107                 bcmerror = -BCME_UNSUPPORTED;
4108                 break;
4109
4110 #if defined(BCMDBG)
4111         case WLC_CURRENT_PWR:
4112                 if (!wlc->pub->up)
4113                         bcmerror = -BCME_NOTUP;
4114                 else
4115                         bcmerror = wlc_get_current_txpwr(wlc, arg, len);
4116                 break;
4117 #endif
4118
4119         case WLC_LAST:
4120                 wiphy_err(wlc->wiphy, "%s: WLC_LAST\n", __func__);
4121         }
4122  done:
4123
4124         if (bcmerror) {
4125                 if (VALID_BCMERROR(bcmerror))
4126                         wlc->pub->bcmerror = bcmerror;
4127                 else {
4128                         bcmerror = 0;
4129                 }
4130
4131         }
4132         /* BMAC_NOTE: for HIGH_ONLY driver, this seems being called after RPC bus failed */
4133         /* In hw_off condition, IOCTLs that reach here are deemed safe but taclear would
4134          * certainly result in getting -1 for register reads. So skip ta_clear altogether
4135          */
4136         if (!(wlc->pub->hw_off))
4137                 ASSERT(wlc_bmac_taclear(wlc->hw, ta_ok) || !ta_ok);
4138
4139         return bcmerror;
4140 }
4141
4142 #if defined(BCMDBG)
4143 /* consolidated register access ioctl error checking */
4144 int wlc_iocregchk(struct wlc_info *wlc, uint band)
4145 {
4146         /* if band is specified, it must be the current band */
4147         if ((band != WLC_BAND_AUTO) && (band != (uint) wlc->band->bandtype))
4148                 return -BCME_BADBAND;
4149
4150         /* if multiband and band is not specified, band must be locked */
4151         if ((band == WLC_BAND_AUTO) && IS_MBAND_UNLOCKED(wlc))
4152                 return -BCME_NOTBANDLOCKED;
4153
4154         /* must have core clocks */
4155         if (!wlc->clk)
4156                 return -BCME_NOCLK;
4157
4158         return 0;
4159 }
4160 #endif                          /* defined(BCMDBG) */
4161
4162 #if defined(BCMDBG)
4163 /* For some ioctls, make sure that the pi pointer matches the current phy */
4164 int wlc_iocpichk(struct wlc_info *wlc, uint phytype)
4165 {
4166         if (wlc->band->phytype != phytype)
4167                 return -BCME_BADBAND;
4168         return 0;
4169 }
4170 #endif
4171
4172 /* Look up the given var name in the given table */
4173 static const bcm_iovar_t *wlc_iovar_lookup(const bcm_iovar_t *table,
4174                                            const char *name)
4175 {
4176         const bcm_iovar_t *vi;
4177         const char *lookup_name;
4178
4179         /* skip any ':' delimited option prefixes */
4180         lookup_name = strrchr(name, ':');
4181         if (lookup_name != NULL)
4182                 lookup_name++;
4183         else
4184                 lookup_name = name;
4185
4186         ASSERT(table != NULL);
4187
4188         for (vi = table; vi->name; vi++) {
4189                 if (!strcmp(vi->name, lookup_name))
4190                         return vi;
4191         }
4192         /* ran to end of table */
4193
4194         return NULL;            /* var name not found */
4195 }
4196
4197 /* simplified integer get interface for common WLC_GET_VAR ioctl handler */
4198 int wlc_iovar_getint(struct wlc_info *wlc, const char *name, int *arg)
4199 {
4200         return wlc_iovar_op(wlc, name, NULL, 0, arg, sizeof(s32), IOV_GET,
4201                             NULL);
4202 }
4203
4204 /* simplified integer set interface for common WLC_SET_VAR ioctl handler */
4205 int wlc_iovar_setint(struct wlc_info *wlc, const char *name, int arg)
4206 {
4207         return wlc_iovar_op(wlc, name, NULL, 0, (void *)&arg, sizeof(arg),
4208                             IOV_SET, NULL);
4209 }
4210
4211 /* simplified s8 get interface for common WLC_GET_VAR ioctl handler */
4212 int wlc_iovar_gets8(struct wlc_info *wlc, const char *name, s8 *arg)
4213 {
4214         int iovar_int;
4215         int err;
4216
4217         err =
4218             wlc_iovar_op(wlc, name, NULL, 0, &iovar_int, sizeof(iovar_int),
4219                          IOV_GET, NULL);
4220         if (!err)
4221                 *arg = (s8) iovar_int;
4222
4223         return err;
4224 }
4225
4226 /*
4227  * register iovar table, watchdog and down handlers.
4228  * calling function must keep 'iovars' until wlc_module_unregister is called.
4229  * 'iovar' must have the last entry's name field being NULL as terminator.
4230  */
4231 int wlc_module_register(struct wlc_pub *pub, const bcm_iovar_t *iovars,
4232                         const char *name, void *hdl, iovar_fn_t i_fn,
4233                         watchdog_fn_t w_fn, down_fn_t d_fn)
4234 {
4235         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
4236         int i;
4237
4238         ASSERT(name != NULL);
4239         ASSERT(i_fn != NULL || w_fn != NULL || d_fn != NULL);
4240
4241         /* find an empty entry and just add, no duplication check! */
4242         for (i = 0; i < WLC_MAXMODULES; i++) {
4243                 if (wlc->modulecb[i].name[0] == '\0') {
4244                         strncpy(wlc->modulecb[i].name, name,
4245                                 sizeof(wlc->modulecb[i].name) - 1);
4246                         wlc->modulecb[i].iovars = iovars;
4247                         wlc->modulecb[i].hdl = hdl;
4248                         wlc->modulecb[i].iovar_fn = i_fn;
4249                         wlc->modulecb[i].watchdog_fn = w_fn;
4250                         wlc->modulecb[i].down_fn = d_fn;
4251                         return 0;
4252                 }
4253         }
4254
4255         /* it is time to increase the capacity */
4256         ASSERT(i < WLC_MAXMODULES);
4257         return -BCME_NORESOURCE;
4258 }
4259
4260 /* unregister module callbacks */
4261 int wlc_module_unregister(struct wlc_pub *pub, const char *name, void *hdl)
4262 {
4263         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
4264         int i;
4265
4266         if (wlc == NULL)
4267                 return -BCME_NOTFOUND;
4268
4269         ASSERT(name != NULL);
4270
4271         for (i = 0; i < WLC_MAXMODULES; i++) {
4272                 if (!strcmp(wlc->modulecb[i].name, name) &&
4273                     (wlc->modulecb[i].hdl == hdl)) {
4274                         memset(&wlc->modulecb[i], 0, sizeof(struct modulecb));
4275                         return 0;
4276                 }
4277         }
4278
4279         /* table not found! */
4280         return -BCME_NOTFOUND;
4281 }
4282
4283 /* Write WME tunable parameters for retransmit/max rate from wlc struct to ucode */
4284 static void wlc_wme_retries_write(struct wlc_info *wlc)
4285 {
4286         int ac;
4287
4288         /* Need clock to do this */
4289         if (!wlc->clk)
4290                 return;
4291
4292         for (ac = 0; ac < AC_COUNT; ac++) {
4293                 wlc_write_shm(wlc, M_AC_TXLMT_ADDR(ac), wlc->wme_retries[ac]);
4294         }
4295 }
4296
4297 /* Get or set an iovar.  The params/p_len pair specifies any additional
4298  * qualifying parameters (e.g. an "element index") for a get, while the
4299  * arg/len pair is the buffer for the value to be set or retrieved.
4300  * Operation (get/set) is specified by the last argument.
4301  * interface context provided by wlcif
4302  *
4303  * All pointers may point into the same buffer.
4304  */
4305 int
4306 wlc_iovar_op(struct wlc_info *wlc, const char *name,
4307              void *params, int p_len, void *arg, int len,
4308              bool set, struct wlc_if *wlcif)
4309 {
4310         int err = 0;
4311         int val_size;
4312         const bcm_iovar_t *vi = NULL;
4313         u32 actionid;
4314         int i;
4315
4316         ASSERT(name != NULL);
4317
4318         ASSERT(len >= 0);
4319
4320         /* Get MUST have return space */
4321         ASSERT(set || (arg && len));
4322
4323         ASSERT(!(wlc->pub->hw_off && wlc->pub->up));
4324
4325         /* Set does NOT take qualifiers */
4326         ASSERT(!set || (!params && !p_len));
4327
4328         if (!set && (len == sizeof(int)) &&
4329             !(IS_ALIGNED((unsigned long)(arg), (uint) sizeof(int)))) {
4330                 wiphy_err(wlc->wiphy, "wl%d: %s unaligned get ptr for %s\n",
4331                           wlc->pub->unit, __func__, name);
4332                 ASSERT(0);
4333         }
4334
4335         /* find the given iovar name */
4336         for (i = 0; i < WLC_MAXMODULES; i++) {
4337                 if (!wlc->modulecb[i].iovars)
4338                         continue;
4339                 vi = wlc_iovar_lookup(wlc->modulecb[i].iovars, name);
4340                 if (vi)
4341                         break;
4342         }
4343         /* iovar name not found */
4344         if (i >= WLC_MAXMODULES) {
4345                 err = -BCME_UNSUPPORTED;
4346                 goto exit;
4347         }
4348
4349         /* set up 'params' pointer in case this is a set command so that
4350          * the convenience int and bool code can be common to set and get
4351          */
4352         if (params == NULL) {
4353                 params = arg;
4354                 p_len = len;
4355         }
4356
4357         if (vi->type == IOVT_VOID)
4358                 val_size = 0;
4359         else if (vi->type == IOVT_BUFFER)
4360                 val_size = len;
4361         else
4362                 /* all other types are integer sized */
4363                 val_size = sizeof(int);
4364
4365         actionid = set ? IOV_SVAL(vi->varid) : IOV_GVAL(vi->varid);
4366
4367         /* Do the actual parameter implementation */
4368         err = wlc->modulecb[i].iovar_fn(wlc->modulecb[i].hdl, vi, actionid,
4369                                         name, params, p_len, arg, len, val_size,
4370                                         wlcif);
4371
4372  exit:
4373         return err;
4374 }
4375
4376 int
4377 wlc_iovar_check(struct wlc_pub *pub, const bcm_iovar_t *vi, void *arg, int len,
4378                 bool set)
4379 {
4380         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
4381         int err = 0;
4382         s32 int_val = 0;
4383
4384         /* check generic condition flags */
4385         if (set) {
4386                 if (((vi->flags & IOVF_SET_DOWN) && wlc->pub->up) ||
4387                     ((vi->flags & IOVF_SET_UP) && !wlc->pub->up)) {
4388                         err = (wlc->pub->up ? -BCME_NOTDOWN : -BCME_NOTUP);
4389                 } else if ((vi->flags & IOVF_SET_BAND)
4390                            && IS_MBAND_UNLOCKED(wlc)) {
4391                         err = -BCME_NOTBANDLOCKED;
4392                 } else if ((vi->flags & IOVF_SET_CLK) && !wlc->clk) {
4393                         err = -BCME_NOCLK;
4394                 }
4395         } else {
4396                 if (((vi->flags & IOVF_GET_DOWN) && wlc->pub->up) ||
4397                     ((vi->flags & IOVF_GET_UP) && !wlc->pub->up)) {
4398                         err = (wlc->pub->up ? -BCME_NOTDOWN : -BCME_NOTUP);
4399                 } else if ((vi->flags & IOVF_GET_BAND)
4400                            && IS_MBAND_UNLOCKED(wlc)) {
4401                         err = -BCME_NOTBANDLOCKED;
4402                 } else if ((vi->flags & IOVF_GET_CLK) && !wlc->clk) {
4403                         err = -BCME_NOCLK;
4404                 }
4405         }
4406
4407         if (err)
4408                 goto exit;
4409
4410         /* length check on io buf */
4411         err = bcm_iovar_lencheck(vi, arg, len, set);
4412         if (err)
4413                 goto exit;
4414
4415         /* On set, check value ranges for integer types */
4416         if (set) {
4417                 switch (vi->type) {
4418                 case IOVT_BOOL:
4419                 case IOVT_INT8:
4420                 case IOVT_INT16:
4421                 case IOVT_INT32:
4422                 case IOVT_UINT8:
4423                 case IOVT_UINT16:
4424                 case IOVT_UINT32:
4425                         memcpy(&int_val, arg, sizeof(int));
4426                         err = wlc_iovar_rangecheck(wlc, int_val, vi);
4427                         break;
4428                 }
4429         }
4430  exit:
4431         return err;
4432 }
4433
4434 /* handler for iovar table wlc_iovars */
4435 /*
4436  * IMPLEMENTATION NOTE: In order to avoid checking for get/set in each
4437  * iovar case, the switch statement maps the iovar id into separate get
4438  * and set values.  If you add a new iovar to the switch you MUST use
4439  * IOV_GVAL and/or IOV_SVAL in the case labels to avoid conflict with
4440  * another case.
4441  * Please use params for additional qualifying parameters.
4442  */
4443 int
4444 wlc_doiovar(void *hdl, const bcm_iovar_t *vi, u32 actionid,
4445             const char *name, void *params, uint p_len, void *arg, int len,
4446             int val_size, struct wlc_if *wlcif)
4447 {
4448         struct wlc_info *wlc = hdl;
4449         struct wlc_bsscfg *bsscfg;
4450         int err = 0;
4451         s32 int_val = 0;
4452         s32 int_val2 = 0;
4453         s32 *ret_int_ptr;
4454         bool bool_val;
4455         bool bool_val2;
4456         wlc_bss_info_t *current_bss;
4457
4458         WL_TRACE("wl%d: %s\n", wlc->pub->unit, __func__);
4459
4460         bsscfg = NULL;
4461         current_bss = NULL;
4462
4463         err = wlc_iovar_check(wlc->pub, vi, arg, len, IOV_ISSET(actionid));
4464         if (err != 0)
4465                 return err;
4466
4467         /* convenience int and bool vals for first 8 bytes of buffer */
4468         if (p_len >= (int)sizeof(int_val))
4469                 memcpy(&int_val, params, sizeof(int_val));
4470
4471         if (p_len >= (int)sizeof(int_val) * 2)
4472                 memcpy(&int_val2,
4473                        (void *)((unsigned long)params + sizeof(int_val)),
4474                        sizeof(int_val));
4475
4476         /* convenience int ptr for 4-byte gets (requires int aligned arg) */
4477         ret_int_ptr = (s32 *) arg;
4478
4479         bool_val = (int_val != 0) ? true : false;
4480         bool_val2 = (int_val2 != 0) ? true : false;
4481
4482         WL_TRACE("wl%d: %s: id %d\n",
4483                  wlc->pub->unit, __func__, IOV_ID(actionid));
4484         /* Do the actual parameter implementation */
4485         switch (actionid) {
4486         case IOV_SVAL(IOV_RTSTHRESH):
4487                 wlc->RTSThresh = int_val;
4488                 break;
4489
4490         case IOV_GVAL(IOV_QTXPOWER):{
4491                         uint qdbm;
4492                         bool override;
4493
4494                         err = wlc_phy_txpower_get(wlc->band->pi, &qdbm,
4495                                 &override);
4496                         if (err != 0)
4497                                 return err;
4498
4499                         /* Return qdbm units */
4500                         *ret_int_ptr =
4501                             qdbm | (override ? WL_TXPWR_OVERRIDE : 0);
4502                         break;
4503                 }
4504
4505                 /* As long as override is false, this only sets the *user* targets.
4506                    User can twiddle this all he wants with no harm.
4507                    wlc_phy_txpower_set() explicitly sets override to false if
4508                    not internal or test.
4509                  */
4510         case IOV_SVAL(IOV_QTXPOWER):{
4511                         u8 qdbm;
4512                         bool override;
4513
4514                         /* Remove override bit and clip to max qdbm value */
4515                         qdbm = (u8)min_t(u32, (int_val & ~WL_TXPWR_OVERRIDE), 0xff);
4516                         /* Extract override setting */
4517                         override = (int_val & WL_TXPWR_OVERRIDE) ? true : false;
4518                         err =
4519                             wlc_phy_txpower_set(wlc->band->pi, qdbm, override);
4520                         break;
4521                 }
4522
4523         case IOV_GVAL(IOV_MPC):
4524                 *ret_int_ptr = (s32) wlc->mpc;
4525                 break;
4526
4527         case IOV_SVAL(IOV_MPC):
4528                 wlc->mpc = bool_val;
4529                 wlc_radio_mpc_upd(wlc);
4530
4531                 break;
4532
4533         case IOV_GVAL(IOV_BCN_LI_BCN):
4534                 *ret_int_ptr = wlc->bcn_li_bcn;
4535                 break;
4536
4537         case IOV_SVAL(IOV_BCN_LI_BCN):
4538                 wlc->bcn_li_bcn = (u8) int_val;
4539                 if (wlc->pub->up)
4540                         wlc_bcn_li_upd(wlc);
4541                 break;
4542
4543         default:
4544                 wiphy_err(wlc->wiphy, "wl%d: %s: unsupported\n",
4545                           wlc->pub->unit, __func__);
4546                 err = -BCME_UNSUPPORTED;
4547                 break;
4548         }
4549
4550         goto exit;              /* avoid unused label warning */
4551
4552  exit:
4553         return err;
4554 }
4555
4556 static int
4557 wlc_iovar_rangecheck(struct wlc_info *wlc, u32 val, const bcm_iovar_t *vi)
4558 {
4559         int err = 0;
4560         u32 min_val = 0;
4561         u32 max_val = 0;
4562
4563         /* Only ranged integers are checked */
4564         switch (vi->type) {
4565         case IOVT_INT32:
4566                 max_val |= 0x7fffffff;
4567                 /* fall through */
4568         case IOVT_INT16:
4569                 max_val |= 0x00007fff;
4570                 /* fall through */
4571         case IOVT_INT8:
4572                 max_val |= 0x0000007f;
4573                 min_val = ~max_val;
4574                 if (vi->flags & IOVF_NTRL)
4575                         min_val = 1;
4576                 else if (vi->flags & IOVF_WHL)
4577                         min_val = 0;
4578                 /* Signed values are checked against max_val and min_val */
4579                 if ((s32) val < (s32) min_val
4580                     || (s32) val > (s32) max_val)
4581                         err = -BCME_RANGE;
4582                 break;
4583
4584         case IOVT_UINT32:
4585                 max_val |= 0xffffffff;
4586                 /* fall through */
4587         case IOVT_UINT16:
4588                 max_val |= 0x0000ffff;
4589                 /* fall through */
4590         case IOVT_UINT8:
4591                 max_val |= 0x000000ff;
4592                 if (vi->flags & IOVF_NTRL)
4593                         min_val = 1;
4594                 if ((val < min_val) || (val > max_val))
4595                         err = -BCME_RANGE;
4596                 break;
4597         }
4598
4599         return err;
4600 }
4601
4602 #ifdef BCMDBG
4603 static const char *supr_reason[] = {
4604         "None", "PMQ Entry", "Flush request",
4605         "Previous frag failure", "Channel mismatch",
4606         "Lifetime Expiry", "Underflow"
4607 };
4608
4609 static void wlc_print_txs_status(u16 s)
4610 {
4611         printk(KERN_DEBUG "[15:12]  %d  frame attempts\n",
4612                (s & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT);
4613         printk(KERN_DEBUG " [11:8]  %d  rts attempts\n",
4614                (s & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT);
4615         printk(KERN_DEBUG "    [7]  %d  PM mode indicated\n",
4616                ((s & TX_STATUS_PMINDCTD) ? 1 : 0));
4617         printk(KERN_DEBUG "    [6]  %d  intermediate status\n",
4618                ((s & TX_STATUS_INTERMEDIATE) ? 1 : 0));
4619         printk(KERN_DEBUG "    [5]  %d  AMPDU\n",
4620                (s & TX_STATUS_AMPDU) ? 1 : 0);
4621         printk(KERN_DEBUG "  [4:2]  %d  Frame Suppressed Reason (%s)\n",
4622                ((s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT),
4623                supr_reason[(s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT]);
4624         printk(KERN_DEBUG "    [1]  %d  acked\n",
4625                ((s & TX_STATUS_ACK_RCV) ? 1 : 0));
4626 }
4627 #endif                          /* BCMDBG */
4628
4629 void wlc_print_txstatus(tx_status_t *txs)
4630 {
4631 #if defined(BCMDBG)
4632         u16 s = txs->status;
4633         u16 ackphyrxsh = txs->ackphyrxsh;
4634
4635         printk(KERN_DEBUG "\ntxpkt (MPDU) Complete\n");
4636
4637         printk(KERN_DEBUG "FrameID: %04x   ", txs->frameid);
4638         printk(KERN_DEBUG "TxStatus: %04x", s);
4639         printk(KERN_DEBUG "\n");
4640
4641         wlc_print_txs_status(s);
4642
4643         printk(KERN_DEBUG "LastTxTime: %04x ", txs->lasttxtime);
4644         printk(KERN_DEBUG "Seq: %04x ", txs->sequence);
4645         printk(KERN_DEBUG "PHYTxStatus: %04x ", txs->phyerr);
4646         printk(KERN_DEBUG "RxAckRSSI: %04x ",
4647                (ackphyrxsh & PRXS1_JSSI_MASK) >> PRXS1_JSSI_SHIFT);
4648         printk(KERN_DEBUG "RxAckSQ: %04x",
4649                (ackphyrxsh & PRXS1_SQ_MASK) >> PRXS1_SQ_SHIFT);
4650         printk(KERN_DEBUG "\n");
4651 #endif                          /* defined(BCMDBG) */
4652 }
4653
4654 static void
4655 wlc_ctrupd_cache(u16 cur_stat, u16 *macstat_snapshot, u32 *macstat)
4656 {
4657         u16 v;
4658         u16 delta;
4659
4660         v = le16_to_cpu(cur_stat);
4661         delta = (u16)(v - *macstat_snapshot);
4662
4663         if (delta != 0) {
4664                 *macstat += delta;
4665                 *macstat_snapshot = v;
4666         }
4667 }
4668
4669 #define MACSTATUPD(name) \
4670         wlc_ctrupd_cache(macstats.name, &wlc->core->macstat_snapshot->name, &wlc->pub->_cnt->name)
4671
4672 void wlc_statsupd(struct wlc_info *wlc)
4673 {
4674         int i;
4675         macstat_t macstats;
4676 #ifdef BCMDBG
4677         u16 delta;
4678         u16 rxf0ovfl;
4679         u16 txfunfl[NFIFO];
4680 #endif                          /* BCMDBG */
4681
4682         /* if driver down, make no sense to update stats */
4683         if (!wlc->pub->up)
4684                 return;
4685
4686 #ifdef BCMDBG
4687         /* save last rx fifo 0 overflow count */
4688         rxf0ovfl = wlc->core->macstat_snapshot->rxf0ovfl;
4689
4690         /* save last tx fifo  underflow count */
4691         for (i = 0; i < NFIFO; i++)
4692                 txfunfl[i] = wlc->core->macstat_snapshot->txfunfl[i];
4693 #endif                          /* BCMDBG */
4694
4695         /* Read mac stats from contiguous shared memory */
4696         wlc_bmac_copyfrom_shm(wlc->hw, M_UCODE_MACSTAT,
4697                               &macstats, sizeof(macstat_t));
4698
4699         /* update mac stats */
4700         MACSTATUPD(txallfrm);
4701         MACSTATUPD(txrtsfrm);
4702         MACSTATUPD(txctsfrm);
4703         MACSTATUPD(txackfrm);
4704         MACSTATUPD(txdnlfrm);
4705         MACSTATUPD(txbcnfrm);
4706         for (i = 0; i < NFIFO; i++)
4707                 MACSTATUPD(txfunfl[i]);
4708         MACSTATUPD(txtplunfl);
4709         MACSTATUPD(txphyerr);
4710         MACSTATUPD(rxfrmtoolong);
4711         MACSTATUPD(rxfrmtooshrt);
4712         MACSTATUPD(rxinvmachdr);
4713         MACSTATUPD(rxbadfcs);
4714         MACSTATUPD(rxbadplcp);
4715         MACSTATUPD(rxcrsglitch);
4716         MACSTATUPD(rxstrt);
4717         MACSTATUPD(rxdfrmucastmbss);
4718         MACSTATUPD(rxmfrmucastmbss);
4719         MACSTATUPD(rxcfrmucast);
4720         MACSTATUPD(rxrtsucast);
4721         MACSTATUPD(rxctsucast);
4722         MACSTATUPD(rxackucast);
4723         MACSTATUPD(rxdfrmocast);
4724         MACSTATUPD(rxmfrmocast);
4725         MACSTATUPD(rxcfrmocast);
4726         MACSTATUPD(rxrtsocast);
4727         MACSTATUPD(rxctsocast);
4728         MACSTATUPD(rxdfrmmcast);
4729         MACSTATUPD(rxmfrmmcast);
4730         MACSTATUPD(rxcfrmmcast);
4731         MACSTATUPD(rxbeaconmbss);
4732         MACSTATUPD(rxdfrmucastobss);
4733         MACSTATUPD(rxbeaconobss);
4734         MACSTATUPD(rxrsptmout);
4735         MACSTATUPD(bcntxcancl);
4736         MACSTATUPD(rxf0ovfl);
4737         MACSTATUPD(rxf1ovfl);
4738         MACSTATUPD(rxf2ovfl);
4739         MACSTATUPD(txsfovfl);
4740         MACSTATUPD(pmqovfl);
4741         MACSTATUPD(rxcgprqfrm);
4742         MACSTATUPD(rxcgprsqovfl);
4743         MACSTATUPD(txcgprsfail);
4744         MACSTATUPD(txcgprssuc);
4745         MACSTATUPD(prs_timeout);
4746         MACSTATUPD(rxnack);
4747         MACSTATUPD(frmscons);
4748         MACSTATUPD(txnack);
4749         MACSTATUPD(txglitch_nack);
4750         MACSTATUPD(txburst);
4751         MACSTATUPD(phywatchdog);
4752         MACSTATUPD(pktengrxducast);
4753         MACSTATUPD(pktengrxdmcast);
4754
4755 #ifdef BCMDBG
4756         /* check for rx fifo 0 overflow */
4757         delta = (u16) (wlc->core->macstat_snapshot->rxf0ovfl - rxf0ovfl);
4758         if (delta)
4759                 wiphy_err(wlc->wiphy, "wl%d: %u rx fifo 0 overflows!\n",
4760                           wlc->pub->unit, delta);
4761
4762         /* check for tx fifo underflows */
4763         for (i = 0; i < NFIFO; i++) {
4764                 delta =
4765                     (u16) (wlc->core->macstat_snapshot->txfunfl[i] -
4766                               txfunfl[i]);
4767                 if (delta)
4768                         wiphy_err(wlc->wiphy, "wl%d: %u tx fifo %d underflows!"
4769                                   "\n", wlc->pub->unit, delta, i);
4770         }
4771 #endif                          /* BCMDBG */
4772
4773         /* dot11 counter update */
4774
4775         WLCNTSET(wlc->pub->_cnt->txrts,
4776                  (wlc->pub->_cnt->rxctsucast -
4777                   wlc->pub->_cnt->d11cnt_txrts_off));
4778         WLCNTSET(wlc->pub->_cnt->rxcrc,
4779                  (wlc->pub->_cnt->rxbadfcs - wlc->pub->_cnt->d11cnt_rxcrc_off));
4780         WLCNTSET(wlc->pub->_cnt->txnocts,
4781                  ((wlc->pub->_cnt->txrtsfrm - wlc->pub->_cnt->rxctsucast) -
4782                   wlc->pub->_cnt->d11cnt_txnocts_off));
4783
4784         /* merge counters from dma module */
4785         for (i = 0; i < NFIFO; i++) {
4786                 if (wlc->hw->di[i]) {
4787                         WLCNTADD(wlc->pub->_cnt->txnobuf,
4788                                  (wlc->hw->di[i])->txnobuf);
4789                         WLCNTADD(wlc->pub->_cnt->rxnobuf,
4790                                  (wlc->hw->di[i])->rxnobuf);
4791                         WLCNTADD(wlc->pub->_cnt->rxgiant,
4792                                  (wlc->hw->di[i])->rxgiants);
4793                         dma_counterreset(wlc->hw->di[i]);
4794                 }
4795         }
4796
4797         /*
4798          * Aggregate transmit and receive errors that probably resulted
4799          * in the loss of a frame are computed on the fly.
4800          */
4801         WLCNTSET(wlc->pub->_cnt->txerror,
4802                  wlc->pub->_cnt->txnobuf + wlc->pub->_cnt->txnoassoc +
4803                  wlc->pub->_cnt->txuflo + wlc->pub->_cnt->txrunt +
4804                  wlc->pub->_cnt->dmade + wlc->pub->_cnt->dmada +
4805                  wlc->pub->_cnt->dmape);
4806         WLCNTSET(wlc->pub->_cnt->rxerror,
4807                  wlc->pub->_cnt->rxoflo + wlc->pub->_cnt->rxnobuf +
4808                  wlc->pub->_cnt->rxfragerr + wlc->pub->_cnt->rxrunt +
4809                  wlc->pub->_cnt->rxgiant + wlc->pub->_cnt->rxnoscb +
4810                  wlc->pub->_cnt->rxbadsrcmac);
4811         for (i = 0; i < NFIFO; i++)
4812                 wlc->pub->_cnt->rxerror += wlc->pub->_cnt->rxuflo[i];
4813 }
4814
4815 bool wlc_chipmatch(u16 vendor, u16 device)
4816 {
4817         if (vendor != PCI_VENDOR_ID_BROADCOM) {
4818                 pr_err("wlc_chipmatch: unknown vendor id %04x\n", vendor);
4819                 return false;
4820         }
4821
4822         if ((device == BCM43224_D11N_ID) || (device == BCM43225_D11N2G_ID))
4823                 return true;
4824
4825         if (device == BCM4313_D11N2G_ID)
4826                 return true;
4827         if ((device == BCM43236_D11N_ID) || (device == BCM43236_D11N2G_ID))
4828                 return true;
4829
4830         pr_err("wlc_chipmatch: unknown device id %04x\n", device);
4831         return false;
4832 }
4833
4834 #if defined(BCMDBG)
4835 void wlc_print_txdesc(d11txh_t *txh)
4836 {
4837         u16 mtcl = le16_to_cpu(txh->MacTxControlLow);
4838         u16 mtch = le16_to_cpu(txh->MacTxControlHigh);
4839         u16 mfc = le16_to_cpu(txh->MacFrameControl);
4840         u16 tfest = le16_to_cpu(txh->TxFesTimeNormal);
4841         u16 ptcw = le16_to_cpu(txh->PhyTxControlWord);
4842         u16 ptcw_1 = le16_to_cpu(txh->PhyTxControlWord_1);
4843         u16 ptcw_1_Fbr = le16_to_cpu(txh->PhyTxControlWord_1_Fbr);
4844         u16 ptcw_1_Rts = le16_to_cpu(txh->PhyTxControlWord_1_Rts);
4845         u16 ptcw_1_FbrRts = le16_to_cpu(txh->PhyTxControlWord_1_FbrRts);
4846         u16 mainrates = le16_to_cpu(txh->MainRates);
4847         u16 xtraft = le16_to_cpu(txh->XtraFrameTypes);
4848         u8 *iv = txh->IV;
4849         u8 *ra = txh->TxFrameRA;
4850         u16 tfestfb = le16_to_cpu(txh->TxFesTimeFallback);
4851         u8 *rtspfb = txh->RTSPLCPFallback;
4852         u16 rtsdfb = le16_to_cpu(txh->RTSDurFallback);
4853         u8 *fragpfb = txh->FragPLCPFallback;
4854         u16 fragdfb = le16_to_cpu(txh->FragDurFallback);
4855         u16 mmodelen = le16_to_cpu(txh->MModeLen);
4856         u16 mmodefbrlen = le16_to_cpu(txh->MModeFbrLen);
4857         u16 tfid = le16_to_cpu(txh->TxFrameID);
4858         u16 txs = le16_to_cpu(txh->TxStatus);
4859         u16 mnmpdu = le16_to_cpu(txh->MaxNMpdus);
4860         u16 mabyte = le16_to_cpu(txh->MaxABytes_MRT);
4861         u16 mabyte_f = le16_to_cpu(txh->MaxABytes_FBR);
4862         u16 mmbyte = le16_to_cpu(txh->MinMBytes);
4863
4864         u8 *rtsph = txh->RTSPhyHeader;
4865         struct ieee80211_rts rts = txh->rts_frame;
4866         char hexbuf[256];
4867
4868         /* add plcp header along with txh descriptor */
4869         prhex("Raw TxDesc + plcp header", (unsigned char *) txh, sizeof(d11txh_t) + 48);
4870
4871         printk(KERN_DEBUG "TxCtlLow: %04x ", mtcl);
4872         printk(KERN_DEBUG "TxCtlHigh: %04x ", mtch);
4873         printk(KERN_DEBUG "FC: %04x ", mfc);
4874         printk(KERN_DEBUG "FES Time: %04x\n", tfest);
4875         printk(KERN_DEBUG "PhyCtl: %04x%s ", ptcw,
4876                (ptcw & PHY_TXC_SHORT_HDR) ? " short" : "");
4877         printk(KERN_DEBUG "PhyCtl_1: %04x ", ptcw_1);
4878         printk(KERN_DEBUG "PhyCtl_1_Fbr: %04x\n", ptcw_1_Fbr);
4879         printk(KERN_DEBUG "PhyCtl_1_Rts: %04x ", ptcw_1_Rts);
4880         printk(KERN_DEBUG "PhyCtl_1_Fbr_Rts: %04x\n", ptcw_1_FbrRts);
4881         printk(KERN_DEBUG "MainRates: %04x ", mainrates);
4882         printk(KERN_DEBUG "XtraFrameTypes: %04x ", xtraft);
4883         printk(KERN_DEBUG "\n");
4884
4885         bcm_format_hex(hexbuf, iv, sizeof(txh->IV));
4886         printk(KERN_DEBUG "SecIV:       %s\n", hexbuf);
4887         bcm_format_hex(hexbuf, ra, sizeof(txh->TxFrameRA));
4888         printk(KERN_DEBUG "RA:          %s\n", hexbuf);
4889
4890         printk(KERN_DEBUG "Fb FES Time: %04x ", tfestfb);
4891         bcm_format_hex(hexbuf, rtspfb, sizeof(txh->RTSPLCPFallback));
4892         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
4893         printk(KERN_DEBUG "RTS DUR: %04x ", rtsdfb);
4894         bcm_format_hex(hexbuf, fragpfb, sizeof(txh->FragPLCPFallback));
4895         printk(KERN_DEBUG "PLCP: %s ", hexbuf);
4896         printk(KERN_DEBUG "DUR: %04x", fragdfb);
4897         printk(KERN_DEBUG "\n");
4898
4899         printk(KERN_DEBUG "MModeLen: %04x ", mmodelen);
4900         printk(KERN_DEBUG "MModeFbrLen: %04x\n", mmodefbrlen);
4901
4902         printk(KERN_DEBUG "FrameID:     %04x\n", tfid);
4903         printk(KERN_DEBUG "TxStatus:    %04x\n", txs);
4904
4905         printk(KERN_DEBUG "MaxNumMpdu:  %04x\n", mnmpdu);
4906         printk(KERN_DEBUG "MaxAggbyte:  %04x\n", mabyte);
4907         printk(KERN_DEBUG "MaxAggbyte_fb:  %04x\n", mabyte_f);
4908         printk(KERN_DEBUG "MinByte:     %04x\n", mmbyte);
4909
4910         bcm_format_hex(hexbuf, rtsph, sizeof(txh->RTSPhyHeader));
4911         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
4912         bcm_format_hex(hexbuf, (u8 *) &rts, sizeof(txh->rts_frame));
4913         printk(KERN_DEBUG "RTS Frame: %s", hexbuf);
4914         printk(KERN_DEBUG "\n");
4915 }
4916 #endif                          /* defined(BCMDBG) */
4917
4918 #if defined(BCMDBG)
4919 void wlc_print_rxh(d11rxhdr_t *rxh)
4920 {
4921         u16 len = rxh->RxFrameSize;
4922         u16 phystatus_0 = rxh->PhyRxStatus_0;
4923         u16 phystatus_1 = rxh->PhyRxStatus_1;
4924         u16 phystatus_2 = rxh->PhyRxStatus_2;
4925         u16 phystatus_3 = rxh->PhyRxStatus_3;
4926         u16 macstatus1 = rxh->RxStatus1;
4927         u16 macstatus2 = rxh->RxStatus2;
4928         char flagstr[64];
4929         char lenbuf[20];
4930         static const bcm_bit_desc_t macstat_flags[] = {
4931                 {RXS_FCSERR, "FCSErr"},
4932                 {RXS_RESPFRAMETX, "Reply"},
4933                 {RXS_PBPRES, "PADDING"},
4934                 {RXS_DECATMPT, "DeCr"},
4935                 {RXS_DECERR, "DeCrErr"},
4936                 {RXS_BCNSENT, "Bcn"},
4937                 {0, NULL}
4938         };
4939
4940         prhex("Raw RxDesc", (unsigned char *) rxh, sizeof(d11rxhdr_t));
4941
4942         bcm_format_flags(macstat_flags, macstatus1, flagstr, 64);
4943
4944         snprintf(lenbuf, sizeof(lenbuf), "0x%x", len);
4945
4946         printk(KERN_DEBUG "RxFrameSize:     %6s (%d)%s\n", lenbuf, len,
4947                (rxh->PhyRxStatus_0 & PRXS0_SHORTH) ? " short preamble" : "");
4948         printk(KERN_DEBUG "RxPHYStatus:     %04x %04x %04x %04x\n",
4949                phystatus_0, phystatus_1, phystatus_2, phystatus_3);
4950         printk(KERN_DEBUG "RxMACStatus:     %x %s\n", macstatus1, flagstr);
4951         printk(KERN_DEBUG "RXMACaggtype:    %x\n",
4952                (macstatus2 & RXS_AGGTYPE_MASK));
4953         printk(KERN_DEBUG "RxTSFTime:       %04x\n", rxh->RxTSFTime);
4954 }
4955 #endif                          /* defined(BCMDBG) */
4956
4957 #if defined(BCMDBG)
4958 int wlc_format_ssid(char *buf, const unsigned char ssid[], uint ssid_len)
4959 {
4960         uint i, c;
4961         char *p = buf;
4962         char *endp = buf + SSID_FMT_BUF_LEN;
4963
4964         if (ssid_len > IEEE80211_MAX_SSID_LEN)
4965                 ssid_len = IEEE80211_MAX_SSID_LEN;
4966
4967         for (i = 0; i < ssid_len; i++) {
4968                 c = (uint) ssid[i];
4969                 if (c == '\\') {
4970                         *p++ = '\\';
4971                         *p++ = '\\';
4972                 } else if (isprint((unsigned char) c)) {
4973                         *p++ = (char)c;
4974                 } else {
4975                         p += snprintf(p, (endp - p), "\\x%02X", c);
4976                 }
4977         }
4978         *p = '\0';
4979         ASSERT(p < endp);
4980
4981         return (int)(p - buf);
4982 }
4983 #endif                          /* defined(BCMDBG) */
4984
4985 static u16 wlc_rate_shm_offset(struct wlc_info *wlc, u8 rate)
4986 {
4987         return wlc_bmac_rate_shm_offset(wlc->hw, rate);
4988 }
4989
4990 /* Callback for device removed */
4991
4992 /*
4993  * Attempts to queue a packet onto a multiple-precedence queue,
4994  * if necessary evicting a lower precedence packet from the queue.
4995  *
4996  * 'prec' is the precedence number that has already been mapped
4997  * from the packet priority.
4998  *
4999  * Returns true if packet consumed (queued), false if not.
5000  */
5001 bool BCMFASTPATH
5002 wlc_prec_enq(struct wlc_info *wlc, struct pktq *q, void *pkt, int prec)
5003 {
5004         return wlc_prec_enq_head(wlc, q, pkt, prec, false);
5005 }
5006
5007 bool BCMFASTPATH
5008 wlc_prec_enq_head(struct wlc_info *wlc, struct pktq *q, struct sk_buff *pkt,
5009                   int prec, bool head)
5010 {
5011         struct sk_buff *p;
5012         int eprec = -1;         /* precedence to evict from */
5013
5014         /* Determine precedence from which to evict packet, if any */
5015         if (pktq_pfull(q, prec))
5016                 eprec = prec;
5017         else if (pktq_full(q)) {
5018                 p = pktq_peek_tail(q, &eprec);
5019                 ASSERT(p != NULL);
5020                 if (eprec > prec) {
5021                         wiphy_err(wlc->wiphy, "%s: Failing: eprec %d > prec %d"
5022                                   "\n", __func__, eprec, prec);
5023                         return false;
5024                 }
5025         }
5026
5027         /* Evict if needed */
5028         if (eprec >= 0) {
5029                 bool discard_oldest;
5030
5031                 /* Detect queueing to unconfigured precedence */
5032                 ASSERT(!pktq_pempty(q, eprec));
5033
5034                 discard_oldest = AC_BITMAP_TST(wlc->wme_dp, eprec);
5035
5036                 /* Refuse newer packet unless configured to discard oldest */
5037                 if (eprec == prec && !discard_oldest) {
5038                         wiphy_err(wlc->wiphy, "%s: No where to go, prec == %d"
5039                                   "\n", __func__, prec);
5040                         return false;
5041                 }
5042
5043                 /* Evict packet according to discard policy */
5044                 p = discard_oldest ? pktq_pdeq(q, eprec) : pktq_pdeq_tail(q,
5045                                                                           eprec);
5046                 ASSERT(p != NULL);
5047
5048                 /* Increment wme stats */
5049                 if (WME_ENAB(wlc->pub)) {
5050                         WLCNTINCR(wlc->pub->_wme_cnt->
5051                                   tx_failed[WME_PRIO2AC(p->priority)].packets);
5052                         WLCNTADD(wlc->pub->_wme_cnt->
5053                                  tx_failed[WME_PRIO2AC(p->priority)].bytes,
5054                                  pkttotlen(p));
5055                 }
5056                 pkt_buf_free_skb(p);
5057                 wlc->pub->_cnt->txnobuf++;
5058         }
5059
5060         /* Enqueue */
5061         if (head)
5062                 p = pktq_penq_head(q, prec, pkt);
5063         else
5064                 p = pktq_penq(q, prec, pkt);
5065         ASSERT(p != NULL);
5066
5067         return true;
5068 }
5069
5070 void BCMFASTPATH wlc_txq_enq(void *ctx, struct scb *scb, struct sk_buff *sdu,
5071                              uint prec)
5072 {
5073         struct wlc_info *wlc = (struct wlc_info *) ctx;
5074         struct wlc_txq_info *qi = wlc->active_queue;    /* Check me */
5075         struct pktq *q = &qi->q;
5076         int prio;
5077
5078         prio = sdu->priority;
5079
5080         ASSERT(pktq_max(q) >= wlc->pub->tunables->datahiwat);
5081
5082         if (!wlc_prec_enq(wlc, q, sdu, prec)) {
5083                 if (!EDCF_ENAB(wlc->pub)
5084                     || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL))
5085                         wiphy_err(wlc->wiphy, "wl%d: wlc_txq_enq: txq overflow"
5086                                   "\n", wlc->pub->unit);
5087
5088                 /*
5089                  * XXX we might hit this condtion in case
5090                  * packet flooding from mac80211 stack
5091                  */
5092                 pkt_buf_free_skb(sdu);
5093                 wlc->pub->_cnt->txnobuf++;
5094         }
5095
5096         /* Check if flow control needs to be turned on after enqueuing the packet
5097          *   Don't turn on flow control if EDCF is enabled. Driver would make the decision on what
5098          *   to drop instead of relying on stack to make the right decision
5099          */
5100         if (!EDCF_ENAB(wlc->pub)
5101             || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL)) {
5102                 if (pktq_len(q) >= wlc->pub->tunables->datahiwat) {
5103                         wlc_txflowcontrol(wlc, qi, ON, ALLPRIO);
5104                 }
5105         } else if (wlc->pub->_priofc) {
5106                 if (pktq_plen(q, wlc_prio2prec_map[prio]) >=
5107                     wlc->pub->tunables->datahiwat) {
5108                         wlc_txflowcontrol(wlc, qi, ON, prio);
5109                 }
5110         }
5111 }
5112
5113 bool BCMFASTPATH
5114 wlc_sendpkt_mac80211(struct wlc_info *wlc, struct sk_buff *sdu,
5115                      struct ieee80211_hw *hw)
5116 {
5117         u8 prio;
5118         uint fifo;
5119         void *pkt;
5120         struct scb *scb = &global_scb;
5121         struct ieee80211_hdr *d11_header = (struct ieee80211_hdr *)(sdu->data);
5122
5123         ASSERT(sdu);
5124
5125         /* 802.11 standard requires management traffic to go at highest priority */
5126         prio = ieee80211_is_data(d11_header->frame_control) ? sdu->priority :
5127                 MAXPRIO;
5128         fifo = prio2fifo[prio];
5129
5130         ASSERT((uint) skb_headroom(sdu) >= TXOFF);
5131         ASSERT(!(sdu->next));
5132         ASSERT(!(sdu->prev));
5133         ASSERT(fifo < NFIFO);
5134
5135         pkt = sdu;
5136         if (unlikely
5137             (wlc_d11hdrs_mac80211(wlc, hw, pkt, scb, 0, 1, fifo, 0, NULL, 0)))
5138                 return -EINVAL;
5139         wlc_txq_enq(wlc, scb, pkt, WLC_PRIO_TO_PREC(prio));
5140         wlc_send_q(wlc, wlc->active_queue);
5141
5142         wlc->pub->_cnt->ieee_tx++;
5143         return 0;
5144 }
5145
5146 void BCMFASTPATH wlc_send_q(struct wlc_info *wlc, struct wlc_txq_info *qi)
5147 {
5148         struct sk_buff *pkt[DOT11_MAXNUMFRAGS];
5149         int prec;
5150         u16 prec_map;
5151         int err = 0, i, count;
5152         uint fifo;
5153         struct pktq *q = &qi->q;
5154         struct ieee80211_tx_info *tx_info;
5155
5156         /* only do work for the active queue */
5157         if (qi != wlc->active_queue)
5158                 return;
5159
5160         if (in_send_q)
5161                 return;
5162         else
5163                 in_send_q = true;
5164
5165         prec_map = wlc->tx_prec_map;
5166
5167         /* Send all the enq'd pkts that we can.
5168          * Dequeue packets with precedence with empty HW fifo only
5169          */
5170         while (prec_map && (pkt[0] = pktq_mdeq(q, prec_map, &prec))) {
5171                 tx_info = IEEE80211_SKB_CB(pkt[0]);
5172                 if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
5173                         err = wlc_sendampdu(wlc->ampdu, qi, pkt, prec);
5174                 } else {
5175                         count = 1;
5176                         err = wlc_prep_pdu(wlc, pkt[0], &fifo);
5177                         if (!err) {
5178                                 for (i = 0; i < count; i++) {
5179                                         wlc_txfifo(wlc, fifo, pkt[i], true, 1);
5180                                 }
5181                         }
5182                 }
5183
5184                 if (err == -BCME_BUSY) {
5185                         pktq_penq_head(q, prec, pkt[0]);
5186                         /* If send failed due to any other reason than a change in
5187                          * HW FIFO condition, quit. Otherwise, read the new prec_map!
5188                          */
5189                         if (prec_map == wlc->tx_prec_map)
5190                                 break;
5191                         prec_map = wlc->tx_prec_map;
5192                 }
5193         }
5194
5195         /* Check if flow control needs to be turned off after sending the packet */
5196         if (!EDCF_ENAB(wlc->pub)
5197             || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL)) {
5198                 if (wlc_txflowcontrol_prio_isset(wlc, qi, ALLPRIO)
5199                     && (pktq_len(q) < wlc->pub->tunables->datahiwat / 2)) {
5200                         wlc_txflowcontrol(wlc, qi, OFF, ALLPRIO);
5201                 }
5202         } else if (wlc->pub->_priofc) {
5203                 int prio;
5204                 for (prio = MAXPRIO; prio >= 0; prio--) {
5205                         if (wlc_txflowcontrol_prio_isset(wlc, qi, prio) &&
5206                             (pktq_plen(q, wlc_prio2prec_map[prio]) <
5207                              wlc->pub->tunables->datahiwat / 2)) {
5208                                 wlc_txflowcontrol(wlc, qi, OFF, prio);
5209                         }
5210                 }
5211         }
5212         in_send_q = false;
5213 }
5214
5215 /*
5216  * bcmc_fid_generate:
5217  * Generate frame ID for a BCMC packet.  The frag field is not used
5218  * for MC frames so is used as part of the sequence number.
5219  */
5220 static inline u16
5221 bcmc_fid_generate(struct wlc_info *wlc, struct wlc_bsscfg *bsscfg,
5222                   d11txh_t *txh)
5223 {
5224         u16 frameid;
5225
5226         frameid = le16_to_cpu(txh->TxFrameID) & ~(TXFID_SEQ_MASK |
5227                                                   TXFID_QUEUE_MASK);
5228         frameid |=
5229             (((wlc->
5230                mc_fid_counter++) << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
5231             TX_BCMC_FIFO;
5232
5233         return frameid;
5234 }
5235
5236 void BCMFASTPATH
5237 wlc_txfifo(struct wlc_info *wlc, uint fifo, struct sk_buff *p, bool commit,
5238            s8 txpktpend)
5239 {
5240         u16 frameid = INVALIDFID;
5241         d11txh_t *txh;
5242
5243         ASSERT(fifo < NFIFO);
5244         txh = (d11txh_t *) (p->data);
5245
5246         /* When a BC/MC frame is being committed to the BCMC fifo via DMA (NOT PIO), update
5247          * ucode or BSS info as appropriate.
5248          */
5249         if (fifo == TX_BCMC_FIFO) {
5250                 frameid = le16_to_cpu(txh->TxFrameID);
5251
5252         }
5253
5254         if (WLC_WAR16165(wlc))
5255                 wlc_war16165(wlc, true);
5256
5257
5258         /* Bump up pending count for if not using rpc. If rpc is used, this will be handled
5259          * in wlc_bmac_txfifo()
5260          */
5261         if (commit) {
5262                 TXPKTPENDINC(wlc, fifo, txpktpend);
5263                 WL_TRACE("wlc_txfifo, pktpend inc %d to %d\n",
5264                          txpktpend, TXPKTPENDGET(wlc, fifo));
5265         }
5266
5267         /* Commit BCMC sequence number in the SHM frame ID location */
5268         if (frameid != INVALIDFID)
5269                 BCMCFID(wlc, frameid);
5270
5271         if (dma_txfast(wlc->hw->di[fifo], p, commit) < 0) {
5272                 wiphy_err(wlc->wiphy, "wlc_txfifo: fatal, toss frames !!!\n");
5273         }
5274 }
5275
5276 static u16
5277 wlc_compute_airtime(struct wlc_info *wlc, ratespec_t rspec, uint length)
5278 {
5279         u16 usec = 0;
5280         uint mac_rate = RSPEC2RATE(rspec);
5281         uint nsyms;
5282
5283         if (IS_MCS(rspec)) {
5284                 /* not supported yet */
5285                 ASSERT(0);
5286         } else if (IS_OFDM(rspec)) {
5287                 /* nsyms = Ceiling(Nbits / (Nbits/sym))
5288                  *
5289                  * Nbits = length * 8
5290                  * Nbits/sym = Mbps * 4 = mac_rate * 2
5291                  */
5292                 nsyms = CEIL((length * 8), (mac_rate * 2));
5293
5294                 /* usec = symbols * usec/symbol */
5295                 usec = (u16) (nsyms * APHY_SYMBOL_TIME);
5296                 return usec;
5297         } else {
5298                 switch (mac_rate) {
5299                 case WLC_RATE_1M:
5300                         usec = length << 3;
5301                         break;
5302                 case WLC_RATE_2M:
5303                         usec = length << 2;
5304                         break;
5305                 case WLC_RATE_5M5:
5306                         usec = (length << 4) / 11;
5307                         break;
5308                 case WLC_RATE_11M:
5309                         usec = (length << 3) / 11;
5310                         break;
5311                 default:
5312                         wiphy_err(wlc->wiphy, "wl%d: wlc_compute_airtime: "
5313                                   "unsupported rspec 0x%x\n",
5314                                   wlc->pub->unit, rspec);
5315                         ASSERT((const char *)"Bad phy_rate" == NULL);
5316                         break;
5317                 }
5318         }
5319
5320         return usec;
5321 }
5322
5323 void BCMFASTPATH
5324 wlc_compute_plcp(struct wlc_info *wlc, ratespec_t rspec, uint length, u8 *plcp)
5325 {
5326         if (IS_MCS(rspec)) {
5327                 wlc_compute_mimo_plcp(rspec, length, plcp);
5328         } else if (IS_OFDM(rspec)) {
5329                 wlc_compute_ofdm_plcp(rspec, length, plcp);
5330         } else {
5331                 wlc_compute_cck_plcp(wlc, rspec, length, plcp);
5332         }
5333         return;
5334 }
5335
5336 /* Rate: 802.11 rate code, length: PSDU length in octets */
5337 static void wlc_compute_mimo_plcp(ratespec_t rspec, uint length, u8 *plcp)
5338 {
5339         u8 mcs = (u8) (rspec & RSPEC_RATE_MASK);
5340         ASSERT(IS_MCS(rspec));
5341         plcp[0] = mcs;
5342         if (RSPEC_IS40MHZ(rspec) || (mcs == 32))
5343                 plcp[0] |= MIMO_PLCP_40MHZ;
5344         WLC_SET_MIMO_PLCP_LEN(plcp, length);
5345         plcp[3] = RSPEC_MIMOPLCP3(rspec);       /* rspec already holds this byte */
5346         plcp[3] |= 0x7;         /* set smoothing, not sounding ppdu & reserved */
5347         plcp[4] = 0;            /* number of extension spatial streams bit 0 & 1 */
5348         plcp[5] = 0;
5349 }
5350
5351 /* Rate: 802.11 rate code, length: PSDU length in octets */
5352 static void BCMFASTPATH
5353 wlc_compute_ofdm_plcp(ratespec_t rspec, u32 length, u8 *plcp)
5354 {
5355         u8 rate_signal;
5356         u32 tmp = 0;
5357         int rate = RSPEC2RATE(rspec);
5358
5359         ASSERT(IS_OFDM(rspec));
5360
5361         /* encode rate per 802.11a-1999 sec 17.3.4.1, with lsb transmitted first */
5362         rate_signal = rate_info[rate] & WLC_RATE_MASK;
5363         ASSERT(rate_signal != 0);
5364
5365         memset(plcp, 0, D11_PHY_HDR_LEN);
5366         D11A_PHY_HDR_SRATE((ofdm_phy_hdr_t *) plcp, rate_signal);
5367
5368         tmp = (length & 0xfff) << 5;
5369         plcp[2] |= (tmp >> 16) & 0xff;
5370         plcp[1] |= (tmp >> 8) & 0xff;
5371         plcp[0] |= tmp & 0xff;
5372
5373         return;
5374 }
5375
5376 /*
5377  * Compute PLCP, but only requires actual rate and length of pkt.
5378  * Rate is given in the driver standard multiple of 500 kbps.
5379  * le is set for 11 Mbps rate if necessary.
5380  * Broken out for PRQ.
5381  */
5382
5383 static void wlc_cck_plcp_set(struct wlc_info *wlc, int rate_500, uint length,
5384                              u8 *plcp)
5385 {
5386         u16 usec = 0;
5387         u8 le = 0;
5388
5389         switch (rate_500) {
5390         case WLC_RATE_1M:
5391                 usec = length << 3;
5392                 break;
5393         case WLC_RATE_2M:
5394                 usec = length << 2;
5395                 break;
5396         case WLC_RATE_5M5:
5397                 usec = (length << 4) / 11;
5398                 if ((length << 4) - (usec * 11) > 0)
5399                         usec++;
5400                 break;
5401         case WLC_RATE_11M:
5402                 usec = (length << 3) / 11;
5403                 if ((length << 3) - (usec * 11) > 0) {
5404                         usec++;
5405                         if ((usec * 11) - (length << 3) >= 8)
5406                                 le = D11B_PLCP_SIGNAL_LE;
5407                 }
5408                 break;
5409
5410         default:
5411                 wiphy_err(wlc->wiphy, "wlc_cck_plcp_set: unsupported rate %d"
5412                           "\n", rate_500);
5413                 rate_500 = WLC_RATE_1M;
5414                 usec = length << 3;
5415                 break;
5416         }
5417         /* PLCP signal byte */
5418         plcp[0] = rate_500 * 5; /* r (500kbps) * 5 == r (100kbps) */
5419         /* PLCP service byte */
5420         plcp[1] = (u8) (le | D11B_PLCP_SIGNAL_LOCKED);
5421         /* PLCP length u16, little endian */
5422         plcp[2] = usec & 0xff;
5423         plcp[3] = (usec >> 8) & 0xff;
5424         /* PLCP CRC16 */
5425         plcp[4] = 0;
5426         plcp[5] = 0;
5427 }
5428
5429 /* Rate: 802.11 rate code, length: PSDU length in octets */
5430 static void wlc_compute_cck_plcp(struct wlc_info *wlc, ratespec_t rspec,
5431                                  uint length, u8 *plcp)
5432 {
5433         int rate = RSPEC2RATE(rspec);
5434
5435         ASSERT(IS_CCK(rspec));
5436
5437         wlc_cck_plcp_set(wlc, rate, length, plcp);
5438 }
5439
5440 /* wlc_compute_frame_dur()
5441  *
5442  * Calculate the 802.11 MAC header DUR field for MPDU
5443  * DUR for a single frame = 1 SIFS + 1 ACK
5444  * DUR for a frame with following frags = 3 SIFS + 2 ACK + next frag time
5445  *
5446  * rate                 MPDU rate in unit of 500kbps
5447  * next_frag_len        next MPDU length in bytes
5448  * preamble_type        use short/GF or long/MM PLCP header
5449  */
5450 static u16 BCMFASTPATH
5451 wlc_compute_frame_dur(struct wlc_info *wlc, ratespec_t rate, u8 preamble_type,
5452                       uint next_frag_len)
5453 {
5454         u16 dur, sifs;
5455
5456         sifs = SIFS(wlc->band);
5457
5458         dur = sifs;
5459         dur += (u16) wlc_calc_ack_time(wlc, rate, preamble_type);
5460
5461         if (next_frag_len) {
5462                 /* Double the current DUR to get 2 SIFS + 2 ACKs */
5463                 dur *= 2;
5464                 /* add another SIFS and the frag time */
5465                 dur += sifs;
5466                 dur +=
5467                     (u16) wlc_calc_frame_time(wlc, rate, preamble_type,
5468                                                  next_frag_len);
5469         }
5470         return dur;
5471 }
5472
5473 /* wlc_compute_rtscts_dur()
5474  *
5475  * Calculate the 802.11 MAC header DUR field for an RTS or CTS frame
5476  * DUR for normal RTS/CTS w/ frame = 3 SIFS + 1 CTS + next frame time + 1 ACK
5477  * DUR for CTS-TO-SELF w/ frame    = 2 SIFS         + next frame time + 1 ACK
5478  *
5479  * cts                  cts-to-self or rts/cts
5480  * rts_rate             rts or cts rate in unit of 500kbps
5481  * rate                 next MPDU rate in unit of 500kbps
5482  * frame_len            next MPDU frame length in bytes
5483  */
5484 u16 BCMFASTPATH
5485 wlc_compute_rtscts_dur(struct wlc_info *wlc, bool cts_only, ratespec_t rts_rate,
5486                        ratespec_t frame_rate, u8 rts_preamble_type,
5487                        u8 frame_preamble_type, uint frame_len, bool ba)
5488 {
5489         u16 dur, sifs;
5490
5491         sifs = SIFS(wlc->band);
5492
5493         if (!cts_only) {        /* RTS/CTS */
5494                 dur = 3 * sifs;
5495                 dur +=
5496                     (u16) wlc_calc_cts_time(wlc, rts_rate,
5497                                                rts_preamble_type);
5498         } else {                /* CTS-TO-SELF */
5499                 dur = 2 * sifs;
5500         }
5501
5502         dur +=
5503             (u16) wlc_calc_frame_time(wlc, frame_rate, frame_preamble_type,
5504                                          frame_len);
5505         if (ba)
5506                 dur +=
5507                     (u16) wlc_calc_ba_time(wlc, frame_rate,
5508                                               WLC_SHORT_PREAMBLE);
5509         else
5510                 dur +=
5511                     (u16) wlc_calc_ack_time(wlc, frame_rate,
5512                                                frame_preamble_type);
5513         return dur;
5514 }
5515
5516 static bool wlc_phy_rspec_check(struct wlc_info *wlc, u16 bw, ratespec_t rspec)
5517 {
5518         if (IS_MCS(rspec)) {
5519                 uint mcs = rspec & RSPEC_RATE_MASK;
5520
5521                 if (mcs < 8) {
5522                         ASSERT(RSPEC_STF(rspec) < PHY_TXC1_MODE_SDM);
5523                 } else if ((mcs >= 8) && (mcs <= 23)) {
5524                         ASSERT(RSPEC_STF(rspec) == PHY_TXC1_MODE_SDM);
5525                 } else if (mcs == 32) {
5526                         ASSERT(RSPEC_STF(rspec) < PHY_TXC1_MODE_SDM);
5527                         ASSERT(bw == PHY_TXC1_BW_40MHZ_DUP);
5528                 }
5529         } else if (IS_OFDM(rspec)) {
5530                 ASSERT(RSPEC_STF(rspec) < PHY_TXC1_MODE_STBC);
5531         } else {
5532                 ASSERT(IS_CCK(rspec));
5533
5534                 ASSERT((bw == PHY_TXC1_BW_20MHZ)
5535                        || (bw == PHY_TXC1_BW_20MHZ_UP));
5536                 ASSERT(RSPEC_STF(rspec) == PHY_TXC1_MODE_SISO);
5537         }
5538
5539         return true;
5540 }
5541
5542 u16 BCMFASTPATH wlc_phytxctl1_calc(struct wlc_info *wlc, ratespec_t rspec)
5543 {
5544         u16 phyctl1 = 0;
5545         u16 bw;
5546
5547         if (WLCISLCNPHY(wlc->band)) {
5548                 bw = PHY_TXC1_BW_20MHZ;
5549         } else {
5550                 bw = RSPEC_GET_BW(rspec);
5551                 /* 10Mhz is not supported yet */
5552                 if (bw < PHY_TXC1_BW_20MHZ) {
5553                         wiphy_err(wlc->wiphy, "wlc_phytxctl1_calc: bw %d is "
5554                                   "not supported yet, set to 20L\n", bw);
5555                         bw = PHY_TXC1_BW_20MHZ;
5556                 }
5557
5558                 wlc_phy_rspec_check(wlc, bw, rspec);
5559         }
5560
5561         if (IS_MCS(rspec)) {
5562                 uint mcs = rspec & RSPEC_RATE_MASK;
5563
5564                 /* bw, stf, coding-type is part of RSPEC_PHYTXBYTE2 returns */
5565                 phyctl1 = RSPEC_PHYTXBYTE2(rspec);
5566                 /* set the upper byte of phyctl1 */
5567                 phyctl1 |= (mcs_table[mcs].tx_phy_ctl3 << 8);
5568         } else if (IS_CCK(rspec) && !WLCISLCNPHY(wlc->band)
5569                    && !WLCISSSLPNPHY(wlc->band)) {
5570                 /* In CCK mode LPPHY overloads OFDM Modulation bits with CCK Data Rate */
5571                 /* Eventually MIMOPHY would also be converted to this format */
5572                 /* 0 = 1Mbps; 1 = 2Mbps; 2 = 5.5Mbps; 3 = 11Mbps */
5573                 phyctl1 = (bw | (RSPEC_STF(rspec) << PHY_TXC1_MODE_SHIFT));
5574         } else {                /* legacy OFDM/CCK */
5575                 s16 phycfg;
5576                 /* get the phyctl byte from rate phycfg table */
5577                 phycfg = wlc_rate_legacy_phyctl(RSPEC2RATE(rspec));
5578                 if (phycfg == -1) {
5579                         wiphy_err(wlc->wiphy, "wlc_phytxctl1_calc: wrong "
5580                                   "legacy OFDM/CCK rate\n");
5581                         ASSERT(0);
5582                         phycfg = 0;
5583                 }
5584                 /* set the upper byte of phyctl1 */
5585                 phyctl1 =
5586                     (bw | (phycfg << 8) |
5587                      (RSPEC_STF(rspec) << PHY_TXC1_MODE_SHIFT));
5588         }
5589
5590 #ifdef BCMDBG
5591         /* phy clock must support 40Mhz if tx descriptor uses it */
5592         if ((phyctl1 & PHY_TXC1_BW_MASK) >= PHY_TXC1_BW_40MHZ) {
5593                 ASSERT(CHSPEC_WLC_BW(wlc->chanspec) == WLC_40_MHZ);
5594                 ASSERT(wlc->chanspec == wlc_phy_chanspec_get(wlc->band->pi));
5595         }
5596 #endif                          /* BCMDBG */
5597         return phyctl1;
5598 }
5599
5600 ratespec_t BCMFASTPATH
5601 wlc_rspec_to_rts_rspec(struct wlc_info *wlc, ratespec_t rspec, bool use_rspec,
5602                        u16 mimo_ctlchbw)
5603 {
5604         ratespec_t rts_rspec = 0;
5605
5606         if (use_rspec) {
5607                 /* use frame rate as rts rate */
5608                 rts_rspec = rspec;
5609
5610         } else if (wlc->band->gmode && wlc->protection->_g && !IS_CCK(rspec)) {
5611                 /* Use 11Mbps as the g protection RTS target rate and fallback.
5612                  * Use the WLC_BASIC_RATE() lookup to find the best basic rate under the
5613                  * target in case 11 Mbps is not Basic.
5614                  * 6 and 9 Mbps are not usually selected by rate selection, but even
5615                  * if the OFDM rate we are protecting is 6 or 9 Mbps, 11 is more robust.
5616                  */
5617                 rts_rspec = WLC_BASIC_RATE(wlc, WLC_RATE_11M);
5618         } else {
5619                 /* calculate RTS rate and fallback rate based on the frame rate
5620                  * RTS must be sent at a basic rate since it is a
5621                  * control frame, sec 9.6 of 802.11 spec
5622                  */
5623                 rts_rspec = WLC_BASIC_RATE(wlc, rspec);
5624         }
5625
5626         if (WLC_PHY_11N_CAP(wlc->band)) {
5627                 /* set rts txbw to correct side band */
5628                 rts_rspec &= ~RSPEC_BW_MASK;
5629
5630                 /* if rspec/rspec_fallback is 40MHz, then send RTS on both 20MHz channel
5631                  * (DUP), otherwise send RTS on control channel
5632                  */
5633                 if (RSPEC_IS40MHZ(rspec) && !IS_CCK(rts_rspec))
5634                         rts_rspec |= (PHY_TXC1_BW_40MHZ_DUP << RSPEC_BW_SHIFT);
5635                 else
5636                         rts_rspec |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
5637
5638                 /* pick siso/cdd as default for ofdm */
5639                 if (IS_OFDM(rts_rspec)) {
5640                         rts_rspec &= ~RSPEC_STF_MASK;
5641                         rts_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
5642                 }
5643         }
5644         return rts_rspec;
5645 }
5646
5647 /*
5648  * Add d11txh_t, cck_phy_hdr_t.
5649  *
5650  * 'p' data must start with 802.11 MAC header
5651  * 'p' must allow enough bytes of local headers to be "pushed" onto the packet
5652  *
5653  * headroom == D11_PHY_HDR_LEN + D11_TXH_LEN (D11_TXH_LEN is now 104 bytes)
5654  *
5655  */
5656 static u16 BCMFASTPATH
5657 wlc_d11hdrs_mac80211(struct wlc_info *wlc, struct ieee80211_hw *hw,
5658                      struct sk_buff *p, struct scb *scb, uint frag,
5659                      uint nfrags, uint queue, uint next_frag_len,
5660                      wsec_key_t *key, ratespec_t rspec_override)
5661 {
5662         struct ieee80211_hdr *h;
5663         d11txh_t *txh;
5664         u8 *plcp, plcp_fallback[D11_PHY_HDR_LEN];
5665         int len, phylen, rts_phylen;
5666         u16 mch, phyctl, xfts, mainrates;
5667         u16 seq = 0, mcl = 0, status = 0, frameid = 0;
5668         ratespec_t rspec[2] = { WLC_RATE_1M, WLC_RATE_1M }, rts_rspec[2] = {
5669         WLC_RATE_1M, WLC_RATE_1M};
5670         bool use_rts = false;
5671         bool use_cts = false;
5672         bool use_rifs = false;
5673         bool short_preamble[2] = { false, false };
5674         u8 preamble_type[2] = { WLC_LONG_PREAMBLE, WLC_LONG_PREAMBLE };
5675         u8 rts_preamble_type[2] = { WLC_LONG_PREAMBLE, WLC_LONG_PREAMBLE };
5676         u8 *rts_plcp, rts_plcp_fallback[D11_PHY_HDR_LEN];
5677         struct ieee80211_rts *rts = NULL;
5678         bool qos;
5679         uint ac;
5680         u32 rate_val[2];
5681         bool hwtkmic = false;
5682         u16 mimo_ctlchbw = PHY_TXC1_BW_20MHZ;
5683 #define ANTCFG_NONE 0xFF
5684         u8 antcfg = ANTCFG_NONE;
5685         u8 fbantcfg = ANTCFG_NONE;
5686         uint phyctl1_stf = 0;
5687         u16 durid = 0;
5688         struct ieee80211_tx_rate *txrate[2];
5689         int k;
5690         struct ieee80211_tx_info *tx_info;
5691         bool is_mcs[2];
5692         u16 mimo_txbw;
5693         u8 mimo_preamble_type;
5694
5695         ASSERT(queue < NFIFO);
5696
5697         /* locate 802.11 MAC header */
5698         h = (struct ieee80211_hdr *)(p->data);
5699         qos = ieee80211_is_data_qos(h->frame_control);
5700
5701         /* compute length of frame in bytes for use in PLCP computations */
5702         len = pkttotlen(p);
5703         phylen = len + FCS_LEN;
5704
5705         /* If WEP enabled, add room in phylen for the additional bytes of
5706          * ICV which MAC generates.  We do NOT add the additional bytes to
5707          * the packet itself, thus phylen = packet length + ICV_LEN + FCS_LEN
5708          * in this case
5709          */
5710         if (key) {
5711                 phylen += key->icv_len;
5712         }
5713
5714         /* Get tx_info */
5715         tx_info = IEEE80211_SKB_CB(p);
5716         ASSERT(tx_info);
5717
5718         /* add PLCP */
5719         plcp = skb_push(p, D11_PHY_HDR_LEN);
5720
5721         /* add Broadcom tx descriptor header */
5722         txh = (d11txh_t *) skb_push(p, D11_TXH_LEN);
5723         memset(txh, 0, D11_TXH_LEN);
5724
5725         /* setup frameid */
5726         if (tx_info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
5727                 /* non-AP STA should never use BCMC queue */
5728                 ASSERT(queue != TX_BCMC_FIFO);
5729                 if (queue == TX_BCMC_FIFO) {
5730                         wiphy_err(wlc->wiphy, "wl%d: %s: ASSERT queue == "
5731                                   "TX_BCMC!\n", WLCWLUNIT(wlc), __func__);
5732                         frameid = bcmc_fid_generate(wlc, NULL, txh);
5733                 } else {
5734                         /* Increment the counter for first fragment */
5735                         if (tx_info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT) {
5736                                 SCB_SEQNUM(scb, p->priority)++;
5737                         }
5738
5739                         /* extract fragment number from frame first */
5740                         seq = le16_to_cpu(seq) & FRAGNUM_MASK;
5741                         seq |= (SCB_SEQNUM(scb, p->priority) << SEQNUM_SHIFT);
5742                         h->seq_ctrl = cpu_to_le16(seq);
5743
5744                         frameid = ((seq << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
5745                             (queue & TXFID_QUEUE_MASK);
5746                 }
5747         }
5748         frameid |= queue & TXFID_QUEUE_MASK;
5749
5750         /* set the ignpmq bit for all pkts tx'd in PS mode and for beacons */
5751         if (SCB_PS(scb) || ieee80211_is_beacon(h->frame_control))
5752                 mcl |= TXC_IGNOREPMQ;
5753
5754         ASSERT(hw->max_rates <= IEEE80211_TX_MAX_RATES);
5755         ASSERT(hw->max_rates == 2);
5756
5757         txrate[0] = tx_info->control.rates;
5758         txrate[1] = txrate[0] + 1;
5759
5760         ASSERT(txrate[0]->idx >= 0);
5761         /* if rate control algorithm didn't give us a fallback rate, use the primary rate */
5762         if (txrate[1]->idx < 0) {
5763                 txrate[1] = txrate[0];
5764         }
5765
5766         for (k = 0; k < hw->max_rates; k++) {
5767                 is_mcs[k] =
5768                     txrate[k]->flags & IEEE80211_TX_RC_MCS ? true : false;
5769                 if (!is_mcs[k]) {
5770                         ASSERT(!(tx_info->flags & IEEE80211_TX_CTL_AMPDU));
5771                         if ((txrate[k]->idx >= 0)
5772                             && (txrate[k]->idx <
5773                                 hw->wiphy->bands[tx_info->band]->n_bitrates)) {
5774                                 rate_val[k] =
5775                                     hw->wiphy->bands[tx_info->band]->
5776                                     bitrates[txrate[k]->idx].hw_value;
5777                                 short_preamble[k] =
5778                                     txrate[k]->
5779                                     flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE ?
5780                                     true : false;
5781                         } else {
5782                                 ASSERT((txrate[k]->idx >= 0) &&
5783                                        (txrate[k]->idx <
5784                                         hw->wiphy->bands[tx_info->band]->
5785                                         n_bitrates));
5786                                 rate_val[k] = WLC_RATE_1M;
5787                         }
5788                 } else {
5789                         rate_val[k] = txrate[k]->idx;
5790                 }
5791                 /* Currently only support same setting for primay and fallback rates.
5792                  * Unify flags for each rate into a single value for the frame
5793                  */
5794                 use_rts |=
5795                     txrate[k]->
5796                     flags & IEEE80211_TX_RC_USE_RTS_CTS ? true : false;
5797                 use_cts |=
5798                     txrate[k]->
5799                     flags & IEEE80211_TX_RC_USE_CTS_PROTECT ? true : false;
5800
5801                 if (is_mcs[k])
5802                         rate_val[k] |= NRATE_MCS_INUSE;
5803
5804                 rspec[k] = mac80211_wlc_set_nrate(wlc, wlc->band, rate_val[k]);
5805
5806                 /* (1) RATE: determine and validate primary rate and fallback rates */
5807                 if (!RSPEC_ACTIVE(rspec[k])) {
5808                         ASSERT(RSPEC_ACTIVE(rspec[k]));
5809                         rspec[k] = WLC_RATE_1M;
5810                 } else {
5811                         if (!is_multicast_ether_addr(h->addr1)) {
5812                                 /* set tx antenna config */
5813                                 wlc_antsel_antcfg_get(wlc->asi, false, false, 0,
5814                                                       0, &antcfg, &fbantcfg);
5815                         }
5816                 }
5817         }
5818
5819         phyctl1_stf = wlc->stf->ss_opmode;
5820
5821         if (N_ENAB(wlc->pub)) {
5822                 for (k = 0; k < hw->max_rates; k++) {
5823                         /* apply siso/cdd to single stream mcs's or ofdm if rspec is auto selected */
5824                         if (((IS_MCS(rspec[k]) &&
5825                               IS_SINGLE_STREAM(rspec[k] & RSPEC_RATE_MASK)) ||
5826                              IS_OFDM(rspec[k]))
5827                             && ((rspec[k] & RSPEC_OVERRIDE_MCS_ONLY)
5828                                 || !(rspec[k] & RSPEC_OVERRIDE))) {
5829                                 rspec[k] &= ~(RSPEC_STF_MASK | RSPEC_STC_MASK);
5830
5831                                 /* For SISO MCS use STBC if possible */
5832                                 if (IS_MCS(rspec[k])
5833                                     && WLC_STF_SS_STBC_TX(wlc, scb)) {
5834                                         u8 stc;
5835
5836                                         ASSERT(WLC_STBC_CAP_PHY(wlc));
5837                                         stc = 1;        /* Nss for single stream is always 1 */
5838                                         rspec[k] |=
5839                                             (PHY_TXC1_MODE_STBC <<
5840                                              RSPEC_STF_SHIFT) | (stc <<
5841                                                                  RSPEC_STC_SHIFT);
5842                                 } else
5843                                         rspec[k] |=
5844                                             (phyctl1_stf << RSPEC_STF_SHIFT);
5845                         }
5846
5847                         /* Is the phy configured to use 40MHZ frames? If so then pick the desired txbw */
5848                         if (CHSPEC_WLC_BW(wlc->chanspec) == WLC_40_MHZ) {
5849                                 /* default txbw is 20in40 SB */
5850                                 mimo_ctlchbw = mimo_txbw =
5851                                     CHSPEC_SB_UPPER(WLC_BAND_PI_RADIO_CHANSPEC)
5852                                     ? PHY_TXC1_BW_20MHZ_UP : PHY_TXC1_BW_20MHZ;
5853
5854                                 if (IS_MCS(rspec[k])) {
5855                                         /* mcs 32 must be 40b/w DUP */
5856                                         if ((rspec[k] & RSPEC_RATE_MASK) == 32) {
5857                                                 mimo_txbw =
5858                                                     PHY_TXC1_BW_40MHZ_DUP;
5859                                                 /* use override */
5860                                         } else if (wlc->mimo_40txbw != AUTO)
5861                                                 mimo_txbw = wlc->mimo_40txbw;
5862                                         /* else check if dst is using 40 Mhz */
5863                                         else if (scb->flags & SCB_IS40)
5864                                                 mimo_txbw = PHY_TXC1_BW_40MHZ;
5865                                 } else if (IS_OFDM(rspec[k])) {
5866                                         if (wlc->ofdm_40txbw != AUTO)
5867                                                 mimo_txbw = wlc->ofdm_40txbw;
5868                                 } else {
5869                                         ASSERT(IS_CCK(rspec[k]));
5870                                         if (wlc->cck_40txbw != AUTO)
5871                                                 mimo_txbw = wlc->cck_40txbw;
5872                                 }
5873                         } else {
5874                                 /* mcs32 is 40 b/w only.
5875                                  * This is possible for probe packets on a STA during SCAN
5876                                  */
5877                                 if ((rspec[k] & RSPEC_RATE_MASK) == 32) {
5878                                         /* mcs 0 */
5879                                         rspec[k] = RSPEC_MIMORATE;
5880                                 }
5881                                 mimo_txbw = PHY_TXC1_BW_20MHZ;
5882                         }
5883
5884                         /* Set channel width */
5885                         rspec[k] &= ~RSPEC_BW_MASK;
5886                         if ((k == 0) || ((k > 0) && IS_MCS(rspec[k])))
5887                                 rspec[k] |= (mimo_txbw << RSPEC_BW_SHIFT);
5888                         else
5889                                 rspec[k] |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
5890
5891                         /* Set Short GI */
5892 #ifdef NOSGIYET
5893                         if (IS_MCS(rspec[k])
5894                             && (txrate[k]->flags & IEEE80211_TX_RC_SHORT_GI))
5895                                 rspec[k] |= RSPEC_SHORT_GI;
5896                         else if (!(txrate[k]->flags & IEEE80211_TX_RC_SHORT_GI))
5897                                 rspec[k] &= ~RSPEC_SHORT_GI;
5898 #else
5899                         rspec[k] &= ~RSPEC_SHORT_GI;
5900 #endif
5901
5902                         mimo_preamble_type = WLC_MM_PREAMBLE;
5903                         if (txrate[k]->flags & IEEE80211_TX_RC_GREEN_FIELD)
5904                                 mimo_preamble_type = WLC_GF_PREAMBLE;
5905
5906                         if ((txrate[k]->flags & IEEE80211_TX_RC_MCS)
5907                             && (!IS_MCS(rspec[k]))) {
5908                                 wiphy_err(wlc->wiphy, "wl%d: %s: IEEE80211_TX_"
5909                                           "RC_MCS != IS_MCS(rspec)\n",
5910                                           WLCWLUNIT(wlc), __func__);
5911                                 ASSERT(0 && "Rate mismatch");
5912                         }
5913
5914                         if (IS_MCS(rspec[k])) {
5915                                 preamble_type[k] = mimo_preamble_type;
5916
5917                                 /* if SGI is selected, then forced mm for single stream */
5918                                 if ((rspec[k] & RSPEC_SHORT_GI)
5919                                     && IS_SINGLE_STREAM(rspec[k] &
5920                                                         RSPEC_RATE_MASK)) {
5921                                         preamble_type[k] = WLC_MM_PREAMBLE;
5922                                 }
5923                         }
5924
5925                         /* mimo bw field MUST now be valid in the rspec (it affects duration calculations) */
5926                         ASSERT(VALID_RATE_DBG(wlc, rspec[0]));
5927
5928                         /* should be better conditionalized */
5929                         if (!IS_MCS(rspec[0])
5930                             && (tx_info->control.rates[0].
5931                                 flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE))
5932                                 preamble_type[k] = WLC_SHORT_PREAMBLE;
5933
5934                         ASSERT(!IS_MCS(rspec[0])
5935                                || WLC_IS_MIMO_PREAMBLE(preamble_type[k]));
5936                 }
5937         } else {
5938                 for (k = 0; k < hw->max_rates; k++) {
5939                         /* Set ctrlchbw as 20Mhz */
5940                         ASSERT(!IS_MCS(rspec[k]));
5941                         rspec[k] &= ~RSPEC_BW_MASK;
5942                         rspec[k] |= (PHY_TXC1_BW_20MHZ << RSPEC_BW_SHIFT);
5943
5944                         /* for nphy, stf of ofdm frames must follow policies */
5945                         if (WLCISNPHY(wlc->band) && IS_OFDM(rspec[k])) {
5946                                 rspec[k] &= ~RSPEC_STF_MASK;
5947                                 rspec[k] |= phyctl1_stf << RSPEC_STF_SHIFT;
5948                         }
5949                 }
5950         }
5951
5952         /* Reset these for use with AMPDU's */
5953         txrate[0]->count = 0;
5954         txrate[1]->count = 0;
5955
5956         /* (2) PROTECTION, may change rspec */
5957         if ((ieee80211_is_data(h->frame_control) ||
5958             ieee80211_is_mgmt(h->frame_control)) &&
5959             (phylen > wlc->RTSThresh) && !is_multicast_ether_addr(h->addr1))
5960                 use_rts = true;
5961
5962         /* (3) PLCP: determine PLCP header and MAC duration, fill d11txh_t */
5963         wlc_compute_plcp(wlc, rspec[0], phylen, plcp);
5964         wlc_compute_plcp(wlc, rspec[1], phylen, plcp_fallback);
5965         memcpy(&txh->FragPLCPFallback,
5966                plcp_fallback, sizeof(txh->FragPLCPFallback));
5967
5968         /* Length field now put in CCK FBR CRC field */
5969         if (IS_CCK(rspec[1])) {
5970                 txh->FragPLCPFallback[4] = phylen & 0xff;
5971                 txh->FragPLCPFallback[5] = (phylen & 0xff00) >> 8;
5972         }
5973
5974         /* MIMO-RATE: need validation ?? */
5975         mainrates =
5976             IS_OFDM(rspec[0]) ? D11A_PHY_HDR_GRATE((ofdm_phy_hdr_t *) plcp) :
5977             plcp[0];
5978
5979         /* DUR field for main rate */
5980         if (!ieee80211_is_pspoll(h->frame_control) &&
5981             !is_multicast_ether_addr(h->addr1) && !use_rifs) {
5982                 durid =
5983                     wlc_compute_frame_dur(wlc, rspec[0], preamble_type[0],
5984                                           next_frag_len);
5985                 h->duration_id = cpu_to_le16(durid);
5986         } else if (use_rifs) {
5987                 /* NAV protect to end of next max packet size */
5988                 durid =
5989                     (u16) wlc_calc_frame_time(wlc, rspec[0],
5990                                                  preamble_type[0],
5991                                                  DOT11_MAX_FRAG_LEN);
5992                 durid += RIFS_11N_TIME;
5993                 h->duration_id = cpu_to_le16(durid);
5994         }
5995
5996         /* DUR field for fallback rate */
5997         if (ieee80211_is_pspoll(h->frame_control))
5998                 txh->FragDurFallback = h->duration_id;
5999         else if (is_multicast_ether_addr(h->addr1) || use_rifs)
6000                 txh->FragDurFallback = 0;
6001         else {
6002                 durid = wlc_compute_frame_dur(wlc, rspec[1],
6003                                               preamble_type[1], next_frag_len);
6004                 txh->FragDurFallback = cpu_to_le16(durid);
6005         }
6006
6007         /* (4) MAC-HDR: MacTxControlLow */
6008         if (frag == 0)
6009                 mcl |= TXC_STARTMSDU;
6010
6011         if (!is_multicast_ether_addr(h->addr1))
6012                 mcl |= TXC_IMMEDACK;
6013
6014         if (BAND_5G(wlc->band->bandtype))
6015                 mcl |= TXC_FREQBAND_5G;
6016
6017         if (CHSPEC_IS40(WLC_BAND_PI_RADIO_CHANSPEC))
6018                 mcl |= TXC_BW_40;
6019
6020         /* set AMIC bit if using hardware TKIP MIC */
6021         if (hwtkmic)
6022                 mcl |= TXC_AMIC;
6023
6024         txh->MacTxControlLow = cpu_to_le16(mcl);
6025
6026         /* MacTxControlHigh */
6027         mch = 0;
6028
6029         /* Set fallback rate preamble type */
6030         if ((preamble_type[1] == WLC_SHORT_PREAMBLE) ||
6031             (preamble_type[1] == WLC_GF_PREAMBLE)) {
6032                 ASSERT((preamble_type[1] == WLC_GF_PREAMBLE) ||
6033                        (!IS_MCS(rspec[1])));
6034                 if (RSPEC2RATE(rspec[1]) != WLC_RATE_1M)
6035                         mch |= TXC_PREAMBLE_DATA_FB_SHORT;
6036         }
6037
6038         /* MacFrameControl */
6039         memcpy(&txh->MacFrameControl, &h->frame_control, sizeof(u16));
6040         txh->TxFesTimeNormal = cpu_to_le16(0);
6041
6042         txh->TxFesTimeFallback = cpu_to_le16(0);
6043
6044         /* TxFrameRA */
6045         memcpy(&txh->TxFrameRA, &h->addr1, ETH_ALEN);
6046
6047         /* TxFrameID */
6048         txh->TxFrameID = cpu_to_le16(frameid);
6049
6050         /* TxStatus, Note the case of recreating the first frag of a suppressed frame
6051          * then we may need to reset the retry cnt's via the status reg
6052          */
6053         txh->TxStatus = cpu_to_le16(status);
6054
6055         /* extra fields for ucode AMPDU aggregation, the new fields are added to
6056          * the END of previous structure so that it's compatible in driver.
6057          */
6058         txh->MaxNMpdus = cpu_to_le16(0);
6059         txh->MaxABytes_MRT = cpu_to_le16(0);
6060         txh->MaxABytes_FBR = cpu_to_le16(0);
6061         txh->MinMBytes = cpu_to_le16(0);
6062
6063         /* (5) RTS/CTS: determine RTS/CTS PLCP header and MAC duration, furnish d11txh_t */
6064         /* RTS PLCP header and RTS frame */
6065         if (use_rts || use_cts) {
6066                 if (use_rts && use_cts)
6067                         use_cts = false;
6068
6069                 for (k = 0; k < 2; k++) {
6070                         rts_rspec[k] = wlc_rspec_to_rts_rspec(wlc, rspec[k],
6071                                                               false,
6072                                                               mimo_ctlchbw);
6073                 }
6074
6075                 if (!IS_OFDM(rts_rspec[0]) &&
6076                     !((RSPEC2RATE(rts_rspec[0]) == WLC_RATE_1M) ||
6077                       (wlc->PLCPHdr_override == WLC_PLCP_LONG))) {
6078                         rts_preamble_type[0] = WLC_SHORT_PREAMBLE;
6079                         mch |= TXC_PREAMBLE_RTS_MAIN_SHORT;
6080                 }
6081
6082                 if (!IS_OFDM(rts_rspec[1]) &&
6083                     !((RSPEC2RATE(rts_rspec[1]) == WLC_RATE_1M) ||
6084                       (wlc->PLCPHdr_override == WLC_PLCP_LONG))) {
6085                         rts_preamble_type[1] = WLC_SHORT_PREAMBLE;
6086                         mch |= TXC_PREAMBLE_RTS_FB_SHORT;
6087                 }
6088
6089                 /* RTS/CTS additions to MacTxControlLow */
6090                 if (use_cts) {
6091                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDCTS);
6092                 } else {
6093                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDRTS);
6094                         txh->MacTxControlLow |= cpu_to_le16(TXC_LONGFRAME);
6095                 }
6096
6097                 /* RTS PLCP header */
6098                 ASSERT(IS_ALIGNED((unsigned long)txh->RTSPhyHeader, sizeof(u16)));
6099                 rts_plcp = txh->RTSPhyHeader;
6100                 if (use_cts)
6101                         rts_phylen = DOT11_CTS_LEN + FCS_LEN;
6102                 else
6103                         rts_phylen = DOT11_RTS_LEN + FCS_LEN;
6104
6105                 wlc_compute_plcp(wlc, rts_rspec[0], rts_phylen, rts_plcp);
6106
6107                 /* fallback rate version of RTS PLCP header */
6108                 wlc_compute_plcp(wlc, rts_rspec[1], rts_phylen,
6109                                  rts_plcp_fallback);
6110                 memcpy(&txh->RTSPLCPFallback, rts_plcp_fallback,
6111                        sizeof(txh->RTSPLCPFallback));
6112
6113                 /* RTS frame fields... */
6114                 rts = (struct ieee80211_rts *)&txh->rts_frame;
6115
6116                 durid = wlc_compute_rtscts_dur(wlc, use_cts, rts_rspec[0],
6117                                                rspec[0], rts_preamble_type[0],
6118                                                preamble_type[0], phylen, false);
6119                 rts->duration = cpu_to_le16(durid);
6120                 /* fallback rate version of RTS DUR field */
6121                 durid = wlc_compute_rtscts_dur(wlc, use_cts,
6122                                                rts_rspec[1], rspec[1],
6123                                                rts_preamble_type[1],
6124                                                preamble_type[1], phylen, false);
6125                 txh->RTSDurFallback = cpu_to_le16(durid);
6126
6127                 if (use_cts) {
6128                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
6129                                                          IEEE80211_STYPE_CTS);
6130
6131                         memcpy(&rts->ra, &h->addr2, ETH_ALEN);
6132                 } else {
6133                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
6134                                                          IEEE80211_STYPE_RTS);
6135
6136                         memcpy(&rts->ra, &h->addr1, 2 * ETH_ALEN);
6137                 }
6138
6139                 /* mainrate
6140                  *    low 8 bits: main frag rate/mcs,
6141                  *    high 8 bits: rts/cts rate/mcs
6142                  */
6143                 mainrates |= (IS_OFDM(rts_rspec[0]) ?
6144                               D11A_PHY_HDR_GRATE((ofdm_phy_hdr_t *) rts_plcp) :
6145                               rts_plcp[0]) << 8;
6146         } else {
6147                 memset((char *)txh->RTSPhyHeader, 0, D11_PHY_HDR_LEN);
6148                 memset((char *)&txh->rts_frame, 0,
6149                         sizeof(struct ieee80211_rts));
6150                 memset((char *)txh->RTSPLCPFallback, 0,
6151                       sizeof(txh->RTSPLCPFallback));
6152                 txh->RTSDurFallback = 0;
6153         }
6154
6155 #ifdef SUPPORT_40MHZ
6156         /* add null delimiter count */
6157         if ((tx_info->flags & IEEE80211_TX_CTL_AMPDU) && IS_MCS(rspec)) {
6158                 txh->RTSPLCPFallback[AMPDU_FBR_NULL_DELIM] =
6159                     wlc_ampdu_null_delim_cnt(wlc->ampdu, scb, rspec, phylen);
6160         }
6161 #endif
6162
6163         /* Now that RTS/RTS FB preamble types are updated, write the final value */
6164         txh->MacTxControlHigh = cpu_to_le16(mch);
6165
6166         /* MainRates (both the rts and frag plcp rates have been calculated now) */
6167         txh->MainRates = cpu_to_le16(mainrates);
6168
6169         /* XtraFrameTypes */
6170         xfts = FRAMETYPE(rspec[1], wlc->mimoft);
6171         xfts |= (FRAMETYPE(rts_rspec[0], wlc->mimoft) << XFTS_RTS_FT_SHIFT);
6172         xfts |= (FRAMETYPE(rts_rspec[1], wlc->mimoft) << XFTS_FBRRTS_FT_SHIFT);
6173         xfts |=
6174             CHSPEC_CHANNEL(WLC_BAND_PI_RADIO_CHANSPEC) << XFTS_CHANNEL_SHIFT;
6175         txh->XtraFrameTypes = cpu_to_le16(xfts);
6176
6177         /* PhyTxControlWord */
6178         phyctl = FRAMETYPE(rspec[0], wlc->mimoft);
6179         if ((preamble_type[0] == WLC_SHORT_PREAMBLE) ||
6180             (preamble_type[0] == WLC_GF_PREAMBLE)) {
6181                 ASSERT((preamble_type[0] == WLC_GF_PREAMBLE)
6182                        || !IS_MCS(rspec[0]));
6183                 if (RSPEC2RATE(rspec[0]) != WLC_RATE_1M)
6184                         phyctl |= PHY_TXC_SHORT_HDR;
6185                 wlc->pub->_cnt->txprshort++;
6186         }
6187
6188         /* phytxant is properly bit shifted */
6189         phyctl |= wlc_stf_d11hdrs_phyctl_txant(wlc, rspec[0]);
6190         txh->PhyTxControlWord = cpu_to_le16(phyctl);
6191
6192         /* PhyTxControlWord_1 */
6193         if (WLC_PHY_11N_CAP(wlc->band)) {
6194                 u16 phyctl1 = 0;
6195
6196                 phyctl1 = wlc_phytxctl1_calc(wlc, rspec[0]);
6197                 txh->PhyTxControlWord_1 = cpu_to_le16(phyctl1);
6198                 phyctl1 = wlc_phytxctl1_calc(wlc, rspec[1]);
6199                 txh->PhyTxControlWord_1_Fbr = cpu_to_le16(phyctl1);
6200
6201                 if (use_rts || use_cts) {
6202                         phyctl1 = wlc_phytxctl1_calc(wlc, rts_rspec[0]);
6203                         txh->PhyTxControlWord_1_Rts = cpu_to_le16(phyctl1);
6204                         phyctl1 = wlc_phytxctl1_calc(wlc, rts_rspec[1]);
6205                         txh->PhyTxControlWord_1_FbrRts = cpu_to_le16(phyctl1);
6206                 }
6207
6208                 /*
6209                  * For mcs frames, if mixedmode(overloaded with long preamble) is going to be set,
6210                  * fill in non-zero MModeLen and/or MModeFbrLen
6211                  *  it will be unnecessary if they are separated
6212                  */
6213                 if (IS_MCS(rspec[0]) && (preamble_type[0] == WLC_MM_PREAMBLE)) {
6214                         u16 mmodelen =
6215                             wlc_calc_lsig_len(wlc, rspec[0], phylen);
6216                         txh->MModeLen = cpu_to_le16(mmodelen);
6217                 }
6218
6219                 if (IS_MCS(rspec[1]) && (preamble_type[1] == WLC_MM_PREAMBLE)) {
6220                         u16 mmodefbrlen =
6221                             wlc_calc_lsig_len(wlc, rspec[1], phylen);
6222                         txh->MModeFbrLen = cpu_to_le16(mmodefbrlen);
6223                 }
6224         }
6225
6226         if (IS_MCS(rspec[0]))
6227                 ASSERT(IS_MCS(rspec[1]));
6228
6229         ASSERT(!IS_MCS(rspec[0]) ||
6230                ((preamble_type[0] == WLC_MM_PREAMBLE) == (txh->MModeLen != 0)));
6231         ASSERT(!IS_MCS(rspec[1]) ||
6232                ((preamble_type[1] == WLC_MM_PREAMBLE) ==
6233                 (txh->MModeFbrLen != 0)));
6234
6235         ac = skb_get_queue_mapping(p);
6236         if (SCB_WME(scb) && qos && wlc->edcf_txop[ac]) {
6237                 uint frag_dur, dur, dur_fallback;
6238
6239                 ASSERT(!is_multicast_ether_addr(h->addr1));
6240
6241                 /* WME: Update TXOP threshold */
6242                 if ((!(tx_info->flags & IEEE80211_TX_CTL_AMPDU)) && (frag == 0)) {
6243                         frag_dur =
6244                             wlc_calc_frame_time(wlc, rspec[0], preamble_type[0],
6245                                                 phylen);
6246
6247                         if (rts) {
6248                                 /* 1 RTS or CTS-to-self frame */
6249                                 dur =
6250                                     wlc_calc_cts_time(wlc, rts_rspec[0],
6251                                                       rts_preamble_type[0]);
6252                                 dur_fallback =
6253                                     wlc_calc_cts_time(wlc, rts_rspec[1],
6254                                                       rts_preamble_type[1]);
6255                                 /* (SIFS + CTS) + SIFS + frame + SIFS + ACK */
6256                                 dur += le16_to_cpu(rts->duration);
6257                                 dur_fallback +=
6258                                         le16_to_cpu(txh->RTSDurFallback);
6259                         } else if (use_rifs) {
6260                                 dur = frag_dur;
6261                                 dur_fallback = 0;
6262                         } else {
6263                                 /* frame + SIFS + ACK */
6264                                 dur = frag_dur;
6265                                 dur +=
6266                                     wlc_compute_frame_dur(wlc, rspec[0],
6267                                                           preamble_type[0], 0);
6268
6269                                 dur_fallback =
6270                                     wlc_calc_frame_time(wlc, rspec[1],
6271                                                         preamble_type[1],
6272                                                         phylen);
6273                                 dur_fallback +=
6274                                     wlc_compute_frame_dur(wlc, rspec[1],
6275                                                           preamble_type[1], 0);
6276                         }
6277                         /* NEED to set TxFesTimeNormal (hard) */
6278                         txh->TxFesTimeNormal = cpu_to_le16((u16) dur);
6279                         /* NEED to set fallback rate version of TxFesTimeNormal (hard) */
6280                         txh->TxFesTimeFallback =
6281                                 cpu_to_le16((u16) dur_fallback);
6282
6283                         /* update txop byte threshold (txop minus intraframe overhead) */
6284                         if (wlc->edcf_txop[ac] >= (dur - frag_dur)) {
6285                                 {
6286                                         uint newfragthresh;
6287
6288                                         newfragthresh =
6289                                             wlc_calc_frame_len(wlc, rspec[0],
6290                                                                preamble_type[0],
6291                                                                (wlc->
6292                                                                 edcf_txop[ac] -
6293                                                                 (dur -
6294                                                                  frag_dur)));
6295                                         /* range bound the fragthreshold */
6296                                         if (newfragthresh < DOT11_MIN_FRAG_LEN)
6297                                                 newfragthresh =
6298                                                     DOT11_MIN_FRAG_LEN;
6299                                         else if (newfragthresh >
6300                                                  wlc->usr_fragthresh)
6301                                                 newfragthresh =
6302                                                     wlc->usr_fragthresh;
6303                                         /* update the fragthresh and do txc update */
6304                                         if (wlc->fragthresh[queue] !=
6305                                             (u16) newfragthresh) {
6306                                                 wlc->fragthresh[queue] =
6307                                                     (u16) newfragthresh;
6308                                         }
6309                                 }
6310                         } else
6311                                 wiphy_err(wlc->wiphy, "wl%d: %s txop invalid "
6312                                           "for rate %d\n",
6313                                           wlc->pub->unit, fifo_names[queue],
6314                                           RSPEC2RATE(rspec[0]));
6315
6316                         if (dur > wlc->edcf_txop[ac])
6317                                 wiphy_err(wlc->wiphy, "wl%d: %s: %s txop "
6318                                           "exceeded phylen %d/%d dur %d/%d\n",
6319                                           wlc->pub->unit, __func__,
6320                                           fifo_names[queue],
6321                                           phylen, wlc->fragthresh[queue],
6322                                           dur, wlc->edcf_txop[ac]);
6323                 }
6324         }
6325
6326         return 0;
6327 }
6328
6329 void wlc_tbtt(struct wlc_info *wlc, d11regs_t *regs)
6330 {
6331         struct wlc_bsscfg *cfg = wlc->cfg;
6332
6333         wlc->pub->_cnt->tbtt++;
6334
6335         if (BSSCFG_STA(cfg)) {
6336                 /* run watchdog here if the watchdog timer is not armed */
6337                 if (WLC_WATCHDOG_TBTT(wlc)) {
6338                         u32 cur, delta;
6339                         if (wlc->WDarmed) {
6340                                 wl_del_timer(wlc->wl, wlc->wdtimer);
6341                                 wlc->WDarmed = false;
6342                         }
6343
6344                         cur = OSL_SYSUPTIME();
6345                         delta = cur > wlc->WDlast ? cur - wlc->WDlast :
6346                             (u32) ~0 - wlc->WDlast + cur + 1;
6347                         if (delta >= TIMER_INTERVAL_WATCHDOG) {
6348                                 wlc_watchdog((void *)wlc);
6349                                 wlc->WDlast = cur;
6350                         }
6351
6352                         wl_add_timer(wlc->wl, wlc->wdtimer,
6353                                      wlc_watchdog_backup_bi(wlc), true);
6354                         wlc->WDarmed = true;
6355                 }
6356         }
6357
6358         if (!cfg->BSS) {
6359                 /* DirFrmQ is now valid...defer setting until end of ATIM window */
6360                 wlc->qvalid |= MCMD_DIRFRMQVAL;
6361         }
6362 }
6363
6364 /* GP timer is a freerunning 32 bit counter, decrements at 1 us rate */
6365 void wlc_hwtimer_gptimer_set(struct wlc_info *wlc, uint us)
6366 {
6367         W_REG(&wlc->regs->gptimer, us);
6368 }
6369
6370 void wlc_hwtimer_gptimer_abort(struct wlc_info *wlc)
6371 {
6372         W_REG(&wlc->regs->gptimer, 0);
6373 }
6374
6375 static void wlc_hwtimer_gptimer_cb(struct wlc_info *wlc)
6376 {
6377         /* when interrupt is generated, the counter is loaded with last value
6378          * written and continue to decrement. So it has to be cleaned first
6379          */
6380         W_REG(&wlc->regs->gptimer, 0);
6381 }
6382
6383 /*
6384  * This fn has all the high level dpc processing from wlc_dpc.
6385  * POLICY: no macinstatus change, no bounding loop.
6386  *         All dpc bounding should be handled in BMAC dpc, like txstatus and rxint
6387  */
6388 void wlc_high_dpc(struct wlc_info *wlc, u32 macintstatus)
6389 {
6390         d11regs_t *regs = wlc->regs;
6391 #ifdef BCMDBG
6392         char flagstr[128];
6393         static const bcm_bit_desc_t int_flags[] = {
6394                 {MI_MACSSPNDD, "MACSSPNDD"},
6395                 {MI_BCNTPL, "BCNTPL"},
6396                 {MI_TBTT, "TBTT"},
6397                 {MI_BCNSUCCESS, "BCNSUCCESS"},
6398                 {MI_BCNCANCLD, "BCNCANCLD"},
6399                 {MI_ATIMWINEND, "ATIMWINEND"},
6400                 {MI_PMQ, "PMQ"},
6401                 {MI_NSPECGEN_0, "NSPECGEN_0"},
6402                 {MI_NSPECGEN_1, "NSPECGEN_1"},
6403                 {MI_MACTXERR, "MACTXERR"},
6404                 {MI_NSPECGEN_3, "NSPECGEN_3"},
6405                 {MI_PHYTXERR, "PHYTXERR"},
6406                 {MI_PME, "PME"},
6407                 {MI_GP0, "GP0"},
6408                 {MI_GP1, "GP1"},
6409                 {MI_DMAINT, "DMAINT"},
6410                 {MI_TXSTOP, "TXSTOP"},
6411                 {MI_CCA, "CCA"},
6412                 {MI_BG_NOISE, "BG_NOISE"},
6413                 {MI_DTIM_TBTT, "DTIM_TBTT"},
6414                 {MI_PRQ, "PRQ"},
6415                 {MI_PWRUP, "PWRUP"},
6416                 {MI_RFDISABLE, "RFDISABLE"},
6417                 {MI_TFS, "TFS"},
6418                 {MI_PHYCHANGED, "PHYCHANGED"},
6419                 {MI_TO, "TO"},
6420                 {0, NULL}
6421         };
6422
6423         if (macintstatus & ~(MI_TBTT | MI_TXSTOP)) {
6424                 bcm_format_flags(int_flags, macintstatus, flagstr,
6425                                  sizeof(flagstr));
6426                 WL_TRACE("wl%d: macintstatus 0x%x %s\n",
6427                          wlc->pub->unit, macintstatus, flagstr);
6428         }
6429 #endif                          /* BCMDBG */
6430
6431         if (macintstatus & MI_PRQ) {
6432                 /* Process probe request FIFO */
6433                 ASSERT(0 && "PRQ Interrupt in non-MBSS");
6434         }
6435
6436         /* TBTT indication */
6437         /* ucode only gives either TBTT or DTIM_TBTT, not both */
6438         if (macintstatus & (MI_TBTT | MI_DTIM_TBTT))
6439                 wlc_tbtt(wlc, regs);
6440
6441         if (macintstatus & MI_GP0) {
6442                 wiphy_err(wlc->wiphy, "wl%d: PSM microcode watchdog fired at "
6443                           "%d (seconds). Resetting.\n",
6444                           wlc->pub->unit, wlc->pub->now);
6445
6446                 printk_once("%s : PSM Watchdog, chipid 0x%x, chiprev 0x%x\n",
6447                                         __func__, wlc->pub->sih->chip,
6448                                         wlc->pub->sih->chiprev);
6449
6450                 wlc->pub->_cnt->psmwds++;
6451
6452                 /* big hammer */
6453                 wl_init(wlc->wl);
6454         }
6455
6456         /* gptimer timeout */
6457         if (macintstatus & MI_TO) {
6458                 wlc_hwtimer_gptimer_cb(wlc);
6459         }
6460
6461         if (macintstatus & MI_RFDISABLE) {
6462                 wiphy_err(wlc->wiphy, "wl%d: MAC Detected a change on the RF "
6463                           "Disable Input 0x%x\n", wlc->pub->unit,
6464                           R_REG(&regs->phydebug) & PDBG_RFD);
6465                 /* delay the cleanup to wl_down in IBSS case */
6466                 if ((R_REG(&regs->phydebug) & PDBG_RFD)) {
6467                         int idx;
6468                         struct wlc_bsscfg *bsscfg;
6469                         FOREACH_BSS(wlc, idx, bsscfg) {
6470                                 if (!BSSCFG_STA(bsscfg) || !bsscfg->enable
6471                                     || !bsscfg->BSS)
6472                                         continue;
6473                                 wiphy_err(wlc->wiphy, "wl%d: wlc_dpc: "
6474                                           "rfdisable -> wlc_bsscfg_disable()"
6475                                           "\n", wlc->pub->unit);
6476                         }
6477                 }
6478         }
6479
6480         /* send any enq'd tx packets. Just makes sure to jump start tx */
6481         if (!pktq_empty(&wlc->active_queue->q))
6482                 wlc_send_q(wlc, wlc->active_queue);
6483
6484         ASSERT(wlc_ps_check(wlc));
6485 }
6486
6487 static void wlc_war16165(struct wlc_info *wlc, bool tx)
6488 {
6489         if (tx) {
6490                 /* the post-increment is used in STAY_AWAKE macro */
6491                 if (wlc->txpend16165war++ == 0)
6492                         wlc_set_ps_ctrl(wlc);
6493         } else {
6494                 wlc->txpend16165war--;
6495                 if (wlc->txpend16165war == 0)
6496                         wlc_set_ps_ctrl(wlc);
6497         }
6498 }
6499
6500 /* process an individual tx_status_t */
6501 /* WLC_HIGH_API */
6502 bool BCMFASTPATH
6503 wlc_dotxstatus(struct wlc_info *wlc, tx_status_t *txs, u32 frm_tx2)
6504 {
6505         struct sk_buff *p;
6506         uint queue;
6507         d11txh_t *txh;
6508         struct scb *scb = NULL;
6509         bool free_pdu;
6510         int tx_rts, tx_frame_count, tx_rts_count;
6511         uint totlen, supr_status;
6512         bool lastframe;
6513         struct ieee80211_hdr *h;
6514         u16 mcl;
6515         struct ieee80211_tx_info *tx_info;
6516         struct ieee80211_tx_rate *txrate;
6517         int i;
6518
6519         (void)(frm_tx2);        /* Compiler reference to avoid unused variable warning */
6520
6521         /* discard intermediate indications for ucode with one legitimate case:
6522          *   e.g. if "useRTS" is set. ucode did a successful rts/cts exchange, but the subsequent
6523          *   tx of DATA failed. so it will start rts/cts from the beginning (resetting the rts
6524          *   transmission count)
6525          */
6526         if (!(txs->status & TX_STATUS_AMPDU)
6527             && (txs->status & TX_STATUS_INTERMEDIATE)) {
6528                 WLCNTADD(wlc->pub->_cnt->txnoack,
6529                          ((txs->
6530                            status & TX_STATUS_FRM_RTX_MASK) >>
6531                           TX_STATUS_FRM_RTX_SHIFT));
6532                 wiphy_err(wlc->wiphy, "%s: INTERMEDIATE but not AMPDU\n",
6533                           __func__);
6534                 return false;
6535         }
6536
6537         queue = txs->frameid & TXFID_QUEUE_MASK;
6538         ASSERT(queue < NFIFO);
6539         if (queue >= NFIFO) {
6540                 p = NULL;
6541                 goto fatal;
6542         }
6543
6544         p = GETNEXTTXP(wlc, queue);
6545         if (WLC_WAR16165(wlc))
6546                 wlc_war16165(wlc, false);
6547         if (p == NULL)
6548                 goto fatal;
6549
6550         txh = (d11txh_t *) (p->data);
6551         mcl = le16_to_cpu(txh->MacTxControlLow);
6552
6553         if (txs->phyerr) {
6554                 if (WL_ERROR_ON()) {
6555                         wiphy_err(wlc->wiphy, "phyerr 0x%x, rate 0x%x\n",
6556                                   txs->phyerr, txh->MainRates);
6557                         wlc_print_txdesc(txh);
6558                 }
6559                 wlc_print_txstatus(txs);
6560         }
6561
6562         ASSERT(txs->frameid == cpu_to_le16(txh->TxFrameID));
6563         if (txs->frameid != cpu_to_le16(txh->TxFrameID))
6564                 goto fatal;
6565
6566         tx_info = IEEE80211_SKB_CB(p);
6567         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
6568
6569         if (tx_info->control.sta)
6570                 scb = (struct scb *)tx_info->control.sta->drv_priv;
6571
6572         if (N_ENAB(wlc->pub)) {
6573                 u8 *plcp = (u8 *) (txh + 1);
6574                 if (PLCP3_ISSGI(plcp[3]))
6575                         wlc->pub->_cnt->txmpdu_sgi++;
6576                 if (PLCP3_ISSTBC(plcp[3]))
6577                         wlc->pub->_cnt->txmpdu_stbc++;
6578         }
6579
6580         if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
6581                 ASSERT((mcl & TXC_AMPDU_MASK) != TXC_AMPDU_NONE);
6582                 wlc_ampdu_dotxstatus(wlc->ampdu, scb, p, txs);
6583                 return false;
6584         }
6585
6586         supr_status = txs->status & TX_STATUS_SUPR_MASK;
6587         if (supr_status == TX_STATUS_SUPR_BADCH)
6588                 WL_TRACE("%s: Pkt tx suppressed, possibly channel %d\n",
6589                          __func__, CHSPEC_CHANNEL(wlc->default_bss->chanspec));
6590
6591         tx_rts = cpu_to_le16(txh->MacTxControlLow) & TXC_SENDRTS;
6592         tx_frame_count =
6593             (txs->status & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT;
6594         tx_rts_count =
6595             (txs->status & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT;
6596
6597         lastframe = !ieee80211_has_morefrags(h->frame_control);
6598
6599         if (!lastframe) {
6600                 wiphy_err(wlc->wiphy, "Not last frame!\n");
6601         } else {
6602                 u16 sfbl, lfbl;
6603                 ieee80211_tx_info_clear_status(tx_info);
6604                 if (queue < AC_COUNT) {
6605                         sfbl = WLC_WME_RETRY_SFB_GET(wlc, wme_fifo2ac[queue]);
6606                         lfbl = WLC_WME_RETRY_LFB_GET(wlc, wme_fifo2ac[queue]);
6607                 } else {
6608                         sfbl = wlc->SFBL;
6609                         lfbl = wlc->LFBL;
6610                 }
6611
6612                 txrate = tx_info->status.rates;
6613                 /* FIXME: this should use a combination of sfbl, lfbl depending on frame length and RTS setting */
6614                 if ((tx_frame_count > sfbl) && (txrate[1].idx >= 0)) {
6615                         /* rate selection requested a fallback rate and we used it */
6616                         txrate->count = lfbl;
6617                         txrate[1].count = tx_frame_count - lfbl;
6618                 } else {
6619                         /* rate selection did not request fallback rate, or we didn't need it */
6620                         txrate->count = tx_frame_count;
6621                         /* rc80211_minstrel.c:minstrel_tx_status() expects unused rates to be marked with idx = -1 */
6622                         txrate[1].idx = -1;
6623                         txrate[1].count = 0;
6624                 }
6625
6626                 /* clear the rest of the rates */
6627                 for (i = 2; i < IEEE80211_TX_MAX_RATES; i++) {
6628                         txrate[i].idx = -1;
6629                         txrate[i].count = 0;
6630                 }
6631
6632                 if (txs->status & TX_STATUS_ACK_RCV)
6633                         tx_info->flags |= IEEE80211_TX_STAT_ACK;
6634         }
6635
6636         totlen = pkttotlen(p);
6637         free_pdu = true;
6638
6639         wlc_txfifo_complete(wlc, queue, 1);
6640
6641         if (lastframe) {
6642                 p->next = NULL;
6643                 p->prev = NULL;
6644                 wlc->txretried = 0;
6645                 /* remove PLCP & Broadcom tx descriptor header */
6646                 skb_pull(p, D11_PHY_HDR_LEN);
6647                 skb_pull(p, D11_TXH_LEN);
6648                 ieee80211_tx_status_irqsafe(wlc->pub->ieee_hw, p);
6649                 wlc->pub->_cnt->ieee_tx_status++;
6650         } else {
6651                 wiphy_err(wlc->wiphy, "%s: Not last frame => not calling "
6652                           "tx_status\n", __func__);
6653         }
6654
6655         return false;
6656
6657  fatal:
6658         ASSERT(0);
6659         if (p)
6660                 pkt_buf_free_skb(p);
6661
6662         return true;
6663
6664 }
6665
6666 void BCMFASTPATH
6667 wlc_txfifo_complete(struct wlc_info *wlc, uint fifo, s8 txpktpend)
6668 {
6669         TXPKTPENDDEC(wlc, fifo, txpktpend);
6670         WL_TRACE("wlc_txfifo_complete, pktpend dec %d to %d\n",
6671                  txpktpend, TXPKTPENDGET(wlc, fifo));
6672
6673         /* There is more room; mark precedences related to this FIFO sendable */
6674         WLC_TX_FIFO_ENAB(wlc, fifo);
6675         ASSERT(TXPKTPENDGET(wlc, fifo) >= 0);
6676
6677         if (!TXPKTPENDTOT(wlc)) {
6678                 if (wlc->block_datafifo & DATA_BLOCK_TX_SUPR)
6679                         wlc_bsscfg_tx_check(wlc);
6680         }
6681
6682         /* Clear MHF2_TXBCMC_NOW flag if BCMC fifo has drained */
6683         if (AP_ENAB(wlc->pub) &&
6684             wlc->bcmcfifo_drain && !TXPKTPENDGET(wlc, TX_BCMC_FIFO)) {
6685                 wlc->bcmcfifo_drain = false;
6686                 wlc_mhf(wlc, MHF2, MHF2_TXBCMC_NOW, 0, WLC_BAND_AUTO);
6687         }
6688
6689         /* figure out which bsscfg is being worked on... */
6690 }
6691
6692 /* Given the beacon interval in kus, and a 64 bit TSF in us,
6693  * return the offset (in us) of the TSF from the last TBTT
6694  */
6695 u32 wlc_calc_tbtt_offset(u32 bp, u32 tsf_h, u32 tsf_l)
6696 {
6697         u32 k, btklo, btkhi, offset;
6698
6699         /* TBTT is always an even multiple of the beacon_interval,
6700          * so the TBTT less than or equal to the beacon timestamp is
6701          * the beacon timestamp minus the beacon timestamp modulo
6702          * the beacon interval.
6703          *
6704          * TBTT = BT - (BT % BIu)
6705          *      = (BTk - (BTk % BP)) * 2^10
6706          *
6707          * BT = beacon timestamp (usec, 64bits)
6708          * BTk = beacon timestamp (Kusec, 54bits)
6709          * BP = beacon interval (Kusec, 16bits)
6710          * BIu = BP * 2^10 = beacon interval (usec, 26bits)
6711          *
6712          * To keep the calculations in u32s, the modulo operation
6713          * on the high part of BT needs to be done in parts using the
6714          * relations:
6715          * X*Y mod Z = ((X mod Z) * (Y mod Z)) mod Z
6716          * and
6717          * (X + Y) mod Z = ((X mod Z) + (Y mod Z)) mod Z
6718          *
6719          * So, if BTk[n] = u16 n [0,3] of BTk.
6720          * BTk % BP = SUM((BTk[n] * 2^16n) % BP , 0<=n<4) % BP
6721          * and the SUM term can be broken down:
6722          * (BTk[n] *     2^16n)    % BP
6723          * (BTk[n] * (2^16n % BP)) % BP
6724          *
6725          * Create a set of power of 2 mod BP constants:
6726          * K[n] = 2^(16n) % BP
6727          *      = (K[n-1] * 2^16) % BP
6728          * K[2] = 2^32 % BP = ((2^16 % BP) * 2^16) % BP
6729          *
6730          * BTk % BP = BTk[0-1] % BP +
6731          *            (BTk[2] * K[2]) % BP +
6732          *            (BTk[3] * K[3]) % BP
6733          *
6734          * Since K[n] < 2^16 and BTk[n] is < 2^16, then BTk[n] * K[n] < 2^32
6735          */
6736
6737         /* BTk = BT >> 10, btklo = BTk[0-3], bkthi = BTk[4-6] */
6738         btklo = (tsf_h << 22) | (tsf_l >> 10);
6739         btkhi = tsf_h >> 10;
6740
6741         /* offset = BTk % BP */
6742         offset = btklo % bp;
6743
6744         /* K[2] = ((2^16 % BP) * 2^16) % BP */
6745         k = (u32) (1 << 16) % bp;
6746         k = (u32) (k * 1 << 16) % (u32) bp;
6747
6748         /* offset += (BTk[2] * K[2]) % BP */
6749         offset += ((btkhi & 0xffff) * k) % bp;
6750
6751         /* BTk[3] */
6752         btkhi = btkhi >> 16;
6753
6754         /* k[3] = (K[2] * 2^16) % BP */
6755         k = (k << 16) % bp;
6756
6757         /* offset += (BTk[3] * K[3]) % BP */
6758         offset += ((btkhi & 0xffff) * k) % bp;
6759
6760         offset = offset % bp;
6761
6762         /* convert offset from kus to us by shifting up 10 bits and
6763          * add in the low 10 bits of tsf that we ignored
6764          */
6765         offset = (offset << 10) + (tsf_l & 0x3FF);
6766
6767         return offset;
6768 }
6769
6770 /* Update beacon listen interval in shared memory */
6771 void wlc_bcn_li_upd(struct wlc_info *wlc)
6772 {
6773         if (AP_ENAB(wlc->pub))
6774                 return;
6775
6776         /* wake up every DTIM is the default */
6777         if (wlc->bcn_li_dtim == 1)
6778                 wlc_write_shm(wlc, M_BCN_LI, 0);
6779         else
6780                 wlc_write_shm(wlc, M_BCN_LI,
6781                               (wlc->bcn_li_dtim << 8) | wlc->bcn_li_bcn);
6782 }
6783
6784 static void
6785 prep_mac80211_status(struct wlc_info *wlc, d11rxhdr_t *rxh, struct sk_buff *p,
6786                      struct ieee80211_rx_status *rx_status)
6787 {
6788         u32 tsf_l, tsf_h;
6789         wlc_d11rxhdr_t *wlc_rxh = (wlc_d11rxhdr_t *) rxh;
6790         int preamble;
6791         int channel;
6792         ratespec_t rspec;
6793         unsigned char *plcp;
6794
6795 #if 0
6796         /* Clearly, this is bogus -- reading the TSF now is wrong */
6797         wlc_read_tsf(wlc, &tsf_l, &tsf_h);      /* mactime */
6798         rx_status->mactime = tsf_h;
6799         rx_status->mactime <<= 32;
6800         rx_status->mactime |= tsf_l;
6801         rx_status->flag |= RX_FLAG_MACTIME_MPDU; /* clearly wrong */
6802 #endif
6803
6804         channel = WLC_CHAN_CHANNEL(rxh->RxChan);
6805
6806         if (channel > 14) {
6807                 rx_status->band = IEEE80211_BAND_5GHZ;
6808                 rx_status->freq = ieee80211_ofdm_chan_to_freq(
6809                                         WF_CHAN_FACTOR_5_G/2, channel);
6810
6811         } else {
6812                 rx_status->band = IEEE80211_BAND_2GHZ;
6813                 rx_status->freq = ieee80211_dsss_chan_to_freq(channel);
6814         }
6815
6816         rx_status->signal = wlc_rxh->rssi;      /* signal */
6817
6818         /* noise */
6819         /* qual */
6820         rx_status->antenna = (rxh->PhyRxStatus_0 & PRXS0_RXANT_UPSUBBAND) ? 1 : 0;      /* ant */
6821
6822         plcp = p->data;
6823
6824         rspec = wlc_compute_rspec(rxh, plcp);
6825         if (IS_MCS(rspec)) {
6826                 rx_status->rate_idx = rspec & RSPEC_RATE_MASK;
6827                 rx_status->flag |= RX_FLAG_HT;
6828                 if (RSPEC_IS40MHZ(rspec))
6829                         rx_status->flag |= RX_FLAG_40MHZ;
6830         } else {
6831                 switch (RSPEC2RATE(rspec)) {
6832                 case WLC_RATE_1M:
6833                         rx_status->rate_idx = 0;
6834                         break;
6835                 case WLC_RATE_2M:
6836                         rx_status->rate_idx = 1;
6837                         break;
6838                 case WLC_RATE_5M5:
6839                         rx_status->rate_idx = 2;
6840                         break;
6841                 case WLC_RATE_11M:
6842                         rx_status->rate_idx = 3;
6843                         break;
6844                 case WLC_RATE_6M:
6845                         rx_status->rate_idx = 4;
6846                         break;
6847                 case WLC_RATE_9M:
6848                         rx_status->rate_idx = 5;
6849                         break;
6850                 case WLC_RATE_12M:
6851                         rx_status->rate_idx = 6;
6852                         break;
6853                 case WLC_RATE_18M:
6854                         rx_status->rate_idx = 7;
6855                         break;
6856                 case WLC_RATE_24M:
6857                         rx_status->rate_idx = 8;
6858                         break;
6859                 case WLC_RATE_36M:
6860                         rx_status->rate_idx = 9;
6861                         break;
6862                 case WLC_RATE_48M:
6863                         rx_status->rate_idx = 10;
6864                         break;
6865                 case WLC_RATE_54M:
6866                         rx_status->rate_idx = 11;
6867                         break;
6868                 default:
6869                         wiphy_err(wlc->wiphy, "%s: Unknown rate\n", __func__);
6870                 }
6871
6872                 /* Determine short preamble and rate_idx */
6873                 preamble = 0;
6874                 if (IS_CCK(rspec)) {
6875                         if (rxh->PhyRxStatus_0 & PRXS0_SHORTH)
6876                                 rx_status->flag |= RX_FLAG_SHORTPRE;
6877                 } else if (IS_OFDM(rspec)) {
6878                         rx_status->flag |= RX_FLAG_SHORTPRE;
6879                 } else {
6880                         wiphy_err(wlc->wiphy, "%s: Unknown modulation\n",
6881                                   __func__);
6882                 }
6883         }
6884
6885         if (PLCP3_ISSGI(plcp[3]))
6886                 rx_status->flag |= RX_FLAG_SHORT_GI;
6887
6888         if (rxh->RxStatus1 & RXS_DECERR) {
6889                 rx_status->flag |= RX_FLAG_FAILED_PLCP_CRC;
6890                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_PLCP_CRC\n",
6891                           __func__);
6892         }
6893         if (rxh->RxStatus1 & RXS_FCSERR) {
6894                 rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
6895                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_FCS_CRC\n",
6896                           __func__);
6897         }
6898 }
6899
6900 static void
6901 wlc_recvctl(struct wlc_info *wlc, d11rxhdr_t *rxh, struct sk_buff *p)
6902 {
6903         int len_mpdu;
6904         struct ieee80211_rx_status rx_status;
6905 #if defined(BCMDBG)
6906         struct sk_buff *skb = p;
6907 #endif                          /* BCMDBG */
6908
6909         memset(&rx_status, 0, sizeof(rx_status));
6910         prep_mac80211_status(wlc, rxh, p, &rx_status);
6911
6912         /* mac header+body length, exclude CRC and plcp header */
6913         len_mpdu = p->len - D11_PHY_HDR_LEN - FCS_LEN;
6914         skb_pull(p, D11_PHY_HDR_LEN);
6915         __skb_trim(p, len_mpdu);
6916
6917         ASSERT(!(p->next));
6918         ASSERT(!(p->prev));
6919
6920         ASSERT(IS_ALIGNED((unsigned long)skb->data, 2));
6921
6922         memcpy(IEEE80211_SKB_RXCB(p), &rx_status, sizeof(rx_status));
6923         ieee80211_rx_irqsafe(wlc->pub->ieee_hw, p);
6924
6925         wlc->pub->_cnt->ieee_rx++;
6926         return;
6927 }
6928
6929 void wlc_bss_list_free(struct wlc_info *wlc, struct wlc_bss_list *bss_list)
6930 {
6931         uint index;
6932
6933         if (!bss_list) {
6934                 wiphy_err(wlc->wiphy, "%s: Attempting to free NULL list\n",
6935                           __func__);
6936                 return;
6937         }
6938         /* inspect all BSS descriptor */
6939         for (index = 0; index < bss_list->count; index++) {
6940                 kfree(bss_list->ptrs[index]);
6941                 bss_list->ptrs[index] = NULL;
6942         }
6943         bss_list->count = 0;
6944 }
6945
6946 /* Process received frames */
6947 /*
6948  * Return true if more frames need to be processed. false otherwise.
6949  * Param 'bound' indicates max. # frames to process before break out.
6950  */
6951 /* WLC_HIGH_API */
6952 void BCMFASTPATH wlc_recv(struct wlc_info *wlc, struct sk_buff *p)
6953 {
6954         d11rxhdr_t *rxh;
6955         struct ieee80211_hdr *h;
6956         uint len;
6957         bool is_amsdu;
6958
6959         WL_TRACE("wl%d: wlc_recv\n", wlc->pub->unit);
6960
6961         /* frame starts with rxhdr */
6962         rxh = (d11rxhdr_t *) (p->data);
6963
6964         /* strip off rxhdr */
6965         skb_pull(p, wlc->hwrxoff);
6966
6967         /* fixup rx header endianness */
6968         rxh->RxFrameSize = le16_to_cpu(rxh->RxFrameSize);
6969         rxh->PhyRxStatus_0 = le16_to_cpu(rxh->PhyRxStatus_0);
6970         rxh->PhyRxStatus_1 = le16_to_cpu(rxh->PhyRxStatus_1);
6971         rxh->PhyRxStatus_2 = le16_to_cpu(rxh->PhyRxStatus_2);
6972         rxh->PhyRxStatus_3 = le16_to_cpu(rxh->PhyRxStatus_3);
6973         rxh->PhyRxStatus_4 = le16_to_cpu(rxh->PhyRxStatus_4);
6974         rxh->PhyRxStatus_5 = le16_to_cpu(rxh->PhyRxStatus_5);
6975         rxh->RxStatus1 = le16_to_cpu(rxh->RxStatus1);
6976         rxh->RxStatus2 = le16_to_cpu(rxh->RxStatus2);
6977         rxh->RxTSFTime = le16_to_cpu(rxh->RxTSFTime);
6978         rxh->RxChan = le16_to_cpu(rxh->RxChan);
6979
6980         /* MAC inserts 2 pad bytes for a4 headers or QoS or A-MSDU subframes */
6981         if (rxh->RxStatus1 & RXS_PBPRES) {
6982                 if (p->len < 2) {
6983                         wlc->pub->_cnt->rxrunt++;
6984                         wiphy_err(wlc->wiphy, "wl%d: wlc_recv: rcvd runt of "
6985                                   "len %d\n", wlc->pub->unit, p->len);
6986                         goto toss;
6987                 }
6988                 skb_pull(p, 2);
6989         }
6990
6991         h = (struct ieee80211_hdr *)(p->data + D11_PHY_HDR_LEN);
6992         len = p->len;
6993
6994         if (rxh->RxStatus1 & RXS_FCSERR) {
6995                 if (wlc->pub->mac80211_state & MAC80211_PROMISC_BCNS) {
6996                         wiphy_err(wlc->wiphy, "FCSERR while scanning******* -"
6997                                   " tossing\n");
6998                         goto toss;
6999                 } else {
7000                         wiphy_err(wlc->wiphy, "RCSERR!!!\n");
7001                         goto toss;
7002                 }
7003         }
7004
7005         /* check received pkt has at least frame control field */
7006         if (len < D11_PHY_HDR_LEN + sizeof(h->frame_control)) {
7007                 wlc->pub->_cnt->rxrunt++;
7008                 goto toss;
7009         }
7010
7011         is_amsdu = rxh->RxStatus2 & RXS_AMSDU_MASK;
7012
7013         /* explicitly test bad src address to avoid sending bad deauth */
7014         if (!is_amsdu) {
7015                 /* CTS and ACK CTL frames are w/o a2 */
7016
7017                 if (ieee80211_is_data(h->frame_control) ||
7018                     ieee80211_is_mgmt(h->frame_control)) {
7019                         if ((is_zero_ether_addr(h->addr2) ||
7020                              is_multicast_ether_addr(h->addr2))) {
7021                                 wiphy_err(wlc->wiphy, "wl%d: %s: dropping a "
7022                                           "frame with invalid src mac address,"
7023                                           " a2: %pM\n",
7024                                          wlc->pub->unit, __func__, h->addr2);
7025                                 wlc->pub->_cnt->rxbadsrcmac++;
7026                                 goto toss;
7027                         }
7028                         wlc->pub->_cnt->rxfrag++;
7029                 }
7030         }
7031
7032         /* due to sheer numbers, toss out probe reqs for now */
7033         if (ieee80211_is_probe_req(h->frame_control))
7034                 goto toss;
7035
7036         if (is_amsdu)
7037                 goto toss;
7038
7039         wlc_recvctl(wlc, rxh, p);
7040         return;
7041
7042  toss:
7043         pkt_buf_free_skb(p);
7044 }
7045
7046 /* calculate frame duration for Mixed-mode L-SIG spoofing, return
7047  * number of bytes goes in the length field
7048  *
7049  * Formula given by HT PHY Spec v 1.13
7050  *   len = 3(nsyms + nstream + 3) - 3
7051  */
7052 u16 BCMFASTPATH
7053 wlc_calc_lsig_len(struct wlc_info *wlc, ratespec_t ratespec, uint mac_len)
7054 {
7055         uint nsyms, len = 0, kNdps;
7056
7057         WL_TRACE("wl%d: wlc_calc_lsig_len: rate %d, len%d\n",
7058                  wlc->pub->unit, RSPEC2RATE(ratespec), mac_len);
7059
7060         if (IS_MCS(ratespec)) {
7061                 uint mcs = ratespec & RSPEC_RATE_MASK;
7062                 /* MCS_TXS(mcs) returns num tx streams - 1 */
7063                 int tot_streams = (MCS_TXS(mcs) + 1) + RSPEC_STC(ratespec);
7064
7065                 ASSERT(WLC_PHY_11N_CAP(wlc->band));
7066                 /* the payload duration calculation matches that of regular ofdm */
7067                 /* 1000Ndbps = kbps * 4 */
7068                 kNdps =
7069                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
7070                              RSPEC_ISSGI(ratespec)) * 4;
7071
7072                 if (RSPEC_STC(ratespec) == 0)
7073                         /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
7074                         nsyms =
7075                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
7076                                   APHY_TAIL_NBITS) * 1000, kNdps);
7077                 else
7078                         /* STBC needs to have even number of symbols */
7079                         nsyms =
7080                             2 *
7081                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
7082                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
7083
7084                 nsyms += (tot_streams + 3);     /* (+3) account for HT-SIG(2) and HT-STF(1) */
7085                 /* 3 bytes/symbol @ legacy 6Mbps rate */
7086                 len = (3 * nsyms) - 3;  /* (-3) excluding service bits and tail bits */
7087         }
7088
7089         return (u16) len;
7090 }
7091
7092 /* calculate frame duration of a given rate and length, return time in usec unit */
7093 uint BCMFASTPATH
7094 wlc_calc_frame_time(struct wlc_info *wlc, ratespec_t ratespec, u8 preamble_type,
7095                     uint mac_len)
7096 {
7097         uint nsyms, dur = 0, Ndps, kNdps;
7098         uint rate = RSPEC2RATE(ratespec);
7099
7100         if (rate == 0) {
7101                 ASSERT(0);
7102                 wiphy_err(wlc->wiphy, "wl%d: WAR: using rate of 1 mbps\n",
7103                           wlc->pub->unit);
7104                 rate = WLC_RATE_1M;
7105         }
7106
7107         WL_TRACE("wl%d: wlc_calc_frame_time: rspec 0x%x, preamble_type %d, len%d\n",
7108                  wlc->pub->unit, ratespec, preamble_type, mac_len);
7109
7110         if (IS_MCS(ratespec)) {
7111                 uint mcs = ratespec & RSPEC_RATE_MASK;
7112                 int tot_streams = MCS_TXS(mcs) + RSPEC_STC(ratespec);
7113                 ASSERT(WLC_PHY_11N_CAP(wlc->band));
7114                 ASSERT(WLC_IS_MIMO_PREAMBLE(preamble_type));
7115
7116                 dur = PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
7117                 if (preamble_type == WLC_MM_PREAMBLE)
7118                         dur += PREN_MM_EXT;
7119                 /* 1000Ndbps = kbps * 4 */
7120                 kNdps =
7121                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
7122                              RSPEC_ISSGI(ratespec)) * 4;
7123
7124                 if (RSPEC_STC(ratespec) == 0)
7125                         /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
7126                         nsyms =
7127                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
7128                                   APHY_TAIL_NBITS) * 1000, kNdps);
7129                 else
7130                         /* STBC needs to have even number of symbols */
7131                         nsyms =
7132                             2 *
7133                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
7134                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
7135
7136                 dur += APHY_SYMBOL_TIME * nsyms;
7137                 if (BAND_2G(wlc->band->bandtype))
7138                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
7139         } else if (IS_OFDM(rate)) {
7140                 dur = APHY_PREAMBLE_TIME;
7141                 dur += APHY_SIGNAL_TIME;
7142                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
7143                 Ndps = rate * 2;
7144                 /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
7145                 nsyms =
7146                     CEIL((APHY_SERVICE_NBITS + 8 * mac_len + APHY_TAIL_NBITS),
7147                          Ndps);
7148                 dur += APHY_SYMBOL_TIME * nsyms;
7149                 if (BAND_2G(wlc->band->bandtype))
7150                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
7151         } else {
7152                 /* calc # bits * 2 so factor of 2 in rate (1/2 mbps) will divide out */
7153                 mac_len = mac_len * 8 * 2;
7154                 /* calc ceiling of bits/rate = microseconds of air time */
7155                 dur = (mac_len + rate - 1) / rate;
7156                 if (preamble_type & WLC_SHORT_PREAMBLE)
7157                         dur += BPHY_PLCP_SHORT_TIME;
7158                 else
7159                         dur += BPHY_PLCP_TIME;
7160         }
7161         return dur;
7162 }
7163
7164 /* The opposite of wlc_calc_frame_time */
7165 static uint
7166 wlc_calc_frame_len(struct wlc_info *wlc, ratespec_t ratespec, u8 preamble_type,
7167                    uint dur)
7168 {
7169         uint nsyms, mac_len, Ndps, kNdps;
7170         uint rate = RSPEC2RATE(ratespec);
7171
7172         WL_TRACE("wl%d: wlc_calc_frame_len: rspec 0x%x, preamble_type %d, dur %d\n",
7173                  wlc->pub->unit, ratespec, preamble_type, dur);
7174
7175         if (IS_MCS(ratespec)) {
7176                 uint mcs = ratespec & RSPEC_RATE_MASK;
7177                 int tot_streams = MCS_TXS(mcs) + RSPEC_STC(ratespec);
7178                 ASSERT(WLC_PHY_11N_CAP(wlc->band));
7179                 dur -= PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
7180                 /* payload calculation matches that of regular ofdm */
7181                 if (BAND_2G(wlc->band->bandtype))
7182                         dur -= DOT11_OFDM_SIGNAL_EXTENSION;
7183                 /* kNdbps = kbps * 4 */
7184                 kNdps =
7185                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
7186                              RSPEC_ISSGI(ratespec)) * 4;
7187                 nsyms = dur / APHY_SYMBOL_TIME;
7188                 mac_len =
7189                     ((nsyms * kNdps) -
7190                      ((APHY_SERVICE_NBITS + APHY_TAIL_NBITS) * 1000)) / 8000;
7191         } else if (IS_OFDM(ratespec)) {
7192                 dur -= APHY_PREAMBLE_TIME;
7193                 dur -= APHY_SIGNAL_TIME;
7194                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
7195                 Ndps = rate * 2;
7196                 nsyms = dur / APHY_SYMBOL_TIME;
7197                 mac_len =
7198                     ((nsyms * Ndps) -
7199                      (APHY_SERVICE_NBITS + APHY_TAIL_NBITS)) / 8;
7200         } else {
7201                 if (preamble_type & WLC_SHORT_PREAMBLE)
7202                         dur -= BPHY_PLCP_SHORT_TIME;
7203                 else
7204                         dur -= BPHY_PLCP_TIME;
7205                 mac_len = dur * rate;
7206                 /* divide out factor of 2 in rate (1/2 mbps) */
7207                 mac_len = mac_len / 8 / 2;
7208         }
7209         return mac_len;
7210 }
7211
7212 static uint
7213 wlc_calc_ba_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
7214 {
7215         WL_TRACE("wl%d: wlc_calc_ba_time: rspec 0x%x, preamble_type %d\n",
7216                  wlc->pub->unit, rspec, preamble_type);
7217         /* Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that is less than
7218          * or equal to the rate of the immediately previous frame in the FES
7219          */
7220         rspec = WLC_BASIC_RATE(wlc, rspec);
7221         ASSERT(VALID_RATE_DBG(wlc, rspec));
7222
7223         /* BA len == 32 == 16(ctl hdr) + 4(ba len) + 8(bitmap) + 4(fcs) */
7224         return wlc_calc_frame_time(wlc, rspec, preamble_type,
7225                                    (DOT11_BA_LEN + DOT11_BA_BITMAP_LEN +
7226                                     FCS_LEN));
7227 }
7228
7229 static uint BCMFASTPATH
7230 wlc_calc_ack_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
7231 {
7232         uint dur = 0;
7233
7234         WL_TRACE("wl%d: wlc_calc_ack_time: rspec 0x%x, preamble_type %d\n",
7235                  wlc->pub->unit, rspec, preamble_type);
7236         /* Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that is less than
7237          * or equal to the rate of the immediately previous frame in the FES
7238          */
7239         rspec = WLC_BASIC_RATE(wlc, rspec);
7240         ASSERT(VALID_RATE_DBG(wlc, rspec));
7241
7242         /* ACK frame len == 14 == 2(fc) + 2(dur) + 6(ra) + 4(fcs) */
7243         dur =
7244             wlc_calc_frame_time(wlc, rspec, preamble_type,
7245                                 (DOT11_ACK_LEN + FCS_LEN));
7246         return dur;
7247 }
7248
7249 static uint
7250 wlc_calc_cts_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
7251 {
7252         WL_TRACE("wl%d: wlc_calc_cts_time: ratespec 0x%x, preamble_type %d\n",
7253                  wlc->pub->unit, rspec, preamble_type);
7254         return wlc_calc_ack_time(wlc, rspec, preamble_type);
7255 }
7256
7257 /* derive wlc->band->basic_rate[] table from 'rateset' */
7258 void wlc_rate_lookup_init(struct wlc_info *wlc, wlc_rateset_t *rateset)
7259 {
7260         u8 rate;
7261         u8 mandatory;
7262         u8 cck_basic = 0;
7263         u8 ofdm_basic = 0;
7264         u8 *br = wlc->band->basic_rate;
7265         uint i;
7266
7267         /* incoming rates are in 500kbps units as in 802.11 Supported Rates */
7268         memset(br, 0, WLC_MAXRATE + 1);
7269
7270         /* For each basic rate in the rates list, make an entry in the
7271          * best basic lookup.
7272          */
7273         for (i = 0; i < rateset->count; i++) {
7274                 /* only make an entry for a basic rate */
7275                 if (!(rateset->rates[i] & WLC_RATE_FLAG))
7276                         continue;
7277
7278                 /* mask off basic bit */
7279                 rate = (rateset->rates[i] & WLC_RATE_MASK);
7280
7281                 if (rate > WLC_MAXRATE) {
7282                         wiphy_err(wlc->wiphy, "wlc_rate_lookup_init: invalid "
7283                                   "rate 0x%X in rate set\n",
7284                                   rateset->rates[i]);
7285                         continue;
7286                 }
7287
7288                 br[rate] = rate;
7289         }
7290
7291         /* The rate lookup table now has non-zero entries for each
7292          * basic rate, equal to the basic rate: br[basicN] = basicN
7293          *
7294          * To look up the best basic rate corresponding to any
7295          * particular rate, code can use the basic_rate table
7296          * like this
7297          *
7298          * basic_rate = wlc->band->basic_rate[tx_rate]
7299          *
7300          * Make sure there is a best basic rate entry for
7301          * every rate by walking up the table from low rates
7302          * to high, filling in holes in the lookup table
7303          */
7304
7305         for (i = 0; i < wlc->band->hw_rateset.count; i++) {
7306                 rate = wlc->band->hw_rateset.rates[i];
7307                 ASSERT(rate <= WLC_MAXRATE);
7308
7309                 if (br[rate] != 0) {
7310                         /* This rate is a basic rate.
7311                          * Keep track of the best basic rate so far by
7312                          * modulation type.
7313                          */
7314                         if (IS_OFDM(rate))
7315                                 ofdm_basic = rate;
7316                         else
7317                                 cck_basic = rate;
7318
7319                         continue;
7320                 }
7321
7322                 /* This rate is not a basic rate so figure out the
7323                  * best basic rate less than this rate and fill in
7324                  * the hole in the table
7325                  */
7326
7327                 br[rate] = IS_OFDM(rate) ? ofdm_basic : cck_basic;
7328
7329                 if (br[rate] != 0)
7330                         continue;
7331
7332                 if (IS_OFDM(rate)) {
7333                         /* In 11g and 11a, the OFDM mandatory rates are 6, 12, and 24 Mbps */
7334                         if (rate >= WLC_RATE_24M)
7335                                 mandatory = WLC_RATE_24M;
7336                         else if (rate >= WLC_RATE_12M)
7337                                 mandatory = WLC_RATE_12M;
7338                         else
7339                                 mandatory = WLC_RATE_6M;
7340                 } else {
7341                         /* In 11b, all the CCK rates are mandatory 1 - 11 Mbps */
7342                         mandatory = rate;
7343                 }
7344
7345                 br[rate] = mandatory;
7346         }
7347 }
7348
7349 static void wlc_write_rate_shm(struct wlc_info *wlc, u8 rate, u8 basic_rate)
7350 {
7351         u8 phy_rate, index;
7352         u8 basic_phy_rate, basic_index;
7353         u16 dir_table, basic_table;
7354         u16 basic_ptr;
7355
7356         /* Shared memory address for the table we are reading */
7357         dir_table = IS_OFDM(basic_rate) ? M_RT_DIRMAP_A : M_RT_DIRMAP_B;
7358
7359         /* Shared memory address for the table we are writing */
7360         basic_table = IS_OFDM(rate) ? M_RT_BBRSMAP_A : M_RT_BBRSMAP_B;
7361
7362         /*
7363          * for a given rate, the LS-nibble of the PLCP SIGNAL field is
7364          * the index into the rate table.
7365          */
7366         phy_rate = rate_info[rate] & WLC_RATE_MASK;
7367         basic_phy_rate = rate_info[basic_rate] & WLC_RATE_MASK;
7368         index = phy_rate & 0xf;
7369         basic_index = basic_phy_rate & 0xf;
7370
7371         /* Find the SHM pointer to the ACK rate entry by looking in the
7372          * Direct-map Table
7373          */
7374         basic_ptr = wlc_read_shm(wlc, (dir_table + basic_index * 2));
7375
7376         /* Update the SHM BSS-basic-rate-set mapping table with the pointer
7377          * to the correct basic rate for the given incoming rate
7378          */
7379         wlc_write_shm(wlc, (basic_table + index * 2), basic_ptr);
7380 }
7381
7382 static const wlc_rateset_t *wlc_rateset_get_hwrs(struct wlc_info *wlc)
7383 {
7384         const wlc_rateset_t *rs_dflt;
7385
7386         if (WLC_PHY_11N_CAP(wlc->band)) {
7387                 if (BAND_5G(wlc->band->bandtype))
7388                         rs_dflt = &ofdm_mimo_rates;
7389                 else
7390                         rs_dflt = &cck_ofdm_mimo_rates;
7391         } else if (wlc->band->gmode)
7392                 rs_dflt = &cck_ofdm_rates;
7393         else
7394                 rs_dflt = &cck_rates;
7395
7396         return rs_dflt;
7397 }
7398
7399 void wlc_set_ratetable(struct wlc_info *wlc)
7400 {
7401         const wlc_rateset_t *rs_dflt;
7402         wlc_rateset_t rs;
7403         u8 rate, basic_rate;
7404         uint i;
7405
7406         rs_dflt = wlc_rateset_get_hwrs(wlc);
7407         ASSERT(rs_dflt != NULL);
7408
7409         wlc_rateset_copy(rs_dflt, &rs);
7410         wlc_rateset_mcs_upd(&rs, wlc->stf->txstreams);
7411
7412         /* walk the phy rate table and update SHM basic rate lookup table */
7413         for (i = 0; i < rs.count; i++) {
7414                 rate = rs.rates[i] & WLC_RATE_MASK;
7415
7416                 /* for a given rate WLC_BASIC_RATE returns the rate at
7417                  * which a response ACK/CTS should be sent.
7418                  */
7419                 basic_rate = WLC_BASIC_RATE(wlc, rate);
7420                 if (basic_rate == 0) {
7421                         /* This should only happen if we are using a
7422                          * restricted rateset.
7423                          */
7424                         basic_rate = rs.rates[0] & WLC_RATE_MASK;
7425                 }
7426
7427                 wlc_write_rate_shm(wlc, rate, basic_rate);
7428         }
7429 }
7430
7431 /*
7432  * Return true if the specified rate is supported by the specified band.
7433  * WLC_BAND_AUTO indicates the current band.
7434  */
7435 bool wlc_valid_rate(struct wlc_info *wlc, ratespec_t rspec, int band,
7436                     bool verbose)
7437 {
7438         wlc_rateset_t *hw_rateset;
7439         uint i;
7440
7441         if ((band == WLC_BAND_AUTO) || (band == wlc->band->bandtype)) {
7442                 hw_rateset = &wlc->band->hw_rateset;
7443         } else if (NBANDS(wlc) > 1) {
7444                 hw_rateset = &wlc->bandstate[OTHERBANDUNIT(wlc)]->hw_rateset;
7445         } else {
7446                 /* other band specified and we are a single band device */
7447                 return false;
7448         }
7449
7450         /* check if this is a mimo rate */
7451         if (IS_MCS(rspec)) {
7452                 if (!VALID_MCS((rspec & RSPEC_RATE_MASK)))
7453                         goto error;
7454
7455                 return isset(hw_rateset->mcs, (rspec & RSPEC_RATE_MASK));
7456         }
7457
7458         for (i = 0; i < hw_rateset->count; i++)
7459                 if (hw_rateset->rates[i] == RSPEC2RATE(rspec))
7460                         return true;
7461  error:
7462         if (verbose) {
7463                 wiphy_err(wlc->wiphy, "wl%d: wlc_valid_rate: rate spec 0x%x "
7464                           "not in hw_rateset\n", wlc->pub->unit, rspec);
7465         }
7466
7467         return false;
7468 }
7469
7470 static void wlc_update_mimo_band_bwcap(struct wlc_info *wlc, u8 bwcap)
7471 {
7472         uint i;
7473         struct wlcband *band;
7474
7475         for (i = 0; i < NBANDS(wlc); i++) {
7476                 if (IS_SINGLEBAND_5G(wlc->deviceid))
7477                         i = BAND_5G_INDEX;
7478                 band = wlc->bandstate[i];
7479                 if (band->bandtype == WLC_BAND_5G) {
7480                         if ((bwcap == WLC_N_BW_40ALL)
7481                             || (bwcap == WLC_N_BW_20IN2G_40IN5G))
7482                                 band->mimo_cap_40 = true;
7483                         else
7484                                 band->mimo_cap_40 = false;
7485                 } else {
7486                         ASSERT(band->bandtype == WLC_BAND_2G);
7487                         if (bwcap == WLC_N_BW_40ALL)
7488                                 band->mimo_cap_40 = true;
7489                         else
7490                                 band->mimo_cap_40 = false;
7491                 }
7492         }
7493
7494         wlc->mimo_band_bwcap = bwcap;
7495 }
7496
7497 void wlc_mod_prb_rsp_rate_table(struct wlc_info *wlc, uint frame_len)
7498 {
7499         const wlc_rateset_t *rs_dflt;
7500         wlc_rateset_t rs;
7501         u8 rate;
7502         u16 entry_ptr;
7503         u8 plcp[D11_PHY_HDR_LEN];
7504         u16 dur, sifs;
7505         uint i;
7506
7507         sifs = SIFS(wlc->band);
7508
7509         rs_dflt = wlc_rateset_get_hwrs(wlc);
7510         ASSERT(rs_dflt != NULL);
7511
7512         wlc_rateset_copy(rs_dflt, &rs);
7513         wlc_rateset_mcs_upd(&rs, wlc->stf->txstreams);
7514
7515         /* walk the phy rate table and update MAC core SHM basic rate table entries */
7516         for (i = 0; i < rs.count; i++) {
7517                 rate = rs.rates[i] & WLC_RATE_MASK;
7518
7519                 entry_ptr = wlc_rate_shm_offset(wlc, rate);
7520
7521                 /* Calculate the Probe Response PLCP for the given rate */
7522                 wlc_compute_plcp(wlc, rate, frame_len, plcp);
7523
7524                 /* Calculate the duration of the Probe Response frame plus SIFS for the MAC */
7525                 dur =
7526                     (u16) wlc_calc_frame_time(wlc, rate, WLC_LONG_PREAMBLE,
7527                                                  frame_len);
7528                 dur += sifs;
7529
7530                 /* Update the SHM Rate Table entry Probe Response values */
7531                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS,
7532                               (u16) (plcp[0] + (plcp[1] << 8)));
7533                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS + 2,
7534                               (u16) (plcp[2] + (plcp[3] << 8)));
7535                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_DUR_POS, dur);
7536         }
7537 }
7538
7539 u16
7540 wlc_compute_bcntsfoff(struct wlc_info *wlc, ratespec_t rspec,
7541                       bool short_preamble, bool phydelay)
7542 {
7543         uint bcntsfoff = 0;
7544
7545         if (IS_MCS(rspec)) {
7546                 wiphy_err(wlc->wiphy, "wl%d: recd beacon with mcs rate; rspec "
7547                           "0x%x\n", wlc->pub->unit, rspec);
7548         } else if (IS_OFDM(rspec)) {
7549                 /* tx delay from MAC through phy to air (2.1 usec) +
7550                  * phy header time (preamble + PLCP SIGNAL == 20 usec) +
7551                  * PLCP SERVICE + MAC header time (SERVICE + FC + DUR + A1 + A2 + A3 + SEQ == 26
7552                  * bytes at beacon rate)
7553                  */
7554                 bcntsfoff += phydelay ? D11A_PHY_TX_DELAY : 0;
7555                 bcntsfoff += APHY_PREAMBLE_TIME + APHY_SIGNAL_TIME;
7556                 bcntsfoff +=
7557                     wlc_compute_airtime(wlc, rspec,
7558                                         APHY_SERVICE_NBITS / 8 +
7559                                         DOT11_MAC_HDR_LEN);
7560         } else {
7561                 /* tx delay from MAC through phy to air (3.4 usec) +
7562                  * phy header time (long preamble + PLCP == 192 usec) +
7563                  * MAC header time (FC + DUR + A1 + A2 + A3 + SEQ == 24 bytes at beacon rate)
7564                  */
7565                 bcntsfoff += phydelay ? D11B_PHY_TX_DELAY : 0;
7566                 bcntsfoff +=
7567                     short_preamble ? D11B_PHY_SPREHDR_TIME :
7568                     D11B_PHY_LPREHDR_TIME;
7569                 bcntsfoff += wlc_compute_airtime(wlc, rspec, DOT11_MAC_HDR_LEN);
7570         }
7571         return (u16) (bcntsfoff);
7572 }
7573
7574 /*      Max buffering needed for beacon template/prb resp template is 142 bytes.
7575  *
7576  *      PLCP header is 6 bytes.
7577  *      802.11 A3 header is 24 bytes.
7578  *      Max beacon frame body template length is 112 bytes.
7579  *      Max probe resp frame body template length is 110 bytes.
7580  *
7581  *      *len on input contains the max length of the packet available.
7582  *
7583  *      The *len value is set to the number of bytes in buf used, and starts with the PLCP
7584  *      and included up to, but not including, the 4 byte FCS.
7585  */
7586 static void
7587 wlc_bcn_prb_template(struct wlc_info *wlc, u16 type, ratespec_t bcn_rspec,
7588                      struct wlc_bsscfg *cfg, u16 *buf, int *len)
7589 {
7590         static const u8 ether_bcast[ETH_ALEN] = {255, 255, 255, 255, 255, 255};
7591         cck_phy_hdr_t *plcp;
7592         struct ieee80211_mgmt *h;
7593         int hdr_len, body_len;
7594
7595         ASSERT(*len >= 142);
7596         ASSERT(type == IEEE80211_STYPE_BEACON ||
7597                type == IEEE80211_STYPE_PROBE_RESP);
7598
7599         if (MBSS_BCN_ENAB(cfg) && type == IEEE80211_STYPE_BEACON)
7600                 hdr_len = DOT11_MAC_HDR_LEN;
7601         else
7602                 hdr_len = D11_PHY_HDR_LEN + DOT11_MAC_HDR_LEN;
7603         body_len = *len - hdr_len;      /* calc buffer size provided for frame body */
7604
7605         *len = hdr_len + body_len;      /* return actual size */
7606
7607         /* format PHY and MAC headers */
7608         memset((char *)buf, 0, hdr_len);
7609
7610         plcp = (cck_phy_hdr_t *) buf;
7611
7612         /* PLCP for Probe Response frames are filled in from core's rate table */
7613         if (type == IEEE80211_STYPE_BEACON && !MBSS_BCN_ENAB(cfg)) {
7614                 /* fill in PLCP */
7615                 wlc_compute_plcp(wlc, bcn_rspec,
7616                                  (DOT11_MAC_HDR_LEN + body_len + FCS_LEN),
7617                                  (u8 *) plcp);
7618
7619         }
7620         /* "Regular" and 16 MBSS but not for 4 MBSS */
7621         /* Update the phytxctl for the beacon based on the rspec */
7622         if (!SOFTBCN_ENAB(cfg))
7623                 wlc_beacon_phytxctl_txant_upd(wlc, bcn_rspec);
7624
7625         if (MBSS_BCN_ENAB(cfg) && type == IEEE80211_STYPE_BEACON)
7626                 h = (struct ieee80211_mgmt *)&plcp[0];
7627         else
7628                 h = (struct ieee80211_mgmt *)&plcp[1];
7629
7630         /* fill in 802.11 header */
7631         h->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | type);
7632
7633         /* DUR is 0 for multicast bcn, or filled in by MAC for prb resp */
7634         /* A1 filled in by MAC for prb resp, broadcast for bcn */
7635         if (type == IEEE80211_STYPE_BEACON)
7636                 memcpy(&h->da, &ether_bcast, ETH_ALEN);
7637         memcpy(&h->sa, &cfg->cur_etheraddr, ETH_ALEN);
7638         memcpy(&h->bssid, &cfg->BSSID, ETH_ALEN);
7639
7640         /* SEQ filled in by MAC */
7641
7642         return;
7643 }
7644
7645 int wlc_get_header_len()
7646 {
7647         return TXOFF;
7648 }
7649
7650 /* Update a beacon for a particular BSS
7651  * For MBSS, this updates the software template and sets "latest" to the index of the
7652  * template updated.
7653  * Otherwise, it updates the hardware template.
7654  */
7655 void wlc_bss_update_beacon(struct wlc_info *wlc, struct wlc_bsscfg *cfg)
7656 {
7657         int len = BCN_TMPL_LEN;
7658
7659         /* Clear the soft intmask */
7660         wlc->defmacintmask &= ~MI_BCNTPL;
7661
7662         if (!cfg->up) {         /* Only allow updates on an UP bss */
7663                 return;
7664         }
7665
7666         /* Optimize:  Some of if/else could be combined */
7667         if (!MBSS_BCN_ENAB(cfg) && HWBCN_ENAB(cfg)) {
7668                 /* Hardware beaconing for this config */
7669                 u16 bcn[BCN_TMPL_LEN / 2];
7670                 u32 both_valid = MCMD_BCN0VLD | MCMD_BCN1VLD;
7671                 d11regs_t *regs = wlc->regs;
7672
7673                 /* Check if both templates are in use, if so sched. an interrupt
7674                  *      that will call back into this routine
7675                  */
7676                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
7677                         /* clear any previous status */
7678                         W_REG(&regs->macintstatus, MI_BCNTPL);
7679                 }
7680                 /* Check that after scheduling the interrupt both of the
7681                  *      templates are still busy. if not clear the int. & remask
7682                  */
7683                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
7684                         wlc->defmacintmask |= MI_BCNTPL;
7685                         return;
7686                 }
7687
7688                 wlc->bcn_rspec =
7689                     wlc_lowest_basic_rspec(wlc, &cfg->current_bss->rateset);
7690                 ASSERT(wlc_valid_rate
7691                        (wlc, wlc->bcn_rspec,
7692                         CHSPEC_IS2G(cfg->current_bss->
7693                                     chanspec) ? WLC_BAND_2G : WLC_BAND_5G,
7694                         true));
7695
7696                 /* update the template and ucode shm */
7697                 wlc_bcn_prb_template(wlc, IEEE80211_STYPE_BEACON,
7698                                      wlc->bcn_rspec, cfg, bcn, &len);
7699                 wlc_write_hw_bcntemplates(wlc, bcn, len, false);
7700         }
7701 }
7702
7703 /*
7704  * Update all beacons for the system.
7705  */
7706 void wlc_update_beacon(struct wlc_info *wlc)
7707 {
7708         int idx;
7709         struct wlc_bsscfg *bsscfg;
7710
7711         /* update AP or IBSS beacons */
7712         FOREACH_BSS(wlc, idx, bsscfg) {
7713                 if (bsscfg->up && (BSSCFG_AP(bsscfg) || !bsscfg->BSS))
7714                         wlc_bss_update_beacon(wlc, bsscfg);
7715         }
7716 }
7717
7718 /* Write ssid into shared memory */
7719 void wlc_shm_ssid_upd(struct wlc_info *wlc, struct wlc_bsscfg *cfg)
7720 {
7721         u8 *ssidptr = cfg->SSID;
7722         u16 base = M_SSID;
7723         u8 ssidbuf[IEEE80211_MAX_SSID_LEN];
7724
7725         /* padding the ssid with zero and copy it into shm */
7726         memset(ssidbuf, 0, IEEE80211_MAX_SSID_LEN);
7727         memcpy(ssidbuf, ssidptr, cfg->SSID_len);
7728
7729         wlc_copyto_shm(wlc, base, ssidbuf, IEEE80211_MAX_SSID_LEN);
7730
7731         if (!MBSS_BCN_ENAB(cfg))
7732                 wlc_write_shm(wlc, M_SSIDLEN, (u16) cfg->SSID_len);
7733 }
7734
7735 void wlc_update_probe_resp(struct wlc_info *wlc, bool suspend)
7736 {
7737         int idx;
7738         struct wlc_bsscfg *bsscfg;
7739
7740         /* update AP or IBSS probe responses */
7741         FOREACH_BSS(wlc, idx, bsscfg) {
7742                 if (bsscfg->up && (BSSCFG_AP(bsscfg) || !bsscfg->BSS))
7743                         wlc_bss_update_probe_resp(wlc, bsscfg, suspend);
7744         }
7745 }
7746
7747 void
7748 wlc_bss_update_probe_resp(struct wlc_info *wlc, struct wlc_bsscfg *cfg,
7749                           bool suspend)
7750 {
7751         u16 prb_resp[BCN_TMPL_LEN / 2];
7752         int len = BCN_TMPL_LEN;
7753
7754         /* write the probe response to hardware, or save in the config structure */
7755         if (!MBSS_PRB_ENAB(cfg)) {
7756
7757                 /* create the probe response template */
7758                 wlc_bcn_prb_template(wlc, IEEE80211_STYPE_PROBE_RESP, 0, cfg,
7759                                      prb_resp, &len);
7760
7761                 if (suspend)
7762                         wlc_suspend_mac_and_wait(wlc);
7763
7764                 /* write the probe response into the template region */
7765                 wlc_bmac_write_template_ram(wlc->hw, T_PRS_TPL_BASE,
7766                                             (len + 3) & ~3, prb_resp);
7767
7768                 /* write the length of the probe response frame (+PLCP/-FCS) */
7769                 wlc_write_shm(wlc, M_PRB_RESP_FRM_LEN, (u16) len);
7770
7771                 /* write the SSID and SSID length */
7772                 wlc_shm_ssid_upd(wlc, cfg);
7773
7774                 /*
7775                  * Write PLCP headers and durations for probe response frames at all rates.
7776                  * Use the actual frame length covered by the PLCP header for the call to
7777                  * wlc_mod_prb_rsp_rate_table() by subtracting the PLCP len and adding the FCS.
7778                  */
7779                 len += (-D11_PHY_HDR_LEN + FCS_LEN);
7780                 wlc_mod_prb_rsp_rate_table(wlc, (u16) len);
7781
7782                 if (suspend)
7783                         wlc_enable_mac(wlc);
7784         } else {                /* Generating probe resp in sw; update local template */
7785                 ASSERT(0 && "No software probe response support without MBSS");
7786         }
7787 }
7788
7789 /* prepares pdu for transmission. returns BCM error codes */
7790 int wlc_prep_pdu(struct wlc_info *wlc, struct sk_buff *pdu, uint *fifop)
7791 {
7792         uint fifo;
7793         d11txh_t *txh;
7794         struct ieee80211_hdr *h;
7795         struct scb *scb;
7796
7797         ASSERT(pdu);
7798         txh = (d11txh_t *) (pdu->data);
7799         ASSERT(txh);
7800         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
7801         ASSERT(h);
7802
7803         /* get the pkt queue info. This was put at wlc_sendctl or wlc_send for PDU */
7804         fifo = le16_to_cpu(txh->TxFrameID) & TXFID_QUEUE_MASK;
7805
7806         scb = NULL;
7807
7808         *fifop = fifo;
7809
7810         /* return if insufficient dma resources */
7811         if (TXAVAIL(wlc, fifo) < MAX_DMA_SEGS) {
7812                 /* Mark precedences related to this FIFO, unsendable */
7813                 WLC_TX_FIFO_CLEAR(wlc, fifo);
7814                 return -BCME_BUSY;
7815         }
7816
7817         if (!ieee80211_is_data(txh->MacFrameControl))
7818                 wlc->pub->_cnt->txctl++;
7819
7820         return 0;
7821 }
7822
7823 /* init tx reported rate mechanism */
7824 void wlc_reprate_init(struct wlc_info *wlc)
7825 {
7826         int i;
7827         struct wlc_bsscfg *bsscfg;
7828
7829         FOREACH_BSS(wlc, i, bsscfg) {
7830                 wlc_bsscfg_reprate_init(bsscfg);
7831         }
7832 }
7833
7834 /* per bsscfg init tx reported rate mechanism */
7835 void wlc_bsscfg_reprate_init(struct wlc_bsscfg *bsscfg)
7836 {
7837         bsscfg->txrspecidx = 0;
7838         memset((char *)bsscfg->txrspec, 0, sizeof(bsscfg->txrspec));
7839 }
7840
7841 /* Retrieve a consolidated set of revision information,
7842  * typically for the WLC_GET_REVINFO ioctl
7843  */
7844 int wlc_get_revision_info(struct wlc_info *wlc, void *buf, uint len)
7845 {
7846         wlc_rev_info_t *rinfo = (wlc_rev_info_t *) buf;
7847
7848         if (len < WL_REV_INFO_LEGACY_LENGTH)
7849                 return -BCME_BUFTOOSHORT;
7850
7851         rinfo->vendorid = wlc->vendorid;
7852         rinfo->deviceid = wlc->deviceid;
7853         rinfo->radiorev = (wlc->band->radiorev << IDCODE_REV_SHIFT) |
7854             (wlc->band->radioid << IDCODE_ID_SHIFT);
7855         rinfo->chiprev = wlc->pub->sih->chiprev;
7856         rinfo->corerev = wlc->pub->corerev;
7857         rinfo->boardid = wlc->pub->sih->boardtype;
7858         rinfo->boardvendor = wlc->pub->sih->boardvendor;
7859         rinfo->boardrev = wlc->pub->boardrev;
7860         rinfo->ucoderev = wlc->ucode_rev;
7861         rinfo->driverrev = EPI_VERSION_NUM;
7862         rinfo->bus = wlc->pub->sih->bustype;
7863         rinfo->chipnum = wlc->pub->sih->chip;
7864
7865         if (len >= (offsetof(wlc_rev_info_t, chippkg))) {
7866                 rinfo->phytype = wlc->band->phytype;
7867                 rinfo->phyrev = wlc->band->phyrev;
7868                 rinfo->anarev = 0;      /* obsolete stuff, suppress */
7869         }
7870
7871         if (len >= sizeof(*rinfo)) {
7872                 rinfo->chippkg = wlc->pub->sih->chippkg;
7873         }
7874
7875         return 0;
7876 }
7877
7878 void wlc_default_rateset(struct wlc_info *wlc, wlc_rateset_t *rs)
7879 {
7880         wlc_rateset_default(rs, NULL, wlc->band->phytype, wlc->band->bandtype,
7881                             false, WLC_RATE_MASK_FULL, (bool) N_ENAB(wlc->pub),
7882                             CHSPEC_WLC_BW(wlc->default_bss->chanspec),
7883                             wlc->stf->txstreams);
7884 }
7885
7886 static void wlc_bss_default_init(struct wlc_info *wlc)
7887 {
7888         chanspec_t chanspec;
7889         struct wlcband *band;
7890         wlc_bss_info_t *bi = wlc->default_bss;
7891
7892         /* init default and target BSS with some sane initial values */
7893         memset((char *)(bi), 0, sizeof(wlc_bss_info_t));
7894         bi->beacon_period = ISSIM_ENAB(wlc->pub->sih) ? BEACON_INTERVAL_DEF_QT :
7895             BEACON_INTERVAL_DEFAULT;
7896         bi->dtim_period = ISSIM_ENAB(wlc->pub->sih) ? DTIM_INTERVAL_DEF_QT :
7897             DTIM_INTERVAL_DEFAULT;
7898
7899         /* fill the default channel as the first valid channel
7900          * starting from the 2G channels
7901          */
7902         chanspec = CH20MHZ_CHSPEC(1);
7903         ASSERT(chanspec != INVCHANSPEC);
7904
7905         wlc->home_chanspec = bi->chanspec = chanspec;
7906
7907         /* find the band of our default channel */
7908         band = wlc->band;
7909         if (NBANDS(wlc) > 1 && band->bandunit != CHSPEC_WLCBANDUNIT(chanspec))
7910                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
7911
7912         /* init bss rates to the band specific default rate set */
7913         wlc_rateset_default(&bi->rateset, NULL, band->phytype, band->bandtype,
7914                             false, WLC_RATE_MASK_FULL, (bool) N_ENAB(wlc->pub),
7915                             CHSPEC_WLC_BW(chanspec), wlc->stf->txstreams);
7916
7917         if (N_ENAB(wlc->pub))
7918                 bi->flags |= WLC_BSS_HT;
7919 }
7920
7921 void
7922 wlc_uint64_sub(u32 *a_high, u32 *a_low, u32 b_high, u32 b_low)
7923 {
7924         if (b_low > *a_low) {
7925                 /* low half needs a carry */
7926                 b_high += 1;
7927         }
7928         *a_low -= b_low;
7929         *a_high -= b_high;
7930 }
7931
7932 static ratespec_t
7933 mac80211_wlc_set_nrate(struct wlc_info *wlc, struct wlcband *cur_band,
7934                        u32 int_val)
7935 {
7936         u8 stf = (int_val & NRATE_STF_MASK) >> NRATE_STF_SHIFT;
7937         u8 rate = int_val & NRATE_RATE_MASK;
7938         ratespec_t rspec;
7939         bool ismcs = ((int_val & NRATE_MCS_INUSE) == NRATE_MCS_INUSE);
7940         bool issgi = ((int_val & NRATE_SGI_MASK) >> NRATE_SGI_SHIFT);
7941         bool override_mcs_only = ((int_val & NRATE_OVERRIDE_MCS_ONLY)
7942                                   == NRATE_OVERRIDE_MCS_ONLY);
7943         int bcmerror = 0;
7944
7945         if (!ismcs) {
7946                 return (ratespec_t) rate;
7947         }
7948
7949         /* validate the combination of rate/mcs/stf is allowed */
7950         if (N_ENAB(wlc->pub) && ismcs) {
7951                 /* mcs only allowed when nmode */
7952                 if (stf > PHY_TXC1_MODE_SDM) {
7953                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid stf\n",
7954                                  WLCWLUNIT(wlc), __func__);
7955                         bcmerror = -BCME_RANGE;
7956                         goto done;
7957                 }
7958
7959                 /* mcs 32 is a special case, DUP mode 40 only */
7960                 if (rate == 32) {
7961                         if (!CHSPEC_IS40(wlc->home_chanspec) ||
7962                             ((stf != PHY_TXC1_MODE_SISO)
7963                              && (stf != PHY_TXC1_MODE_CDD))) {
7964                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid mcs "
7965                                           "32\n", WLCWLUNIT(wlc), __func__);
7966                                 bcmerror = -BCME_RANGE;
7967                                 goto done;
7968                         }
7969                         /* mcs > 7 must use stf SDM */
7970                 } else if (rate > HIGHEST_SINGLE_STREAM_MCS) {
7971                         /* mcs > 7 must use stf SDM */
7972                         if (stf != PHY_TXC1_MODE_SDM) {
7973                                 WL_TRACE("wl%d: %s: enabling SDM mode for mcs %d\n",
7974                                          WLCWLUNIT(wlc), __func__, rate);
7975                                 stf = PHY_TXC1_MODE_SDM;
7976                         }
7977                 } else {
7978                         /* MCS 0-7 may use SISO, CDD, and for phy_rev >= 3 STBC */
7979                         if ((stf > PHY_TXC1_MODE_STBC) ||
7980                             (!WLC_STBC_CAP_PHY(wlc)
7981                              && (stf == PHY_TXC1_MODE_STBC))) {
7982                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid STBC"
7983                                           "\n", WLCWLUNIT(wlc), __func__);
7984                                 bcmerror = -BCME_RANGE;
7985                                 goto done;
7986                         }
7987                 }
7988         } else if (IS_OFDM(rate)) {
7989                 if ((stf != PHY_TXC1_MODE_CDD) && (stf != PHY_TXC1_MODE_SISO)) {
7990                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid OFDM\n",
7991                                   WLCWLUNIT(wlc), __func__);
7992                         bcmerror = -BCME_RANGE;
7993                         goto done;
7994                 }
7995         } else if (IS_CCK(rate)) {
7996                 if ((cur_band->bandtype != WLC_BAND_2G)
7997                     || (stf != PHY_TXC1_MODE_SISO)) {
7998                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid CCK\n",
7999                                   WLCWLUNIT(wlc), __func__);
8000                         bcmerror = -BCME_RANGE;
8001                         goto done;
8002                 }
8003         } else {
8004                 wiphy_err(wlc->wiphy, "wl%d: %s: Unknown rate type\n",
8005                           WLCWLUNIT(wlc), __func__);
8006                 bcmerror = -BCME_RANGE;
8007                 goto done;
8008         }
8009         /* make sure multiple antennae are available for non-siso rates */
8010         if ((stf != PHY_TXC1_MODE_SISO) && (wlc->stf->txstreams == 1)) {
8011                 wiphy_err(wlc->wiphy, "wl%d: %s: SISO antenna but !SISO "
8012                           "request\n", WLCWLUNIT(wlc), __func__);
8013                 bcmerror = -BCME_RANGE;
8014                 goto done;
8015         }
8016
8017         rspec = rate;
8018         if (ismcs) {
8019                 rspec |= RSPEC_MIMORATE;
8020                 /* For STBC populate the STC field of the ratespec */
8021                 if (stf == PHY_TXC1_MODE_STBC) {
8022                         u8 stc;
8023                         stc = 1;        /* Nss for single stream is always 1 */
8024                         rspec |= (stc << RSPEC_STC_SHIFT);
8025                 }
8026         }
8027
8028         rspec |= (stf << RSPEC_STF_SHIFT);
8029
8030         if (override_mcs_only)
8031                 rspec |= RSPEC_OVERRIDE_MCS_ONLY;
8032
8033         if (issgi)
8034                 rspec |= RSPEC_SHORT_GI;
8035
8036         if ((rate != 0)
8037             && !wlc_valid_rate(wlc, rspec, cur_band->bandtype, true)) {
8038                 return rate;
8039         }
8040
8041         return rspec;
8042 done:
8043         return rate;
8044 }
8045
8046 /* formula:  IDLE_BUSY_RATIO_X_16 = (100-duty_cycle)/duty_cycle*16 */
8047 static int
8048 wlc_duty_cycle_set(struct wlc_info *wlc, int duty_cycle, bool isOFDM,
8049                    bool writeToShm)
8050 {
8051         int idle_busy_ratio_x_16 = 0;
8052         uint offset =
8053             isOFDM ? M_TX_IDLE_BUSY_RATIO_X_16_OFDM :
8054             M_TX_IDLE_BUSY_RATIO_X_16_CCK;
8055         if (duty_cycle > 100 || duty_cycle < 0) {
8056                 wiphy_err(wlc->wiphy, "wl%d:  duty cycle value off limit\n",
8057                           wlc->pub->unit);
8058                 return -BCME_RANGE;
8059         }
8060         if (duty_cycle)
8061                 idle_busy_ratio_x_16 = (100 - duty_cycle) * 16 / duty_cycle;
8062         /* Only write to shared memory  when wl is up */
8063         if (writeToShm)
8064                 wlc_write_shm(wlc, offset, (u16) idle_busy_ratio_x_16);
8065
8066         if (isOFDM)
8067                 wlc->tx_duty_cycle_ofdm = (u16) duty_cycle;
8068         else
8069                 wlc->tx_duty_cycle_cck = (u16) duty_cycle;
8070
8071         return 0;
8072 }
8073
8074 /* Read a single u16 from shared memory.
8075  * SHM 'offset' needs to be an even address
8076  */
8077 u16 wlc_read_shm(struct wlc_info *wlc, uint offset)
8078 {
8079         return wlc_bmac_read_shm(wlc->hw, offset);
8080 }
8081
8082 /* Write a single u16 to shared memory.
8083  * SHM 'offset' needs to be an even address
8084  */
8085 void wlc_write_shm(struct wlc_info *wlc, uint offset, u16 v)
8086 {
8087         wlc_bmac_write_shm(wlc->hw, offset, v);
8088 }
8089
8090 /* Set a range of shared memory to a value.
8091  * SHM 'offset' needs to be an even address and
8092  * Range length 'len' must be an even number of bytes
8093  */
8094 void wlc_set_shm(struct wlc_info *wlc, uint offset, u16 v, int len)
8095 {
8096         /* offset and len need to be even */
8097         ASSERT((offset & 1) == 0);
8098         ASSERT((len & 1) == 0);
8099
8100         if (len <= 0)
8101                 return;
8102
8103         wlc_bmac_set_shm(wlc->hw, offset, v, len);
8104 }
8105
8106 /* Copy a buffer to shared memory.
8107  * SHM 'offset' needs to be an even address and
8108  * Buffer length 'len' must be an even number of bytes
8109  */
8110 void wlc_copyto_shm(struct wlc_info *wlc, uint offset, const void *buf, int len)
8111 {
8112         /* offset and len need to be even */
8113         ASSERT((offset & 1) == 0);
8114         ASSERT((len & 1) == 0);
8115
8116         if (len <= 0)
8117                 return;
8118         wlc_bmac_copyto_objmem(wlc->hw, offset, buf, len, OBJADDR_SHM_SEL);
8119
8120 }
8121
8122 /* Copy from shared memory to a buffer.
8123  * SHM 'offset' needs to be an even address and
8124  * Buffer length 'len' must be an even number of bytes
8125  */
8126 void wlc_copyfrom_shm(struct wlc_info *wlc, uint offset, void *buf, int len)
8127 {
8128         /* offset and len need to be even */
8129         ASSERT((offset & 1) == 0);
8130         ASSERT((len & 1) == 0);
8131
8132         if (len <= 0)
8133                 return;
8134
8135         wlc_bmac_copyfrom_objmem(wlc->hw, offset, buf, len, OBJADDR_SHM_SEL);
8136 }
8137
8138 /* wrapper BMAC functions to for HIGH driver access */
8139 void wlc_mctrl(struct wlc_info *wlc, u32 mask, u32 val)
8140 {
8141         wlc_bmac_mctrl(wlc->hw, mask, val);
8142 }
8143
8144 void wlc_corereset(struct wlc_info *wlc, u32 flags)
8145 {
8146         wlc_bmac_corereset(wlc->hw, flags);
8147 }
8148
8149 void wlc_mhf(struct wlc_info *wlc, u8 idx, u16 mask, u16 val, int bands)
8150 {
8151         wlc_bmac_mhf(wlc->hw, idx, mask, val, bands);
8152 }
8153
8154 u16 wlc_mhf_get(struct wlc_info *wlc, u8 idx, int bands)
8155 {
8156         return wlc_bmac_mhf_get(wlc->hw, idx, bands);
8157 }
8158
8159 int wlc_xmtfifo_sz_get(struct wlc_info *wlc, uint fifo, uint *blocks)
8160 {
8161         return wlc_bmac_xmtfifo_sz_get(wlc->hw, fifo, blocks);
8162 }
8163
8164 void wlc_write_template_ram(struct wlc_info *wlc, int offset, int len,
8165                             void *buf)
8166 {
8167         wlc_bmac_write_template_ram(wlc->hw, offset, len, buf);
8168 }
8169
8170 void wlc_write_hw_bcntemplates(struct wlc_info *wlc, void *bcn, int len,
8171                                bool both)
8172 {
8173         wlc_bmac_write_hw_bcntemplates(wlc->hw, bcn, len, both);
8174 }
8175
8176 void
8177 wlc_set_addrmatch(struct wlc_info *wlc, int match_reg_offset,
8178                   const u8 *addr)
8179 {
8180         wlc_bmac_set_addrmatch(wlc->hw, match_reg_offset, addr);
8181         if (match_reg_offset == RCM_BSSID_OFFSET)
8182                 memcpy(wlc->cfg->BSSID, addr, ETH_ALEN);
8183 }
8184
8185 void wlc_set_rcmta(struct wlc_info *wlc, int idx, const u8 *addr)
8186 {
8187         wlc_bmac_set_rcmta(wlc->hw, idx, addr);
8188 }
8189
8190 void wlc_read_tsf(struct wlc_info *wlc, u32 *tsf_l_ptr, u32 *tsf_h_ptr)
8191 {
8192         wlc_bmac_read_tsf(wlc->hw, tsf_l_ptr, tsf_h_ptr);
8193 }
8194
8195 void wlc_set_cwmin(struct wlc_info *wlc, u16 newmin)
8196 {
8197         wlc->band->CWmin = newmin;
8198         wlc_bmac_set_cwmin(wlc->hw, newmin);
8199 }
8200
8201 void wlc_set_cwmax(struct wlc_info *wlc, u16 newmax)
8202 {
8203         wlc->band->CWmax = newmax;
8204         wlc_bmac_set_cwmax(wlc->hw, newmax);
8205 }
8206
8207 void wlc_fifoerrors(struct wlc_info *wlc)
8208 {
8209
8210         wlc_bmac_fifoerrors(wlc->hw);
8211 }
8212
8213 /* Search mem rw utilities */
8214
8215 void wlc_pllreq(struct wlc_info *wlc, bool set, mbool req_bit)
8216 {
8217         wlc_bmac_pllreq(wlc->hw, set, req_bit);
8218 }
8219
8220 void wlc_reset_bmac_done(struct wlc_info *wlc)
8221 {
8222 }
8223
8224 void wlc_ht_mimops_cap_update(struct wlc_info *wlc, u8 mimops_mode)
8225 {
8226         wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_SM_PS;
8227         wlc->ht_cap.cap_info |= (mimops_mode << IEEE80211_HT_CAP_SM_PS_SHIFT);
8228
8229         if (AP_ENAB(wlc->pub) && wlc->clk) {
8230                 wlc_update_beacon(wlc);
8231                 wlc_update_probe_resp(wlc, true);
8232         }
8233 }
8234
8235 /* check for the particular priority flow control bit being set */
8236 bool
8237 wlc_txflowcontrol_prio_isset(struct wlc_info *wlc, struct wlc_txq_info *q,
8238                              int prio)
8239 {
8240         uint prio_mask;
8241
8242         if (prio == ALLPRIO) {
8243                 prio_mask = TXQ_STOP_FOR_PRIOFC_MASK;
8244         } else {
8245                 ASSERT(prio >= 0 && prio <= MAXPRIO);
8246                 prio_mask = NBITVAL(prio);
8247         }
8248
8249         return (q->stopped & prio_mask) == prio_mask;
8250 }
8251
8252 /* propagate the flow control to all interfaces using the given tx queue */
8253 void wlc_txflowcontrol(struct wlc_info *wlc, struct wlc_txq_info *qi,
8254                        bool on, int prio)
8255 {
8256         uint prio_bits;
8257         uint cur_bits;
8258
8259         WL_TRACE("%s: flow control kicks in\n", __func__);
8260
8261         if (prio == ALLPRIO) {
8262                 prio_bits = TXQ_STOP_FOR_PRIOFC_MASK;
8263         } else {
8264                 ASSERT(prio >= 0 && prio <= MAXPRIO);
8265                 prio_bits = NBITVAL(prio);
8266         }
8267
8268         cur_bits = qi->stopped & prio_bits;
8269
8270         /* Check for the case of no change and return early
8271          * Otherwise update the bit and continue
8272          */
8273         if (on) {
8274                 if (cur_bits == prio_bits) {
8275                         return;
8276                 }
8277                 mboolset(qi->stopped, prio_bits);
8278         } else {
8279                 if (cur_bits == 0) {
8280                         return;
8281                 }
8282                 mboolclr(qi->stopped, prio_bits);
8283         }
8284
8285         /* If there is a flow control override we will not change the external
8286          * flow control state.
8287          */
8288         if (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK) {
8289                 return;
8290         }
8291
8292         wlc_txflowcontrol_signal(wlc, qi, on, prio);
8293 }
8294
8295 void
8296 wlc_txflowcontrol_override(struct wlc_info *wlc, struct wlc_txq_info *qi,
8297                            bool on, uint override)
8298 {
8299         uint prev_override;
8300
8301         ASSERT(override != 0);
8302         ASSERT((override & TXQ_STOP_FOR_PRIOFC_MASK) == 0);
8303
8304         prev_override = (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK);
8305
8306         /* Update the flow control bits and do an early return if there is
8307          * no change in the external flow control state.
8308          */
8309         if (on) {
8310                 mboolset(qi->stopped, override);
8311                 /* if there was a previous override bit on, then setting this
8312                  * makes no difference.
8313                  */
8314                 if (prev_override) {
8315                         return;
8316                 }
8317
8318                 wlc_txflowcontrol_signal(wlc, qi, ON, ALLPRIO);
8319         } else {
8320                 mboolclr(qi->stopped, override);
8321                 /* clearing an override bit will only make a difference for
8322                  * flow control if it was the only bit set. For any other
8323                  * override setting, just return
8324                  */
8325                 if (prev_override != override) {
8326                         return;
8327                 }
8328
8329                 if (qi->stopped == 0) {
8330                         wlc_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
8331                 } else {
8332                         int prio;
8333
8334                         for (prio = MAXPRIO; prio >= 0; prio--) {
8335                                 if (!mboolisset(qi->stopped, NBITVAL(prio)))
8336                                         wlc_txflowcontrol_signal(wlc, qi, OFF,
8337                                                                  prio);
8338                         }
8339                 }
8340         }
8341 }
8342
8343 static void wlc_txflowcontrol_reset(struct wlc_info *wlc)
8344 {
8345         struct wlc_txq_info *qi;
8346
8347         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
8348                 if (qi->stopped) {
8349                         wlc_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
8350                         qi->stopped = 0;
8351                 }
8352         }
8353 }
8354
8355 static void
8356 wlc_txflowcontrol_signal(struct wlc_info *wlc, struct wlc_txq_info *qi, bool on,
8357                          int prio)
8358 {
8359         struct wlc_if *wlcif;
8360
8361         for (wlcif = wlc->wlcif_list; wlcif != NULL; wlcif = wlcif->next) {
8362                 if (wlcif->qi == qi && wlcif->flags & WLC_IF_LINKED)
8363                         wl_txflowcontrol(wlc->wl, wlcif->wlif, on, prio);
8364         }
8365 }
8366
8367 static struct wlc_txq_info *wlc_txq_alloc(struct wlc_info *wlc)
8368 {
8369         struct wlc_txq_info *qi, *p;
8370
8371         qi = wlc_calloc(wlc->pub->unit, sizeof(struct wlc_txq_info));
8372         if (qi != NULL) {
8373                 /*
8374                  * Have enough room for control packets along with HI watermark
8375                  * Also, add room to txq for total psq packets if all the SCBs
8376                  * leave PS mode. The watermark for flowcontrol to OS packets
8377                  * will remain the same
8378                  */
8379                 pktq_init(&qi->q, WLC_PREC_COUNT,
8380                           (2 * wlc->pub->tunables->datahiwat) + PKTQ_LEN_DEFAULT
8381                           + wlc->pub->psq_pkts_total);
8382
8383                 /* add this queue to the the global list */
8384                 p = wlc->tx_queues;
8385                 if (p == NULL) {
8386                         wlc->tx_queues = qi;
8387                 } else {
8388                         while (p->next != NULL)
8389                                 p = p->next;
8390                         p->next = qi;
8391                 }
8392         }
8393         return qi;
8394 }
8395
8396 static void wlc_txq_free(struct wlc_info *wlc, struct wlc_txq_info *qi)
8397 {
8398         struct wlc_txq_info *p;
8399
8400         if (qi == NULL)
8401                 return;
8402
8403         /* remove the queue from the linked list */
8404         p = wlc->tx_queues;
8405         if (p == qi)
8406                 wlc->tx_queues = p->next;
8407         else {
8408                 while (p != NULL && p->next != qi)
8409                         p = p->next;
8410                 ASSERT(p->next == qi);
8411                 if (p != NULL)
8412                         p->next = p->next->next;
8413         }
8414
8415         kfree(qi);
8416 }
8417
8418 /*
8419  * Flag 'scan in progress' to withhold dynamic phy calibration
8420  */
8421 void wlc_scan_start(struct wlc_info *wlc)
8422 {
8423         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, true);
8424 }
8425
8426 void wlc_scan_stop(struct wlc_info *wlc)
8427 {
8428         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, false);
8429 }
8430
8431 void wlc_associate_upd(struct wlc_info *wlc, bool state)
8432 {
8433         wlc->pub->associated = state;
8434         wlc->cfg->associated = state;
8435 }
8436
8437 /*
8438  * When a remote STA/AP is removed by Mac80211, or when it can no longer accept
8439  * AMPDU traffic, packets pending in hardware have to be invalidated so that
8440  * when later on hardware releases them, they can be handled appropriately.
8441  */
8442 void wlc_inval_dma_pkts(struct wlc_hw_info *hw,
8443                                struct ieee80211_sta *sta,
8444                                void (*dma_callback_fn))
8445 {
8446         struct hnddma_pub *dmah;
8447         int i;
8448         for (i = 0; i < NFIFO; i++) {
8449                 dmah = hw->di[i];
8450                 if (dmah != NULL)
8451                         dma_walk_packets(dmah, dma_callback_fn, sta);
8452         }
8453 }
8454
8455 int wlc_get_curband(struct wlc_info *wlc)
8456 {
8457         return wlc->band->bandunit;
8458 }