]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/staging/brcm80211/brcmsmac/main.c
e2ea9b4433930ffa630d234a91de89a4db3f2df8
[mv-sheeva.git] / drivers / staging / brcm80211 / brcmsmac / main.c
1 /*
2  * Copyright (c) 2010 Broadcom Corporation
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
11  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
13  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
14  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 #include <linux/kernel.h>
17 #include <linux/ctype.h>
18 #include <linux/etherdevice.h>
19 #include <linux/pci_ids.h>
20 #include <net/mac80211.h>
21
22 #include <defs.h>
23 #include <brcm_hw_ids.h>
24 #include <brcmu_utils.h>
25 #include <brcmu_wifi.h>
26 #include <aiutils.h>
27 #include "srom.h"
28 #include "dma.h"
29
30 #include "pmu.h"
31 #include "d11.h"
32 #include "types.h"
33 #include "rate.h"
34 #include "scb.h"
35 #include "pub.h"
36 #include "key.h"
37 #include "phy/phy_hal.h"
38 #include "channel.h"
39 #include "main.h"
40 #include "bottom_mac.h"
41 #include "phy_hal.h"
42 #include "antsel.h"
43 #include "stf.h"
44 #include "ampdu.h"
45 #include "alloc.h"
46 #include "mac80211_if.h"
47
48 /*
49  * WPA(2) definitions
50  */
51 #define RSN_CAP_4_REPLAY_CNTRS          2
52 #define RSN_CAP_16_REPLAY_CNTRS         3
53
54 #define WPA_CAP_4_REPLAY_CNTRS          RSN_CAP_4_REPLAY_CNTRS
55 #define WPA_CAP_16_REPLAY_CNTRS         RSN_CAP_16_REPLAY_CNTRS
56
57 /*
58  * Indication for txflowcontrol that all priority bits in
59  * TXQ_STOP_FOR_PRIOFC_MASK are to be considered.
60  */
61 #define ALLPRIO         -1
62
63 /*
64  * 32 SSID chars, max of 4 chars for each SSID char "\xFF", plus NULL.
65  */
66 #define SSID_FMT_BUF_LEN        ((4 * IEEE80211_MAX_SSID_LEN) + 1)
67
68 #define TIMER_INTERVAL_WATCHDOG 1000    /* watchdog timer, in unit of ms */
69 #define TIMER_INTERVAL_RADIOCHK 800     /* radio monitor timer, in unit of ms */
70
71 #ifndef WLC_MPC_MAX_DELAYCNT
72 #define WLC_MPC_MAX_DELAYCNT    10      /* Max MPC timeout, in unit of watchdog */
73 #endif
74 #define WLC_MPC_MIN_DELAYCNT    1       /* Min MPC timeout, in unit of watchdog */
75 #define WLC_MPC_THRESHOLD       3       /* MPC count threshold level */
76
77 #define BEACON_INTERVAL_DEFAULT 100     /* beacon interval, in unit of 1024TU */
78 #define DTIM_INTERVAL_DEFAULT   3       /* DTIM interval, in unit of beacon interval */
79
80 /* Scale down delays to accommodate QT slow speed */
81 #define BEACON_INTERVAL_DEF_QT  20      /* beacon interval, in unit of 1024TU */
82 #define DTIM_INTERVAL_DEF_QT    1       /* DTIM interval, in unit of beacon interval */
83
84 #define TBTT_ALIGN_LEEWAY_US    100     /* min leeway before first TBTT in us */
85
86 /* Software feature flag defines used by wlfeatureflag */
87 #define WL_SWFL_NOHWRADIO       0x0004
88 #define WL_SWFL_FLOWCONTROL     0x0008  /* Enable backpressure to OS stack */
89 #define WL_SWFL_WLBSSSORT       0x0010  /* Per-port supports sorting of BSS */
90
91 /* n-mode support capability */
92 /* 2x2 includes both 1x1 & 2x2 devices
93  * reserved #define 2 for future when we want to separate 1x1 & 2x2 and
94  * control it independently
95  */
96 #define WL_11N_2x2                      1
97 #define WL_11N_3x3                      3
98 #define WL_11N_4x4                      4
99
100 /* define 11n feature disable flags */
101 #define WLFEATURE_DISABLE_11N           0x00000001
102 #define WLFEATURE_DISABLE_11N_STBC_TX   0x00000002
103 #define WLFEATURE_DISABLE_11N_STBC_RX   0x00000004
104 #define WLFEATURE_DISABLE_11N_SGI_TX    0x00000008
105 #define WLFEATURE_DISABLE_11N_SGI_RX    0x00000010
106 #define WLFEATURE_DISABLE_11N_AMPDU_TX  0x00000020
107 #define WLFEATURE_DISABLE_11N_AMPDU_RX  0x00000040
108 #define WLFEATURE_DISABLE_11N_GF        0x00000080
109
110 #define EDCF_ACI_MASK                0x60
111 #define EDCF_ACI_SHIFT               5
112 #define EDCF_ECWMIN_MASK             0x0f
113 #define EDCF_ECWMAX_SHIFT            4
114 #define EDCF_AIFSN_MASK              0x0f
115 #define EDCF_AIFSN_MAX               15
116 #define EDCF_ECWMAX_MASK             0xf0
117
118 #define EDCF_AC_BE_TXOP_STA          0x0000
119 #define EDCF_AC_BK_TXOP_STA          0x0000
120 #define EDCF_AC_VO_ACI_STA           0x62
121 #define EDCF_AC_VO_ECW_STA           0x32
122 #define EDCF_AC_VI_ACI_STA           0x42
123 #define EDCF_AC_VI_ECW_STA           0x43
124 #define EDCF_AC_BK_ECW_STA           0xA4
125 #define EDCF_AC_VI_TXOP_STA          0x005e
126 #define EDCF_AC_VO_TXOP_STA          0x002f
127 #define EDCF_AC_BE_ACI_STA           0x03
128 #define EDCF_AC_BE_ECW_STA           0xA4
129 #define EDCF_AC_BK_ACI_STA           0x27
130 #define EDCF_AC_VO_TXOP_AP           0x002f
131
132 #define EDCF_TXOP2USEC(txop)         ((txop) << 5)
133 #define EDCF_ECW2CW(exp)             ((1 << (exp)) - 1)
134
135 #define APHY_SYMBOL_TIME        4
136 #define APHY_PREAMBLE_TIME      16
137 #define APHY_SIGNAL_TIME        4
138 #define APHY_SIFS_TIME          16
139 #define APHY_SERVICE_NBITS      16
140 #define APHY_TAIL_NBITS         6
141 #define BPHY_SIFS_TIME          10
142 #define BPHY_PLCP_SHORT_TIME    96
143
144 #define PREN_PREAMBLE           24
145 #define PREN_MM_EXT             12
146 #define PREN_PREAMBLE_EXT       4
147
148 #define DOT11_MAC_HDR_LEN               24
149 #define DOT11_ACK_LEN           10
150 #define DOT11_BA_LEN            4
151 #define DOT11_OFDM_SIGNAL_EXTENSION     6
152 #define DOT11_MIN_FRAG_LEN              256
153 #define DOT11_RTS_LEN           16
154 #define DOT11_CTS_LEN           10
155 #define DOT11_BA_BITMAP_LEN             128
156 #define DOT11_MIN_BEACON_PERIOD         1
157 #define DOT11_MAX_BEACON_PERIOD         0xFFFF
158 #define DOT11_MAXNUMFRAGS       16
159 #define DOT11_MAX_FRAG_LEN              2346
160
161 #define BPHY_PLCP_TIME          192
162 #define RIFS_11N_TIME           2
163
164 #define WME_VER                 1
165 #define WME_SUBTYPE_PARAM_IE    1
166 #define WME_TYPE                2
167 #define WME_OUI                 "\x00\x50\xf2"
168
169 #define AC_BE                   0
170 #define AC_BK                   1
171 #define AC_VI                   2
172 #define AC_VO                   3
173
174 /*
175  * driver maintains internal 'tick'(wlc->pub->now) which increments in 1s OS timer(soft
176  * watchdog) it is not a wall clock and won't increment when driver is in "down" state
177  * this low resolution driver tick can be used for maintenance tasks such as phy
178  * calibration and scb update
179  */
180
181 /* To inform the ucode of the last mcast frame posted so that it can clear moredata bit */
182 #define BCMCFID(wlc, fid) wlc_bmac_write_shm((wlc)->hw, M_BCMC_FID, (fid))
183
184 #define WLC_WAR16165(wlc) (wlc->pub->sih->bustype == PCI_BUS && \
185                                 (!AP_ENAB(wlc->pub)) && (wlc->war16165))
186
187 /* debug/trace */
188 uint brcm_msg_level =
189 #if defined(BCMDBG)
190         LOG_ERROR_VAL;
191 #else
192         0;
193 #endif                          /* BCMDBG */
194
195 /* Find basic rate for a given rate */
196 #define WLC_BASIC_RATE(wlc, rspec)      (IS_MCS(rspec) ? \
197                         (wlc)->band->basic_rate[mcs_table[rspec & RSPEC_RATE_MASK].leg_ofdm] : \
198                         (wlc)->band->basic_rate[rspec & RSPEC_RATE_MASK])
199
200 #define FRAMETYPE(r, mimoframe) (IS_MCS(r) ? mimoframe  : (IS_CCK(r) ? FT_CCK : FT_OFDM))
201
202 #define RFDISABLE_DEFAULT       10000000        /* rfdisable delay timer 500 ms, runs of ALP clock */
203
204 #define WLC_TEMPSENSE_PERIOD            10      /* 10 second timeout */
205
206 #define SCAN_IN_PROGRESS(x)     0
207
208 #define EPI_VERSION_NUM         0x054b0b00
209
210 #ifdef BCMDBG
211 /* pointer to most recently allocated wl/wlc */
212 static struct wlc_info *wlc_info_dbg = (struct wlc_info *) (NULL);
213 #endif
214
215 const u8 prio2fifo[NUMPRIO] = {
216         TX_AC_BE_FIFO,          /* 0    BE      AC_BE   Best Effort */
217         TX_AC_BK_FIFO,          /* 1    BK      AC_BK   Background */
218         TX_AC_BK_FIFO,          /* 2    --      AC_BK   Background */
219         TX_AC_BE_FIFO,          /* 3    EE      AC_BE   Best Effort */
220         TX_AC_VI_FIFO,          /* 4    CL      AC_VI   Video */
221         TX_AC_VI_FIFO,          /* 5    VI      AC_VI   Video */
222         TX_AC_VO_FIFO,          /* 6    VO      AC_VO   Voice */
223         TX_AC_VO_FIFO           /* 7    NC      AC_VO   Voice */
224 };
225
226 /* precedences numbers for wlc queues. These are twice as may levels as
227  * 802.1D priorities.
228  * Odd numbers are used for HI priority traffic at same precedence levels
229  * These constants are used ONLY by wlc_prio2prec_map.  Do not use them elsewhere.
230  */
231 #define _WLC_PREC_NONE          0       /* None = - */
232 #define _WLC_PREC_BK            2       /* BK - Background */
233 #define _WLC_PREC_BE            4       /* BE - Best-effort */
234 #define _WLC_PREC_EE            6       /* EE - Excellent-effort */
235 #define _WLC_PREC_CL            8       /* CL - Controlled Load */
236 #define _WLC_PREC_VI            10      /* Vi - Video */
237 #define _WLC_PREC_VO            12      /* Vo - Voice */
238 #define _WLC_PREC_NC            14      /* NC - Network Control */
239
240 #define MAXMACLIST              64      /* max # source MAC matches */
241 #define BCN_TEMPLATE_COUNT      2
242
243 #define WLC_BSSCFG_HW_BCN       0x20    /* The BSS is generating beacons in HW */
244
245 #define HWBCN_ENAB(cfg)         (((cfg)->flags & WLC_BSSCFG_HW_BCN) != 0)
246 #define HWPRB_ENAB(cfg)         (((cfg)->flags & WLC_BSSCFG_HW_PRB) != 0)
247
248 #define MBSS_BCN_ENAB(cfg)       0
249 #define MBSS_PRB_ENAB(cfg)       0
250 #define SOFTBCN_ENAB(pub)    (0)
251
252 /* 802.1D Priority to precedence queue mapping */
253 const u8 wlc_prio2prec_map[] = {
254         _WLC_PREC_BE,           /* 0 BE - Best-effort */
255         _WLC_PREC_BK,           /* 1 BK - Background */
256         _WLC_PREC_NONE,         /* 2 None = - */
257         _WLC_PREC_EE,           /* 3 EE - Excellent-effort */
258         _WLC_PREC_CL,           /* 4 CL - Controlled Load */
259         _WLC_PREC_VI,           /* 5 Vi - Video */
260         _WLC_PREC_VO,           /* 6 Vo - Voice */
261         _WLC_PREC_NC,           /* 7 NC - Network Control */
262 };
263
264 /* Check if a particular BSS config is AP or STA */
265 #define BSSCFG_AP(cfg)          (0)
266 #define BSSCFG_STA(cfg)         (1)
267 #define BSSCFG_IBSS(cfg)        (!(cfg)->BSS)
268
269 /* Iterator for "associated" STA bss configs:
270    (struct wlc_info *wlc, int idx, struct wlc_bsscfg *cfg) */
271 #define FOREACH_AS_STA(wlc, idx, cfg) \
272         for (idx = 0; (int) idx < WLC_MAXBSSCFG; idx++) \
273                 if ((cfg = (wlc)->bsscfg[idx]) && BSSCFG_STA(cfg) && cfg->associated)
274
275 /* As above for all non-NULL BSS configs */
276 #define FOREACH_BSS(wlc, idx, cfg) \
277         for (idx = 0; (int) idx < WLC_MAXBSSCFG; idx++) \
278                 if ((cfg = (wlc)->bsscfg[idx]))
279
280 /* Sanity check for tx_prec_map and fifo synchup
281  * Either there are some packets pending for the fifo, else if fifo is empty then
282  * all the corresponding precmap bits should be set
283  */
284 #define WLC_TX_FIFO_CHECK(wlc, fifo) (TXPKTPENDGET((wlc), (fifo)) ||    \
285         (TXPKTPENDGET((wlc), (fifo)) == 0 && \
286         ((wlc)->tx_prec_map & (wlc)->fifo2prec_map[(fifo)]) == \
287         (wlc)->fifo2prec_map[(fifo)]))
288
289 /* TX FIFO number to WME/802.1E Access Category */
290 const u8 wme_fifo2ac[] = { AC_BK, AC_BE, AC_VI, AC_VO, AC_BE, AC_BE };
291
292 /* WME/802.1E Access Category to TX FIFO number */
293 static const u8 wme_ac2fifo[] = { 1, 0, 2, 3 };
294
295 static bool in_send_q = false;
296
297 /* Shared memory location index for various AC params */
298 #define wme_shmemacindex(ac)    wme_ac2fifo[ac]
299
300 #ifdef BCMDBG
301 static const char *fifo_names[] = {
302         "AC_BK", "AC_BE", "AC_VI", "AC_VO", "BCMC", "ATIM" };
303 #else
304 static const char fifo_names[6][0];
305 #endif
306
307 static const u8 acbitmap2maxprio[] = {
308         PRIO_8021D_BE, PRIO_8021D_BE, PRIO_8021D_BK, PRIO_8021D_BK,
309         PRIO_8021D_VI, PRIO_8021D_VI, PRIO_8021D_VI, PRIO_8021D_VI,
310         PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO,
311         PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO, PRIO_8021D_VO
312 };
313
314 /* currently the best mechanism for determining SIFS is the band in use */
315 #define SIFS(band) ((band)->bandtype == WLC_BAND_5G ? APHY_SIFS_TIME : BPHY_SIFS_TIME);
316
317 /* value for # replay counters currently supported */
318 #define WLC_REPLAY_CNTRS_VALUE  WPA_CAP_16_REPLAY_CNTRS
319
320 /* local prototypes */
321 static u16 wlc_d11hdrs_mac80211(struct wlc_info *wlc,
322                                                struct ieee80211_hw *hw,
323                                                struct sk_buff *p,
324                                                struct scb *scb, uint frag,
325                                                uint nfrags, uint queue,
326                                                uint next_frag_len,
327                                                wsec_key_t *key,
328                                                ratespec_t rspec_override);
329 static void wlc_bss_default_init(struct wlc_info *wlc);
330 static void wlc_ucode_mac_upd(struct wlc_info *wlc);
331 static ratespec_t mac80211_wlc_set_nrate(struct wlc_info *wlc,
332                                          struct wlcband *cur_band, u32 int_val);
333 static void wlc_tx_prec_map_init(struct wlc_info *wlc);
334 static void wlc_watchdog(void *arg);
335 static void wlc_watchdog_by_timer(void *arg);
336 static u16 wlc_rate_shm_offset(struct wlc_info *wlc, u8 rate);
337 static int wlc_set_rateset(struct wlc_info *wlc, wlc_rateset_t *rs_arg);
338 static u8 wlc_local_constraint_qdbm(struct wlc_info *wlc);
339
340 /* send and receive */
341 static struct wlc_txq_info *wlc_txq_alloc(struct wlc_info *wlc);
342 static void wlc_txq_free(struct wlc_info *wlc,
343                          struct wlc_txq_info *qi);
344 static void wlc_txflowcontrol_signal(struct wlc_info *wlc,
345                                      struct wlc_txq_info *qi,
346                                      bool on, int prio);
347 static void wlc_txflowcontrol_reset(struct wlc_info *wlc);
348 static void wlc_compute_cck_plcp(struct wlc_info *wlc, ratespec_t rate,
349                                  uint length, u8 *plcp);
350 static void wlc_compute_ofdm_plcp(ratespec_t rate, uint length, u8 *plcp);
351 static void wlc_compute_mimo_plcp(ratespec_t rate, uint length, u8 *plcp);
352 static u16 wlc_compute_frame_dur(struct wlc_info *wlc, ratespec_t rate,
353                                     u8 preamble_type, uint next_frag_len);
354 static u64 wlc_recover_tsf64(struct wlc_info *wlc, struct wlc_d11rxhdr *rxh);
355 static void wlc_recvctl(struct wlc_info *wlc,
356                         d11rxhdr_t *rxh, struct sk_buff *p);
357 static uint wlc_calc_frame_len(struct wlc_info *wlc, ratespec_t rate,
358                                u8 preamble_type, uint dur);
359 static uint wlc_calc_ack_time(struct wlc_info *wlc, ratespec_t rate,
360                               u8 preamble_type);
361 static uint wlc_calc_cts_time(struct wlc_info *wlc, ratespec_t rate,
362                               u8 preamble_type);
363 /* interrupt, up/down, band */
364 static void wlc_setband(struct wlc_info *wlc, uint bandunit);
365 static chanspec_t wlc_init_chanspec(struct wlc_info *wlc);
366 static void wlc_bandinit_ordered(struct wlc_info *wlc, chanspec_t chanspec);
367 static void wlc_bsinit(struct wlc_info *wlc);
368 static int wlc_duty_cycle_set(struct wlc_info *wlc, int duty_cycle, bool isOFDM,
369                               bool writeToShm);
370 static void wlc_radio_hwdisable_upd(struct wlc_info *wlc);
371 static bool wlc_radio_monitor_start(struct wlc_info *wlc);
372 static void wlc_radio_timer(void *arg);
373 static void wlc_radio_enable(struct wlc_info *wlc);
374 static void wlc_radio_upd(struct wlc_info *wlc);
375
376 /* scan, association, BSS */
377 static uint wlc_calc_ba_time(struct wlc_info *wlc, ratespec_t rate,
378                              u8 preamble_type);
379 static void wlc_update_mimo_band_bwcap(struct wlc_info *wlc, u8 bwcap);
380 static void wlc_ht_update_sgi_rx(struct wlc_info *wlc, int val);
381 static void wlc_ht_update_ldpc(struct wlc_info *wlc, s8 val);
382 static void wlc_war16165(struct wlc_info *wlc, bool tx);
383
384 static void wlc_wme_retries_write(struct wlc_info *wlc);
385 static bool wlc_attach_stf_ant_init(struct wlc_info *wlc);
386 static uint wlc_attach_module(struct wlc_info *wlc);
387 static void wlc_detach_module(struct wlc_info *wlc);
388 static void wlc_timers_deinit(struct wlc_info *wlc);
389 static void wlc_down_led_upd(struct wlc_info *wlc);
390 static uint wlc_down_del_timer(struct wlc_info *wlc);
391 static void wlc_ofdm_rateset_war(struct wlc_info *wlc);
392 static int _wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
393                       struct wlc_if *wlcif);
394
395 /* conditions under which the PM bit should be set in outgoing frames and STAY_AWAKE is meaningful
396  */
397 bool wlc_ps_allowed(struct wlc_info *wlc)
398 {
399         int idx;
400         struct wlc_bsscfg *cfg;
401
402         /* disallow PS when one of the following global conditions meets */
403         if (!wlc->pub->associated)
404                 return false;
405
406         /* disallow PS when one of these meets when not scanning */
407         if (AP_ACTIVE(wlc) || wlc->monitor)
408                 return false;
409
410         FOREACH_AS_STA(wlc, idx, cfg) {
411                 /* disallow PS when one of the following bsscfg specific conditions meets */
412                 if (!cfg->BSS || !WLC_PORTOPEN(cfg))
413                         return false;
414
415                 if (!cfg->dtim_programmed)
416                         return false;
417         }
418
419         return true;
420 }
421
422 void wlc_reset(struct wlc_info *wlc)
423 {
424         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
425
426         /* slurp up hw mac counters before core reset */
427         wlc_statsupd(wlc);
428
429         /* reset our snapshot of macstat counters */
430         memset((char *)wlc->core->macstat_snapshot, 0,
431                 sizeof(macstat_t));
432
433         wlc_bmac_reset(wlc->hw);
434 }
435
436 void wlc_fatal_error(struct wlc_info *wlc)
437 {
438         wiphy_err(wlc->wiphy, "wl%d: fatal error, reinitializing\n",
439                   wlc->pub->unit);
440         brcms_init(wlc->wl);
441 }
442
443 /* Return the channel the driver should initialize during wlc_init.
444  * the channel may have to be changed from the currently configured channel
445  * if other configurations are in conflict (bandlocked, 11n mode disabled,
446  * invalid channel for current country, etc.)
447  */
448 static chanspec_t wlc_init_chanspec(struct wlc_info *wlc)
449 {
450         chanspec_t chanspec =
451             1 | WL_CHANSPEC_BW_20 | WL_CHANSPEC_CTL_SB_NONE |
452             WL_CHANSPEC_BAND_2G;
453
454         return chanspec;
455 }
456
457 struct scb global_scb;
458
459 static void wlc_init_scb(struct wlc_info *wlc, struct scb *scb)
460 {
461         int i;
462         scb->flags = SCB_WMECAP | SCB_HTCAP;
463         for (i = 0; i < NUMPRIO; i++)
464                 scb->seqnum[i] = 0;
465 }
466
467 void wlc_init(struct wlc_info *wlc)
468 {
469         d11regs_t *regs;
470         chanspec_t chanspec;
471         int i;
472         struct wlc_bsscfg *bsscfg;
473         bool mute = false;
474
475         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
476
477         regs = wlc->regs;
478
479         /* This will happen if a big-hammer was executed. In that case, we want to go back
480          * to the channel that we were on and not new channel
481          */
482         if (wlc->pub->associated)
483                 chanspec = wlc->home_chanspec;
484         else
485                 chanspec = wlc_init_chanspec(wlc);
486
487         wlc_bmac_init(wlc->hw, chanspec, mute);
488
489         /* update beacon listen interval */
490         wlc_bcn_li_upd(wlc);
491
492         /* the world is new again, so is our reported rate */
493         wlc_reprate_init(wlc);
494
495         /* write ethernet address to core */
496         FOREACH_BSS(wlc, i, bsscfg) {
497                 wlc_set_mac(bsscfg);
498                 wlc_set_bssid(bsscfg);
499         }
500
501         /* Update tsf_cfprep if associated and up */
502         if (wlc->pub->associated) {
503                 FOREACH_BSS(wlc, i, bsscfg) {
504                         if (bsscfg->up) {
505                                 u32 bi;
506
507                                 /* get beacon period and convert to uS */
508                                 bi = bsscfg->current_bss->beacon_period << 10;
509                                 /*
510                                  * update since init path would reset
511                                  * to default value
512                                  */
513                                 W_REG(&regs->tsf_cfprep,
514                                       (bi << CFPREP_CBI_SHIFT));
515
516                                 /* Update maccontrol PM related bits */
517                                 wlc_set_ps_ctrl(wlc);
518
519                                 break;
520                         }
521                 }
522         }
523
524         wlc_key_hw_init_all(wlc);
525
526         wlc_bandinit_ordered(wlc, chanspec);
527
528         wlc_init_scb(wlc, &global_scb);
529
530         /* init probe response timeout */
531         wlc_write_shm(wlc, M_PRS_MAXTIME, wlc->prb_resp_timeout);
532
533         /* init max burst txop (framebursting) */
534         wlc_write_shm(wlc, M_MBURST_TXOP,
535                       (wlc->
536                        _rifs ? (EDCF_AC_VO_TXOP_AP << 5) : MAXFRAMEBURST_TXOP));
537
538         /* initialize maximum allowed duty cycle */
539         wlc_duty_cycle_set(wlc, wlc->tx_duty_cycle_ofdm, true, true);
540         wlc_duty_cycle_set(wlc, wlc->tx_duty_cycle_cck, false, true);
541
542         /* Update some shared memory locations related to max AMPDU size allowed to received */
543         wlc_ampdu_shm_upd(wlc->ampdu);
544
545         /* band-specific inits */
546         wlc_bsinit(wlc);
547
548         /* Enable EDCF mode (while the MAC is suspended) */
549         if (EDCF_ENAB(wlc->pub)) {
550                 OR_REG(&regs->ifs_ctl, IFS_USEEDCF);
551                 wlc_edcf_setparams(wlc, false);
552         }
553
554         /* Init precedence maps for empty FIFOs */
555         wlc_tx_prec_map_init(wlc);
556
557         /* read the ucode version if we have not yet done so */
558         if (wlc->ucode_rev == 0) {
559                 wlc->ucode_rev =
560                     wlc_read_shm(wlc, M_BOM_REV_MAJOR) << NBITS(u16);
561                 wlc->ucode_rev |= wlc_read_shm(wlc, M_BOM_REV_MINOR);
562         }
563
564         /* ..now really unleash hell (allow the MAC out of suspend) */
565         wlc_enable_mac(wlc);
566
567         /* clear tx flow control */
568         wlc_txflowcontrol_reset(wlc);
569
570         /* clear tx data fifo suspends */
571         wlc->tx_suspended = false;
572
573         /* enable the RF Disable Delay timer */
574         W_REG(&wlc->regs->rfdisabledly, RFDISABLE_DEFAULT);
575
576         /* initialize mpc delay */
577         wlc->mpc_delay_off = wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
578
579         /*
580          * Initialize WME parameters; if they haven't been set by some other
581          * mechanism (IOVar, etc) then read them from the hardware.
582          */
583         if (WLC_WME_RETRY_SHORT_GET(wlc, 0) == 0) {     /* Uninitialized; read from HW */
584                 int ac;
585
586                 for (ac = 0; ac < AC_COUNT; ac++) {
587                         wlc->wme_retries[ac] =
588                             wlc_read_shm(wlc, M_AC_TXLMT_ADDR(ac));
589                 }
590         }
591 }
592
593 void wlc_mac_bcn_promisc_change(struct wlc_info *wlc, bool promisc)
594 {
595         wlc->bcnmisc_monitor = promisc;
596         wlc_mac_bcn_promisc(wlc);
597 }
598
599 void wlc_mac_bcn_promisc(struct wlc_info *wlc)
600 {
601         if ((AP_ENAB(wlc->pub) && (N_ENAB(wlc->pub) || wlc->band->gmode)) ||
602             wlc->bcnmisc_ibss || wlc->bcnmisc_scan || wlc->bcnmisc_monitor)
603                 wlc_mctrl(wlc, MCTL_BCNS_PROMISC, MCTL_BCNS_PROMISC);
604         else
605                 wlc_mctrl(wlc, MCTL_BCNS_PROMISC, 0);
606 }
607
608 /* set or clear maccontrol bits MCTL_PROMISC and MCTL_KEEPCONTROL */
609 void wlc_mac_promisc(struct wlc_info *wlc)
610 {
611         u32 promisc_bits = 0;
612
613         /* promiscuous mode just sets MCTL_PROMISC
614          * Note: APs get all BSS traffic without the need to set the MCTL_PROMISC bit
615          * since all BSS data traffic is directed at the AP
616          */
617         if (PROMISC_ENAB(wlc->pub) && !AP_ENAB(wlc->pub))
618                 promisc_bits |= MCTL_PROMISC;
619
620         /* monitor mode needs both MCTL_PROMISC and MCTL_KEEPCONTROL
621          * Note: monitor mode also needs MCTL_BCNS_PROMISC, but that is
622          * handled in wlc_mac_bcn_promisc()
623          */
624         if (MONITOR_ENAB(wlc))
625                 promisc_bits |= MCTL_PROMISC | MCTL_KEEPCONTROL;
626
627         wlc_mctrl(wlc, MCTL_PROMISC | MCTL_KEEPCONTROL, promisc_bits);
628 }
629
630 /* push sw hps and wake state through hardware */
631 void wlc_set_ps_ctrl(struct wlc_info *wlc)
632 {
633         u32 v1, v2;
634         bool hps;
635         bool awake_before;
636
637         hps = PS_ALLOWED(wlc);
638
639         BCMMSG(wlc->wiphy, "wl%d: hps %d\n", wlc->pub->unit, hps);
640
641         v1 = R_REG(&wlc->regs->maccontrol);
642         v2 = MCTL_WAKE;
643         if (hps)
644                 v2 |= MCTL_HPS;
645
646         wlc_mctrl(wlc, MCTL_WAKE | MCTL_HPS, v2);
647
648         awake_before = ((v1 & MCTL_WAKE) || ((v1 & MCTL_HPS) == 0));
649
650         if (!awake_before)
651                 wlc_bmac_wait_for_wake(wlc->hw);
652
653 }
654
655 /*
656  * Write this BSS config's MAC address to core.
657  * Updates RXE match engine.
658  */
659 int wlc_set_mac(struct wlc_bsscfg *cfg)
660 {
661         int err = 0;
662         struct wlc_info *wlc = cfg->wlc;
663
664         if (cfg == wlc->cfg) {
665                 /* enter the MAC addr into the RXE match registers */
666                 wlc_set_addrmatch(wlc, RCM_MAC_OFFSET, cfg->cur_etheraddr);
667         }
668
669         wlc_ampdu_macaddr_upd(wlc);
670
671         return err;
672 }
673
674 /* Write the BSS config's BSSID address to core (set_bssid in d11procs.tcl).
675  * Updates RXE match engine.
676  */
677 void wlc_set_bssid(struct wlc_bsscfg *cfg)
678 {
679         struct wlc_info *wlc = cfg->wlc;
680
681         /* if primary config, we need to update BSSID in RXE match registers */
682         if (cfg == wlc->cfg) {
683                 wlc_set_addrmatch(wlc, RCM_BSSID_OFFSET, cfg->BSSID);
684         }
685 #ifdef SUPPORT_HWKEYS
686         else if (BSSCFG_STA(cfg) && cfg->BSS) {
687                 wlc_rcmta_add_bssid(wlc, cfg);
688         }
689 #endif
690 }
691
692 /*
693  * Suspend the the MAC and update the slot timing
694  * for standard 11b/g (20us slots) or shortslot 11g (9us slots).
695  */
696 void wlc_switch_shortslot(struct wlc_info *wlc, bool shortslot)
697 {
698         int idx;
699         struct wlc_bsscfg *cfg;
700
701         /* use the override if it is set */
702         if (wlc->shortslot_override != WLC_SHORTSLOT_AUTO)
703                 shortslot = (wlc->shortslot_override == WLC_SHORTSLOT_ON);
704
705         if (wlc->shortslot == shortslot)
706                 return;
707
708         wlc->shortslot = shortslot;
709
710         /* update the capability based on current shortslot mode */
711         FOREACH_BSS(wlc, idx, cfg) {
712                 if (!cfg->associated)
713                         continue;
714                 cfg->current_bss->capability &=
715                                         ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
716                 if (wlc->shortslot)
717                         cfg->current_bss->capability |=
718                                         WLAN_CAPABILITY_SHORT_SLOT_TIME;
719         }
720
721         wlc_bmac_set_shortslot(wlc->hw, shortslot);
722 }
723
724 static u8 wlc_local_constraint_qdbm(struct wlc_info *wlc)
725 {
726         u8 local;
727         s16 local_max;
728
729         local = WLC_TXPWR_MAX;
730         if (wlc->pub->associated &&
731             (brcmu_chspec_ctlchan(wlc->chanspec) ==
732              brcmu_chspec_ctlchan(wlc->home_chanspec))) {
733
734                 /* get the local power constraint if we are on the AP's
735                  * channel [802.11h, 7.3.2.13]
736                  */
737                 /* Clamp the value between 0 and WLC_TXPWR_MAX w/o overflowing the target */
738                 local_max =
739                     (wlc->txpwr_local_max -
740                      wlc->txpwr_local_constraint) * WLC_TXPWR_DB_FACTOR;
741                 if (local_max > 0 && local_max < WLC_TXPWR_MAX)
742                         return (u8) local_max;
743                 if (local_max < 0)
744                         return 0;
745         }
746
747         return local;
748 }
749
750 /* propagate home chanspec to all bsscfgs in case bsscfg->current_bss->chanspec is referenced */
751 void wlc_set_home_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
752 {
753         if (wlc->home_chanspec != chanspec) {
754                 int idx;
755                 struct wlc_bsscfg *cfg;
756
757                 wlc->home_chanspec = chanspec;
758
759                 FOREACH_BSS(wlc, idx, cfg) {
760                         if (!cfg->associated)
761                                 continue;
762
763                         cfg->current_bss->chanspec = chanspec;
764                 }
765
766         }
767 }
768
769 static void wlc_set_phy_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
770 {
771         /* Save our copy of the chanspec */
772         wlc->chanspec = chanspec;
773
774         /* Set the chanspec and power limits for this locale after computing
775          * any 11h local tx power constraints.
776          */
777         wlc_channel_set_chanspec(wlc->cmi, chanspec,
778                                  wlc_local_constraint_qdbm(wlc));
779
780         if (wlc->stf->ss_algosel_auto)
781                 wlc_stf_ss_algo_channel_get(wlc, &wlc->stf->ss_algo_channel,
782                                             chanspec);
783
784         wlc_stf_ss_update(wlc, wlc->band);
785
786 }
787
788 void wlc_set_chanspec(struct wlc_info *wlc, chanspec_t chanspec)
789 {
790         uint bandunit;
791         bool switchband = false;
792         chanspec_t old_chanspec = wlc->chanspec;
793
794         if (!wlc_valid_chanspec_db(wlc->cmi, chanspec)) {
795                 wiphy_err(wlc->wiphy, "wl%d: %s: Bad channel %d\n",
796                           wlc->pub->unit, __func__, CHSPEC_CHANNEL(chanspec));
797                 return;
798         }
799
800         /* Switch bands if necessary */
801         if (NBANDS(wlc) > 1) {
802                 bandunit = CHSPEC_WLCBANDUNIT(chanspec);
803                 if (wlc->band->bandunit != bandunit || wlc->bandinit_pending) {
804                         switchband = true;
805                         if (wlc->bandlocked) {
806                                 wiphy_err(wlc->wiphy, "wl%d: %s: chspec %d "
807                                           "band is locked!\n",
808                                           wlc->pub->unit, __func__,
809                                           CHSPEC_CHANNEL(chanspec));
810                                 return;
811                         }
812                         /* BMAC_NOTE: should the setband call come after the wlc_bmac_chanspec() ?
813                          * if the setband updates (wlc_bsinit) use low level calls to inspect and
814                          * set state, the state inspected may be from the wrong band, or the
815                          * following wlc_bmac_set_chanspec() may undo the work.
816                          */
817                         wlc_setband(wlc, bandunit);
818                 }
819         }
820
821         /* sync up phy/radio chanspec */
822         wlc_set_phy_chanspec(wlc, chanspec);
823
824         /* init antenna selection */
825         if (CHSPEC_WLC_BW(old_chanspec) != CHSPEC_WLC_BW(chanspec)) {
826                 wlc_antsel_init(wlc->asi);
827
828                 /* Fix the hardware rateset based on bw.
829                  * Mainly add MCS32 for 40Mhz, remove MCS 32 for 20Mhz
830                  */
831                 wlc_rateset_bw_mcs_filter(&wlc->band->hw_rateset,
832                                           wlc->band->
833                                           mimo_cap_40 ? CHSPEC_WLC_BW(chanspec)
834                                           : 0);
835         }
836
837         /* update some mac configuration since chanspec changed */
838         wlc_ucode_mac_upd(wlc);
839 }
840
841 ratespec_t wlc_lowest_basic_rspec(struct wlc_info *wlc, wlc_rateset_t *rs)
842 {
843         ratespec_t lowest_basic_rspec;
844         uint i;
845
846         /* Use the lowest basic rate */
847         lowest_basic_rspec = rs->rates[0] & WLC_RATE_MASK;
848         for (i = 0; i < rs->count; i++) {
849                 if (rs->rates[i] & WLC_RATE_FLAG) {
850                         lowest_basic_rspec = rs->rates[i] & WLC_RATE_MASK;
851                         break;
852                 }
853         }
854 #if NCONF
855         /* pick siso/cdd as default for OFDM (note no basic rate MCSs are supported yet) */
856         if (IS_OFDM(lowest_basic_rspec)) {
857                 lowest_basic_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
858         }
859 #endif
860
861         return lowest_basic_rspec;
862 }
863
864 /* This function changes the phytxctl for beacon based on current beacon ratespec AND txant
865  * setting as per this table:
866  *  ratespec     CCK            ant = wlc->stf->txant
867  *              OFDM            ant = 3
868  */
869 void wlc_beacon_phytxctl_txant_upd(struct wlc_info *wlc, ratespec_t bcn_rspec)
870 {
871         u16 phyctl;
872         u16 phytxant = wlc->stf->phytxant;
873         u16 mask = PHY_TXC_ANT_MASK;
874
875         /* for non-siso rates or default setting, use the available chains */
876         if (WLC_PHY_11N_CAP(wlc->band)) {
877                 phytxant = wlc_stf_phytxchain_sel(wlc, bcn_rspec);
878         }
879
880         phyctl = wlc_read_shm(wlc, M_BCN_PCTLWD);
881         phyctl = (phyctl & ~mask) | phytxant;
882         wlc_write_shm(wlc, M_BCN_PCTLWD, phyctl);
883 }
884
885 /* centralized protection config change function to simplify debugging, no consistency checking
886  * this should be called only on changes to avoid overhead in periodic function
887 */
888 void wlc_protection_upd(struct wlc_info *wlc, uint idx, int val)
889 {
890         BCMMSG(wlc->wiphy, "idx %d, val %d\n", idx, val);
891
892         switch (idx) {
893         case WLC_PROT_G_SPEC:
894                 wlc->protection->_g = (bool) val;
895                 break;
896         case WLC_PROT_G_OVR:
897                 wlc->protection->g_override = (s8) val;
898                 break;
899         case WLC_PROT_G_USER:
900                 wlc->protection->gmode_user = (u8) val;
901                 break;
902         case WLC_PROT_OVERLAP:
903                 wlc->protection->overlap = (s8) val;
904                 break;
905         case WLC_PROT_N_USER:
906                 wlc->protection->nmode_user = (s8) val;
907                 break;
908         case WLC_PROT_N_CFG:
909                 wlc->protection->n_cfg = (s8) val;
910                 break;
911         case WLC_PROT_N_CFG_OVR:
912                 wlc->protection->n_cfg_override = (s8) val;
913                 break;
914         case WLC_PROT_N_NONGF:
915                 wlc->protection->nongf = (bool) val;
916                 break;
917         case WLC_PROT_N_NONGF_OVR:
918                 wlc->protection->nongf_override = (s8) val;
919                 break;
920         case WLC_PROT_N_PAM_OVR:
921                 wlc->protection->n_pam_override = (s8) val;
922                 break;
923         case WLC_PROT_N_OBSS:
924                 wlc->protection->n_obss = (bool) val;
925                 break;
926
927         default:
928                 break;
929         }
930
931 }
932
933 static void wlc_ht_update_sgi_rx(struct wlc_info *wlc, int val)
934 {
935         wlc->ht_cap.cap_info &= ~(IEEE80211_HT_CAP_SGI_20 |
936                                         IEEE80211_HT_CAP_SGI_40);
937         wlc->ht_cap.cap_info |= (val & WLC_N_SGI_20) ?
938                                         IEEE80211_HT_CAP_SGI_20 : 0;
939         wlc->ht_cap.cap_info |= (val & WLC_N_SGI_40) ?
940                                         IEEE80211_HT_CAP_SGI_40 : 0;
941
942         if (wlc->pub->up) {
943                 wlc_update_beacon(wlc);
944                 wlc_update_probe_resp(wlc, true);
945         }
946 }
947
948 static void wlc_ht_update_ldpc(struct wlc_info *wlc, s8 val)
949 {
950         wlc->stf->ldpc = val;
951
952         wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_LDPC_CODING;
953         if (wlc->stf->ldpc != OFF)
954                 wlc->ht_cap.cap_info |= IEEE80211_HT_CAP_LDPC_CODING;
955
956         if (wlc->pub->up) {
957                 wlc_update_beacon(wlc);
958                 wlc_update_probe_resp(wlc, true);
959                 wlc_phy_ldpc_override_set(wlc->band->pi, (val ? true : false));
960         }
961 }
962
963 /*
964  * ucode, hwmac update
965  *    Channel dependent updates for ucode and hw
966  */
967 static void wlc_ucode_mac_upd(struct wlc_info *wlc)
968 {
969         /* enable or disable any active IBSSs depending on whether or not
970          * we are on the home channel
971          */
972         if (wlc->home_chanspec == WLC_BAND_PI_RADIO_CHANSPEC) {
973                 if (wlc->pub->associated) {
974                         /* BMAC_NOTE: This is something that should be fixed in ucode inits.
975                          * I think that the ucode inits set up the bcn templates and shm values
976                          * with a bogus beacon. This should not be done in the inits. If ucode needs
977                          * to set up a beacon for testing, the test routines should write it down,
978                          * not expect the inits to populate a bogus beacon.
979                          */
980                         if (WLC_PHY_11N_CAP(wlc->band)) {
981                                 wlc_write_shm(wlc, M_BCN_TXTSF_OFFSET,
982                                               wlc->band->bcntsfoff);
983                         }
984                 }
985         } else {
986                 /* disable an active IBSS if we are not on the home channel */
987         }
988
989         /* update the various promisc bits */
990         wlc_mac_bcn_promisc(wlc);
991         wlc_mac_promisc(wlc);
992 }
993
994 static void wlc_bandinit_ordered(struct wlc_info *wlc, chanspec_t chanspec)
995 {
996         wlc_rateset_t default_rateset;
997         uint parkband;
998         uint i, band_order[2];
999
1000         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
1001         /*
1002          * We might have been bandlocked during down and the chip power-cycled (hibernate).
1003          * figure out the right band to park on
1004          */
1005         if (wlc->bandlocked || NBANDS(wlc) == 1) {
1006                 parkband = wlc->band->bandunit; /* updated in wlc_bandlock() */
1007                 band_order[0] = band_order[1] = parkband;
1008         } else {
1009                 /* park on the band of the specified chanspec */
1010                 parkband = CHSPEC_WLCBANDUNIT(chanspec);
1011
1012                 /* order so that parkband initialize last */
1013                 band_order[0] = parkband ^ 1;
1014                 band_order[1] = parkband;
1015         }
1016
1017         /* make each band operational, software state init */
1018         for (i = 0; i < NBANDS(wlc); i++) {
1019                 uint j = band_order[i];
1020
1021                 wlc->band = wlc->bandstate[j];
1022
1023                 wlc_default_rateset(wlc, &default_rateset);
1024
1025                 /* fill in hw_rate */
1026                 wlc_rateset_filter(&default_rateset, &wlc->band->hw_rateset,
1027                                    false, WLC_RATES_CCK_OFDM, WLC_RATE_MASK,
1028                                    (bool) N_ENAB(wlc->pub));
1029
1030                 /* init basic rate lookup */
1031                 wlc_rate_lookup_init(wlc, &default_rateset);
1032         }
1033
1034         /* sync up phy/radio chanspec */
1035         wlc_set_phy_chanspec(wlc, chanspec);
1036 }
1037
1038 /* band-specific init */
1039 static void WLBANDINITFN(wlc_bsinit) (struct wlc_info *wlc)
1040 {
1041         BCMMSG(wlc->wiphy, "wl%d: bandunit %d\n",
1042                  wlc->pub->unit, wlc->band->bandunit);
1043
1044         /* write ucode ACK/CTS rate table */
1045         wlc_set_ratetable(wlc);
1046
1047         /* update some band specific mac configuration */
1048         wlc_ucode_mac_upd(wlc);
1049
1050         /* init antenna selection */
1051         wlc_antsel_init(wlc->asi);
1052
1053 }
1054
1055 /* switch to and initialize new band */
1056 static void WLBANDINITFN(wlc_setband) (struct wlc_info *wlc, uint bandunit)
1057 {
1058         int idx;
1059         struct wlc_bsscfg *cfg;
1060
1061         wlc->band = wlc->bandstate[bandunit];
1062
1063         if (!wlc->pub->up)
1064                 return;
1065
1066         /* wait for at least one beacon before entering sleeping state */
1067         FOREACH_AS_STA(wlc, idx, cfg)
1068             cfg->PMawakebcn = true;
1069         wlc_set_ps_ctrl(wlc);
1070
1071         /* band-specific initializations */
1072         wlc_bsinit(wlc);
1073 }
1074
1075 /* Initialize a WME Parameter Info Element with default STA parameters from WMM Spec, Table 12 */
1076 void wlc_wme_initparams_sta(struct wlc_info *wlc, wme_param_ie_t *pe)
1077 {
1078         static const wme_param_ie_t stadef = {
1079                 WME_OUI,
1080                 WME_TYPE,
1081                 WME_SUBTYPE_PARAM_IE,
1082                 WME_VER,
1083                 0,
1084                 0,
1085                 {
1086                  {EDCF_AC_BE_ACI_STA, EDCF_AC_BE_ECW_STA,
1087                   cpu_to_le16(EDCF_AC_BE_TXOP_STA)},
1088                  {EDCF_AC_BK_ACI_STA, EDCF_AC_BK_ECW_STA,
1089                   cpu_to_le16(EDCF_AC_BK_TXOP_STA)},
1090                  {EDCF_AC_VI_ACI_STA, EDCF_AC_VI_ECW_STA,
1091                   cpu_to_le16(EDCF_AC_VI_TXOP_STA)},
1092                  {EDCF_AC_VO_ACI_STA, EDCF_AC_VO_ECW_STA,
1093                   cpu_to_le16(EDCF_AC_VO_TXOP_STA)}
1094                  }
1095         };
1096         memcpy(pe, &stadef, sizeof(*pe));
1097 }
1098
1099 void wlc_wme_setparams(struct wlc_info *wlc, u16 aci,
1100                        const struct ieee80211_tx_queue_params *params,
1101                        bool suspend)
1102 {
1103         int i;
1104         shm_acparams_t acp_shm;
1105         u16 *shm_entry;
1106
1107         /* Only apply params if the core is out of reset and has clocks */
1108         if (!wlc->clk) {
1109                 wiphy_err(wlc->wiphy, "wl%d: %s : no-clock\n", wlc->pub->unit,
1110                           __func__);
1111                 return;
1112         }
1113
1114         do {
1115                 memset((char *)&acp_shm, 0, sizeof(shm_acparams_t));
1116                 /* fill in shm ac params struct */
1117                 acp_shm.txop = le16_to_cpu(params->txop);
1118                 /* convert from units of 32us to us for ucode */
1119                 wlc->edcf_txop[aci & 0x3] = acp_shm.txop =
1120                     EDCF_TXOP2USEC(acp_shm.txop);
1121                 acp_shm.aifs = (params->aifs & EDCF_AIFSN_MASK);
1122
1123                 if (aci == AC_VI && acp_shm.txop == 0
1124                     && acp_shm.aifs < EDCF_AIFSN_MAX)
1125                         acp_shm.aifs++;
1126
1127                 if (acp_shm.aifs < EDCF_AIFSN_MIN
1128                     || acp_shm.aifs > EDCF_AIFSN_MAX) {
1129                         wiphy_err(wlc->wiphy, "wl%d: wlc_edcf_setparams: bad "
1130                                   "aifs %d\n", wlc->pub->unit, acp_shm.aifs);
1131                         continue;
1132                 }
1133
1134                 acp_shm.cwmin = params->cw_min;
1135                 acp_shm.cwmax = params->cw_max;
1136                 acp_shm.cwcur = acp_shm.cwmin;
1137                 acp_shm.bslots =
1138                     R_REG(&wlc->regs->tsf_random) & acp_shm.cwcur;
1139                 acp_shm.reggap = acp_shm.bslots + acp_shm.aifs;
1140                 /* Indicate the new params to the ucode */
1141                 acp_shm.status = wlc_read_shm(wlc, (M_EDCF_QINFO +
1142                                                     wme_shmemacindex(aci) *
1143                                                     M_EDCF_QLEN +
1144                                                     M_EDCF_STATUS_OFF));
1145                 acp_shm.status |= WME_STATUS_NEWAC;
1146
1147                 /* Fill in shm acparam table */
1148                 shm_entry = (u16 *) &acp_shm;
1149                 for (i = 0; i < (int)sizeof(shm_acparams_t); i += 2)
1150                         wlc_write_shm(wlc,
1151                                       M_EDCF_QINFO +
1152                                       wme_shmemacindex(aci) * M_EDCF_QLEN + i,
1153                                       *shm_entry++);
1154
1155         } while (0);
1156
1157         if (suspend)
1158                 wlc_suspend_mac_and_wait(wlc);
1159
1160         if (suspend)
1161                 wlc_enable_mac(wlc);
1162
1163 }
1164
1165 void wlc_edcf_setparams(struct wlc_info *wlc, bool suspend)
1166 {
1167         u16 aci;
1168         int i_ac;
1169         edcf_acparam_t *edcf_acp;
1170
1171         struct ieee80211_tx_queue_params txq_pars;
1172         struct ieee80211_tx_queue_params *params = &txq_pars;
1173
1174         /*
1175          * AP uses AC params from wme_param_ie_ap.
1176          * AP advertises AC params from wme_param_ie.
1177          * STA uses AC params from wme_param_ie.
1178          */
1179
1180         edcf_acp = (edcf_acparam_t *) &wlc->wme_param_ie.acparam[0];
1181
1182         for (i_ac = 0; i_ac < AC_COUNT; i_ac++, edcf_acp++) {
1183                 /* find out which ac this set of params applies to */
1184                 aci = (edcf_acp->ACI & EDCF_ACI_MASK) >> EDCF_ACI_SHIFT;
1185
1186                 /* fill in shm ac params struct */
1187                 params->txop = edcf_acp->TXOP;
1188                 params->aifs = edcf_acp->ACI;
1189
1190                 /* CWmin = 2^(ECWmin) - 1 */
1191                 params->cw_min = EDCF_ECW2CW(edcf_acp->ECW & EDCF_ECWMIN_MASK);
1192                 /* CWmax = 2^(ECWmax) - 1 */
1193                 params->cw_max = EDCF_ECW2CW((edcf_acp->ECW & EDCF_ECWMAX_MASK)
1194                                             >> EDCF_ECWMAX_SHIFT);
1195                 wlc_wme_setparams(wlc, aci, params, suspend);
1196         }
1197
1198         if (suspend)
1199                 wlc_suspend_mac_and_wait(wlc);
1200
1201         if (AP_ENAB(wlc->pub) && WME_ENAB(wlc->pub)) {
1202                 wlc_update_beacon(wlc);
1203                 wlc_update_probe_resp(wlc, false);
1204         }
1205
1206         if (suspend)
1207                 wlc_enable_mac(wlc);
1208
1209 }
1210
1211 bool wlc_timers_init(struct wlc_info *wlc, int unit)
1212 {
1213         wlc->wdtimer = brcms_init_timer(wlc->wl, wlc_watchdog_by_timer,
1214                 wlc, "watchdog");
1215         if (!wlc->wdtimer) {
1216                 wiphy_err(wlc->wiphy, "wl%d:  wl_init_timer for wdtimer "
1217                           "failed\n", unit);
1218                 goto fail;
1219         }
1220
1221         wlc->radio_timer = brcms_init_timer(wlc->wl, wlc_radio_timer,
1222                 wlc, "radio");
1223         if (!wlc->radio_timer) {
1224                 wiphy_err(wlc->wiphy, "wl%d:  wl_init_timer for radio_timer "
1225                           "failed\n", unit);
1226                 goto fail;
1227         }
1228
1229         return true;
1230
1231  fail:
1232         return false;
1233 }
1234
1235 /*
1236  * Initialize wlc_info default values ...
1237  * may get overrides later in this function
1238  */
1239 void wlc_info_init(struct wlc_info *wlc, int unit)
1240 {
1241         int i;
1242         /* Assume the device is there until proven otherwise */
1243         wlc->device_present = true;
1244
1245         /* Save our copy of the chanspec */
1246         wlc->chanspec = CH20MHZ_CHSPEC(1);
1247
1248         /* various 802.11g modes */
1249         wlc->shortslot = false;
1250         wlc->shortslot_override = WLC_SHORTSLOT_AUTO;
1251
1252         wlc_protection_upd(wlc, WLC_PROT_G_OVR, WLC_PROTECTION_AUTO);
1253         wlc_protection_upd(wlc, WLC_PROT_G_SPEC, false);
1254
1255         wlc_protection_upd(wlc, WLC_PROT_N_CFG_OVR, WLC_PROTECTION_AUTO);
1256         wlc_protection_upd(wlc, WLC_PROT_N_CFG, WLC_N_PROTECTION_OFF);
1257         wlc_protection_upd(wlc, WLC_PROT_N_NONGF_OVR, WLC_PROTECTION_AUTO);
1258         wlc_protection_upd(wlc, WLC_PROT_N_NONGF, false);
1259         wlc_protection_upd(wlc, WLC_PROT_N_PAM_OVR, AUTO);
1260
1261         wlc_protection_upd(wlc, WLC_PROT_OVERLAP, WLC_PROTECTION_CTL_OVERLAP);
1262
1263         /* 802.11g draft 4.0 NonERP elt advertisement */
1264         wlc->include_legacy_erp = true;
1265
1266         wlc->stf->ant_rx_ovr = ANT_RX_DIV_DEF;
1267         wlc->stf->txant = ANT_TX_DEF;
1268
1269         wlc->prb_resp_timeout = WLC_PRB_RESP_TIMEOUT;
1270
1271         wlc->usr_fragthresh = DOT11_DEFAULT_FRAG_LEN;
1272         for (i = 0; i < NFIFO; i++)
1273                 wlc->fragthresh[i] = DOT11_DEFAULT_FRAG_LEN;
1274         wlc->RTSThresh = DOT11_DEFAULT_RTS_LEN;
1275
1276         /* default rate fallback retry limits */
1277         wlc->SFBL = RETRY_SHORT_FB;
1278         wlc->LFBL = RETRY_LONG_FB;
1279
1280         /* default mac retry limits */
1281         wlc->SRL = RETRY_SHORT_DEF;
1282         wlc->LRL = RETRY_LONG_DEF;
1283
1284         /* Set flag to indicate that hw keys should be used when available. */
1285         wlc->wsec_swkeys = false;
1286
1287         /* init the 4 static WEP default keys */
1288         for (i = 0; i < WSEC_MAX_DEFAULT_KEYS; i++) {
1289                 wlc->wsec_keys[i] = wlc->wsec_def_keys[i];
1290                 wlc->wsec_keys[i]->idx = (u8) i;
1291         }
1292
1293         /* WME QoS mode is Auto by default */
1294         wlc->pub->_wme = AUTO;
1295
1296 #ifdef BCMSDIODEV_ENABLED
1297         wlc->pub->_priofc = true;       /* enable priority flow control for sdio dongle */
1298 #endif
1299
1300         wlc->pub->_ampdu = AMPDU_AGG_HOST;
1301         wlc->pub->bcmerror = 0;
1302         wlc->pub->_coex = ON;
1303
1304         /* initialize mpc delay */
1305         wlc->mpc_delay_off = wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
1306 }
1307
1308 static bool wlc_state_bmac_sync(struct wlc_info *wlc)
1309 {
1310         wlc_bmac_state_t state_bmac;
1311
1312         if (wlc_bmac_state_get(wlc->hw, &state_bmac) != 0)
1313                 return false;
1314
1315         wlc->machwcap = state_bmac.machwcap;
1316         wlc_protection_upd(wlc, WLC_PROT_N_PAM_OVR,
1317                            (s8) state_bmac.preamble_ovr);
1318
1319         return true;
1320 }
1321
1322 static uint wlc_attach_module(struct wlc_info *wlc)
1323 {
1324         uint err = 0;
1325         uint unit;
1326         unit = wlc->pub->unit;
1327
1328         wlc->asi = wlc_antsel_attach(wlc);
1329         if (wlc->asi == NULL) {
1330                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_antsel_attach "
1331                           "failed\n", unit);
1332                 err = 44;
1333                 goto fail;
1334         }
1335
1336         wlc->ampdu = wlc_ampdu_attach(wlc);
1337         if (wlc->ampdu == NULL) {
1338                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_ampdu_attach "
1339                           "failed\n", unit);
1340                 err = 50;
1341                 goto fail;
1342         }
1343
1344         if ((wlc_stf_attach(wlc) != 0)) {
1345                 wiphy_err(wlc->wiphy, "wl%d: wlc_attach: wlc_stf_attach "
1346                           "failed\n", unit);
1347                 err = 68;
1348                 goto fail;
1349         }
1350  fail:
1351         return err;
1352 }
1353
1354 struct wlc_pub *wlc_pub(void *wlc)
1355 {
1356         return ((struct wlc_info *) wlc)->pub;
1357 }
1358
1359 #define CHIP_SUPPORTS_11N(wlc)  1
1360
1361 /*
1362  * The common driver entry routine. Error codes should be unique
1363  */
1364 void *wlc_attach(struct brcms_info *wl, u16 vendor, u16 device, uint unit,
1365                  bool piomode, void *regsva, uint bustype, void *btparam,
1366                  uint *perr)
1367 {
1368         struct wlc_info *wlc;
1369         uint err = 0;
1370         uint j;
1371         struct wlc_pub *pub;
1372         uint n_disabled;
1373
1374         /* allocate struct wlc_info state and its substructures */
1375         wlc = (struct wlc_info *) wlc_attach_malloc(unit, &err, device);
1376         if (wlc == NULL)
1377                 goto fail;
1378         wlc->wiphy = wl->wiphy;
1379         pub = wlc->pub;
1380
1381 #if defined(BCMDBG)
1382         wlc_info_dbg = wlc;
1383 #endif
1384
1385         wlc->band = wlc->bandstate[0];
1386         wlc->core = wlc->corestate;
1387         wlc->wl = wl;
1388         pub->unit = unit;
1389         pub->_piomode = piomode;
1390         wlc->bandinit_pending = false;
1391
1392         /* populate struct wlc_info with default values  */
1393         wlc_info_init(wlc, unit);
1394
1395         /* update sta/ap related parameters */
1396         wlc_ap_upd(wlc);
1397
1398         /* 11n_disable nvram */
1399         n_disabled = getintvar(pub->vars, "11n_disable");
1400
1401         /*
1402          * low level attach steps(all hw accesses go
1403          * inside, no more in rest of the attach)
1404          */
1405         err = wlc_bmac_attach(wlc, vendor, device, unit, piomode, regsva,
1406                               bustype, btparam);
1407         if (err)
1408                 goto fail;
1409
1410         /* for some states, due to different info pointer(e,g, wlc, wlc_hw) or master/slave split,
1411          * HIGH driver(both monolithic and HIGH_ONLY) needs to sync states FROM BMAC portion driver
1412          */
1413         if (!wlc_state_bmac_sync(wlc)) {
1414                 err = 20;
1415                 goto fail;
1416         }
1417
1418         pub->phy_11ncapable = WLC_PHY_11N_CAP(wlc->band);
1419
1420         /* propagate *vars* from BMAC driver to high driver */
1421         wlc_bmac_copyfrom_vars(wlc->hw, &pub->vars, &wlc->vars_size);
1422
1423
1424         /* set maximum allowed duty cycle */
1425         wlc->tx_duty_cycle_ofdm =
1426             (u16) getintvar(pub->vars, "tx_duty_cycle_ofdm");
1427         wlc->tx_duty_cycle_cck =
1428             (u16) getintvar(pub->vars, "tx_duty_cycle_cck");
1429
1430         wlc_stf_phy_chain_calc(wlc);
1431
1432         /* txchain 1: txant 0, txchain 2: txant 1 */
1433         if (WLCISNPHY(wlc->band) && (wlc->stf->txstreams == 1))
1434                 wlc->stf->txant = wlc->stf->hw_txchain - 1;
1435
1436         /* push to BMAC driver */
1437         wlc_phy_stf_chain_init(wlc->band->pi, wlc->stf->hw_txchain,
1438                                wlc->stf->hw_rxchain);
1439
1440         /* pull up some info resulting from the low attach */
1441         {
1442                 int i;
1443                 for (i = 0; i < NFIFO; i++)
1444                         wlc->core->txavail[i] = wlc->hw->txavail[i];
1445         }
1446
1447         wlc_bmac_hw_etheraddr(wlc->hw, wlc->perm_etheraddr);
1448
1449         memcpy(&pub->cur_etheraddr, &wlc->perm_etheraddr, ETH_ALEN);
1450
1451         for (j = 0; j < NBANDS(wlc); j++) {
1452                 /* Use band 1 for single band 11a */
1453                 if (IS_SINGLEBAND_5G(wlc->deviceid))
1454                         j = BAND_5G_INDEX;
1455
1456                 wlc->band = wlc->bandstate[j];
1457
1458                 if (!wlc_attach_stf_ant_init(wlc)) {
1459                         err = 24;
1460                         goto fail;
1461                 }
1462
1463                 /* default contention windows size limits */
1464                 wlc->band->CWmin = APHY_CWMIN;
1465                 wlc->band->CWmax = PHY_CWMAX;
1466
1467                 /* init gmode value */
1468                 if (BAND_2G(wlc->band->bandtype)) {
1469                         wlc->band->gmode = GMODE_AUTO;
1470                         wlc_protection_upd(wlc, WLC_PROT_G_USER,
1471                                            wlc->band->gmode);
1472                 }
1473
1474                 /* init _n_enab supported mode */
1475                 if (WLC_PHY_11N_CAP(wlc->band) && CHIP_SUPPORTS_11N(wlc)) {
1476                         if (n_disabled & WLFEATURE_DISABLE_11N) {
1477                                 pub->_n_enab = OFF;
1478                                 wlc_protection_upd(wlc, WLC_PROT_N_USER, OFF);
1479                         } else {
1480                                 pub->_n_enab = SUPPORT_11N;
1481                                 wlc_protection_upd(wlc, WLC_PROT_N_USER,
1482                                                    ((pub->_n_enab ==
1483                                                      SUPPORT_11N) ? WL_11N_2x2 :
1484                                                     WL_11N_3x3));
1485                         }
1486                 }
1487
1488                 /* init per-band default rateset, depend on band->gmode */
1489                 wlc_default_rateset(wlc, &wlc->band->defrateset);
1490
1491                 /* fill in hw_rateset (used early by WLC_SET_RATESET) */
1492                 wlc_rateset_filter(&wlc->band->defrateset,
1493                                    &wlc->band->hw_rateset, false,
1494                                    WLC_RATES_CCK_OFDM, WLC_RATE_MASK,
1495                                    (bool) N_ENAB(wlc->pub));
1496         }
1497
1498         /* update antenna config due to wlc->stf->txant/txchain/ant_rx_ovr change */
1499         wlc_stf_phy_txant_upd(wlc);
1500
1501         /* attach each modules */
1502         err = wlc_attach_module(wlc);
1503         if (err != 0)
1504                 goto fail;
1505
1506         if (!wlc_timers_init(wlc, unit)) {
1507                 wiphy_err(wl->wiphy, "wl%d: %s: wlc_init_timer failed\n", unit,
1508                           __func__);
1509                 err = 32;
1510                 goto fail;
1511         }
1512
1513         /* depend on rateset, gmode */
1514         wlc->cmi = wlc_channel_mgr_attach(wlc);
1515         if (!wlc->cmi) {
1516                 wiphy_err(wl->wiphy, "wl%d: %s: wlc_channel_mgr_attach failed"
1517                           "\n", unit, __func__);
1518                 err = 33;
1519                 goto fail;
1520         }
1521
1522         /* init default when all parameters are ready, i.e. ->rateset */
1523         wlc_bss_default_init(wlc);
1524
1525         /*
1526          * Complete the wlc default state initializations..
1527          */
1528
1529         /* allocate our initial queue */
1530         wlc->pkt_queue = wlc_txq_alloc(wlc);
1531         if (wlc->pkt_queue == NULL) {
1532                 wiphy_err(wl->wiphy, "wl%d: %s: failed to malloc tx queue\n",
1533                           unit, __func__);
1534                 err = 100;
1535                 goto fail;
1536         }
1537
1538         wlc->bsscfg[0] = wlc->cfg;
1539         wlc->cfg->_idx = 0;
1540         wlc->cfg->wlc = wlc;
1541         pub->txmaxpkts = MAXTXPKTS;
1542
1543         wlc_wme_initparams_sta(wlc, &wlc->wme_param_ie);
1544
1545         wlc->mimoft = FT_HT;
1546         wlc->ht_cap.cap_info = HT_CAP;
1547         if (HT_ENAB(wlc->pub))
1548                 wlc->stf->ldpc = AUTO;
1549
1550         wlc->mimo_40txbw = AUTO;
1551         wlc->ofdm_40txbw = AUTO;
1552         wlc->cck_40txbw = AUTO;
1553         wlc_update_mimo_band_bwcap(wlc, WLC_N_BW_20IN2G_40IN5G);
1554
1555         /* Set default values of SGI */
1556         if (WLC_SGI_CAP_PHY(wlc)) {
1557                 wlc_ht_update_sgi_rx(wlc, (WLC_N_SGI_20 | WLC_N_SGI_40));
1558                 wlc->sgi_tx = AUTO;
1559         } else if (WLCISSSLPNPHY(wlc->band)) {
1560                 wlc_ht_update_sgi_rx(wlc, (WLC_N_SGI_20 | WLC_N_SGI_40));
1561                 wlc->sgi_tx = AUTO;
1562         } else {
1563                 wlc_ht_update_sgi_rx(wlc, 0);
1564                 wlc->sgi_tx = OFF;
1565         }
1566
1567         /* *******nvram 11n config overrides Start ********* */
1568
1569         /* apply the sgi override from nvram conf */
1570         if (n_disabled & WLFEATURE_DISABLE_11N_SGI_TX)
1571                 wlc->sgi_tx = OFF;
1572
1573         if (n_disabled & WLFEATURE_DISABLE_11N_SGI_RX)
1574                 wlc_ht_update_sgi_rx(wlc, 0);
1575
1576         /* apply the stbc override from nvram conf */
1577         if (n_disabled & WLFEATURE_DISABLE_11N_STBC_TX) {
1578                 wlc->bandstate[BAND_2G_INDEX]->band_stf_stbc_tx = OFF;
1579                 wlc->bandstate[BAND_5G_INDEX]->band_stf_stbc_tx = OFF;
1580                 wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_TX_STBC;
1581         }
1582         if (n_disabled & WLFEATURE_DISABLE_11N_STBC_RX)
1583                 wlc_stf_stbc_rx_set(wlc, HT_CAP_RX_STBC_NO);
1584
1585         /* apply the GF override from nvram conf */
1586         if (n_disabled & WLFEATURE_DISABLE_11N_GF)
1587                 wlc->ht_cap.cap_info &= ~IEEE80211_HT_CAP_GRN_FLD;
1588
1589         /* initialize radio_mpc_disable according to wlc->mpc */
1590         wlc_radio_mpc_upd(wlc);
1591
1592         if ((wlc->pub->sih->chip) == BCM43235_CHIP_ID) {
1593                 if ((getintvar(wlc->pub->vars, "aa2g") == 7) ||
1594                     (getintvar(wlc->pub->vars, "aa5g") == 7)) {
1595                         wlc_bmac_antsel_set(wlc->hw, 1);
1596                 }
1597         } else {
1598                 wlc_bmac_antsel_set(wlc->hw, wlc->asi->antsel_avail);
1599         }
1600
1601         if (perr)
1602                 *perr = 0;
1603
1604         return (void *)wlc;
1605
1606  fail:
1607         wiphy_err(wl->wiphy, "wl%d: %s: failed with err %d\n",
1608                   unit, __func__, err);
1609         if (wlc)
1610                 wlc_detach(wlc);
1611
1612         if (perr)
1613                 *perr = err;
1614         return NULL;
1615 }
1616
1617 static void wlc_attach_antgain_init(struct wlc_info *wlc)
1618 {
1619         uint unit;
1620         unit = wlc->pub->unit;
1621
1622         if ((wlc->band->antgain == -1) && (wlc->pub->sromrev == 1)) {
1623                 /* default antenna gain for srom rev 1 is 2 dBm (8 qdbm) */
1624                 wlc->band->antgain = 8;
1625         } else if (wlc->band->antgain == -1) {
1626                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid antennas available in"
1627                           " srom, using 2dB\n", unit, __func__);
1628                 wlc->band->antgain = 8;
1629         } else {
1630                 s8 gain, fract;
1631                 /* Older sroms specified gain in whole dbm only.  In order
1632                  * be able to specify qdbm granularity and remain backward compatible
1633                  * the whole dbms are now encoded in only low 6 bits and remaining qdbms
1634                  * are encoded in the hi 2 bits. 6 bit signed number ranges from
1635                  * -32 - 31. Examples: 0x1 = 1 db,
1636                  * 0xc1 = 1.75 db (1 + 3 quarters),
1637                  * 0x3f = -1 (-1 + 0 quarters),
1638                  * 0x7f = -.75 (-1 in low 6 bits + 1 quarters in hi 2 bits) = -3 qdbm.
1639                  * 0xbf = -.50 (-1 in low 6 bits + 2 quarters in hi 2 bits) = -2 qdbm.
1640                  */
1641                 gain = wlc->band->antgain & 0x3f;
1642                 gain <<= 2;     /* Sign extend */
1643                 gain >>= 2;
1644                 fract = (wlc->band->antgain & 0xc0) >> 6;
1645                 wlc->band->antgain = 4 * gain + fract;
1646         }
1647 }
1648
1649 static bool wlc_attach_stf_ant_init(struct wlc_info *wlc)
1650 {
1651         int aa;
1652         uint unit;
1653         char *vars;
1654         int bandtype;
1655
1656         unit = wlc->pub->unit;
1657         vars = wlc->pub->vars;
1658         bandtype = wlc->band->bandtype;
1659
1660         /* get antennas available */
1661         aa = (s8) getintvar(vars, (BAND_5G(bandtype) ? "aa5g" : "aa2g"));
1662         if (aa == 0)
1663                 aa = (s8) getintvar(vars,
1664                                       (BAND_5G(bandtype) ? "aa1" : "aa0"));
1665         if ((aa < 1) || (aa > 15)) {
1666                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid antennas available in"
1667                           " srom (0x%x), using 3\n", unit, __func__, aa);
1668                 aa = 3;
1669         }
1670
1671         /* reset the defaults if we have a single antenna */
1672         if (aa == 1) {
1673                 wlc->stf->ant_rx_ovr = ANT_RX_DIV_FORCE_0;
1674                 wlc->stf->txant = ANT_TX_FORCE_0;
1675         } else if (aa == 2) {
1676                 wlc->stf->ant_rx_ovr = ANT_RX_DIV_FORCE_1;
1677                 wlc->stf->txant = ANT_TX_FORCE_1;
1678         } else {
1679         }
1680
1681         /* Compute Antenna Gain */
1682         wlc->band->antgain =
1683             (s8) getintvar(vars, (BAND_5G(bandtype) ? "ag1" : "ag0"));
1684         wlc_attach_antgain_init(wlc);
1685
1686         return true;
1687 }
1688
1689
1690 static void wlc_timers_deinit(struct wlc_info *wlc)
1691 {
1692         /* free timer state */
1693         if (wlc->wdtimer) {
1694                 brcms_free_timer(wlc->wl, wlc->wdtimer);
1695                 wlc->wdtimer = NULL;
1696         }
1697         if (wlc->radio_timer) {
1698                 brcms_free_timer(wlc->wl, wlc->radio_timer);
1699                 wlc->radio_timer = NULL;
1700         }
1701 }
1702
1703 static void wlc_detach_module(struct wlc_info *wlc)
1704 {
1705         if (wlc->asi) {
1706                 wlc_antsel_detach(wlc->asi);
1707                 wlc->asi = NULL;
1708         }
1709
1710         if (wlc->ampdu) {
1711                 wlc_ampdu_detach(wlc->ampdu);
1712                 wlc->ampdu = NULL;
1713         }
1714
1715         wlc_stf_detach(wlc);
1716 }
1717
1718 /*
1719  * Return a count of the number of driver callbacks still pending.
1720  *
1721  * General policy is that wlc_detach can only dealloc/free software states. It can NOT
1722  *  touch hardware registers since the d11core may be in reset and clock may not be available.
1723  *    One exception is sb register access, which is possible if crystal is turned on
1724  * After "down" state, driver should avoid software timer with the exception of radio_monitor.
1725  */
1726 uint wlc_detach(struct wlc_info *wlc)
1727 {
1728         uint callbacks = 0;
1729
1730         if (wlc == NULL)
1731                 return 0;
1732
1733         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
1734
1735         callbacks += wlc_bmac_detach(wlc);
1736
1737         /* delete software timers */
1738         if (!wlc_radio_monitor_stop(wlc))
1739                 callbacks++;
1740
1741         wlc_channel_mgr_detach(wlc->cmi);
1742
1743         wlc_timers_deinit(wlc);
1744
1745         wlc_detach_module(wlc);
1746
1747
1748         while (wlc->tx_queues != NULL)
1749                 wlc_txq_free(wlc, wlc->tx_queues);
1750
1751         wlc_detach_mfree(wlc);
1752         return callbacks;
1753 }
1754
1755 /* update state that depends on the current value of "ap" */
1756 void wlc_ap_upd(struct wlc_info *wlc)
1757 {
1758         if (AP_ENAB(wlc->pub))
1759                 wlc->PLCPHdr_override = WLC_PLCP_AUTO;  /* AP: short not allowed, but not enforced */
1760         else
1761                 wlc->PLCPHdr_override = WLC_PLCP_SHORT; /* STA-BSS; short capable */
1762
1763         /* fixup mpc */
1764         wlc->mpc = true;
1765 }
1766
1767 /* read hwdisable state and propagate to wlc flag */
1768 static void wlc_radio_hwdisable_upd(struct wlc_info *wlc)
1769 {
1770         if (wlc->pub->wlfeatureflag & WL_SWFL_NOHWRADIO || wlc->pub->hw_off)
1771                 return;
1772
1773         if (wlc_bmac_radio_read_hwdisabled(wlc->hw)) {
1774                 mboolset(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE);
1775         } else {
1776                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE);
1777         }
1778 }
1779
1780 /* return true if Minimum Power Consumption should be entered, false otherwise */
1781 bool wlc_is_non_delay_mpc(struct wlc_info *wlc)
1782 {
1783         return false;
1784 }
1785
1786 bool wlc_ismpc(struct wlc_info *wlc)
1787 {
1788         return (wlc->mpc_delay_off == 0) && (wlc_is_non_delay_mpc(wlc));
1789 }
1790
1791 void wlc_radio_mpc_upd(struct wlc_info *wlc)
1792 {
1793         bool mpc_radio, radio_state;
1794
1795         /*
1796          * Clear the WL_RADIO_MPC_DISABLE bit when mpc feature is disabled
1797          * in case the WL_RADIO_MPC_DISABLE bit was set. Stop the radio
1798          * monitor also when WL_RADIO_MPC_DISABLE is the only reason that
1799          * the radio is going down.
1800          */
1801         if (!wlc->mpc) {
1802                 if (!wlc->pub->radio_disabled)
1803                         return;
1804                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE);
1805                 wlc_radio_upd(wlc);
1806                 if (!wlc->pub->radio_disabled)
1807                         wlc_radio_monitor_stop(wlc);
1808                 return;
1809         }
1810
1811         /*
1812          * sync ismpc logic with WL_RADIO_MPC_DISABLE bit in wlc->pub->radio_disabled
1813          * to go ON, always call radio_upd synchronously
1814          * to go OFF, postpone radio_upd to later when context is safe(e.g. watchdog)
1815          */
1816         radio_state =
1817             (mboolisset(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE) ? OFF :
1818              ON);
1819         mpc_radio = (wlc_ismpc(wlc) == true) ? OFF : ON;
1820
1821         if (radio_state == ON && mpc_radio == OFF)
1822                 wlc->mpc_delay_off = wlc->mpc_dlycnt;
1823         else if (radio_state == OFF && mpc_radio == ON) {
1824                 mboolclr(wlc->pub->radio_disabled, WL_RADIO_MPC_DISABLE);
1825                 wlc_radio_upd(wlc);
1826                 if (wlc->mpc_offcnt < WLC_MPC_THRESHOLD) {
1827                         wlc->mpc_dlycnt = WLC_MPC_MAX_DELAYCNT;
1828                 } else
1829                         wlc->mpc_dlycnt = WLC_MPC_MIN_DELAYCNT;
1830                 wlc->mpc_dur += OSL_SYSUPTIME() - wlc->mpc_laston_ts;
1831         }
1832         /* Below logic is meant to capture the transition from mpc off to mpc on for reasons
1833          * other than wlc->mpc_delay_off keeping the mpc off. In that case reset
1834          * wlc->mpc_delay_off to wlc->mpc_dlycnt, so that we restart the countdown of mpc_delay_off
1835          */
1836         if ((wlc->prev_non_delay_mpc == false) &&
1837             (wlc_is_non_delay_mpc(wlc) == true) && wlc->mpc_delay_off) {
1838                 wlc->mpc_delay_off = wlc->mpc_dlycnt;
1839         }
1840         wlc->prev_non_delay_mpc = wlc_is_non_delay_mpc(wlc);
1841 }
1842
1843 /*
1844  * centralized radio disable/enable function,
1845  * invoke radio enable/disable after updating hwradio status
1846  */
1847 static void wlc_radio_upd(struct wlc_info *wlc)
1848 {
1849         if (wlc->pub->radio_disabled) {
1850                 wlc_radio_disable(wlc);
1851         } else {
1852                 wlc_radio_enable(wlc);
1853         }
1854 }
1855
1856 /* maintain LED behavior in down state */
1857 static void wlc_down_led_upd(struct wlc_info *wlc)
1858 {
1859         /* maintain LEDs while in down state, turn on sbclk if not available yet */
1860         /* turn on sbclk if necessary */
1861         if (!AP_ENAB(wlc->pub)) {
1862                 wlc_pllreq(wlc, true, WLC_PLLREQ_FLIP);
1863
1864                 wlc_pllreq(wlc, false, WLC_PLLREQ_FLIP);
1865         }
1866 }
1867
1868 /* update hwradio status and return it */
1869 bool wlc_check_radio_disabled(struct wlc_info *wlc)
1870 {
1871         wlc_radio_hwdisable_upd(wlc);
1872
1873         return mboolisset(wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE) ? true : false;
1874 }
1875
1876 void wlc_radio_disable(struct wlc_info *wlc)
1877 {
1878         if (!wlc->pub->up) {
1879                 wlc_down_led_upd(wlc);
1880                 return;
1881         }
1882
1883         wlc_radio_monitor_start(wlc);
1884         brcms_down(wlc->wl);
1885 }
1886
1887 static void wlc_radio_enable(struct wlc_info *wlc)
1888 {
1889         if (wlc->pub->up)
1890                 return;
1891
1892         if (DEVICEREMOVED(wlc))
1893                 return;
1894
1895         brcms_up(wlc->wl);
1896 }
1897
1898 /* periodical query hw radio button while driver is "down" */
1899 static void wlc_radio_timer(void *arg)
1900 {
1901         struct wlc_info *wlc = (struct wlc_info *) arg;
1902
1903         if (DEVICEREMOVED(wlc)) {
1904                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
1905                         __func__);
1906                 brcms_down(wlc->wl);
1907                 return;
1908         }
1909
1910         /* cap mpc off count */
1911         if (wlc->mpc_offcnt < WLC_MPC_MAX_DELAYCNT)
1912                 wlc->mpc_offcnt++;
1913
1914         wlc_radio_hwdisable_upd(wlc);
1915         wlc_radio_upd(wlc);
1916 }
1917
1918 static bool wlc_radio_monitor_start(struct wlc_info *wlc)
1919 {
1920         /* Don't start the timer if HWRADIO feature is disabled */
1921         if (wlc->radio_monitor || (wlc->pub->wlfeatureflag & WL_SWFL_NOHWRADIO))
1922                 return true;
1923
1924         wlc->radio_monitor = true;
1925         wlc_pllreq(wlc, true, WLC_PLLREQ_RADIO_MON);
1926         brcms_add_timer(wlc->wl, wlc->radio_timer, TIMER_INTERVAL_RADIOCHK,
1927                         true);
1928         return true;
1929 }
1930
1931 bool wlc_radio_monitor_stop(struct wlc_info *wlc)
1932 {
1933         if (!wlc->radio_monitor)
1934                 return true;
1935
1936         wlc->radio_monitor = false;
1937         wlc_pllreq(wlc, false, WLC_PLLREQ_RADIO_MON);
1938         return brcms_del_timer(wlc->wl, wlc->radio_timer);
1939 }
1940
1941 static void wlc_watchdog_by_timer(void *arg)
1942 {
1943         wlc_watchdog(arg);
1944 }
1945
1946 /* common watchdog code */
1947 static void wlc_watchdog(void *arg)
1948 {
1949         struct wlc_info *wlc = (struct wlc_info *) arg;
1950         int i;
1951         struct wlc_bsscfg *cfg;
1952
1953         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
1954
1955         if (!wlc->pub->up)
1956                 return;
1957
1958         if (DEVICEREMOVED(wlc)) {
1959                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
1960                           __func__);
1961                 brcms_down(wlc->wl);
1962                 return;
1963         }
1964
1965         /* increment second count */
1966         wlc->pub->now++;
1967
1968         /* delay radio disable */
1969         if (wlc->mpc_delay_off) {
1970                 if (--wlc->mpc_delay_off == 0) {
1971                         mboolset(wlc->pub->radio_disabled,
1972                                  WL_RADIO_MPC_DISABLE);
1973                         if (wlc->mpc && wlc_ismpc(wlc))
1974                                 wlc->mpc_offcnt = 0;
1975                         wlc->mpc_laston_ts = OSL_SYSUPTIME();
1976                 }
1977         }
1978
1979         /* mpc sync */
1980         wlc_radio_mpc_upd(wlc);
1981         /* radio sync: sw/hw/mpc --> radio_disable/radio_enable */
1982         wlc_radio_hwdisable_upd(wlc);
1983         wlc_radio_upd(wlc);
1984         /* if radio is disable, driver may be down, quit here */
1985         if (wlc->pub->radio_disabled)
1986                 return;
1987
1988         wlc_bmac_watchdog(wlc);
1989
1990         /* occasionally sample mac stat counters to detect 16-bit counter wrap */
1991         if ((wlc->pub->now % SW_TIMER_MAC_STAT_UPD) == 0)
1992                 wlc_statsupd(wlc);
1993
1994         /* Manage TKIP countermeasures timers */
1995         FOREACH_BSS(wlc, i, cfg) {
1996                 if (cfg->tk_cm_dt) {
1997                         cfg->tk_cm_dt--;
1998                 }
1999                 if (cfg->tk_cm_bt) {
2000                         cfg->tk_cm_bt--;
2001                 }
2002         }
2003
2004         /* Call any registered watchdog handlers */
2005         for (i = 0; i < WLC_MAXMODULES; i++) {
2006                 if (wlc->modulecb[i].watchdog_fn)
2007                         wlc->modulecb[i].watchdog_fn(wlc->modulecb[i].hdl);
2008         }
2009
2010         if (WLCISNPHY(wlc->band) && !wlc->pub->tempsense_disable &&
2011             ((wlc->pub->now - wlc->tempsense_lasttime) >=
2012              WLC_TEMPSENSE_PERIOD)) {
2013                 wlc->tempsense_lasttime = wlc->pub->now;
2014                 wlc_tempsense_upd(wlc);
2015         }
2016 }
2017
2018 /* make interface operational */
2019 int wlc_up(struct wlc_info *wlc)
2020 {
2021         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
2022
2023         /* HW is turned off so don't try to access it */
2024         if (wlc->pub->hw_off || DEVICEREMOVED(wlc))
2025                 return -ENOMEDIUM;
2026
2027         if (!wlc->pub->hw_up) {
2028                 wlc_bmac_hw_up(wlc->hw);
2029                 wlc->pub->hw_up = true;
2030         }
2031
2032         if ((wlc->pub->boardflags & BFL_FEM)
2033             && (wlc->pub->sih->chip == BCM4313_CHIP_ID)) {
2034                 if (wlc->pub->boardrev >= 0x1250
2035                     && (wlc->pub->boardflags & BFL_FEM_BT)) {
2036                         wlc_mhf(wlc, MHF5, MHF5_4313_GPIOCTRL,
2037                                 MHF5_4313_GPIOCTRL, WLC_BAND_ALL);
2038                 } else {
2039                         wlc_mhf(wlc, MHF4, MHF4_EXTPA_ENABLE, MHF4_EXTPA_ENABLE,
2040                                 WLC_BAND_ALL);
2041                 }
2042         }
2043
2044         /*
2045          * Need to read the hwradio status here to cover the case where the system
2046          * is loaded with the hw radio disabled. We do not want to bring the driver up in this case.
2047          * if radio is disabled, abort up, lower power, start radio timer and return 0(for NDIS)
2048          * don't call radio_update to avoid looping wlc_up.
2049          *
2050          * wlc_bmac_up_prep() returns either 0 or -BCME_RADIOOFF only
2051          */
2052         if (!wlc->pub->radio_disabled) {
2053                 int status = wlc_bmac_up_prep(wlc->hw);
2054                 if (status == -ENOMEDIUM) {
2055                         if (!mboolisset
2056                             (wlc->pub->radio_disabled, WL_RADIO_HW_DISABLE)) {
2057                                 int idx;
2058                                 struct wlc_bsscfg *bsscfg;
2059                                 mboolset(wlc->pub->radio_disabled,
2060                                          WL_RADIO_HW_DISABLE);
2061
2062                                 FOREACH_BSS(wlc, idx, bsscfg) {
2063                                         if (!BSSCFG_STA(bsscfg)
2064                                             || !bsscfg->enable || !bsscfg->BSS)
2065                                                 continue;
2066                                         wiphy_err(wlc->wiphy, "wl%d.%d: wlc_up"
2067                                                   ": rfdisable -> "
2068                                                   "wlc_bsscfg_disable()\n",
2069                                                    wlc->pub->unit, idx);
2070                                 }
2071                         }
2072                 }
2073         }
2074
2075         if (wlc->pub->radio_disabled) {
2076                 wlc_radio_monitor_start(wlc);
2077                 return 0;
2078         }
2079
2080         /* wlc_bmac_up_prep has done wlc_corereset(). so clk is on, set it */
2081         wlc->clk = true;
2082
2083         wlc_radio_monitor_stop(wlc);
2084
2085         /* Set EDCF hostflags */
2086         if (EDCF_ENAB(wlc->pub)) {
2087                 wlc_mhf(wlc, MHF1, MHF1_EDCF, MHF1_EDCF, WLC_BAND_ALL);
2088         } else {
2089                 wlc_mhf(wlc, MHF1, MHF1_EDCF, 0, WLC_BAND_ALL);
2090         }
2091
2092         if (WLC_WAR16165(wlc))
2093                 wlc_mhf(wlc, MHF2, MHF2_PCISLOWCLKWAR, MHF2_PCISLOWCLKWAR,
2094                         WLC_BAND_ALL);
2095
2096         brcms_init(wlc->wl);
2097         wlc->pub->up = true;
2098
2099         if (wlc->bandinit_pending) {
2100                 wlc_suspend_mac_and_wait(wlc);
2101                 wlc_set_chanspec(wlc, wlc->default_bss->chanspec);
2102                 wlc->bandinit_pending = false;
2103                 wlc_enable_mac(wlc);
2104         }
2105
2106         wlc_bmac_up_finish(wlc->hw);
2107
2108         /* other software states up after ISR is running */
2109         /* start APs that were to be brought up but are not up  yet */
2110         /* if (AP_ENAB(wlc->pub)) wlc_restart_ap(wlc->ap); */
2111
2112         /* Program the TX wme params with the current settings */
2113         wlc_wme_retries_write(wlc);
2114
2115         /* start one second watchdog timer */
2116         brcms_add_timer(wlc->wl, wlc->wdtimer, TIMER_INTERVAL_WATCHDOG, true);
2117         wlc->WDarmed = true;
2118
2119         /* ensure antenna config is up to date */
2120         wlc_stf_phy_txant_upd(wlc);
2121         /* ensure LDPC config is in sync */
2122         wlc_ht_update_ldpc(wlc, wlc->stf->ldpc);
2123
2124         return 0;
2125 }
2126
2127 /* Initialize the base precedence map for dequeueing from txq based on WME settings */
2128 static void wlc_tx_prec_map_init(struct wlc_info *wlc)
2129 {
2130         wlc->tx_prec_map = WLC_PREC_BMP_ALL;
2131         memset(wlc->fifo2prec_map, 0, NFIFO * sizeof(u16));
2132
2133         /* For non-WME, both fifos have overlapping MAXPRIO. So just disable all precedences
2134          * if either is full.
2135          */
2136         if (!EDCF_ENAB(wlc->pub)) {
2137                 wlc->fifo2prec_map[TX_DATA_FIFO] = WLC_PREC_BMP_ALL;
2138                 wlc->fifo2prec_map[TX_CTL_FIFO] = WLC_PREC_BMP_ALL;
2139         } else {
2140                 wlc->fifo2prec_map[TX_AC_BK_FIFO] = WLC_PREC_BMP_AC_BK;
2141                 wlc->fifo2prec_map[TX_AC_BE_FIFO] = WLC_PREC_BMP_AC_BE;
2142                 wlc->fifo2prec_map[TX_AC_VI_FIFO] = WLC_PREC_BMP_AC_VI;
2143                 wlc->fifo2prec_map[TX_AC_VO_FIFO] = WLC_PREC_BMP_AC_VO;
2144         }
2145 }
2146
2147 static uint wlc_down_del_timer(struct wlc_info *wlc)
2148 {
2149         uint callbacks = 0;
2150
2151         return callbacks;
2152 }
2153
2154 /*
2155  * Mark the interface nonoperational, stop the software mechanisms,
2156  * disable the hardware, free any transient buffer state.
2157  * Return a count of the number of driver callbacks still pending.
2158  */
2159 uint wlc_down(struct wlc_info *wlc)
2160 {
2161
2162         uint callbacks = 0;
2163         int i;
2164         bool dev_gone = false;
2165         struct wlc_txq_info *qi;
2166
2167         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
2168
2169         /* check if we are already in the going down path */
2170         if (wlc->going_down) {
2171                 wiphy_err(wlc->wiphy, "wl%d: %s: Driver going down so return"
2172                           "\n", wlc->pub->unit, __func__);
2173                 return 0;
2174         }
2175         if (!wlc->pub->up)
2176                 return callbacks;
2177
2178         /* in between, mpc could try to bring down again.. */
2179         wlc->going_down = true;
2180
2181         callbacks += wlc_bmac_down_prep(wlc->hw);
2182
2183         dev_gone = DEVICEREMOVED(wlc);
2184
2185         /* Call any registered down handlers */
2186         for (i = 0; i < WLC_MAXMODULES; i++) {
2187                 if (wlc->modulecb[i].down_fn)
2188                         callbacks +=
2189                             wlc->modulecb[i].down_fn(wlc->modulecb[i].hdl);
2190         }
2191
2192         /* cancel the watchdog timer */
2193         if (wlc->WDarmed) {
2194                 if (!brcms_del_timer(wlc->wl, wlc->wdtimer))
2195                         callbacks++;
2196                 wlc->WDarmed = false;
2197         }
2198         /* cancel all other timers */
2199         callbacks += wlc_down_del_timer(wlc);
2200
2201         wlc->pub->up = false;
2202
2203         wlc_phy_mute_upd(wlc->band->pi, false, PHY_MUTE_ALL);
2204
2205         /* clear txq flow control */
2206         wlc_txflowcontrol_reset(wlc);
2207
2208         /* flush tx queues */
2209         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
2210                 brcmu_pktq_flush(&qi->q, true, NULL, NULL);
2211         }
2212
2213         callbacks += wlc_bmac_down_finish(wlc->hw);
2214
2215         /* wlc_bmac_down_finish has done wlc_coredisable(). so clk is off */
2216         wlc->clk = false;
2217
2218         wlc->going_down = false;
2219         return callbacks;
2220 }
2221
2222 /* Set the current gmode configuration */
2223 int wlc_set_gmode(struct wlc_info *wlc, u8 gmode, bool config)
2224 {
2225         int ret = 0;
2226         uint i;
2227         wlc_rateset_t rs;
2228         /* Default to 54g Auto */
2229         s8 shortslot = WLC_SHORTSLOT_AUTO;      /* Advertise and use shortslot (-1/0/1 Auto/Off/On) */
2230         bool shortslot_restrict = false;        /* Restrict association to stations that support shortslot
2231                                                  */
2232         bool ofdm_basic = false;        /* Make 6, 12, and 24 basic rates */
2233         int preamble = WLC_PLCP_LONG;   /* Advertise and use short preambles (-1/0/1 Auto/Off/On) */
2234         bool preamble_restrict = false; /* Restrict association to stations that support short
2235                                          * preambles
2236                                          */
2237         struct wlcband *band;
2238
2239         /* if N-support is enabled, allow Gmode set as long as requested
2240          * Gmode is not GMODE_LEGACY_B
2241          */
2242         if (N_ENAB(wlc->pub) && gmode == GMODE_LEGACY_B)
2243                 return -ENOTSUPP;
2244
2245         /* verify that we are dealing with 2G band and grab the band pointer */
2246         if (wlc->band->bandtype == WLC_BAND_2G)
2247                 band = wlc->band;
2248         else if ((NBANDS(wlc) > 1) &&
2249                  (wlc->bandstate[OTHERBANDUNIT(wlc)]->bandtype == WLC_BAND_2G))
2250                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
2251         else
2252                 return -EINVAL;
2253
2254         /* Legacy or bust when no OFDM is supported by regulatory */
2255         if ((wlc_channel_locale_flags_in_band(wlc->cmi, band->bandunit) &
2256              WLC_NO_OFDM) && (gmode != GMODE_LEGACY_B))
2257                 return -EINVAL;
2258
2259         /* update configuration value */
2260         if (config == true)
2261                 wlc_protection_upd(wlc, WLC_PROT_G_USER, gmode);
2262
2263         /* Clear supported rates filter */
2264         memset(&wlc->sup_rates_override, 0, sizeof(wlc_rateset_t));
2265
2266         /* Clear rateset override */
2267         memset(&rs, 0, sizeof(wlc_rateset_t));
2268
2269         switch (gmode) {
2270         case GMODE_LEGACY_B:
2271                 shortslot = WLC_SHORTSLOT_OFF;
2272                 wlc_rateset_copy(&gphy_legacy_rates, &rs);
2273
2274                 break;
2275
2276         case GMODE_LRS:
2277                 if (AP_ENAB(wlc->pub))
2278                         wlc_rateset_copy(&cck_rates, &wlc->sup_rates_override);
2279                 break;
2280
2281         case GMODE_AUTO:
2282                 /* Accept defaults */
2283                 break;
2284
2285         case GMODE_ONLY:
2286                 ofdm_basic = true;
2287                 preamble = WLC_PLCP_SHORT;
2288                 preamble_restrict = true;
2289                 break;
2290
2291         case GMODE_PERFORMANCE:
2292                 if (AP_ENAB(wlc->pub))  /* Put all rates into the Supported Rates element */
2293                         wlc_rateset_copy(&cck_ofdm_rates,
2294                                          &wlc->sup_rates_override);
2295
2296                 shortslot = WLC_SHORTSLOT_ON;
2297                 shortslot_restrict = true;
2298                 ofdm_basic = true;
2299                 preamble = WLC_PLCP_SHORT;
2300                 preamble_restrict = true;
2301                 break;
2302
2303         default:
2304                 /* Error */
2305                 wiphy_err(wlc->wiphy, "wl%d: %s: invalid gmode %d\n",
2306                           wlc->pub->unit, __func__, gmode);
2307                 return -ENOTSUPP;
2308         }
2309
2310         /*
2311          * If we are switching to gmode == GMODE_LEGACY_B,
2312          * clean up rate info that may refer to OFDM rates.
2313          */
2314         if ((gmode == GMODE_LEGACY_B) && (band->gmode != GMODE_LEGACY_B)) {
2315                 band->gmode = gmode;
2316                 if (band->rspec_override && !IS_CCK(band->rspec_override)) {
2317                         band->rspec_override = 0;
2318                         wlc_reprate_init(wlc);
2319                 }
2320                 if (band->mrspec_override && !IS_CCK(band->mrspec_override)) {
2321                         band->mrspec_override = 0;
2322                 }
2323         }
2324
2325         band->gmode = gmode;
2326
2327         wlc->shortslot_override = shortslot;
2328
2329         if (AP_ENAB(wlc->pub)) {
2330                 /* wlc->ap->shortslot_restrict = shortslot_restrict; */
2331                 wlc->PLCPHdr_override =
2332                     (preamble !=
2333                      WLC_PLCP_LONG) ? WLC_PLCP_SHORT : WLC_PLCP_AUTO;
2334         }
2335
2336         if ((AP_ENAB(wlc->pub) && preamble != WLC_PLCP_LONG)
2337             || preamble == WLC_PLCP_SHORT)
2338                 wlc->default_bss->capability |= WLAN_CAPABILITY_SHORT_PREAMBLE;
2339         else
2340                 wlc->default_bss->capability &= ~WLAN_CAPABILITY_SHORT_PREAMBLE;
2341
2342         /* Update shortslot capability bit for AP and IBSS */
2343         if ((AP_ENAB(wlc->pub) && shortslot == WLC_SHORTSLOT_AUTO) ||
2344             shortslot == WLC_SHORTSLOT_ON)
2345                 wlc->default_bss->capability |= WLAN_CAPABILITY_SHORT_SLOT_TIME;
2346         else
2347                 wlc->default_bss->capability &=
2348                                         ~WLAN_CAPABILITY_SHORT_SLOT_TIME;
2349
2350         /* Use the default 11g rateset */
2351         if (!rs.count)
2352                 wlc_rateset_copy(&cck_ofdm_rates, &rs);
2353
2354         if (ofdm_basic) {
2355                 for (i = 0; i < rs.count; i++) {
2356                         if (rs.rates[i] == WLC_RATE_6M
2357                             || rs.rates[i] == WLC_RATE_12M
2358                             || rs.rates[i] == WLC_RATE_24M)
2359                                 rs.rates[i] |= WLC_RATE_FLAG;
2360                 }
2361         }
2362
2363         /* Set default bss rateset */
2364         wlc->default_bss->rateset.count = rs.count;
2365         memcpy(wlc->default_bss->rateset.rates, rs.rates, 
2366                sizeof(wlc->default_bss->rateset.rates));
2367
2368         return ret;
2369 }
2370
2371 static int wlc_nmode_validate(struct wlc_info *wlc, s32 nmode)
2372 {
2373         int err = 0;
2374
2375         switch (nmode) {
2376
2377         case OFF:
2378                 break;
2379
2380         case AUTO:
2381         case WL_11N_2x2:
2382         case WL_11N_3x3:
2383                 if (!(WLC_PHY_11N_CAP(wlc->band)))
2384                         err = -EINVAL;
2385                 break;
2386
2387         default:
2388                 err = -EINVAL;
2389                 break;
2390         }
2391
2392         return err;
2393 }
2394
2395 int wlc_set_nmode(struct wlc_info *wlc, s32 nmode)
2396 {
2397         uint i;
2398         int err;
2399
2400         err = wlc_nmode_validate(wlc, nmode);
2401         if (err)
2402                 return err;
2403
2404         switch (nmode) {
2405         case OFF:
2406                 wlc->pub->_n_enab = OFF;
2407                 wlc->default_bss->flags &= ~WLC_BSS_HT;
2408                 /* delete the mcs rates from the default and hw ratesets */
2409                 wlc_rateset_mcs_clear(&wlc->default_bss->rateset);
2410                 for (i = 0; i < NBANDS(wlc); i++) {
2411                         memset(wlc->bandstate[i]->hw_rateset.mcs, 0,
2412                                MCSSET_LEN);
2413                         if (IS_MCS(wlc->band->rspec_override)) {
2414                                 wlc->bandstate[i]->rspec_override = 0;
2415                                 wlc_reprate_init(wlc);
2416                         }
2417                         if (IS_MCS(wlc->band->mrspec_override))
2418                                 wlc->bandstate[i]->mrspec_override = 0;
2419                 }
2420                 break;
2421
2422         case AUTO:
2423                 if (wlc->stf->txstreams == WL_11N_3x3)
2424                         nmode = WL_11N_3x3;
2425                 else
2426                         nmode = WL_11N_2x2;
2427         case WL_11N_2x2:
2428         case WL_11N_3x3:
2429                 /* force GMODE_AUTO if NMODE is ON */
2430                 wlc_set_gmode(wlc, GMODE_AUTO, true);
2431                 if (nmode == WL_11N_3x3)
2432                         wlc->pub->_n_enab = SUPPORT_HT;
2433                 else
2434                         wlc->pub->_n_enab = SUPPORT_11N;
2435                 wlc->default_bss->flags |= WLC_BSS_HT;
2436                 /* add the mcs rates to the default and hw ratesets */
2437                 wlc_rateset_mcs_build(&wlc->default_bss->rateset,
2438                                       wlc->stf->txstreams);
2439                 for (i = 0; i < NBANDS(wlc); i++)
2440                         memcpy(wlc->bandstate[i]->hw_rateset.mcs,
2441                                wlc->default_bss->rateset.mcs, MCSSET_LEN);
2442                 break;
2443
2444         default:
2445                 break;
2446         }
2447
2448         return err;
2449 }
2450
2451 static int wlc_set_rateset(struct wlc_info *wlc, wlc_rateset_t *rs_arg)
2452 {
2453         wlc_rateset_t rs, new;
2454         uint bandunit;
2455
2456         memcpy(&rs, rs_arg, sizeof(wlc_rateset_t));
2457
2458         /* check for bad count value */
2459         if ((rs.count == 0) || (rs.count > WLC_NUMRATES))
2460                 return -EINVAL;
2461
2462         /* try the current band */
2463         bandunit = wlc->band->bandunit;
2464         memcpy(&new, &rs, sizeof(wlc_rateset_t));
2465         if (wlc_rate_hwrs_filter_sort_validate
2466             (&new, &wlc->bandstate[bandunit]->hw_rateset, true,
2467              wlc->stf->txstreams))
2468                 goto good;
2469
2470         /* try the other band */
2471         if (IS_MBAND_UNLOCKED(wlc)) {
2472                 bandunit = OTHERBANDUNIT(wlc);
2473                 memcpy(&new, &rs, sizeof(wlc_rateset_t));
2474                 if (wlc_rate_hwrs_filter_sort_validate(&new,
2475                                                        &wlc->
2476                                                        bandstate[bandunit]->
2477                                                        hw_rateset, true,
2478                                                        wlc->stf->txstreams))
2479                         goto good;
2480         }
2481
2482         return -EBADE;
2483
2484  good:
2485         /* apply new rateset */
2486         memcpy(&wlc->default_bss->rateset, &new, sizeof(wlc_rateset_t));
2487         memcpy(&wlc->bandstate[bandunit]->defrateset, &new,
2488                sizeof(wlc_rateset_t));
2489         return 0;
2490 }
2491
2492 /* simplified integer set interface for common ioctl handler */
2493 int wlc_set(struct wlc_info *wlc, int cmd, int arg)
2494 {
2495         return wlc_ioctl(wlc, cmd, (void *)&arg, sizeof(arg), NULL);
2496 }
2497
2498 /* simplified integer get interface for common ioctl handler */
2499 int wlc_get(struct wlc_info *wlc, int cmd, int *arg)
2500 {
2501         return wlc_ioctl(wlc, cmd, arg, sizeof(int), NULL);
2502 }
2503
2504 static void wlc_ofdm_rateset_war(struct wlc_info *wlc)
2505 {
2506         u8 r;
2507         bool war = false;
2508
2509         if (wlc->cfg->associated)
2510                 r = wlc->cfg->current_bss->rateset.rates[0];
2511         else
2512                 r = wlc->default_bss->rateset.rates[0];
2513
2514         wlc_phy_ofdm_rateset_war(wlc->band->pi, war);
2515
2516         return;
2517 }
2518
2519 int
2520 wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
2521           struct wlc_if *wlcif)
2522 {
2523         return _wlc_ioctl(wlc, cmd, arg, len, wlcif);
2524 }
2525
2526 /* common ioctl handler. return: 0=ok, -1=error, positive=particular error */
2527 static int
2528 _wlc_ioctl(struct wlc_info *wlc, int cmd, void *arg, int len,
2529            struct wlc_if *wlcif)
2530 {
2531         int val, *pval;
2532         bool bool_val;
2533         int bcmerror;
2534         d11regs_t *regs;
2535         struct scb *nextscb;
2536         bool ta_ok;
2537         uint band;
2538         struct wlc_bsscfg *bsscfg;
2539         wlc_bss_info_t *current_bss;
2540
2541         /* update bsscfg pointer */
2542         bsscfg = wlc->cfg;
2543         current_bss = bsscfg->current_bss;
2544
2545         /* initialize the following to get rid of compiler warning */
2546         nextscb = NULL;
2547         ta_ok = false;
2548         band = 0;
2549
2550         /* If the device is turned off, then it's not "removed" */
2551         if (!wlc->pub->hw_off && DEVICEREMOVED(wlc)) {
2552                 wiphy_err(wlc->wiphy, "wl%d: %s: dead chip\n", wlc->pub->unit,
2553                           __func__);
2554                 brcms_down(wlc->wl);
2555                 return -EBADE;
2556         }
2557
2558         /* default argument is generic integer */
2559         pval = arg ? (int *)arg:NULL;
2560
2561         /* This will prevent the misaligned access */
2562         if (pval && (u32) len >= sizeof(val))
2563                 memcpy(&val, pval, sizeof(val));
2564         else
2565                 val = 0;
2566
2567         /* bool conversion to avoid duplication below */
2568         bool_val = val != 0;
2569         bcmerror = 0;
2570         regs = wlc->regs;
2571
2572         if ((arg == NULL) || (len <= 0)) {
2573                 wiphy_err(wlc->wiphy, "wl%d: %s: Command %d needs arguments\n",
2574                           wlc->pub->unit, __func__, cmd);
2575                 bcmerror = -EINVAL;
2576                 goto done;
2577         }
2578
2579         switch (cmd) {
2580
2581         case WLC_SET_CHANNEL:{
2582                         chanspec_t chspec = CH20MHZ_CHSPEC(val);
2583
2584                         if (val < 0 || val > MAXCHANNEL) {
2585                                 bcmerror = -EINVAL;
2586                                 break;
2587                         }
2588
2589                         if (!wlc_valid_chanspec_db(wlc->cmi, chspec)) {
2590                                 bcmerror = -EINVAL;
2591                                 break;
2592                         }
2593
2594                         if (!wlc->pub->up && IS_MBAND_UNLOCKED(wlc)) {
2595                                 if (wlc->band->bandunit !=
2596                                     CHSPEC_WLCBANDUNIT(chspec))
2597                                         wlc->bandinit_pending = true;
2598                                 else
2599                                         wlc->bandinit_pending = false;
2600                         }
2601
2602                         wlc->default_bss->chanspec = chspec;
2603                         /* wlc_BSSinit() will sanitize the rateset before using it.. */
2604                         if (wlc->pub->up &&
2605                             (WLC_BAND_PI_RADIO_CHANSPEC != chspec)) {
2606                                 wlc_set_home_chanspec(wlc, chspec);
2607                                 wlc_suspend_mac_and_wait(wlc);
2608                                 wlc_set_chanspec(wlc, chspec);
2609                                 wlc_enable_mac(wlc);
2610                         }
2611                         break;
2612                 }
2613
2614         case WLC_SET_SRL:
2615                 if (val >= 1 && val <= RETRY_SHORT_MAX) {
2616                         int ac;
2617                         wlc->SRL = (u16) val;
2618
2619                         wlc_bmac_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
2620
2621                         for (ac = 0; ac < AC_COUNT; ac++) {
2622                                 WLC_WME_RETRY_SHORT_SET(wlc, ac, wlc->SRL);
2623                         }
2624                         wlc_wme_retries_write(wlc);
2625                 } else
2626                         bcmerror = -EINVAL;
2627                 break;
2628
2629         case WLC_SET_LRL:
2630                 if (val >= 1 && val <= 255) {
2631                         int ac;
2632                         wlc->LRL = (u16) val;
2633
2634                         wlc_bmac_retrylimit_upd(wlc->hw, wlc->SRL, wlc->LRL);
2635
2636                         for (ac = 0; ac < AC_COUNT; ac++) {
2637                                 WLC_WME_RETRY_LONG_SET(wlc, ac, wlc->LRL);
2638                         }
2639                         wlc_wme_retries_write(wlc);
2640                 } else
2641                         bcmerror = -EINVAL;
2642                 break;
2643
2644         case WLC_GET_CURR_RATESET:{
2645                         wl_rateset_t *ret_rs = (wl_rateset_t *) arg;
2646                         wlc_rateset_t *rs;
2647
2648                         if (wlc->pub->associated)
2649                                 rs = &current_bss->rateset;
2650                         else
2651                                 rs = &wlc->default_bss->rateset;
2652
2653                         if (len < (int)(rs->count + sizeof(rs->count))) {
2654                                 bcmerror = -EOVERFLOW;
2655                                 break;
2656                         }
2657
2658                         /* Copy only legacy rateset section */
2659                         ret_rs->count = rs->count;
2660                         memcpy(&ret_rs->rates, &rs->rates, rs->count);
2661                         break;
2662                 }
2663
2664         case WLC_SET_RATESET:{
2665                         wlc_rateset_t rs;
2666                         wl_rateset_t *in_rs = (wl_rateset_t *) arg;
2667
2668                         if (len < (int)(in_rs->count + sizeof(in_rs->count))) {
2669                                 bcmerror = -EOVERFLOW;
2670                                 break;
2671                         }
2672
2673                         if (in_rs->count > WLC_NUMRATES) {
2674                                 bcmerror = -ENOBUFS;
2675                                 break;
2676                         }
2677
2678                         memset(&rs, 0, sizeof(wlc_rateset_t));
2679
2680                         /* Copy only legacy rateset section */
2681                         rs.count = in_rs->count;
2682                         memcpy(&rs.rates, &in_rs->rates, rs.count);
2683
2684                         /* merge rateset coming in with the current mcsset */
2685                         if (N_ENAB(wlc->pub)) {
2686                                 if (bsscfg->associated)
2687                                         memcpy(rs.mcs,
2688                                                &current_bss->rateset.mcs[0],
2689                                                MCSSET_LEN);
2690                                 else
2691                                         memcpy(rs.mcs,
2692                                                &wlc->default_bss->rateset.mcs[0],
2693                                                MCSSET_LEN);
2694                         }
2695
2696                         bcmerror = wlc_set_rateset(wlc, &rs);
2697
2698                         if (!bcmerror)
2699                                 wlc_ofdm_rateset_war(wlc);
2700
2701                         break;
2702                 }
2703
2704         case WLC_SET_BCNPRD:
2705                 /* range [1, 0xffff] */
2706                 if (val >= DOT11_MIN_BEACON_PERIOD
2707                     && val <= DOT11_MAX_BEACON_PERIOD) {
2708                         wlc->default_bss->beacon_period = (u16) val;
2709                 } else
2710                         bcmerror = -EINVAL;
2711                 break;
2712
2713         case WLC_GET_PHYLIST:
2714                 {
2715                         unsigned char *cp = arg;
2716                         if (len < 3) {
2717                                 bcmerror = -EOVERFLOW;
2718                                 break;
2719                         }
2720
2721                         if (WLCISNPHY(wlc->band)) {
2722                                 *cp++ = 'n';
2723                         } else if (WLCISLCNPHY(wlc->band)) {
2724                                 *cp++ = 'c';
2725                         } else if (WLCISSSLPNPHY(wlc->band)) {
2726                                 *cp++ = 's';
2727                         }
2728                         *cp = '\0';
2729                         break;
2730                 }
2731
2732         case WLC_SET_SHORTSLOT_OVERRIDE:
2733                 if ((val != WLC_SHORTSLOT_AUTO) &&
2734                     (val != WLC_SHORTSLOT_OFF) && (val != WLC_SHORTSLOT_ON)) {
2735                         bcmerror = -EINVAL;
2736                         break;
2737                 }
2738
2739                 wlc->shortslot_override = (s8) val;
2740
2741                 /* shortslot is an 11g feature, so no more work if we are
2742                  * currently on the 5G band
2743                  */
2744                 if (BAND_5G(wlc->band->bandtype))
2745                         break;
2746
2747                 if (wlc->pub->up && wlc->pub->associated) {
2748                         /* let watchdog or beacon processing update shortslot */
2749                 } else if (wlc->pub->up) {
2750                         /* unassociated shortslot is off */
2751                         wlc_switch_shortslot(wlc, false);
2752                 } else {
2753                         /* driver is down, so just update the wlc_info value */
2754                         if (wlc->shortslot_override == WLC_SHORTSLOT_AUTO) {
2755                                 wlc->shortslot = false;
2756                         } else {
2757                                 wlc->shortslot =
2758                                     (wlc->shortslot_override ==
2759                                      WLC_SHORTSLOT_ON);
2760                         }
2761                 }
2762
2763                 break;
2764
2765         }
2766  done:
2767
2768         if (bcmerror)
2769                 wlc->pub->bcmerror = bcmerror;
2770
2771         return bcmerror;
2772 }
2773
2774 /*
2775  * register watchdog and down handlers.
2776  */
2777 int wlc_module_register(struct wlc_pub *pub,
2778                         const char *name, void *hdl,
2779                         watchdog_fn_t w_fn, down_fn_t d_fn)
2780 {
2781         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
2782         int i;
2783
2784         /* find an empty entry and just add, no duplication check! */
2785         for (i = 0; i < WLC_MAXMODULES; i++) {
2786                 if (wlc->modulecb[i].name[0] == '\0') {
2787                         strncpy(wlc->modulecb[i].name, name,
2788                                 sizeof(wlc->modulecb[i].name) - 1);
2789                         wlc->modulecb[i].hdl = hdl;
2790                         wlc->modulecb[i].watchdog_fn = w_fn;
2791                         wlc->modulecb[i].down_fn = d_fn;
2792                         return 0;
2793                 }
2794         }
2795
2796         return -ENOSR;
2797 }
2798
2799 /* unregister module callbacks */
2800 int wlc_module_unregister(struct wlc_pub *pub, const char *name, void *hdl)
2801 {
2802         struct wlc_info *wlc = (struct wlc_info *) pub->wlc;
2803         int i;
2804
2805         if (wlc == NULL)
2806                 return -ENODATA;
2807
2808         for (i = 0; i < WLC_MAXMODULES; i++) {
2809                 if (!strcmp(wlc->modulecb[i].name, name) &&
2810                     (wlc->modulecb[i].hdl == hdl)) {
2811                         memset(&wlc->modulecb[i], 0, sizeof(struct modulecb));
2812                         return 0;
2813                 }
2814         }
2815
2816         /* table not found! */
2817         return -ENODATA;
2818 }
2819
2820 /* Write WME tunable parameters for retransmit/max rate from wlc struct to ucode */
2821 static void wlc_wme_retries_write(struct wlc_info *wlc)
2822 {
2823         int ac;
2824
2825         /* Need clock to do this */
2826         if (!wlc->clk)
2827                 return;
2828
2829         for (ac = 0; ac < AC_COUNT; ac++) {
2830                 wlc_write_shm(wlc, M_AC_TXLMT_ADDR(ac), wlc->wme_retries[ac]);
2831         }
2832 }
2833
2834 #ifdef BCMDBG
2835 static const char *supr_reason[] = {
2836         "None", "PMQ Entry", "Flush request",
2837         "Previous frag failure", "Channel mismatch",
2838         "Lifetime Expiry", "Underflow"
2839 };
2840
2841 static void wlc_print_txs_status(u16 s)
2842 {
2843         printk(KERN_DEBUG "[15:12]  %d  frame attempts\n",
2844                (s & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT);
2845         printk(KERN_DEBUG " [11:8]  %d  rts attempts\n",
2846                (s & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT);
2847         printk(KERN_DEBUG "    [7]  %d  PM mode indicated\n",
2848                ((s & TX_STATUS_PMINDCTD) ? 1 : 0));
2849         printk(KERN_DEBUG "    [6]  %d  intermediate status\n",
2850                ((s & TX_STATUS_INTERMEDIATE) ? 1 : 0));
2851         printk(KERN_DEBUG "    [5]  %d  AMPDU\n",
2852                (s & TX_STATUS_AMPDU) ? 1 : 0);
2853         printk(KERN_DEBUG "  [4:2]  %d  Frame Suppressed Reason (%s)\n",
2854                ((s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT),
2855                supr_reason[(s & TX_STATUS_SUPR_MASK) >> TX_STATUS_SUPR_SHIFT]);
2856         printk(KERN_DEBUG "    [1]  %d  acked\n",
2857                ((s & TX_STATUS_ACK_RCV) ? 1 : 0));
2858 }
2859 #endif                          /* BCMDBG */
2860
2861 void wlc_print_txstatus(tx_status_t *txs)
2862 {
2863 #if defined(BCMDBG)
2864         u16 s = txs->status;
2865         u16 ackphyrxsh = txs->ackphyrxsh;
2866
2867         printk(KERN_DEBUG "\ntxpkt (MPDU) Complete\n");
2868
2869         printk(KERN_DEBUG "FrameID: %04x   ", txs->frameid);
2870         printk(KERN_DEBUG "TxStatus: %04x", s);
2871         printk(KERN_DEBUG "\n");
2872
2873         wlc_print_txs_status(s);
2874
2875         printk(KERN_DEBUG "LastTxTime: %04x ", txs->lasttxtime);
2876         printk(KERN_DEBUG "Seq: %04x ", txs->sequence);
2877         printk(KERN_DEBUG "PHYTxStatus: %04x ", txs->phyerr);
2878         printk(KERN_DEBUG "RxAckRSSI: %04x ",
2879                (ackphyrxsh & PRXS1_JSSI_MASK) >> PRXS1_JSSI_SHIFT);
2880         printk(KERN_DEBUG "RxAckSQ: %04x",
2881                (ackphyrxsh & PRXS1_SQ_MASK) >> PRXS1_SQ_SHIFT);
2882         printk(KERN_DEBUG "\n");
2883 #endif                          /* defined(BCMDBG) */
2884 }
2885
2886 void wlc_statsupd(struct wlc_info *wlc)
2887 {
2888         int i;
2889         macstat_t macstats;
2890 #ifdef BCMDBG
2891         u16 delta;
2892         u16 rxf0ovfl;
2893         u16 txfunfl[NFIFO];
2894 #endif                          /* BCMDBG */
2895
2896         /* if driver down, make no sense to update stats */
2897         if (!wlc->pub->up)
2898                 return;
2899
2900 #ifdef BCMDBG
2901         /* save last rx fifo 0 overflow count */
2902         rxf0ovfl = wlc->core->macstat_snapshot->rxf0ovfl;
2903
2904         /* save last tx fifo  underflow count */
2905         for (i = 0; i < NFIFO; i++)
2906                 txfunfl[i] = wlc->core->macstat_snapshot->txfunfl[i];
2907 #endif                          /* BCMDBG */
2908
2909         /* Read mac stats from contiguous shared memory */
2910         wlc_bmac_copyfrom_shm(wlc->hw, M_UCODE_MACSTAT,
2911                               &macstats, sizeof(macstat_t));
2912
2913 #ifdef BCMDBG
2914         /* check for rx fifo 0 overflow */
2915         delta = (u16) (wlc->core->macstat_snapshot->rxf0ovfl - rxf0ovfl);
2916         if (delta)
2917                 wiphy_err(wlc->wiphy, "wl%d: %u rx fifo 0 overflows!\n",
2918                           wlc->pub->unit, delta);
2919
2920         /* check for tx fifo underflows */
2921         for (i = 0; i < NFIFO; i++) {
2922                 delta =
2923                     (u16) (wlc->core->macstat_snapshot->txfunfl[i] -
2924                               txfunfl[i]);
2925                 if (delta)
2926                         wiphy_err(wlc->wiphy, "wl%d: %u tx fifo %d underflows!"
2927                                   "\n", wlc->pub->unit, delta, i);
2928         }
2929 #endif                          /* BCMDBG */
2930
2931         /* merge counters from dma module */
2932         for (i = 0; i < NFIFO; i++) {
2933                 if (wlc->hw->di[i]) {
2934                         dma_counterreset(wlc->hw->di[i]);
2935                 }
2936         }
2937 }
2938
2939 bool wlc_chipmatch(u16 vendor, u16 device)
2940 {
2941         if (vendor != PCI_VENDOR_ID_BROADCOM) {
2942                 pr_err("wlc_chipmatch: unknown vendor id %04x\n", vendor);
2943                 return false;
2944         }
2945
2946         if (device == BCM43224_D11N_ID_VEN1)
2947                 return true;
2948         if ((device == BCM43224_D11N_ID) || (device == BCM43225_D11N2G_ID))
2949                 return true;
2950         if (device == BCM4313_D11N2G_ID)
2951                 return true;
2952         if ((device == BCM43236_D11N_ID) || (device == BCM43236_D11N2G_ID))
2953                 return true;
2954
2955         pr_err("wlc_chipmatch: unknown device id %04x\n", device);
2956         return false;
2957 }
2958
2959 #if defined(BCMDBG)
2960 void wlc_print_txdesc(d11txh_t *txh)
2961 {
2962         u16 mtcl = le16_to_cpu(txh->MacTxControlLow);
2963         u16 mtch = le16_to_cpu(txh->MacTxControlHigh);
2964         u16 mfc = le16_to_cpu(txh->MacFrameControl);
2965         u16 tfest = le16_to_cpu(txh->TxFesTimeNormal);
2966         u16 ptcw = le16_to_cpu(txh->PhyTxControlWord);
2967         u16 ptcw_1 = le16_to_cpu(txh->PhyTxControlWord_1);
2968         u16 ptcw_1_Fbr = le16_to_cpu(txh->PhyTxControlWord_1_Fbr);
2969         u16 ptcw_1_Rts = le16_to_cpu(txh->PhyTxControlWord_1_Rts);
2970         u16 ptcw_1_FbrRts = le16_to_cpu(txh->PhyTxControlWord_1_FbrRts);
2971         u16 mainrates = le16_to_cpu(txh->MainRates);
2972         u16 xtraft = le16_to_cpu(txh->XtraFrameTypes);
2973         u8 *iv = txh->IV;
2974         u8 *ra = txh->TxFrameRA;
2975         u16 tfestfb = le16_to_cpu(txh->TxFesTimeFallback);
2976         u8 *rtspfb = txh->RTSPLCPFallback;
2977         u16 rtsdfb = le16_to_cpu(txh->RTSDurFallback);
2978         u8 *fragpfb = txh->FragPLCPFallback;
2979         u16 fragdfb = le16_to_cpu(txh->FragDurFallback);
2980         u16 mmodelen = le16_to_cpu(txh->MModeLen);
2981         u16 mmodefbrlen = le16_to_cpu(txh->MModeFbrLen);
2982         u16 tfid = le16_to_cpu(txh->TxFrameID);
2983         u16 txs = le16_to_cpu(txh->TxStatus);
2984         u16 mnmpdu = le16_to_cpu(txh->MaxNMpdus);
2985         u16 mabyte = le16_to_cpu(txh->MaxABytes_MRT);
2986         u16 mabyte_f = le16_to_cpu(txh->MaxABytes_FBR);
2987         u16 mmbyte = le16_to_cpu(txh->MinMBytes);
2988
2989         u8 *rtsph = txh->RTSPhyHeader;
2990         struct ieee80211_rts rts = txh->rts_frame;
2991         char hexbuf[256];
2992
2993         /* add plcp header along with txh descriptor */
2994         printk(KERN_DEBUG "Raw TxDesc + plcp header:\n");
2995         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
2996                              txh, sizeof(d11txh_t) + 48);
2997
2998         printk(KERN_DEBUG "TxCtlLow: %04x ", mtcl);
2999         printk(KERN_DEBUG "TxCtlHigh: %04x ", mtch);
3000         printk(KERN_DEBUG "FC: %04x ", mfc);
3001         printk(KERN_DEBUG "FES Time: %04x\n", tfest);
3002         printk(KERN_DEBUG "PhyCtl: %04x%s ", ptcw,
3003                (ptcw & PHY_TXC_SHORT_HDR) ? " short" : "");
3004         printk(KERN_DEBUG "PhyCtl_1: %04x ", ptcw_1);
3005         printk(KERN_DEBUG "PhyCtl_1_Fbr: %04x\n", ptcw_1_Fbr);
3006         printk(KERN_DEBUG "PhyCtl_1_Rts: %04x ", ptcw_1_Rts);
3007         printk(KERN_DEBUG "PhyCtl_1_Fbr_Rts: %04x\n", ptcw_1_FbrRts);
3008         printk(KERN_DEBUG "MainRates: %04x ", mainrates);
3009         printk(KERN_DEBUG "XtraFrameTypes: %04x ", xtraft);
3010         printk(KERN_DEBUG "\n");
3011
3012         brcmu_format_hex(hexbuf, iv, sizeof(txh->IV));
3013         printk(KERN_DEBUG "SecIV:       %s\n", hexbuf);
3014         brcmu_format_hex(hexbuf, ra, sizeof(txh->TxFrameRA));
3015         printk(KERN_DEBUG "RA:          %s\n", hexbuf);
3016
3017         printk(KERN_DEBUG "Fb FES Time: %04x ", tfestfb);
3018         brcmu_format_hex(hexbuf, rtspfb, sizeof(txh->RTSPLCPFallback));
3019         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
3020         printk(KERN_DEBUG "RTS DUR: %04x ", rtsdfb);
3021         brcmu_format_hex(hexbuf, fragpfb, sizeof(txh->FragPLCPFallback));
3022         printk(KERN_DEBUG "PLCP: %s ", hexbuf);
3023         printk(KERN_DEBUG "DUR: %04x", fragdfb);
3024         printk(KERN_DEBUG "\n");
3025
3026         printk(KERN_DEBUG "MModeLen: %04x ", mmodelen);
3027         printk(KERN_DEBUG "MModeFbrLen: %04x\n", mmodefbrlen);
3028
3029         printk(KERN_DEBUG "FrameID:     %04x\n", tfid);
3030         printk(KERN_DEBUG "TxStatus:    %04x\n", txs);
3031
3032         printk(KERN_DEBUG "MaxNumMpdu:  %04x\n", mnmpdu);
3033         printk(KERN_DEBUG "MaxAggbyte:  %04x\n", mabyte);
3034         printk(KERN_DEBUG "MaxAggbyte_fb:  %04x\n", mabyte_f);
3035         printk(KERN_DEBUG "MinByte:     %04x\n", mmbyte);
3036
3037         brcmu_format_hex(hexbuf, rtsph, sizeof(txh->RTSPhyHeader));
3038         printk(KERN_DEBUG "RTS PLCP: %s ", hexbuf);
3039         brcmu_format_hex(hexbuf, (u8 *) &rts, sizeof(txh->rts_frame));
3040         printk(KERN_DEBUG "RTS Frame: %s", hexbuf);
3041         printk(KERN_DEBUG "\n");
3042 }
3043 #endif                          /* defined(BCMDBG) */
3044
3045 #if defined(BCMDBG)
3046 void wlc_print_rxh(d11rxhdr_t *rxh)
3047 {
3048         u16 len = rxh->RxFrameSize;
3049         u16 phystatus_0 = rxh->PhyRxStatus_0;
3050         u16 phystatus_1 = rxh->PhyRxStatus_1;
3051         u16 phystatus_2 = rxh->PhyRxStatus_2;
3052         u16 phystatus_3 = rxh->PhyRxStatus_3;
3053         u16 macstatus1 = rxh->RxStatus1;
3054         u16 macstatus2 = rxh->RxStatus2;
3055         char flagstr[64];
3056         char lenbuf[20];
3057         static const struct brcmu_bit_desc macstat_flags[] = {
3058                 {RXS_FCSERR, "FCSErr"},
3059                 {RXS_RESPFRAMETX, "Reply"},
3060                 {RXS_PBPRES, "PADDING"},
3061                 {RXS_DECATMPT, "DeCr"},
3062                 {RXS_DECERR, "DeCrErr"},
3063                 {RXS_BCNSENT, "Bcn"},
3064                 {0, NULL}
3065         };
3066
3067         printk(KERN_DEBUG "Raw RxDesc:\n");
3068         print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, rxh, sizeof(d11rxhdr_t));
3069
3070         brcmu_format_flags(macstat_flags, macstatus1, flagstr, 64);
3071
3072         snprintf(lenbuf, sizeof(lenbuf), "0x%x", len);
3073
3074         printk(KERN_DEBUG "RxFrameSize:     %6s (%d)%s\n", lenbuf, len,
3075                (rxh->PhyRxStatus_0 & PRXS0_SHORTH) ? " short preamble" : "");
3076         printk(KERN_DEBUG "RxPHYStatus:     %04x %04x %04x %04x\n",
3077                phystatus_0, phystatus_1, phystatus_2, phystatus_3);
3078         printk(KERN_DEBUG "RxMACStatus:     %x %s\n", macstatus1, flagstr);
3079         printk(KERN_DEBUG "RXMACaggtype:    %x\n",
3080                (macstatus2 & RXS_AGGTYPE_MASK));
3081         printk(KERN_DEBUG "RxTSFTime:       %04x\n", rxh->RxTSFTime);
3082 }
3083 #endif                          /* defined(BCMDBG) */
3084
3085 static u16 wlc_rate_shm_offset(struct wlc_info *wlc, u8 rate)
3086 {
3087         return wlc_bmac_rate_shm_offset(wlc->hw, rate);
3088 }
3089
3090 /* Callback for device removed */
3091
3092 /*
3093  * Attempts to queue a packet onto a multiple-precedence queue,
3094  * if necessary evicting a lower precedence packet from the queue.
3095  *
3096  * 'prec' is the precedence number that has already been mapped
3097  * from the packet priority.
3098  *
3099  * Returns true if packet consumed (queued), false if not.
3100  */
3101 bool
3102 wlc_prec_enq(struct wlc_info *wlc, struct pktq *q, void *pkt, int prec)
3103 {
3104         return wlc_prec_enq_head(wlc, q, pkt, prec, false);
3105 }
3106
3107 bool
3108 wlc_prec_enq_head(struct wlc_info *wlc, struct pktq *q, struct sk_buff *pkt,
3109                   int prec, bool head)
3110 {
3111         struct sk_buff *p;
3112         int eprec = -1;         /* precedence to evict from */
3113
3114         /* Determine precedence from which to evict packet, if any */
3115         if (pktq_pfull(q, prec))
3116                 eprec = prec;
3117         else if (pktq_full(q)) {
3118                 p = brcmu_pktq_peek_tail(q, &eprec);
3119                 if (eprec > prec) {
3120                         wiphy_err(wlc->wiphy, "%s: Failing: eprec %d > prec %d"
3121                                   "\n", __func__, eprec, prec);
3122                         return false;
3123                 }
3124         }
3125
3126         /* Evict if needed */
3127         if (eprec >= 0) {
3128                 bool discard_oldest;
3129
3130                 discard_oldest = AC_BITMAP_TST(wlc->wme_dp, eprec);
3131
3132                 /* Refuse newer packet unless configured to discard oldest */
3133                 if (eprec == prec && !discard_oldest) {
3134                         wiphy_err(wlc->wiphy, "%s: No where to go, prec == %d"
3135                                   "\n", __func__, prec);
3136                         return false;
3137                 }
3138
3139                 /* Evict packet according to discard policy */
3140                 p = discard_oldest ? brcmu_pktq_pdeq(q, eprec) :
3141                         brcmu_pktq_pdeq_tail(q, eprec);
3142                 brcmu_pkt_buf_free_skb(p);
3143         }
3144
3145         /* Enqueue */
3146         if (head)
3147                 p = brcmu_pktq_penq_head(q, prec, pkt);
3148         else
3149                 p = brcmu_pktq_penq(q, prec, pkt);
3150
3151         return true;
3152 }
3153
3154 void wlc_txq_enq(void *ctx, struct scb *scb, struct sk_buff *sdu,
3155                              uint prec)
3156 {
3157         struct wlc_info *wlc = (struct wlc_info *) ctx;
3158         struct wlc_txq_info *qi = wlc->pkt_queue;       /* Check me */
3159         struct pktq *q = &qi->q;
3160         int prio;
3161
3162         prio = sdu->priority;
3163
3164         if (!wlc_prec_enq(wlc, q, sdu, prec)) {
3165                 if (!EDCF_ENAB(wlc->pub)
3166                     || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL))
3167                         wiphy_err(wlc->wiphy, "wl%d: wlc_txq_enq: txq overflow"
3168                                   "\n", wlc->pub->unit);
3169
3170                 /*
3171                  * XXX we might hit this condtion in case
3172                  * packet flooding from mac80211 stack
3173                  */
3174                 brcmu_pkt_buf_free_skb(sdu);
3175         }
3176
3177         /* Check if flow control needs to be turned on after enqueuing the packet
3178          *   Don't turn on flow control if EDCF is enabled. Driver would make the decision on what
3179          *   to drop instead of relying on stack to make the right decision
3180          */
3181         if (!EDCF_ENAB(wlc->pub)
3182             || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL)) {
3183                 if (pktq_len(q) >= wlc->pub->tunables->datahiwat) {
3184                         wlc_txflowcontrol(wlc, qi, ON, ALLPRIO);
3185                 }
3186         } else if (wlc->pub->_priofc) {
3187                 if (pktq_plen(q, wlc_prio2prec_map[prio]) >=
3188                     wlc->pub->tunables->datahiwat) {
3189                         wlc_txflowcontrol(wlc, qi, ON, prio);
3190                 }
3191         }
3192 }
3193
3194 bool
3195 wlc_sendpkt_mac80211(struct wlc_info *wlc, struct sk_buff *sdu,
3196                      struct ieee80211_hw *hw)
3197 {
3198         u8 prio;
3199         uint fifo;
3200         void *pkt;
3201         struct scb *scb = &global_scb;
3202         struct ieee80211_hdr *d11_header = (struct ieee80211_hdr *)(sdu->data);
3203
3204         /* 802.11 standard requires management traffic to go at highest priority */
3205         prio = ieee80211_is_data(d11_header->frame_control) ? sdu->priority :
3206                 MAXPRIO;
3207         fifo = prio2fifo[prio];
3208         pkt = sdu;
3209         if (unlikely
3210             (wlc_d11hdrs_mac80211(wlc, hw, pkt, scb, 0, 1, fifo, 0, NULL, 0)))
3211                 return -EINVAL;
3212         wlc_txq_enq(wlc, scb, pkt, WLC_PRIO_TO_PREC(prio));
3213         wlc_send_q(wlc);
3214         return 0;
3215 }
3216
3217 void wlc_send_q(struct wlc_info *wlc)
3218 {
3219         struct sk_buff *pkt[DOT11_MAXNUMFRAGS];
3220         int prec;
3221         u16 prec_map;
3222         int err = 0, i, count;
3223         uint fifo;
3224         struct wlc_txq_info *qi = wlc->pkt_queue;
3225         struct pktq *q = &qi->q;
3226         struct ieee80211_tx_info *tx_info;
3227
3228         if (in_send_q)
3229                 return;
3230         else
3231                 in_send_q = true;
3232
3233         prec_map = wlc->tx_prec_map;
3234
3235         /* Send all the enq'd pkts that we can.
3236          * Dequeue packets with precedence with empty HW fifo only
3237          */
3238         while (prec_map && (pkt[0] = brcmu_pktq_mdeq(q, prec_map, &prec))) {
3239                 tx_info = IEEE80211_SKB_CB(pkt[0]);
3240                 if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
3241                         err = wlc_sendampdu(wlc->ampdu, qi, pkt, prec);
3242                 } else {
3243                         count = 1;
3244                         err = wlc_prep_pdu(wlc, pkt[0], &fifo);
3245                         if (!err) {
3246                                 for (i = 0; i < count; i++) {
3247                                         wlc_txfifo(wlc, fifo, pkt[i], true, 1);
3248                                 }
3249                         }
3250                 }
3251
3252                 if (err == -EBUSY) {
3253                         brcmu_pktq_penq_head(q, prec, pkt[0]);
3254                         /* If send failed due to any other reason than a change in
3255                          * HW FIFO condition, quit. Otherwise, read the new prec_map!
3256                          */
3257                         if (prec_map == wlc->tx_prec_map)
3258                                 break;
3259                         prec_map = wlc->tx_prec_map;
3260                 }
3261         }
3262
3263         /* Check if flow control needs to be turned off after sending the packet */
3264         if (!EDCF_ENAB(wlc->pub)
3265             || (wlc->pub->wlfeatureflag & WL_SWFL_FLOWCONTROL)) {
3266                 if (wlc_txflowcontrol_prio_isset(wlc, qi, ALLPRIO)
3267                     && (pktq_len(q) < wlc->pub->tunables->datahiwat / 2)) {
3268                         wlc_txflowcontrol(wlc, qi, OFF, ALLPRIO);
3269                 }
3270         } else if (wlc->pub->_priofc) {
3271                 int prio;
3272                 for (prio = MAXPRIO; prio >= 0; prio--) {
3273                         if (wlc_txflowcontrol_prio_isset(wlc, qi, prio) &&
3274                             (pktq_plen(q, wlc_prio2prec_map[prio]) <
3275                              wlc->pub->tunables->datahiwat / 2)) {
3276                                 wlc_txflowcontrol(wlc, qi, OFF, prio);
3277                         }
3278                 }
3279         }
3280         in_send_q = false;
3281 }
3282
3283 /*
3284  * bcmc_fid_generate:
3285  * Generate frame ID for a BCMC packet.  The frag field is not used
3286  * for MC frames so is used as part of the sequence number.
3287  */
3288 static inline u16
3289 bcmc_fid_generate(struct wlc_info *wlc, struct wlc_bsscfg *bsscfg,
3290                   d11txh_t *txh)
3291 {
3292         u16 frameid;
3293
3294         frameid = le16_to_cpu(txh->TxFrameID) & ~(TXFID_SEQ_MASK |
3295                                                   TXFID_QUEUE_MASK);
3296         frameid |=
3297             (((wlc->
3298                mc_fid_counter++) << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
3299             TX_BCMC_FIFO;
3300
3301         return frameid;
3302 }
3303
3304 void
3305 wlc_txfifo(struct wlc_info *wlc, uint fifo, struct sk_buff *p, bool commit,
3306            s8 txpktpend)
3307 {
3308         u16 frameid = INVALIDFID;
3309         d11txh_t *txh;
3310
3311         txh = (d11txh_t *) (p->data);
3312
3313         /* When a BC/MC frame is being committed to the BCMC fifo via DMA (NOT PIO), update
3314          * ucode or BSS info as appropriate.
3315          */
3316         if (fifo == TX_BCMC_FIFO) {
3317                 frameid = le16_to_cpu(txh->TxFrameID);
3318
3319         }
3320
3321         if (WLC_WAR16165(wlc))
3322                 wlc_war16165(wlc, true);
3323
3324
3325         /* Bump up pending count for if not using rpc. If rpc is used, this will be handled
3326          * in wlc_bmac_txfifo()
3327          */
3328         if (commit) {
3329                 TXPKTPENDINC(wlc, fifo, txpktpend);
3330                 BCMMSG(wlc->wiphy, "pktpend inc %d to %d\n",
3331                          txpktpend, TXPKTPENDGET(wlc, fifo));
3332         }
3333
3334         /* Commit BCMC sequence number in the SHM frame ID location */
3335         if (frameid != INVALIDFID)
3336                 BCMCFID(wlc, frameid);
3337
3338         if (dma_txfast(wlc->hw->di[fifo], p, commit) < 0) {
3339                 wiphy_err(wlc->wiphy, "wlc_txfifo: fatal, toss frames !!!\n");
3340         }
3341 }
3342
3343 void
3344 wlc_compute_plcp(struct wlc_info *wlc, ratespec_t rspec, uint length, u8 *plcp)
3345 {
3346         if (IS_MCS(rspec)) {
3347                 wlc_compute_mimo_plcp(rspec, length, plcp);
3348         } else if (IS_OFDM(rspec)) {
3349                 wlc_compute_ofdm_plcp(rspec, length, plcp);
3350         } else {
3351                 wlc_compute_cck_plcp(wlc, rspec, length, plcp);
3352         }
3353         return;
3354 }
3355
3356 /* Rate: 802.11 rate code, length: PSDU length in octets */
3357 static void wlc_compute_mimo_plcp(ratespec_t rspec, uint length, u8 *plcp)
3358 {
3359         u8 mcs = (u8) (rspec & RSPEC_RATE_MASK);
3360         plcp[0] = mcs;
3361         if (RSPEC_IS40MHZ(rspec) || (mcs == 32))
3362                 plcp[0] |= MIMO_PLCP_40MHZ;
3363         WLC_SET_MIMO_PLCP_LEN(plcp, length);
3364         plcp[3] = RSPEC_MIMOPLCP3(rspec);       /* rspec already holds this byte */
3365         plcp[3] |= 0x7;         /* set smoothing, not sounding ppdu & reserved */
3366         plcp[4] = 0;            /* number of extension spatial streams bit 0 & 1 */
3367         plcp[5] = 0;
3368 }
3369
3370 /* Rate: 802.11 rate code, length: PSDU length in octets */
3371 static void
3372 wlc_compute_ofdm_plcp(ratespec_t rspec, u32 length, u8 *plcp)
3373 {
3374         u8 rate_signal;
3375         u32 tmp = 0;
3376         int rate = RSPEC2RATE(rspec);
3377
3378         /* encode rate per 802.11a-1999 sec 17.3.4.1, with lsb transmitted first */
3379         rate_signal = rate_info[rate] & WLC_RATE_MASK;
3380         memset(plcp, 0, D11_PHY_HDR_LEN);
3381         D11A_PHY_HDR_SRATE((ofdm_phy_hdr_t *) plcp, rate_signal);
3382
3383         tmp = (length & 0xfff) << 5;
3384         plcp[2] |= (tmp >> 16) & 0xff;
3385         plcp[1] |= (tmp >> 8) & 0xff;
3386         plcp[0] |= tmp & 0xff;
3387
3388         return;
3389 }
3390
3391 /*
3392  * Compute PLCP, but only requires actual rate and length of pkt.
3393  * Rate is given in the driver standard multiple of 500 kbps.
3394  * le is set for 11 Mbps rate if necessary.
3395  * Broken out for PRQ.
3396  */
3397
3398 static void wlc_cck_plcp_set(struct wlc_info *wlc, int rate_500, uint length,
3399                              u8 *plcp)
3400 {
3401         u16 usec = 0;
3402         u8 le = 0;
3403
3404         switch (rate_500) {
3405         case WLC_RATE_1M:
3406                 usec = length << 3;
3407                 break;
3408         case WLC_RATE_2M:
3409                 usec = length << 2;
3410                 break;
3411         case WLC_RATE_5M5:
3412                 usec = (length << 4) / 11;
3413                 if ((length << 4) - (usec * 11) > 0)
3414                         usec++;
3415                 break;
3416         case WLC_RATE_11M:
3417                 usec = (length << 3) / 11;
3418                 if ((length << 3) - (usec * 11) > 0) {
3419                         usec++;
3420                         if ((usec * 11) - (length << 3) >= 8)
3421                                 le = D11B_PLCP_SIGNAL_LE;
3422                 }
3423                 break;
3424
3425         default:
3426                 wiphy_err(wlc->wiphy, "wlc_cck_plcp_set: unsupported rate %d"
3427                           "\n", rate_500);
3428                 rate_500 = WLC_RATE_1M;
3429                 usec = length << 3;
3430                 break;
3431         }
3432         /* PLCP signal byte */
3433         plcp[0] = rate_500 * 5; /* r (500kbps) * 5 == r (100kbps) */
3434         /* PLCP service byte */
3435         plcp[1] = (u8) (le | D11B_PLCP_SIGNAL_LOCKED);
3436         /* PLCP length u16, little endian */
3437         plcp[2] = usec & 0xff;
3438         plcp[3] = (usec >> 8) & 0xff;
3439         /* PLCP CRC16 */
3440         plcp[4] = 0;
3441         plcp[5] = 0;
3442 }
3443
3444 /* Rate: 802.11 rate code, length: PSDU length in octets */
3445 static void wlc_compute_cck_plcp(struct wlc_info *wlc, ratespec_t rspec,
3446                                  uint length, u8 *plcp)
3447 {
3448         int rate = RSPEC2RATE(rspec);
3449
3450         wlc_cck_plcp_set(wlc, rate, length, plcp);
3451 }
3452
3453 /* wlc_compute_frame_dur()
3454  *
3455  * Calculate the 802.11 MAC header DUR field for MPDU
3456  * DUR for a single frame = 1 SIFS + 1 ACK
3457  * DUR for a frame with following frags = 3 SIFS + 2 ACK + next frag time
3458  *
3459  * rate                 MPDU rate in unit of 500kbps
3460  * next_frag_len        next MPDU length in bytes
3461  * preamble_type        use short/GF or long/MM PLCP header
3462  */
3463 static u16
3464 wlc_compute_frame_dur(struct wlc_info *wlc, ratespec_t rate, u8 preamble_type,
3465                       uint next_frag_len)
3466 {
3467         u16 dur, sifs;
3468
3469         sifs = SIFS(wlc->band);
3470
3471         dur = sifs;
3472         dur += (u16) wlc_calc_ack_time(wlc, rate, preamble_type);
3473
3474         if (next_frag_len) {
3475                 /* Double the current DUR to get 2 SIFS + 2 ACKs */
3476                 dur *= 2;
3477                 /* add another SIFS and the frag time */
3478                 dur += sifs;
3479                 dur +=
3480                     (u16) wlc_calc_frame_time(wlc, rate, preamble_type,
3481                                                  next_frag_len);
3482         }
3483         return dur;
3484 }
3485
3486 /* wlc_compute_rtscts_dur()
3487  *
3488  * Calculate the 802.11 MAC header DUR field for an RTS or CTS frame
3489  * DUR for normal RTS/CTS w/ frame = 3 SIFS + 1 CTS + next frame time + 1 ACK
3490  * DUR for CTS-TO-SELF w/ frame    = 2 SIFS         + next frame time + 1 ACK
3491  *
3492  * cts                  cts-to-self or rts/cts
3493  * rts_rate             rts or cts rate in unit of 500kbps
3494  * rate                 next MPDU rate in unit of 500kbps
3495  * frame_len            next MPDU frame length in bytes
3496  */
3497 u16
3498 wlc_compute_rtscts_dur(struct wlc_info *wlc, bool cts_only, ratespec_t rts_rate,
3499                        ratespec_t frame_rate, u8 rts_preamble_type,
3500                        u8 frame_preamble_type, uint frame_len, bool ba)
3501 {
3502         u16 dur, sifs;
3503
3504         sifs = SIFS(wlc->band);
3505
3506         if (!cts_only) {        /* RTS/CTS */
3507                 dur = 3 * sifs;
3508                 dur +=
3509                     (u16) wlc_calc_cts_time(wlc, rts_rate,
3510                                                rts_preamble_type);
3511         } else {                /* CTS-TO-SELF */
3512                 dur = 2 * sifs;
3513         }
3514
3515         dur +=
3516             (u16) wlc_calc_frame_time(wlc, frame_rate, frame_preamble_type,
3517                                          frame_len);
3518         if (ba)
3519                 dur +=
3520                     (u16) wlc_calc_ba_time(wlc, frame_rate,
3521                                               WLC_SHORT_PREAMBLE);
3522         else
3523                 dur +=
3524                     (u16) wlc_calc_ack_time(wlc, frame_rate,
3525                                                frame_preamble_type);
3526         return dur;
3527 }
3528
3529 u16 wlc_phytxctl1_calc(struct wlc_info *wlc, ratespec_t rspec)
3530 {
3531         u16 phyctl1 = 0;
3532         u16 bw;
3533
3534         if (WLCISLCNPHY(wlc->band)) {
3535                 bw = PHY_TXC1_BW_20MHZ;
3536         } else {
3537                 bw = RSPEC_GET_BW(rspec);
3538                 /* 10Mhz is not supported yet */
3539                 if (bw < PHY_TXC1_BW_20MHZ) {
3540                         wiphy_err(wlc->wiphy, "wlc_phytxctl1_calc: bw %d is "
3541                                   "not supported yet, set to 20L\n", bw);
3542                         bw = PHY_TXC1_BW_20MHZ;
3543                 }
3544         }
3545
3546         if (IS_MCS(rspec)) {
3547                 uint mcs = rspec & RSPEC_RATE_MASK;
3548
3549                 /* bw, stf, coding-type is part of RSPEC_PHYTXBYTE2 returns */
3550                 phyctl1 = RSPEC_PHYTXBYTE2(rspec);
3551                 /* set the upper byte of phyctl1 */
3552                 phyctl1 |= (mcs_table[mcs].tx_phy_ctl3 << 8);
3553         } else if (IS_CCK(rspec) && !WLCISLCNPHY(wlc->band)
3554                    && !WLCISSSLPNPHY(wlc->band)) {
3555                 /* In CCK mode LPPHY overloads OFDM Modulation bits with CCK Data Rate */
3556                 /* Eventually MIMOPHY would also be converted to this format */
3557                 /* 0 = 1Mbps; 1 = 2Mbps; 2 = 5.5Mbps; 3 = 11Mbps */
3558                 phyctl1 = (bw | (RSPEC_STF(rspec) << PHY_TXC1_MODE_SHIFT));
3559         } else {                /* legacy OFDM/CCK */
3560                 s16 phycfg;
3561                 /* get the phyctl byte from rate phycfg table */
3562                 phycfg = wlc_rate_legacy_phyctl(RSPEC2RATE(rspec));
3563                 if (phycfg == -1) {
3564                         wiphy_err(wlc->wiphy, "wlc_phytxctl1_calc: wrong "
3565                                   "legacy OFDM/CCK rate\n");
3566                         phycfg = 0;
3567                 }
3568                 /* set the upper byte of phyctl1 */
3569                 phyctl1 =
3570                     (bw | (phycfg << 8) |
3571                      (RSPEC_STF(rspec) << PHY_TXC1_MODE_SHIFT));
3572         }
3573         return phyctl1;
3574 }
3575
3576 ratespec_t
3577 wlc_rspec_to_rts_rspec(struct wlc_info *wlc, ratespec_t rspec, bool use_rspec,
3578                        u16 mimo_ctlchbw)
3579 {
3580         ratespec_t rts_rspec = 0;
3581
3582         if (use_rspec) {
3583                 /* use frame rate as rts rate */
3584                 rts_rspec = rspec;
3585
3586         } else if (wlc->band->gmode && wlc->protection->_g && !IS_CCK(rspec)) {
3587                 /* Use 11Mbps as the g protection RTS target rate and fallback.
3588                  * Use the WLC_BASIC_RATE() lookup to find the best basic rate under the
3589                  * target in case 11 Mbps is not Basic.
3590                  * 6 and 9 Mbps are not usually selected by rate selection, but even
3591                  * if the OFDM rate we are protecting is 6 or 9 Mbps, 11 is more robust.
3592                  */
3593                 rts_rspec = WLC_BASIC_RATE(wlc, WLC_RATE_11M);
3594         } else {
3595                 /* calculate RTS rate and fallback rate based on the frame rate
3596                  * RTS must be sent at a basic rate since it is a
3597                  * control frame, sec 9.6 of 802.11 spec
3598                  */
3599                 rts_rspec = WLC_BASIC_RATE(wlc, rspec);
3600         }
3601
3602         if (WLC_PHY_11N_CAP(wlc->band)) {
3603                 /* set rts txbw to correct side band */
3604                 rts_rspec &= ~RSPEC_BW_MASK;
3605
3606                 /* if rspec/rspec_fallback is 40MHz, then send RTS on both 20MHz channel
3607                  * (DUP), otherwise send RTS on control channel
3608                  */
3609                 if (RSPEC_IS40MHZ(rspec) && !IS_CCK(rts_rspec))
3610                         rts_rspec |= (PHY_TXC1_BW_40MHZ_DUP << RSPEC_BW_SHIFT);
3611                 else
3612                         rts_rspec |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
3613
3614                 /* pick siso/cdd as default for ofdm */
3615                 if (IS_OFDM(rts_rspec)) {
3616                         rts_rspec &= ~RSPEC_STF_MASK;
3617                         rts_rspec |= (wlc->stf->ss_opmode << RSPEC_STF_SHIFT);
3618                 }
3619         }
3620         return rts_rspec;
3621 }
3622
3623 /*
3624  * Add d11txh_t, cck_phy_hdr_t.
3625  *
3626  * 'p' data must start with 802.11 MAC header
3627  * 'p' must allow enough bytes of local headers to be "pushed" onto the packet
3628  *
3629  * headroom == D11_PHY_HDR_LEN + D11_TXH_LEN (D11_TXH_LEN is now 104 bytes)
3630  *
3631  */
3632 static u16
3633 wlc_d11hdrs_mac80211(struct wlc_info *wlc, struct ieee80211_hw *hw,
3634                      struct sk_buff *p, struct scb *scb, uint frag,
3635                      uint nfrags, uint queue, uint next_frag_len,
3636                      wsec_key_t *key, ratespec_t rspec_override)
3637 {
3638         struct ieee80211_hdr *h;
3639         d11txh_t *txh;
3640         u8 *plcp, plcp_fallback[D11_PHY_HDR_LEN];
3641         int len, phylen, rts_phylen;
3642         u16 mch, phyctl, xfts, mainrates;
3643         u16 seq = 0, mcl = 0, status = 0, frameid = 0;
3644         ratespec_t rspec[2] = { WLC_RATE_1M, WLC_RATE_1M }, rts_rspec[2] = {
3645         WLC_RATE_1M, WLC_RATE_1M};
3646         bool use_rts = false;
3647         bool use_cts = false;
3648         bool use_rifs = false;
3649         bool short_preamble[2] = { false, false };
3650         u8 preamble_type[2] = { WLC_LONG_PREAMBLE, WLC_LONG_PREAMBLE };
3651         u8 rts_preamble_type[2] = { WLC_LONG_PREAMBLE, WLC_LONG_PREAMBLE };
3652         u8 *rts_plcp, rts_plcp_fallback[D11_PHY_HDR_LEN];
3653         struct ieee80211_rts *rts = NULL;
3654         bool qos;
3655         uint ac;
3656         u32 rate_val[2];
3657         bool hwtkmic = false;
3658         u16 mimo_ctlchbw = PHY_TXC1_BW_20MHZ;
3659 #define ANTCFG_NONE 0xFF
3660         u8 antcfg = ANTCFG_NONE;
3661         u8 fbantcfg = ANTCFG_NONE;
3662         uint phyctl1_stf = 0;
3663         u16 durid = 0;
3664         struct ieee80211_tx_rate *txrate[2];
3665         int k;
3666         struct ieee80211_tx_info *tx_info;
3667         bool is_mcs[2];
3668         u16 mimo_txbw;
3669         u8 mimo_preamble_type;
3670
3671         /* locate 802.11 MAC header */
3672         h = (struct ieee80211_hdr *)(p->data);
3673         qos = ieee80211_is_data_qos(h->frame_control);
3674
3675         /* compute length of frame in bytes for use in PLCP computations */
3676         len = brcmu_pkttotlen(p);
3677         phylen = len + FCS_LEN;
3678
3679         /* If WEP enabled, add room in phylen for the additional bytes of
3680          * ICV which MAC generates.  We do NOT add the additional bytes to
3681          * the packet itself, thus phylen = packet length + ICV_LEN + FCS_LEN
3682          * in this case
3683          */
3684         if (key) {
3685                 phylen += key->icv_len;
3686         }
3687
3688         /* Get tx_info */
3689         tx_info = IEEE80211_SKB_CB(p);
3690
3691         /* add PLCP */
3692         plcp = skb_push(p, D11_PHY_HDR_LEN);
3693
3694         /* add Broadcom tx descriptor header */
3695         txh = (d11txh_t *) skb_push(p, D11_TXH_LEN);
3696         memset(txh, 0, D11_TXH_LEN);
3697
3698         /* setup frameid */
3699         if (tx_info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
3700                 /* non-AP STA should never use BCMC queue */
3701                 if (queue == TX_BCMC_FIFO) {
3702                         wiphy_err(wlc->wiphy, "wl%d: %s: ASSERT queue == "
3703                                   "TX_BCMC!\n", WLCWLUNIT(wlc), __func__);
3704                         frameid = bcmc_fid_generate(wlc, NULL, txh);
3705                 } else {
3706                         /* Increment the counter for first fragment */
3707                         if (tx_info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT) {
3708                                 SCB_SEQNUM(scb, p->priority)++;
3709                         }
3710
3711                         /* extract fragment number from frame first */
3712                         seq = le16_to_cpu(seq) & FRAGNUM_MASK;
3713                         seq |= (SCB_SEQNUM(scb, p->priority) << SEQNUM_SHIFT);
3714                         h->seq_ctrl = cpu_to_le16(seq);
3715
3716                         frameid = ((seq << TXFID_SEQ_SHIFT) & TXFID_SEQ_MASK) |
3717                             (queue & TXFID_QUEUE_MASK);
3718                 }
3719         }
3720         frameid |= queue & TXFID_QUEUE_MASK;
3721
3722         /* set the ignpmq bit for all pkts tx'd in PS mode and for beacons */
3723         if (SCB_PS(scb) || ieee80211_is_beacon(h->frame_control))
3724                 mcl |= TXC_IGNOREPMQ;
3725
3726         txrate[0] = tx_info->control.rates;
3727         txrate[1] = txrate[0] + 1;
3728
3729         /* if rate control algorithm didn't give us a fallback rate, use the primary rate */
3730         if (txrate[1]->idx < 0) {
3731                 txrate[1] = txrate[0];
3732         }
3733
3734         for (k = 0; k < hw->max_rates; k++) {
3735                 is_mcs[k] =
3736                     txrate[k]->flags & IEEE80211_TX_RC_MCS ? true : false;
3737                 if (!is_mcs[k]) {
3738                         if ((txrate[k]->idx >= 0)
3739                             && (txrate[k]->idx <
3740                                 hw->wiphy->bands[tx_info->band]->n_bitrates)) {
3741                                 rate_val[k] =
3742                                     hw->wiphy->bands[tx_info->band]->
3743                                     bitrates[txrate[k]->idx].hw_value;
3744                                 short_preamble[k] =
3745                                     txrate[k]->
3746                                     flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE ?
3747                                     true : false;
3748                         } else {
3749                                 rate_val[k] = WLC_RATE_1M;
3750                         }
3751                 } else {
3752                         rate_val[k] = txrate[k]->idx;
3753                 }
3754                 /* Currently only support same setting for primay and fallback rates.
3755                  * Unify flags for each rate into a single value for the frame
3756                  */
3757                 use_rts |=
3758                     txrate[k]->
3759                     flags & IEEE80211_TX_RC_USE_RTS_CTS ? true : false;
3760                 use_cts |=
3761                     txrate[k]->
3762                     flags & IEEE80211_TX_RC_USE_CTS_PROTECT ? true : false;
3763
3764                 if (is_mcs[k])
3765                         rate_val[k] |= NRATE_MCS_INUSE;
3766
3767                 rspec[k] = mac80211_wlc_set_nrate(wlc, wlc->band, rate_val[k]);
3768
3769                 /* (1) RATE: determine and validate primary rate and fallback rates */
3770                 if (!RSPEC_ACTIVE(rspec[k])) {
3771                         rspec[k] = WLC_RATE_1M;
3772                 } else {
3773                         if (!is_multicast_ether_addr(h->addr1)) {
3774                                 /* set tx antenna config */
3775                                 wlc_antsel_antcfg_get(wlc->asi, false, false, 0,
3776                                                       0, &antcfg, &fbantcfg);
3777                         }
3778                 }
3779         }
3780
3781         phyctl1_stf = wlc->stf->ss_opmode;
3782
3783         if (N_ENAB(wlc->pub)) {
3784                 for (k = 0; k < hw->max_rates; k++) {
3785                         /* apply siso/cdd to single stream mcs's or ofdm if rspec is auto selected */
3786                         if (((IS_MCS(rspec[k]) &&
3787                               IS_SINGLE_STREAM(rspec[k] & RSPEC_RATE_MASK)) ||
3788                              IS_OFDM(rspec[k]))
3789                             && ((rspec[k] & RSPEC_OVERRIDE_MCS_ONLY)
3790                                 || !(rspec[k] & RSPEC_OVERRIDE))) {
3791                                 rspec[k] &= ~(RSPEC_STF_MASK | RSPEC_STC_MASK);
3792
3793                                 /* For SISO MCS use STBC if possible */
3794                                 if (IS_MCS(rspec[k])
3795                                     && WLC_STF_SS_STBC_TX(wlc, scb)) {
3796                                         u8 stc;
3797
3798                                         stc = 1;        /* Nss for single stream is always 1 */
3799                                         rspec[k] |=
3800                                             (PHY_TXC1_MODE_STBC <<
3801                                              RSPEC_STF_SHIFT) | (stc <<
3802                                                                  RSPEC_STC_SHIFT);
3803                                 } else
3804                                         rspec[k] |=
3805                                             (phyctl1_stf << RSPEC_STF_SHIFT);
3806                         }
3807
3808                         /* Is the phy configured to use 40MHZ frames? If so then pick the desired txbw */
3809                         if (CHSPEC_WLC_BW(wlc->chanspec) == WLC_40_MHZ) {
3810                                 /* default txbw is 20in40 SB */
3811                                 mimo_ctlchbw = mimo_txbw =
3812                                     CHSPEC_SB_UPPER(WLC_BAND_PI_RADIO_CHANSPEC)
3813                                     ? PHY_TXC1_BW_20MHZ_UP : PHY_TXC1_BW_20MHZ;
3814
3815                                 if (IS_MCS(rspec[k])) {
3816                                         /* mcs 32 must be 40b/w DUP */
3817                                         if ((rspec[k] & RSPEC_RATE_MASK) == 32) {
3818                                                 mimo_txbw =
3819                                                     PHY_TXC1_BW_40MHZ_DUP;
3820                                                 /* use override */
3821                                         } else if (wlc->mimo_40txbw != AUTO)
3822                                                 mimo_txbw = wlc->mimo_40txbw;
3823                                         /* else check if dst is using 40 Mhz */
3824                                         else if (scb->flags & SCB_IS40)
3825                                                 mimo_txbw = PHY_TXC1_BW_40MHZ;
3826                                 } else if (IS_OFDM(rspec[k])) {
3827                                         if (wlc->ofdm_40txbw != AUTO)
3828                                                 mimo_txbw = wlc->ofdm_40txbw;
3829                                 } else {
3830                                         if (wlc->cck_40txbw != AUTO)
3831                                                 mimo_txbw = wlc->cck_40txbw;
3832                                 }
3833                         } else {
3834                                 /* mcs32 is 40 b/w only.
3835                                  * This is possible for probe packets on a STA during SCAN
3836                                  */
3837                                 if ((rspec[k] & RSPEC_RATE_MASK) == 32) {
3838                                         /* mcs 0 */
3839                                         rspec[k] = RSPEC_MIMORATE;
3840                                 }
3841                                 mimo_txbw = PHY_TXC1_BW_20MHZ;
3842                         }
3843
3844                         /* Set channel width */
3845                         rspec[k] &= ~RSPEC_BW_MASK;
3846                         if ((k == 0) || ((k > 0) && IS_MCS(rspec[k])))
3847                                 rspec[k] |= (mimo_txbw << RSPEC_BW_SHIFT);
3848                         else
3849                                 rspec[k] |= (mimo_ctlchbw << RSPEC_BW_SHIFT);
3850
3851                         /* Set Short GI */
3852 #ifdef NOSGIYET
3853                         if (IS_MCS(rspec[k])
3854                             && (txrate[k]->flags & IEEE80211_TX_RC_SHORT_GI))
3855                                 rspec[k] |= RSPEC_SHORT_GI;
3856                         else if (!(txrate[k]->flags & IEEE80211_TX_RC_SHORT_GI))
3857                                 rspec[k] &= ~RSPEC_SHORT_GI;
3858 #else
3859                         rspec[k] &= ~RSPEC_SHORT_GI;
3860 #endif
3861
3862                         mimo_preamble_type = WLC_MM_PREAMBLE;
3863                         if (txrate[k]->flags & IEEE80211_TX_RC_GREEN_FIELD)
3864                                 mimo_preamble_type = WLC_GF_PREAMBLE;
3865
3866                         if ((txrate[k]->flags & IEEE80211_TX_RC_MCS)
3867                             && (!IS_MCS(rspec[k]))) {
3868                                 wiphy_err(wlc->wiphy, "wl%d: %s: IEEE80211_TX_"
3869                                           "RC_MCS != IS_MCS(rspec)\n",
3870                                           WLCWLUNIT(wlc), __func__);
3871                         }
3872
3873                         if (IS_MCS(rspec[k])) {
3874                                 preamble_type[k] = mimo_preamble_type;
3875
3876                                 /* if SGI is selected, then forced mm for single stream */
3877                                 if ((rspec[k] & RSPEC_SHORT_GI)
3878                                     && IS_SINGLE_STREAM(rspec[k] &
3879                                                         RSPEC_RATE_MASK)) {
3880                                         preamble_type[k] = WLC_MM_PREAMBLE;
3881                                 }
3882                         }
3883
3884                         /* should be better conditionalized */
3885                         if (!IS_MCS(rspec[0])
3886                             && (tx_info->control.rates[0].
3887                                 flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE))
3888                                 preamble_type[k] = WLC_SHORT_PREAMBLE;
3889                 }
3890         } else {
3891                 for (k = 0; k < hw->max_rates; k++) {
3892                         /* Set ctrlchbw as 20Mhz */
3893                         rspec[k] &= ~RSPEC_BW_MASK;
3894                         rspec[k] |= (PHY_TXC1_BW_20MHZ << RSPEC_BW_SHIFT);
3895
3896                         /* for nphy, stf of ofdm frames must follow policies */
3897                         if (WLCISNPHY(wlc->band) && IS_OFDM(rspec[k])) {
3898                                 rspec[k] &= ~RSPEC_STF_MASK;
3899                                 rspec[k] |= phyctl1_stf << RSPEC_STF_SHIFT;
3900                         }
3901                 }
3902         }
3903
3904         /* Reset these for use with AMPDU's */
3905         txrate[0]->count = 0;
3906         txrate[1]->count = 0;
3907
3908         /* (2) PROTECTION, may change rspec */
3909         if ((ieee80211_is_data(h->frame_control) ||
3910             ieee80211_is_mgmt(h->frame_control)) &&
3911             (phylen > wlc->RTSThresh) && !is_multicast_ether_addr(h->addr1))
3912                 use_rts = true;
3913
3914         /* (3) PLCP: determine PLCP header and MAC duration, fill d11txh_t */
3915         wlc_compute_plcp(wlc, rspec[0], phylen, plcp);
3916         wlc_compute_plcp(wlc, rspec[1], phylen, plcp_fallback);
3917         memcpy(&txh->FragPLCPFallback,
3918                plcp_fallback, sizeof(txh->FragPLCPFallback));
3919
3920         /* Length field now put in CCK FBR CRC field */
3921         if (IS_CCK(rspec[1])) {
3922                 txh->FragPLCPFallback[4] = phylen & 0xff;
3923                 txh->FragPLCPFallback[5] = (phylen & 0xff00) >> 8;
3924         }
3925
3926         /* MIMO-RATE: need validation ?? */
3927         mainrates =
3928             IS_OFDM(rspec[0]) ? D11A_PHY_HDR_GRATE((ofdm_phy_hdr_t *) plcp) :
3929             plcp[0];
3930
3931         /* DUR field for main rate */
3932         if (!ieee80211_is_pspoll(h->frame_control) &&
3933             !is_multicast_ether_addr(h->addr1) && !use_rifs) {
3934                 durid =
3935                     wlc_compute_frame_dur(wlc, rspec[0], preamble_type[0],
3936                                           next_frag_len);
3937                 h->duration_id = cpu_to_le16(durid);
3938         } else if (use_rifs) {
3939                 /* NAV protect to end of next max packet size */
3940                 durid =
3941                     (u16) wlc_calc_frame_time(wlc, rspec[0],
3942                                                  preamble_type[0],
3943                                                  DOT11_MAX_FRAG_LEN);
3944                 durid += RIFS_11N_TIME;
3945                 h->duration_id = cpu_to_le16(durid);
3946         }
3947
3948         /* DUR field for fallback rate */
3949         if (ieee80211_is_pspoll(h->frame_control))
3950                 txh->FragDurFallback = h->duration_id;
3951         else if (is_multicast_ether_addr(h->addr1) || use_rifs)
3952                 txh->FragDurFallback = 0;
3953         else {
3954                 durid = wlc_compute_frame_dur(wlc, rspec[1],
3955                                               preamble_type[1], next_frag_len);
3956                 txh->FragDurFallback = cpu_to_le16(durid);
3957         }
3958
3959         /* (4) MAC-HDR: MacTxControlLow */
3960         if (frag == 0)
3961                 mcl |= TXC_STARTMSDU;
3962
3963         if (!is_multicast_ether_addr(h->addr1))
3964                 mcl |= TXC_IMMEDACK;
3965
3966         if (BAND_5G(wlc->band->bandtype))
3967                 mcl |= TXC_FREQBAND_5G;
3968
3969         if (CHSPEC_IS40(WLC_BAND_PI_RADIO_CHANSPEC))
3970                 mcl |= TXC_BW_40;
3971
3972         /* set AMIC bit if using hardware TKIP MIC */
3973         if (hwtkmic)
3974                 mcl |= TXC_AMIC;
3975
3976         txh->MacTxControlLow = cpu_to_le16(mcl);
3977
3978         /* MacTxControlHigh */
3979         mch = 0;
3980
3981         /* Set fallback rate preamble type */
3982         if ((preamble_type[1] == WLC_SHORT_PREAMBLE) ||
3983             (preamble_type[1] == WLC_GF_PREAMBLE)) {
3984                 if (RSPEC2RATE(rspec[1]) != WLC_RATE_1M)
3985                         mch |= TXC_PREAMBLE_DATA_FB_SHORT;
3986         }
3987
3988         /* MacFrameControl */
3989         memcpy(&txh->MacFrameControl, &h->frame_control, sizeof(u16));
3990         txh->TxFesTimeNormal = cpu_to_le16(0);
3991
3992         txh->TxFesTimeFallback = cpu_to_le16(0);
3993
3994         /* TxFrameRA */
3995         memcpy(&txh->TxFrameRA, &h->addr1, ETH_ALEN);
3996
3997         /* TxFrameID */
3998         txh->TxFrameID = cpu_to_le16(frameid);
3999
4000         /* TxStatus, Note the case of recreating the first frag of a suppressed frame
4001          * then we may need to reset the retry cnt's via the status reg
4002          */
4003         txh->TxStatus = cpu_to_le16(status);
4004
4005         /* extra fields for ucode AMPDU aggregation, the new fields are added to
4006          * the END of previous structure so that it's compatible in driver.
4007          */
4008         txh->MaxNMpdus = cpu_to_le16(0);
4009         txh->MaxABytes_MRT = cpu_to_le16(0);
4010         txh->MaxABytes_FBR = cpu_to_le16(0);
4011         txh->MinMBytes = cpu_to_le16(0);
4012
4013         /* (5) RTS/CTS: determine RTS/CTS PLCP header and MAC duration, furnish d11txh_t */
4014         /* RTS PLCP header and RTS frame */
4015         if (use_rts || use_cts) {
4016                 if (use_rts && use_cts)
4017                         use_cts = false;
4018
4019                 for (k = 0; k < 2; k++) {
4020                         rts_rspec[k] = wlc_rspec_to_rts_rspec(wlc, rspec[k],
4021                                                               false,
4022                                                               mimo_ctlchbw);
4023                 }
4024
4025                 if (!IS_OFDM(rts_rspec[0]) &&
4026                     !((RSPEC2RATE(rts_rspec[0]) == WLC_RATE_1M) ||
4027                       (wlc->PLCPHdr_override == WLC_PLCP_LONG))) {
4028                         rts_preamble_type[0] = WLC_SHORT_PREAMBLE;
4029                         mch |= TXC_PREAMBLE_RTS_MAIN_SHORT;
4030                 }
4031
4032                 if (!IS_OFDM(rts_rspec[1]) &&
4033                     !((RSPEC2RATE(rts_rspec[1]) == WLC_RATE_1M) ||
4034                       (wlc->PLCPHdr_override == WLC_PLCP_LONG))) {
4035                         rts_preamble_type[1] = WLC_SHORT_PREAMBLE;
4036                         mch |= TXC_PREAMBLE_RTS_FB_SHORT;
4037                 }
4038
4039                 /* RTS/CTS additions to MacTxControlLow */
4040                 if (use_cts) {
4041                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDCTS);
4042                 } else {
4043                         txh->MacTxControlLow |= cpu_to_le16(TXC_SENDRTS);
4044                         txh->MacTxControlLow |= cpu_to_le16(TXC_LONGFRAME);
4045                 }
4046
4047                 /* RTS PLCP header */
4048                 rts_plcp = txh->RTSPhyHeader;
4049                 if (use_cts)
4050                         rts_phylen = DOT11_CTS_LEN + FCS_LEN;
4051                 else
4052                         rts_phylen = DOT11_RTS_LEN + FCS_LEN;
4053
4054                 wlc_compute_plcp(wlc, rts_rspec[0], rts_phylen, rts_plcp);
4055
4056                 /* fallback rate version of RTS PLCP header */
4057                 wlc_compute_plcp(wlc, rts_rspec[1], rts_phylen,
4058                                  rts_plcp_fallback);
4059                 memcpy(&txh->RTSPLCPFallback, rts_plcp_fallback,
4060                        sizeof(txh->RTSPLCPFallback));
4061
4062                 /* RTS frame fields... */
4063                 rts = (struct ieee80211_rts *)&txh->rts_frame;
4064
4065                 durid = wlc_compute_rtscts_dur(wlc, use_cts, rts_rspec[0],
4066                                                rspec[0], rts_preamble_type[0],
4067                                                preamble_type[0], phylen, false);
4068                 rts->duration = cpu_to_le16(durid);
4069                 /* fallback rate version of RTS DUR field */
4070                 durid = wlc_compute_rtscts_dur(wlc, use_cts,
4071                                                rts_rspec[1], rspec[1],
4072                                                rts_preamble_type[1],
4073                                                preamble_type[1], phylen, false);
4074                 txh->RTSDurFallback = cpu_to_le16(durid);
4075
4076                 if (use_cts) {
4077                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
4078                                                          IEEE80211_STYPE_CTS);
4079
4080                         memcpy(&rts->ra, &h->addr2, ETH_ALEN);
4081                 } else {
4082                         rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
4083                                                          IEEE80211_STYPE_RTS);
4084
4085                         memcpy(&rts->ra, &h->addr1, 2 * ETH_ALEN);
4086                 }
4087
4088                 /* mainrate
4089                  *    low 8 bits: main frag rate/mcs,
4090                  *    high 8 bits: rts/cts rate/mcs
4091                  */
4092                 mainrates |= (IS_OFDM(rts_rspec[0]) ?
4093                               D11A_PHY_HDR_GRATE((ofdm_phy_hdr_t *) rts_plcp) :
4094                               rts_plcp[0]) << 8;
4095         } else {
4096                 memset((char *)txh->RTSPhyHeader, 0, D11_PHY_HDR_LEN);
4097                 memset((char *)&txh->rts_frame, 0,
4098                         sizeof(struct ieee80211_rts));
4099                 memset((char *)txh->RTSPLCPFallback, 0,
4100                       sizeof(txh->RTSPLCPFallback));
4101                 txh->RTSDurFallback = 0;
4102         }
4103
4104 #ifdef SUPPORT_40MHZ
4105         /* add null delimiter count */
4106         if ((tx_info->flags & IEEE80211_TX_CTL_AMPDU) && IS_MCS(rspec)) {
4107                 txh->RTSPLCPFallback[AMPDU_FBR_NULL_DELIM] =
4108                     wlc_ampdu_null_delim_cnt(wlc->ampdu, scb, rspec, phylen);
4109         }
4110 #endif
4111
4112         /* Now that RTS/RTS FB preamble types are updated, write the final value */
4113         txh->MacTxControlHigh = cpu_to_le16(mch);
4114
4115         /* MainRates (both the rts and frag plcp rates have been calculated now) */
4116         txh->MainRates = cpu_to_le16(mainrates);
4117
4118         /* XtraFrameTypes */
4119         xfts = FRAMETYPE(rspec[1], wlc->mimoft);
4120         xfts |= (FRAMETYPE(rts_rspec[0], wlc->mimoft) << XFTS_RTS_FT_SHIFT);
4121         xfts |= (FRAMETYPE(rts_rspec[1], wlc->mimoft) << XFTS_FBRRTS_FT_SHIFT);
4122         xfts |=
4123             CHSPEC_CHANNEL(WLC_BAND_PI_RADIO_CHANSPEC) << XFTS_CHANNEL_SHIFT;
4124         txh->XtraFrameTypes = cpu_to_le16(xfts);
4125
4126         /* PhyTxControlWord */
4127         phyctl = FRAMETYPE(rspec[0], wlc->mimoft);
4128         if ((preamble_type[0] == WLC_SHORT_PREAMBLE) ||
4129             (preamble_type[0] == WLC_GF_PREAMBLE)) {
4130                 if (RSPEC2RATE(rspec[0]) != WLC_RATE_1M)
4131                         phyctl |= PHY_TXC_SHORT_HDR;
4132         }
4133
4134         /* phytxant is properly bit shifted */
4135         phyctl |= wlc_stf_d11hdrs_phyctl_txant(wlc, rspec[0]);
4136         txh->PhyTxControlWord = cpu_to_le16(phyctl);
4137
4138         /* PhyTxControlWord_1 */
4139         if (WLC_PHY_11N_CAP(wlc->band)) {
4140                 u16 phyctl1 = 0;
4141
4142                 phyctl1 = wlc_phytxctl1_calc(wlc, rspec[0]);
4143                 txh->PhyTxControlWord_1 = cpu_to_le16(phyctl1);
4144                 phyctl1 = wlc_phytxctl1_calc(wlc, rspec[1]);
4145                 txh->PhyTxControlWord_1_Fbr = cpu_to_le16(phyctl1);
4146
4147                 if (use_rts || use_cts) {
4148                         phyctl1 = wlc_phytxctl1_calc(wlc, rts_rspec[0]);
4149                         txh->PhyTxControlWord_1_Rts = cpu_to_le16(phyctl1);
4150                         phyctl1 = wlc_phytxctl1_calc(wlc, rts_rspec[1]);
4151                         txh->PhyTxControlWord_1_FbrRts = cpu_to_le16(phyctl1);
4152                 }
4153
4154                 /*
4155                  * For mcs frames, if mixedmode(overloaded with long preamble) is going to be set,
4156                  * fill in non-zero MModeLen and/or MModeFbrLen
4157                  *  it will be unnecessary if they are separated
4158                  */
4159                 if (IS_MCS(rspec[0]) && (preamble_type[0] == WLC_MM_PREAMBLE)) {
4160                         u16 mmodelen =
4161                             wlc_calc_lsig_len(wlc, rspec[0], phylen);
4162                         txh->MModeLen = cpu_to_le16(mmodelen);
4163                 }
4164
4165                 if (IS_MCS(rspec[1]) && (preamble_type[1] == WLC_MM_PREAMBLE)) {
4166                         u16 mmodefbrlen =
4167                             wlc_calc_lsig_len(wlc, rspec[1], phylen);
4168                         txh->MModeFbrLen = cpu_to_le16(mmodefbrlen);
4169                 }
4170         }
4171
4172         ac = skb_get_queue_mapping(p);
4173         if (SCB_WME(scb) && qos && wlc->edcf_txop[ac]) {
4174                 uint frag_dur, dur, dur_fallback;
4175
4176                 /* WME: Update TXOP threshold */
4177                 if ((!(tx_info->flags & IEEE80211_TX_CTL_AMPDU)) && (frag == 0)) {
4178                         frag_dur =
4179                             wlc_calc_frame_time(wlc, rspec[0], preamble_type[0],
4180                                                 phylen);
4181
4182                         if (rts) {
4183                                 /* 1 RTS or CTS-to-self frame */
4184                                 dur =
4185                                     wlc_calc_cts_time(wlc, rts_rspec[0],
4186                                                       rts_preamble_type[0]);
4187                                 dur_fallback =
4188                                     wlc_calc_cts_time(wlc, rts_rspec[1],
4189                                                       rts_preamble_type[1]);
4190                                 /* (SIFS + CTS) + SIFS + frame + SIFS + ACK */
4191                                 dur += le16_to_cpu(rts->duration);
4192                                 dur_fallback +=
4193                                         le16_to_cpu(txh->RTSDurFallback);
4194                         } else if (use_rifs) {
4195                                 dur = frag_dur;
4196                                 dur_fallback = 0;
4197                         } else {
4198                                 /* frame + SIFS + ACK */
4199                                 dur = frag_dur;
4200                                 dur +=
4201                                     wlc_compute_frame_dur(wlc, rspec[0],
4202                                                           preamble_type[0], 0);
4203
4204                                 dur_fallback =
4205                                     wlc_calc_frame_time(wlc, rspec[1],
4206                                                         preamble_type[1],
4207                                                         phylen);
4208                                 dur_fallback +=
4209                                     wlc_compute_frame_dur(wlc, rspec[1],
4210                                                           preamble_type[1], 0);
4211                         }
4212                         /* NEED to set TxFesTimeNormal (hard) */
4213                         txh->TxFesTimeNormal = cpu_to_le16((u16) dur);
4214                         /* NEED to set fallback rate version of TxFesTimeNormal (hard) */
4215                         txh->TxFesTimeFallback =
4216                                 cpu_to_le16((u16) dur_fallback);
4217
4218                         /* update txop byte threshold (txop minus intraframe overhead) */
4219                         if (wlc->edcf_txop[ac] >= (dur - frag_dur)) {
4220                                 {
4221                                         uint newfragthresh;
4222
4223                                         newfragthresh =
4224                                             wlc_calc_frame_len(wlc, rspec[0],
4225                                                                preamble_type[0],
4226                                                                (wlc->
4227                                                                 edcf_txop[ac] -
4228                                                                 (dur -
4229                                                                  frag_dur)));
4230                                         /* range bound the fragthreshold */
4231                                         if (newfragthresh < DOT11_MIN_FRAG_LEN)
4232                                                 newfragthresh =
4233                                                     DOT11_MIN_FRAG_LEN;
4234                                         else if (newfragthresh >
4235                                                  wlc->usr_fragthresh)
4236                                                 newfragthresh =
4237                                                     wlc->usr_fragthresh;
4238                                         /* update the fragthresh and do txc update */
4239                                         if (wlc->fragthresh[queue] !=
4240                                             (u16) newfragthresh) {
4241                                                 wlc->fragthresh[queue] =
4242                                                     (u16) newfragthresh;
4243                                         }
4244                                 }
4245                         } else
4246                                 wiphy_err(wlc->wiphy, "wl%d: %s txop invalid "
4247                                           "for rate %d\n",
4248                                           wlc->pub->unit, fifo_names[queue],
4249                                           RSPEC2RATE(rspec[0]));
4250
4251                         if (dur > wlc->edcf_txop[ac])
4252                                 wiphy_err(wlc->wiphy, "wl%d: %s: %s txop "
4253                                           "exceeded phylen %d/%d dur %d/%d\n",
4254                                           wlc->pub->unit, __func__,
4255                                           fifo_names[queue],
4256                                           phylen, wlc->fragthresh[queue],
4257                                           dur, wlc->edcf_txop[ac]);
4258                 }
4259         }
4260
4261         return 0;
4262 }
4263
4264 void wlc_tbtt(struct wlc_info *wlc, d11regs_t *regs)
4265 {
4266         struct wlc_bsscfg *cfg = wlc->cfg;
4267
4268         if (!cfg->BSS) {
4269                 /* DirFrmQ is now valid...defer setting until end of ATIM window */
4270                 wlc->qvalid |= MCMD_DIRFRMQVAL;
4271         }
4272 }
4273
4274 static void wlc_war16165(struct wlc_info *wlc, bool tx)
4275 {
4276         if (tx) {
4277                 /* the post-increment is used in STAY_AWAKE macro */
4278                 if (wlc->txpend16165war++ == 0)
4279                         wlc_set_ps_ctrl(wlc);
4280         } else {
4281                 wlc->txpend16165war--;
4282                 if (wlc->txpend16165war == 0)
4283                         wlc_set_ps_ctrl(wlc);
4284         }
4285 }
4286
4287 /* process an individual tx_status_t */
4288 /* WLC_HIGH_API */
4289 bool
4290 wlc_dotxstatus(struct wlc_info *wlc, tx_status_t *txs, u32 frm_tx2)
4291 {
4292         struct sk_buff *p;
4293         uint queue;
4294         d11txh_t *txh;
4295         struct scb *scb = NULL;
4296         bool free_pdu;
4297         int tx_rts, tx_frame_count, tx_rts_count;
4298         uint totlen, supr_status;
4299         bool lastframe;
4300         struct ieee80211_hdr *h;
4301         u16 mcl;
4302         struct ieee80211_tx_info *tx_info;
4303         struct ieee80211_tx_rate *txrate;
4304         int i;
4305
4306         (void)(frm_tx2);        /* Compiler reference to avoid unused variable warning */
4307
4308         /* discard intermediate indications for ucode with one legitimate case:
4309          *   e.g. if "useRTS" is set. ucode did a successful rts/cts exchange, but the subsequent
4310          *   tx of DATA failed. so it will start rts/cts from the beginning (resetting the rts
4311          *   transmission count)
4312          */
4313         if (!(txs->status & TX_STATUS_AMPDU)
4314             && (txs->status & TX_STATUS_INTERMEDIATE)) {
4315                 wiphy_err(wlc->wiphy, "%s: INTERMEDIATE but not AMPDU\n",
4316                           __func__);
4317                 return false;
4318         }
4319
4320         queue = txs->frameid & TXFID_QUEUE_MASK;
4321         if (queue >= NFIFO) {
4322                 p = NULL;
4323                 goto fatal;
4324         }
4325
4326         p = GETNEXTTXP(wlc, queue);
4327         if (WLC_WAR16165(wlc))
4328                 wlc_war16165(wlc, false);
4329         if (p == NULL)
4330                 goto fatal;
4331
4332         txh = (d11txh_t *) (p->data);
4333         mcl = le16_to_cpu(txh->MacTxControlLow);
4334
4335         if (txs->phyerr) {
4336                 if (WL_ERROR_ON()) {
4337                         wiphy_err(wlc->wiphy, "phyerr 0x%x, rate 0x%x\n",
4338                                   txs->phyerr, txh->MainRates);
4339                         wlc_print_txdesc(txh);
4340                 }
4341                 wlc_print_txstatus(txs);
4342         }
4343
4344         if (txs->frameid != cpu_to_le16(txh->TxFrameID))
4345                 goto fatal;
4346         tx_info = IEEE80211_SKB_CB(p);
4347         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
4348
4349         if (tx_info->control.sta)
4350                 scb = (struct scb *)tx_info->control.sta->drv_priv;
4351
4352         if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
4353                 wlc_ampdu_dotxstatus(wlc->ampdu, scb, p, txs);
4354                 return false;
4355         }
4356
4357         supr_status = txs->status & TX_STATUS_SUPR_MASK;
4358         if (supr_status == TX_STATUS_SUPR_BADCH)
4359                 BCMMSG(wlc->wiphy,
4360                        "%s: Pkt tx suppressed, possibly channel %d\n",
4361                        __func__, CHSPEC_CHANNEL(wlc->default_bss->chanspec));
4362
4363         tx_rts = cpu_to_le16(txh->MacTxControlLow) & TXC_SENDRTS;
4364         tx_frame_count =
4365             (txs->status & TX_STATUS_FRM_RTX_MASK) >> TX_STATUS_FRM_RTX_SHIFT;
4366         tx_rts_count =
4367             (txs->status & TX_STATUS_RTS_RTX_MASK) >> TX_STATUS_RTS_RTX_SHIFT;
4368
4369         lastframe = !ieee80211_has_morefrags(h->frame_control);
4370
4371         if (!lastframe) {
4372                 wiphy_err(wlc->wiphy, "Not last frame!\n");
4373         } else {
4374                 u16 sfbl, lfbl;
4375                 ieee80211_tx_info_clear_status(tx_info);
4376                 if (queue < AC_COUNT) {
4377                         sfbl = WLC_WME_RETRY_SFB_GET(wlc, wme_fifo2ac[queue]);
4378                         lfbl = WLC_WME_RETRY_LFB_GET(wlc, wme_fifo2ac[queue]);
4379                 } else {
4380                         sfbl = wlc->SFBL;
4381                         lfbl = wlc->LFBL;
4382                 }
4383
4384                 txrate = tx_info->status.rates;
4385                 /* FIXME: this should use a combination of sfbl, lfbl depending on frame length and RTS setting */
4386                 if ((tx_frame_count > sfbl) && (txrate[1].idx >= 0)) {
4387                         /* rate selection requested a fallback rate and we used it */
4388                         txrate->count = lfbl;
4389                         txrate[1].count = tx_frame_count - lfbl;
4390                 } else {
4391                         /* rate selection did not request fallback rate, or we didn't need it */
4392                         txrate->count = tx_frame_count;
4393                         /* rc80211_minstrel.c:minstrel_tx_status() expects unused rates to be marked with idx = -1 */
4394                         txrate[1].idx = -1;
4395                         txrate[1].count = 0;
4396                 }
4397
4398                 /* clear the rest of the rates */
4399                 for (i = 2; i < IEEE80211_TX_MAX_RATES; i++) {
4400                         txrate[i].idx = -1;
4401                         txrate[i].count = 0;
4402                 }
4403
4404                 if (txs->status & TX_STATUS_ACK_RCV)
4405                         tx_info->flags |= IEEE80211_TX_STAT_ACK;
4406         }
4407
4408         totlen = brcmu_pkttotlen(p);
4409         free_pdu = true;
4410
4411         wlc_txfifo_complete(wlc, queue, 1);
4412
4413         if (lastframe) {
4414                 p->next = NULL;
4415                 p->prev = NULL;
4416                 /* remove PLCP & Broadcom tx descriptor header */
4417                 skb_pull(p, D11_PHY_HDR_LEN);
4418                 skb_pull(p, D11_TXH_LEN);
4419                 ieee80211_tx_status_irqsafe(wlc->pub->ieee_hw, p);
4420         } else {
4421                 wiphy_err(wlc->wiphy, "%s: Not last frame => not calling "
4422                           "tx_status\n", __func__);
4423         }
4424
4425         return false;
4426
4427  fatal:
4428         if (p)
4429                 brcmu_pkt_buf_free_skb(p);
4430
4431         return true;
4432
4433 }
4434
4435 void
4436 wlc_txfifo_complete(struct wlc_info *wlc, uint fifo, s8 txpktpend)
4437 {
4438         TXPKTPENDDEC(wlc, fifo, txpktpend);
4439         BCMMSG(wlc->wiphy, "pktpend dec %d to %d\n", txpktpend,
4440                 TXPKTPENDGET(wlc, fifo));
4441
4442         /* There is more room; mark precedences related to this FIFO sendable */
4443         WLC_TX_FIFO_ENAB(wlc, fifo);
4444
4445         /* Clear MHF2_TXBCMC_NOW flag if BCMC fifo has drained */
4446         if (AP_ENAB(wlc->pub) &&
4447             !TXPKTPENDGET(wlc, TX_BCMC_FIFO)) {
4448                 wlc_mhf(wlc, MHF2, MHF2_TXBCMC_NOW, 0, WLC_BAND_AUTO);
4449         }
4450
4451         /* figure out which bsscfg is being worked on... */
4452 }
4453
4454 /* Update beacon listen interval in shared memory */
4455 void wlc_bcn_li_upd(struct wlc_info *wlc)
4456 {
4457         if (AP_ENAB(wlc->pub))
4458                 return;
4459
4460         /* wake up every DTIM is the default */
4461         if (wlc->bcn_li_dtim == 1)
4462                 wlc_write_shm(wlc, M_BCN_LI, 0);
4463         else
4464                 wlc_write_shm(wlc, M_BCN_LI,
4465                               (wlc->bcn_li_dtim << 8) | wlc->bcn_li_bcn);
4466 }
4467
4468 /*
4469  * recover 64bit TSF value from the 16bit TSF value in the rx header
4470  * given the assumption that the TSF passed in header is within 65ms
4471  * of the current tsf.
4472  *
4473  * 6       5       4       4       3       2       1
4474  * 3.......6.......8.......0.......2.......4.......6.......8......0
4475  * |<---------- tsf_h ----------->||<--- tsf_l -->||<-RxTSFTime ->|
4476  *
4477  * The RxTSFTime are the lowest 16 bits and provided by the ucode. The
4478  * tsf_l is filled in by wlc_bmac_recv, which is done earlier in the
4479  * receive call sequence after rx interrupt. Only the higher 16 bits
4480  * are used. Finally, the tsf_h is read from the tsf register.
4481  */
4482 static u64 wlc_recover_tsf64(struct wlc_info *wlc, struct wlc_d11rxhdr *rxh)
4483 {
4484         u32 tsf_h, tsf_l;
4485         u16 rx_tsf_0_15, rx_tsf_16_31;
4486
4487         wlc_bmac_read_tsf(wlc->hw, &tsf_l, &tsf_h);
4488
4489         rx_tsf_16_31 = (u16)(tsf_l >> 16);
4490         rx_tsf_0_15 = rxh->rxhdr.RxTSFTime;
4491
4492         /*
4493          * a greater tsf time indicates the low 16 bits of
4494          * tsf_l wrapped, so decrement the high 16 bits.
4495          */
4496         if ((u16)tsf_l < rx_tsf_0_15) {
4497                 rx_tsf_16_31 -= 1;
4498                 if (rx_tsf_16_31 == 0xffff)
4499                         tsf_h -= 1;
4500         }
4501
4502         return ((u64)tsf_h << 32) | (((u32)rx_tsf_16_31 << 16) + rx_tsf_0_15);
4503 }
4504
4505 static void
4506 prep_mac80211_status(struct wlc_info *wlc, d11rxhdr_t *rxh, struct sk_buff *p,
4507                      struct ieee80211_rx_status *rx_status)
4508 {
4509         wlc_d11rxhdr_t *wlc_rxh = (wlc_d11rxhdr_t *) rxh;
4510         int preamble;
4511         int channel;
4512         ratespec_t rspec;
4513         unsigned char *plcp;
4514
4515         /* fill in TSF and flag its presence */
4516         rx_status->mactime = wlc_recover_tsf64(wlc, wlc_rxh);
4517         rx_status->flag |= RX_FLAG_MACTIME_MPDU;
4518
4519         channel = WLC_CHAN_CHANNEL(rxh->RxChan);
4520
4521         if (channel > 14) {
4522                 rx_status->band = IEEE80211_BAND_5GHZ;
4523                 rx_status->freq = ieee80211_ofdm_chan_to_freq(
4524                                         WF_CHAN_FACTOR_5_G/2, channel);
4525
4526         } else {
4527                 rx_status->band = IEEE80211_BAND_2GHZ;
4528                 rx_status->freq = ieee80211_dsss_chan_to_freq(channel);
4529         }
4530
4531         rx_status->signal = wlc_rxh->rssi;      /* signal */
4532
4533         /* noise */
4534         /* qual */
4535         rx_status->antenna = (rxh->PhyRxStatus_0 & PRXS0_RXANT_UPSUBBAND) ? 1 : 0;      /* ant */
4536
4537         plcp = p->data;
4538
4539         rspec = wlc_compute_rspec(rxh, plcp);
4540         if (IS_MCS(rspec)) {
4541                 rx_status->rate_idx = rspec & RSPEC_RATE_MASK;
4542                 rx_status->flag |= RX_FLAG_HT;
4543                 if (RSPEC_IS40MHZ(rspec))
4544                         rx_status->flag |= RX_FLAG_40MHZ;
4545         } else {
4546                 switch (RSPEC2RATE(rspec)) {
4547                 case WLC_RATE_1M:
4548                         rx_status->rate_idx = 0;
4549                         break;
4550                 case WLC_RATE_2M:
4551                         rx_status->rate_idx = 1;
4552                         break;
4553                 case WLC_RATE_5M5:
4554                         rx_status->rate_idx = 2;
4555                         break;
4556                 case WLC_RATE_11M:
4557                         rx_status->rate_idx = 3;
4558                         break;
4559                 case WLC_RATE_6M:
4560                         rx_status->rate_idx = 4;
4561                         break;
4562                 case WLC_RATE_9M:
4563                         rx_status->rate_idx = 5;
4564                         break;
4565                 case WLC_RATE_12M:
4566                         rx_status->rate_idx = 6;
4567                         break;
4568                 case WLC_RATE_18M:
4569                         rx_status->rate_idx = 7;
4570                         break;
4571                 case WLC_RATE_24M:
4572                         rx_status->rate_idx = 8;
4573                         break;
4574                 case WLC_RATE_36M:
4575                         rx_status->rate_idx = 9;
4576                         break;
4577                 case WLC_RATE_48M:
4578                         rx_status->rate_idx = 10;
4579                         break;
4580                 case WLC_RATE_54M:
4581                         rx_status->rate_idx = 11;
4582                         break;
4583                 default:
4584                         wiphy_err(wlc->wiphy, "%s: Unknown rate\n", __func__);
4585                 }
4586
4587                 /* Determine short preamble and rate_idx */
4588                 preamble = 0;
4589                 if (IS_CCK(rspec)) {
4590                         if (rxh->PhyRxStatus_0 & PRXS0_SHORTH)
4591                                 rx_status->flag |= RX_FLAG_SHORTPRE;
4592                 } else if (IS_OFDM(rspec)) {
4593                         rx_status->flag |= RX_FLAG_SHORTPRE;
4594                 } else {
4595                         wiphy_err(wlc->wiphy, "%s: Unknown modulation\n",
4596                                   __func__);
4597                 }
4598         }
4599
4600         if (PLCP3_ISSGI(plcp[3]))
4601                 rx_status->flag |= RX_FLAG_SHORT_GI;
4602
4603         if (rxh->RxStatus1 & RXS_DECERR) {
4604                 rx_status->flag |= RX_FLAG_FAILED_PLCP_CRC;
4605                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_PLCP_CRC\n",
4606                           __func__);
4607         }
4608         if (rxh->RxStatus1 & RXS_FCSERR) {
4609                 rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
4610                 wiphy_err(wlc->wiphy, "%s:  RX_FLAG_FAILED_FCS_CRC\n",
4611                           __func__);
4612         }
4613 }
4614
4615 static void
4616 wlc_recvctl(struct wlc_info *wlc, d11rxhdr_t *rxh, struct sk_buff *p)
4617 {
4618         int len_mpdu;
4619         struct ieee80211_rx_status rx_status;
4620
4621         memset(&rx_status, 0, sizeof(rx_status));
4622         prep_mac80211_status(wlc, rxh, p, &rx_status);
4623
4624         /* mac header+body length, exclude CRC and plcp header */
4625         len_mpdu = p->len - D11_PHY_HDR_LEN - FCS_LEN;
4626         skb_pull(p, D11_PHY_HDR_LEN);
4627         __skb_trim(p, len_mpdu);
4628
4629         memcpy(IEEE80211_SKB_RXCB(p), &rx_status, sizeof(rx_status));
4630         ieee80211_rx_irqsafe(wlc->pub->ieee_hw, p);
4631         return;
4632 }
4633
4634 /* Process received frames */
4635 /*
4636  * Return true if more frames need to be processed. false otherwise.
4637  * Param 'bound' indicates max. # frames to process before break out.
4638  */
4639 /* WLC_HIGH_API */
4640 void wlc_recv(struct wlc_info *wlc, struct sk_buff *p)
4641 {
4642         d11rxhdr_t *rxh;
4643         struct ieee80211_hdr *h;
4644         uint len;
4645         bool is_amsdu;
4646
4647         BCMMSG(wlc->wiphy, "wl%d\n", wlc->pub->unit);
4648
4649         /* frame starts with rxhdr */
4650         rxh = (d11rxhdr_t *) (p->data);
4651
4652         /* strip off rxhdr */
4653         skb_pull(p, WL_HWRXOFF);
4654
4655         /* fixup rx header endianness */
4656         rxh->RxFrameSize = le16_to_cpu(rxh->RxFrameSize);
4657         rxh->PhyRxStatus_0 = le16_to_cpu(rxh->PhyRxStatus_0);
4658         rxh->PhyRxStatus_1 = le16_to_cpu(rxh->PhyRxStatus_1);
4659         rxh->PhyRxStatus_2 = le16_to_cpu(rxh->PhyRxStatus_2);
4660         rxh->PhyRxStatus_3 = le16_to_cpu(rxh->PhyRxStatus_3);
4661         rxh->PhyRxStatus_4 = le16_to_cpu(rxh->PhyRxStatus_4);
4662         rxh->PhyRxStatus_5 = le16_to_cpu(rxh->PhyRxStatus_5);
4663         rxh->RxStatus1 = le16_to_cpu(rxh->RxStatus1);
4664         rxh->RxStatus2 = le16_to_cpu(rxh->RxStatus2);
4665         rxh->RxTSFTime = le16_to_cpu(rxh->RxTSFTime);
4666         rxh->RxChan = le16_to_cpu(rxh->RxChan);
4667
4668         /* MAC inserts 2 pad bytes for a4 headers or QoS or A-MSDU subframes */
4669         if (rxh->RxStatus1 & RXS_PBPRES) {
4670                 if (p->len < 2) {
4671                         wiphy_err(wlc->wiphy, "wl%d: wlc_recv: rcvd runt of "
4672                                   "len %d\n", wlc->pub->unit, p->len);
4673                         goto toss;
4674                 }
4675                 skb_pull(p, 2);
4676         }
4677
4678         h = (struct ieee80211_hdr *)(p->data + D11_PHY_HDR_LEN);
4679         len = p->len;
4680
4681         if (rxh->RxStatus1 & RXS_FCSERR) {
4682                 if (wlc->pub->mac80211_state & MAC80211_PROMISC_BCNS) {
4683                         wiphy_err(wlc->wiphy, "FCSERR while scanning******* -"
4684                                   " tossing\n");
4685                         goto toss;
4686                 } else {
4687                         wiphy_err(wlc->wiphy, "RCSERR!!!\n");
4688                         goto toss;
4689                 }
4690         }
4691
4692         /* check received pkt has at least frame control field */
4693         if (len < D11_PHY_HDR_LEN + sizeof(h->frame_control)) {
4694                 goto toss;
4695         }
4696
4697         is_amsdu = rxh->RxStatus2 & RXS_AMSDU_MASK;
4698
4699         /* explicitly test bad src address to avoid sending bad deauth */
4700         if (!is_amsdu) {
4701                 /* CTS and ACK CTL frames are w/o a2 */
4702
4703                 if (ieee80211_is_data(h->frame_control) ||
4704                     ieee80211_is_mgmt(h->frame_control)) {
4705                         if ((is_zero_ether_addr(h->addr2) ||
4706                              is_multicast_ether_addr(h->addr2))) {
4707                                 wiphy_err(wlc->wiphy, "wl%d: %s: dropping a "
4708                                           "frame with invalid src mac address,"
4709                                           " a2: %pM\n",
4710                                          wlc->pub->unit, __func__, h->addr2);
4711                                 goto toss;
4712                         }
4713                 }
4714         }
4715
4716         /* due to sheer numbers, toss out probe reqs for now */
4717         if (ieee80211_is_probe_req(h->frame_control))
4718                 goto toss;
4719
4720         if (is_amsdu)
4721                 goto toss;
4722
4723         wlc_recvctl(wlc, rxh, p);
4724         return;
4725
4726  toss:
4727         brcmu_pkt_buf_free_skb(p);
4728 }
4729
4730 /* calculate frame duration for Mixed-mode L-SIG spoofing, return
4731  * number of bytes goes in the length field
4732  *
4733  * Formula given by HT PHY Spec v 1.13
4734  *   len = 3(nsyms + nstream + 3) - 3
4735  */
4736 u16
4737 wlc_calc_lsig_len(struct wlc_info *wlc, ratespec_t ratespec, uint mac_len)
4738 {
4739         uint nsyms, len = 0, kNdps;
4740
4741         BCMMSG(wlc->wiphy, "wl%d: rate %d, len%d\n",
4742                  wlc->pub->unit, RSPEC2RATE(ratespec), mac_len);
4743
4744         if (IS_MCS(ratespec)) {
4745                 uint mcs = ratespec & RSPEC_RATE_MASK;
4746                 /* MCS_TXS(mcs) returns num tx streams - 1 */
4747                 int tot_streams = (MCS_TXS(mcs) + 1) + RSPEC_STC(ratespec);
4748
4749                 /* the payload duration calculation matches that of regular ofdm */
4750                 /* 1000Ndbps = kbps * 4 */
4751                 kNdps =
4752                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4753                              RSPEC_ISSGI(ratespec)) * 4;
4754
4755                 if (RSPEC_STC(ratespec) == 0)
4756                         /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4757                         nsyms =
4758                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4759                                   APHY_TAIL_NBITS) * 1000, kNdps);
4760                 else
4761                         /* STBC needs to have even number of symbols */
4762                         nsyms =
4763                             2 *
4764                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4765                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
4766
4767                 nsyms += (tot_streams + 3);     /* (+3) account for HT-SIG(2) and HT-STF(1) */
4768                 /* 3 bytes/symbol @ legacy 6Mbps rate */
4769                 len = (3 * nsyms) - 3;  /* (-3) excluding service bits and tail bits */
4770         }
4771
4772         return (u16) len;
4773 }
4774
4775 /* calculate frame duration of a given rate and length, return time in usec unit */
4776 uint
4777 wlc_calc_frame_time(struct wlc_info *wlc, ratespec_t ratespec, u8 preamble_type,
4778                     uint mac_len)
4779 {
4780         uint nsyms, dur = 0, Ndps, kNdps;
4781         uint rate = RSPEC2RATE(ratespec);
4782
4783         if (rate == 0) {
4784                 wiphy_err(wlc->wiphy, "wl%d: WAR: using rate of 1 mbps\n",
4785                           wlc->pub->unit);
4786                 rate = WLC_RATE_1M;
4787         }
4788
4789         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d, len%d\n",
4790                  wlc->pub->unit, ratespec, preamble_type, mac_len);
4791
4792         if (IS_MCS(ratespec)) {
4793                 uint mcs = ratespec & RSPEC_RATE_MASK;
4794                 int tot_streams = MCS_TXS(mcs) + RSPEC_STC(ratespec);
4795
4796                 dur = PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
4797                 if (preamble_type == WLC_MM_PREAMBLE)
4798                         dur += PREN_MM_EXT;
4799                 /* 1000Ndbps = kbps * 4 */
4800                 kNdps =
4801                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4802                              RSPEC_ISSGI(ratespec)) * 4;
4803
4804                 if (RSPEC_STC(ratespec) == 0)
4805                         /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4806                         nsyms =
4807                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4808                                   APHY_TAIL_NBITS) * 1000, kNdps);
4809                 else
4810                         /* STBC needs to have even number of symbols */
4811                         nsyms =
4812                             2 *
4813                             CEIL((APHY_SERVICE_NBITS + 8 * mac_len +
4814                                   APHY_TAIL_NBITS) * 1000, 2 * kNdps);
4815
4816                 dur += APHY_SYMBOL_TIME * nsyms;
4817                 if (BAND_2G(wlc->band->bandtype))
4818                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
4819         } else if (IS_OFDM(rate)) {
4820                 dur = APHY_PREAMBLE_TIME;
4821                 dur += APHY_SIGNAL_TIME;
4822                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
4823                 Ndps = rate * 2;
4824                 /* NSyms = CEILING((SERVICE + 8*NBytes + TAIL) / Ndbps) */
4825                 nsyms =
4826                     CEIL((APHY_SERVICE_NBITS + 8 * mac_len + APHY_TAIL_NBITS),
4827                          Ndps);
4828                 dur += APHY_SYMBOL_TIME * nsyms;
4829                 if (BAND_2G(wlc->band->bandtype))
4830                         dur += DOT11_OFDM_SIGNAL_EXTENSION;
4831         } else {
4832                 /* calc # bits * 2 so factor of 2 in rate (1/2 mbps) will divide out */
4833                 mac_len = mac_len * 8 * 2;
4834                 /* calc ceiling of bits/rate = microseconds of air time */
4835                 dur = (mac_len + rate - 1) / rate;
4836                 if (preamble_type & WLC_SHORT_PREAMBLE)
4837                         dur += BPHY_PLCP_SHORT_TIME;
4838                 else
4839                         dur += BPHY_PLCP_TIME;
4840         }
4841         return dur;
4842 }
4843
4844 /* The opposite of wlc_calc_frame_time */
4845 static uint
4846 wlc_calc_frame_len(struct wlc_info *wlc, ratespec_t ratespec, u8 preamble_type,
4847                    uint dur)
4848 {
4849         uint nsyms, mac_len, Ndps, kNdps;
4850         uint rate = RSPEC2RATE(ratespec);
4851
4852         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d, dur %d\n",
4853                  wlc->pub->unit, ratespec, preamble_type, dur);
4854
4855         if (IS_MCS(ratespec)) {
4856                 uint mcs = ratespec & RSPEC_RATE_MASK;
4857                 int tot_streams = MCS_TXS(mcs) + RSPEC_STC(ratespec);
4858                 dur -= PREN_PREAMBLE + (tot_streams * PREN_PREAMBLE_EXT);
4859                 /* payload calculation matches that of regular ofdm */
4860                 if (BAND_2G(wlc->band->bandtype))
4861                         dur -= DOT11_OFDM_SIGNAL_EXTENSION;
4862                 /* kNdbps = kbps * 4 */
4863                 kNdps =
4864                     MCS_RATE(mcs, RSPEC_IS40MHZ(ratespec),
4865                              RSPEC_ISSGI(ratespec)) * 4;
4866                 nsyms = dur / APHY_SYMBOL_TIME;
4867                 mac_len =
4868                     ((nsyms * kNdps) -
4869                      ((APHY_SERVICE_NBITS + APHY_TAIL_NBITS) * 1000)) / 8000;
4870         } else if (IS_OFDM(ratespec)) {
4871                 dur -= APHY_PREAMBLE_TIME;
4872                 dur -= APHY_SIGNAL_TIME;
4873                 /* Ndbps = Mbps * 4 = rate(500Kbps) * 2 */
4874                 Ndps = rate * 2;
4875                 nsyms = dur / APHY_SYMBOL_TIME;
4876                 mac_len =
4877                     ((nsyms * Ndps) -
4878                      (APHY_SERVICE_NBITS + APHY_TAIL_NBITS)) / 8;
4879         } else {
4880                 if (preamble_type & WLC_SHORT_PREAMBLE)
4881                         dur -= BPHY_PLCP_SHORT_TIME;
4882                 else
4883                         dur -= BPHY_PLCP_TIME;
4884                 mac_len = dur * rate;
4885                 /* divide out factor of 2 in rate (1/2 mbps) */
4886                 mac_len = mac_len / 8 / 2;
4887         }
4888         return mac_len;
4889 }
4890
4891 static uint
4892 wlc_calc_ba_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4893 {
4894         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, "
4895                  "preamble_type %d\n", wlc->pub->unit, rspec, preamble_type);
4896         /* Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that is less than
4897          * or equal to the rate of the immediately previous frame in the FES
4898          */
4899         rspec = WLC_BASIC_RATE(wlc, rspec);
4900         /* BA len == 32 == 16(ctl hdr) + 4(ba len) + 8(bitmap) + 4(fcs) */
4901         return wlc_calc_frame_time(wlc, rspec, preamble_type,
4902                                    (DOT11_BA_LEN + DOT11_BA_BITMAP_LEN +
4903                                     FCS_LEN));
4904 }
4905
4906 static uint
4907 wlc_calc_ack_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4908 {
4909         uint dur = 0;
4910
4911         BCMMSG(wlc->wiphy, "wl%d: rspec 0x%x, preamble_type %d\n",
4912                 wlc->pub->unit, rspec, preamble_type);
4913         /* Spec 9.6: ack rate is the highest rate in BSSBasicRateSet that is less than
4914          * or equal to the rate of the immediately previous frame in the FES
4915          */
4916         rspec = WLC_BASIC_RATE(wlc, rspec);
4917         /* ACK frame len == 14 == 2(fc) + 2(dur) + 6(ra) + 4(fcs) */
4918         dur =
4919             wlc_calc_frame_time(wlc, rspec, preamble_type,
4920                                 (DOT11_ACK_LEN + FCS_LEN));
4921         return dur;
4922 }
4923
4924 static uint
4925 wlc_calc_cts_time(struct wlc_info *wlc, ratespec_t rspec, u8 preamble_type)
4926 {
4927         BCMMSG(wlc->wiphy, "wl%d: ratespec 0x%x, preamble_type %d\n",
4928                 wlc->pub->unit, rspec, preamble_type);
4929         return wlc_calc_ack_time(wlc, rspec, preamble_type);
4930 }
4931
4932 /* derive wlc->band->basic_rate[] table from 'rateset' */
4933 void wlc_rate_lookup_init(struct wlc_info *wlc, wlc_rateset_t *rateset)
4934 {
4935         u8 rate;
4936         u8 mandatory;
4937         u8 cck_basic = 0;
4938         u8 ofdm_basic = 0;
4939         u8 *br = wlc->band->basic_rate;
4940         uint i;
4941
4942         /* incoming rates are in 500kbps units as in 802.11 Supported Rates */
4943         memset(br, 0, WLC_MAXRATE + 1);
4944
4945         /* For each basic rate in the rates list, make an entry in the
4946          * best basic lookup.
4947          */
4948         for (i = 0; i < rateset->count; i++) {
4949                 /* only make an entry for a basic rate */
4950                 if (!(rateset->rates[i] & WLC_RATE_FLAG))
4951                         continue;
4952
4953                 /* mask off basic bit */
4954                 rate = (rateset->rates[i] & WLC_RATE_MASK);
4955
4956                 if (rate > WLC_MAXRATE) {
4957                         wiphy_err(wlc->wiphy, "wlc_rate_lookup_init: invalid "
4958                                   "rate 0x%X in rate set\n",
4959                                   rateset->rates[i]);
4960                         continue;
4961                 }
4962
4963                 br[rate] = rate;
4964         }
4965
4966         /* The rate lookup table now has non-zero entries for each
4967          * basic rate, equal to the basic rate: br[basicN] = basicN
4968          *
4969          * To look up the best basic rate corresponding to any
4970          * particular rate, code can use the basic_rate table
4971          * like this
4972          *
4973          * basic_rate = wlc->band->basic_rate[tx_rate]
4974          *
4975          * Make sure there is a best basic rate entry for
4976          * every rate by walking up the table from low rates
4977          * to high, filling in holes in the lookup table
4978          */
4979
4980         for (i = 0; i < wlc->band->hw_rateset.count; i++) {
4981                 rate = wlc->band->hw_rateset.rates[i];
4982
4983                 if (br[rate] != 0) {
4984                         /* This rate is a basic rate.
4985                          * Keep track of the best basic rate so far by
4986                          * modulation type.
4987                          */
4988                         if (IS_OFDM(rate))
4989                                 ofdm_basic = rate;
4990                         else
4991                                 cck_basic = rate;
4992
4993                         continue;
4994                 }
4995
4996                 /* This rate is not a basic rate so figure out the
4997                  * best basic rate less than this rate and fill in
4998                  * the hole in the table
4999                  */
5000
5001                 br[rate] = IS_OFDM(rate) ? ofdm_basic : cck_basic;
5002
5003                 if (br[rate] != 0)
5004                         continue;
5005
5006                 if (IS_OFDM(rate)) {
5007                         /* In 11g and 11a, the OFDM mandatory rates are 6, 12, and 24 Mbps */
5008                         if (rate >= WLC_RATE_24M)
5009                                 mandatory = WLC_RATE_24M;
5010                         else if (rate >= WLC_RATE_12M)
5011                                 mandatory = WLC_RATE_12M;
5012                         else
5013                                 mandatory = WLC_RATE_6M;
5014                 } else {
5015                         /* In 11b, all the CCK rates are mandatory 1 - 11 Mbps */
5016                         mandatory = rate;
5017                 }
5018
5019                 br[rate] = mandatory;
5020         }
5021 }
5022
5023 static void wlc_write_rate_shm(struct wlc_info *wlc, u8 rate, u8 basic_rate)
5024 {
5025         u8 phy_rate, index;
5026         u8 basic_phy_rate, basic_index;
5027         u16 dir_table, basic_table;
5028         u16 basic_ptr;
5029
5030         /* Shared memory address for the table we are reading */
5031         dir_table = IS_OFDM(basic_rate) ? M_RT_DIRMAP_A : M_RT_DIRMAP_B;
5032
5033         /* Shared memory address for the table we are writing */
5034         basic_table = IS_OFDM(rate) ? M_RT_BBRSMAP_A : M_RT_BBRSMAP_B;
5035
5036         /*
5037          * for a given rate, the LS-nibble of the PLCP SIGNAL field is
5038          * the index into the rate table.
5039          */
5040         phy_rate = rate_info[rate] & WLC_RATE_MASK;
5041         basic_phy_rate = rate_info[basic_rate] & WLC_RATE_MASK;
5042         index = phy_rate & 0xf;
5043         basic_index = basic_phy_rate & 0xf;
5044
5045         /* Find the SHM pointer to the ACK rate entry by looking in the
5046          * Direct-map Table
5047          */
5048         basic_ptr = wlc_read_shm(wlc, (dir_table + basic_index * 2));
5049
5050         /* Update the SHM BSS-basic-rate-set mapping table with the pointer
5051          * to the correct basic rate for the given incoming rate
5052          */
5053         wlc_write_shm(wlc, (basic_table + index * 2), basic_ptr);
5054 }
5055
5056 static const wlc_rateset_t *wlc_rateset_get_hwrs(struct wlc_info *wlc)
5057 {
5058         const wlc_rateset_t *rs_dflt;
5059
5060         if (WLC_PHY_11N_CAP(wlc->band)) {
5061                 if (BAND_5G(wlc->band->bandtype))
5062                         rs_dflt = &ofdm_mimo_rates;
5063                 else
5064                         rs_dflt = &cck_ofdm_mimo_rates;
5065         } else if (wlc->band->gmode)
5066                 rs_dflt = &cck_ofdm_rates;
5067         else
5068                 rs_dflt = &cck_rates;
5069
5070         return rs_dflt;
5071 }
5072
5073 void wlc_set_ratetable(struct wlc_info *wlc)
5074 {
5075         const wlc_rateset_t *rs_dflt;
5076         wlc_rateset_t rs;
5077         u8 rate, basic_rate;
5078         uint i;
5079
5080         rs_dflt = wlc_rateset_get_hwrs(wlc);
5081
5082         wlc_rateset_copy(rs_dflt, &rs);
5083         wlc_rateset_mcs_upd(&rs, wlc->stf->txstreams);
5084
5085         /* walk the phy rate table and update SHM basic rate lookup table */
5086         for (i = 0; i < rs.count; i++) {
5087                 rate = rs.rates[i] & WLC_RATE_MASK;
5088
5089                 /* for a given rate WLC_BASIC_RATE returns the rate at
5090                  * which a response ACK/CTS should be sent.
5091                  */
5092                 basic_rate = WLC_BASIC_RATE(wlc, rate);
5093                 if (basic_rate == 0) {
5094                         /* This should only happen if we are using a
5095                          * restricted rateset.
5096                          */
5097                         basic_rate = rs.rates[0] & WLC_RATE_MASK;
5098                 }
5099
5100                 wlc_write_rate_shm(wlc, rate, basic_rate);
5101         }
5102 }
5103
5104 /*
5105  * Return true if the specified rate is supported by the specified band.
5106  * WLC_BAND_AUTO indicates the current band.
5107  */
5108 bool wlc_valid_rate(struct wlc_info *wlc, ratespec_t rspec, int band,
5109                     bool verbose)
5110 {
5111         wlc_rateset_t *hw_rateset;
5112         uint i;
5113
5114         if ((band == WLC_BAND_AUTO) || (band == wlc->band->bandtype)) {
5115                 hw_rateset = &wlc->band->hw_rateset;
5116         } else if (NBANDS(wlc) > 1) {
5117                 hw_rateset = &wlc->bandstate[OTHERBANDUNIT(wlc)]->hw_rateset;
5118         } else {
5119                 /* other band specified and we are a single band device */
5120                 return false;
5121         }
5122
5123         /* check if this is a mimo rate */
5124         if (IS_MCS(rspec)) {
5125                 if (!VALID_MCS((rspec & RSPEC_RATE_MASK)))
5126                         goto error;
5127
5128                 return isset(hw_rateset->mcs, (rspec & RSPEC_RATE_MASK));
5129         }
5130
5131         for (i = 0; i < hw_rateset->count; i++)
5132                 if (hw_rateset->rates[i] == RSPEC2RATE(rspec))
5133                         return true;
5134  error:
5135         if (verbose) {
5136                 wiphy_err(wlc->wiphy, "wl%d: wlc_valid_rate: rate spec 0x%x "
5137                           "not in hw_rateset\n", wlc->pub->unit, rspec);
5138         }
5139
5140         return false;
5141 }
5142
5143 static void wlc_update_mimo_band_bwcap(struct wlc_info *wlc, u8 bwcap)
5144 {
5145         uint i;
5146         struct wlcband *band;
5147
5148         for (i = 0; i < NBANDS(wlc); i++) {
5149                 if (IS_SINGLEBAND_5G(wlc->deviceid))
5150                         i = BAND_5G_INDEX;
5151                 band = wlc->bandstate[i];
5152                 if (band->bandtype == WLC_BAND_5G) {
5153                         if ((bwcap == WLC_N_BW_40ALL)
5154                             || (bwcap == WLC_N_BW_20IN2G_40IN5G))
5155                                 band->mimo_cap_40 = true;
5156                         else
5157                                 band->mimo_cap_40 = false;
5158                 } else {
5159                         if (bwcap == WLC_N_BW_40ALL)
5160                                 band->mimo_cap_40 = true;
5161                         else
5162                                 band->mimo_cap_40 = false;
5163                 }
5164         }
5165 }
5166
5167 void wlc_mod_prb_rsp_rate_table(struct wlc_info *wlc, uint frame_len)
5168 {
5169         const wlc_rateset_t *rs_dflt;
5170         wlc_rateset_t rs;
5171         u8 rate;
5172         u16 entry_ptr;
5173         u8 plcp[D11_PHY_HDR_LEN];
5174         u16 dur, sifs;
5175         uint i;
5176
5177         sifs = SIFS(wlc->band);
5178
5179         rs_dflt = wlc_rateset_get_hwrs(wlc);
5180
5181         wlc_rateset_copy(rs_dflt, &rs);
5182         wlc_rateset_mcs_upd(&rs, wlc->stf->txstreams);
5183
5184         /* walk the phy rate table and update MAC core SHM basic rate table entries */
5185         for (i = 0; i < rs.count; i++) {
5186                 rate = rs.rates[i] & WLC_RATE_MASK;
5187
5188                 entry_ptr = wlc_rate_shm_offset(wlc, rate);
5189
5190                 /* Calculate the Probe Response PLCP for the given rate */
5191                 wlc_compute_plcp(wlc, rate, frame_len, plcp);
5192
5193                 /* Calculate the duration of the Probe Response frame plus SIFS for the MAC */
5194                 dur =
5195                     (u16) wlc_calc_frame_time(wlc, rate, WLC_LONG_PREAMBLE,
5196                                                  frame_len);
5197                 dur += sifs;
5198
5199                 /* Update the SHM Rate Table entry Probe Response values */
5200                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS,
5201                               (u16) (plcp[0] + (plcp[1] << 8)));
5202                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_PLCP_POS + 2,
5203                               (u16) (plcp[2] + (plcp[3] << 8)));
5204                 wlc_write_shm(wlc, entry_ptr + M_RT_PRS_DUR_POS, dur);
5205         }
5206 }
5207
5208 /*      Max buffering needed for beacon template/prb resp template is 142 bytes.
5209  *
5210  *      PLCP header is 6 bytes.
5211  *      802.11 A3 header is 24 bytes.
5212  *      Max beacon frame body template length is 112 bytes.
5213  *      Max probe resp frame body template length is 110 bytes.
5214  *
5215  *      *len on input contains the max length of the packet available.
5216  *
5217  *      The *len value is set to the number of bytes in buf used, and starts with the PLCP
5218  *      and included up to, but not including, the 4 byte FCS.
5219  */
5220 static void
5221 wlc_bcn_prb_template(struct wlc_info *wlc, u16 type, ratespec_t bcn_rspec,
5222                      struct wlc_bsscfg *cfg, u16 *buf, int *len)
5223 {
5224         static const u8 ether_bcast[ETH_ALEN] = {255, 255, 255, 255, 255, 255};
5225         cck_phy_hdr_t *plcp;
5226         struct ieee80211_mgmt *h;
5227         int hdr_len, body_len;
5228
5229         if (MBSS_BCN_ENAB(cfg) && type == IEEE80211_STYPE_BEACON)
5230                 hdr_len = DOT11_MAC_HDR_LEN;
5231         else
5232                 hdr_len = D11_PHY_HDR_LEN + DOT11_MAC_HDR_LEN;
5233         body_len = *len - hdr_len;      /* calc buffer size provided for frame body */
5234
5235         *len = hdr_len + body_len;      /* return actual size */
5236
5237         /* format PHY and MAC headers */
5238         memset((char *)buf, 0, hdr_len);
5239
5240         plcp = (cck_phy_hdr_t *) buf;
5241
5242         /* PLCP for Probe Response frames are filled in from core's rate table */
5243         if (type == IEEE80211_STYPE_BEACON && !MBSS_BCN_ENAB(cfg)) {
5244                 /* fill in PLCP */
5245                 wlc_compute_plcp(wlc, bcn_rspec,
5246                                  (DOT11_MAC_HDR_LEN + body_len + FCS_LEN),
5247                                  (u8 *) plcp);
5248
5249         }
5250         /* "Regular" and 16 MBSS but not for 4 MBSS */
5251         /* Update the phytxctl for the beacon based on the rspec */
5252         if (!SOFTBCN_ENAB(cfg))
5253                 wlc_beacon_phytxctl_txant_upd(wlc, bcn_rspec);
5254
5255         if (MBSS_BCN_ENAB(cfg) && type == IEEE80211_STYPE_BEACON)
5256                 h = (struct ieee80211_mgmt *)&plcp[0];
5257         else
5258                 h = (struct ieee80211_mgmt *)&plcp[1];
5259
5260         /* fill in 802.11 header */
5261         h->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | type);
5262
5263         /* DUR is 0 for multicast bcn, or filled in by MAC for prb resp */
5264         /* A1 filled in by MAC for prb resp, broadcast for bcn */
5265         if (type == IEEE80211_STYPE_BEACON)
5266                 memcpy(&h->da, &ether_bcast, ETH_ALEN);
5267         memcpy(&h->sa, &cfg->cur_etheraddr, ETH_ALEN);
5268         memcpy(&h->bssid, &cfg->BSSID, ETH_ALEN);
5269
5270         /* SEQ filled in by MAC */
5271
5272         return;
5273 }
5274
5275 int wlc_get_header_len()
5276 {
5277         return TXOFF;
5278 }
5279
5280 /* Update a beacon for a particular BSS
5281  * For MBSS, this updates the software template and sets "latest" to the index of the
5282  * template updated.
5283  * Otherwise, it updates the hardware template.
5284  */
5285 void wlc_bss_update_beacon(struct wlc_info *wlc, struct wlc_bsscfg *cfg)
5286 {
5287         int len = BCN_TMPL_LEN;
5288
5289         /* Clear the soft intmask */
5290         wlc->defmacintmask &= ~MI_BCNTPL;
5291
5292         if (!cfg->up) {         /* Only allow updates on an UP bss */
5293                 return;
5294         }
5295
5296         /* Optimize:  Some of if/else could be combined */
5297         if (!MBSS_BCN_ENAB(cfg) && HWBCN_ENAB(cfg)) {
5298                 /* Hardware beaconing for this config */
5299                 u16 bcn[BCN_TMPL_LEN / 2];
5300                 u32 both_valid = MCMD_BCN0VLD | MCMD_BCN1VLD;
5301                 d11regs_t *regs = wlc->regs;
5302
5303                 /* Check if both templates are in use, if so sched. an interrupt
5304                  *      that will call back into this routine
5305                  */
5306                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
5307                         /* clear any previous status */
5308                         W_REG(&regs->macintstatus, MI_BCNTPL);
5309                 }
5310                 /* Check that after scheduling the interrupt both of the
5311                  *      templates are still busy. if not clear the int. & remask
5312                  */
5313                 if ((R_REG(&regs->maccommand) & both_valid) == both_valid) {
5314                         wlc->defmacintmask |= MI_BCNTPL;
5315                         return;
5316                 }
5317
5318                 wlc->bcn_rspec =
5319                     wlc_lowest_basic_rspec(wlc, &cfg->current_bss->rateset);
5320                 /* update the template and ucode shm */
5321                 wlc_bcn_prb_template(wlc, IEEE80211_STYPE_BEACON,
5322                                      wlc->bcn_rspec, cfg, bcn, &len);
5323                 wlc_write_hw_bcntemplates(wlc, bcn, len, false);
5324         }
5325 }
5326
5327 /*
5328  * Update all beacons for the system.
5329  */
5330 void wlc_update_beacon(struct wlc_info *wlc)
5331 {
5332         int idx;
5333         struct wlc_bsscfg *bsscfg;
5334
5335         /* update AP or IBSS beacons */
5336         FOREACH_BSS(wlc, idx, bsscfg) {
5337                 if (bsscfg->up && (BSSCFG_AP(bsscfg) || !bsscfg->BSS))
5338                         wlc_bss_update_beacon(wlc, bsscfg);
5339         }
5340 }
5341
5342 /* Write ssid into shared memory */
5343 void wlc_shm_ssid_upd(struct wlc_info *wlc, struct wlc_bsscfg *cfg)
5344 {
5345         u8 *ssidptr = cfg->SSID;
5346         u16 base = M_SSID;
5347         u8 ssidbuf[IEEE80211_MAX_SSID_LEN];
5348
5349         /* padding the ssid with zero and copy it into shm */
5350         memset(ssidbuf, 0, IEEE80211_MAX_SSID_LEN);
5351         memcpy(ssidbuf, ssidptr, cfg->SSID_len);
5352
5353         wlc_copyto_shm(wlc, base, ssidbuf, IEEE80211_MAX_SSID_LEN);
5354
5355         if (!MBSS_BCN_ENAB(cfg))
5356                 wlc_write_shm(wlc, M_SSIDLEN, (u16) cfg->SSID_len);
5357 }
5358
5359 void wlc_update_probe_resp(struct wlc_info *wlc, bool suspend)
5360 {
5361         int idx;
5362         struct wlc_bsscfg *bsscfg;
5363
5364         /* update AP or IBSS probe responses */
5365         FOREACH_BSS(wlc, idx, bsscfg) {
5366                 if (bsscfg->up && (BSSCFG_AP(bsscfg) || !bsscfg->BSS))
5367                         wlc_bss_update_probe_resp(wlc, bsscfg, suspend);
5368         }
5369 }
5370
5371 void
5372 wlc_bss_update_probe_resp(struct wlc_info *wlc, struct wlc_bsscfg *cfg,
5373                           bool suspend)
5374 {
5375         u16 prb_resp[BCN_TMPL_LEN / 2];
5376         int len = BCN_TMPL_LEN;
5377
5378         /* write the probe response to hardware, or save in the config structure */
5379         if (!MBSS_PRB_ENAB(cfg)) {
5380
5381                 /* create the probe response template */
5382                 wlc_bcn_prb_template(wlc, IEEE80211_STYPE_PROBE_RESP, 0, cfg,
5383                                      prb_resp, &len);
5384
5385                 if (suspend)
5386                         wlc_suspend_mac_and_wait(wlc);
5387
5388                 /* write the probe response into the template region */
5389                 wlc_bmac_write_template_ram(wlc->hw, T_PRS_TPL_BASE,
5390                                             (len + 3) & ~3, prb_resp);
5391
5392                 /* write the length of the probe response frame (+PLCP/-FCS) */
5393                 wlc_write_shm(wlc, M_PRB_RESP_FRM_LEN, (u16) len);
5394
5395                 /* write the SSID and SSID length */
5396                 wlc_shm_ssid_upd(wlc, cfg);
5397
5398                 /*
5399                  * Write PLCP headers and durations for probe response frames at all rates.
5400                  * Use the actual frame length covered by the PLCP header for the call to
5401                  * wlc_mod_prb_rsp_rate_table() by subtracting the PLCP len and adding the FCS.
5402                  */
5403                 len += (-D11_PHY_HDR_LEN + FCS_LEN);
5404                 wlc_mod_prb_rsp_rate_table(wlc, (u16) len);
5405
5406                 if (suspend)
5407                         wlc_enable_mac(wlc);
5408         } else {                /* Generating probe resp in sw; update local template */
5409                 /* error: No software probe response support without MBSS */
5410         }
5411 }
5412
5413 /* prepares pdu for transmission. returns BCM error codes */
5414 int wlc_prep_pdu(struct wlc_info *wlc, struct sk_buff *pdu, uint *fifop)
5415 {
5416         uint fifo;
5417         d11txh_t *txh;
5418         struct ieee80211_hdr *h;
5419         struct scb *scb;
5420
5421         txh = (d11txh_t *) (pdu->data);
5422         h = (struct ieee80211_hdr *)((u8 *) (txh + 1) + D11_PHY_HDR_LEN);
5423
5424         /* get the pkt queue info. This was put at wlc_sendctl or wlc_send for PDU */
5425         fifo = le16_to_cpu(txh->TxFrameID) & TXFID_QUEUE_MASK;
5426
5427         scb = NULL;
5428
5429         *fifop = fifo;
5430
5431         /* return if insufficient dma resources */
5432         if (TXAVAIL(wlc, fifo) < MAX_DMA_SEGS) {
5433                 /* Mark precedences related to this FIFO, unsendable */
5434                 WLC_TX_FIFO_CLEAR(wlc, fifo);
5435                 return -EBUSY;
5436         }
5437         return 0;
5438 }
5439
5440 /* init tx reported rate mechanism */
5441 void wlc_reprate_init(struct wlc_info *wlc)
5442 {
5443         int i;
5444         struct wlc_bsscfg *bsscfg;
5445
5446         FOREACH_BSS(wlc, i, bsscfg) {
5447                 wlc_bsscfg_reprate_init(bsscfg);
5448         }
5449 }
5450
5451 /* per bsscfg init tx reported rate mechanism */
5452 void wlc_bsscfg_reprate_init(struct wlc_bsscfg *bsscfg)
5453 {
5454         bsscfg->txrspecidx = 0;
5455         memset((char *)bsscfg->txrspec, 0, sizeof(bsscfg->txrspec));
5456 }
5457
5458 void wlc_default_rateset(struct wlc_info *wlc, wlc_rateset_t *rs)
5459 {
5460         wlc_rateset_default(rs, NULL, wlc->band->phytype, wlc->band->bandtype,
5461                             false, WLC_RATE_MASK_FULL, (bool) N_ENAB(wlc->pub),
5462                             CHSPEC_WLC_BW(wlc->default_bss->chanspec),
5463                             wlc->stf->txstreams);
5464 }
5465
5466 static void wlc_bss_default_init(struct wlc_info *wlc)
5467 {
5468         chanspec_t chanspec;
5469         struct wlcband *band;
5470         wlc_bss_info_t *bi = wlc->default_bss;
5471
5472         /* init default and target BSS with some sane initial values */
5473         memset((char *)(bi), 0, sizeof(wlc_bss_info_t));
5474         bi->beacon_period = ISSIM_ENAB(wlc->pub->sih) ? BEACON_INTERVAL_DEF_QT :
5475             BEACON_INTERVAL_DEFAULT;
5476         bi->dtim_period = ISSIM_ENAB(wlc->pub->sih) ? DTIM_INTERVAL_DEF_QT :
5477             DTIM_INTERVAL_DEFAULT;
5478
5479         /* fill the default channel as the first valid channel
5480          * starting from the 2G channels
5481          */
5482         chanspec = CH20MHZ_CHSPEC(1);
5483         wlc->home_chanspec = bi->chanspec = chanspec;
5484
5485         /* find the band of our default channel */
5486         band = wlc->band;
5487         if (NBANDS(wlc) > 1 && band->bandunit != CHSPEC_WLCBANDUNIT(chanspec))
5488                 band = wlc->bandstate[OTHERBANDUNIT(wlc)];
5489
5490         /* init bss rates to the band specific default rate set */
5491         wlc_rateset_default(&bi->rateset, NULL, band->phytype, band->bandtype,
5492                             false, WLC_RATE_MASK_FULL, (bool) N_ENAB(wlc->pub),
5493                             CHSPEC_WLC_BW(chanspec), wlc->stf->txstreams);
5494
5495         if (N_ENAB(wlc->pub))
5496                 bi->flags |= WLC_BSS_HT;
5497 }
5498
5499 static ratespec_t
5500 mac80211_wlc_set_nrate(struct wlc_info *wlc, struct wlcband *cur_band,
5501                        u32 int_val)
5502 {
5503         u8 stf = (int_val & NRATE_STF_MASK) >> NRATE_STF_SHIFT;
5504         u8 rate = int_val & NRATE_RATE_MASK;
5505         ratespec_t rspec;
5506         bool ismcs = ((int_val & NRATE_MCS_INUSE) == NRATE_MCS_INUSE);
5507         bool issgi = ((int_val & NRATE_SGI_MASK) >> NRATE_SGI_SHIFT);
5508         bool override_mcs_only = ((int_val & NRATE_OVERRIDE_MCS_ONLY)
5509                                   == NRATE_OVERRIDE_MCS_ONLY);
5510         int bcmerror = 0;
5511
5512         if (!ismcs) {
5513                 return (ratespec_t) rate;
5514         }
5515
5516         /* validate the combination of rate/mcs/stf is allowed */
5517         if (N_ENAB(wlc->pub) && ismcs) {
5518                 /* mcs only allowed when nmode */
5519                 if (stf > PHY_TXC1_MODE_SDM) {
5520                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid stf\n",
5521                                  WLCWLUNIT(wlc), __func__);
5522                         bcmerror = -EINVAL;
5523                         goto done;
5524                 }
5525
5526                 /* mcs 32 is a special case, DUP mode 40 only */
5527                 if (rate == 32) {
5528                         if (!CHSPEC_IS40(wlc->home_chanspec) ||
5529                             ((stf != PHY_TXC1_MODE_SISO)
5530                              && (stf != PHY_TXC1_MODE_CDD))) {
5531                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid mcs "
5532                                           "32\n", WLCWLUNIT(wlc), __func__);
5533                                 bcmerror = -EINVAL;
5534                                 goto done;
5535                         }
5536                         /* mcs > 7 must use stf SDM */
5537                 } else if (rate > HIGHEST_SINGLE_STREAM_MCS) {
5538                         /* mcs > 7 must use stf SDM */
5539                         if (stf != PHY_TXC1_MODE_SDM) {
5540                                 BCMMSG(wlc->wiphy, "wl%d: enabling "
5541                                          "SDM mode for mcs %d\n",
5542                                          WLCWLUNIT(wlc), rate);
5543                                 stf = PHY_TXC1_MODE_SDM;
5544                         }
5545                 } else {
5546                         /* MCS 0-7 may use SISO, CDD, and for phy_rev >= 3 STBC */
5547                         if ((stf > PHY_TXC1_MODE_STBC) ||
5548                             (!WLC_STBC_CAP_PHY(wlc)
5549                              && (stf == PHY_TXC1_MODE_STBC))) {
5550                                 wiphy_err(wlc->wiphy, "wl%d: %s: Invalid STBC"
5551                                           "\n", WLCWLUNIT(wlc), __func__);
5552                                 bcmerror = -EINVAL;
5553                                 goto done;
5554                         }
5555                 }
5556         } else if (IS_OFDM(rate)) {
5557                 if ((stf != PHY_TXC1_MODE_CDD) && (stf != PHY_TXC1_MODE_SISO)) {
5558                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid OFDM\n",
5559                                   WLCWLUNIT(wlc), __func__);
5560                         bcmerror = -EINVAL;
5561                         goto done;
5562                 }
5563         } else if (IS_CCK(rate)) {
5564                 if ((cur_band->bandtype != WLC_BAND_2G)
5565                     || (stf != PHY_TXC1_MODE_SISO)) {
5566                         wiphy_err(wlc->wiphy, "wl%d: %s: Invalid CCK\n",
5567                                   WLCWLUNIT(wlc), __func__);
5568                         bcmerror = -EINVAL;
5569                         goto done;
5570                 }
5571         } else {
5572                 wiphy_err(wlc->wiphy, "wl%d: %s: Unknown rate type\n",
5573                           WLCWLUNIT(wlc), __func__);
5574                 bcmerror = -EINVAL;
5575                 goto done;
5576         }
5577         /* make sure multiple antennae are available for non-siso rates */
5578         if ((stf != PHY_TXC1_MODE_SISO) && (wlc->stf->txstreams == 1)) {
5579                 wiphy_err(wlc->wiphy, "wl%d: %s: SISO antenna but !SISO "
5580                           "request\n", WLCWLUNIT(wlc), __func__);
5581                 bcmerror = -EINVAL;
5582                 goto done;
5583         }
5584
5585         rspec = rate;
5586         if (ismcs) {
5587                 rspec |= RSPEC_MIMORATE;
5588                 /* For STBC populate the STC field of the ratespec */
5589                 if (stf == PHY_TXC1_MODE_STBC) {
5590                         u8 stc;
5591                         stc = 1;        /* Nss for single stream is always 1 */
5592                         rspec |= (stc << RSPEC_STC_SHIFT);
5593                 }
5594         }
5595
5596         rspec |= (stf << RSPEC_STF_SHIFT);
5597
5598         if (override_mcs_only)
5599                 rspec |= RSPEC_OVERRIDE_MCS_ONLY;
5600
5601         if (issgi)
5602                 rspec |= RSPEC_SHORT_GI;
5603
5604         if ((rate != 0)
5605             && !wlc_valid_rate(wlc, rspec, cur_band->bandtype, true)) {
5606                 return rate;
5607         }
5608
5609         return rspec;
5610 done:
5611         return rate;
5612 }
5613
5614 /* formula:  IDLE_BUSY_RATIO_X_16 = (100-duty_cycle)/duty_cycle*16 */
5615 static int
5616 wlc_duty_cycle_set(struct wlc_info *wlc, int duty_cycle, bool isOFDM,
5617                    bool writeToShm)
5618 {
5619         int idle_busy_ratio_x_16 = 0;
5620         uint offset =
5621             isOFDM ? M_TX_IDLE_BUSY_RATIO_X_16_OFDM :
5622             M_TX_IDLE_BUSY_RATIO_X_16_CCK;
5623         if (duty_cycle > 100 || duty_cycle < 0) {
5624                 wiphy_err(wlc->wiphy, "wl%d:  duty cycle value off limit\n",
5625                           wlc->pub->unit);
5626                 return -EINVAL;
5627         }
5628         if (duty_cycle)
5629                 idle_busy_ratio_x_16 = (100 - duty_cycle) * 16 / duty_cycle;
5630         /* Only write to shared memory  when wl is up */
5631         if (writeToShm)
5632                 wlc_write_shm(wlc, offset, (u16) idle_busy_ratio_x_16);
5633
5634         if (isOFDM)
5635                 wlc->tx_duty_cycle_ofdm = (u16) duty_cycle;
5636         else
5637                 wlc->tx_duty_cycle_cck = (u16) duty_cycle;
5638
5639         return 0;
5640 }
5641
5642 /* Read a single u16 from shared memory.
5643  * SHM 'offset' needs to be an even address
5644  */
5645 u16 wlc_read_shm(struct wlc_info *wlc, uint offset)
5646 {
5647         return wlc_bmac_read_shm(wlc->hw, offset);
5648 }
5649
5650 /* Write a single u16 to shared memory.
5651  * SHM 'offset' needs to be an even address
5652  */
5653 void wlc_write_shm(struct wlc_info *wlc, uint offset, u16 v)
5654 {
5655         wlc_bmac_write_shm(wlc->hw, offset, v);
5656 }
5657
5658 /* Copy a buffer to shared memory.
5659  * SHM 'offset' needs to be an even address and
5660  * Buffer length 'len' must be an even number of bytes
5661  */
5662 void wlc_copyto_shm(struct wlc_info *wlc, uint offset, const void *buf, int len)
5663 {
5664         /* offset and len need to be even */
5665         if (len <= 0 || (offset & 1) || (len & 1))
5666                 return;
5667
5668         wlc_bmac_copyto_objmem(wlc->hw, offset, buf, len, OBJADDR_SHM_SEL);
5669
5670 }
5671
5672 /* wrapper BMAC functions to for HIGH driver access */
5673 void wlc_mctrl(struct wlc_info *wlc, u32 mask, u32 val)
5674 {
5675         wlc_bmac_mctrl(wlc->hw, mask, val);
5676 }
5677
5678 void wlc_mhf(struct wlc_info *wlc, u8 idx, u16 mask, u16 val, int bands)
5679 {
5680         wlc_bmac_mhf(wlc->hw, idx, mask, val, bands);
5681 }
5682
5683 int wlc_xmtfifo_sz_get(struct wlc_info *wlc, uint fifo, uint *blocks)
5684 {
5685         return wlc_bmac_xmtfifo_sz_get(wlc->hw, fifo, blocks);
5686 }
5687
5688 void wlc_write_template_ram(struct wlc_info *wlc, int offset, int len,
5689                             void *buf)
5690 {
5691         wlc_bmac_write_template_ram(wlc->hw, offset, len, buf);
5692 }
5693
5694 void wlc_write_hw_bcntemplates(struct wlc_info *wlc, void *bcn, int len,
5695                                bool both)
5696 {
5697         wlc_bmac_write_hw_bcntemplates(wlc->hw, bcn, len, both);
5698 }
5699
5700 void
5701 wlc_set_addrmatch(struct wlc_info *wlc, int match_reg_offset,
5702                   const u8 *addr)
5703 {
5704         wlc_bmac_set_addrmatch(wlc->hw, match_reg_offset, addr);
5705         if (match_reg_offset == RCM_BSSID_OFFSET)
5706                 memcpy(wlc->cfg->BSSID, addr, ETH_ALEN);
5707 }
5708
5709 void wlc_pllreq(struct wlc_info *wlc, bool set, mbool req_bit)
5710 {
5711         wlc_bmac_pllreq(wlc->hw, set, req_bit);
5712 }
5713
5714 void wlc_reset_bmac_done(struct wlc_info *wlc)
5715 {
5716 }
5717
5718 /* check for the particular priority flow control bit being set */
5719 bool
5720 wlc_txflowcontrol_prio_isset(struct wlc_info *wlc, struct wlc_txq_info *q,
5721                              int prio)
5722 {
5723         uint prio_mask;
5724
5725         if (prio == ALLPRIO) {
5726                 prio_mask = TXQ_STOP_FOR_PRIOFC_MASK;
5727         } else {
5728                 prio_mask = NBITVAL(prio);
5729         }
5730
5731         return (q->stopped & prio_mask) == prio_mask;
5732 }
5733
5734 /* propagate the flow control to all interfaces using the given tx queue */
5735 void wlc_txflowcontrol(struct wlc_info *wlc, struct wlc_txq_info *qi,
5736                        bool on, int prio)
5737 {
5738         uint prio_bits;
5739         uint cur_bits;
5740
5741         BCMMSG(wlc->wiphy, "flow control kicks in\n");
5742
5743         if (prio == ALLPRIO) {
5744                 prio_bits = TXQ_STOP_FOR_PRIOFC_MASK;
5745         } else {
5746                 prio_bits = NBITVAL(prio);
5747         }
5748
5749         cur_bits = qi->stopped & prio_bits;
5750
5751         /* Check for the case of no change and return early
5752          * Otherwise update the bit and continue
5753          */
5754         if (on) {
5755                 if (cur_bits == prio_bits) {
5756                         return;
5757                 }
5758                 mboolset(qi->stopped, prio_bits);
5759         } else {
5760                 if (cur_bits == 0) {
5761                         return;
5762                 }
5763                 mboolclr(qi->stopped, prio_bits);
5764         }
5765
5766         /* If there is a flow control override we will not change the external
5767          * flow control state.
5768          */
5769         if (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK) {
5770                 return;
5771         }
5772
5773         wlc_txflowcontrol_signal(wlc, qi, on, prio);
5774 }
5775
5776 void
5777 wlc_txflowcontrol_override(struct wlc_info *wlc, struct wlc_txq_info *qi,
5778                            bool on, uint override)
5779 {
5780         uint prev_override;
5781
5782         prev_override = (qi->stopped & ~TXQ_STOP_FOR_PRIOFC_MASK);
5783
5784         /* Update the flow control bits and do an early return if there is
5785          * no change in the external flow control state.
5786          */
5787         if (on) {
5788                 mboolset(qi->stopped, override);
5789                 /* if there was a previous override bit on, then setting this
5790                  * makes no difference.
5791                  */
5792                 if (prev_override) {
5793                         return;
5794                 }
5795
5796                 wlc_txflowcontrol_signal(wlc, qi, ON, ALLPRIO);
5797         } else {
5798                 mboolclr(qi->stopped, override);
5799                 /* clearing an override bit will only make a difference for
5800                  * flow control if it was the only bit set. For any other
5801                  * override setting, just return
5802                  */
5803                 if (prev_override != override) {
5804                         return;
5805                 }
5806
5807                 if (qi->stopped == 0) {
5808                         wlc_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
5809                 } else {
5810                         int prio;
5811
5812                         for (prio = MAXPRIO; prio >= 0; prio--) {
5813                                 if (!mboolisset(qi->stopped, NBITVAL(prio)))
5814                                         wlc_txflowcontrol_signal(wlc, qi, OFF,
5815                                                                  prio);
5816                         }
5817                 }
5818         }
5819 }
5820
5821 static void wlc_txflowcontrol_reset(struct wlc_info *wlc)
5822 {
5823         struct wlc_txq_info *qi;
5824
5825         for (qi = wlc->tx_queues; qi != NULL; qi = qi->next) {
5826                 if (qi->stopped) {
5827                         wlc_txflowcontrol_signal(wlc, qi, OFF, ALLPRIO);
5828                         qi->stopped = 0;
5829                 }
5830         }
5831 }
5832
5833 static void
5834 wlc_txflowcontrol_signal(struct wlc_info *wlc, struct wlc_txq_info *qi, bool on,
5835                          int prio)
5836 {
5837 #ifdef NON_FUNCTIONAL
5838         /* wlcif_list is never filled so this function is not functional */
5839         struct wlc_if *wlcif;
5840
5841         for (wlcif = wlc->wlcif_list; wlcif != NULL; wlcif = wlcif->next) {
5842                 if (wlcif->qi == qi && wlcif->flags & WLC_IF_LINKED)
5843                         brcms_txflowcontrol(wlc->wl, wlcif->wlif, on, prio);
5844         }
5845 #endif
5846 }
5847
5848 static struct wlc_txq_info *wlc_txq_alloc(struct wlc_info *wlc)
5849 {
5850         struct wlc_txq_info *qi, *p;
5851
5852         qi = kzalloc(sizeof(struct wlc_txq_info), GFP_ATOMIC);
5853         if (qi != NULL) {
5854                 /*
5855                  * Have enough room for control packets along with HI watermark
5856                  * Also, add room to txq for total psq packets if all the SCBs
5857                  * leave PS mode. The watermark for flowcontrol to OS packets
5858                  * will remain the same
5859                  */
5860                 brcmu_pktq_init(&qi->q, WLC_PREC_COUNT,
5861                           (2 * wlc->pub->tunables->datahiwat) + PKTQ_LEN_DEFAULT
5862                           + wlc->pub->psq_pkts_total);
5863
5864                 /* add this queue to the the global list */
5865                 p = wlc->tx_queues;
5866                 if (p == NULL) {
5867                         wlc->tx_queues = qi;
5868                 } else {
5869                         while (p->next != NULL)
5870                                 p = p->next;
5871                         p->next = qi;
5872                 }
5873         }
5874         return qi;
5875 }
5876
5877 static void wlc_txq_free(struct wlc_info *wlc, struct wlc_txq_info *qi)
5878 {
5879         struct wlc_txq_info *p;
5880
5881         if (qi == NULL)
5882                 return;
5883
5884         /* remove the queue from the linked list */
5885         p = wlc->tx_queues;
5886         if (p == qi)
5887                 wlc->tx_queues = p->next;
5888         else {
5889                 while (p != NULL && p->next != qi)
5890                         p = p->next;
5891                 if (p != NULL)
5892                         p->next = p->next->next;
5893         }
5894
5895         kfree(qi);
5896 }
5897
5898 /*
5899  * Flag 'scan in progress' to withhold dynamic phy calibration
5900  */
5901 void wlc_scan_start(struct wlc_info *wlc)
5902 {
5903         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, true);
5904 }
5905
5906 void wlc_scan_stop(struct wlc_info *wlc)
5907 {
5908         wlc_phy_hold_upd(wlc->band->pi, PHY_HOLD_FOR_SCAN, false);
5909 }
5910
5911 void wlc_associate_upd(struct wlc_info *wlc, bool state)
5912 {
5913         wlc->pub->associated = state;
5914         wlc->cfg->associated = state;
5915 }
5916
5917 /*
5918  * When a remote STA/AP is removed by Mac80211, or when it can no longer accept
5919  * AMPDU traffic, packets pending in hardware have to be invalidated so that
5920  * when later on hardware releases them, they can be handled appropriately.
5921  */
5922 void wlc_inval_dma_pkts(struct wlc_hw_info *hw,
5923                                struct ieee80211_sta *sta,
5924                                void (*dma_callback_fn))
5925 {
5926         struct dma_pub *dmah;
5927         int i;
5928         for (i = 0; i < NFIFO; i++) {
5929                 dmah = hw->di[i];
5930                 if (dmah != NULL)
5931                         dma_walk_packets(dmah, dma_callback_fn, sta);
5932         }
5933 }
5934
5935 int wlc_get_curband(struct wlc_info *wlc)
5936 {
5937         return wlc->band->bandunit;
5938 }
5939
5940 void wlc_wait_for_tx_completion(struct wlc_info *wlc, bool drop)
5941 {
5942         /* flush packet queue when requested */
5943         if (drop)
5944                 brcmu_pktq_flush(&wlc->pkt_queue->q, false, NULL, NULL);
5945
5946         /* wait for queue and DMA fifos to run dry */
5947         while (!pktq_empty(&wlc->pkt_queue->q) ||
5948                TXPKTPENDTOT(wlc) > 0) {
5949                 brcms_msleep(wlc->wl, 1);
5950         }
5951 }
5952
5953 int wlc_set_par(struct wlc_info *wlc, enum wlc_par_id par_id, int int_val)
5954 {
5955         int err = 0;
5956
5957         switch (par_id) {
5958         case IOV_BCN_LI_BCN:
5959                 wlc->bcn_li_bcn = (u8) int_val;
5960                 if (wlc->pub->up)
5961                         wlc_bcn_li_upd(wlc);
5962                 break;
5963                 /* As long as override is false, this only sets the *user*
5964                    targets. User can twiddle this all he wants with no harm.
5965                    wlc_phy_txpower_set() explicitly sets override to false if
5966                    not internal or test.
5967                  */
5968         case IOV_QTXPOWER:{
5969                 u8 qdbm;
5970                 bool override;
5971
5972                 /* Remove override bit and clip to max qdbm value */
5973                 qdbm = (u8)min_t(u32, (int_val & ~WL_TXPWR_OVERRIDE), 0xff);
5974                 /* Extract override setting */
5975                 override = (int_val & WL_TXPWR_OVERRIDE) ? true : false;
5976                 err =
5977                     wlc_phy_txpower_set(wlc->band->pi, qdbm, override);
5978                 break;
5979                 }
5980         case IOV_MPC:
5981                 wlc->mpc = (bool)int_val;
5982                 wlc_radio_mpc_upd(wlc);
5983                 break;
5984         default:
5985                 err = -ENOTSUPP;
5986         }
5987         return err;
5988 }
5989
5990 int wlc_get_par(struct wlc_info *wlc, enum wlc_par_id par_id, int *ret_int_ptr)
5991 {
5992         int err = 0;
5993
5994         switch (par_id) {
5995         case IOV_BCN_LI_BCN:
5996                 *ret_int_ptr = wlc->bcn_li_bcn;
5997                 break;
5998         case IOV_QTXPOWER: {
5999                 uint qdbm;
6000                 bool override;
6001
6002                 err = wlc_phy_txpower_get(wlc->band->pi, &qdbm,
6003                         &override);
6004                 if (err != 0)
6005                         return err;
6006
6007                 /* Return qdbm units */
6008                 *ret_int_ptr =
6009                     qdbm | (override ? WL_TXPWR_OVERRIDE : 0);
6010                 break;
6011                 }
6012         case IOV_MPC:
6013                 *ret_int_ptr = (s32) wlc->mpc;
6014                 break;
6015         default:
6016                 err = -ENOTSUPP;
6017         }
6018         return err;
6019 }
6020
6021 /*
6022  * Search the name=value vars for a specific one and return its value.
6023  * Returns NULL if not found.
6024  */
6025 char *getvar(char *vars, const char *name)
6026 {
6027         char *s;
6028         int len;
6029
6030         if (!name)
6031                 return NULL;
6032
6033         len = strlen(name);
6034         if (len == 0)
6035                 return NULL;
6036
6037         /* first look in vars[] */
6038         for (s = vars; s && *s;) {
6039                 if ((memcmp(s, name, len) == 0) && (s[len] == '='))
6040                         return &s[len + 1];
6041
6042                 while (*s++)
6043                         ;
6044         }
6045         /* nothing found */
6046         return NULL;
6047 }
6048
6049 /*
6050  * Search the vars for a specific one and return its value as
6051  * an integer. Returns 0 if not found.
6052  */
6053 int getintvar(char *vars, const char *name)
6054 {
6055         char *val;
6056
6057         val = getvar(vars, name);
6058         if (val == NULL)
6059                 return 0;
6060
6061         return simple_strtoul(val, NULL, 0);
6062 }