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