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