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