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