iwlwifi: move DVM code into subdirectory
[cascardo/linux.git] / drivers / net / wireless / iwlwifi / dvm / scan.c
1 /******************************************************************************
2  *
3  * GPL LICENSE SUMMARY
4  *
5  * Copyright(c) 2008 - 2012 Intel Corporation. All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of version 2 of the GNU General Public License as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
19  * USA
20  *
21  * The full GNU General Public License is included in this distribution
22  * in the file called LICENSE.GPL.
23  *
24  * Contact Information:
25  *  Intel Linux Wireless <ilw@linux.intel.com>
26  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
27  *****************************************************************************/
28 #include <linux/slab.h>
29 #include <linux/types.h>
30 #include <linux/etherdevice.h>
31 #include <net/mac80211.h>
32
33 #include "eeprom.h"
34 #include "dev.h"
35 #include "agn.h"
36
37 /* For active scan, listen ACTIVE_DWELL_TIME (msec) on each channel after
38  * sending probe req.  This should be set long enough to hear probe responses
39  * from more than one AP.  */
40 #define IWL_ACTIVE_DWELL_TIME_24    (30)       /* all times in msec */
41 #define IWL_ACTIVE_DWELL_TIME_52    (20)
42
43 #define IWL_ACTIVE_DWELL_FACTOR_24GHZ (3)
44 #define IWL_ACTIVE_DWELL_FACTOR_52GHZ (2)
45
46 /* For passive scan, listen PASSIVE_DWELL_TIME (msec) on each channel.
47  * Must be set longer than active dwell time.
48  * For the most reliable scan, set > AP beacon interval (typically 100msec). */
49 #define IWL_PASSIVE_DWELL_TIME_24   (20)       /* all times in msec */
50 #define IWL_PASSIVE_DWELL_TIME_52   (10)
51 #define IWL_PASSIVE_DWELL_BASE      (100)
52 #define IWL_CHANNEL_TUNE_TIME       5
53 #define MAX_SCAN_CHANNEL            50
54
55 static int iwl_send_scan_abort(struct iwl_priv *priv)
56 {
57         int ret;
58         struct iwl_host_cmd cmd = {
59                 .id = REPLY_SCAN_ABORT_CMD,
60                 .flags = CMD_SYNC | CMD_WANT_SKB,
61         };
62         __le32 *status;
63
64         /* Exit instantly with error when device is not ready
65          * to receive scan abort command or it does not perform
66          * hardware scan currently */
67         if (!test_bit(STATUS_READY, &priv->status) ||
68             !test_bit(STATUS_GEO_CONFIGURED, &priv->status) ||
69             !test_bit(STATUS_SCAN_HW, &priv->status) ||
70             test_bit(STATUS_FW_ERROR, &priv->status))
71                 return -EIO;
72
73         ret = iwl_dvm_send_cmd(priv, &cmd);
74         if (ret)
75                 return ret;
76
77         status = (void *)cmd.resp_pkt->data;
78         if (*status != CAN_ABORT_STATUS) {
79                 /* The scan abort will return 1 for success or
80                  * 2 for "failure".  A failure condition can be
81                  * due to simply not being in an active scan which
82                  * can occur if we send the scan abort before we
83                  * the microcode has notified us that a scan is
84                  * completed. */
85                 IWL_DEBUG_SCAN(priv, "SCAN_ABORT ret %d.\n",
86                                le32_to_cpu(*status));
87                 ret = -EIO;
88         }
89
90         iwl_free_resp(&cmd);
91         return ret;
92 }
93
94 static void iwl_complete_scan(struct iwl_priv *priv, bool aborted)
95 {
96         /* check if scan was requested from mac80211 */
97         if (priv->scan_request) {
98                 IWL_DEBUG_SCAN(priv, "Complete scan in mac80211\n");
99                 ieee80211_scan_completed(priv->hw, aborted);
100         }
101
102         if (priv->scan_type == IWL_SCAN_ROC)
103                 iwl_scan_roc_expired(priv);
104
105         priv->scan_type = IWL_SCAN_NORMAL;
106         priv->scan_vif = NULL;
107         priv->scan_request = NULL;
108 }
109
110 static void iwl_process_scan_complete(struct iwl_priv *priv)
111 {
112         bool aborted;
113
114         lockdep_assert_held(&priv->mutex);
115
116         if (!test_and_clear_bit(STATUS_SCAN_COMPLETE, &priv->status))
117                 return;
118
119         IWL_DEBUG_SCAN(priv, "Completed scan.\n");
120
121         cancel_delayed_work(&priv->scan_check);
122
123         aborted = test_and_clear_bit(STATUS_SCAN_ABORTING, &priv->status);
124         if (aborted)
125                 IWL_DEBUG_SCAN(priv, "Aborted scan completed.\n");
126
127         if (!test_and_clear_bit(STATUS_SCANNING, &priv->status)) {
128                 IWL_DEBUG_SCAN(priv, "Scan already completed.\n");
129                 goto out_settings;
130         }
131
132         if (priv->scan_type == IWL_SCAN_ROC)
133                 iwl_scan_roc_expired(priv);
134
135         if (priv->scan_type != IWL_SCAN_NORMAL && !aborted) {
136                 int err;
137
138                 /* Check if mac80211 requested scan during our internal scan */
139                 if (priv->scan_request == NULL)
140                         goto out_complete;
141
142                 /* If so request a new scan */
143                 err = iwl_scan_initiate(priv, priv->scan_vif, IWL_SCAN_NORMAL,
144                                         priv->scan_request->channels[0]->band);
145                 if (err) {
146                         IWL_DEBUG_SCAN(priv,
147                                 "failed to initiate pending scan: %d\n", err);
148                         aborted = true;
149                         goto out_complete;
150                 }
151
152                 return;
153         }
154
155 out_complete:
156         iwl_complete_scan(priv, aborted);
157
158 out_settings:
159         /* Can we still talk to firmware ? */
160         if (!iwl_is_ready_rf(priv))
161                 return;
162
163         iwlagn_post_scan(priv);
164 }
165
166 void iwl_force_scan_end(struct iwl_priv *priv)
167 {
168         lockdep_assert_held(&priv->mutex);
169
170         if (!test_bit(STATUS_SCANNING, &priv->status)) {
171                 IWL_DEBUG_SCAN(priv, "Forcing scan end while not scanning\n");
172                 return;
173         }
174
175         IWL_DEBUG_SCAN(priv, "Forcing scan end\n");
176         clear_bit(STATUS_SCANNING, &priv->status);
177         clear_bit(STATUS_SCAN_HW, &priv->status);
178         clear_bit(STATUS_SCAN_ABORTING, &priv->status);
179         clear_bit(STATUS_SCAN_COMPLETE, &priv->status);
180         iwl_complete_scan(priv, true);
181 }
182
183 static void iwl_do_scan_abort(struct iwl_priv *priv)
184 {
185         int ret;
186
187         lockdep_assert_held(&priv->mutex);
188
189         if (!test_bit(STATUS_SCANNING, &priv->status)) {
190                 IWL_DEBUG_SCAN(priv, "Not performing scan to abort\n");
191                 return;
192         }
193
194         if (test_and_set_bit(STATUS_SCAN_ABORTING, &priv->status)) {
195                 IWL_DEBUG_SCAN(priv, "Scan abort in progress\n");
196                 return;
197         }
198
199         ret = iwl_send_scan_abort(priv);
200         if (ret) {
201                 IWL_DEBUG_SCAN(priv, "Send scan abort failed %d\n", ret);
202                 iwl_force_scan_end(priv);
203         } else
204                 IWL_DEBUG_SCAN(priv, "Successfully send scan abort\n");
205 }
206
207 /**
208  * iwl_scan_cancel - Cancel any currently executing HW scan
209  */
210 int iwl_scan_cancel(struct iwl_priv *priv)
211 {
212         IWL_DEBUG_SCAN(priv, "Queuing abort scan\n");
213         queue_work(priv->workqueue, &priv->abort_scan);
214         return 0;
215 }
216
217 /**
218  * iwl_scan_cancel_timeout - Cancel any currently executing HW scan
219  * @ms: amount of time to wait (in milliseconds) for scan to abort
220  *
221  */
222 void iwl_scan_cancel_timeout(struct iwl_priv *priv, unsigned long ms)
223 {
224         unsigned long timeout = jiffies + msecs_to_jiffies(ms);
225
226         lockdep_assert_held(&priv->mutex);
227
228         IWL_DEBUG_SCAN(priv, "Scan cancel timeout\n");
229
230         iwl_do_scan_abort(priv);
231
232         while (time_before_eq(jiffies, timeout)) {
233                 if (!test_bit(STATUS_SCAN_HW, &priv->status))
234                         goto finished;
235                 msleep(20);
236         }
237
238         return;
239
240  finished:
241         /*
242          * Now STATUS_SCAN_HW is clear. This means that the
243          * device finished, but the background work is going
244          * to execute at best as soon as we release the mutex.
245          * Since we need to be able to issue a new scan right
246          * after this function returns, run the complete here.
247          * The STATUS_SCAN_COMPLETE bit will then be cleared
248          * and prevent the background work from "completing"
249          * a possible new scan.
250          */
251         iwl_process_scan_complete(priv);
252 }
253
254 /* Service response to REPLY_SCAN_CMD (0x80) */
255 static int iwl_rx_reply_scan(struct iwl_priv *priv,
256                               struct iwl_rx_cmd_buffer *rxb,
257                               struct iwl_device_cmd *cmd)
258 {
259 #ifdef CONFIG_IWLWIFI_DEBUG
260         struct iwl_rx_packet *pkt = rxb_addr(rxb);
261         struct iwl_scanreq_notification *notif = (void *)pkt->data;
262
263         IWL_DEBUG_SCAN(priv, "Scan request status = 0x%x\n", notif->status);
264 #endif
265         return 0;
266 }
267
268 /* Service SCAN_START_NOTIFICATION (0x82) */
269 static int iwl_rx_scan_start_notif(struct iwl_priv *priv,
270                                     struct iwl_rx_cmd_buffer *rxb,
271                                     struct iwl_device_cmd *cmd)
272 {
273         struct iwl_rx_packet *pkt = rxb_addr(rxb);
274         struct iwl_scanstart_notification *notif = (void *)pkt->data;
275
276         priv->scan_start_tsf = le32_to_cpu(notif->tsf_low);
277         IWL_DEBUG_SCAN(priv, "Scan start: "
278                        "%d [802.11%s] "
279                        "(TSF: 0x%08X:%08X) - %d (beacon timer %u)\n",
280                        notif->channel,
281                        notif->band ? "bg" : "a",
282                        le32_to_cpu(notif->tsf_high),
283                        le32_to_cpu(notif->tsf_low),
284                        notif->status, notif->beacon_timer);
285
286         if (priv->scan_type == IWL_SCAN_ROC &&
287             !priv->hw_roc_start_notified) {
288                 ieee80211_ready_on_channel(priv->hw);
289                 priv->hw_roc_start_notified = true;
290         }
291
292         return 0;
293 }
294
295 /* Service SCAN_RESULTS_NOTIFICATION (0x83) */
296 static int iwl_rx_scan_results_notif(struct iwl_priv *priv,
297                                       struct iwl_rx_cmd_buffer *rxb,
298                                       struct iwl_device_cmd *cmd)
299 {
300 #ifdef CONFIG_IWLWIFI_DEBUG
301         struct iwl_rx_packet *pkt = rxb_addr(rxb);
302         struct iwl_scanresults_notification *notif = (void *)pkt->data;
303
304         IWL_DEBUG_SCAN(priv, "Scan ch.res: "
305                        "%d [802.11%s] "
306                        "probe status: %u:%u "
307                        "(TSF: 0x%08X:%08X) - %d "
308                        "elapsed=%lu usec\n",
309                        notif->channel,
310                        notif->band ? "bg" : "a",
311                        notif->probe_status, notif->num_probe_not_sent,
312                        le32_to_cpu(notif->tsf_high),
313                        le32_to_cpu(notif->tsf_low),
314                        le32_to_cpu(notif->statistics[0]),
315                        le32_to_cpu(notif->tsf_low) - priv->scan_start_tsf);
316 #endif
317         return 0;
318 }
319
320 /* Service SCAN_COMPLETE_NOTIFICATION (0x84) */
321 static int iwl_rx_scan_complete_notif(struct iwl_priv *priv,
322                                        struct iwl_rx_cmd_buffer *rxb,
323                                        struct iwl_device_cmd *cmd)
324 {
325         struct iwl_rx_packet *pkt = rxb_addr(rxb);
326         struct iwl_scancomplete_notification *scan_notif = (void *)pkt->data;
327
328         IWL_DEBUG_SCAN(priv, "Scan complete: %d channels (TSF 0x%08X:%08X) - %d\n",
329                        scan_notif->scanned_channels,
330                        scan_notif->tsf_low,
331                        scan_notif->tsf_high, scan_notif->status);
332
333         IWL_DEBUG_SCAN(priv, "Scan on %sGHz took %dms\n",
334                        (priv->scan_band == IEEE80211_BAND_2GHZ) ? "2.4" : "5.2",
335                        jiffies_to_msecs(jiffies - priv->scan_start));
336
337         /*
338          * When aborting, we run the scan completed background work inline
339          * and the background work must then do nothing. The SCAN_COMPLETE
340          * bit helps implement that logic and thus needs to be set before
341          * queueing the work. Also, since the scan abort waits for SCAN_HW
342          * to clear, we need to set SCAN_COMPLETE before clearing SCAN_HW
343          * to avoid a race there.
344          */
345         set_bit(STATUS_SCAN_COMPLETE, &priv->status);
346         clear_bit(STATUS_SCAN_HW, &priv->status);
347         queue_work(priv->workqueue, &priv->scan_completed);
348
349         if (priv->iw_mode != NL80211_IFTYPE_ADHOC &&
350             iwl_advanced_bt_coexist(priv) &&
351             priv->bt_status != scan_notif->bt_status) {
352                 if (scan_notif->bt_status) {
353                         /* BT on */
354                         if (!priv->bt_ch_announce)
355                                 priv->bt_traffic_load =
356                                         IWL_BT_COEX_TRAFFIC_LOAD_HIGH;
357                         /*
358                          * otherwise, no traffic load information provided
359                          * no changes made
360                          */
361                 } else {
362                         /* BT off */
363                         priv->bt_traffic_load =
364                                 IWL_BT_COEX_TRAFFIC_LOAD_NONE;
365                 }
366                 priv->bt_status = scan_notif->bt_status;
367                 queue_work(priv->workqueue,
368                            &priv->bt_traffic_change_work);
369         }
370         return 0;
371 }
372
373 void iwl_setup_rx_scan_handlers(struct iwl_priv *priv)
374 {
375         /* scan handlers */
376         priv->rx_handlers[REPLY_SCAN_CMD] = iwl_rx_reply_scan;
377         priv->rx_handlers[SCAN_START_NOTIFICATION] = iwl_rx_scan_start_notif;
378         priv->rx_handlers[SCAN_RESULTS_NOTIFICATION] =
379                                         iwl_rx_scan_results_notif;
380         priv->rx_handlers[SCAN_COMPLETE_NOTIFICATION] =
381                                         iwl_rx_scan_complete_notif;
382 }
383
384 static u16 iwl_get_active_dwell_time(struct iwl_priv *priv,
385                                      enum ieee80211_band band, u8 n_probes)
386 {
387         if (band == IEEE80211_BAND_5GHZ)
388                 return IWL_ACTIVE_DWELL_TIME_52 +
389                         IWL_ACTIVE_DWELL_FACTOR_52GHZ * (n_probes + 1);
390         else
391                 return IWL_ACTIVE_DWELL_TIME_24 +
392                         IWL_ACTIVE_DWELL_FACTOR_24GHZ * (n_probes + 1);
393 }
394
395 static u16 iwl_limit_dwell(struct iwl_priv *priv, u16 dwell_time)
396 {
397         struct iwl_rxon_context *ctx;
398
399         /*
400          * If we're associated, we clamp the dwell time 98%
401          * of the smallest beacon interval (minus 2 * channel
402          * tune time)
403          */
404         for_each_context(priv, ctx) {
405                 u16 value;
406
407                 switch (ctx->staging.dev_type) {
408                 case RXON_DEV_TYPE_P2P:
409                         /* no timing constraints */
410                         continue;
411                 case RXON_DEV_TYPE_ESS:
412                 default:
413                         /* timing constraints if associated */
414                         if (!iwl_is_associated_ctx(ctx))
415                                 continue;
416                         break;
417                 case RXON_DEV_TYPE_CP:
418                 case RXON_DEV_TYPE_2STA:
419                         /*
420                          * These seem to always have timers for TBTT
421                          * active in uCode even when not associated yet.
422                          */
423                         break;
424                 }
425
426                 value = ctx->beacon_int;
427                 if (!value)
428                         value = IWL_PASSIVE_DWELL_BASE;
429                 value = (value * 98) / 100 - IWL_CHANNEL_TUNE_TIME * 2;
430                 dwell_time = min(value, dwell_time);
431         }
432
433         return dwell_time;
434 }
435
436 static u16 iwl_get_passive_dwell_time(struct iwl_priv *priv,
437                                       enum ieee80211_band band)
438 {
439         u16 passive = (band == IEEE80211_BAND_2GHZ) ?
440             IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_24 :
441             IWL_PASSIVE_DWELL_BASE + IWL_PASSIVE_DWELL_TIME_52;
442
443         return iwl_limit_dwell(priv, passive);
444 }
445
446 /* Return valid, unused, channel for a passive scan to reset the RF */
447 static u8 iwl_get_single_channel_number(struct iwl_priv *priv,
448                                         enum ieee80211_band band)
449 {
450         struct ieee80211_supported_band *sband = priv->hw->wiphy->bands[band];
451         struct iwl_rxon_context *ctx;
452         int i;
453
454         for (i = 0; i < sband->n_channels; i++) {
455                 bool busy = false;
456
457                 for_each_context(priv, ctx) {
458                         busy = sband->channels[i].hw_value ==
459                                 le16_to_cpu(ctx->staging.channel);
460                         if (busy)
461                                 break;
462                 }
463
464                 if (busy)
465                         continue;
466
467                 if (!(sband->channels[i].flags & IEEE80211_CHAN_DISABLED))
468                         return sband->channels[i].hw_value;
469         }
470
471         return 0;
472 }
473
474 static int iwl_get_single_channel_for_scan(struct iwl_priv *priv,
475                                            struct ieee80211_vif *vif,
476                                            enum ieee80211_band band,
477                                            struct iwl_scan_channel *scan_ch)
478 {
479         const struct ieee80211_supported_band *sband;
480         u16 passive_dwell = 0;
481         u16 active_dwell = 0;
482         int added = 0;
483         u16 channel = 0;
484
485         sband = iwl_get_hw_mode(priv, band);
486         if (!sband) {
487                 IWL_ERR(priv, "invalid band\n");
488                 return added;
489         }
490
491         active_dwell = iwl_get_active_dwell_time(priv, band, 0);
492         passive_dwell = iwl_get_passive_dwell_time(priv, band);
493
494         if (passive_dwell <= active_dwell)
495                 passive_dwell = active_dwell + 1;
496
497         channel = iwl_get_single_channel_number(priv, band);
498         if (channel) {
499                 scan_ch->channel = cpu_to_le16(channel);
500                 scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
501                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
502                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
503                 /* Set txpower levels to defaults */
504                 scan_ch->dsp_atten = 110;
505                 if (band == IEEE80211_BAND_5GHZ)
506                         scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
507                 else
508                         scan_ch->tx_gain = ((1 << 5) | (5 << 3));
509                 added++;
510         } else
511                 IWL_ERR(priv, "no valid channel found\n");
512         return added;
513 }
514
515 static int iwl_get_channels_for_scan(struct iwl_priv *priv,
516                                      struct ieee80211_vif *vif,
517                                      enum ieee80211_band band,
518                                      u8 is_active, u8 n_probes,
519                                      struct iwl_scan_channel *scan_ch)
520 {
521         struct ieee80211_channel *chan;
522         const struct ieee80211_supported_band *sband;
523         u16 passive_dwell = 0;
524         u16 active_dwell = 0;
525         int added, i;
526         u16 channel;
527
528         sband = iwl_get_hw_mode(priv, band);
529         if (!sband)
530                 return 0;
531
532         active_dwell = iwl_get_active_dwell_time(priv, band, n_probes);
533         passive_dwell = iwl_get_passive_dwell_time(priv, band);
534
535         if (passive_dwell <= active_dwell)
536                 passive_dwell = active_dwell + 1;
537
538         for (i = 0, added = 0; i < priv->scan_request->n_channels; i++) {
539                 chan = priv->scan_request->channels[i];
540
541                 if (chan->band != band)
542                         continue;
543
544                 channel = chan->hw_value;
545                 scan_ch->channel = cpu_to_le16(channel);
546
547                 if (!is_active || (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN))
548                         scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
549                 else
550                         scan_ch->type = SCAN_CHANNEL_TYPE_ACTIVE;
551
552                 if (n_probes)
553                         scan_ch->type |= IWL_SCAN_PROBE_MASK(n_probes);
554
555                 scan_ch->active_dwell = cpu_to_le16(active_dwell);
556                 scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
557
558                 /* Set txpower levels to defaults */
559                 scan_ch->dsp_atten = 110;
560
561                 /* NOTE: if we were doing 6Mb OFDM for scans we'd use
562                  * power level:
563                  * scan_ch->tx_gain = ((1 << 5) | (2 << 3)) | 3;
564                  */
565                 if (band == IEEE80211_BAND_5GHZ)
566                         scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
567                 else
568                         scan_ch->tx_gain = ((1 << 5) | (5 << 3));
569
570                 IWL_DEBUG_SCAN(priv, "Scanning ch=%d prob=0x%X [%s %d]\n",
571                                channel, le32_to_cpu(scan_ch->type),
572                                (scan_ch->type & SCAN_CHANNEL_TYPE_ACTIVE) ?
573                                 "ACTIVE" : "PASSIVE",
574                                (scan_ch->type & SCAN_CHANNEL_TYPE_ACTIVE) ?
575                                active_dwell : passive_dwell);
576
577                 scan_ch++;
578                 added++;
579         }
580
581         IWL_DEBUG_SCAN(priv, "total channels to scan %d\n", added);
582         return added;
583 }
584
585 /**
586  * iwl_fill_probe_req - fill in all required fields and IE for probe request
587  */
588
589 static u16 iwl_fill_probe_req(struct ieee80211_mgmt *frame, const u8 *ta,
590                               const u8 *ies, int ie_len, const u8 *ssid,
591                               u8 ssid_len, int left)
592 {
593         int len = 0;
594         u8 *pos = NULL;
595
596         /* Make sure there is enough space for the probe request,
597          * two mandatory IEs and the data */
598         left -= 24;
599         if (left < 0)
600                 return 0;
601
602         frame->frame_control = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
603         memcpy(frame->da, iwl_bcast_addr, ETH_ALEN);
604         memcpy(frame->sa, ta, ETH_ALEN);
605         memcpy(frame->bssid, iwl_bcast_addr, ETH_ALEN);
606         frame->seq_ctrl = 0;
607
608         len += 24;
609
610         /* ...next IE... */
611         pos = &frame->u.probe_req.variable[0];
612
613         /* fill in our SSID IE */
614         left -= ssid_len + 2;
615         if (left < 0)
616                 return 0;
617         *pos++ = WLAN_EID_SSID;
618         *pos++ = ssid_len;
619         if (ssid && ssid_len) {
620                 memcpy(pos, ssid, ssid_len);
621                 pos += ssid_len;
622         }
623
624         len += ssid_len + 2;
625
626         if (WARN_ON(left < ie_len))
627                 return len;
628
629         if (ies && ie_len) {
630                 memcpy(pos, ies, ie_len);
631                 len += ie_len;
632         }
633
634         return (u16)len;
635 }
636
637 static int iwlagn_request_scan(struct iwl_priv *priv, struct ieee80211_vif *vif)
638 {
639         struct iwl_host_cmd cmd = {
640                 .id = REPLY_SCAN_CMD,
641                 .len = { sizeof(struct iwl_scan_cmd), },
642                 .flags = CMD_SYNC,
643         };
644         struct iwl_scan_cmd *scan;
645         struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
646         u32 rate_flags = 0;
647         u16 cmd_len = 0;
648         u16 rx_chain = 0;
649         enum ieee80211_band band;
650         u8 n_probes = 0;
651         u8 rx_ant = priv->hw_params.valid_rx_ant;
652         u8 rate;
653         bool is_active = false;
654         int  chan_mod;
655         u8 active_chains;
656         u8 scan_tx_antennas = priv->hw_params.valid_tx_ant;
657         int ret;
658         int scan_cmd_size = sizeof(struct iwl_scan_cmd) +
659                             MAX_SCAN_CHANNEL * sizeof(struct iwl_scan_channel) +
660                             priv->fw->ucode_capa.max_probe_length;
661         const u8 *ssid = NULL;
662         u8 ssid_len = 0;
663
664         if (WARN_ON_ONCE(priv->scan_request &&
665                          priv->scan_request->n_channels > MAX_SCAN_CHANNEL))
666                 return -EINVAL;
667
668         lockdep_assert_held(&priv->mutex);
669
670         if (vif)
671                 ctx = iwl_rxon_ctx_from_vif(vif);
672
673         if (!priv->scan_cmd) {
674                 priv->scan_cmd = kmalloc(scan_cmd_size, GFP_KERNEL);
675                 if (!priv->scan_cmd) {
676                         IWL_DEBUG_SCAN(priv,
677                                        "fail to allocate memory for scan\n");
678                         return -ENOMEM;
679                 }
680         }
681         scan = priv->scan_cmd;
682         memset(scan, 0, scan_cmd_size);
683
684         scan->quiet_plcp_th = IWL_PLCP_QUIET_THRESH;
685         scan->quiet_time = IWL_ACTIVE_QUIET_TIME;
686
687         if (priv->scan_type != IWL_SCAN_ROC &&
688             iwl_is_any_associated(priv)) {
689                 u16 interval = 0;
690                 u32 extra;
691                 u32 suspend_time = 100;
692                 u32 scan_suspend_time = 100;
693
694                 IWL_DEBUG_INFO(priv, "Scanning while associated...\n");
695                 switch (priv->scan_type) {
696                 case IWL_SCAN_ROC:
697                         WARN_ON(1);
698                         break;
699                 case IWL_SCAN_RADIO_RESET:
700                         interval = 0;
701                         break;
702                 case IWL_SCAN_NORMAL:
703                         interval = vif->bss_conf.beacon_int;
704                         break;
705                 }
706
707                 scan->suspend_time = 0;
708                 scan->max_out_time = cpu_to_le32(200 * 1024);
709                 if (!interval)
710                         interval = suspend_time;
711
712                 extra = (suspend_time / interval) << 22;
713                 scan_suspend_time = (extra |
714                     ((suspend_time % interval) * 1024));
715                 scan->suspend_time = cpu_to_le32(scan_suspend_time);
716                 IWL_DEBUG_SCAN(priv, "suspend_time 0x%X beacon interval %d\n",
717                                scan_suspend_time, interval);
718         } else if (priv->scan_type == IWL_SCAN_ROC) {
719                 scan->suspend_time = 0;
720                 scan->max_out_time = 0;
721                 scan->quiet_time = 0;
722                 scan->quiet_plcp_th = 0;
723         }
724
725         switch (priv->scan_type) {
726         case IWL_SCAN_RADIO_RESET:
727                 IWL_DEBUG_SCAN(priv, "Start internal passive scan.\n");
728                 break;
729         case IWL_SCAN_NORMAL:
730                 if (priv->scan_request->n_ssids) {
731                         int i, p = 0;
732                         IWL_DEBUG_SCAN(priv, "Kicking off active scan\n");
733                         /*
734                          * The highest priority SSID is inserted to the
735                          * probe request template.
736                          */
737                         ssid_len = priv->scan_request->ssids[0].ssid_len;
738                         ssid = priv->scan_request->ssids[0].ssid;
739
740                         /*
741                          * Invert the order of ssids, the firmware will invert
742                          * it back.
743                          */
744                         for (i = priv->scan_request->n_ssids - 1; i >= 1; i--) {
745                                 scan->direct_scan[p].id = WLAN_EID_SSID;
746                                 scan->direct_scan[p].len =
747                                         priv->scan_request->ssids[i].ssid_len;
748                                 memcpy(scan->direct_scan[p].ssid,
749                                        priv->scan_request->ssids[i].ssid,
750                                        priv->scan_request->ssids[i].ssid_len);
751                                 n_probes++;
752                                 p++;
753                         }
754                         is_active = true;
755                 } else
756                         IWL_DEBUG_SCAN(priv, "Start passive scan.\n");
757                 break;
758         case IWL_SCAN_ROC:
759                 IWL_DEBUG_SCAN(priv, "Start ROC scan.\n");
760                 break;
761         }
762
763         scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
764         scan->tx_cmd.sta_id = ctx->bcast_sta_id;
765         scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
766
767         switch (priv->scan_band) {
768         case IEEE80211_BAND_2GHZ:
769                 scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
770                 chan_mod = le32_to_cpu(
771                         priv->contexts[IWL_RXON_CTX_BSS].active.flags &
772                                                 RXON_FLG_CHANNEL_MODE_MSK)
773                                        >> RXON_FLG_CHANNEL_MODE_POS;
774                 if ((priv->scan_request && priv->scan_request->no_cck) ||
775                     chan_mod == CHANNEL_MODE_PURE_40) {
776                         rate = IWL_RATE_6M_PLCP;
777                 } else {
778                         rate = IWL_RATE_1M_PLCP;
779                         rate_flags = RATE_MCS_CCK_MSK;
780                 }
781                 /*
782                  * Internal scans are passive, so we can indiscriminately set
783                  * the BT ignore flag on 2.4 GHz since it applies to TX only.
784                  */
785                 if (priv->cfg->bt_params &&
786                     priv->cfg->bt_params->advanced_bt_coexist)
787                         scan->tx_cmd.tx_flags |= TX_CMD_FLG_IGNORE_BT;
788                 break;
789         case IEEE80211_BAND_5GHZ:
790                 rate = IWL_RATE_6M_PLCP;
791                 break;
792         default:
793                 IWL_WARN(priv, "Invalid scan band\n");
794                 return -EIO;
795         }
796
797         /*
798          * If active scanning is requested but a certain channel is
799          * marked passive, we can do active scanning if we detect
800          * transmissions.
801          *
802          * There is an issue with some firmware versions that triggers
803          * a sysassert on a "good CRC threshold" of zero (== disabled),
804          * on a radar channel even though this means that we should NOT
805          * send probes.
806          *
807          * The "good CRC threshold" is the number of frames that we
808          * need to receive during our dwell time on a channel before
809          * sending out probes -- setting this to a huge value will
810          * mean we never reach it, but at the same time work around
811          * the aforementioned issue. Thus use IWL_GOOD_CRC_TH_NEVER
812          * here instead of IWL_GOOD_CRC_TH_DISABLED.
813          *
814          * This was fixed in later versions along with some other
815          * scan changes, and the threshold behaves as a flag in those
816          * versions.
817          */
818         if (priv->new_scan_threshold_behaviour)
819                 scan->good_CRC_th = is_active ? IWL_GOOD_CRC_TH_DEFAULT :
820                                                 IWL_GOOD_CRC_TH_DISABLED;
821         else
822                 scan->good_CRC_th = is_active ? IWL_GOOD_CRC_TH_DEFAULT :
823                                                 IWL_GOOD_CRC_TH_NEVER;
824
825         band = priv->scan_band;
826
827         if (band == IEEE80211_BAND_2GHZ &&
828             priv->cfg->bt_params &&
829             priv->cfg->bt_params->advanced_bt_coexist) {
830                 /* transmit 2.4 GHz probes only on first antenna */
831                 scan_tx_antennas = first_antenna(scan_tx_antennas);
832         }
833
834         priv->scan_tx_ant[band] = iwl_toggle_tx_ant(priv,
835                                                     priv->scan_tx_ant[band],
836                                                     scan_tx_antennas);
837         rate_flags |= iwl_ant_idx_to_flags(priv->scan_tx_ant[band]);
838         scan->tx_cmd.rate_n_flags = iwl_hw_set_rate_n_flags(rate, rate_flags);
839
840         /*
841          * In power save mode while associated use one chain,
842          * otherwise use all chains
843          */
844         if (test_bit(STATUS_POWER_PMI, &priv->status) &&
845             !(priv->hw->conf.flags & IEEE80211_CONF_IDLE)) {
846                 /* rx_ant has been set to all valid chains previously */
847                 active_chains = rx_ant &
848                                 ((u8)(priv->chain_noise_data.active_chains));
849                 if (!active_chains)
850                         active_chains = rx_ant;
851
852                 IWL_DEBUG_SCAN(priv, "chain_noise_data.active_chains: %u\n",
853                                 priv->chain_noise_data.active_chains);
854
855                 rx_ant = first_antenna(active_chains);
856         }
857         if (priv->cfg->bt_params &&
858             priv->cfg->bt_params->advanced_bt_coexist &&
859             priv->bt_full_concurrent) {
860                 /* operated as 1x1 in full concurrency mode */
861                 rx_ant = first_antenna(rx_ant);
862         }
863
864         /* MIMO is not used here, but value is required */
865         rx_chain |=
866                 priv->hw_params.valid_rx_ant << RXON_RX_CHAIN_VALID_POS;
867         rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_MIMO_SEL_POS;
868         rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_SEL_POS;
869         rx_chain |= 0x1 << RXON_RX_CHAIN_DRIVER_FORCE_POS;
870         scan->rx_chain = cpu_to_le16(rx_chain);
871         switch (priv->scan_type) {
872         case IWL_SCAN_NORMAL:
873                 cmd_len = iwl_fill_probe_req(
874                                         (struct ieee80211_mgmt *)scan->data,
875                                         vif->addr,
876                                         priv->scan_request->ie,
877                                         priv->scan_request->ie_len,
878                                         ssid, ssid_len,
879                                         scan_cmd_size - sizeof(*scan));
880                 break;
881         case IWL_SCAN_RADIO_RESET:
882         case IWL_SCAN_ROC:
883                 /* use bcast addr, will not be transmitted but must be valid */
884                 cmd_len = iwl_fill_probe_req(
885                                         (struct ieee80211_mgmt *)scan->data,
886                                         iwl_bcast_addr, NULL, 0,
887                                         NULL, 0,
888                                         scan_cmd_size - sizeof(*scan));
889                 break;
890         default:
891                 BUG();
892         }
893         scan->tx_cmd.len = cpu_to_le16(cmd_len);
894
895         scan->filter_flags |= (RXON_FILTER_ACCEPT_GRP_MSK |
896                                RXON_FILTER_BCON_AWARE_MSK);
897
898         switch (priv->scan_type) {
899         case IWL_SCAN_RADIO_RESET:
900                 scan->channel_count =
901                         iwl_get_single_channel_for_scan(priv, vif, band,
902                                 (void *)&scan->data[cmd_len]);
903                 break;
904         case IWL_SCAN_NORMAL:
905                 scan->channel_count =
906                         iwl_get_channels_for_scan(priv, vif, band,
907                                 is_active, n_probes,
908                                 (void *)&scan->data[cmd_len]);
909                 break;
910         case IWL_SCAN_ROC: {
911                 struct iwl_scan_channel *scan_ch;
912                 int n_chan, i;
913                 u16 dwell;
914
915                 dwell = iwl_limit_dwell(priv, priv->hw_roc_duration);
916                 n_chan = DIV_ROUND_UP(priv->hw_roc_duration, dwell);
917
918                 scan->channel_count = n_chan;
919
920                 scan_ch = (void *)&scan->data[cmd_len];
921
922                 for (i = 0; i < n_chan; i++) {
923                         scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
924                         scan_ch->channel =
925                                 cpu_to_le16(priv->hw_roc_channel->hw_value);
926
927                         if (i == n_chan - 1)
928                                 dwell = priv->hw_roc_duration - i * dwell;
929
930                         scan_ch->active_dwell =
931                         scan_ch->passive_dwell = cpu_to_le16(dwell);
932
933                         /* Set txpower levels to defaults */
934                         scan_ch->dsp_atten = 110;
935
936                         /* NOTE: if we were doing 6Mb OFDM for scans we'd use
937                          * power level:
938                          * scan_ch->tx_gain = ((1 << 5) | (2 << 3)) | 3;
939                          */
940                         if (priv->hw_roc_channel->band == IEEE80211_BAND_5GHZ)
941                                 scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
942                         else
943                                 scan_ch->tx_gain = ((1 << 5) | (5 << 3));
944
945                         scan_ch++;
946                 }
947                 }
948
949                 break;
950         }
951
952         if (scan->channel_count == 0) {
953                 IWL_DEBUG_SCAN(priv, "channel count %d\n", scan->channel_count);
954                 return -EIO;
955         }
956
957         cmd.len[0] += le16_to_cpu(scan->tx_cmd.len) +
958             scan->channel_count * sizeof(struct iwl_scan_channel);
959         cmd.data[0] = scan;
960         cmd.dataflags[0] = IWL_HCMD_DFL_NOCOPY;
961         scan->len = cpu_to_le16(cmd.len[0]);
962
963         /* set scan bit here for PAN params */
964         set_bit(STATUS_SCAN_HW, &priv->status);
965
966         ret = iwlagn_set_pan_params(priv);
967         if (ret) {
968                 clear_bit(STATUS_SCAN_HW, &priv->status);
969                 return ret;
970         }
971
972         ret = iwl_dvm_send_cmd(priv, &cmd);
973         if (ret) {
974                 clear_bit(STATUS_SCAN_HW, &priv->status);
975                 iwlagn_set_pan_params(priv);
976         }
977
978         return ret;
979 }
980
981 void iwl_init_scan_params(struct iwl_priv *priv)
982 {
983         u8 ant_idx = fls(priv->hw_params.valid_tx_ant) - 1;
984         if (!priv->scan_tx_ant[IEEE80211_BAND_5GHZ])
985                 priv->scan_tx_ant[IEEE80211_BAND_5GHZ] = ant_idx;
986         if (!priv->scan_tx_ant[IEEE80211_BAND_2GHZ])
987                 priv->scan_tx_ant[IEEE80211_BAND_2GHZ] = ant_idx;
988 }
989
990 int __must_check iwl_scan_initiate(struct iwl_priv *priv,
991                                    struct ieee80211_vif *vif,
992                                    enum iwl_scan_type scan_type,
993                                    enum ieee80211_band band)
994 {
995         int ret;
996
997         lockdep_assert_held(&priv->mutex);
998
999         cancel_delayed_work(&priv->scan_check);
1000
1001         if (!iwl_is_ready_rf(priv)) {
1002                 IWL_WARN(priv, "Request scan called when driver not ready.\n");
1003                 return -EIO;
1004         }
1005
1006         if (test_bit(STATUS_SCAN_HW, &priv->status)) {
1007                 IWL_DEBUG_SCAN(priv,
1008                         "Multiple concurrent scan requests in parallel.\n");
1009                 return -EBUSY;
1010         }
1011
1012         if (test_bit(STATUS_SCAN_ABORTING, &priv->status)) {
1013                 IWL_DEBUG_SCAN(priv, "Scan request while abort pending.\n");
1014                 return -EBUSY;
1015         }
1016
1017         IWL_DEBUG_SCAN(priv, "Starting %sscan...\n",
1018                         scan_type == IWL_SCAN_NORMAL ? "" :
1019                         scan_type == IWL_SCAN_ROC ? "remain-on-channel " :
1020                         "internal short ");
1021
1022         set_bit(STATUS_SCANNING, &priv->status);
1023         priv->scan_type = scan_type;
1024         priv->scan_start = jiffies;
1025         priv->scan_band = band;
1026
1027         ret = iwlagn_request_scan(priv, vif);
1028         if (ret) {
1029                 clear_bit(STATUS_SCANNING, &priv->status);
1030                 priv->scan_type = IWL_SCAN_NORMAL;
1031                 return ret;
1032         }
1033
1034         queue_delayed_work(priv->workqueue, &priv->scan_check,
1035                            IWL_SCAN_CHECK_WATCHDOG);
1036
1037         return 0;
1038 }
1039
1040
1041 /*
1042  * internal short scan, this function should only been called while associated.
1043  * It will reset and tune the radio to prevent possible RF related problem
1044  */
1045 void iwl_internal_short_hw_scan(struct iwl_priv *priv)
1046 {
1047         queue_work(priv->workqueue, &priv->start_internal_scan);
1048 }
1049
1050 static void iwl_bg_start_internal_scan(struct work_struct *work)
1051 {
1052         struct iwl_priv *priv =
1053                 container_of(work, struct iwl_priv, start_internal_scan);
1054
1055         IWL_DEBUG_SCAN(priv, "Start internal scan\n");
1056
1057         mutex_lock(&priv->mutex);
1058
1059         if (priv->scan_type == IWL_SCAN_RADIO_RESET) {
1060                 IWL_DEBUG_SCAN(priv, "Internal scan already in progress\n");
1061                 goto unlock;
1062         }
1063
1064         if (test_bit(STATUS_SCANNING, &priv->status)) {
1065                 IWL_DEBUG_SCAN(priv, "Scan already in progress.\n");
1066                 goto unlock;
1067         }
1068
1069         if (iwl_scan_initiate(priv, NULL, IWL_SCAN_RADIO_RESET, priv->band))
1070                 IWL_DEBUG_SCAN(priv, "failed to start internal short scan\n");
1071  unlock:
1072         mutex_unlock(&priv->mutex);
1073 }
1074
1075 static void iwl_bg_scan_check(struct work_struct *data)
1076 {
1077         struct iwl_priv *priv =
1078             container_of(data, struct iwl_priv, scan_check.work);
1079
1080         IWL_DEBUG_SCAN(priv, "Scan check work\n");
1081
1082         /* Since we are here firmware does not finish scan and
1083          * most likely is in bad shape, so we don't bother to
1084          * send abort command, just force scan complete to mac80211 */
1085         mutex_lock(&priv->mutex);
1086         iwl_force_scan_end(priv);
1087         mutex_unlock(&priv->mutex);
1088 }
1089
1090 static void iwl_bg_abort_scan(struct work_struct *work)
1091 {
1092         struct iwl_priv *priv = container_of(work, struct iwl_priv, abort_scan);
1093
1094         IWL_DEBUG_SCAN(priv, "Abort scan work\n");
1095
1096         /* We keep scan_check work queued in case when firmware will not
1097          * report back scan completed notification */
1098         mutex_lock(&priv->mutex);
1099         iwl_scan_cancel_timeout(priv, 200);
1100         mutex_unlock(&priv->mutex);
1101 }
1102
1103 static void iwl_bg_scan_completed(struct work_struct *work)
1104 {
1105         struct iwl_priv *priv =
1106                 container_of(work, struct iwl_priv, scan_completed);
1107
1108         mutex_lock(&priv->mutex);
1109         iwl_process_scan_complete(priv);
1110         mutex_unlock(&priv->mutex);
1111 }
1112
1113 void iwl_setup_scan_deferred_work(struct iwl_priv *priv)
1114 {
1115         INIT_WORK(&priv->scan_completed, iwl_bg_scan_completed);
1116         INIT_WORK(&priv->abort_scan, iwl_bg_abort_scan);
1117         INIT_WORK(&priv->start_internal_scan, iwl_bg_start_internal_scan);
1118         INIT_DELAYED_WORK(&priv->scan_check, iwl_bg_scan_check);
1119 }
1120
1121 void iwl_cancel_scan_deferred_work(struct iwl_priv *priv)
1122 {
1123         cancel_work_sync(&priv->start_internal_scan);
1124         cancel_work_sync(&priv->abort_scan);
1125         cancel_work_sync(&priv->scan_completed);
1126
1127         if (cancel_delayed_work_sync(&priv->scan_check)) {
1128                 mutex_lock(&priv->mutex);
1129                 iwl_force_scan_end(priv);
1130                 mutex_unlock(&priv->mutex);
1131         }
1132 }
1133
1134 void iwl_scan_roc_expired(struct iwl_priv *priv)
1135 {
1136         /*
1137          * The status bit should be set here, to prevent a race
1138          * where the atomic_read returns 1, but before the execution continues
1139          * iwl_scan_offchannel_skb_status() checks if the status bit is set
1140          */
1141         set_bit(STATUS_SCAN_ROC_EXPIRED, &priv->status);
1142
1143         if (atomic_read(&priv->num_aux_in_flight) == 0) {
1144                 ieee80211_remain_on_channel_expired(priv->hw);
1145                 priv->hw_roc_channel = NULL;
1146                 schedule_delayed_work(&priv->hw_roc_disable_work,
1147                                       10 * HZ);
1148
1149                 clear_bit(STATUS_SCAN_ROC_EXPIRED, &priv->status);
1150         } else {
1151                 IWL_DEBUG_SCAN(priv, "ROC done with %d frames in aux\n",
1152                                atomic_read(&priv->num_aux_in_flight));
1153         }
1154 }
1155
1156 void iwl_scan_offchannel_skb(struct iwl_priv *priv)
1157 {
1158         WARN_ON(!priv->hw_roc_start_notified);
1159         atomic_inc(&priv->num_aux_in_flight);
1160 }
1161
1162 void iwl_scan_offchannel_skb_status(struct iwl_priv *priv)
1163 {
1164         if (atomic_dec_return(&priv->num_aux_in_flight) == 0 &&
1165             test_bit(STATUS_SCAN_ROC_EXPIRED, &priv->status)) {
1166                 IWL_DEBUG_SCAN(priv, "0 aux frames. Calling ROC expired\n");
1167                 iwl_scan_roc_expired(priv);
1168         }
1169 }