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