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