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