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