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