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