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