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