[PATCH] libertas: remove bss_descriptior->networktsf
[safe/jmp/linux-2.6] / drivers / net / wireless / libertas / scan.c
1 /**
2   * Functions implementing wlan scan IOCTL and firmware command APIs
3   *
4   * IOCTL handlers as well as command preperation and response routines
5   *  for sending scan commands to the firmware.
6   */
7 #include <linux/ctype.h>
8 #include <linux/if.h>
9 #include <linux/netdevice.h>
10 #include <linux/wireless.h>
11 #include <linux/etherdevice.h>
12
13 #include <net/ieee80211.h>
14 #include <net/iw_handler.h>
15
16 #include "host.h"
17 #include "decl.h"
18 #include "dev.h"
19 #include "scan.h"
20 #include "join.h"
21
22 //! Approximate amount of data needed to pass a scan result back to iwlist
23 #define MAX_SCAN_CELL_SIZE  (IW_EV_ADDR_LEN             \
24                              + IW_ESSID_MAX_SIZE        \
25                              + IW_EV_UINT_LEN           \
26                              + IW_EV_FREQ_LEN           \
27                              + IW_EV_QUAL_LEN           \
28                              + IW_ESSID_MAX_SIZE        \
29                              + IW_EV_PARAM_LEN          \
30                              + 40)      /* 40 for WPAIE */
31
32 //! Memory needed to store a max sized channel List TLV for a firmware scan
33 #define CHAN_TLV_MAX_SIZE  (sizeof(struct mrvlietypesheader)    \
34                             + (MRVDRV_MAX_CHANNELS_PER_SCAN     \
35                                * sizeof(struct chanscanparamset)))
36
37 //! Memory needed to store a max number/size SSID TLV for a firmware scan
38 #define SSID_TLV_MAX_SIZE  (1 * sizeof(struct mrvlietypes_ssidparamset))
39
40 //! Maximum memory needed for a wlan_scan_cmd_config with all TLVs at max
41 #define MAX_SCAN_CFG_ALLOC (sizeof(struct wlan_scan_cmd_config)  \
42                             + sizeof(struct mrvlietypes_numprobes)   \
43                             + CHAN_TLV_MAX_SIZE                 \
44                             + SSID_TLV_MAX_SIZE)
45
46 //! The maximum number of channels the firmware can scan per command
47 #define MRVDRV_MAX_CHANNELS_PER_SCAN   14
48
49 /**
50  * @brief Number of channels to scan per firmware scan command issuance.
51  *
52  *  Number restricted to prevent hitting the limit on the amount of scan data
53  *  returned in a single firmware scan command.
54  */
55 #define MRVDRV_CHANNELS_PER_SCAN_CMD   4
56
57 //! Scan time specified in the channel TLV for each channel for passive scans
58 #define MRVDRV_PASSIVE_SCAN_CHAN_TIME  100
59
60 //! Scan time specified in the channel TLV for each channel for active scans
61 #define MRVDRV_ACTIVE_SCAN_CHAN_TIME   100
62
63 static const u8 zeromac[ETH_ALEN] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
64 static const u8 bcastmac[ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
65
66 static inline void clear_bss_descriptor (struct bss_descriptor * bss)
67 {
68         /* Don't blow away ->list, just BSS data */
69         memset(bss, 0, offsetof(struct bss_descriptor, list));
70 }
71
72 static inline int match_bss_no_security(struct wlan_802_11_security * secinfo,
73                         struct bss_descriptor * match_bss)
74 {
75         if (   !secinfo->wep_enabled
76             && !secinfo->WPAenabled
77             && !secinfo->WPA2enabled
78             && match_bss->wpa_ie[0] != MFIE_TYPE_GENERIC
79             && match_bss->rsn_ie[0] != MFIE_TYPE_RSN
80             && !(match_bss->capability & WLAN_CAPABILITY_PRIVACY)) {
81                 return 1;
82         }
83         return 0;
84 }
85
86 static inline int match_bss_static_wep(struct wlan_802_11_security * secinfo,
87                         struct bss_descriptor * match_bss)
88 {
89         if ( secinfo->wep_enabled
90            && !secinfo->WPAenabled
91            && !secinfo->WPA2enabled
92            && (match_bss->capability & WLAN_CAPABILITY_PRIVACY)) {
93                 return 1;
94         }
95         return 0;
96 }
97
98 static inline int match_bss_wpa(struct wlan_802_11_security * secinfo,
99                         struct bss_descriptor * match_bss)
100 {
101         if (  !secinfo->wep_enabled
102            && secinfo->WPAenabled
103            && (match_bss->wpa_ie[0] == MFIE_TYPE_GENERIC)
104            /* privacy bit may NOT be set in some APs like LinkSys WRT54G
105               && (match_bss->capability & WLAN_CAPABILITY_PRIVACY)) {
106             */
107            ) {
108                 return 1;
109         }
110         return 0;
111 }
112
113 static inline int match_bss_wpa2(struct wlan_802_11_security * secinfo,
114                         struct bss_descriptor * match_bss)
115 {
116         if (  !secinfo->wep_enabled
117            && secinfo->WPA2enabled
118            && (match_bss->rsn_ie[0] == MFIE_TYPE_RSN)
119            /* privacy bit may NOT be set in some APs like LinkSys WRT54G
120               && (match_bss->capability & WLAN_CAPABILITY_PRIVACY)) {
121             */
122            ) {
123                 return 1;
124         }
125         return 0;
126 }
127
128 static inline int match_bss_dynamic_wep(struct wlan_802_11_security * secinfo,
129                         struct bss_descriptor * match_bss)
130 {
131         if (  !secinfo->wep_enabled
132            && !secinfo->WPAenabled
133            && !secinfo->WPA2enabled
134            && (match_bss->wpa_ie[0] != MFIE_TYPE_GENERIC)
135            && (match_bss->rsn_ie[0] != MFIE_TYPE_RSN)
136            && (match_bss->capability & WLAN_CAPABILITY_PRIVACY)) {
137                 return 1;
138         }
139         return 0;
140 }
141
142 /**
143  *  @brief Check if a scanned network compatible with the driver settings
144  *
145  *   WEP     WPA     WPA2    ad-hoc  encrypt                      Network
146  * enabled enabled  enabled   AES     mode   privacy  WPA  WPA2  Compatible
147  *    0       0        0       0      NONE      0      0    0   yes No security
148  *    1       0        0       0      NONE      1      0    0   yes Static WEP
149  *    0       1        0       0       x        1x     1    x   yes WPA
150  *    0       0        1       0       x        1x     x    1   yes WPA2
151  *    0       0        0       1      NONE      1      0    0   yes Ad-hoc AES
152  *    0       0        0       0     !=NONE     1      0    0   yes Dynamic WEP
153  *
154  *
155  *  @param adapter A pointer to wlan_adapter
156  *  @param index   Index in scantable to check against current driver settings
157  *  @param mode    Network mode: Infrastructure or IBSS
158  *
159  *  @return        Index in scantable, or error code if negative
160  */
161 static int is_network_compatible(wlan_adapter * adapter,
162                 struct bss_descriptor * bss, u8 mode)
163 {
164         int matched = 0;
165
166         lbs_deb_enter(LBS_DEB_ASSOC);
167
168         if (bss->mode != mode)
169                 goto done;
170
171         if ((matched = match_bss_no_security(&adapter->secinfo, bss))) {
172                 goto done;
173         } else if ((matched = match_bss_static_wep(&adapter->secinfo, bss))) {
174                 goto done;
175         } else if ((matched = match_bss_wpa(&adapter->secinfo, bss))) {
176                 lbs_deb_scan(
177                        "is_network_compatible() WPA: wpa_ie=%#x "
178                        "wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s "
179                        "privacy=%#x\n", bss->wpa_ie[0], bss->rsn_ie[0],
180                        adapter->secinfo.wep_enabled ? "e" : "d",
181                        adapter->secinfo.WPAenabled ? "e" : "d",
182                        adapter->secinfo.WPA2enabled ? "e" : "d",
183                        (bss->capability & WLAN_CAPABILITY_PRIVACY));
184                 goto done;
185         } else if ((matched = match_bss_wpa2(&adapter->secinfo, bss))) {
186                 lbs_deb_scan(
187                        "is_network_compatible() WPA2: wpa_ie=%#x "
188                        "wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s "
189                        "privacy=%#x\n", bss->wpa_ie[0], bss->rsn_ie[0],
190                        adapter->secinfo.wep_enabled ? "e" : "d",
191                        adapter->secinfo.WPAenabled ? "e" : "d",
192                        adapter->secinfo.WPA2enabled ? "e" : "d",
193                        (bss->capability & WLAN_CAPABILITY_PRIVACY));
194                 goto done;
195         } else if ((matched = match_bss_dynamic_wep(&adapter->secinfo, bss))) {
196                 lbs_deb_scan(
197                        "is_network_compatible() dynamic WEP: "
198                        "wpa_ie=%#x wpa2_ie=%#x privacy=%#x\n",
199                        bss->wpa_ie[0], bss->rsn_ie[0],
200                        (bss->capability & WLAN_CAPABILITY_PRIVACY));
201                 goto done;
202         }
203
204         /* bss security settings don't match those configured on card */
205         lbs_deb_scan(
206                "is_network_compatible() FAILED: wpa_ie=%#x "
207                "wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s privacy=%#x\n",
208                bss->wpa_ie[0], bss->rsn_ie[0],
209                adapter->secinfo.wep_enabled ? "e" : "d",
210                adapter->secinfo.WPAenabled ? "e" : "d",
211                adapter->secinfo.WPA2enabled ? "e" : "d",
212                (bss->capability & WLAN_CAPABILITY_PRIVACY));
213
214 done:
215         lbs_deb_leave(LBS_DEB_SCAN);
216         return matched;
217 }
218
219 /**
220  *  @brief Create a channel list for the driver to scan based on region info
221  *
222  *  Use the driver region/band information to construct a comprehensive list
223  *    of channels to scan.  This routine is used for any scan that is not
224  *    provided a specific channel list to scan.
225  *
226  *  @param priv          A pointer to wlan_private structure
227  *  @param scanchanlist  Output parameter: resulting channel list to scan
228  *  @param filteredscan  Flag indicating whether or not a BSSID or SSID filter
229  *                       is being sent in the command to firmware.  Used to
230  *                       increase the number of channels sent in a scan
231  *                       command and to disable the firmware channel scan
232  *                       filter.
233  *
234  *  @return              void
235  */
236 static void wlan_scan_create_channel_list(wlan_private * priv,
237                                           struct chanscanparamset * scanchanlist,
238                                           u8 filteredscan)
239 {
240
241         wlan_adapter *adapter = priv->adapter;
242         struct region_channel *scanregion;
243         struct chan_freq_power *cfp;
244         int rgnidx;
245         int chanidx;
246         int nextchan;
247         u8 scantype;
248
249         chanidx = 0;
250
251         /* Set the default scan type to the user specified type, will later
252          *   be changed to passive on a per channel basis if restricted by
253          *   regulatory requirements (11d or 11h)
254          */
255         scantype = CMD_SCAN_TYPE_ACTIVE;
256
257         for (rgnidx = 0; rgnidx < ARRAY_SIZE(adapter->region_channel); rgnidx++) {
258                 if (priv->adapter->enable11d &&
259                     adapter->connect_status != LIBERTAS_CONNECTED) {
260                         /* Scan all the supported chan for the first scan */
261                         if (!adapter->universal_channel[rgnidx].valid)
262                                 continue;
263                         scanregion = &adapter->universal_channel[rgnidx];
264
265                         /* clear the parsed_region_chan for the first scan */
266                         memset(&adapter->parsed_region_chan, 0x00,
267                                sizeof(adapter->parsed_region_chan));
268                 } else {
269                         if (!adapter->region_channel[rgnidx].valid)
270                                 continue;
271                         scanregion = &adapter->region_channel[rgnidx];
272                 }
273
274                 for (nextchan = 0;
275                      nextchan < scanregion->nrcfp; nextchan++, chanidx++) {
276
277                         cfp = scanregion->CFP + nextchan;
278
279                         if (priv->adapter->enable11d) {
280                                 scantype =
281                                     libertas_get_scan_type_11d(cfp->channel,
282                                                            &adapter->
283                                                            parsed_region_chan);
284                         }
285
286                         switch (scanregion->band) {
287                         case BAND_B:
288                         case BAND_G:
289                         default:
290                                 scanchanlist[chanidx].radiotype =
291                                     CMD_SCAN_RADIO_TYPE_BG;
292                                 break;
293                         }
294
295                         if (scantype == CMD_SCAN_TYPE_PASSIVE) {
296                                 scanchanlist[chanidx].maxscantime =
297                                     cpu_to_le16(MRVDRV_PASSIVE_SCAN_CHAN_TIME);
298                                 scanchanlist[chanidx].chanscanmode.passivescan =
299                                     1;
300                         } else {
301                                 scanchanlist[chanidx].maxscantime =
302                                     cpu_to_le16(MRVDRV_ACTIVE_SCAN_CHAN_TIME);
303                                 scanchanlist[chanidx].chanscanmode.passivescan =
304                                     0;
305                         }
306
307                         scanchanlist[chanidx].channumber = cfp->channel;
308
309                         if (filteredscan) {
310                                 scanchanlist[chanidx].chanscanmode.
311                                     disablechanfilt = 1;
312                         }
313                 }
314         }
315 }
316
317 /**
318  *  @brief Construct a wlan_scan_cmd_config structure to use in issue scan cmds
319  *
320  *  Application layer or other functions can invoke wlan_scan_networks
321  *    with a scan configuration supplied in a wlan_ioctl_user_scan_cfg struct.
322  *    This structure is used as the basis of one or many wlan_scan_cmd_config
323  *    commands that are sent to the command processing module and sent to
324  *    firmware.
325  *
326  *  Create a wlan_scan_cmd_config based on the following user supplied
327  *    parameters (if present):
328  *             - SSID filter
329  *             - BSSID filter
330  *             - Number of Probes to be sent
331  *             - channel list
332  *
333  *  If the SSID or BSSID filter is not present, disable/clear the filter.
334  *  If the number of probes is not set, use the adapter default setting
335  *  Qualify the channel
336  *
337  *  @param priv             A pointer to wlan_private structure
338  *  @param puserscanin      NULL or pointer to scan configuration parameters
339  *  @param ppchantlvout     Output parameter: Pointer to the start of the
340  *                          channel TLV portion of the output scan config
341  *  @param pscanchanlist    Output parameter: Pointer to the resulting channel
342  *                          list to scan
343  *  @param pmaxchanperscan  Output parameter: Number of channels to scan for
344  *                          each issuance of the firmware scan command
345  *  @param pfilteredscan    Output parameter: Flag indicating whether or not
346  *                          a BSSID or SSID filter is being sent in the
347  *                          command to firmware.  Used to increase the number
348  *                          of channels sent in a scan command and to
349  *                          disable the firmware channel scan filter.
350  *  @param pscancurrentonly Output parameter: Flag indicating whether or not
351  *                          we are only scanning our current active channel
352  *
353  *  @return                 resulting scan configuration
354  */
355 static struct wlan_scan_cmd_config *
356 wlan_scan_setup_scan_config(wlan_private * priv,
357                             const struct wlan_ioctl_user_scan_cfg * puserscanin,
358                             struct mrvlietypes_chanlistparamset ** ppchantlvout,
359                             struct chanscanparamset * pscanchanlist,
360                             int *pmaxchanperscan,
361                             u8 * pfilteredscan,
362                             u8 * pscancurrentonly)
363 {
364         struct mrvlietypes_numprobes *pnumprobestlv;
365         struct mrvlietypes_ssidparamset *pssidtlv;
366         struct wlan_scan_cmd_config * pscancfgout = NULL;
367         u8 *ptlvpos;
368         u16 numprobes;
369         int chanidx;
370         int scantype;
371         int scandur;
372         int channel;
373         int radiotype;
374
375         pscancfgout = kzalloc(MAX_SCAN_CFG_ALLOC, GFP_KERNEL);
376         if (pscancfgout == NULL)
377                 goto out;
378
379         /* The tlvbufferlen is calculated for each scan command.  The TLVs added
380          *   in this routine will be preserved since the routine that sends
381          *   the command will append channelTLVs at *ppchantlvout.  The difference
382          *   between the *ppchantlvout and the tlvbuffer start will be used
383          *   to calculate the size of anything we add in this routine.
384          */
385         pscancfgout->tlvbufferlen = 0;
386
387         /* Running tlv pointer.  Assigned to ppchantlvout at end of function
388          *  so later routines know where channels can be added to the command buf
389          */
390         ptlvpos = pscancfgout->tlvbuffer;
391
392         /*
393          * Set the initial scan paramters for progressive scanning.  If a specific
394          *   BSSID or SSID is used, the number of channels in the scan command
395          *   will be increased to the absolute maximum
396          */
397         *pmaxchanperscan = MRVDRV_CHANNELS_PER_SCAN_CMD;
398
399         /* Initialize the scan as un-filtered by firmware, set to TRUE below if
400          *   a SSID or BSSID filter is sent in the command
401          */
402         *pfilteredscan = 0;
403
404         /* Initialize the scan as not being only on the current channel.  If
405          *   the channel list is customized, only contains one channel, and
406          *   is the active channel, this is set true and data flow is not halted.
407          */
408         *pscancurrentonly = 0;
409
410         if (puserscanin) {
411
412                 /* Set the bss type scan filter, use adapter setting if unset */
413                 pscancfgout->bsstype =
414                     puserscanin->bsstype ? puserscanin->bsstype : CMD_BSS_TYPE_ANY;
415
416                 /* Set the number of probes to send, use adapter setting if unset */
417                 numprobes = puserscanin->numprobes ? puserscanin->numprobes : 0;
418
419                 /*
420                  * Set the BSSID filter to the incoming configuration,
421                  *   if non-zero.  If not set, it will remain disabled (all zeros).
422                  */
423                 memcpy(pscancfgout->bssid, puserscanin->bssid,
424                        sizeof(pscancfgout->bssid));
425
426                 if (puserscanin->ssid_len) {
427                         pssidtlv =
428                             (struct mrvlietypes_ssidparamset *) pscancfgout->
429                             tlvbuffer;
430                         pssidtlv->header.type = cpu_to_le16(TLV_TYPE_SSID);
431                         pssidtlv->header.len = cpu_to_le16(puserscanin->ssid_len);
432                         memcpy(pssidtlv->ssid, puserscanin->ssid,
433                                puserscanin->ssid_len);
434                         ptlvpos += sizeof(pssidtlv->header) + puserscanin->ssid_len;
435                 }
436
437                 /*
438                  *  The default number of channels sent in the command is low to
439                  *    ensure the response buffer from the firmware does not truncate
440                  *    scan results.  That is not an issue with an SSID or BSSID
441                  *    filter applied to the scan results in the firmware.
442                  */
443                 if (   puserscanin->ssid_len
444                     || (compare_ether_addr(pscancfgout->bssid, &zeromac[0]) != 0)) {
445                         *pmaxchanperscan = MRVDRV_MAX_CHANNELS_PER_SCAN;
446                         *pfilteredscan = 1;
447                 }
448         } else {
449                 pscancfgout->bsstype = CMD_BSS_TYPE_ANY;
450                 numprobes = 0;
451         }
452
453         /* If the input config or adapter has the number of Probes set, add tlv */
454         if (numprobes) {
455                 pnumprobestlv = (struct mrvlietypes_numprobes *) ptlvpos;
456                 pnumprobestlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES);
457                 pnumprobestlv->header.len = cpu_to_le16(2);
458                 pnumprobestlv->numprobes = cpu_to_le16(numprobes);
459
460                 ptlvpos += sizeof(*pnumprobestlv);
461         }
462
463         /*
464          * Set the output for the channel TLV to the address in the tlv buffer
465          *   past any TLVs that were added in this fuction (SSID, numprobes).
466          *   channel TLVs will be added past this for each scan command, preserving
467          *   the TLVs that were previously added.
468          */
469         *ppchantlvout = (struct mrvlietypes_chanlistparamset *) ptlvpos;
470
471         if (puserscanin && puserscanin->chanlist[0].channumber) {
472
473                 lbs_deb_scan("Scan: Using supplied channel list\n");
474
475                 for (chanidx = 0;
476                      chanidx < WLAN_IOCTL_USER_SCAN_CHAN_MAX
477                      && puserscanin->chanlist[chanidx].channumber; chanidx++) {
478
479                         channel = puserscanin->chanlist[chanidx].channumber;
480                         (pscanchanlist + chanidx)->channumber = channel;
481
482                         radiotype = puserscanin->chanlist[chanidx].radiotype;
483                         (pscanchanlist + chanidx)->radiotype = radiotype;
484
485                         scantype = puserscanin->chanlist[chanidx].scantype;
486
487                         if (scantype == CMD_SCAN_TYPE_PASSIVE) {
488                                 (pscanchanlist +
489                                  chanidx)->chanscanmode.passivescan = 1;
490                         } else {
491                                 (pscanchanlist +
492                                  chanidx)->chanscanmode.passivescan = 0;
493                         }
494
495                         if (puserscanin->chanlist[chanidx].scantime) {
496                                 scandur =
497                                     puserscanin->chanlist[chanidx].scantime;
498                         } else {
499                                 if (scantype == CMD_SCAN_TYPE_PASSIVE) {
500                                         scandur = MRVDRV_PASSIVE_SCAN_CHAN_TIME;
501                                 } else {
502                                         scandur = MRVDRV_ACTIVE_SCAN_CHAN_TIME;
503                                 }
504                         }
505
506                         (pscanchanlist + chanidx)->minscantime =
507                             cpu_to_le16(scandur);
508                         (pscanchanlist + chanidx)->maxscantime =
509                             cpu_to_le16(scandur);
510                 }
511
512                 /* Check if we are only scanning the current channel */
513                 if ((chanidx == 1) && (puserscanin->chanlist[0].channumber
514                                        ==
515                                        priv->adapter->curbssparams.channel)) {
516                         *pscancurrentonly = 1;
517                         lbs_deb_scan("Scan: Scanning current channel only");
518                 }
519
520         } else {
521                 lbs_deb_scan("Scan: Creating full region channel list\n");
522                 wlan_scan_create_channel_list(priv, pscanchanlist,
523                                               *pfilteredscan);
524         }
525
526 out:
527         return pscancfgout;
528 }
529
530 /**
531  *  @brief Construct and send multiple scan config commands to the firmware
532  *
533  *  Previous routines have created a wlan_scan_cmd_config with any requested
534  *   TLVs.  This function splits the channel TLV into maxchanperscan lists
535  *   and sends the portion of the channel TLV along with the other TLVs
536  *   to the wlan_cmd routines for execution in the firmware.
537  *
538  *  @param priv            A pointer to wlan_private structure
539  *  @param maxchanperscan  Maximum number channels to be included in each
540  *                         scan command sent to firmware
541  *  @param filteredscan    Flag indicating whether or not a BSSID or SSID
542  *                         filter is being used for the firmware command
543  *                         scan command sent to firmware
544  *  @param pscancfgout     Scan configuration used for this scan.
545  *  @param pchantlvout     Pointer in the pscancfgout where the channel TLV
546  *                         should start.  This is past any other TLVs that
547  *                         must be sent down in each firmware command.
548  *  @param pscanchanlist   List of channels to scan in maxchanperscan segments
549  *
550  *  @return                0 or error return otherwise
551  */
552 static int wlan_scan_channel_list(wlan_private * priv,
553                                   int maxchanperscan,
554                                   u8 filteredscan,
555                                   struct wlan_scan_cmd_config * pscancfgout,
556                                   struct mrvlietypes_chanlistparamset * pchantlvout,
557                                   struct chanscanparamset * pscanchanlist,
558                                   const struct wlan_ioctl_user_scan_cfg * puserscanin,
559                                   int full_scan)
560 {
561         struct chanscanparamset *ptmpchan;
562         struct chanscanparamset *pstartchan;
563         u8 scanband;
564         int doneearly;
565         int tlvidx;
566         int ret = 0;
567         int scanned = 0;
568         union iwreq_data wrqu;
569
570         lbs_deb_enter(LBS_DEB_ASSOC);
571
572         if (pscancfgout == 0 || pchantlvout == 0 || pscanchanlist == 0) {
573                 lbs_deb_scan("Scan: Null detect: %p, %p, %p\n",
574                        pscancfgout, pchantlvout, pscanchanlist);
575                 return -1;
576         }
577
578         pchantlvout->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
579
580         /* Set the temp channel struct pointer to the start of the desired list */
581         ptmpchan = pscanchanlist;
582
583         if (priv->adapter->last_scanned_channel && !puserscanin)
584                 ptmpchan += priv->adapter->last_scanned_channel;
585
586         /* Loop through the desired channel list, sending a new firmware scan
587          *   commands for each maxchanperscan channels (or for 1,6,11 individually
588          *   if configured accordingly)
589          */
590         while (ptmpchan->channumber) {
591
592                 tlvidx = 0;
593                 pchantlvout->header.len = 0;
594                 scanband = ptmpchan->radiotype;
595                 pstartchan = ptmpchan;
596                 doneearly = 0;
597
598                 /* Construct the channel TLV for the scan command.  Continue to
599                  *  insert channel TLVs until:
600                  *    - the tlvidx hits the maximum configured per scan command
601                  *    - the next channel to insert is 0 (end of desired channel list)
602                  *    - doneearly is set (controlling individual scanning of 1,6,11)
603                  */
604                 while (tlvidx < maxchanperscan && ptmpchan->channumber
605                        && !doneearly && scanned < 2) {
606
607             lbs_deb_scan(
608                     "Scan: Chan(%3d), Radio(%d), mode(%d,%d), Dur(%d)\n",
609                 ptmpchan->channumber, ptmpchan->radiotype,
610                 ptmpchan->chanscanmode.passivescan,
611                 ptmpchan->chanscanmode.disablechanfilt,
612                 ptmpchan->maxscantime);
613
614                         /* Copy the current channel TLV to the command being prepared */
615                         memcpy(pchantlvout->chanscanparam + tlvidx,
616                                ptmpchan, sizeof(pchantlvout->chanscanparam));
617
618                         /* Increment the TLV header length by the size appended */
619                         /* Ew, it would be _so_ nice if we could just declare the
620                            variable little-endian and let GCC handle it for us */
621                         pchantlvout->header.len =
622                                 cpu_to_le16(le16_to_cpu(pchantlvout->header.len) +
623                                             sizeof(pchantlvout->chanscanparam));
624
625                         /*
626                          *  The tlv buffer length is set to the number of bytes of the
627                          *    between the channel tlv pointer and the start of the
628                          *    tlv buffer.  This compensates for any TLVs that were appended
629                          *    before the channel list.
630                          */
631                         pscancfgout->tlvbufferlen = ((u8 *) pchantlvout
632                                                      - pscancfgout->tlvbuffer);
633
634                         /*  Add the size of the channel tlv header and the data length */
635                         pscancfgout->tlvbufferlen +=
636                             (sizeof(pchantlvout->header)
637                              + le16_to_cpu(pchantlvout->header.len));
638
639                         /* Increment the index to the channel tlv we are constructing */
640                         tlvidx++;
641
642                         doneearly = 0;
643
644                         /* Stop the loop if the *current* channel is in the 1,6,11 set
645                          *   and we are not filtering on a BSSID or SSID.
646                          */
647                         if (!filteredscan && (ptmpchan->channumber == 1
648                                               || ptmpchan->channumber == 6
649                                               || ptmpchan->channumber == 11)) {
650                                 doneearly = 1;
651                         }
652
653                         /* Increment the tmp pointer to the next channel to be scanned */
654                         ptmpchan++;
655                         scanned++;
656
657                         /* Stop the loop if the *next* channel is in the 1,6,11 set.
658                          *  This will cause it to be the only channel scanned on the next
659                          *  interation
660                          */
661                         if (!filteredscan && (ptmpchan->channumber == 1
662                                               || ptmpchan->channumber == 6
663                                               || ptmpchan->channumber == 11)) {
664                                 doneearly = 1;
665                         }
666                 }
667
668                 /* Send the scan command to the firmware with the specified cfg */
669                 ret = libertas_prepare_and_send_command(priv, CMD_802_11_SCAN, 0,
670                                             0, 0, pscancfgout);
671                 if (scanned >= 2 && !full_scan) {
672                         ret = 0;
673                         goto done;
674                 }
675                 scanned = 0;
676         }
677
678 done:
679         priv->adapter->last_scanned_channel = ptmpchan->channumber;
680
681         /* Tell userspace the scan table has been updated */
682         memset(&wrqu, 0, sizeof(union iwreq_data));
683         wireless_send_event(priv->dev, SIOCGIWSCAN, &wrqu, NULL);
684
685         lbs_deb_leave_args(LBS_DEB_SCAN, "ret %d", ret);
686         return ret;
687 }
688
689 static void
690 clear_selected_scan_list_entries(wlan_adapter * adapter,
691                                  const struct wlan_ioctl_user_scan_cfg * scan_cfg)
692 {
693         struct bss_descriptor * bss;
694         struct bss_descriptor * safe;
695         u32 clear_ssid_flag = 0, clear_bssid_flag = 0;
696
697         if (!scan_cfg)
698                 return;
699
700         if (scan_cfg->clear_ssid && scan_cfg->ssid_len)
701                 clear_ssid_flag = 1;
702
703         if (scan_cfg->clear_bssid
704             && (compare_ether_addr(scan_cfg->bssid, &zeromac[0]) != 0)
705             && (compare_ether_addr(scan_cfg->bssid, &bcastmac[0]) != 0)) {
706                 clear_bssid_flag = 1;
707         }
708
709         if (!clear_ssid_flag && !clear_bssid_flag)
710                 return;
711
712         mutex_lock(&adapter->lock);
713         list_for_each_entry_safe (bss, safe, &adapter->network_list, list) {
714                 u32 clear = 0;
715
716                 /* Check for an SSID match */
717                 if (   clear_ssid_flag
718                     && (bss->ssid_len == scan_cfg->ssid_len)
719                     && !memcmp(bss->ssid, scan_cfg->ssid, bss->ssid_len))
720                         clear = 1;
721
722                 /* Check for a BSSID match */
723                 if (   clear_bssid_flag
724                     && !compare_ether_addr(bss->bssid, scan_cfg->bssid))
725                         clear = 1;
726
727                 if (clear) {
728                         list_move_tail (&bss->list, &adapter->network_free_list);
729                         clear_bss_descriptor(bss);
730                 }
731         }
732         mutex_unlock(&adapter->lock);
733 }
734
735
736 /**
737  *  @brief Internal function used to start a scan based on an input config
738  *
739  *  Use the input user scan configuration information when provided in
740  *    order to send the appropriate scan commands to firmware to populate or
741  *    update the internal driver scan table
742  *
743  *  @param priv          A pointer to wlan_private structure
744  *  @param puserscanin   Pointer to the input configuration for the requested
745  *                       scan.
746  *
747  *  @return              0 or < 0 if error
748  */
749 int wlan_scan_networks(wlan_private * priv,
750                               const struct wlan_ioctl_user_scan_cfg * puserscanin,
751                               int full_scan)
752 {
753         wlan_adapter * adapter = priv->adapter;
754         struct mrvlietypes_chanlistparamset *pchantlvout;
755         struct chanscanparamset * scan_chan_list = NULL;
756         struct wlan_scan_cmd_config * scan_cfg = NULL;
757         u8 filteredscan;
758         u8 scancurrentchanonly;
759         int maxchanperscan;
760         int ret;
761 #ifdef CONFIG_LIBERTAS_DEBUG
762         struct bss_descriptor * iter_bss;
763         int i = 0;
764 #endif
765
766         lbs_deb_enter(LBS_DEB_ASSOC);
767
768         scan_chan_list = kzalloc(sizeof(struct chanscanparamset) *
769                                 WLAN_IOCTL_USER_SCAN_CHAN_MAX, GFP_KERNEL);
770         if (scan_chan_list == NULL) {
771                 ret = -ENOMEM;
772                 goto out;
773         }
774
775         scan_cfg = wlan_scan_setup_scan_config(priv,
776                                                puserscanin,
777                                                &pchantlvout,
778                                                scan_chan_list,
779                                                &maxchanperscan,
780                                                &filteredscan,
781                                                &scancurrentchanonly);
782         if (scan_cfg == NULL) {
783                 ret = -ENOMEM;
784                 goto out;
785         }
786
787         clear_selected_scan_list_entries(adapter, puserscanin);
788
789         /* Keep the data path active if we are only scanning our current channel */
790         if (!scancurrentchanonly) {
791                 netif_stop_queue(priv->dev);
792                 netif_carrier_off(priv->dev);
793                 if (priv->mesh_dev) {
794                         netif_stop_queue(priv->mesh_dev);
795                         netif_carrier_off(priv->mesh_dev);
796                 }
797         }
798
799         ret = wlan_scan_channel_list(priv,
800                                      maxchanperscan,
801                                      filteredscan,
802                                      scan_cfg,
803                                      pchantlvout,
804                                      scan_chan_list,
805                                      puserscanin,
806                                      full_scan);
807
808 #ifdef CONFIG_LIBERTAS_DEBUG
809         /* Dump the scan table */
810         mutex_lock(&adapter->lock);
811         list_for_each_entry (iter_bss, &adapter->network_list, list) {
812                 lbs_deb_scan("Scan:(%02d) " MAC_FMT ", RSSI[%03d], SSID[%s]\n",
813                        i++, MAC_ARG(iter_bss->bssid), (s32) iter_bss->rssi,
814                        escape_essid(iter_bss->ssid, iter_bss->ssid_len));
815         }
816         mutex_unlock(&adapter->lock);
817 #endif
818
819         if (priv->adapter->connect_status == LIBERTAS_CONNECTED) {
820                 netif_carrier_on(priv->dev);
821                 netif_wake_queue(priv->dev);
822                 if (priv->mesh_dev) {
823                         netif_carrier_on(priv->mesh_dev);
824                         netif_wake_queue(priv->mesh_dev);
825                 }
826         }
827
828 out:
829         if (scan_cfg)
830                 kfree(scan_cfg);
831
832         if (scan_chan_list)
833                 kfree(scan_chan_list);
834
835         lbs_deb_leave_args(LBS_DEB_SCAN, "ret %d", ret);
836         return ret;
837 }
838
839 /**
840  *  @brief Interpret a BSS scan response returned from the firmware
841  *
842  *  Parse the various fixed fields and IEs passed back for a a BSS probe
843  *   response or beacon from the scan command.  Record information as needed
844  *   in the scan table struct bss_descriptor for that entry.
845  *
846  *  @param bss  Output parameter: Pointer to the BSS Entry
847  *
848  *  @return             0 or -1
849  */
850 static int libertas_process_bss(struct bss_descriptor * bss,
851                                 u8 ** pbeaconinfo, int *bytesleft)
852 {
853         struct ieeetypes_fhparamset *pFH;
854         struct ieeetypes_dsparamset *pDS;
855         struct ieeetypes_cfparamset *pCF;
856         struct ieeetypes_ibssparamset *pibss;
857         struct ieeetypes_countryinfoset *pcountryinfo;
858         u8 *pos, *end, *p;
859         u8 n_ex_rates = 0, got_basic_rates = 0, n_basic_rates = 0;
860         u16 beaconsize = 0;
861         int ret;
862
863         lbs_deb_enter(LBS_DEB_ASSOC);
864
865         if (*bytesleft >= sizeof(beaconsize)) {
866                 /* Extract & convert beacon size from the command buffer */
867                 beaconsize = le16_to_cpup((void *)*pbeaconinfo);
868                 *bytesleft -= sizeof(beaconsize);
869                 *pbeaconinfo += sizeof(beaconsize);
870         }
871
872         if (beaconsize == 0 || beaconsize > *bytesleft) {
873                 *pbeaconinfo += *bytesleft;
874                 *bytesleft = 0;
875                 return -1;
876         }
877
878         /* Initialize the current working beacon pointer for this BSS iteration */
879         pos = *pbeaconinfo;
880         end = pos + beaconsize;
881
882         /* Advance the return beacon pointer past the current beacon */
883         *pbeaconinfo += beaconsize;
884         *bytesleft -= beaconsize;
885
886         memcpy(bss->bssid, pos, ETH_ALEN);
887         lbs_deb_scan("process_bss: AP BSSID " MAC_FMT "\n", MAC_ARG(bss->bssid));
888         pos += ETH_ALEN;
889
890         if ((end - pos) < 12) {
891                 lbs_deb_scan("process_bss: Not enough bytes left\n");
892                 return -1;
893         }
894
895         /*
896          * next 4 fields are RSSI, time stamp, beacon interval,
897          *   and capability information
898          */
899
900         /* RSSI is 1 byte long */
901         bss->rssi = *pos;
902         lbs_deb_scan("process_bss: RSSI=%02X\n", *pos);
903         pos++;
904
905         /* time stamp is 8 bytes long */
906         bss->timestamp = le64_to_cpup((void *) pos);
907         pos += 8;
908
909         /* beacon interval is 2 bytes long */
910         bss->beaconperiod = le16_to_cpup((void *) pos);
911         pos += 2;
912
913         /* capability information is 2 bytes long */
914         bss->capability = le16_to_cpup((void *) pos);
915         lbs_deb_scan("process_bss: capabilities = 0x%4X\n", bss->capability);
916         pos += 2;
917
918         if (bss->capability & WLAN_CAPABILITY_PRIVACY)
919                 lbs_deb_scan("process_bss: AP WEP enabled\n");
920         if (bss->capability & WLAN_CAPABILITY_IBSS)
921                 bss->mode = IW_MODE_ADHOC;
922         else
923                 bss->mode = IW_MODE_INFRA;
924
925         /* rest of the current buffer are IE's */
926         lbs_deb_scan("process_bss: IE length for this AP = %zd\n", end - pos);
927         lbs_deb_hex(LBS_DEB_SCAN, "process_bss: IE info", pos, end - pos);
928
929         /* process variable IE */
930         while (pos <= end - 2) {
931                 struct ieee80211_info_element * elem =
932                         (struct ieee80211_info_element *) pos;
933
934                 if (pos + elem->len > end) {
935                         lbs_deb_scan("process_bss: error in processing IE, "
936                                "bytes left < IE length\n");
937                         break;
938                 }
939
940                 switch (elem->id) {
941                 case MFIE_TYPE_SSID:
942                         bss->ssid_len = elem->len;
943                         memcpy(bss->ssid, elem->data, elem->len);
944                         lbs_deb_scan("ssid '%s', ssid length %u\n",
945                                      escape_essid(bss->ssid, bss->ssid_len),
946                                      bss->ssid_len);
947                         break;
948
949                 case MFIE_TYPE_RATES:
950                         n_basic_rates = min_t(u8, MAX_RATES, elem->len);
951                         memcpy(bss->rates, elem->data, n_basic_rates);
952                         got_basic_rates = 1;
953                         break;
954
955                 case MFIE_TYPE_FH_SET:
956                         pFH = (struct ieeetypes_fhparamset *) pos;
957                         memmove(&bss->phyparamset.fhparamset, pFH,
958                                 sizeof(struct ieeetypes_fhparamset));
959 #if 0 /* I think we can store these LE */
960                         bss->phyparamset.fhparamset.dwelltime
961                             = le16_to_cpu(bss->phyparamset.fhparamset.dwelltime);
962 #endif
963                         break;
964
965                 case MFIE_TYPE_DS_SET:
966                         pDS = (struct ieeetypes_dsparamset *) pos;
967                         bss->channel = pDS->currentchan;
968                         memcpy(&bss->phyparamset.dsparamset, pDS,
969                                sizeof(struct ieeetypes_dsparamset));
970                         break;
971
972                 case MFIE_TYPE_CF_SET:
973                         pCF = (struct ieeetypes_cfparamset *) pos;
974                         memcpy(&bss->ssparamset.cfparamset, pCF,
975                                sizeof(struct ieeetypes_cfparamset));
976                         break;
977
978                 case MFIE_TYPE_IBSS_SET:
979                         pibss = (struct ieeetypes_ibssparamset *) pos;
980                         bss->atimwindow = le32_to_cpu(pibss->atimwindow);
981                         memmove(&bss->ssparamset.ibssparamset, pibss,
982                                 sizeof(struct ieeetypes_ibssparamset));
983 #if 0
984                         bss->ssparamset.ibssparamset.atimwindow
985                             = le16_to_cpu(bss->ssparamset.ibssparamset.atimwindow);
986 #endif
987                         break;
988
989                 case MFIE_TYPE_COUNTRY:
990                         pcountryinfo = (struct ieeetypes_countryinfoset *) pos;
991                         if (pcountryinfo->len < sizeof(pcountryinfo->countrycode)
992                             || pcountryinfo->len > 254) {
993                                 lbs_deb_scan("process_bss: 11D- Err "
994                                        "CountryInfo len =%d min=%zd max=254\n",
995                                        pcountryinfo->len,
996                                        sizeof(pcountryinfo->countrycode));
997                                 ret = -1;
998                                 goto done;
999                         }
1000
1001                         memcpy(&bss->countryinfo,
1002                                pcountryinfo, pcountryinfo->len + 2);
1003                         lbs_deb_hex(LBS_DEB_SCAN, "process_bss: 11d countryinfo",
1004                                 (u8 *) pcountryinfo,
1005                                 (u32) (pcountryinfo->len + 2));
1006                         break;
1007
1008                 case MFIE_TYPE_RATES_EX:
1009                         /* only process extended supported rate if data rate is
1010                          * already found. Data rate IE should come before
1011                          * extended supported rate IE
1012                          */
1013                         if (!got_basic_rates)
1014                                 break;
1015
1016                         n_ex_rates = elem->len;
1017                         if (n_basic_rates + n_ex_rates > MAX_RATES)
1018                                 n_ex_rates = MAX_RATES - n_basic_rates;
1019
1020                         p = bss->rates + n_basic_rates;
1021                         memcpy(p, elem->data, n_ex_rates);
1022                         break;
1023
1024                 case MFIE_TYPE_GENERIC:
1025                         if (elem->len >= 4 &&
1026                             elem->data[0] == 0x00 &&
1027                             elem->data[1] == 0x50 &&
1028                             elem->data[2] == 0xf2 &&
1029                             elem->data[3] == 0x01) {
1030                                 bss->wpa_ie_len = min(elem->len + 2,
1031                                                       MAX_WPA_IE_LEN);
1032                                 memcpy(bss->wpa_ie, elem, bss->wpa_ie_len);
1033                                 lbs_deb_hex(LBS_DEB_SCAN, "process_bss: WPA IE", bss->wpa_ie,
1034                                             elem->len);
1035                         } else if (elem->len >= MARVELL_MESH_IE_LENGTH &&
1036                             elem->data[0] == 0x00 &&
1037                             elem->data[1] == 0x50 &&
1038                             elem->data[2] == 0x43 &&
1039                             elem->data[3] == 0x04) {
1040                                 bss->mesh = 1;
1041                         }
1042                         break;
1043
1044                 case MFIE_TYPE_RSN:
1045                         bss->rsn_ie_len = min(elem->len + 2, MAX_WPA_IE_LEN);
1046                         memcpy(bss->rsn_ie, elem, bss->rsn_ie_len);
1047                         lbs_deb_hex(LBS_DEB_SCAN, "process_bss: RSN_IE", bss->rsn_ie, elem->len);
1048                         break;
1049
1050                 default:
1051                         break;
1052                 }
1053
1054                 pos += elem->len + 2;
1055         }
1056
1057         /* Timestamp */
1058         bss->last_scanned = jiffies;
1059         libertas_unset_basic_rate_flags(bss->rates, sizeof(bss->rates));
1060
1061         ret = 0;
1062
1063 done:
1064         lbs_deb_leave_args(LBS_DEB_SCAN, "ret %d", ret);
1065         return ret;
1066 }
1067
1068 /**
1069  *  @brief Compare two SSIDs
1070  *
1071  *  @param ssid1    A pointer to ssid to compare
1072  *  @param ssid2    A pointer to ssid to compare
1073  *
1074  *  @return         0--ssid is same, otherwise is different
1075  */
1076 int libertas_ssid_cmp(u8 *ssid1, u8 ssid1_len, u8 *ssid2, u8 ssid2_len)
1077 {
1078         if (ssid1_len != ssid2_len)
1079                 return -1;
1080
1081         return memcmp(ssid1, ssid2, ssid1_len);
1082 }
1083
1084 /**
1085  *  @brief This function finds a specific compatible BSSID in the scan list
1086  *
1087  *  @param adapter  A pointer to wlan_adapter
1088  *  @param bssid    BSSID to find in the scan list
1089  *  @param mode     Network mode: Infrastructure or IBSS
1090  *
1091  *  @return         index in BSSID list, or error return code (< 0)
1092  */
1093 struct bss_descriptor * libertas_find_bssid_in_list(wlan_adapter * adapter,
1094                 u8 * bssid, u8 mode)
1095 {
1096         struct bss_descriptor * iter_bss;
1097         struct bss_descriptor * found_bss = NULL;
1098
1099         if (!bssid)
1100                 return NULL;
1101
1102         lbs_deb_hex(LBS_DEB_SCAN, "looking for",
1103                 bssid, ETH_ALEN);
1104
1105         /* Look through the scan table for a compatible match.  The loop will
1106          *   continue past a matched bssid that is not compatible in case there
1107          *   is an AP with multiple SSIDs assigned to the same BSSID
1108          */
1109         mutex_lock(&adapter->lock);
1110         list_for_each_entry (iter_bss, &adapter->network_list, list) {
1111                 if (compare_ether_addr(iter_bss->bssid, bssid))
1112                         continue; /* bssid doesn't match */
1113                 switch (mode) {
1114                 case IW_MODE_INFRA:
1115                 case IW_MODE_ADHOC:
1116                         if (!is_network_compatible(adapter, iter_bss, mode))
1117                                 break;
1118                         found_bss = iter_bss;
1119                         break;
1120                 default:
1121                         found_bss = iter_bss;
1122                         break;
1123                 }
1124         }
1125         mutex_unlock(&adapter->lock);
1126
1127         return found_bss;
1128 }
1129
1130 /**
1131  *  @brief This function finds ssid in ssid list.
1132  *
1133  *  @param adapter  A pointer to wlan_adapter
1134  *  @param ssid     SSID to find in the list
1135  *  @param bssid    BSSID to qualify the SSID selection (if provided)
1136  *  @param mode     Network mode: Infrastructure or IBSS
1137  *
1138  *  @return         index in BSSID list
1139  */
1140 struct bss_descriptor * libertas_find_ssid_in_list(wlan_adapter * adapter,
1141                    u8 *ssid, u8 ssid_len, u8 * bssid, u8 mode,
1142                    int channel)
1143 {
1144         u8 bestrssi = 0;
1145         struct bss_descriptor * iter_bss = NULL;
1146         struct bss_descriptor * found_bss = NULL;
1147         struct bss_descriptor * tmp_oldest = NULL;
1148
1149         mutex_lock(&adapter->lock);
1150
1151         list_for_each_entry (iter_bss, &adapter->network_list, list) {
1152                 if (   !tmp_oldest
1153                     || (iter_bss->last_scanned < tmp_oldest->last_scanned))
1154                         tmp_oldest = iter_bss;
1155
1156                 if (libertas_ssid_cmp(iter_bss->ssid, iter_bss->ssid_len,
1157                                       ssid, ssid_len) != 0)
1158                         continue; /* ssid doesn't match */
1159                 if (bssid && compare_ether_addr(iter_bss->bssid, bssid) != 0)
1160                         continue; /* bssid doesn't match */
1161                 if ((channel > 0) && (iter_bss->channel != channel))
1162                         continue; /* channel doesn't match */
1163
1164                 switch (mode) {
1165                 case IW_MODE_INFRA:
1166                 case IW_MODE_ADHOC:
1167                         if (!is_network_compatible(adapter, iter_bss, mode))
1168                                 break;
1169
1170                         if (bssid) {
1171                                 /* Found requested BSSID */
1172                                 found_bss = iter_bss;
1173                                 goto out;
1174                         }
1175
1176                         if (SCAN_RSSI(iter_bss->rssi) > bestrssi) {
1177                                 bestrssi = SCAN_RSSI(iter_bss->rssi);
1178                                 found_bss = iter_bss;
1179                         }
1180                         break;
1181                 case IW_MODE_AUTO:
1182                 default:
1183                         if (SCAN_RSSI(iter_bss->rssi) > bestrssi) {
1184                                 bestrssi = SCAN_RSSI(iter_bss->rssi);
1185                                 found_bss = iter_bss;
1186                         }
1187                         break;
1188                 }
1189         }
1190
1191 out:
1192         mutex_unlock(&adapter->lock);
1193         return found_bss;
1194 }
1195
1196 /**
1197  *  @brief This function finds the best SSID in the Scan List
1198  *
1199  *  Search the scan table for the best SSID that also matches the current
1200  *   adapter network preference (infrastructure or adhoc)
1201  *
1202  *  @param adapter  A pointer to wlan_adapter
1203  *
1204  *  @return         index in BSSID list
1205  */
1206 static struct bss_descriptor * libertas_find_best_ssid_in_list(wlan_adapter * adapter,
1207                 u8 mode)
1208 {
1209         u8 bestrssi = 0;
1210         struct bss_descriptor * iter_bss;
1211         struct bss_descriptor * best_bss = NULL;
1212
1213         mutex_lock(&adapter->lock);
1214
1215         list_for_each_entry (iter_bss, &adapter->network_list, list) {
1216                 switch (mode) {
1217                 case IW_MODE_INFRA:
1218                 case IW_MODE_ADHOC:
1219                         if (!is_network_compatible(adapter, iter_bss, mode))
1220                                 break;
1221                         if (SCAN_RSSI(iter_bss->rssi) <= bestrssi)
1222                                 break;
1223                         bestrssi = SCAN_RSSI(iter_bss->rssi);
1224                         best_bss = iter_bss;
1225                         break;
1226                 case IW_MODE_AUTO:
1227                 default:
1228                         if (SCAN_RSSI(iter_bss->rssi) <= bestrssi)
1229                                 break;
1230                         bestrssi = SCAN_RSSI(iter_bss->rssi);
1231                         best_bss = iter_bss;
1232                         break;
1233                 }
1234         }
1235
1236         mutex_unlock(&adapter->lock);
1237         return best_bss;
1238 }
1239
1240 /**
1241  *  @brief Find the AP with specific ssid in the scan list
1242  *
1243  *  @param priv         A pointer to wlan_private structure
1244  *  @param pSSID        A pointer to AP's ssid
1245  *
1246  *  @return             0--success, otherwise--fail
1247  */
1248 int libertas_find_best_network_ssid(wlan_private * priv,
1249                 u8 *out_ssid, u8 *out_ssid_len, u8 preferred_mode, u8 *out_mode)
1250 {
1251         wlan_adapter *adapter = priv->adapter;
1252         int ret = -1;
1253         struct bss_descriptor * found;
1254
1255         lbs_deb_enter(LBS_DEB_ASSOC);
1256
1257         wlan_scan_networks(priv, NULL, 1);
1258         if (adapter->surpriseremoved)
1259                 return -1;
1260
1261         wait_event_interruptible(adapter->cmd_pending, !adapter->nr_cmd_pending);
1262
1263         found = libertas_find_best_ssid_in_list(adapter, preferred_mode);
1264         if (found && (found->ssid_len > 0)) {
1265                 memcpy(out_ssid, &found->ssid, IW_ESSID_MAX_SIZE);
1266                 *out_ssid_len = found->ssid_len;
1267                 *out_mode = found->mode;
1268                 ret = 0;
1269         }
1270
1271         lbs_deb_leave_args(LBS_DEB_SCAN, "ret %d", ret);
1272         return ret;
1273 }
1274
1275 /**
1276  *  @brief Scan Network
1277  *
1278  *  @param dev          A pointer to net_device structure
1279  *  @param info         A pointer to iw_request_info structure
1280  *  @param vwrq         A pointer to iw_param structure
1281  *  @param extra        A pointer to extra data buf
1282  *
1283  *  @return             0 --success, otherwise fail
1284  */
1285 int libertas_set_scan(struct net_device *dev, struct iw_request_info *info,
1286                   struct iw_param *vwrq, char *extra)
1287 {
1288         wlan_private *priv = dev->priv;
1289         wlan_adapter *adapter = priv->adapter;
1290
1291         lbs_deb_enter(LBS_DEB_SCAN);
1292
1293         wlan_scan_networks(priv, NULL, 0);
1294
1295         if (adapter->surpriseremoved)
1296                 return -1;
1297
1298         lbs_deb_leave(LBS_DEB_SCAN);
1299         return 0;
1300 }
1301
1302 /**
1303  *  @brief Send a scan command for all available channels filtered on a spec
1304  *
1305  *  @param priv             A pointer to wlan_private structure
1306  *  @param prequestedssid   A pointer to AP's ssid
1307  *  @param keeppreviousscan Flag used to save/clear scan table before scan
1308  *
1309  *  @return                0-success, otherwise fail
1310  */
1311 int libertas_send_specific_ssid_scan(wlan_private * priv,
1312                         u8 *ssid, u8 ssid_len, u8 clear_ssid)
1313 {
1314         wlan_adapter *adapter = priv->adapter;
1315         struct wlan_ioctl_user_scan_cfg scancfg;
1316         int ret = 0;
1317
1318         lbs_deb_enter(LBS_DEB_ASSOC);
1319
1320         if (!ssid_len)
1321                 goto out;
1322
1323         memset(&scancfg, 0x00, sizeof(scancfg));
1324         memcpy(scancfg.ssid, ssid, ssid_len);
1325         scancfg.ssid_len = ssid_len;
1326         scancfg.clear_ssid = clear_ssid;
1327
1328         wlan_scan_networks(priv, &scancfg, 1);
1329         if (adapter->surpriseremoved)
1330                 return -1;
1331         wait_event_interruptible(adapter->cmd_pending, !adapter->nr_cmd_pending);
1332
1333 out:
1334         lbs_deb_leave(LBS_DEB_ASSOC);
1335         return ret;
1336 }
1337
1338 static inline char *libertas_translate_scan(wlan_private *priv,
1339                                         char *start, char *stop,
1340                                         struct bss_descriptor *bss)
1341 {
1342         wlan_adapter *adapter = priv->adapter;
1343         struct chan_freq_power *cfp;
1344         char *current_val;      /* For rates */
1345         struct iw_event iwe;    /* Temporary buffer */
1346         int j;
1347 #define PERFECT_RSSI ((u8)50)
1348 #define WORST_RSSI   ((u8)0)
1349 #define RSSI_DIFF    ((u8)(PERFECT_RSSI - WORST_RSSI))
1350         u8 rssi;
1351
1352         cfp = libertas_find_cfp_by_band_and_channel(adapter, 0, bss->channel);
1353         if (!cfp) {
1354                 lbs_deb_scan("Invalid channel number %d\n", bss->channel);
1355                 return NULL;
1356         }
1357
1358         /* First entry *MUST* be the AP BSSID */
1359         iwe.cmd = SIOCGIWAP;
1360         iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
1361         memcpy(iwe.u.ap_addr.sa_data, &bss->bssid, ETH_ALEN);
1362         start = iwe_stream_add_event(start, stop, &iwe, IW_EV_ADDR_LEN);
1363
1364         /* SSID */
1365         iwe.cmd = SIOCGIWESSID;
1366         iwe.u.data.flags = 1;
1367         iwe.u.data.length = min((u32) bss->ssid_len, (u32) IW_ESSID_MAX_SIZE);
1368         start = iwe_stream_add_point(start, stop, &iwe, bss->ssid);
1369
1370         /* Mode */
1371         iwe.cmd = SIOCGIWMODE;
1372         iwe.u.mode = bss->mode;
1373         start = iwe_stream_add_event(start, stop, &iwe, IW_EV_UINT_LEN);
1374
1375         /* Frequency */
1376         iwe.cmd = SIOCGIWFREQ;
1377         iwe.u.freq.m = (long)cfp->freq * 100000;
1378         iwe.u.freq.e = 1;
1379         start = iwe_stream_add_event(start, stop, &iwe, IW_EV_FREQ_LEN);
1380
1381         /* Add quality statistics */
1382         iwe.cmd = IWEVQUAL;
1383         iwe.u.qual.updated = IW_QUAL_ALL_UPDATED;
1384         iwe.u.qual.level = SCAN_RSSI(bss->rssi);
1385
1386         rssi = iwe.u.qual.level - MRVDRV_NF_DEFAULT_SCAN_VALUE;
1387         iwe.u.qual.qual =
1388             (100 * RSSI_DIFF * RSSI_DIFF - (PERFECT_RSSI - rssi) *
1389              (15 * (RSSI_DIFF) + 62 * (PERFECT_RSSI - rssi))) /
1390             (RSSI_DIFF * RSSI_DIFF);
1391         if (iwe.u.qual.qual > 100)
1392                 iwe.u.qual.qual = 100;
1393
1394         if (adapter->NF[TYPE_BEACON][TYPE_NOAVG] == 0) {
1395                 iwe.u.qual.noise = MRVDRV_NF_DEFAULT_SCAN_VALUE;
1396         } else {
1397                 iwe.u.qual.noise =
1398                     CAL_NF(adapter->NF[TYPE_BEACON][TYPE_NOAVG]);
1399         }
1400
1401         /* Locally created ad-hoc BSSs won't have beacons if this is the
1402          * only station in the adhoc network; so get signal strength
1403          * from receive statistics.
1404          */
1405         if ((adapter->mode == IW_MODE_ADHOC)
1406             && adapter->adhoccreate
1407             && !libertas_ssid_cmp(adapter->curbssparams.ssid,
1408                                   adapter->curbssparams.ssid_len,
1409                                   bss->ssid, bss->ssid_len)) {
1410                 int snr, nf;
1411                 snr = adapter->SNR[TYPE_RXPD][TYPE_AVG] / AVG_SCALE;
1412                 nf = adapter->NF[TYPE_RXPD][TYPE_AVG] / AVG_SCALE;
1413                 iwe.u.qual.level = CAL_RSSI(snr, nf);
1414         }
1415         start = iwe_stream_add_event(start, stop, &iwe, IW_EV_QUAL_LEN);
1416
1417         /* Add encryption capability */
1418         iwe.cmd = SIOCGIWENCODE;
1419         if (bss->capability & WLAN_CAPABILITY_PRIVACY) {
1420                 iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
1421         } else {
1422                 iwe.u.data.flags = IW_ENCODE_DISABLED;
1423         }
1424         iwe.u.data.length = 0;
1425         start = iwe_stream_add_point(start, stop, &iwe, bss->ssid);
1426
1427         current_val = start + IW_EV_LCP_LEN;
1428
1429         iwe.cmd = SIOCGIWRATE;
1430         iwe.u.bitrate.fixed = 0;
1431         iwe.u.bitrate.disabled = 0;
1432         iwe.u.bitrate.value = 0;
1433
1434         for (j = 0; bss->rates[j] && (j < sizeof(bss->rates)); j++) {
1435                 /* Bit rate given in 500 kb/s units */
1436                 iwe.u.bitrate.value = bss->rates[j] * 500000;
1437                 current_val = iwe_stream_add_value(start, current_val,
1438                                          stop, &iwe, IW_EV_PARAM_LEN);
1439         }
1440         if ((bss->mode == IW_MODE_ADHOC)
1441             && !libertas_ssid_cmp(adapter->curbssparams.ssid,
1442                                   adapter->curbssparams.ssid_len,
1443                                   bss->ssid, bss->ssid_len)
1444             && adapter->adhoccreate) {
1445                 iwe.u.bitrate.value = 22 * 500000;
1446                 current_val = iwe_stream_add_value(start, current_val,
1447                                          stop, &iwe, IW_EV_PARAM_LEN);
1448         }
1449         /* Check if we added any event */
1450         if((current_val - start) > IW_EV_LCP_LEN)
1451                 start = current_val;
1452
1453         memset(&iwe, 0, sizeof(iwe));
1454         if (bss->wpa_ie_len) {
1455                 char buf[MAX_WPA_IE_LEN];
1456                 memcpy(buf, bss->wpa_ie, bss->wpa_ie_len);
1457                 iwe.cmd = IWEVGENIE;
1458                 iwe.u.data.length = bss->wpa_ie_len;
1459                 start = iwe_stream_add_point(start, stop, &iwe, buf);
1460         }
1461
1462         memset(&iwe, 0, sizeof(iwe));
1463         if (bss->rsn_ie_len) {
1464                 char buf[MAX_WPA_IE_LEN];
1465                 memcpy(buf, bss->rsn_ie, bss->rsn_ie_len);
1466                 iwe.cmd = IWEVGENIE;
1467                 iwe.u.data.length = bss->rsn_ie_len;
1468                 start = iwe_stream_add_point(start, stop, &iwe, buf);
1469         }
1470
1471         return start;
1472 }
1473
1474 /**
1475  *  @brief  Retrieve the scan table entries via wireless tools IOCTL call
1476  *
1477  *  @param dev          A pointer to net_device structure
1478  *  @param info         A pointer to iw_request_info structure
1479  *  @param dwrq         A pointer to iw_point structure
1480  *  @param extra        A pointer to extra data buf
1481  *
1482  *  @return             0 --success, otherwise fail
1483  */
1484 int libertas_get_scan(struct net_device *dev, struct iw_request_info *info,
1485                   struct iw_point *dwrq, char *extra)
1486 {
1487 #define SCAN_ITEM_SIZE 128
1488         wlan_private *priv = dev->priv;
1489         wlan_adapter *adapter = priv->adapter;
1490         int err = 0;
1491         char *ev = extra;
1492         char *stop = ev + dwrq->length;
1493         struct bss_descriptor * iter_bss;
1494         struct bss_descriptor * safe;
1495
1496         lbs_deb_enter(LBS_DEB_ASSOC);
1497
1498         /* If we've got an uncompleted scan, schedule the next part */
1499         if (!adapter->nr_cmd_pending && adapter->last_scanned_channel)
1500                 wlan_scan_networks(priv, NULL, 0);
1501
1502         /* Update RSSI if current BSS is a locally created ad-hoc BSS */
1503         if ((adapter->mode == IW_MODE_ADHOC) && adapter->adhoccreate) {
1504                 libertas_prepare_and_send_command(priv, CMD_802_11_RSSI, 0,
1505                                         CMD_OPTION_WAITFORRSP, 0, NULL);
1506         }
1507
1508         mutex_lock(&adapter->lock);
1509         list_for_each_entry_safe (iter_bss, safe, &adapter->network_list, list) {
1510                 char * next_ev;
1511                 unsigned long stale_time;
1512
1513                 if (stop - ev < SCAN_ITEM_SIZE) {
1514                         err = -E2BIG;
1515                         break;
1516                 }
1517
1518                 /* For mesh device, list only mesh networks */
1519                 if (dev == priv->mesh_dev && !iter_bss->mesh)
1520                         continue;
1521
1522                 /* Prune old an old scan result */
1523                 stale_time = iter_bss->last_scanned + DEFAULT_MAX_SCAN_AGE;
1524                 if (time_after(jiffies, stale_time)) {
1525                         list_move_tail (&iter_bss->list,
1526                                         &adapter->network_free_list);
1527                         clear_bss_descriptor(iter_bss);
1528                         continue;
1529                 }
1530
1531                 /* Translate to WE format this entry */
1532                 next_ev = libertas_translate_scan(priv, ev, stop, iter_bss);
1533                 if (next_ev == NULL)
1534                         continue;
1535                 ev = next_ev;
1536         }
1537         mutex_unlock(&adapter->lock);
1538
1539         dwrq->length = (ev - extra);
1540         dwrq->flags = 0;
1541
1542         lbs_deb_leave(LBS_DEB_ASSOC);
1543         return err;
1544 }
1545
1546 /**
1547  *  @brief Prepare a scan command to be sent to the firmware
1548  *
1549  *  Use the wlan_scan_cmd_config sent to the command processing module in
1550  *   the libertas_prepare_and_send_command to configure a cmd_ds_802_11_scan command
1551  *   struct to send to firmware.
1552  *
1553  *  The fixed fields specifying the BSS type and BSSID filters as well as a
1554  *   variable number/length of TLVs are sent in the command to firmware.
1555  *
1556  *  @param priv       A pointer to wlan_private structure
1557  *  @param cmd        A pointer to cmd_ds_command structure to be sent to
1558  *                    firmware with the cmd_DS_801_11_SCAN structure
1559  *  @param pdata_buf  Void pointer cast of a wlan_scan_cmd_config struct used
1560  *                    to set the fields/TLVs for the command sent to firmware
1561  *
1562  *  @return           0 or -1
1563  *
1564  *  @sa wlan_scan_create_channel_list
1565  */
1566 int libertas_cmd_80211_scan(wlan_private * priv,
1567                          struct cmd_ds_command *cmd, void *pdata_buf)
1568 {
1569         struct cmd_ds_802_11_scan *pscan = &cmd->params.scan;
1570         struct wlan_scan_cmd_config *pscancfg;
1571
1572         lbs_deb_enter(LBS_DEB_ASSOC);
1573
1574         pscancfg = pdata_buf;
1575
1576         /* Set fixed field variables in scan command */
1577         pscan->bsstype = pscancfg->bsstype;
1578         memcpy(pscan->bssid, pscancfg->bssid, ETH_ALEN);
1579         memcpy(pscan->tlvbuffer, pscancfg->tlvbuffer, pscancfg->tlvbufferlen);
1580
1581         cmd->command = cpu_to_le16(CMD_802_11_SCAN);
1582
1583         /* size is equal to the sizeof(fixed portions) + the TLV len + header */
1584         cmd->size = cpu_to_le16(sizeof(pscan->bsstype) + ETH_ALEN
1585                                 + pscancfg->tlvbufferlen + S_DS_GEN);
1586
1587         lbs_deb_scan("SCAN_CMD: command=%x, size=%x, seqnum=%x\n",
1588                      le16_to_cpu(cmd->command), le16_to_cpu(cmd->size),
1589                      le16_to_cpu(cmd->seqnum));
1590
1591         lbs_deb_leave(LBS_DEB_ASSOC);
1592         return 0;
1593 }
1594
1595 static inline int is_same_network(struct bss_descriptor *src,
1596                                   struct bss_descriptor *dst)
1597 {
1598         /* A network is only a duplicate if the channel, BSSID, and ESSID
1599          * all match.  We treat all <hidden> with the same BSSID and channel
1600          * as one network */
1601         return ((src->ssid_len == dst->ssid_len) &&
1602                 (src->channel == dst->channel) &&
1603                 !compare_ether_addr(src->bssid, dst->bssid) &&
1604                 !memcmp(src->ssid, dst->ssid, src->ssid_len));
1605 }
1606
1607 /**
1608  *  @brief This function handles the command response of scan
1609  *
1610  *   The response buffer for the scan command has the following
1611  *      memory layout:
1612  *
1613  *     .-----------------------------------------------------------.
1614  *     |  header (4 * sizeof(u16)):  Standard command response hdr |
1615  *     .-----------------------------------------------------------.
1616  *     |  bufsize (u16) : sizeof the BSS Description data          |
1617  *     .-----------------------------------------------------------.
1618  *     |  NumOfSet (u8) : Number of BSS Descs returned             |
1619  *     .-----------------------------------------------------------.
1620  *     |  BSSDescription data (variable, size given in bufsize)    |
1621  *     .-----------------------------------------------------------.
1622  *     |  TLV data (variable, size calculated using header->size,  |
1623  *     |            bufsize and sizeof the fixed fields above)     |
1624  *     .-----------------------------------------------------------.
1625  *
1626  *  @param priv    A pointer to wlan_private structure
1627  *  @param resp    A pointer to cmd_ds_command
1628  *
1629  *  @return        0 or -1
1630  */
1631 int libertas_ret_80211_scan(wlan_private * priv, struct cmd_ds_command *resp)
1632 {
1633         wlan_adapter *adapter = priv->adapter;
1634         struct cmd_ds_802_11_scan_rsp *pscan;
1635         struct bss_descriptor * iter_bss;
1636         struct bss_descriptor * safe;
1637         u8 *pbssinfo;
1638         u16 scanrespsize;
1639         int bytesleft;
1640         int idx;
1641         int tlvbufsize;
1642         int ret;
1643
1644         lbs_deb_enter(LBS_DEB_ASSOC);
1645
1646         /* Prune old entries from scan table */
1647         list_for_each_entry_safe (iter_bss, safe, &adapter->network_list, list) {
1648                 unsigned long stale_time = iter_bss->last_scanned + DEFAULT_MAX_SCAN_AGE;
1649                 if (time_before(jiffies, stale_time))
1650                         continue;
1651                 list_move_tail (&iter_bss->list, &adapter->network_free_list);
1652                 clear_bss_descriptor(iter_bss);
1653         }
1654
1655         pscan = &resp->params.scanresp;
1656
1657         if (pscan->nr_sets > MAX_NETWORK_COUNT) {
1658                 lbs_deb_scan(
1659                        "SCAN_RESP: too many scan results (%d, max %d)!!\n",
1660                        pscan->nr_sets, MAX_NETWORK_COUNT);
1661                 ret = -1;
1662                 goto done;
1663         }
1664
1665         bytesleft = le16_to_cpu(pscan->bssdescriptsize);
1666         lbs_deb_scan("SCAN_RESP: bssdescriptsize %d\n", bytesleft);
1667
1668         scanrespsize = le16_to_cpu(resp->size);
1669         lbs_deb_scan("SCAN_RESP: returned %d AP before parsing\n",
1670                pscan->nr_sets);
1671
1672         pbssinfo = pscan->bssdesc_and_tlvbuffer;
1673
1674         /* The size of the TLV buffer is equal to the entire command response
1675          *   size (scanrespsize) minus the fixed fields (sizeof()'s), the
1676          *   BSS Descriptions (bssdescriptsize as bytesLef) and the command
1677          *   response header (S_DS_GEN)
1678          */
1679         tlvbufsize = scanrespsize - (bytesleft + sizeof(pscan->bssdescriptsize)
1680                                      + sizeof(pscan->nr_sets)
1681                                      + S_DS_GEN);
1682
1683         /*
1684          *  Process each scan response returned (pscan->nr_sets).  Save
1685          *    the information in the newbssentry and then insert into the
1686          *    driver scan table either as an update to an existing entry
1687          *    or as an addition at the end of the table
1688          */
1689         for (idx = 0; idx < pscan->nr_sets && bytesleft; idx++) {
1690                 struct bss_descriptor new;
1691                 struct bss_descriptor * found = NULL;
1692                 struct bss_descriptor * oldest = NULL;
1693
1694                 /* Process the data fields and IEs returned for this BSS */
1695                 memset(&new, 0, sizeof (struct bss_descriptor));
1696                 if (libertas_process_bss(&new, &pbssinfo, &bytesleft) != 0) {
1697                         /* error parsing the scan response, skipped */
1698                         lbs_deb_scan("SCAN_RESP: process_bss returned ERROR\n");
1699                         continue;
1700                 }
1701
1702                 /* Try to find this bss in the scan table */
1703                 list_for_each_entry (iter_bss, &adapter->network_list, list) {
1704                         if (is_same_network(iter_bss, &new)) {
1705                                 found = iter_bss;
1706                                 break;
1707                         }
1708
1709                         if ((oldest == NULL) ||
1710                             (iter_bss->last_scanned < oldest->last_scanned))
1711                                 oldest = iter_bss;
1712                 }
1713
1714                 if (found) {
1715                         /* found, clear it */
1716                         clear_bss_descriptor(found);
1717                 } else if (!list_empty(&adapter->network_free_list)) {
1718                         /* Pull one from the free list */
1719                         found = list_entry(adapter->network_free_list.next,
1720                                            struct bss_descriptor, list);
1721                         list_move_tail(&found->list, &adapter->network_list);
1722                 } else if (oldest) {
1723                         /* If there are no more slots, expire the oldest */
1724                         found = oldest;
1725                         clear_bss_descriptor(found);
1726                         list_move_tail(&found->list, &adapter->network_list);
1727                 } else {
1728                         continue;
1729                 }
1730
1731                 lbs_deb_scan("SCAN_RESP: BSSID = " MAC_FMT "\n",
1732                        new.bssid[0], new.bssid[1], new.bssid[2],
1733                        new.bssid[3], new.bssid[4], new.bssid[5]);
1734
1735                 /* Copy the locally created newbssentry to the scan table */
1736                 memcpy(found, &new, offsetof(struct bss_descriptor, list));
1737         }
1738
1739         ret = 0;
1740
1741 done:
1742         lbs_deb_leave_args(LBS_DEB_SCAN, "ret %d", ret);
1743         return ret;
1744 }