xref: /openbmc/linux/drivers/net/wireless/intel/iwlwifi/mvm/d3.c (revision b68fc09be48edbc47de1a0f3d42ef8adf6c0ac55)
1 /******************************************************************************
2  *
3  * This file is provided under a dual BSD/GPLv2 license.  When using or
4  * redistributing this file, you may do so under either license.
5  *
6  * GPL LICENSE SUMMARY
7  *
8  * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
9  * Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH
10  * Copyright(c) 2016 - 2017 Intel Deutschland GmbH
11  * Copyright(c) 2018        Intel Corporation
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of version 2 of the GNU General Public License as
15  * published by the Free Software Foundation.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * The full GNU General Public License is included in this distribution
23  * in the file called COPYING.
24  *
25  * Contact Information:
26  *  Intel Linux Wireless <linuxwifi@intel.com>
27  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
28  *
29  * BSD LICENSE
30  *
31  * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
32  * Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH
33  * Copyright(c) 2016 - 2017 Intel Deutschland GmbH
34  * Copyright(c) 2018        Intel Corporation
35  * All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  *
41  *  * Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  *  * Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in
45  *    the documentation and/or other materials provided with the
46  *    distribution.
47  *  * Neither the name Intel Corporation nor the names of its
48  *    contributors may be used to endorse or promote products derived
49  *    from this software without specific prior written permission.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
52  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
53  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
54  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
55  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
56  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
57  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
58  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
59  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
60  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
61  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62  *
63  *****************************************************************************/
64 
65 #include <linux/etherdevice.h>
66 #include <linux/ip.h>
67 #include <linux/fs.h>
68 #include <net/cfg80211.h>
69 #include <net/ipv6.h>
70 #include <net/tcp.h>
71 #include <net/addrconf.h>
72 #include "iwl-modparams.h"
73 #include "fw-api.h"
74 #include "mvm.h"
75 
76 void iwl_mvm_set_rekey_data(struct ieee80211_hw *hw,
77 			    struct ieee80211_vif *vif,
78 			    struct cfg80211_gtk_rekey_data *data)
79 {
80 	struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
81 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
82 
83 	if (iwlwifi_mod_params.swcrypto)
84 		return;
85 
86 	mutex_lock(&mvm->mutex);
87 
88 	memcpy(mvmvif->rekey_data.kek, data->kek, NL80211_KEK_LEN);
89 	memcpy(mvmvif->rekey_data.kck, data->kck, NL80211_KCK_LEN);
90 	mvmvif->rekey_data.replay_ctr =
91 		cpu_to_le64(be64_to_cpup((__be64 *)data->replay_ctr));
92 	mvmvif->rekey_data.valid = true;
93 
94 	mutex_unlock(&mvm->mutex);
95 }
96 
97 #if IS_ENABLED(CONFIG_IPV6)
98 void iwl_mvm_ipv6_addr_change(struct ieee80211_hw *hw,
99 			      struct ieee80211_vif *vif,
100 			      struct inet6_dev *idev)
101 {
102 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
103 	struct inet6_ifaddr *ifa;
104 	int idx = 0;
105 
106 	memset(mvmvif->tentative_addrs, 0, sizeof(mvmvif->tentative_addrs));
107 
108 	read_lock_bh(&idev->lock);
109 	list_for_each_entry(ifa, &idev->addr_list, if_list) {
110 		mvmvif->target_ipv6_addrs[idx] = ifa->addr;
111 		if (ifa->flags & IFA_F_TENTATIVE)
112 			__set_bit(idx, mvmvif->tentative_addrs);
113 		idx++;
114 		if (idx >= IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS_MAX)
115 			break;
116 	}
117 	read_unlock_bh(&idev->lock);
118 
119 	mvmvif->num_target_ipv6_addrs = idx;
120 }
121 #endif
122 
123 void iwl_mvm_set_default_unicast_key(struct ieee80211_hw *hw,
124 				     struct ieee80211_vif *vif, int idx)
125 {
126 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
127 
128 	mvmvif->tx_key_idx = idx;
129 }
130 
131 static void iwl_mvm_convert_p1k(u16 *p1k, __le16 *out)
132 {
133 	int i;
134 
135 	for (i = 0; i < IWL_P1K_SIZE; i++)
136 		out[i] = cpu_to_le16(p1k[i]);
137 }
138 
139 static const u8 *iwl_mvm_find_max_pn(struct ieee80211_key_conf *key,
140 				     struct iwl_mvm_key_pn *ptk_pn,
141 				     struct ieee80211_key_seq *seq,
142 				     int tid, int queues)
143 {
144 	const u8 *ret = seq->ccmp.pn;
145 	int i;
146 
147 	/* get the PN from mac80211, used on the default queue */
148 	ieee80211_get_key_rx_seq(key, tid, seq);
149 
150 	/* and use the internal data for the other queues */
151 	for (i = 1; i < queues; i++) {
152 		const u8 *tmp = ptk_pn->q[i].pn[tid];
153 
154 		if (memcmp(ret, tmp, IEEE80211_CCMP_PN_LEN) <= 0)
155 			ret = tmp;
156 	}
157 
158 	return ret;
159 }
160 
161 struct wowlan_key_data {
162 	struct iwl_wowlan_rsc_tsc_params_cmd *rsc_tsc;
163 	struct iwl_wowlan_tkip_params_cmd *tkip;
164 	bool error, use_rsc_tsc, use_tkip, configure_keys;
165 	int wep_key_idx;
166 };
167 
168 static void iwl_mvm_wowlan_program_keys(struct ieee80211_hw *hw,
169 					struct ieee80211_vif *vif,
170 					struct ieee80211_sta *sta,
171 					struct ieee80211_key_conf *key,
172 					void *_data)
173 {
174 	struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
175 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
176 	struct wowlan_key_data *data = _data;
177 	struct aes_sc *aes_sc, *aes_tx_sc = NULL;
178 	struct tkip_sc *tkip_sc, *tkip_tx_sc = NULL;
179 	struct iwl_p1k_cache *rx_p1ks;
180 	u8 *rx_mic_key;
181 	struct ieee80211_key_seq seq;
182 	u32 cur_rx_iv32 = 0;
183 	u16 p1k[IWL_P1K_SIZE];
184 	int ret, i;
185 
186 	switch (key->cipher) {
187 	case WLAN_CIPHER_SUITE_WEP40:
188 	case WLAN_CIPHER_SUITE_WEP104: { /* hack it for now */
189 		struct {
190 			struct iwl_mvm_wep_key_cmd wep_key_cmd;
191 			struct iwl_mvm_wep_key wep_key;
192 		} __packed wkc = {
193 			.wep_key_cmd.mac_id_n_color =
194 				cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
195 								mvmvif->color)),
196 			.wep_key_cmd.num_keys = 1,
197 			/* firmware sets STA_KEY_FLG_WEP_13BYTES */
198 			.wep_key_cmd.decryption_type = STA_KEY_FLG_WEP,
199 			.wep_key.key_index = key->keyidx,
200 			.wep_key.key_size = key->keylen,
201 		};
202 
203 		/*
204 		 * This will fail -- the key functions don't set support
205 		 * pairwise WEP keys. However, that's better than silently
206 		 * failing WoWLAN. Or maybe not?
207 		 */
208 		if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE)
209 			break;
210 
211 		memcpy(&wkc.wep_key.key[3], key->key, key->keylen);
212 		if (key->keyidx == mvmvif->tx_key_idx) {
213 			/* TX key must be at offset 0 */
214 			wkc.wep_key.key_offset = 0;
215 		} else {
216 			/* others start at 1 */
217 			data->wep_key_idx++;
218 			wkc.wep_key.key_offset = data->wep_key_idx;
219 		}
220 
221 		if (data->configure_keys) {
222 			mutex_lock(&mvm->mutex);
223 			ret = iwl_mvm_send_cmd_pdu(mvm, WEP_KEY, 0,
224 						   sizeof(wkc), &wkc);
225 			data->error = ret != 0;
226 
227 			mvm->ptk_ivlen = key->iv_len;
228 			mvm->ptk_icvlen = key->icv_len;
229 			mvm->gtk_ivlen = key->iv_len;
230 			mvm->gtk_icvlen = key->icv_len;
231 			mutex_unlock(&mvm->mutex);
232 		}
233 
234 		/* don't upload key again */
235 		return;
236 	}
237 	default:
238 		data->error = true;
239 		return;
240 	case WLAN_CIPHER_SUITE_AES_CMAC:
241 		/*
242 		 * Ignore CMAC keys -- the WoWLAN firmware doesn't support them
243 		 * but we also shouldn't abort suspend due to that. It does have
244 		 * support for the IGTK key renewal, but doesn't really use the
245 		 * IGTK for anything. This means we could spuriously wake up or
246 		 * be deauthenticated, but that was considered acceptable.
247 		 */
248 		return;
249 	case WLAN_CIPHER_SUITE_TKIP:
250 		if (sta) {
251 			u64 pn64;
252 
253 			tkip_sc = data->rsc_tsc->all_tsc_rsc.tkip.unicast_rsc;
254 			tkip_tx_sc = &data->rsc_tsc->all_tsc_rsc.tkip.tsc;
255 
256 			rx_p1ks = data->tkip->rx_uni;
257 
258 			pn64 = atomic64_read(&key->tx_pn);
259 			tkip_tx_sc->iv16 = cpu_to_le16(TKIP_PN_TO_IV16(pn64));
260 			tkip_tx_sc->iv32 = cpu_to_le32(TKIP_PN_TO_IV32(pn64));
261 
262 			ieee80211_get_tkip_p1k_iv(key, TKIP_PN_TO_IV32(pn64),
263 						  p1k);
264 			iwl_mvm_convert_p1k(p1k, data->tkip->tx.p1k);
265 
266 			memcpy(data->tkip->mic_keys.tx,
267 			       &key->key[NL80211_TKIP_DATA_OFFSET_TX_MIC_KEY],
268 			       IWL_MIC_KEY_SIZE);
269 
270 			rx_mic_key = data->tkip->mic_keys.rx_unicast;
271 		} else {
272 			tkip_sc =
273 				data->rsc_tsc->all_tsc_rsc.tkip.multicast_rsc;
274 			rx_p1ks = data->tkip->rx_multi;
275 			rx_mic_key = data->tkip->mic_keys.rx_mcast;
276 		}
277 
278 		/*
279 		 * For non-QoS this relies on the fact that both the uCode and
280 		 * mac80211 use TID 0 (as they need to to avoid replay attacks)
281 		 * for checking the IV in the frames.
282 		 */
283 		for (i = 0; i < IWL_NUM_RSC; i++) {
284 			ieee80211_get_key_rx_seq(key, i, &seq);
285 			tkip_sc[i].iv16 = cpu_to_le16(seq.tkip.iv16);
286 			tkip_sc[i].iv32 = cpu_to_le32(seq.tkip.iv32);
287 			/* wrapping isn't allowed, AP must rekey */
288 			if (seq.tkip.iv32 > cur_rx_iv32)
289 				cur_rx_iv32 = seq.tkip.iv32;
290 		}
291 
292 		ieee80211_get_tkip_rx_p1k(key, vif->bss_conf.bssid,
293 					  cur_rx_iv32, p1k);
294 		iwl_mvm_convert_p1k(p1k, rx_p1ks[0].p1k);
295 		ieee80211_get_tkip_rx_p1k(key, vif->bss_conf.bssid,
296 					  cur_rx_iv32 + 1, p1k);
297 		iwl_mvm_convert_p1k(p1k, rx_p1ks[1].p1k);
298 
299 		memcpy(rx_mic_key,
300 		       &key->key[NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY],
301 		       IWL_MIC_KEY_SIZE);
302 
303 		data->use_tkip = true;
304 		data->use_rsc_tsc = true;
305 		break;
306 	case WLAN_CIPHER_SUITE_CCMP:
307 		if (sta) {
308 			u64 pn64;
309 
310 			aes_sc = data->rsc_tsc->all_tsc_rsc.aes.unicast_rsc;
311 			aes_tx_sc = &data->rsc_tsc->all_tsc_rsc.aes.tsc;
312 
313 			pn64 = atomic64_read(&key->tx_pn);
314 			aes_tx_sc->pn = cpu_to_le64(pn64);
315 		} else {
316 			aes_sc = data->rsc_tsc->all_tsc_rsc.aes.multicast_rsc;
317 		}
318 
319 		/*
320 		 * For non-QoS this relies on the fact that both the uCode and
321 		 * mac80211/our RX code use TID 0 for checking the PN.
322 		 */
323 		if (sta && iwl_mvm_has_new_rx_api(mvm)) {
324 			struct iwl_mvm_sta *mvmsta;
325 			struct iwl_mvm_key_pn *ptk_pn;
326 			const u8 *pn;
327 
328 			mvmsta = iwl_mvm_sta_from_mac80211(sta);
329 			ptk_pn = rcu_dereference_protected(
330 						mvmsta->ptk_pn[key->keyidx],
331 						lockdep_is_held(&mvm->mutex));
332 			if (WARN_ON(!ptk_pn))
333 				break;
334 
335 			for (i = 0; i < IWL_MAX_TID_COUNT; i++) {
336 				pn = iwl_mvm_find_max_pn(key, ptk_pn, &seq, i,
337 						mvm->trans->num_rx_queues);
338 				aes_sc[i].pn = cpu_to_le64((u64)pn[5] |
339 							   ((u64)pn[4] << 8) |
340 							   ((u64)pn[3] << 16) |
341 							   ((u64)pn[2] << 24) |
342 							   ((u64)pn[1] << 32) |
343 							   ((u64)pn[0] << 40));
344 			}
345 		} else {
346 			for (i = 0; i < IWL_NUM_RSC; i++) {
347 				u8 *pn = seq.ccmp.pn;
348 
349 				ieee80211_get_key_rx_seq(key, i, &seq);
350 				aes_sc[i].pn = cpu_to_le64((u64)pn[5] |
351 							   ((u64)pn[4] << 8) |
352 							   ((u64)pn[3] << 16) |
353 							   ((u64)pn[2] << 24) |
354 							   ((u64)pn[1] << 32) |
355 							   ((u64)pn[0] << 40));
356 			}
357 		}
358 		data->use_rsc_tsc = true;
359 		break;
360 	}
361 
362 	if (data->configure_keys) {
363 		mutex_lock(&mvm->mutex);
364 		/*
365 		 * The D3 firmware hardcodes the key offset 0 as the key it
366 		 * uses to transmit packets to the AP, i.e. the PTK.
367 		 */
368 		if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) {
369 			mvm->ptk_ivlen = key->iv_len;
370 			mvm->ptk_icvlen = key->icv_len;
371 			ret = iwl_mvm_set_sta_key(mvm, vif, sta, key, 0);
372 		} else {
373 			/*
374 			 * firmware only supports TSC/RSC for a single key,
375 			 * so if there are multiple keep overwriting them
376 			 * with new ones -- this relies on mac80211 doing
377 			 * list_add_tail().
378 			 */
379 			mvm->gtk_ivlen = key->iv_len;
380 			mvm->gtk_icvlen = key->icv_len;
381 			ret = iwl_mvm_set_sta_key(mvm, vif, sta, key, 1);
382 		}
383 		mutex_unlock(&mvm->mutex);
384 		data->error = ret != 0;
385 	}
386 }
387 
388 static int iwl_mvm_send_patterns(struct iwl_mvm *mvm,
389 				 struct cfg80211_wowlan *wowlan)
390 {
391 	struct iwl_wowlan_patterns_cmd *pattern_cmd;
392 	struct iwl_host_cmd cmd = {
393 		.id = WOWLAN_PATTERNS,
394 		.dataflags[0] = IWL_HCMD_DFL_NOCOPY,
395 	};
396 	int i, err;
397 
398 	if (!wowlan->n_patterns)
399 		return 0;
400 
401 	cmd.len[0] = sizeof(*pattern_cmd) +
402 		wowlan->n_patterns * sizeof(struct iwl_wowlan_pattern);
403 
404 	pattern_cmd = kmalloc(cmd.len[0], GFP_KERNEL);
405 	if (!pattern_cmd)
406 		return -ENOMEM;
407 
408 	pattern_cmd->n_patterns = cpu_to_le32(wowlan->n_patterns);
409 
410 	for (i = 0; i < wowlan->n_patterns; i++) {
411 		int mask_len = DIV_ROUND_UP(wowlan->patterns[i].pattern_len, 8);
412 
413 		memcpy(&pattern_cmd->patterns[i].mask,
414 		       wowlan->patterns[i].mask, mask_len);
415 		memcpy(&pattern_cmd->patterns[i].pattern,
416 		       wowlan->patterns[i].pattern,
417 		       wowlan->patterns[i].pattern_len);
418 		pattern_cmd->patterns[i].mask_size = mask_len;
419 		pattern_cmd->patterns[i].pattern_size =
420 			wowlan->patterns[i].pattern_len;
421 	}
422 
423 	cmd.data[0] = pattern_cmd;
424 	err = iwl_mvm_send_cmd(mvm, &cmd);
425 	kfree(pattern_cmd);
426 	return err;
427 }
428 
429 static int iwl_mvm_d3_reprogram(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
430 				struct ieee80211_sta *ap_sta)
431 {
432 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
433 	struct ieee80211_chanctx_conf *ctx;
434 	u8 chains_static, chains_dynamic;
435 	struct cfg80211_chan_def chandef;
436 	int ret, i;
437 	struct iwl_binding_cmd_v1 binding_cmd = {};
438 	struct iwl_time_quota_cmd quota_cmd = {};
439 	struct iwl_time_quota_data *quota;
440 	u32 status;
441 
442 	if (WARN_ON_ONCE(iwl_mvm_is_cdb_supported(mvm)))
443 		return -EINVAL;
444 
445 	/* add back the PHY */
446 	if (WARN_ON(!mvmvif->phy_ctxt))
447 		return -EINVAL;
448 
449 	rcu_read_lock();
450 	ctx = rcu_dereference(vif->chanctx_conf);
451 	if (WARN_ON(!ctx)) {
452 		rcu_read_unlock();
453 		return -EINVAL;
454 	}
455 	chandef = ctx->def;
456 	chains_static = ctx->rx_chains_static;
457 	chains_dynamic = ctx->rx_chains_dynamic;
458 	rcu_read_unlock();
459 
460 	ret = iwl_mvm_phy_ctxt_add(mvm, mvmvif->phy_ctxt, &chandef,
461 				   chains_static, chains_dynamic);
462 	if (ret)
463 		return ret;
464 
465 	/* add back the MAC */
466 	mvmvif->uploaded = false;
467 
468 	if (WARN_ON(!vif->bss_conf.assoc))
469 		return -EINVAL;
470 
471 	ret = iwl_mvm_mac_ctxt_add(mvm, vif);
472 	if (ret)
473 		return ret;
474 
475 	/* add back binding - XXX refactor? */
476 	binding_cmd.id_and_color =
477 		cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
478 						mvmvif->phy_ctxt->color));
479 	binding_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD);
480 	binding_cmd.phy =
481 		cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
482 						mvmvif->phy_ctxt->color));
483 	binding_cmd.macs[0] = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
484 							      mvmvif->color));
485 	for (i = 1; i < MAX_MACS_IN_BINDING; i++)
486 		binding_cmd.macs[i] = cpu_to_le32(FW_CTXT_INVALID);
487 
488 	status = 0;
489 	ret = iwl_mvm_send_cmd_pdu_status(mvm, BINDING_CONTEXT_CMD,
490 					  IWL_BINDING_CMD_SIZE_V1, &binding_cmd,
491 					  &status);
492 	if (ret) {
493 		IWL_ERR(mvm, "Failed to add binding: %d\n", ret);
494 		return ret;
495 	}
496 
497 	if (status) {
498 		IWL_ERR(mvm, "Binding command failed: %u\n", status);
499 		return -EIO;
500 	}
501 
502 	ret = iwl_mvm_sta_send_to_fw(mvm, ap_sta, false, 0);
503 	if (ret)
504 		return ret;
505 	rcu_assign_pointer(mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], ap_sta);
506 
507 	ret = iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
508 	if (ret)
509 		return ret;
510 
511 	/* and some quota */
512 	quota = iwl_mvm_quota_cmd_get_quota(mvm, &quota_cmd, 0);
513 	quota->id_and_color =
514 		cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
515 						mvmvif->phy_ctxt->color));
516 	quota->quota = cpu_to_le32(IWL_MVM_MAX_QUOTA);
517 	quota->max_duration = cpu_to_le32(IWL_MVM_MAX_QUOTA);
518 
519 	for (i = 1; i < MAX_BINDINGS; i++) {
520 		quota = iwl_mvm_quota_cmd_get_quota(mvm, &quota_cmd, i);
521 		quota->id_and_color = cpu_to_le32(FW_CTXT_INVALID);
522 	}
523 
524 	ret = iwl_mvm_send_cmd_pdu(mvm, TIME_QUOTA_CMD, 0,
525 				   iwl_mvm_quota_cmd_size(mvm), &quota_cmd);
526 	if (ret)
527 		IWL_ERR(mvm, "Failed to send quota: %d\n", ret);
528 
529 	if (iwl_mvm_is_lar_supported(mvm) && iwl_mvm_init_fw_regd(mvm))
530 		IWL_ERR(mvm, "Failed to initialize D3 LAR information\n");
531 
532 	return 0;
533 }
534 
535 static int iwl_mvm_get_last_nonqos_seq(struct iwl_mvm *mvm,
536 				       struct ieee80211_vif *vif)
537 {
538 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
539 	struct iwl_nonqos_seq_query_cmd query_cmd = {
540 		.get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_GET),
541 		.mac_id_n_color =
542 			cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
543 							mvmvif->color)),
544 	};
545 	struct iwl_host_cmd cmd = {
546 		.id = NON_QOS_TX_COUNTER_CMD,
547 		.flags = CMD_WANT_SKB,
548 	};
549 	int err;
550 	u32 size;
551 
552 	cmd.data[0] = &query_cmd;
553 	cmd.len[0] = sizeof(query_cmd);
554 
555 	err = iwl_mvm_send_cmd(mvm, &cmd);
556 	if (err)
557 		return err;
558 
559 	size = iwl_rx_packet_payload_len(cmd.resp_pkt);
560 	if (size < sizeof(__le16)) {
561 		err = -EINVAL;
562 	} else {
563 		err = le16_to_cpup((__le16 *)cmd.resp_pkt->data);
564 		/* firmware returns next, not last-used seqno */
565 		err = (u16) (err - 0x10);
566 	}
567 
568 	iwl_free_resp(&cmd);
569 	return err;
570 }
571 
572 void iwl_mvm_set_last_nonqos_seq(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
573 {
574 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
575 	struct iwl_nonqos_seq_query_cmd query_cmd = {
576 		.get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_SET),
577 		.mac_id_n_color =
578 			cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
579 							mvmvif->color)),
580 		.value = cpu_to_le16(mvmvif->seqno),
581 	};
582 
583 	/* return if called during restart, not resume from D3 */
584 	if (!mvmvif->seqno_valid)
585 		return;
586 
587 	mvmvif->seqno_valid = false;
588 
589 	if (iwl_mvm_send_cmd_pdu(mvm, NON_QOS_TX_COUNTER_CMD, 0,
590 				 sizeof(query_cmd), &query_cmd))
591 		IWL_ERR(mvm, "failed to set non-QoS seqno\n");
592 }
593 
594 static int iwl_mvm_switch_to_d3(struct iwl_mvm *mvm)
595 {
596 	iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_REGULAR, true);
597 
598 	iwl_mvm_stop_device(mvm);
599 	/*
600 	 * Set the HW restart bit -- this is mostly true as we're
601 	 * going to load new firmware and reprogram that, though
602 	 * the reprogramming is going to be manual to avoid adding
603 	 * all the MACs that aren't support.
604 	 * We don't have to clear up everything though because the
605 	 * reprogramming is manual. When we resume, we'll actually
606 	 * go through a proper restart sequence again to switch
607 	 * back to the runtime firmware image.
608 	 */
609 	set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
610 
611 	/* the fw is reset, so all the keys are cleared */
612 	memset(mvm->fw_key_table, 0, sizeof(mvm->fw_key_table));
613 
614 	mvm->ptk_ivlen = 0;
615 	mvm->ptk_icvlen = 0;
616 	mvm->ptk_ivlen = 0;
617 	mvm->ptk_icvlen = 0;
618 
619 	return iwl_mvm_load_d3_fw(mvm);
620 }
621 
622 static int
623 iwl_mvm_get_wowlan_config(struct iwl_mvm *mvm,
624 			  struct cfg80211_wowlan *wowlan,
625 			  struct iwl_wowlan_config_cmd *wowlan_config_cmd,
626 			  struct ieee80211_vif *vif, struct iwl_mvm_vif *mvmvif,
627 			  struct ieee80211_sta *ap_sta)
628 {
629 	int ret;
630 	struct iwl_mvm_sta *mvm_ap_sta = iwl_mvm_sta_from_mac80211(ap_sta);
631 
632 	/* TODO: wowlan_config_cmd->wowlan_ba_teardown_tids */
633 
634 	wowlan_config_cmd->is_11n_connection =
635 					ap_sta->ht_cap.ht_supported;
636 	wowlan_config_cmd->flags = ENABLE_L3_FILTERING |
637 		ENABLE_NBNS_FILTERING | ENABLE_DHCP_FILTERING;
638 
639 	/* Query the last used seqno and set it */
640 	ret = iwl_mvm_get_last_nonqos_seq(mvm, vif);
641 	if (ret < 0)
642 		return ret;
643 
644 	wowlan_config_cmd->non_qos_seq = cpu_to_le16(ret);
645 
646 	iwl_mvm_set_wowlan_qos_seq(mvm_ap_sta, wowlan_config_cmd);
647 
648 	if (wowlan->disconnect)
649 		wowlan_config_cmd->wakeup_filter |=
650 			cpu_to_le32(IWL_WOWLAN_WAKEUP_BEACON_MISS |
651 				    IWL_WOWLAN_WAKEUP_LINK_CHANGE);
652 	if (wowlan->magic_pkt)
653 		wowlan_config_cmd->wakeup_filter |=
654 			cpu_to_le32(IWL_WOWLAN_WAKEUP_MAGIC_PACKET);
655 	if (wowlan->gtk_rekey_failure)
656 		wowlan_config_cmd->wakeup_filter |=
657 			cpu_to_le32(IWL_WOWLAN_WAKEUP_GTK_REKEY_FAIL);
658 	if (wowlan->eap_identity_req)
659 		wowlan_config_cmd->wakeup_filter |=
660 			cpu_to_le32(IWL_WOWLAN_WAKEUP_EAP_IDENT_REQ);
661 	if (wowlan->four_way_handshake)
662 		wowlan_config_cmd->wakeup_filter |=
663 			cpu_to_le32(IWL_WOWLAN_WAKEUP_4WAY_HANDSHAKE);
664 	if (wowlan->n_patterns)
665 		wowlan_config_cmd->wakeup_filter |=
666 			cpu_to_le32(IWL_WOWLAN_WAKEUP_PATTERN_MATCH);
667 
668 	if (wowlan->rfkill_release)
669 		wowlan_config_cmd->wakeup_filter |=
670 			cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT);
671 
672 	if (wowlan->tcp) {
673 		/*
674 		 * Set the "link change" (really "link lost") flag as well
675 		 * since that implies losing the TCP connection.
676 		 */
677 		wowlan_config_cmd->wakeup_filter |=
678 			cpu_to_le32(IWL_WOWLAN_WAKEUP_REMOTE_LINK_LOSS |
679 				    IWL_WOWLAN_WAKEUP_REMOTE_SIGNATURE_TABLE |
680 				    IWL_WOWLAN_WAKEUP_REMOTE_WAKEUP_PACKET |
681 				    IWL_WOWLAN_WAKEUP_LINK_CHANGE);
682 	}
683 
684 	if (wowlan->any) {
685 		wowlan_config_cmd->wakeup_filter |=
686 			cpu_to_le32(IWL_WOWLAN_WAKEUP_BEACON_MISS |
687 				    IWL_WOWLAN_WAKEUP_LINK_CHANGE |
688 				    IWL_WOWLAN_WAKEUP_RX_FRAME |
689 				    IWL_WOWLAN_WAKEUP_BCN_FILTERING);
690 	}
691 
692 	return 0;
693 }
694 
695 static void
696 iwl_mvm_iter_d0i3_ap_keys(struct iwl_mvm *mvm,
697 			  struct ieee80211_vif *vif,
698 			  void (*iter)(struct ieee80211_hw *hw,
699 				       struct ieee80211_vif *vif,
700 				       struct ieee80211_sta *sta,
701 				       struct ieee80211_key_conf *key,
702 				       void *data),
703 			  void *data)
704 {
705 	struct ieee80211_sta *ap_sta;
706 
707 	rcu_read_lock();
708 
709 	ap_sta = rcu_dereference(mvm->fw_id_to_mac_id[mvm->d0i3_ap_sta_id]);
710 	if (IS_ERR_OR_NULL(ap_sta))
711 		goto out;
712 
713 	ieee80211_iter_keys_rcu(mvm->hw, vif, iter, data);
714 out:
715 	rcu_read_unlock();
716 }
717 
718 int iwl_mvm_wowlan_config_key_params(struct iwl_mvm *mvm,
719 				     struct ieee80211_vif *vif,
720 				     bool d0i3,
721 				     u32 cmd_flags)
722 {
723 	struct iwl_wowlan_kek_kck_material_cmd kek_kck_cmd = {};
724 	struct iwl_wowlan_tkip_params_cmd tkip_cmd = {};
725 	struct wowlan_key_data key_data = {
726 		.configure_keys = !d0i3,
727 		.use_rsc_tsc = false,
728 		.tkip = &tkip_cmd,
729 		.use_tkip = false,
730 	};
731 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
732 	int ret;
733 
734 	key_data.rsc_tsc = kzalloc(sizeof(*key_data.rsc_tsc), GFP_KERNEL);
735 	if (!key_data.rsc_tsc)
736 		return -ENOMEM;
737 
738 	/*
739 	 * if we have to configure keys, call ieee80211_iter_keys(),
740 	 * as we need non-atomic context in order to take the
741 	 * required locks.
742 	 * for the d0i3 we can't use ieee80211_iter_keys(), as
743 	 * taking (almost) any mutex might result in deadlock.
744 	 */
745 	if (!d0i3) {
746 		/*
747 		 * Note that currently we don't propagate cmd_flags
748 		 * to the iterator. In case of key_data.configure_keys,
749 		 * all the configured commands are SYNC, and
750 		 * iwl_mvm_wowlan_program_keys() will take care of
751 		 * locking/unlocking mvm->mutex.
752 		 */
753 		ieee80211_iter_keys(mvm->hw, vif,
754 				    iwl_mvm_wowlan_program_keys,
755 				    &key_data);
756 	} else {
757 		iwl_mvm_iter_d0i3_ap_keys(mvm, vif,
758 					  iwl_mvm_wowlan_program_keys,
759 					  &key_data);
760 	}
761 
762 	if (key_data.error) {
763 		ret = -EIO;
764 		goto out;
765 	}
766 
767 	if (key_data.use_rsc_tsc) {
768 		ret = iwl_mvm_send_cmd_pdu(mvm,
769 					   WOWLAN_TSC_RSC_PARAM, cmd_flags,
770 					   sizeof(*key_data.rsc_tsc),
771 					   key_data.rsc_tsc);
772 		if (ret)
773 			goto out;
774 	}
775 
776 	if (key_data.use_tkip &&
777 	    !fw_has_api(&mvm->fw->ucode_capa,
778 			IWL_UCODE_TLV_API_TKIP_MIC_KEYS)) {
779 		ret = iwl_mvm_send_cmd_pdu(mvm,
780 					   WOWLAN_TKIP_PARAM,
781 					   cmd_flags, sizeof(tkip_cmd),
782 					   &tkip_cmd);
783 		if (ret)
784 			goto out;
785 	}
786 
787 	/* configure rekey data only if offloaded rekey is supported (d3) */
788 	if (mvmvif->rekey_data.valid && !d0i3) {
789 		memset(&kek_kck_cmd, 0, sizeof(kek_kck_cmd));
790 		memcpy(kek_kck_cmd.kck, mvmvif->rekey_data.kck,
791 		       NL80211_KCK_LEN);
792 		kek_kck_cmd.kck_len = cpu_to_le16(NL80211_KCK_LEN);
793 		memcpy(kek_kck_cmd.kek, mvmvif->rekey_data.kek,
794 		       NL80211_KEK_LEN);
795 		kek_kck_cmd.kek_len = cpu_to_le16(NL80211_KEK_LEN);
796 		kek_kck_cmd.replay_ctr = mvmvif->rekey_data.replay_ctr;
797 
798 		ret = iwl_mvm_send_cmd_pdu(mvm,
799 					   WOWLAN_KEK_KCK_MATERIAL, cmd_flags,
800 					   sizeof(kek_kck_cmd),
801 					   &kek_kck_cmd);
802 		if (ret)
803 			goto out;
804 	}
805 	ret = 0;
806 out:
807 	kfree(key_data.rsc_tsc);
808 	return ret;
809 }
810 
811 static int
812 iwl_mvm_wowlan_config(struct iwl_mvm *mvm,
813 		      struct cfg80211_wowlan *wowlan,
814 		      struct iwl_wowlan_config_cmd *wowlan_config_cmd,
815 		      struct ieee80211_vif *vif, struct iwl_mvm_vif *mvmvif,
816 		      struct ieee80211_sta *ap_sta)
817 {
818 	int ret;
819 	bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
820 					 IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
821 
822 	if (!unified_image) {
823 		ret = iwl_mvm_switch_to_d3(mvm);
824 		if (ret)
825 			return ret;
826 
827 		ret = iwl_mvm_d3_reprogram(mvm, vif, ap_sta);
828 		if (ret)
829 			return ret;
830 	}
831 
832 	if (!iwlwifi_mod_params.swcrypto) {
833 		/*
834 		 * This needs to be unlocked due to lock ordering
835 		 * constraints. Since we're in the suspend path
836 		 * that isn't really a problem though.
837 		 */
838 		mutex_unlock(&mvm->mutex);
839 		ret = iwl_mvm_wowlan_config_key_params(mvm, vif, false,
840 						       CMD_ASYNC);
841 		mutex_lock(&mvm->mutex);
842 		if (ret)
843 			return ret;
844 	}
845 
846 	ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION, 0,
847 				   sizeof(*wowlan_config_cmd),
848 				   wowlan_config_cmd);
849 	if (ret)
850 		return ret;
851 
852 	ret = iwl_mvm_send_patterns(mvm, wowlan);
853 	if (ret)
854 		return ret;
855 
856 	return iwl_mvm_send_proto_offload(mvm, vif, false, true, 0);
857 }
858 
859 static int
860 iwl_mvm_netdetect_config(struct iwl_mvm *mvm,
861 			 struct cfg80211_wowlan *wowlan,
862 			 struct cfg80211_sched_scan_request *nd_config,
863 			 struct ieee80211_vif *vif)
864 {
865 	struct iwl_wowlan_config_cmd wowlan_config_cmd = {};
866 	int ret;
867 	bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
868 					 IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
869 
870 	if (!unified_image) {
871 		ret = iwl_mvm_switch_to_d3(mvm);
872 		if (ret)
873 			return ret;
874 	} else {
875 		/* In theory, we wouldn't have to stop a running sched
876 		 * scan in order to start another one (for
877 		 * net-detect).  But in practice this doesn't seem to
878 		 * work properly, so stop any running sched_scan now.
879 		 */
880 		ret = iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_SCHED, true);
881 		if (ret)
882 			return ret;
883 	}
884 
885 	/* rfkill release can be either for wowlan or netdetect */
886 	if (wowlan->rfkill_release)
887 		wowlan_config_cmd.wakeup_filter |=
888 			cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT);
889 
890 	ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION, 0,
891 				   sizeof(wowlan_config_cmd),
892 				   &wowlan_config_cmd);
893 	if (ret)
894 		return ret;
895 
896 	ret = iwl_mvm_sched_scan_start(mvm, vif, nd_config, &mvm->nd_ies,
897 				       IWL_MVM_SCAN_NETDETECT);
898 	if (ret)
899 		return ret;
900 
901 	if (WARN_ON(mvm->nd_match_sets || mvm->nd_channels))
902 		return -EBUSY;
903 
904 	/* save the sched scan matchsets... */
905 	if (nd_config->n_match_sets) {
906 		mvm->nd_match_sets = kmemdup(nd_config->match_sets,
907 					     sizeof(*nd_config->match_sets) *
908 					     nd_config->n_match_sets,
909 					     GFP_KERNEL);
910 		if (mvm->nd_match_sets)
911 			mvm->n_nd_match_sets = nd_config->n_match_sets;
912 	}
913 
914 	/* ...and the sched scan channels for later reporting */
915 	mvm->nd_channels = kmemdup(nd_config->channels,
916 				   sizeof(*nd_config->channels) *
917 				   nd_config->n_channels,
918 				   GFP_KERNEL);
919 	if (mvm->nd_channels)
920 		mvm->n_nd_channels = nd_config->n_channels;
921 
922 	return 0;
923 }
924 
925 static void iwl_mvm_free_nd(struct iwl_mvm *mvm)
926 {
927 	kfree(mvm->nd_match_sets);
928 	mvm->nd_match_sets = NULL;
929 	mvm->n_nd_match_sets = 0;
930 	kfree(mvm->nd_channels);
931 	mvm->nd_channels = NULL;
932 	mvm->n_nd_channels = 0;
933 }
934 
935 static int __iwl_mvm_suspend(struct ieee80211_hw *hw,
936 			     struct cfg80211_wowlan *wowlan,
937 			     bool test)
938 {
939 	struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
940 	struct ieee80211_vif *vif = NULL;
941 	struct iwl_mvm_vif *mvmvif = NULL;
942 	struct ieee80211_sta *ap_sta = NULL;
943 	struct iwl_d3_manager_config d3_cfg_cmd_data = {
944 		/*
945 		 * Program the minimum sleep time to 10 seconds, as many
946 		 * platforms have issues processing a wakeup signal while
947 		 * still being in the process of suspending.
948 		 */
949 		.min_sleep_time = cpu_to_le32(10 * 1000 * 1000),
950 	};
951 	struct iwl_host_cmd d3_cfg_cmd = {
952 		.id = D3_CONFIG_CMD,
953 		.flags = CMD_WANT_SKB,
954 		.data[0] = &d3_cfg_cmd_data,
955 		.len[0] = sizeof(d3_cfg_cmd_data),
956 	};
957 	int ret;
958 	int len __maybe_unused;
959 	bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
960 					 IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
961 
962 	if (!wowlan) {
963 		/*
964 		 * mac80211 shouldn't get here, but for D3 test
965 		 * it doesn't warrant a warning
966 		 */
967 		WARN_ON(!test);
968 		return -EINVAL;
969 	}
970 
971 	mutex_lock(&mvm->mutex);
972 
973 	vif = iwl_mvm_get_bss_vif(mvm);
974 	if (IS_ERR_OR_NULL(vif)) {
975 		ret = 1;
976 		goto out_noreset;
977 	}
978 
979 	mvmvif = iwl_mvm_vif_from_mac80211(vif);
980 
981 	if (mvmvif->ap_sta_id == IWL_MVM_INVALID_STA) {
982 		/* if we're not associated, this must be netdetect */
983 		if (!wowlan->nd_config) {
984 			ret = 1;
985 			goto out_noreset;
986 		}
987 
988 		ret = iwl_mvm_netdetect_config(
989 			mvm, wowlan, wowlan->nd_config, vif);
990 		if (ret)
991 			goto out;
992 
993 		mvm->net_detect = true;
994 	} else {
995 		struct iwl_wowlan_config_cmd wowlan_config_cmd = {};
996 
997 		ap_sta = rcu_dereference_protected(
998 			mvm->fw_id_to_mac_id[mvmvif->ap_sta_id],
999 			lockdep_is_held(&mvm->mutex));
1000 		if (IS_ERR_OR_NULL(ap_sta)) {
1001 			ret = -EINVAL;
1002 			goto out_noreset;
1003 		}
1004 
1005 		ret = iwl_mvm_get_wowlan_config(mvm, wowlan, &wowlan_config_cmd,
1006 						vif, mvmvif, ap_sta);
1007 		if (ret)
1008 			goto out_noreset;
1009 		ret = iwl_mvm_wowlan_config(mvm, wowlan, &wowlan_config_cmd,
1010 					    vif, mvmvif, ap_sta);
1011 		if (ret)
1012 			goto out;
1013 
1014 		mvm->net_detect = false;
1015 	}
1016 
1017 	ret = iwl_mvm_power_update_device(mvm);
1018 	if (ret)
1019 		goto out;
1020 
1021 	ret = iwl_mvm_power_update_mac(mvm);
1022 	if (ret)
1023 		goto out;
1024 
1025 #ifdef CONFIG_IWLWIFI_DEBUGFS
1026 	if (mvm->d3_wake_sysassert)
1027 		d3_cfg_cmd_data.wakeup_flags |=
1028 			cpu_to_le32(IWL_WAKEUP_D3_CONFIG_FW_ERROR);
1029 #endif
1030 
1031 	/*
1032 	 * TODO: this is needed because the firmware is not stopping
1033 	 * the recording automatically before entering D3.  This can
1034 	 * be removed once the FW starts doing that.
1035 	 */
1036 	_iwl_fw_dbg_stop_recording(mvm->fwrt.trans, NULL);
1037 
1038 	/* must be last -- this switches firmware state */
1039 	ret = iwl_mvm_send_cmd(mvm, &d3_cfg_cmd);
1040 	if (ret)
1041 		goto out;
1042 #ifdef CONFIG_IWLWIFI_DEBUGFS
1043 	len = iwl_rx_packet_payload_len(d3_cfg_cmd.resp_pkt);
1044 	if (len >= sizeof(u32)) {
1045 		mvm->d3_test_pme_ptr =
1046 			le32_to_cpup((__le32 *)d3_cfg_cmd.resp_pkt->data);
1047 	}
1048 #endif
1049 	iwl_free_resp(&d3_cfg_cmd);
1050 
1051 	clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1052 
1053 	iwl_trans_d3_suspend(mvm->trans, test, !unified_image);
1054  out:
1055 	if (ret < 0) {
1056 		iwl_mvm_free_nd(mvm);
1057 
1058 		if (!unified_image) {
1059 			iwl_mvm_ref(mvm, IWL_MVM_REF_UCODE_DOWN);
1060 			if (mvm->fw_restart > 0) {
1061 				mvm->fw_restart--;
1062 				ieee80211_restart_hw(mvm->hw);
1063 			}
1064 		}
1065 	}
1066  out_noreset:
1067 	mutex_unlock(&mvm->mutex);
1068 
1069 	return ret;
1070 }
1071 
1072 static int iwl_mvm_enter_d0i3_sync(struct iwl_mvm *mvm)
1073 {
1074 	struct iwl_notification_wait wait_d3;
1075 	static const u16 d3_notif[] = { D3_CONFIG_CMD };
1076 	int ret;
1077 
1078 	iwl_init_notification_wait(&mvm->notif_wait, &wait_d3,
1079 				   d3_notif, ARRAY_SIZE(d3_notif),
1080 				   NULL, NULL);
1081 
1082 	ret = iwl_mvm_enter_d0i3(mvm->hw->priv);
1083 	if (ret)
1084 		goto remove_notif;
1085 
1086 	ret = iwl_wait_notification(&mvm->notif_wait, &wait_d3, HZ);
1087 	WARN_ON_ONCE(ret);
1088 	return ret;
1089 
1090 remove_notif:
1091 	iwl_remove_notification(&mvm->notif_wait, &wait_d3);
1092 	return ret;
1093 }
1094 
1095 int iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan)
1096 {
1097 	struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1098 	struct iwl_trans *trans = mvm->trans;
1099 	int ret;
1100 
1101 	/* make sure the d0i3 exit work is not pending */
1102 	flush_work(&mvm->d0i3_exit_work);
1103 	iwl_mvm_pause_tcm(mvm, true);
1104 
1105 	iwl_fw_runtime_suspend(&mvm->fwrt);
1106 
1107 	ret = iwl_trans_suspend(trans);
1108 	if (ret)
1109 		return ret;
1110 
1111 	if (wowlan->any) {
1112 		trans->system_pm_mode = IWL_PLAT_PM_MODE_D0I3;
1113 
1114 		if (iwl_mvm_enter_d0i3_on_suspend(mvm)) {
1115 			ret = iwl_mvm_enter_d0i3_sync(mvm);
1116 
1117 			if (ret)
1118 				return ret;
1119 		}
1120 
1121 		mutex_lock(&mvm->d0i3_suspend_mutex);
1122 		__set_bit(D0I3_DEFER_WAKEUP, &mvm->d0i3_suspend_flags);
1123 		mutex_unlock(&mvm->d0i3_suspend_mutex);
1124 
1125 		iwl_trans_d3_suspend(trans, false, false);
1126 
1127 		return 0;
1128 	}
1129 
1130 	trans->system_pm_mode = IWL_PLAT_PM_MODE_D3;
1131 
1132 	return __iwl_mvm_suspend(hw, wowlan, false);
1133 }
1134 
1135 /* converted data from the different status responses */
1136 struct iwl_wowlan_status_data {
1137 	u16 pattern_number;
1138 	u16 qos_seq_ctr[8];
1139 	u32 wakeup_reasons;
1140 	u32 wake_packet_length;
1141 	u32 wake_packet_bufsize;
1142 	const u8 *wake_packet;
1143 };
1144 
1145 static void iwl_mvm_report_wakeup_reasons(struct iwl_mvm *mvm,
1146 					  struct ieee80211_vif *vif,
1147 					  struct iwl_wowlan_status_data *status)
1148 {
1149 	struct sk_buff *pkt = NULL;
1150 	struct cfg80211_wowlan_wakeup wakeup = {
1151 		.pattern_idx = -1,
1152 	};
1153 	struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup;
1154 	u32 reasons = status->wakeup_reasons;
1155 
1156 	if (reasons == IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS) {
1157 		wakeup_report = NULL;
1158 		goto report;
1159 	}
1160 
1161 	pm_wakeup_event(mvm->dev, 0);
1162 
1163 	if (reasons & IWL_WOWLAN_WAKEUP_BY_MAGIC_PACKET)
1164 		wakeup.magic_pkt = true;
1165 
1166 	if (reasons & IWL_WOWLAN_WAKEUP_BY_PATTERN)
1167 		wakeup.pattern_idx =
1168 			status->pattern_number;
1169 
1170 	if (reasons & (IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON |
1171 		       IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH))
1172 		wakeup.disconnect = true;
1173 
1174 	if (reasons & IWL_WOWLAN_WAKEUP_BY_GTK_REKEY_FAILURE)
1175 		wakeup.gtk_rekey_failure = true;
1176 
1177 	if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED)
1178 		wakeup.rfkill_release = true;
1179 
1180 	if (reasons & IWL_WOWLAN_WAKEUP_BY_EAPOL_REQUEST)
1181 		wakeup.eap_identity_req = true;
1182 
1183 	if (reasons & IWL_WOWLAN_WAKEUP_BY_FOUR_WAY_HANDSHAKE)
1184 		wakeup.four_way_handshake = true;
1185 
1186 	if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_LINK_LOSS)
1187 		wakeup.tcp_connlost = true;
1188 
1189 	if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_SIGNATURE_TABLE)
1190 		wakeup.tcp_nomoretokens = true;
1191 
1192 	if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_WAKEUP_PACKET)
1193 		wakeup.tcp_match = true;
1194 
1195 	if (status->wake_packet_bufsize) {
1196 		int pktsize = status->wake_packet_bufsize;
1197 		int pktlen = status->wake_packet_length;
1198 		const u8 *pktdata = status->wake_packet;
1199 		struct ieee80211_hdr *hdr = (void *)pktdata;
1200 		int truncated = pktlen - pktsize;
1201 
1202 		/* this would be a firmware bug */
1203 		if (WARN_ON_ONCE(truncated < 0))
1204 			truncated = 0;
1205 
1206 		if (ieee80211_is_data(hdr->frame_control)) {
1207 			int hdrlen = ieee80211_hdrlen(hdr->frame_control);
1208 			int ivlen = 0, icvlen = 4; /* also FCS */
1209 
1210 			pkt = alloc_skb(pktsize, GFP_KERNEL);
1211 			if (!pkt)
1212 				goto report;
1213 
1214 			skb_put_data(pkt, pktdata, hdrlen);
1215 			pktdata += hdrlen;
1216 			pktsize -= hdrlen;
1217 
1218 			if (ieee80211_has_protected(hdr->frame_control)) {
1219 				/*
1220 				 * This is unlocked and using gtk_i(c)vlen,
1221 				 * but since everything is under RTNL still
1222 				 * that's not really a problem - changing
1223 				 * it would be difficult.
1224 				 */
1225 				if (is_multicast_ether_addr(hdr->addr1)) {
1226 					ivlen = mvm->gtk_ivlen;
1227 					icvlen += mvm->gtk_icvlen;
1228 				} else {
1229 					ivlen = mvm->ptk_ivlen;
1230 					icvlen += mvm->ptk_icvlen;
1231 				}
1232 			}
1233 
1234 			/* if truncated, FCS/ICV is (partially) gone */
1235 			if (truncated >= icvlen) {
1236 				icvlen = 0;
1237 				truncated -= icvlen;
1238 			} else {
1239 				icvlen -= truncated;
1240 				truncated = 0;
1241 			}
1242 
1243 			pktsize -= ivlen + icvlen;
1244 			pktdata += ivlen;
1245 
1246 			skb_put_data(pkt, pktdata, pktsize);
1247 
1248 			if (ieee80211_data_to_8023(pkt, vif->addr, vif->type))
1249 				goto report;
1250 			wakeup.packet = pkt->data;
1251 			wakeup.packet_present_len = pkt->len;
1252 			wakeup.packet_len = pkt->len - truncated;
1253 			wakeup.packet_80211 = false;
1254 		} else {
1255 			int fcslen = 4;
1256 
1257 			if (truncated >= 4) {
1258 				truncated -= 4;
1259 				fcslen = 0;
1260 			} else {
1261 				fcslen -= truncated;
1262 				truncated = 0;
1263 			}
1264 			pktsize -= fcslen;
1265 			wakeup.packet = status->wake_packet;
1266 			wakeup.packet_present_len = pktsize;
1267 			wakeup.packet_len = pktlen - truncated;
1268 			wakeup.packet_80211 = true;
1269 		}
1270 	}
1271 
1272  report:
1273 	ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL);
1274 	kfree_skb(pkt);
1275 }
1276 
1277 static void iwl_mvm_aes_sc_to_seq(struct aes_sc *sc,
1278 				  struct ieee80211_key_seq *seq)
1279 {
1280 	u64 pn;
1281 
1282 	pn = le64_to_cpu(sc->pn);
1283 	seq->ccmp.pn[0] = pn >> 40;
1284 	seq->ccmp.pn[1] = pn >> 32;
1285 	seq->ccmp.pn[2] = pn >> 24;
1286 	seq->ccmp.pn[3] = pn >> 16;
1287 	seq->ccmp.pn[4] = pn >> 8;
1288 	seq->ccmp.pn[5] = pn;
1289 }
1290 
1291 static void iwl_mvm_tkip_sc_to_seq(struct tkip_sc *sc,
1292 				   struct ieee80211_key_seq *seq)
1293 {
1294 	seq->tkip.iv32 = le32_to_cpu(sc->iv32);
1295 	seq->tkip.iv16 = le16_to_cpu(sc->iv16);
1296 }
1297 
1298 static void iwl_mvm_set_aes_rx_seq(struct iwl_mvm *mvm, struct aes_sc *scs,
1299 				   struct ieee80211_sta *sta,
1300 				   struct ieee80211_key_conf *key)
1301 {
1302 	int tid;
1303 
1304 	BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS);
1305 
1306 	if (sta && iwl_mvm_has_new_rx_api(mvm)) {
1307 		struct iwl_mvm_sta *mvmsta;
1308 		struct iwl_mvm_key_pn *ptk_pn;
1309 
1310 		mvmsta = iwl_mvm_sta_from_mac80211(sta);
1311 
1312 		ptk_pn = rcu_dereference_protected(mvmsta->ptk_pn[key->keyidx],
1313 						   lockdep_is_held(&mvm->mutex));
1314 		if (WARN_ON(!ptk_pn))
1315 			return;
1316 
1317 		for (tid = 0; tid < IWL_MAX_TID_COUNT; tid++) {
1318 			struct ieee80211_key_seq seq = {};
1319 			int i;
1320 
1321 			iwl_mvm_aes_sc_to_seq(&scs[tid], &seq);
1322 			ieee80211_set_key_rx_seq(key, tid, &seq);
1323 			for (i = 1; i < mvm->trans->num_rx_queues; i++)
1324 				memcpy(ptk_pn->q[i].pn[tid],
1325 				       seq.ccmp.pn, IEEE80211_CCMP_PN_LEN);
1326 		}
1327 	} else {
1328 		for (tid = 0; tid < IWL_NUM_RSC; tid++) {
1329 			struct ieee80211_key_seq seq = {};
1330 
1331 			iwl_mvm_aes_sc_to_seq(&scs[tid], &seq);
1332 			ieee80211_set_key_rx_seq(key, tid, &seq);
1333 		}
1334 	}
1335 }
1336 
1337 static void iwl_mvm_set_tkip_rx_seq(struct tkip_sc *scs,
1338 				    struct ieee80211_key_conf *key)
1339 {
1340 	int tid;
1341 
1342 	BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS);
1343 
1344 	for (tid = 0; tid < IWL_NUM_RSC; tid++) {
1345 		struct ieee80211_key_seq seq = {};
1346 
1347 		iwl_mvm_tkip_sc_to_seq(&scs[tid], &seq);
1348 		ieee80211_set_key_rx_seq(key, tid, &seq);
1349 	}
1350 }
1351 
1352 static void iwl_mvm_set_key_rx_seq(struct iwl_mvm *mvm,
1353 				   struct ieee80211_key_conf *key,
1354 				   struct iwl_wowlan_status *status)
1355 {
1356 	union iwl_all_tsc_rsc *rsc = &status->gtk[0].rsc.all_tsc_rsc;
1357 
1358 	switch (key->cipher) {
1359 	case WLAN_CIPHER_SUITE_CCMP:
1360 		iwl_mvm_set_aes_rx_seq(mvm, rsc->aes.multicast_rsc, NULL, key);
1361 		break;
1362 	case WLAN_CIPHER_SUITE_TKIP:
1363 		iwl_mvm_set_tkip_rx_seq(rsc->tkip.multicast_rsc, key);
1364 		break;
1365 	default:
1366 		WARN_ON(1);
1367 	}
1368 }
1369 
1370 struct iwl_mvm_d3_gtk_iter_data {
1371 	struct iwl_mvm *mvm;
1372 	struct iwl_wowlan_status *status;
1373 	void *last_gtk;
1374 	u32 cipher;
1375 	bool find_phase, unhandled_cipher;
1376 	int num_keys;
1377 };
1378 
1379 static void iwl_mvm_d3_update_keys(struct ieee80211_hw *hw,
1380 				   struct ieee80211_vif *vif,
1381 				   struct ieee80211_sta *sta,
1382 				   struct ieee80211_key_conf *key,
1383 				   void *_data)
1384 {
1385 	struct iwl_mvm_d3_gtk_iter_data *data = _data;
1386 
1387 	if (data->unhandled_cipher)
1388 		return;
1389 
1390 	switch (key->cipher) {
1391 	case WLAN_CIPHER_SUITE_WEP40:
1392 	case WLAN_CIPHER_SUITE_WEP104:
1393 		/* ignore WEP completely, nothing to do */
1394 		return;
1395 	case WLAN_CIPHER_SUITE_CCMP:
1396 	case WLAN_CIPHER_SUITE_TKIP:
1397 		/* we support these */
1398 		break;
1399 	default:
1400 		/* everything else (even CMAC for MFP) - disconnect from AP */
1401 		data->unhandled_cipher = true;
1402 		return;
1403 	}
1404 
1405 	data->num_keys++;
1406 
1407 	/*
1408 	 * pairwise key - update sequence counters only;
1409 	 * note that this assumes no TDLS sessions are active
1410 	 */
1411 	if (sta) {
1412 		struct ieee80211_key_seq seq = {};
1413 		union iwl_all_tsc_rsc *sc =
1414 			&data->status->gtk[0].rsc.all_tsc_rsc;
1415 
1416 		if (data->find_phase)
1417 			return;
1418 
1419 		switch (key->cipher) {
1420 		case WLAN_CIPHER_SUITE_CCMP:
1421 			iwl_mvm_set_aes_rx_seq(data->mvm, sc->aes.unicast_rsc,
1422 					       sta, key);
1423 			atomic64_set(&key->tx_pn, le64_to_cpu(sc->aes.tsc.pn));
1424 			break;
1425 		case WLAN_CIPHER_SUITE_TKIP:
1426 			iwl_mvm_tkip_sc_to_seq(&sc->tkip.tsc, &seq);
1427 			iwl_mvm_set_tkip_rx_seq(sc->tkip.unicast_rsc, key);
1428 			atomic64_set(&key->tx_pn,
1429 				     (u64)seq.tkip.iv16 |
1430 				     ((u64)seq.tkip.iv32 << 16));
1431 			break;
1432 		}
1433 
1434 		/* that's it for this key */
1435 		return;
1436 	}
1437 
1438 	if (data->find_phase) {
1439 		data->last_gtk = key;
1440 		data->cipher = key->cipher;
1441 		return;
1442 	}
1443 
1444 	if (data->status->num_of_gtk_rekeys)
1445 		ieee80211_remove_key(key);
1446 	else if (data->last_gtk == key)
1447 		iwl_mvm_set_key_rx_seq(data->mvm, key, data->status);
1448 }
1449 
1450 static bool iwl_mvm_setup_connection_keep(struct iwl_mvm *mvm,
1451 					  struct ieee80211_vif *vif,
1452 					  struct iwl_wowlan_status *status)
1453 {
1454 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1455 	struct iwl_mvm_d3_gtk_iter_data gtkdata = {
1456 		.mvm = mvm,
1457 		.status = status,
1458 	};
1459 	u32 disconnection_reasons =
1460 		IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON |
1461 		IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH;
1462 
1463 	if (!status || !vif->bss_conf.bssid)
1464 		return false;
1465 
1466 	if (le32_to_cpu(status->wakeup_reasons) & disconnection_reasons)
1467 		return false;
1468 
1469 	/* find last GTK that we used initially, if any */
1470 	gtkdata.find_phase = true;
1471 	ieee80211_iter_keys(mvm->hw, vif,
1472 			    iwl_mvm_d3_update_keys, &gtkdata);
1473 	/* not trying to keep connections with MFP/unhandled ciphers */
1474 	if (gtkdata.unhandled_cipher)
1475 		return false;
1476 	if (!gtkdata.num_keys)
1477 		goto out;
1478 	if (!gtkdata.last_gtk)
1479 		return false;
1480 
1481 	/*
1482 	 * invalidate all other GTKs that might still exist and update
1483 	 * the one that we used
1484 	 */
1485 	gtkdata.find_phase = false;
1486 	ieee80211_iter_keys(mvm->hw, vif,
1487 			    iwl_mvm_d3_update_keys, &gtkdata);
1488 
1489 	if (status->num_of_gtk_rekeys) {
1490 		struct ieee80211_key_conf *key;
1491 		struct {
1492 			struct ieee80211_key_conf conf;
1493 			u8 key[32];
1494 		} conf = {
1495 			.conf.cipher = gtkdata.cipher,
1496 			.conf.keyidx =
1497 				iwlmvm_wowlan_gtk_idx(&status->gtk[0]),
1498 		};
1499 		__be64 replay_ctr;
1500 
1501 		switch (gtkdata.cipher) {
1502 		case WLAN_CIPHER_SUITE_CCMP:
1503 			conf.conf.keylen = WLAN_KEY_LEN_CCMP;
1504 			memcpy(conf.conf.key, status->gtk[0].key,
1505 			       WLAN_KEY_LEN_CCMP);
1506 			break;
1507 		case WLAN_CIPHER_SUITE_TKIP:
1508 			conf.conf.keylen = WLAN_KEY_LEN_TKIP;
1509 			memcpy(conf.conf.key, status->gtk[0].key, 16);
1510 			/* leave TX MIC key zeroed, we don't use it anyway */
1511 			memcpy(conf.conf.key +
1512 			       NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY,
1513 			       status->gtk[0].tkip_mic_key, 8);
1514 			break;
1515 		}
1516 
1517 		key = ieee80211_gtk_rekey_add(vif, &conf.conf);
1518 		if (IS_ERR(key))
1519 			return false;
1520 		iwl_mvm_set_key_rx_seq(mvm, key, status);
1521 
1522 		replay_ctr =
1523 			cpu_to_be64(le64_to_cpu(status->replay_ctr));
1524 
1525 		ieee80211_gtk_rekey_notify(vif, vif->bss_conf.bssid,
1526 					   (void *)&replay_ctr, GFP_KERNEL);
1527 	}
1528 
1529 out:
1530 	mvmvif->seqno_valid = true;
1531 	/* +0x10 because the set API expects next-to-use, not last-used */
1532 	mvmvif->seqno = le16_to_cpu(status->non_qos_seq_ctr) + 0x10;
1533 
1534 	return true;
1535 }
1536 
1537 struct iwl_wowlan_status *iwl_mvm_send_wowlan_get_status(struct iwl_mvm *mvm)
1538 {
1539 	struct iwl_wowlan_status *v7, *status;
1540 	struct iwl_host_cmd cmd = {
1541 		.id = WOWLAN_GET_STATUSES,
1542 		.flags = CMD_WANT_SKB,
1543 	};
1544 	int ret, len, status_size;
1545 
1546 	lockdep_assert_held(&mvm->mutex);
1547 
1548 	ret = iwl_mvm_send_cmd(mvm, &cmd);
1549 	if (ret) {
1550 		IWL_ERR(mvm, "failed to query wakeup status (%d)\n", ret);
1551 		return ERR_PTR(ret);
1552 	}
1553 
1554 	if (!fw_has_api(&mvm->fw->ucode_capa,
1555 			IWL_UCODE_TLV_API_WOWLAN_KEY_MATERIAL)) {
1556 		struct iwl_wowlan_status_v6 *v6 = (void *)cmd.resp_pkt->data;
1557 		int data_size;
1558 
1559 		status_size = sizeof(*v6);
1560 		len = iwl_rx_packet_payload_len(cmd.resp_pkt);
1561 
1562 		if (len < status_size) {
1563 			IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1564 			status = ERR_PTR(-EIO);
1565 			goto out_free_resp;
1566 		}
1567 
1568 		data_size = ALIGN(le32_to_cpu(v6->wake_packet_bufsize), 4);
1569 
1570 		if (len != (status_size + data_size)) {
1571 			IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1572 			status = ERR_PTR(-EIO);
1573 			goto out_free_resp;
1574 		}
1575 
1576 		status = kzalloc(sizeof(*status) + data_size, GFP_KERNEL);
1577 		if (!status)
1578 			goto out_free_resp;
1579 
1580 		BUILD_BUG_ON(sizeof(v6->gtk.decrypt_key) >
1581 			     sizeof(status->gtk[0].key));
1582 		BUILD_BUG_ON(sizeof(v6->gtk.tkip_mic_key) >
1583 			     sizeof(status->gtk[0].tkip_mic_key));
1584 
1585 		/* copy GTK info to the right place */
1586 		memcpy(status->gtk[0].key, v6->gtk.decrypt_key,
1587 		       sizeof(v6->gtk.decrypt_key));
1588 		memcpy(status->gtk[0].tkip_mic_key, v6->gtk.tkip_mic_key,
1589 		       sizeof(v6->gtk.tkip_mic_key));
1590 		memcpy(&status->gtk[0].rsc, &v6->gtk.rsc,
1591 		       sizeof(status->gtk[0].rsc));
1592 
1593 		/* hardcode the key length to 16 since v6 only supports 16 */
1594 		status->gtk[0].key_len = 16;
1595 
1596 		/*
1597 		 * The key index only uses 2 bits (values 0 to 3) and
1598 		 * we always set bit 7 which means this is the
1599 		 * currently used key.
1600 		 */
1601 		status->gtk[0].key_flags = v6->gtk.key_index | BIT(7);
1602 
1603 		status->replay_ctr = v6->replay_ctr;
1604 
1605 		/* everything starting from pattern_number is identical */
1606 		memcpy(&status->pattern_number, &v6->pattern_number,
1607 		       offsetof(struct iwl_wowlan_status, wake_packet) -
1608 		       offsetof(struct iwl_wowlan_status, pattern_number) +
1609 		       data_size);
1610 
1611 		goto out_free_resp;
1612 	}
1613 
1614 	v7 = (void *)cmd.resp_pkt->data;
1615 	status_size = sizeof(*v7);
1616 	len = iwl_rx_packet_payload_len(cmd.resp_pkt);
1617 
1618 	if (len < status_size) {
1619 		IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1620 		status = ERR_PTR(-EIO);
1621 		goto out_free_resp;
1622 	}
1623 
1624 	if (len != (status_size +
1625 		    ALIGN(le32_to_cpu(v7->wake_packet_bufsize), 4))) {
1626 		IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1627 		status = ERR_PTR(-EIO);
1628 		goto out_free_resp;
1629 	}
1630 
1631 	status = kmemdup(v7, len, GFP_KERNEL);
1632 
1633 out_free_resp:
1634 	iwl_free_resp(&cmd);
1635 	return status;
1636 }
1637 
1638 static struct iwl_wowlan_status *
1639 iwl_mvm_get_wakeup_status(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1640 {
1641 	u32 base = mvm->error_event_table[0];
1642 	struct error_table_start {
1643 		/* cf. struct iwl_error_event_table */
1644 		u32 valid;
1645 		u32 error_id;
1646 	} err_info;
1647 	int ret;
1648 
1649 	iwl_trans_read_mem_bytes(mvm->trans, base,
1650 				 &err_info, sizeof(err_info));
1651 
1652 	if (err_info.valid) {
1653 		IWL_INFO(mvm, "error table is valid (%d) with error (%d)\n",
1654 			 err_info.valid, err_info.error_id);
1655 		if (err_info.error_id == RF_KILL_INDICATOR_FOR_WOWLAN) {
1656 			struct cfg80211_wowlan_wakeup wakeup = {
1657 				.rfkill_release = true,
1658 			};
1659 			ieee80211_report_wowlan_wakeup(vif, &wakeup,
1660 						       GFP_KERNEL);
1661 		}
1662 		return ERR_PTR(-EIO);
1663 	}
1664 
1665 	/* only for tracing for now */
1666 	ret = iwl_mvm_send_cmd_pdu(mvm, OFFLOADS_QUERY_CMD, 0, 0, NULL);
1667 	if (ret)
1668 		IWL_ERR(mvm, "failed to query offload statistics (%d)\n", ret);
1669 
1670 	return iwl_mvm_send_wowlan_get_status(mvm);
1671 }
1672 
1673 /* releases the MVM mutex */
1674 static bool iwl_mvm_query_wakeup_reasons(struct iwl_mvm *mvm,
1675 					 struct ieee80211_vif *vif)
1676 {
1677 	struct iwl_wowlan_status_data status;
1678 	struct iwl_wowlan_status *fw_status;
1679 	int i;
1680 	bool keep;
1681 	struct iwl_mvm_sta *mvm_ap_sta;
1682 
1683 	fw_status = iwl_mvm_get_wakeup_status(mvm, vif);
1684 	if (IS_ERR_OR_NULL(fw_status))
1685 		goto out_unlock;
1686 
1687 	status.pattern_number = le16_to_cpu(fw_status->pattern_number);
1688 	for (i = 0; i < 8; i++)
1689 		status.qos_seq_ctr[i] =
1690 			le16_to_cpu(fw_status->qos_seq_ctr[i]);
1691 	status.wakeup_reasons = le32_to_cpu(fw_status->wakeup_reasons);
1692 	status.wake_packet_length =
1693 		le32_to_cpu(fw_status->wake_packet_length);
1694 	status.wake_packet_bufsize =
1695 		le32_to_cpu(fw_status->wake_packet_bufsize);
1696 	status.wake_packet = fw_status->wake_packet;
1697 
1698 	/* still at hard-coded place 0 for D3 image */
1699 	mvm_ap_sta = iwl_mvm_sta_from_staid_protected(mvm, 0);
1700 	if (!mvm_ap_sta)
1701 		goto out_free;
1702 
1703 	for (i = 0; i < IWL_MAX_TID_COUNT; i++) {
1704 		u16 seq = status.qos_seq_ctr[i];
1705 		/* firmware stores last-used value, we store next value */
1706 		seq += 0x10;
1707 		mvm_ap_sta->tid_data[i].seq_number = seq;
1708 	}
1709 
1710 	/* now we have all the data we need, unlock to avoid mac80211 issues */
1711 	mutex_unlock(&mvm->mutex);
1712 
1713 	iwl_mvm_report_wakeup_reasons(mvm, vif, &status);
1714 
1715 	keep = iwl_mvm_setup_connection_keep(mvm, vif, fw_status);
1716 
1717 	kfree(fw_status);
1718 	return keep;
1719 
1720 out_free:
1721 	kfree(fw_status);
1722 out_unlock:
1723 	mutex_unlock(&mvm->mutex);
1724 	return false;
1725 }
1726 
1727 void iwl_mvm_d0i3_update_keys(struct iwl_mvm *mvm,
1728 			      struct ieee80211_vif *vif,
1729 			      struct iwl_wowlan_status *status)
1730 {
1731 	struct iwl_mvm_d3_gtk_iter_data gtkdata = {
1732 		.mvm = mvm,
1733 		.status = status,
1734 	};
1735 
1736 	/*
1737 	 * rekey handling requires taking locks that can't be taken now.
1738 	 * however, d0i3 doesn't offload rekey, so we're fine.
1739 	 */
1740 	if (WARN_ON_ONCE(status->num_of_gtk_rekeys))
1741 		return;
1742 
1743 	/* find last GTK that we used initially, if any */
1744 	gtkdata.find_phase = true;
1745 	iwl_mvm_iter_d0i3_ap_keys(mvm, vif, iwl_mvm_d3_update_keys, &gtkdata);
1746 
1747 	gtkdata.find_phase = false;
1748 	iwl_mvm_iter_d0i3_ap_keys(mvm, vif, iwl_mvm_d3_update_keys, &gtkdata);
1749 }
1750 
1751 struct iwl_mvm_nd_query_results {
1752 	u32 matched_profiles;
1753 	struct iwl_scan_offload_profile_match matches[IWL_SCAN_MAX_PROFILES];
1754 };
1755 
1756 static int
1757 iwl_mvm_netdetect_query_results(struct iwl_mvm *mvm,
1758 				struct iwl_mvm_nd_query_results *results)
1759 {
1760 	struct iwl_scan_offload_profiles_query *query;
1761 	struct iwl_host_cmd cmd = {
1762 		.id = SCAN_OFFLOAD_PROFILES_QUERY_CMD,
1763 		.flags = CMD_WANT_SKB,
1764 	};
1765 	int ret, len;
1766 
1767 	ret = iwl_mvm_send_cmd(mvm, &cmd);
1768 	if (ret) {
1769 		IWL_ERR(mvm, "failed to query matched profiles (%d)\n", ret);
1770 		return ret;
1771 	}
1772 
1773 	len = iwl_rx_packet_payload_len(cmd.resp_pkt);
1774 	if (len < sizeof(*query)) {
1775 		IWL_ERR(mvm, "Invalid scan offload profiles query response!\n");
1776 		ret = -EIO;
1777 		goto out_free_resp;
1778 	}
1779 
1780 	query = (void *)cmd.resp_pkt->data;
1781 
1782 	results->matched_profiles = le32_to_cpu(query->matched_profiles);
1783 	memcpy(results->matches, query->matches, sizeof(results->matches));
1784 
1785 #ifdef CONFIG_IWLWIFI_DEBUGFS
1786 	mvm->last_netdetect_scans = le32_to_cpu(query->n_scans_done);
1787 #endif
1788 
1789 out_free_resp:
1790 	iwl_free_resp(&cmd);
1791 	return ret;
1792 }
1793 
1794 static void iwl_mvm_query_netdetect_reasons(struct iwl_mvm *mvm,
1795 					    struct ieee80211_vif *vif)
1796 {
1797 	struct cfg80211_wowlan_nd_info *net_detect = NULL;
1798 	struct cfg80211_wowlan_wakeup wakeup = {
1799 		.pattern_idx = -1,
1800 	};
1801 	struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup;
1802 	struct iwl_mvm_nd_query_results query;
1803 	struct iwl_wowlan_status *fw_status;
1804 	unsigned long matched_profiles;
1805 	u32 reasons = 0;
1806 	int i, j, n_matches, ret;
1807 
1808 	fw_status = iwl_mvm_get_wakeup_status(mvm, vif);
1809 	if (!IS_ERR_OR_NULL(fw_status)) {
1810 		reasons = le32_to_cpu(fw_status->wakeup_reasons);
1811 		kfree(fw_status);
1812 	}
1813 
1814 	if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED)
1815 		wakeup.rfkill_release = true;
1816 
1817 	if (reasons != IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS)
1818 		goto out;
1819 
1820 	ret = iwl_mvm_netdetect_query_results(mvm, &query);
1821 	if (ret || !query.matched_profiles) {
1822 		wakeup_report = NULL;
1823 		goto out;
1824 	}
1825 
1826 	matched_profiles = query.matched_profiles;
1827 	if (mvm->n_nd_match_sets) {
1828 		n_matches = hweight_long(matched_profiles);
1829 	} else {
1830 		IWL_ERR(mvm, "no net detect match information available\n");
1831 		n_matches = 0;
1832 	}
1833 
1834 	net_detect = kzalloc(sizeof(*net_detect) +
1835 			     (n_matches * sizeof(net_detect->matches[0])),
1836 			     GFP_KERNEL);
1837 	if (!net_detect || !n_matches)
1838 		goto out_report_nd;
1839 
1840 	for_each_set_bit(i, &matched_profiles, mvm->n_nd_match_sets) {
1841 		struct iwl_scan_offload_profile_match *fw_match;
1842 		struct cfg80211_wowlan_nd_match *match;
1843 		int idx, n_channels = 0;
1844 
1845 		fw_match = &query.matches[i];
1846 
1847 		for (j = 0; j < SCAN_OFFLOAD_MATCHING_CHANNELS_LEN; j++)
1848 			n_channels += hweight8(fw_match->matching_channels[j]);
1849 
1850 		match = kzalloc(sizeof(*match) +
1851 				(n_channels * sizeof(*match->channels)),
1852 				GFP_KERNEL);
1853 		if (!match)
1854 			goto out_report_nd;
1855 
1856 		net_detect->matches[net_detect->n_matches++] = match;
1857 
1858 		/* We inverted the order of the SSIDs in the scan
1859 		 * request, so invert the index here.
1860 		 */
1861 		idx = mvm->n_nd_match_sets - i - 1;
1862 		match->ssid.ssid_len = mvm->nd_match_sets[idx].ssid.ssid_len;
1863 		memcpy(match->ssid.ssid, mvm->nd_match_sets[idx].ssid.ssid,
1864 		       match->ssid.ssid_len);
1865 
1866 		if (mvm->n_nd_channels < n_channels)
1867 			continue;
1868 
1869 		for (j = 0; j < SCAN_OFFLOAD_MATCHING_CHANNELS_LEN * 8; j++)
1870 			if (fw_match->matching_channels[j / 8] & (BIT(j % 8)))
1871 				match->channels[match->n_channels++] =
1872 					mvm->nd_channels[j]->center_freq;
1873 	}
1874 
1875 out_report_nd:
1876 	wakeup.net_detect = net_detect;
1877 out:
1878 	iwl_mvm_free_nd(mvm);
1879 
1880 	mutex_unlock(&mvm->mutex);
1881 	ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL);
1882 
1883 	if (net_detect) {
1884 		for (i = 0; i < net_detect->n_matches; i++)
1885 			kfree(net_detect->matches[i]);
1886 		kfree(net_detect);
1887 	}
1888 }
1889 
1890 static void iwl_mvm_read_d3_sram(struct iwl_mvm *mvm)
1891 {
1892 #ifdef CONFIG_IWLWIFI_DEBUGFS
1893 	const struct fw_img *img = &mvm->fw->img[IWL_UCODE_WOWLAN];
1894 	u32 len = img->sec[IWL_UCODE_SECTION_DATA].len;
1895 	u32 offs = img->sec[IWL_UCODE_SECTION_DATA].offset;
1896 
1897 	if (!mvm->store_d3_resume_sram)
1898 		return;
1899 
1900 	if (!mvm->d3_resume_sram) {
1901 		mvm->d3_resume_sram = kzalloc(len, GFP_KERNEL);
1902 		if (!mvm->d3_resume_sram)
1903 			return;
1904 	}
1905 
1906 	iwl_trans_read_mem_bytes(mvm->trans, offs, mvm->d3_resume_sram, len);
1907 #endif
1908 }
1909 
1910 static void iwl_mvm_d3_disconnect_iter(void *data, u8 *mac,
1911 				       struct ieee80211_vif *vif)
1912 {
1913 	/* skip the one we keep connection on */
1914 	if (data == vif)
1915 		return;
1916 
1917 	if (vif->type == NL80211_IFTYPE_STATION)
1918 		ieee80211_resume_disconnect(vif);
1919 }
1920 
1921 static int __iwl_mvm_resume(struct iwl_mvm *mvm, bool test)
1922 {
1923 	struct ieee80211_vif *vif = NULL;
1924 	int ret = 1;
1925 	enum iwl_d3_status d3_status;
1926 	bool keep = false;
1927 	bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
1928 					 IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
1929 	bool d0i3_first = fw_has_capa(&mvm->fw->ucode_capa,
1930 				      IWL_UCODE_TLV_CAPA_D0I3_END_FIRST);
1931 
1932 	mutex_lock(&mvm->mutex);
1933 
1934 	/* get the BSS vif pointer again */
1935 	vif = iwl_mvm_get_bss_vif(mvm);
1936 	if (IS_ERR_OR_NULL(vif))
1937 		goto err;
1938 
1939 	ret = iwl_trans_d3_resume(mvm->trans, &d3_status, test, !unified_image);
1940 	if (ret)
1941 		goto err;
1942 
1943 	if (d3_status != IWL_D3_STATUS_ALIVE) {
1944 		IWL_INFO(mvm, "Device was reset during suspend\n");
1945 		goto err;
1946 	}
1947 
1948 	iwl_fw_dbg_read_d3_debug_data(&mvm->fwrt);
1949 	/* query SRAM first in case we want event logging */
1950 	iwl_mvm_read_d3_sram(mvm);
1951 
1952 	if (d0i3_first) {
1953 		ret = iwl_mvm_send_cmd_pdu(mvm, D0I3_END_CMD, 0, 0, NULL);
1954 		if (ret < 0) {
1955 			IWL_ERR(mvm, "Failed to send D0I3_END_CMD first (%d)\n",
1956 				ret);
1957 			goto err;
1958 		}
1959 	}
1960 
1961 	/*
1962 	 * Query the current location and source from the D3 firmware so we
1963 	 * can play it back when we re-intiailize the D0 firmware
1964 	 */
1965 	iwl_mvm_update_changed_regdom(mvm);
1966 
1967 	if (!unified_image)
1968 		/*  Re-configure default SAR profile */
1969 		iwl_mvm_sar_select_profile(mvm, 1, 1);
1970 
1971 	if (mvm->net_detect) {
1972 		/* If this is a non-unified image, we restart the FW,
1973 		 * so no need to stop the netdetect scan.  If that
1974 		 * fails, continue and try to get the wake-up reasons,
1975 		 * but trigger a HW restart by keeping a failure code
1976 		 * in ret.
1977 		 */
1978 		if (unified_image)
1979 			ret = iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_NETDETECT,
1980 						false);
1981 
1982 		iwl_mvm_query_netdetect_reasons(mvm, vif);
1983 		/* has unlocked the mutex, so skip that */
1984 		goto out;
1985 	} else {
1986 		keep = iwl_mvm_query_wakeup_reasons(mvm, vif);
1987 #ifdef CONFIG_IWLWIFI_DEBUGFS
1988 		if (keep)
1989 			mvm->keep_vif = vif;
1990 #endif
1991 		/* has unlocked the mutex, so skip that */
1992 		goto out_iterate;
1993 	}
1994 
1995 err:
1996 	iwl_mvm_free_nd(mvm);
1997 	mutex_unlock(&mvm->mutex);
1998 
1999 out_iterate:
2000 	if (!test)
2001 		ieee80211_iterate_active_interfaces_rtnl(mvm->hw,
2002 			IEEE80211_IFACE_ITER_NORMAL,
2003 			iwl_mvm_d3_disconnect_iter, keep ? vif : NULL);
2004 
2005 out:
2006 	/* no need to reset the device in unified images, if successful */
2007 	if (unified_image && !ret) {
2008 		/* nothing else to do if we already sent D0I3_END_CMD */
2009 		if (d0i3_first)
2010 			return 0;
2011 
2012 		ret = iwl_mvm_send_cmd_pdu(mvm, D0I3_END_CMD, 0, 0, NULL);
2013 		if (!ret)
2014 			return 0;
2015 	}
2016 
2017 	/*
2018 	 * Reconfigure the device in one of the following cases:
2019 	 * 1. We are not using a unified image
2020 	 * 2. We are using a unified image but had an error while exiting D3
2021 	 */
2022 	set_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED, &mvm->status);
2023 	set_bit(IWL_MVM_STATUS_D3_RECONFIG, &mvm->status);
2024 	/*
2025 	 * When switching images we return 1, which causes mac80211
2026 	 * to do a reconfig with IEEE80211_RECONFIG_TYPE_RESTART.
2027 	 * This type of reconfig calls iwl_mvm_restart_complete(),
2028 	 * where we unref the IWL_MVM_REF_UCODE_DOWN, so we need
2029 	 * to take the reference here.
2030 	 */
2031 	iwl_mvm_ref(mvm, IWL_MVM_REF_UCODE_DOWN);
2032 
2033 	return 1;
2034 }
2035 
2036 static int iwl_mvm_resume_d3(struct iwl_mvm *mvm)
2037 {
2038 	iwl_trans_resume(mvm->trans);
2039 
2040 	return __iwl_mvm_resume(mvm, false);
2041 }
2042 
2043 static int iwl_mvm_resume_d0i3(struct iwl_mvm *mvm)
2044 {
2045 	bool exit_now;
2046 	enum iwl_d3_status d3_status;
2047 	struct iwl_trans *trans = mvm->trans;
2048 
2049 	iwl_trans_d3_resume(trans, &d3_status, false, false);
2050 
2051 	/*
2052 	 * make sure to clear D0I3_DEFER_WAKEUP before
2053 	 * calling iwl_trans_resume(), which might wait
2054 	 * for d0i3 exit completion.
2055 	 */
2056 	mutex_lock(&mvm->d0i3_suspend_mutex);
2057 	__clear_bit(D0I3_DEFER_WAKEUP, &mvm->d0i3_suspend_flags);
2058 	exit_now = __test_and_clear_bit(D0I3_PENDING_WAKEUP,
2059 					&mvm->d0i3_suspend_flags);
2060 	mutex_unlock(&mvm->d0i3_suspend_mutex);
2061 	if (exit_now) {
2062 		IWL_DEBUG_RPM(mvm, "Run deferred d0i3 exit\n");
2063 		_iwl_mvm_exit_d0i3(mvm);
2064 	}
2065 
2066 	iwl_trans_resume(trans);
2067 
2068 	if (iwl_mvm_enter_d0i3_on_suspend(mvm)) {
2069 		int ret = iwl_mvm_exit_d0i3(mvm->hw->priv);
2070 
2071 		if (ret)
2072 			return ret;
2073 		/*
2074 		 * d0i3 exit will be deferred until reconfig_complete.
2075 		 * make sure there we are out of d0i3.
2076 		 */
2077 	}
2078 	return 0;
2079 }
2080 
2081 int iwl_mvm_resume(struct ieee80211_hw *hw)
2082 {
2083 	struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2084 	int ret;
2085 
2086 	if (mvm->trans->system_pm_mode == IWL_PLAT_PM_MODE_D0I3)
2087 		ret = iwl_mvm_resume_d0i3(mvm);
2088 	else
2089 		ret = iwl_mvm_resume_d3(mvm);
2090 
2091 	mvm->trans->system_pm_mode = IWL_PLAT_PM_MODE_DISABLED;
2092 
2093 	iwl_mvm_resume_tcm(mvm);
2094 
2095 	iwl_fw_runtime_resume(&mvm->fwrt);
2096 
2097 	return ret;
2098 }
2099 
2100 void iwl_mvm_set_wakeup(struct ieee80211_hw *hw, bool enabled)
2101 {
2102 	struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2103 
2104 	device_set_wakeup_enable(mvm->trans->dev, enabled);
2105 }
2106 
2107 #ifdef CONFIG_IWLWIFI_DEBUGFS
2108 static int iwl_mvm_d3_test_open(struct inode *inode, struct file *file)
2109 {
2110 	struct iwl_mvm *mvm = inode->i_private;
2111 	int err;
2112 
2113 	if (mvm->d3_test_active)
2114 		return -EBUSY;
2115 
2116 	file->private_data = inode->i_private;
2117 
2118 	ieee80211_stop_queues(mvm->hw);
2119 	synchronize_net();
2120 
2121 	mvm->trans->system_pm_mode = IWL_PLAT_PM_MODE_D3;
2122 
2123 	iwl_mvm_pause_tcm(mvm, true);
2124 
2125 	iwl_fw_runtime_suspend(&mvm->fwrt);
2126 
2127 	/* start pseudo D3 */
2128 	rtnl_lock();
2129 	err = __iwl_mvm_suspend(mvm->hw, mvm->hw->wiphy->wowlan_config, true);
2130 	rtnl_unlock();
2131 	if (err > 0)
2132 		err = -EINVAL;
2133 	if (err) {
2134 		ieee80211_wake_queues(mvm->hw);
2135 		return err;
2136 	}
2137 	mvm->d3_test_active = true;
2138 	mvm->keep_vif = NULL;
2139 	return 0;
2140 }
2141 
2142 static ssize_t iwl_mvm_d3_test_read(struct file *file, char __user *user_buf,
2143 				    size_t count, loff_t *ppos)
2144 {
2145 	struct iwl_mvm *mvm = file->private_data;
2146 	u32 pme_asserted;
2147 
2148 	while (true) {
2149 		/* read pme_ptr if available */
2150 		if (mvm->d3_test_pme_ptr) {
2151 			pme_asserted = iwl_trans_read_mem32(mvm->trans,
2152 						mvm->d3_test_pme_ptr);
2153 			if (pme_asserted)
2154 				break;
2155 		}
2156 
2157 		if (msleep_interruptible(100))
2158 			break;
2159 	}
2160 
2161 	return 0;
2162 }
2163 
2164 static void iwl_mvm_d3_test_disconn_work_iter(void *_data, u8 *mac,
2165 					      struct ieee80211_vif *vif)
2166 {
2167 	/* skip the one we keep connection on */
2168 	if (_data == vif)
2169 		return;
2170 
2171 	if (vif->type == NL80211_IFTYPE_STATION)
2172 		ieee80211_connection_loss(vif);
2173 }
2174 
2175 static int iwl_mvm_d3_test_release(struct inode *inode, struct file *file)
2176 {
2177 	struct iwl_mvm *mvm = inode->i_private;
2178 	bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
2179 					 IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
2180 
2181 	mvm->d3_test_active = false;
2182 
2183 	iwl_fw_dbg_read_d3_debug_data(&mvm->fwrt);
2184 
2185 	rtnl_lock();
2186 	__iwl_mvm_resume(mvm, true);
2187 	rtnl_unlock();
2188 
2189 	iwl_mvm_resume_tcm(mvm);
2190 
2191 	iwl_fw_runtime_resume(&mvm->fwrt);
2192 
2193 	mvm->trans->system_pm_mode = IWL_PLAT_PM_MODE_DISABLED;
2194 
2195 	iwl_abort_notification_waits(&mvm->notif_wait);
2196 	if (!unified_image) {
2197 		int remaining_time = 10;
2198 
2199 		ieee80211_restart_hw(mvm->hw);
2200 
2201 		/* wait for restart and disconnect all interfaces */
2202 		while (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) &&
2203 		       remaining_time > 0) {
2204 			remaining_time--;
2205 			msleep(1000);
2206 		}
2207 
2208 		if (remaining_time == 0)
2209 			IWL_ERR(mvm, "Timed out waiting for HW restart!\n");
2210 	}
2211 
2212 	ieee80211_iterate_active_interfaces_atomic(
2213 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
2214 		iwl_mvm_d3_test_disconn_work_iter, mvm->keep_vif);
2215 
2216 	ieee80211_wake_queues(mvm->hw);
2217 
2218 	return 0;
2219 }
2220 
2221 const struct file_operations iwl_dbgfs_d3_test_ops = {
2222 	.llseek = no_llseek,
2223 	.open = iwl_mvm_d3_test_open,
2224 	.read = iwl_mvm_d3_test_read,
2225 	.release = iwl_mvm_d3_test_release,
2226 };
2227 #endif
2228