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