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