Merge branch 'for-linus' of master.kernel.org:/home/rmk/linux-2.6-arm
[linux-2.6] / drivers / net / wireless / libertas / scan.c
1 /* -*- mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
2 /* vi: set expandtab shiftwidth=4 tabstop=4 textwidth=78: */
3
4 /**
5   * Functions implementing wlan scan IOCTL and firmware command APIs
6   *
7   * IOCTL handlers as well as command preperation and response routines
8   *  for sending scan commands to the firmware.
9   */
10 #include <linux/ctype.h>
11 #include <linux/if.h>
12 #include <linux/netdevice.h>
13 #include <linux/wireless.h>
14
15 #include <net/ieee80211.h>
16 #include <net/iw_handler.h>
17
18 #include "host.h"
19 #include "decl.h"
20 #include "dev.h"
21 #include "scan.h"
22
23 //! Approximate amount of data needed to pass a scan result back to iwlist
24 #define MAX_SCAN_CELL_SIZE  (IW_EV_ADDR_LEN             \
25                              + IW_ESSID_MAX_SIZE        \
26                              + IW_EV_UINT_LEN           \
27                              + IW_EV_FREQ_LEN           \
28                              + IW_EV_QUAL_LEN           \
29                              + IW_ESSID_MAX_SIZE        \
30                              + IW_EV_PARAM_LEN          \
31                              + 40)      /* 40 for WPAIE */
32
33 //! Memory needed to store a max sized channel List TLV for a firmware scan
34 #define CHAN_TLV_MAX_SIZE  (sizeof(struct mrvlietypesheader)    \
35                             + (MRVDRV_MAX_CHANNELS_PER_SCAN     \
36                                * sizeof(struct chanscanparamset)))
37
38 //! Memory needed to store a max number/size SSID TLV for a firmware scan
39 #define SSID_TLV_MAX_SIZE  (1 * sizeof(struct mrvlietypes_ssidparamset))
40
41 //! Maximum memory needed for a wlan_scan_cmd_config with all TLVs at max
42 #define MAX_SCAN_CFG_ALLOC (sizeof(struct wlan_scan_cmd_config)  \
43                             + sizeof(struct mrvlietypes_numprobes)   \
44                             + CHAN_TLV_MAX_SIZE                 \
45                             + SSID_TLV_MAX_SIZE)
46
47 //! The maximum number of channels the firmware can scan per command
48 #define MRVDRV_MAX_CHANNELS_PER_SCAN   14
49
50 /**
51  * @brief Number of channels to scan per firmware scan command issuance.
52  *
53  *  Number restricted to prevent hitting the limit on the amount of scan data
54  *  returned in a single firmware scan command.
55  */
56 #define MRVDRV_CHANNELS_PER_SCAN_CMD   4
57
58 //! Scan time specified in the channel TLV for each channel for passive scans
59 #define MRVDRV_PASSIVE_SCAN_CHAN_TIME  100
60
61 //! Scan time specified in the channel TLV for each channel for active scans
62 #define MRVDRV_ACTIVE_SCAN_CHAN_TIME   100
63
64 //! Macro to enable/disable SSID checking before storing a scan table
65 #ifdef DISCARD_BAD_SSID
66 #define CHECK_SSID_IS_VALID(x) ssid_valid(&bssidEntry.ssid)
67 #else
68 #define CHECK_SSID_IS_VALID(x) 1
69 #endif
70
71 /**
72  *  @brief Check if a scanned network compatible with the driver settings
73  *
74  *   WEP     WPA     WPA2    ad-hoc  encrypt                      Network
75  * enabled enabled  enabled   AES     mode   privacy  WPA  WPA2  Compatible
76  *    0       0        0       0      NONE      0      0    0   yes No security
77  *    1       0        0       0      NONE      1      0    0   yes Static WEP
78  *    0       1        0       0       x        1x     1    x   yes WPA
79  *    0       0        1       0       x        1x     x    1   yes WPA2
80  *    0       0        0       1      NONE      1      0    0   yes Ad-hoc AES
81  *    0       0        0       0     !=NONE     1      0    0   yes Dynamic WEP
82  *
83  *
84  *  @param adapter A pointer to wlan_adapter
85  *  @param index   Index in scantable to check against current driver settings
86  *  @param mode    Network mode: Infrastructure or IBSS
87  *
88  *  @return        Index in scantable, or error code if negative
89  */
90 static int is_network_compatible(wlan_adapter * adapter, int index, int mode)
91 {
92         ENTER();
93
94         if (adapter->scantable[index].inframode == mode) {
95                 if (adapter->secinfo.WEPstatus == wlan802_11WEPdisabled
96                     && !adapter->secinfo.WPAenabled
97                     && !adapter->secinfo.WPA2enabled
98                     && adapter->scantable[index].wpa_supplicant.wpa_ie[0] !=
99                     WPA_IE
100                     && adapter->scantable[index].wpa2_supplicant.wpa_ie[0] !=
101                     WPA2_IE && adapter->secinfo.Encryptionmode == CIPHER_NONE
102                     && !adapter->scantable[index].privacy) {
103                         /* no security */
104                         LEAVE();
105                         return index;
106                 } else if (adapter->secinfo.WEPstatus == wlan802_11WEPenabled
107                            && !adapter->secinfo.WPAenabled
108                            && !adapter->secinfo.WPA2enabled
109                            && adapter->scantable[index].privacy) {
110                         /* static WEP enabled */
111                         LEAVE();
112                         return index;
113                 } else if (adapter->secinfo.WEPstatus == wlan802_11WEPdisabled
114                            && adapter->secinfo.WPAenabled
115                            && !adapter->secinfo.WPA2enabled
116                            && (adapter->scantable[index].wpa_supplicant.
117                                wpa_ie[0]
118                                == WPA_IE)
119                            /* privacy bit may NOT be set in some APs like LinkSys WRT54G
120                               && adapter->scantable[index].privacy */
121                     ) {
122                         /* WPA enabled */
123             lbs_pr_debug(1,
124                                "is_network_compatible() WPA: index=%d wpa_ie=%#x "
125                                "wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s Encmode=%#x "
126                                "privacy=%#x\n", index,
127                                adapter->scantable[index].wpa_supplicant.
128                                wpa_ie[0],
129                                adapter->scantable[index].wpa2_supplicant.
130                                wpa_ie[0],
131                                (adapter->secinfo.WEPstatus ==
132                                 wlan802_11WEPenabled) ? "e" : "d",
133                                (adapter->secinfo.WPAenabled) ? "e" : "d",
134                                (adapter->secinfo.WPA2enabled) ? "e" : "d",
135                                adapter->secinfo.Encryptionmode,
136                                adapter->scantable[index].privacy);
137                         LEAVE();
138                         return index;
139                 } else if (adapter->secinfo.WEPstatus == wlan802_11WEPdisabled
140                            && !adapter->secinfo.WPAenabled
141                            && adapter->secinfo.WPA2enabled
142                            && (adapter->scantable[index].wpa2_supplicant.
143                                wpa_ie[0]
144                                == WPA2_IE)
145                            /* privacy bit may NOT be set in some APs like LinkSys WRT54G
146                               && adapter->scantable[index].privacy */
147                     ) {
148                         /* WPA2 enabled */
149             lbs_pr_debug(1,
150                                "is_network_compatible() WPA2: index=%d wpa_ie=%#x "
151                                "wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s Encmode=%#x "
152                                "privacy=%#x\n", index,
153                                adapter->scantable[index].wpa_supplicant.
154                                wpa_ie[0],
155                                adapter->scantable[index].wpa2_supplicant.
156                                wpa_ie[0],
157                                (adapter->secinfo.WEPstatus ==
158                                 wlan802_11WEPenabled) ? "e" : "d",
159                                (adapter->secinfo.WPAenabled) ? "e" : "d",
160                                (adapter->secinfo.WPA2enabled) ? "e" : "d",
161                                adapter->secinfo.Encryptionmode,
162                                adapter->scantable[index].privacy);
163                         LEAVE();
164                         return index;
165                 } else if (adapter->secinfo.WEPstatus == wlan802_11WEPdisabled
166                            && !adapter->secinfo.WPAenabled
167                            && !adapter->secinfo.WPA2enabled
168                            && (adapter->scantable[index].wpa_supplicant.
169                                wpa_ie[0]
170                                != WPA_IE)
171                            && (adapter->scantable[index].wpa2_supplicant.
172                                wpa_ie[0]
173                                != WPA2_IE)
174                            && adapter->secinfo.Encryptionmode != CIPHER_NONE
175                            && adapter->scantable[index].privacy) {
176                         /* dynamic WEP enabled */
177             lbs_pr_debug(1,
178                                "is_network_compatible() dynamic WEP: index=%d "
179                                "wpa_ie=%#x wpa2_ie=%#x Encmode=%#x privacy=%#x\n",
180                                index,
181                                adapter->scantable[index].wpa_supplicant.
182                                wpa_ie[0],
183                                adapter->scantable[index].wpa2_supplicant.
184                                wpa_ie[0], adapter->secinfo.Encryptionmode,
185                                adapter->scantable[index].privacy);
186                         LEAVE();
187                         return index;
188                 }
189
190                 /* security doesn't match */
191         lbs_pr_debug(1,
192                        "is_network_compatible() FAILED: index=%d wpa_ie=%#x "
193                        "wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s Encmode=%#x privacy=%#x\n",
194                        index,
195                        adapter->scantable[index].wpa_supplicant.wpa_ie[0],
196                        adapter->scantable[index].wpa2_supplicant.wpa_ie[0],
197                        (adapter->secinfo.WEPstatus ==
198                         wlan802_11WEPenabled) ? "e" : "d",
199                        (adapter->secinfo.WPAenabled) ? "e" : "d",
200                        (adapter->secinfo.WPA2enabled) ? "e" : "d",
201                        adapter->secinfo.Encryptionmode,
202                        adapter->scantable[index].privacy);
203                 LEAVE();
204                 return -ECONNREFUSED;
205         }
206
207         /* mode doesn't match */
208         LEAVE();
209         return -ENETUNREACH;
210 }
211
212 /**
213  *  @brief This function validates a SSID as being able to be printed
214  *
215  *  @param pssid   SSID structure to validate
216  *
217  *  @return        TRUE or FALSE
218  */
219 static u8 ssid_valid(struct WLAN_802_11_SSID *pssid)
220 {
221         int ssididx;
222
223         for (ssididx = 0; ssididx < pssid->ssidlength; ssididx++) {
224                 if (!isprint(pssid->ssid[ssididx])) {
225                         return 0;
226                 }
227         }
228
229         return 1;
230 }
231
232 /**
233  *  @brief Post process the scan table after a new scan command has completed
234  *
235  *  Inspect each entry of the scan table and try to find an entry that
236  *    matches our current associated/joined network from the scan.  If
237  *    one is found, update the stored copy of the bssdescriptor for our
238  *    current network.
239  *
240  *  Debug dump the current scan table contents if compiled accordingly.
241  *
242  *  @param priv   A pointer to wlan_private structure
243  *
244  *  @return       void
245  */
246 static void wlan_scan_process_results(wlan_private * priv)
247 {
248         wlan_adapter *adapter = priv->adapter;
249         int foundcurrent;
250         int i;
251
252         foundcurrent = 0;
253
254         if (adapter->connect_status == libertas_connected) {
255                 /* try to find the current BSSID in the new scan list */
256                 for (i = 0; i < adapter->numinscantable; i++) {
257                         if (!libertas_SSID_cmp(&adapter->scantable[i].ssid,
258                                      &adapter->curbssparams.ssid) &&
259                             !memcmp(adapter->curbssparams.bssid,
260                                     adapter->scantable[i].macaddress,
261                                     ETH_ALEN)) {
262                                 foundcurrent = 1;
263                         }
264                 }
265
266                 if (foundcurrent) {
267                         /* Make a copy of current BSSID descriptor */
268                         memcpy(&adapter->curbssparams.bssdescriptor,
269                                &adapter->scantable[i],
270                                sizeof(adapter->curbssparams.bssdescriptor));
271                 }
272         }
273
274         for (i = 0; i < adapter->numinscantable; i++) {
275                 lbs_pr_debug(1, "Scan:(%02d) %02x:%02x:%02x:%02x:%02x:%02x, "
276                        "RSSI[%03d], SSID[%s]\n",
277                        i,
278                        adapter->scantable[i].macaddress[0],
279                        adapter->scantable[i].macaddress[1],
280                        adapter->scantable[i].macaddress[2],
281                        adapter->scantable[i].macaddress[3],
282                        adapter->scantable[i].macaddress[4],
283                        adapter->scantable[i].macaddress[5],
284                        (s32) adapter->scantable[i].rssi,
285                        adapter->scantable[i].ssid.ssid);
286         }
287 }
288
289 /**
290  *  @brief Create a channel list for the driver to scan based on region info
291  *
292  *  Use the driver region/band information to construct a comprehensive list
293  *    of channels to scan.  This routine is used for any scan that is not
294  *    provided a specific channel list to scan.
295  *
296  *  @param priv          A pointer to wlan_private structure
297  *  @param scanchanlist  Output parameter: resulting channel list to scan
298  *  @param filteredscan  Flag indicating whether or not a BSSID or SSID filter
299  *                       is being sent in the command to firmware.  Used to
300  *                       increase the number of channels sent in a scan
301  *                       command and to disable the firmware channel scan
302  *                       filter.
303  *
304  *  @return              void
305  */
306 static void wlan_scan_create_channel_list(wlan_private * priv,
307                                           struct chanscanparamset * scanchanlist,
308                                           u8 filteredscan)
309 {
310
311         wlan_adapter *adapter = priv->adapter;
312         struct region_channel *scanregion;
313         struct chan_freq_power *cfp;
314         int rgnidx;
315         int chanidx;
316         int nextchan;
317         u8 scantype;
318
319         chanidx = 0;
320
321         /* Set the default scan type to the user specified type, will later
322          *   be changed to passive on a per channel basis if restricted by
323          *   regulatory requirements (11d or 11h)
324          */
325         scantype = adapter->scantype;
326
327         for (rgnidx = 0; rgnidx < ARRAY_SIZE(adapter->region_channel); rgnidx++) {
328                 if (priv->adapter->enable11d &&
329                     adapter->connect_status != libertas_connected) {
330                         /* Scan all the supported chan for the first scan */
331                         if (!adapter->universal_channel[rgnidx].valid)
332                                 continue;
333                         scanregion = &adapter->universal_channel[rgnidx];
334
335                         /* clear the parsed_region_chan for the first scan */
336                         memset(&adapter->parsed_region_chan, 0x00,
337                                sizeof(adapter->parsed_region_chan));
338                 } else {
339                         if (!adapter->region_channel[rgnidx].valid)
340                                 continue;
341                         scanregion = &adapter->region_channel[rgnidx];
342                 }
343
344                 for (nextchan = 0;
345                      nextchan < scanregion->nrcfp; nextchan++, chanidx++) {
346
347                         cfp = scanregion->CFP + nextchan;
348
349                         if (priv->adapter->enable11d) {
350                                 scantype =
351                                     libertas_get_scan_type_11d(cfp->channel,
352                                                            &adapter->
353                                                            parsed_region_chan);
354                         }
355
356                         switch (scanregion->band) {
357                         case BAND_B:
358                         case BAND_G:
359                         default:
360                                 scanchanlist[chanidx].radiotype =
361                                     cmd_scan_radio_type_bg;
362                                 break;
363                         }
364
365                         if (scantype == cmd_scan_type_passive) {
366                                 scanchanlist[chanidx].maxscantime =
367                                     cpu_to_le16
368                                     (MRVDRV_PASSIVE_SCAN_CHAN_TIME);
369                                 scanchanlist[chanidx].chanscanmode.passivescan =
370                                     1;
371                         } else {
372                                 scanchanlist[chanidx].maxscantime =
373                                     cpu_to_le16
374                                     (MRVDRV_ACTIVE_SCAN_CHAN_TIME);
375                                 scanchanlist[chanidx].chanscanmode.passivescan =
376                                     0;
377                         }
378
379                         scanchanlist[chanidx].channumber = cfp->channel;
380
381                         if (filteredscan) {
382                                 scanchanlist[chanidx].chanscanmode.
383                                     disablechanfilt = 1;
384                         }
385                 }
386         }
387 }
388
389 /**
390  *  @brief Construct a wlan_scan_cmd_config structure to use in issue scan cmds
391  *
392  *  Application layer or other functions can invoke wlan_scan_networks
393  *    with a scan configuration supplied in a wlan_ioctl_user_scan_cfg struct.
394  *    This structure is used as the basis of one or many wlan_scan_cmd_config
395  *    commands that are sent to the command processing module and sent to
396  *    firmware.
397  *
398  *  Create a wlan_scan_cmd_config based on the following user supplied
399  *    parameters (if present):
400  *             - SSID filter
401  *             - BSSID filter
402  *             - Number of Probes to be sent
403  *             - channel list
404  *
405  *  If the SSID or BSSID filter is not present, disable/clear the filter.
406  *  If the number of probes is not set, use the adapter default setting
407  *  Qualify the channel
408  *
409  *  @param priv             A pointer to wlan_private structure
410  *  @param puserscanin      NULL or pointer to scan configuration parameters
411  *  @param ppchantlvout     Output parameter: Pointer to the start of the
412  *                          channel TLV portion of the output scan config
413  *  @param pscanchanlist    Output parameter: Pointer to the resulting channel
414  *                          list to scan
415  *  @param pmaxchanperscan  Output parameter: Number of channels to scan for
416  *                          each issuance of the firmware scan command
417  *  @param pfilteredscan    Output parameter: Flag indicating whether or not
418  *                          a BSSID or SSID filter is being sent in the
419  *                          command to firmware.  Used to increase the number
420  *                          of channels sent in a scan command and to
421  *                          disable the firmware channel scan filter.
422  *  @param pscancurrentonly Output parameter: Flag indicating whether or not
423  *                          we are only scanning our current active channel
424  *
425  *  @return                 resulting scan configuration
426  */
427 static struct wlan_scan_cmd_config *
428 wlan_scan_setup_scan_config(wlan_private * priv,
429                             const struct wlan_ioctl_user_scan_cfg * puserscanin,
430                             struct mrvlietypes_chanlistparamset ** ppchantlvout,
431                             struct chanscanparamset * pscanchanlist,
432                             int *pmaxchanperscan,
433                             u8 * pfilteredscan,
434                             u8 * pscancurrentonly)
435 {
436         wlan_adapter *adapter = priv->adapter;
437         const u8 zeromac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };
438         struct mrvlietypes_numprobes *pnumprobestlv;
439         struct mrvlietypes_ssidparamset *pssidtlv;
440         struct wlan_scan_cmd_config * pscancfgout = NULL;
441         u8 *ptlvpos;
442         u16 numprobes;
443         u16 ssidlen;
444         int chanidx;
445         int scantype;
446         int scandur;
447         int channel;
448         int radiotype;
449
450         pscancfgout = kzalloc(MAX_SCAN_CFG_ALLOC, GFP_KERNEL);
451         if (pscancfgout == NULL)
452                 goto out;
453
454         /* The tlvbufferlen is calculated for each scan command.  The TLVs added
455          *   in this routine will be preserved since the routine that sends
456          *   the command will append channelTLVs at *ppchantlvout.  The difference
457          *   between the *ppchantlvout and the tlvbuffer start will be used
458          *   to calculate the size of anything we add in this routine.
459          */
460         pscancfgout->tlvbufferlen = 0;
461
462         /* Running tlv pointer.  Assigned to ppchantlvout at end of function
463          *  so later routines know where channels can be added to the command buf
464          */
465         ptlvpos = pscancfgout->tlvbuffer;
466
467         /*
468          * Set the initial scan paramters for progressive scanning.  If a specific
469          *   BSSID or SSID is used, the number of channels in the scan command
470          *   will be increased to the absolute maximum
471          */
472         *pmaxchanperscan = MRVDRV_CHANNELS_PER_SCAN_CMD;
473
474         /* Initialize the scan as un-filtered by firmware, set to TRUE below if
475          *   a SSID or BSSID filter is sent in the command
476          */
477         *pfilteredscan = 0;
478
479         /* Initialize the scan as not being only on the current channel.  If
480          *   the channel list is customized, only contains one channel, and
481          *   is the active channel, this is set true and data flow is not halted.
482          */
483         *pscancurrentonly = 0;
484
485         if (puserscanin) {
486
487                 /* Set the bss type scan filter, use adapter setting if unset */
488                 pscancfgout->bsstype =
489                     (puserscanin->bsstype ? puserscanin->bsstype : adapter->
490                      scanmode);
491
492                 /* Set the number of probes to send, use adapter setting if unset */
493                 numprobes = (puserscanin->numprobes ? puserscanin->numprobes :
494                              adapter->scanprobes);
495
496                 /*
497                  * Set the BSSID filter to the incoming configuration,
498                  *   if non-zero.  If not set, it will remain disabled (all zeros).
499                  */
500                 memcpy(pscancfgout->specificBSSID,
501                        puserscanin->specificBSSID,
502                        sizeof(pscancfgout->specificBSSID));
503
504                 ssidlen = strlen(puserscanin->specificSSID);
505
506                 if (ssidlen) {
507                         pssidtlv =
508                             (struct mrvlietypes_ssidparamset *) pscancfgout->
509                             tlvbuffer;
510                         pssidtlv->header.type = cpu_to_le16(TLV_TYPE_SSID);
511                         pssidtlv->header.len = cpu_to_le16(ssidlen);
512                         memcpy(pssidtlv->ssid, puserscanin->specificSSID,
513                                ssidlen);
514                         ptlvpos += sizeof(pssidtlv->header) + ssidlen;
515                 }
516
517                 /*
518                  *  The default number of channels sent in the command is low to
519                  *    ensure the response buffer from the firmware does not truncate
520                  *    scan results.  That is not an issue with an SSID or BSSID
521                  *    filter applied to the scan results in the firmware.
522                  */
523                 if (ssidlen || (memcmp(pscancfgout->specificBSSID,
524                                        &zeromac, sizeof(zeromac)) != 0)) {
525                         *pmaxchanperscan = MRVDRV_MAX_CHANNELS_PER_SCAN;
526                         *pfilteredscan = 1;
527                 }
528         } else {
529                 pscancfgout->bsstype = adapter->scanmode;
530                 numprobes = adapter->scanprobes;
531         }
532
533         /* If the input config or adapter has the number of Probes set, add tlv */
534         if (numprobes) {
535                 pnumprobestlv = (struct mrvlietypes_numprobes *) ptlvpos;
536                 pnumprobestlv->header.type =
537                     cpu_to_le16(TLV_TYPE_NUMPROBES);
538                 pnumprobestlv->header.len = sizeof(pnumprobestlv->numprobes);
539                 pnumprobestlv->numprobes = cpu_to_le16(numprobes);
540
541                 ptlvpos +=
542                     sizeof(pnumprobestlv->header) + pnumprobestlv->header.len;
543
544                 pnumprobestlv->header.len =
545                     cpu_to_le16(pnumprobestlv->header.len);
546         }
547
548         /*
549          * Set the output for the channel TLV to the address in the tlv buffer
550          *   past any TLVs that were added in this fuction (SSID, numprobes).
551          *   channel TLVs will be added past this for each scan command, preserving
552          *   the TLVs that were previously added.
553          */
554         *ppchantlvout = (struct mrvlietypes_chanlistparamset *) ptlvpos;
555
556         if (puserscanin && puserscanin->chanlist[0].channumber) {
557
558                 lbs_pr_debug(1, "Scan: Using supplied channel list\n");
559
560                 for (chanidx = 0;
561                      chanidx < WLAN_IOCTL_USER_SCAN_CHAN_MAX
562                      && puserscanin->chanlist[chanidx].channumber; chanidx++) {
563
564                         channel = puserscanin->chanlist[chanidx].channumber;
565                         (pscanchanlist + chanidx)->channumber = channel;
566
567                         radiotype = puserscanin->chanlist[chanidx].radiotype;
568                         (pscanchanlist + chanidx)->radiotype = radiotype;
569
570                         scantype = puserscanin->chanlist[chanidx].scantype;
571
572                         if (scantype == cmd_scan_type_passive) {
573                                 (pscanchanlist +
574                                  chanidx)->chanscanmode.passivescan = 1;
575                         } else {
576                                 (pscanchanlist +
577                                  chanidx)->chanscanmode.passivescan = 0;
578                         }
579
580                         if (puserscanin->chanlist[chanidx].scantime) {
581                                 scandur =
582                                     puserscanin->chanlist[chanidx].scantime;
583                         } else {
584                                 if (scantype == cmd_scan_type_passive) {
585                                         scandur = MRVDRV_PASSIVE_SCAN_CHAN_TIME;
586                                 } else {
587                                         scandur = MRVDRV_ACTIVE_SCAN_CHAN_TIME;
588                                 }
589                         }
590
591                         (pscanchanlist + chanidx)->minscantime =
592                             cpu_to_le16(scandur);
593                         (pscanchanlist + chanidx)->maxscantime =
594                             cpu_to_le16(scandur);
595                 }
596
597                 /* Check if we are only scanning the current channel */
598                 if ((chanidx == 1) && (puserscanin->chanlist[0].channumber
599                                        ==
600                                        priv->adapter->curbssparams.channel)) {
601                         *pscancurrentonly = 1;
602                         lbs_pr_debug(1, "Scan: Scanning current channel only");
603                 }
604
605         } else {
606                 lbs_pr_debug(1, "Scan: Creating full region channel list\n");
607                 wlan_scan_create_channel_list(priv, pscanchanlist,
608                                               *pfilteredscan);
609         }
610
611 out:
612         return pscancfgout;
613 }
614
615 /**
616  *  @brief Construct and send multiple scan config commands to the firmware
617  *
618  *  Previous routines have created a wlan_scan_cmd_config with any requested
619  *   TLVs.  This function splits the channel TLV into maxchanperscan lists
620  *   and sends the portion of the channel TLV along with the other TLVs
621  *   to the wlan_cmd routines for execution in the firmware.
622  *
623  *  @param priv            A pointer to wlan_private structure
624  *  @param maxchanperscan  Maximum number channels to be included in each
625  *                         scan command sent to firmware
626  *  @param filteredscan    Flag indicating whether or not a BSSID or SSID
627  *                         filter is being used for the firmware command
628  *                         scan command sent to firmware
629  *  @param pscancfgout     Scan configuration used for this scan.
630  *  @param pchantlvout     Pointer in the pscancfgout where the channel TLV
631  *                         should start.  This is past any other TLVs that
632  *                         must be sent down in each firmware command.
633  *  @param pscanchanlist   List of channels to scan in maxchanperscan segments
634  *
635  *  @return                0 or error return otherwise
636  */
637 static int wlan_scan_channel_list(wlan_private * priv,
638                                   int maxchanperscan,
639                                   u8 filteredscan,
640                                   struct wlan_scan_cmd_config * pscancfgout,
641                                   struct mrvlietypes_chanlistparamset * pchantlvout,
642                                   struct chanscanparamset * pscanchanlist)
643 {
644         struct chanscanparamset *ptmpchan;
645         struct chanscanparamset *pstartchan;
646         u8 scanband;
647         int doneearly;
648         int tlvidx;
649         int ret = 0;
650
651         ENTER();
652
653         if (pscancfgout == 0 || pchantlvout == 0 || pscanchanlist == 0) {
654                 lbs_pr_debug(1, "Scan: Null detect: %p, %p, %p\n",
655                        pscancfgout, pchantlvout, pscanchanlist);
656                 return -1;
657         }
658
659         pchantlvout->header.type = cpu_to_le16(TLV_TYPE_CHANLIST);
660
661         /* Set the temp channel struct pointer to the start of the desired list */
662         ptmpchan = pscanchanlist;
663
664         /* Loop through the desired channel list, sending a new firmware scan
665          *   commands for each maxchanperscan channels (or for 1,6,11 individually
666          *   if configured accordingly)
667          */
668         while (ptmpchan->channumber) {
669
670                 tlvidx = 0;
671                 pchantlvout->header.len = 0;
672                 scanband = ptmpchan->radiotype;
673                 pstartchan = ptmpchan;
674                 doneearly = 0;
675
676                 /* Construct the channel TLV for the scan command.  Continue to
677                  *  insert channel TLVs until:
678                  *    - the tlvidx hits the maximum configured per scan command
679                  *    - the next channel to insert is 0 (end of desired channel list)
680                  *    - doneearly is set (controlling individual scanning of 1,6,11)
681                  */
682                 while (tlvidx < maxchanperscan && ptmpchan->channumber
683                        && !doneearly) {
684
685             lbs_pr_debug(1,
686                     "Scan: Chan(%3d), Radio(%d), mode(%d,%d), Dur(%d)\n",
687                 ptmpchan->channumber, ptmpchan->radiotype,
688                 ptmpchan->chanscanmode.passivescan,
689                 ptmpchan->chanscanmode.disablechanfilt,
690                 ptmpchan->maxscantime);
691
692                         /* Copy the current channel TLV to the command being prepared */
693                         memcpy(pchantlvout->chanscanparam + tlvidx,
694                                ptmpchan, sizeof(pchantlvout->chanscanparam));
695
696                         /* Increment the TLV header length by the size appended */
697                         pchantlvout->header.len +=
698                             sizeof(pchantlvout->chanscanparam);
699
700                         /*
701                          *  The tlv buffer length is set to the number of bytes of the
702                          *    between the channel tlv pointer and the start of the
703                          *    tlv buffer.  This compensates for any TLVs that were appended
704                          *    before the channel list.
705                          */
706                         pscancfgout->tlvbufferlen = ((u8 *) pchantlvout
707                                                      - pscancfgout->tlvbuffer);
708
709                         /*  Add the size of the channel tlv header and the data length */
710                         pscancfgout->tlvbufferlen +=
711                             (sizeof(pchantlvout->header)
712                              + pchantlvout->header.len);
713
714                         /* Increment the index to the channel tlv we are constructing */
715                         tlvidx++;
716
717                         doneearly = 0;
718
719                         /* Stop the loop if the *current* channel is in the 1,6,11 set
720                          *   and we are not filtering on a BSSID or SSID.
721                          */
722                         if (!filteredscan && (ptmpchan->channumber == 1
723                                               || ptmpchan->channumber == 6
724                                               || ptmpchan->channumber == 11)) {
725                                 doneearly = 1;
726                         }
727
728                         /* Increment the tmp pointer to the next channel to be scanned */
729                         ptmpchan++;
730
731                         /* Stop the loop if the *next* channel is in the 1,6,11 set.
732                          *  This will cause it to be the only channel scanned on the next
733                          *  interation
734                          */
735                         if (!filteredscan && (ptmpchan->channumber == 1
736                                               || ptmpchan->channumber == 6
737                                               || ptmpchan->channumber == 11)) {
738                                 doneearly = 1;
739                         }
740                 }
741
742                 /* Send the scan command to the firmware with the specified cfg */
743                 ret = libertas_prepare_and_send_command(priv, cmd_802_11_scan, 0,
744                                             0, 0, pscancfgout);
745         }
746
747         LEAVE();
748         return ret;
749 }
750
751 /**
752  *  @brief Internal function used to start a scan based on an input config
753  *
754  *  Use the input user scan configuration information when provided in
755  *    order to send the appropriate scan commands to firmware to populate or
756  *    update the internal driver scan table
757  *
758  *  @param priv          A pointer to wlan_private structure
759  *  @param puserscanin   Pointer to the input configuration for the requested
760  *                       scan.
761  *
762  *  @return              0 or < 0 if error
763  */
764 int wlan_scan_networks(wlan_private * priv,
765                               const struct wlan_ioctl_user_scan_cfg * puserscanin)
766 {
767         wlan_adapter *adapter = priv->adapter;
768         struct mrvlietypes_chanlistparamset *pchantlvout;
769         struct chanscanparamset * scan_chan_list = NULL;
770         struct wlan_scan_cmd_config * scan_cfg = NULL;
771         u8 keeppreviousscan;
772         u8 filteredscan;
773         u8 scancurrentchanonly;
774         int maxchanperscan;
775         int ret;
776
777         ENTER();
778
779         scan_chan_list = kzalloc(sizeof(struct chanscanparamset) *
780                                 WLAN_IOCTL_USER_SCAN_CHAN_MAX, GFP_KERNEL);
781         if (scan_chan_list == NULL) {
782                 ret = -ENOMEM;
783                 goto out;
784         }
785
786         scan_cfg = wlan_scan_setup_scan_config(priv,
787                                                puserscanin,
788                                                &pchantlvout,
789                                                scan_chan_list,
790                                                &maxchanperscan,
791                                                &filteredscan,
792                                                &scancurrentchanonly);
793         if (scan_cfg == NULL) {
794                 ret = -ENOMEM;
795                 goto out;
796         }
797
798         keeppreviousscan = 0;
799
800         if (puserscanin) {
801                 keeppreviousscan = puserscanin->keeppreviousscan;
802         }
803
804         if (!keeppreviousscan) {
805                 memset(adapter->scantable, 0x00,
806                        sizeof(struct bss_descriptor) * MRVDRV_MAX_BSSID_LIST);
807                 adapter->numinscantable = 0;
808         }
809
810         /* Keep the data path active if we are only scanning our current channel */
811         if (!scancurrentchanonly) {
812                 netif_stop_queue(priv->wlan_dev.netdev);
813                 netif_carrier_off(priv->wlan_dev.netdev);
814         }
815
816         ret = wlan_scan_channel_list(priv,
817                                      maxchanperscan,
818                                      filteredscan,
819                                      scan_cfg,
820                                      pchantlvout,
821                                      scan_chan_list);
822
823         /*  Process the resulting scan table:
824          *    - Remove any bad ssids
825          *    - Update our current BSS information from scan data
826          */
827         wlan_scan_process_results(priv);
828
829         if (priv->adapter->connect_status == libertas_connected) {
830                 netif_carrier_on(priv->wlan_dev.netdev);
831                 netif_wake_queue(priv->wlan_dev.netdev);
832         }
833
834 out:
835         if (scan_cfg)
836                 kfree(scan_cfg);
837
838         if (scan_chan_list)
839                 kfree(scan_chan_list);
840
841         LEAVE();
842         return ret;
843 }
844
845 /**
846  *  @brief Inspect the scan response buffer for pointers to expected TLVs
847  *
848  *  TLVs can be included at the end of the scan response BSS information.
849  *    Parse the data in the buffer for pointers to TLVs that can potentially
850  *    be passed back in the response
851  *
852  *  @param ptlv        Pointer to the start of the TLV buffer to parse
853  *  @param tlvbufsize  size of the TLV buffer
854  *  @param ptsftlv     Output parameter: Pointer to the TSF TLV if found
855  *
856  *  @return            void
857  */
858 static
859 void wlan_ret_802_11_scan_get_tlv_ptrs(struct mrvlietypes_data * ptlv,
860                                        int tlvbufsize,
861                                        struct mrvlietypes_tsftimestamp ** ptsftlv)
862 {
863         struct mrvlietypes_data *pcurrenttlv;
864         int tlvbufleft;
865         u16 tlvtype;
866         u16 tlvlen;
867
868         pcurrenttlv = ptlv;
869         tlvbufleft = tlvbufsize;
870         *ptsftlv = NULL;
871
872         lbs_pr_debug(1, "SCAN_RESP: tlvbufsize = %d\n", tlvbufsize);
873         lbs_dbg_hex("SCAN_RESP: TLV Buf", (u8 *) ptlv, tlvbufsize);
874
875         while (tlvbufleft >= sizeof(struct mrvlietypesheader)) {
876                 tlvtype = le16_to_cpu(pcurrenttlv->header.type);
877                 tlvlen = le16_to_cpu(pcurrenttlv->header.len);
878
879                 switch (tlvtype) {
880                 case TLV_TYPE_TSFTIMESTAMP:
881                         *ptsftlv = (struct mrvlietypes_tsftimestamp *) pcurrenttlv;
882                         break;
883
884                 default:
885                         lbs_pr_debug(1, "SCAN_RESP: Unhandled TLV = %d\n",
886                                tlvtype);
887                         /* Give up, this seems corrupted */
888                         return;
889                 }               /* switch */
890
891                 tlvbufleft -= (sizeof(ptlv->header) + tlvlen);
892                 pcurrenttlv =
893                     (struct mrvlietypes_data *) (pcurrenttlv->Data + tlvlen);
894         }                       /* while */
895 }
896
897 /**
898  *  @brief Interpret a BSS scan response returned from the firmware
899  *
900  *  Parse the various fixed fields and IEs passed back for a a BSS probe
901  *   response or beacon from the scan command.  Record information as needed
902  *   in the scan table struct bss_descriptor for that entry.
903  *
904  *  @param pBSSIDEntry  Output parameter: Pointer to the BSS Entry
905  *
906  *  @return             0 or -1
907  */
908 static int InterpretBSSDescriptionWithIE(struct bss_descriptor * pBSSEntry,
909                                          u8 ** pbeaconinfo, int *bytesleft)
910 {
911         enum ieeetypes_elementid elemID;
912         struct ieeetypes_fhparamset *pFH;
913         struct ieeetypes_dsparamset *pDS;
914         struct ieeetypes_cfparamset *pCF;
915         struct ieeetypes_ibssparamset *pibss;
916         struct ieeetypes_capinfo *pcap;
917         struct WLAN_802_11_FIXED_IEs fixedie;
918         u8 *pcurrentptr;
919         u8 *pRate;
920         u8 elemlen;
921         u8 bytestocopy;
922         u8 ratesize;
923         u16 beaconsize;
924         u8 founddatarateie;
925         int bytesleftforcurrentbeacon;
926
927         struct WPA_SUPPLICANT *pwpa_supplicant;
928         struct WPA_SUPPLICANT *pwpa2_supplicant;
929         struct IE_WPA *pIe;
930         const u8 oui01[4] = { 0x00, 0x50, 0xf2, 0x01 };
931
932         struct ieeetypes_countryinfoset *pcountryinfo;
933
934         ENTER();
935
936         founddatarateie = 0;
937         ratesize = 0;
938         beaconsize = 0;
939
940         if (*bytesleft >= sizeof(beaconsize)) {
941                 /* Extract & convert beacon size from the command buffer */
942                 memcpy(&beaconsize, *pbeaconinfo, sizeof(beaconsize));
943                 beaconsize = le16_to_cpu(beaconsize);
944                 *bytesleft -= sizeof(beaconsize);
945                 *pbeaconinfo += sizeof(beaconsize);
946         }
947
948         if (beaconsize == 0 || beaconsize > *bytesleft) {
949
950                 *pbeaconinfo += *bytesleft;
951                 *bytesleft = 0;
952
953                 return -1;
954         }
955
956         /* Initialize the current working beacon pointer for this BSS iteration */
957         pcurrentptr = *pbeaconinfo;
958
959         /* Advance the return beacon pointer past the current beacon */
960         *pbeaconinfo += beaconsize;
961         *bytesleft -= beaconsize;
962
963         bytesleftforcurrentbeacon = beaconsize;
964
965         pwpa_supplicant = &pBSSEntry->wpa_supplicant;
966         pwpa2_supplicant = &pBSSEntry->wpa2_supplicant;
967
968         memcpy(pBSSEntry->macaddress, pcurrentptr, ETH_ALEN);
969         lbs_pr_debug(1, "InterpretIE: AP MAC Addr-%x:%x:%x:%x:%x:%x\n",
970                pBSSEntry->macaddress[0], pBSSEntry->macaddress[1],
971                pBSSEntry->macaddress[2], pBSSEntry->macaddress[3],
972                pBSSEntry->macaddress[4], pBSSEntry->macaddress[5]);
973
974         pcurrentptr += ETH_ALEN;
975         bytesleftforcurrentbeacon -= ETH_ALEN;
976
977         if (bytesleftforcurrentbeacon < 12) {
978                 lbs_pr_debug(1, "InterpretIE: Not enough bytes left\n");
979                 return -1;
980         }
981
982         /*
983          * next 4 fields are RSSI, time stamp, beacon interval,
984          *   and capability information
985          */
986
987         /* RSSI is 1 byte long */
988         pBSSEntry->rssi = le32_to_cpu((long)(*pcurrentptr));
989         lbs_pr_debug(1, "InterpretIE: RSSI=%02X\n", *pcurrentptr);
990         pcurrentptr += 1;
991         bytesleftforcurrentbeacon -= 1;
992
993         /* time stamp is 8 bytes long */
994         memcpy(fixedie.timestamp, pcurrentptr, 8);
995         memcpy(pBSSEntry->timestamp, pcurrentptr, 8);
996         pcurrentptr += 8;
997         bytesleftforcurrentbeacon -= 8;
998
999         /* beacon interval is 2 bytes long */
1000         memcpy(&fixedie.beaconinterval, pcurrentptr, 2);
1001         pBSSEntry->beaconperiod = le16_to_cpu(fixedie.beaconinterval);
1002         pcurrentptr += 2;
1003         bytesleftforcurrentbeacon -= 2;
1004
1005         /* capability information is 2 bytes long */
1006         memcpy(&fixedie.capabilities, pcurrentptr, 2);
1007         lbs_pr_debug(1, "InterpretIE: fixedie.capabilities=0x%X\n",
1008                fixedie.capabilities);
1009         fixedie.capabilities = le16_to_cpu(fixedie.capabilities);
1010         pcap = (struct ieeetypes_capinfo *) & fixedie.capabilities;
1011         memcpy(&pBSSEntry->cap, pcap, sizeof(struct ieeetypes_capinfo));
1012         pcurrentptr += 2;
1013         bytesleftforcurrentbeacon -= 2;
1014
1015         /* rest of the current buffer are IE's */
1016         lbs_pr_debug(1, "InterpretIE: IElength for this AP = %d\n",
1017                bytesleftforcurrentbeacon);
1018
1019         lbs_dbg_hex("InterpretIE: IE info", (u8 *) pcurrentptr,
1020                 bytesleftforcurrentbeacon);
1021
1022         if (pcap->privacy) {
1023                 lbs_pr_debug(1, "InterpretIE: AP WEP enabled\n");
1024                 pBSSEntry->privacy = wlan802_11privfilter8021xWEP;
1025         } else {
1026                 pBSSEntry->privacy = wlan802_11privfilteracceptall;
1027         }
1028
1029         if (pcap->ibss == 1) {
1030                 pBSSEntry->inframode = wlan802_11ibss;
1031         } else {
1032                 pBSSEntry->inframode = wlan802_11infrastructure;
1033         }
1034
1035         /* process variable IE */
1036         while (bytesleftforcurrentbeacon >= 2) {
1037                 elemID = (enum ieeetypes_elementid) (*((u8 *) pcurrentptr));
1038                 elemlen = *((u8 *) pcurrentptr + 1);
1039
1040                 if (bytesleftforcurrentbeacon < elemlen) {
1041                         lbs_pr_debug(1, "InterpretIE: error in processing IE, "
1042                                "bytes left < IE length\n");
1043                         bytesleftforcurrentbeacon = 0;
1044                         continue;
1045                 }
1046
1047                 switch (elemID) {
1048
1049                 case SSID:
1050                         pBSSEntry->ssid.ssidlength = elemlen;
1051                         memcpy(pBSSEntry->ssid.ssid, (pcurrentptr + 2),
1052                                elemlen);
1053                         lbs_pr_debug(1, "ssid: %32s", pBSSEntry->ssid.ssid);
1054                         break;
1055
1056                 case SUPPORTED_RATES:
1057                         memcpy(pBSSEntry->datarates, (pcurrentptr + 2),
1058                                elemlen);
1059                         memmove(pBSSEntry->libertas_supported_rates, (pcurrentptr + 2),
1060                                 elemlen);
1061                         ratesize = elemlen;
1062                         founddatarateie = 1;
1063                         break;
1064
1065                 case EXTRA_IE:
1066                         lbs_pr_debug(1, "InterpretIE: EXTRA_IE Found!\n");
1067                         pBSSEntry->extra_ie = 1;
1068                         break;
1069
1070                 case FH_PARAM_SET:
1071                         pFH = (struct ieeetypes_fhparamset *) pcurrentptr;
1072                         memmove(&pBSSEntry->phyparamset.fhparamset, pFH,
1073                                 sizeof(struct ieeetypes_fhparamset));
1074                         pBSSEntry->phyparamset.fhparamset.dwelltime
1075                             =
1076                             le16_to_cpu(pBSSEntry->phyparamset.fhparamset.
1077                                              dwelltime);
1078                         break;
1079
1080                 case DS_PARAM_SET:
1081                         pDS = (struct ieeetypes_dsparamset *) pcurrentptr;
1082
1083                         pBSSEntry->channel = pDS->currentchan;
1084
1085                         memcpy(&pBSSEntry->phyparamset.dsparamset, pDS,
1086                                sizeof(struct ieeetypes_dsparamset));
1087                         break;
1088
1089                 case CF_PARAM_SET:
1090                         pCF = (struct ieeetypes_cfparamset *) pcurrentptr;
1091
1092                         memcpy(&pBSSEntry->ssparamset.cfparamset, pCF,
1093                                sizeof(struct ieeetypes_cfparamset));
1094                         break;
1095
1096                 case IBSS_PARAM_SET:
1097                         pibss = (struct ieeetypes_ibssparamset *) pcurrentptr;
1098                         pBSSEntry->atimwindow =
1099                             le32_to_cpu(pibss->atimwindow);
1100
1101                         memmove(&pBSSEntry->ssparamset.ibssparamset, pibss,
1102                                 sizeof(struct ieeetypes_ibssparamset));
1103
1104                         pBSSEntry->ssparamset.ibssparamset.atimwindow
1105                             =
1106                             le16_to_cpu(pBSSEntry->ssparamset.ibssparamset.
1107                                              atimwindow);
1108                         break;
1109
1110                         /* Handle Country Info IE */
1111                 case COUNTRY_INFO:
1112                         pcountryinfo =
1113                             (struct ieeetypes_countryinfoset *) pcurrentptr;
1114
1115                         if (pcountryinfo->len <
1116                             sizeof(pcountryinfo->countrycode)
1117                             || pcountryinfo->len > 254) {
1118                                 lbs_pr_debug(1, "InterpretIE: 11D- Err "
1119                                        "CountryInfo len =%d min=%d max=254\n",
1120                                        pcountryinfo->len,
1121                                        sizeof(pcountryinfo->countrycode));
1122                                 LEAVE();
1123                                 return -1;
1124                         }
1125
1126                         memcpy(&pBSSEntry->countryinfo,
1127                                pcountryinfo, pcountryinfo->len + 2);
1128                         lbs_dbg_hex("InterpretIE: 11D- CountryInfo:",
1129                                 (u8 *) pcountryinfo,
1130                                 (u32) (pcountryinfo->len + 2));
1131                         break;
1132
1133                 case EXTENDED_SUPPORTED_RATES:
1134                         /*
1135                          * only process extended supported rate
1136                          * if data rate is already found.
1137                          * data rate IE should come before
1138                          * extended supported rate IE
1139                          */
1140                         if (founddatarateie) {
1141                                 if ((elemlen + ratesize) > WLAN_SUPPORTED_RATES) {
1142                                         bytestocopy =
1143                                             (WLAN_SUPPORTED_RATES - ratesize);
1144                                 } else {
1145                                         bytestocopy = elemlen;
1146                                 }
1147
1148                                 pRate = (u8 *) pBSSEntry->datarates;
1149                                 pRate += ratesize;
1150                                 memmove(pRate, (pcurrentptr + 2), bytestocopy);
1151
1152                                 pRate = (u8 *) pBSSEntry->libertas_supported_rates;
1153
1154                                 pRate += ratesize;
1155                                 memmove(pRate, (pcurrentptr + 2), bytestocopy);
1156                         }
1157                         break;
1158
1159                 case VENDOR_SPECIFIC_221:
1160 #define IE_ID_LEN_FIELDS_BYTES 2
1161                         pIe = (struct IE_WPA *)pcurrentptr;
1162
1163                         if (!memcmp(pIe->oui, oui01, sizeof(oui01))) {
1164                                 pwpa_supplicant->wpa_ie_len
1165                                     = min_t(size_t, elemlen + IE_ID_LEN_FIELDS_BYTES,
1166                                           sizeof(pwpa_supplicant->wpa_ie));
1167                                 memcpy(pwpa_supplicant->wpa_ie,
1168                                        pcurrentptr,
1169                                        pwpa_supplicant->wpa_ie_len);
1170                                 lbs_dbg_hex("InterpretIE: Resp WPA_IE",
1171                                         pwpa_supplicant->wpa_ie, elemlen);
1172                         }
1173                         break;
1174                 case WPA2_IE:
1175                         pIe = (struct IE_WPA *)pcurrentptr;
1176                         pwpa2_supplicant->wpa_ie_len
1177                             = min_t(size_t, elemlen + IE_ID_LEN_FIELDS_BYTES,
1178                                   sizeof(pwpa2_supplicant->wpa_ie));
1179                         memcpy(pwpa2_supplicant->wpa_ie,
1180                                pcurrentptr, pwpa2_supplicant->wpa_ie_len);
1181
1182                         lbs_dbg_hex("InterpretIE: Resp WPA2_IE",
1183                                 pwpa2_supplicant->wpa_ie, elemlen);
1184                         break;
1185                 case TIM:
1186                         break;
1187
1188                 case CHALLENGE_TEXT:
1189                         break;
1190                 }
1191
1192                 pcurrentptr += elemlen + 2;
1193
1194                 /* need to account for IE ID and IE len */
1195                 bytesleftforcurrentbeacon -= (elemlen + 2);
1196
1197         }                       /* while (bytesleftforcurrentbeacon > 2) */
1198
1199         return 0;
1200 }
1201
1202 /**
1203  *  @brief Compare two SSIDs
1204  *
1205  *  @param ssid1    A pointer to ssid to compare
1206  *  @param ssid2    A pointer to ssid to compare
1207  *
1208  *  @return         0--ssid is same, otherwise is different
1209  */
1210 int libertas_SSID_cmp(struct WLAN_802_11_SSID *ssid1, struct WLAN_802_11_SSID *ssid2)
1211 {
1212         if (!ssid1 || !ssid2)
1213                 return -1;
1214
1215         if (ssid1->ssidlength != ssid2->ssidlength)
1216                 return -1;
1217
1218         return memcmp(ssid1->ssid, ssid2->ssid, ssid1->ssidlength);
1219 }
1220
1221 /**
1222  *  @brief This function finds a specific compatible BSSID in the scan list
1223  *
1224  *  @param adapter  A pointer to wlan_adapter
1225  *  @param bssid    BSSID to find in the scan list
1226  *  @param mode     Network mode: Infrastructure or IBSS
1227  *
1228  *  @return         index in BSSID list, or error return code (< 0)
1229  */
1230 int libertas_find_BSSID_in_list(wlan_adapter * adapter, u8 * bssid, int mode)
1231 {
1232         int ret = -ENETUNREACH;
1233         int i;
1234
1235         if (!bssid)
1236                 return -EFAULT;
1237
1238         lbs_pr_debug(1, "FindBSSID: Num of BSSIDs = %d\n",
1239                adapter->numinscantable);
1240
1241         /* Look through the scan table for a compatible match. The ret return
1242          *   variable will be equal to the index in the scan table (greater
1243          *   than zero) if the network is compatible.  The loop will continue
1244          *   past a matched bssid that is not compatible in case there is an
1245          *   AP with multiple SSIDs assigned to the same BSSID
1246          */
1247         for (i = 0; ret < 0 && i < adapter->numinscantable; i++) {
1248                 if (!memcmp(adapter->scantable[i].macaddress, bssid, ETH_ALEN)) {
1249                         switch (mode) {
1250                         case wlan802_11infrastructure:
1251                         case wlan802_11ibss:
1252                                 ret = is_network_compatible(adapter, i, mode);
1253                                 break;
1254                         default:
1255                                 ret = i;
1256                                 break;
1257                         }
1258                 }
1259         }
1260
1261         return ret;
1262 }
1263
1264 /**
1265  *  @brief This function finds ssid in ssid list.
1266  *
1267  *  @param adapter  A pointer to wlan_adapter
1268  *  @param ssid     SSID to find in the list
1269  *  @param bssid    BSSID to qualify the SSID selection (if provided)
1270  *  @param mode     Network mode: Infrastructure or IBSS
1271  *
1272  *  @return         index in BSSID list
1273  */
1274 int libertas_find_SSID_in_list(wlan_adapter * adapter,
1275                    struct WLAN_802_11_SSID *ssid, u8 * bssid, int mode)
1276 {
1277         int net = -ENETUNREACH;
1278         u8 bestrssi = 0;
1279         int i;
1280         int j;
1281
1282         lbs_pr_debug(1, "Num of Entries in Table = %d\n", adapter->numinscantable);
1283
1284         for (i = 0; i < adapter->numinscantable; i++) {
1285                 if (!libertas_SSID_cmp(&adapter->scantable[i].ssid, ssid) &&
1286                     (!bssid ||
1287                      !memcmp(adapter->scantable[i].
1288                              macaddress, bssid, ETH_ALEN))) {
1289                         switch (mode) {
1290                         case wlan802_11infrastructure:
1291                         case wlan802_11ibss:
1292                                 j = is_network_compatible(adapter, i, mode);
1293
1294                                 if (j >= 0) {
1295                                         if (bssid) {
1296                                                 return i;
1297                                         }
1298
1299                                         if (SCAN_RSSI
1300                                             (adapter->scantable[i].rssi)
1301                                             > bestrssi) {
1302                                                 bestrssi =
1303                                                     SCAN_RSSI(adapter->
1304                                                               scantable[i].
1305                                                               rssi);
1306                                                 net = i;
1307                                         }
1308                                 } else {
1309                                         if (net == -ENETUNREACH) {
1310                                                 net = j;
1311                                         }
1312                                 }
1313                                 break;
1314                         case wlan802_11autounknown:
1315                         default:
1316                                 if (SCAN_RSSI(adapter->scantable[i].rssi)
1317                                     > bestrssi) {
1318                                         bestrssi =
1319                                             SCAN_RSSI(adapter->scantable[i].
1320                                                       rssi);
1321                                         net = i;
1322                                 }
1323                                 break;
1324                         }
1325                 }
1326         }
1327
1328         return net;
1329 }
1330
1331 /**
1332  *  @brief This function finds the best SSID in the Scan List
1333  *
1334  *  Search the scan table for the best SSID that also matches the current
1335  *   adapter network preference (infrastructure or adhoc)
1336  *
1337  *  @param adapter  A pointer to wlan_adapter
1338  *
1339  *  @return         index in BSSID list
1340  */
1341 int libertas_find_best_SSID_in_list(wlan_adapter * adapter,
1342                                     enum WLAN_802_11_NETWORK_INFRASTRUCTURE mode)
1343 {
1344         int bestnet = -ENETUNREACH;
1345         u8 bestrssi = 0;
1346         int i;
1347
1348         ENTER();
1349
1350         lbs_pr_debug(1, "Num of BSSIDs = %d\n", adapter->numinscantable);
1351
1352         for (i = 0; i < adapter->numinscantable; i++) {
1353                 switch (mode) {
1354                 case wlan802_11infrastructure:
1355                 case wlan802_11ibss:
1356                         if (is_network_compatible(adapter, i, mode) >= 0) {
1357                                 if (SCAN_RSSI(adapter->scantable[i].rssi) >
1358                                     bestrssi) {
1359                                         bestrssi =
1360                                             SCAN_RSSI(adapter->scantable[i].
1361                                                       rssi);
1362                                         bestnet = i;
1363                                 }
1364                         }
1365                         break;
1366                 case wlan802_11autounknown:
1367                 default:
1368                         if (SCAN_RSSI(adapter->scantable[i].rssi) > bestrssi) {
1369                                 bestrssi =
1370                                     SCAN_RSSI(adapter->scantable[i].rssi);
1371                                 bestnet = i;
1372                         }
1373                         break;
1374                 }
1375         }
1376
1377         LEAVE();
1378         return bestnet;
1379 }
1380
1381 /**
1382  *  @brief Find the AP with specific ssid in the scan list
1383  *
1384  *  @param priv         A pointer to wlan_private structure
1385  *  @param pSSID        A pointer to AP's ssid
1386  *
1387  *  @return             0--success, otherwise--fail
1388  */
1389 int libertas_find_best_network_SSID(wlan_private * priv,
1390                                     struct WLAN_802_11_SSID *pSSID,
1391                                     enum WLAN_802_11_NETWORK_INFRASTRUCTURE preferred_mode,
1392                                     enum WLAN_802_11_NETWORK_INFRASTRUCTURE *out_mode)
1393 {
1394         wlan_adapter *adapter = priv->adapter;
1395         int ret = 0;
1396         struct bss_descriptor *preqbssid;
1397         int i;
1398
1399         ENTER();
1400
1401         memset(pSSID, 0, sizeof(struct WLAN_802_11_SSID));
1402
1403         wlan_scan_networks(priv, NULL);
1404         if (adapter->surpriseremoved)
1405                 return -1;
1406         wait_event_interruptible(adapter->cmd_pending, !adapter->nr_cmd_pending);
1407
1408         i = libertas_find_best_SSID_in_list(adapter, preferred_mode);
1409         if (i < 0) {
1410                 ret = -1;
1411                 goto out;
1412         }
1413
1414         preqbssid = &adapter->scantable[i];
1415         memcpy(pSSID, &preqbssid->ssid,
1416                sizeof(struct WLAN_802_11_SSID));
1417         *out_mode = preqbssid->inframode;
1418
1419         if (!pSSID->ssidlength) {
1420                 ret = -1;
1421         }
1422
1423 out:
1424         LEAVE();
1425         return ret;
1426 }
1427
1428 /**
1429  *  @brief Scan Network
1430  *
1431  *  @param dev          A pointer to net_device structure
1432  *  @param info         A pointer to iw_request_info structure
1433  *  @param vwrq         A pointer to iw_param structure
1434  *  @param extra        A pointer to extra data buf
1435  *
1436  *  @return             0 --success, otherwise fail
1437  */
1438 int libertas_set_scan(struct net_device *dev, struct iw_request_info *info,
1439                   struct iw_param *vwrq, char *extra)
1440 {
1441         wlan_private *priv = dev->priv;
1442         wlan_adapter *adapter = priv->adapter;
1443         union iwreq_data wrqu;
1444
1445         ENTER();
1446
1447         if (!wlan_scan_networks(priv, NULL)) {
1448                 memset(&wrqu, 0, sizeof(union iwreq_data));
1449                 wireless_send_event(priv->wlan_dev.netdev, SIOCGIWSCAN, &wrqu,
1450                                     NULL);
1451         }
1452
1453         if (adapter->surpriseremoved)
1454                 return -1;
1455
1456         LEAVE();
1457         return 0;
1458 }
1459
1460 /**
1461  *  @brief Send a scan command for all available channels filtered on a spec
1462  *
1463  *  @param priv             A pointer to wlan_private structure
1464  *  @param prequestedssid   A pointer to AP's ssid
1465  *  @param keeppreviousscan Flag used to save/clear scan table before scan
1466  *
1467  *  @return                0-success, otherwise fail
1468  */
1469 int libertas_send_specific_SSID_scan(wlan_private * priv,
1470                          struct WLAN_802_11_SSID *prequestedssid,
1471                          u8 keeppreviousscan)
1472 {
1473         wlan_adapter *adapter = priv->adapter;
1474         struct wlan_ioctl_user_scan_cfg scancfg;
1475
1476         ENTER();
1477
1478         if (prequestedssid == NULL) {
1479                 return -1;
1480         }
1481
1482         memset(&scancfg, 0x00, sizeof(scancfg));
1483
1484         memcpy(scancfg.specificSSID, prequestedssid->ssid,
1485                prequestedssid->ssidlength);
1486         scancfg.keeppreviousscan = keeppreviousscan;
1487
1488         wlan_scan_networks(priv, &scancfg);
1489         if (adapter->surpriseremoved)
1490                 return -1;
1491         wait_event_interruptible(adapter->cmd_pending, !adapter->nr_cmd_pending);
1492
1493         LEAVE();
1494         return 0;
1495 }
1496
1497 /**
1498  *  @brief scan an AP with specific BSSID
1499  *
1500  *  @param priv             A pointer to wlan_private structure
1501  *  @param bssid            A pointer to AP's bssid
1502  *  @param keeppreviousscan Flag used to save/clear scan table before scan
1503  *
1504  *  @return          0-success, otherwise fail
1505  */
1506 int libertas_send_specific_BSSID_scan(wlan_private * priv, u8 * bssid, u8 keeppreviousscan)
1507 {
1508         struct wlan_ioctl_user_scan_cfg scancfg;
1509
1510         ENTER();
1511
1512         if (bssid == NULL) {
1513                 return -1;
1514         }
1515
1516         memset(&scancfg, 0x00, sizeof(scancfg));
1517         memcpy(scancfg.specificBSSID, bssid, sizeof(scancfg.specificBSSID));
1518         scancfg.keeppreviousscan = keeppreviousscan;
1519
1520         wlan_scan_networks(priv, &scancfg);
1521         if (priv->adapter->surpriseremoved)
1522                 return -1;
1523         wait_event_interruptible(priv->adapter->cmd_pending,
1524                 !priv->adapter->nr_cmd_pending);
1525
1526         LEAVE();
1527         return 0;
1528 }
1529
1530 /**
1531  *  @brief  Retrieve the scan table entries via wireless tools IOCTL call
1532  *
1533  *  @param dev          A pointer to net_device structure
1534  *  @param info         A pointer to iw_request_info structure
1535  *  @param dwrq         A pointer to iw_point structure
1536  *  @param extra        A pointer to extra data buf
1537  *
1538  *  @return             0 --success, otherwise fail
1539  */
1540 int libertas_get_scan(struct net_device *dev, struct iw_request_info *info,
1541                   struct iw_point *dwrq, char *extra)
1542 {
1543         wlan_private *priv = dev->priv;
1544         wlan_adapter *adapter = priv->adapter;
1545         int ret = 0;
1546         char *current_ev = extra;
1547         char *end_buf = extra + IW_SCAN_MAX_DATA;
1548         struct chan_freq_power *cfp;
1549         struct bss_descriptor *pscantable;
1550         char *current_val;      /* For rates */
1551         struct iw_event iwe;    /* Temporary buffer */
1552         int i;
1553         int j;
1554         int rate;
1555 #define PERFECT_RSSI ((u8)50)
1556 #define WORST_RSSI   ((u8)0)
1557 #define RSSI_DIFF    ((u8)(PERFECT_RSSI - WORST_RSSI))
1558         u8 rssi;
1559
1560         u8 buf[16 + 256 * 2];
1561         u8 *ptr;
1562
1563         ENTER();
1564
1565         /*
1566          * if there's either commands in the queue or one being
1567          * processed return -EAGAIN for iwlist to retry later.
1568          */
1569     if (adapter->nr_cmd_pending)
1570                 return -EAGAIN;
1571
1572         if (adapter->connect_status == libertas_connected)
1573                 lbs_pr_debug(1, "Current ssid: %32s\n",
1574                        adapter->curbssparams.ssid.ssid);
1575
1576         lbs_pr_debug(1, "Scan: Get: numinscantable = %d\n",
1577                adapter->numinscantable);
1578
1579         /* The old API using SIOCGIWAPLIST had a hard limit of IW_MAX_AP.
1580          * The new API using SIOCGIWSCAN is only limited by buffer size
1581          * WE-14 -> WE-16 the buffer is limited to IW_SCAN_MAX_DATA bytes
1582          * which is 4096.
1583          */
1584         for (i = 0; i < adapter->numinscantable; i++) {
1585                 if ((current_ev + MAX_SCAN_CELL_SIZE) >= end_buf) {
1586                         lbs_pr_debug(1, "i=%d break out: current_ev=%p end_buf=%p "
1587                                "MAX_SCAN_CELL_SIZE=%d\n",
1588                                i, current_ev, end_buf, MAX_SCAN_CELL_SIZE);
1589                         break;
1590                 }
1591
1592                 pscantable = &adapter->scantable[i];
1593
1594                 lbs_pr_debug(1, "i=%d  ssid: %32s\n", i, pscantable->ssid.ssid);
1595
1596                 cfp =
1597                     libertas_find_cfp_by_band_and_channel(adapter, 0,
1598                                                  pscantable->channel);
1599                 if (!cfp) {
1600                         lbs_pr_debug(1, "Invalid channel number %d\n",
1601                                pscantable->channel);
1602                         continue;
1603                 }
1604
1605                 if (!ssid_valid(&adapter->scantable[i].ssid)) {
1606                         continue;
1607                 }
1608
1609                 /* First entry *MUST* be the AP MAC address */
1610                 iwe.cmd = SIOCGIWAP;
1611                 iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
1612                 memcpy(iwe.u.ap_addr.sa_data,
1613                        &adapter->scantable[i].macaddress, ETH_ALEN);
1614
1615                 iwe.len = IW_EV_ADDR_LEN;
1616                 current_ev =
1617                     iwe_stream_add_event(current_ev, end_buf, &iwe, iwe.len);
1618
1619                 //Add the ESSID
1620                 iwe.u.data.length = adapter->scantable[i].ssid.ssidlength;
1621
1622                 if (iwe.u.data.length > 32) {
1623                         iwe.u.data.length = 32;
1624                 }
1625
1626                 iwe.cmd = SIOCGIWESSID;
1627                 iwe.u.data.flags = 1;
1628                 iwe.len = IW_EV_POINT_LEN + iwe.u.data.length;
1629                 current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe,
1630                                                   adapter->scantable[i].ssid.
1631                                                   ssid);
1632
1633                 //Add mode
1634                 iwe.cmd = SIOCGIWMODE;
1635                 iwe.u.mode = adapter->scantable[i].inframode + 1;
1636                 iwe.len = IW_EV_UINT_LEN;
1637                 current_ev =
1638                     iwe_stream_add_event(current_ev, end_buf, &iwe, iwe.len);
1639
1640                 //frequency
1641                 iwe.cmd = SIOCGIWFREQ;
1642                 iwe.u.freq.m = (long)cfp->freq * 100000;
1643                 iwe.u.freq.e = 1;
1644                 iwe.len = IW_EV_FREQ_LEN;
1645                 current_ev =
1646                     iwe_stream_add_event(current_ev, end_buf, &iwe, iwe.len);
1647
1648                 /* Add quality statistics */
1649                 iwe.cmd = IWEVQUAL;
1650                 iwe.u.qual.updated = IW_QUAL_ALL_UPDATED;
1651                 iwe.u.qual.level = SCAN_RSSI(adapter->scantable[i].rssi);
1652
1653                 rssi = iwe.u.qual.level - MRVDRV_NF_DEFAULT_SCAN_VALUE;
1654                 iwe.u.qual.qual =
1655                     (100 * RSSI_DIFF * RSSI_DIFF - (PERFECT_RSSI - rssi) *
1656                      (15 * (RSSI_DIFF) + 62 * (PERFECT_RSSI - rssi))) /
1657                     (RSSI_DIFF * RSSI_DIFF);
1658                 if (iwe.u.qual.qual > 100)
1659                         iwe.u.qual.qual = 100;
1660                 else if (iwe.u.qual.qual < 1)
1661                         iwe.u.qual.qual = 0;
1662
1663                 if (adapter->NF[TYPE_BEACON][TYPE_NOAVG] == 0) {
1664                         iwe.u.qual.noise = MRVDRV_NF_DEFAULT_SCAN_VALUE;
1665                 } else {
1666                         iwe.u.qual.noise =
1667                             CAL_NF(adapter->NF[TYPE_BEACON][TYPE_NOAVG]);
1668                 }
1669                 if ((adapter->inframode == wlan802_11ibss) &&
1670                     !libertas_SSID_cmp(&adapter->curbssparams.ssid,
1671                              &adapter->scantable[i].ssid)
1672                     && adapter->adhoccreate) {
1673                         ret = libertas_prepare_and_send_command(priv,
1674                                                     cmd_802_11_rssi,
1675                                                     0,
1676                                                     cmd_option_waitforrsp,
1677                                                     0, NULL);
1678
1679                         if (!ret) {
1680                                 iwe.u.qual.level =
1681                                     CAL_RSSI(adapter->SNR[TYPE_RXPD][TYPE_AVG] /
1682                                              AVG_SCALE,
1683                                              adapter->NF[TYPE_RXPD][TYPE_AVG] /
1684                                              AVG_SCALE);
1685                         }
1686                 }
1687                 iwe.len = IW_EV_QUAL_LEN;
1688                 current_ev =
1689                     iwe_stream_add_event(current_ev, end_buf, &iwe, iwe.len);
1690
1691                 /* Add encryption capability */
1692                 iwe.cmd = SIOCGIWENCODE;
1693                 if (adapter->scantable[i].privacy) {
1694                         iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
1695                 } else {
1696                         iwe.u.data.flags = IW_ENCODE_DISABLED;
1697                 }
1698                 iwe.u.data.length = 0;
1699                 iwe.len = IW_EV_POINT_LEN + iwe.u.data.length;
1700                 current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe,
1701                                                   adapter->scantable->ssid.
1702                                                   ssid);
1703
1704                 current_val = current_ev + IW_EV_LCP_LEN;
1705
1706                 iwe.cmd = SIOCGIWRATE;
1707
1708                 iwe.u.bitrate.fixed = 0;
1709                 iwe.u.bitrate.disabled = 0;
1710                 iwe.u.bitrate.value = 0;
1711
1712                 /* Bit rate given in 500 kb/s units (+ 0x80) */
1713                 for (j = 0; j < sizeof(adapter->scantable[i].libertas_supported_rates);
1714                      j++) {
1715                         if (adapter->scantable[i].libertas_supported_rates[j] == 0) {
1716                                 break;
1717                         }
1718                         rate =
1719                             (adapter->scantable[i].libertas_supported_rates[j] & 0x7F) *
1720                             500000;
1721                         if (rate > iwe.u.bitrate.value) {
1722                                 iwe.u.bitrate.value = rate;
1723                         }
1724
1725                         iwe.u.bitrate.value =
1726                             (adapter->scantable[i].libertas_supported_rates[j]
1727                              & 0x7f) * 500000;
1728                         iwe.len = IW_EV_PARAM_LEN;
1729                         current_ev =
1730                             iwe_stream_add_value(current_ev, current_val,
1731                                                  end_buf, &iwe, iwe.len);
1732
1733                 }
1734                 if ((adapter->scantable[i].inframode == wlan802_11ibss)
1735                     && !libertas_SSID_cmp(&adapter->curbssparams.ssid,
1736                                 &adapter->scantable[i].ssid)
1737                     && adapter->adhoccreate) {
1738                         iwe.u.bitrate.value = 22 * 500000;
1739                 }
1740                 iwe.len = IW_EV_PARAM_LEN;
1741                 current_ev =
1742                     iwe_stream_add_value(current_ev, current_val, end_buf, &iwe,
1743                                          iwe.len);
1744
1745                 /* Add new value to event */
1746                 current_val = current_ev + IW_EV_LCP_LEN;
1747
1748                 if (adapter->scantable[i].wpa2_supplicant.wpa_ie[0] == WPA2_IE) {
1749                         memset(&iwe, 0, sizeof(iwe));
1750                         memset(buf, 0, sizeof(buf));
1751                         memcpy(buf, adapter->scantable[i].
1752                                                 wpa2_supplicant.wpa_ie,
1753                                         adapter->scantable[i].wpa2_supplicant.
1754                                                 wpa_ie_len);
1755                         iwe.cmd = IWEVGENIE;
1756                         iwe.u.data.length = adapter->scantable[i].
1757                                         wpa2_supplicant.wpa_ie_len;
1758                         iwe.len = IW_EV_POINT_LEN + iwe.u.data.length;
1759                         current_ev = iwe_stream_add_point(current_ev, end_buf,
1760                                         &iwe, buf);
1761                 }
1762                 if (adapter->scantable[i].wpa_supplicant.wpa_ie[0] == WPA_IE) {
1763                         memset(&iwe, 0, sizeof(iwe));
1764                         memset(buf, 0, sizeof(buf));
1765                         memcpy(buf, adapter->scantable[i].
1766                                                 wpa_supplicant.wpa_ie,
1767                                         adapter->scantable[i].wpa_supplicant.
1768                                                 wpa_ie_len);
1769                         iwe.cmd = IWEVGENIE;
1770                         iwe.u.data.length = adapter->scantable[i].
1771                                         wpa_supplicant.wpa_ie_len;
1772                         iwe.len = IW_EV_POINT_LEN + iwe.u.data.length;
1773                         current_ev = iwe_stream_add_point(current_ev, end_buf,
1774                                         &iwe, buf);
1775                 }
1776
1777
1778                 if (adapter->scantable[i].extra_ie != 0) {
1779                         memset(&iwe, 0, sizeof(iwe));
1780                         memset(buf, 0, sizeof(buf));
1781                         ptr = buf;
1782                         ptr += sprintf(ptr, "extra_ie");
1783                         iwe.u.data.length = strlen(buf);
1784
1785                         lbs_pr_debug(1, "iwe.u.data.length %d\n",
1786                                iwe.u.data.length);
1787                         lbs_pr_debug(1, "BUF: %s \n", buf);
1788
1789                         iwe.cmd = IWEVCUSTOM;
1790                         iwe.len = IW_EV_POINT_LEN + iwe.u.data.length;
1791                         current_ev =
1792                             iwe_stream_add_point(current_ev, end_buf, &iwe,
1793                                                  buf);
1794                 }
1795
1796                 current_val = current_ev + IW_EV_LCP_LEN;
1797
1798                 /*
1799                  * Check if we added any event
1800                  */
1801                 if ((current_val - current_ev) > IW_EV_LCP_LEN)
1802                         current_ev = current_val;
1803         }
1804
1805         dwrq->length = (current_ev - extra);
1806         dwrq->flags = 0;
1807
1808         LEAVE();
1809         return 0;
1810 }
1811
1812 /**
1813  *  @brief Prepare a scan command to be sent to the firmware
1814  *
1815  *  Use the wlan_scan_cmd_config sent to the command processing module in
1816  *   the libertas_prepare_and_send_command to configure a cmd_ds_802_11_scan command
1817  *   struct to send to firmware.
1818  *
1819  *  The fixed fields specifying the BSS type and BSSID filters as well as a
1820  *   variable number/length of TLVs are sent in the command to firmware.
1821  *
1822  *  @param priv       A pointer to wlan_private structure
1823  *  @param cmd        A pointer to cmd_ds_command structure to be sent to
1824  *                    firmware with the cmd_DS_801_11_SCAN structure
1825  *  @param pdata_buf  Void pointer cast of a wlan_scan_cmd_config struct used
1826  *                    to set the fields/TLVs for the command sent to firmware
1827  *
1828  *  @return           0 or -1
1829  *
1830  *  @sa wlan_scan_create_channel_list
1831  */
1832 int libertas_cmd_80211_scan(wlan_private * priv,
1833                          struct cmd_ds_command *cmd, void *pdata_buf)
1834 {
1835         struct cmd_ds_802_11_scan *pscan = &cmd->params.scan;
1836         struct wlan_scan_cmd_config *pscancfg;
1837
1838         ENTER();
1839
1840         pscancfg = pdata_buf;
1841
1842         /* Set fixed field variables in scan command */
1843         pscan->bsstype = pscancfg->bsstype;
1844         memcpy(pscan->BSSID, pscancfg->specificBSSID, sizeof(pscan->BSSID));
1845         memcpy(pscan->tlvbuffer, pscancfg->tlvbuffer, pscancfg->tlvbufferlen);
1846
1847         cmd->command = cpu_to_le16(cmd_802_11_scan);
1848
1849         /* size is equal to the sizeof(fixed portions) + the TLV len + header */
1850         cmd->size = cpu_to_le16(sizeof(pscan->bsstype)
1851                                      + sizeof(pscan->BSSID)
1852                                      + pscancfg->tlvbufferlen + S_DS_GEN);
1853
1854         lbs_pr_debug(1, "SCAN_CMD: command=%x, size=%x, seqnum=%x\n",
1855                cmd->command, cmd->size, cmd->seqnum);
1856         LEAVE();
1857         return 0;
1858 }
1859
1860 /**
1861  *  @brief This function handles the command response of scan
1862  *
1863  *   The response buffer for the scan command has the following
1864  *      memory layout:
1865  *
1866  *     .-----------------------------------------------------------.
1867  *     |  header (4 * sizeof(u16)):  Standard command response hdr |
1868  *     .-----------------------------------------------------------.
1869  *     |  bufsize (u16) : sizeof the BSS Description data          |
1870  *     .-----------------------------------------------------------.
1871  *     |  NumOfSet (u8) : Number of BSS Descs returned             |
1872  *     .-----------------------------------------------------------.
1873  *     |  BSSDescription data (variable, size given in bufsize)    |
1874  *     .-----------------------------------------------------------.
1875  *     |  TLV data (variable, size calculated using header->size,  |
1876  *     |            bufsize and sizeof the fixed fields above)     |
1877  *     .-----------------------------------------------------------.
1878  *
1879  *  @param priv    A pointer to wlan_private structure
1880  *  @param resp    A pointer to cmd_ds_command
1881  *
1882  *  @return        0 or -1
1883  */
1884 int libertas_ret_80211_scan(wlan_private * priv, struct cmd_ds_command *resp)
1885 {
1886         wlan_adapter *adapter = priv->adapter;
1887         struct cmd_ds_802_11_scan_rsp *pscan;
1888         struct bss_descriptor newbssentry;
1889         struct mrvlietypes_data *ptlv;
1890         struct mrvlietypes_tsftimestamp *ptsftlv;
1891         u8 *pbssinfo;
1892         u16 scanrespsize;
1893         int bytesleft;
1894         int numintable;
1895         int bssIdx;
1896         int idx;
1897         int tlvbufsize;
1898         u64 tsfval;
1899
1900         ENTER();
1901
1902         pscan = &resp->params.scanresp;
1903
1904         if (pscan->nr_sets > MRVDRV_MAX_BSSID_LIST) {
1905         lbs_pr_debug(1,
1906                        "SCAN_RESP: Invalid number of AP returned (%d)!!\n",
1907                        pscan->nr_sets);
1908                 LEAVE();
1909                 return -1;
1910         }
1911
1912         bytesleft = le16_to_cpu(pscan->bssdescriptsize);
1913         lbs_pr_debug(1, "SCAN_RESP: bssdescriptsize %d\n", bytesleft);
1914
1915         scanrespsize = le16_to_cpu(resp->size);
1916         lbs_pr_debug(1, "SCAN_RESP: returned %d AP before parsing\n",
1917                pscan->nr_sets);
1918
1919         numintable = adapter->numinscantable;
1920         pbssinfo = pscan->bssdesc_and_tlvbuffer;
1921
1922         /* The size of the TLV buffer is equal to the entire command response
1923          *   size (scanrespsize) minus the fixed fields (sizeof()'s), the
1924          *   BSS Descriptions (bssdescriptsize as bytesLef) and the command
1925          *   response header (S_DS_GEN)
1926          */
1927         tlvbufsize = scanrespsize - (bytesleft + sizeof(pscan->bssdescriptsize)
1928                                      + sizeof(pscan->nr_sets)
1929                                      + S_DS_GEN);
1930
1931         ptlv = (struct mrvlietypes_data *) (pscan->bssdesc_and_tlvbuffer + bytesleft);
1932
1933         /* Search the TLV buffer space in the scan response for any valid TLVs */
1934         wlan_ret_802_11_scan_get_tlv_ptrs(ptlv, tlvbufsize, &ptsftlv);
1935
1936         /*
1937          *  Process each scan response returned (pscan->nr_sets).  Save
1938          *    the information in the newbssentry and then insert into the
1939          *    driver scan table either as an update to an existing entry
1940          *    or as an addition at the end of the table
1941          */
1942         for (idx = 0; idx < pscan->nr_sets && bytesleft; idx++) {
1943                 /* Zero out the newbssentry we are about to store info in */
1944                 memset(&newbssentry, 0x00, sizeof(newbssentry));
1945
1946                 /* Process the data fields and IEs returned for this BSS */
1947                 if ((InterpretBSSDescriptionWithIE(&newbssentry,
1948                                                    &pbssinfo,
1949                                                    &bytesleft) ==
1950                      0)
1951                     && CHECK_SSID_IS_VALID(&newbssentry.ssid)) {
1952
1953             lbs_pr_debug(1,
1954                                "SCAN_RESP: BSSID = %02x:%02x:%02x:%02x:%02x:%02x\n",
1955                                newbssentry.macaddress[0],
1956                                newbssentry.macaddress[1],
1957                                newbssentry.macaddress[2],
1958                                newbssentry.macaddress[3],
1959                                newbssentry.macaddress[4],
1960                                newbssentry.macaddress[5]);
1961
1962                         /*
1963                          * Search the scan table for the same bssid
1964                          */
1965                         for (bssIdx = 0; bssIdx < numintable; bssIdx++) {
1966                                 if (memcmp(newbssentry.macaddress,
1967                                            adapter->scantable[bssIdx].
1968                                            macaddress,
1969                                            sizeof(newbssentry.macaddress)) ==
1970                                     0) {
1971                                         /*
1972                                          * If the SSID matches as well, it is a duplicate of
1973                                          *   this entry.  Keep the bssIdx set to this
1974                                          *   entry so we replace the old contents in the table
1975                                          */
1976                                         if ((newbssentry.ssid.ssidlength ==
1977                                              adapter->scantable[bssIdx].ssid.
1978                                              ssidlength)
1979                                             &&
1980                                             (memcmp
1981                                              (newbssentry.ssid.ssid,
1982                                               adapter->scantable[bssIdx].ssid.
1983                                               ssid,
1984                                               newbssentry.ssid.ssidlength) ==
1985                                              0)) {
1986                         lbs_pr_debug(1,
1987                                                        "SCAN_RESP: Duplicate of index: %d\n",
1988                                                        bssIdx);
1989                                                 break;
1990                                         }
1991                                 }
1992                         }
1993                         /*
1994                          * If the bssIdx is equal to the number of entries in the table,
1995                          *   the new entry was not a duplicate; append it to the scan
1996                          *   table
1997                          */
1998                         if (bssIdx == numintable) {
1999                                 /* Range check the bssIdx, keep it limited to the last entry */
2000                                 if (bssIdx == MRVDRV_MAX_BSSID_LIST) {
2001                                         bssIdx--;
2002                                 } else {
2003                                         numintable++;
2004                                 }
2005                         }
2006
2007                         /*
2008                          * If the TSF TLV was appended to the scan results, save the
2009                          *   this entries TSF value in the networktsf field.  The
2010                          *   networktsf is the firmware's TSF value at the time the
2011                          *   beacon or probe response was received.
2012                          */
2013                         if (ptsftlv) {
2014                                 memcpy(&tsfval, &ptsftlv->tsftable[idx],
2015                                        sizeof(tsfval));
2016                                 tsfval = le64_to_cpu(tsfval);
2017
2018                                 memcpy(&newbssentry.networktsf,
2019                                        &tsfval, sizeof(newbssentry.networktsf));
2020                         }
2021
2022                         /* Copy the locally created newbssentry to the scan table */
2023                         memcpy(&adapter->scantable[bssIdx],
2024                                &newbssentry,
2025                                sizeof(adapter->scantable[bssIdx]));
2026
2027                 } else {
2028
2029                         /* error parsing/interpreting the scan response, skipped */
2030                         lbs_pr_debug(1, "SCAN_RESP: "
2031                                "InterpretBSSDescriptionWithIE returned ERROR\n");
2032                 }
2033         }
2034
2035         lbs_pr_debug(1, "SCAN_RESP: Scanned %2d APs, %d valid, %d total\n",
2036                pscan->nr_sets, numintable - adapter->numinscantable,
2037                numintable);
2038
2039         /* Update the total number of BSSIDs in the scan table */
2040         adapter->numinscantable = numintable;
2041
2042         LEAVE();
2043         return 0;
2044 }