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