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