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