GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / net / wireless / intel / iwlwifi / mvm / d3.c
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 binding_cmd = {};
438         struct iwl_time_quota_cmd quota_cmd = {};
439         struct iwl_time_quota_data *quota;
440         u32 status;
441         int size;
442
443         if (fw_has_capa(&mvm->fw->ucode_capa,
444                         IWL_UCODE_TLV_CAPA_BINDING_CDB_SUPPORT)) {
445                 size = sizeof(binding_cmd);
446                 if (mvmvif->phy_ctxt->channel->band == NL80211_BAND_2GHZ ||
447                     !iwl_mvm_is_cdb_supported(mvm))
448                         binding_cmd.lmac_id = cpu_to_le32(IWL_LMAC_24G_INDEX);
449                 else
450                         binding_cmd.lmac_id = cpu_to_le32(IWL_LMAC_5G_INDEX);
451         } else {
452                 size = IWL_BINDING_CMD_SIZE_V1;
453         }
454
455         /* add back the PHY */
456         if (WARN_ON(!mvmvif->phy_ctxt))
457                 return -EINVAL;
458
459         rcu_read_lock();
460         ctx = rcu_dereference(vif->chanctx_conf);
461         if (WARN_ON(!ctx)) {
462                 rcu_read_unlock();
463                 return -EINVAL;
464         }
465         chandef = ctx->def;
466         chains_static = ctx->rx_chains_static;
467         chains_dynamic = ctx->rx_chains_dynamic;
468         rcu_read_unlock();
469
470         ret = iwl_mvm_phy_ctxt_add(mvm, mvmvif->phy_ctxt, &chandef,
471                                    chains_static, chains_dynamic);
472         if (ret)
473                 return ret;
474
475         /* add back the MAC */
476         mvmvif->uploaded = false;
477
478         if (WARN_ON(!vif->bss_conf.assoc))
479                 return -EINVAL;
480
481         ret = iwl_mvm_mac_ctxt_add(mvm, vif);
482         if (ret)
483                 return ret;
484
485         /* add back binding - XXX refactor? */
486         binding_cmd.id_and_color =
487                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
488                                                 mvmvif->phy_ctxt->color));
489         binding_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD);
490         binding_cmd.phy =
491                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
492                                                 mvmvif->phy_ctxt->color));
493         binding_cmd.macs[0] = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
494                                                               mvmvif->color));
495         for (i = 1; i < MAX_MACS_IN_BINDING; i++)
496                 binding_cmd.macs[i] = cpu_to_le32(FW_CTXT_INVALID);
497
498         status = 0;
499         ret = iwl_mvm_send_cmd_pdu_status(mvm, BINDING_CONTEXT_CMD,
500                                           size, &binding_cmd, &status);
501         if (ret) {
502                 IWL_ERR(mvm, "Failed to add binding: %d\n", ret);
503                 return ret;
504         }
505
506         if (status) {
507                 IWL_ERR(mvm, "Binding command failed: %u\n", status);
508                 return -EIO;
509         }
510
511         ret = iwl_mvm_sta_send_to_fw(mvm, ap_sta, false, 0);
512         if (ret)
513                 return ret;
514         rcu_assign_pointer(mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], ap_sta);
515
516         ret = iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
517         if (ret)
518                 return ret;
519
520         /* and some quota */
521         quota = iwl_mvm_quota_cmd_get_quota(mvm, &quota_cmd, 0);
522         quota->id_and_color =
523                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
524                                                 mvmvif->phy_ctxt->color));
525         quota->quota = cpu_to_le32(IWL_MVM_MAX_QUOTA);
526         quota->max_duration = cpu_to_le32(IWL_MVM_MAX_QUOTA);
527
528         for (i = 1; i < MAX_BINDINGS; i++) {
529                 quota = iwl_mvm_quota_cmd_get_quota(mvm, &quota_cmd, i);
530                 quota->id_and_color = cpu_to_le32(FW_CTXT_INVALID);
531         }
532
533         ret = iwl_mvm_send_cmd_pdu(mvm, TIME_QUOTA_CMD, 0,
534                                    iwl_mvm_quota_cmd_size(mvm), &quota_cmd);
535         if (ret)
536                 IWL_ERR(mvm, "Failed to send quota: %d\n", ret);
537
538         if (iwl_mvm_is_lar_supported(mvm) && iwl_mvm_init_fw_regd(mvm))
539                 IWL_ERR(mvm, "Failed to initialize D3 LAR information\n");
540
541         return 0;
542 }
543
544 static int iwl_mvm_get_last_nonqos_seq(struct iwl_mvm *mvm,
545                                        struct ieee80211_vif *vif)
546 {
547         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
548         struct iwl_nonqos_seq_query_cmd query_cmd = {
549                 .get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_GET),
550                 .mac_id_n_color =
551                         cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
552                                                         mvmvif->color)),
553         };
554         struct iwl_host_cmd cmd = {
555                 .id = NON_QOS_TX_COUNTER_CMD,
556                 .flags = CMD_WANT_SKB,
557         };
558         int err;
559         u32 size;
560
561         cmd.data[0] = &query_cmd;
562         cmd.len[0] = sizeof(query_cmd);
563
564         err = iwl_mvm_send_cmd(mvm, &cmd);
565         if (err)
566                 return err;
567
568         size = iwl_rx_packet_payload_len(cmd.resp_pkt);
569         if (size < sizeof(__le16)) {
570                 err = -EINVAL;
571         } else {
572                 err = le16_to_cpup((__le16 *)cmd.resp_pkt->data);
573                 /* firmware returns next, not last-used seqno */
574                 err = (u16) (err - 0x10);
575         }
576
577         iwl_free_resp(&cmd);
578         return err;
579 }
580
581 void iwl_mvm_set_last_nonqos_seq(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
582 {
583         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
584         struct iwl_nonqos_seq_query_cmd query_cmd = {
585                 .get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_SET),
586                 .mac_id_n_color =
587                         cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
588                                                         mvmvif->color)),
589                 .value = cpu_to_le16(mvmvif->seqno),
590         };
591
592         /* return if called during restart, not resume from D3 */
593         if (!mvmvif->seqno_valid)
594                 return;
595
596         mvmvif->seqno_valid = false;
597
598         if (iwl_mvm_send_cmd_pdu(mvm, NON_QOS_TX_COUNTER_CMD, 0,
599                                  sizeof(query_cmd), &query_cmd))
600                 IWL_ERR(mvm, "failed to set non-QoS seqno\n");
601 }
602
603 static int iwl_mvm_switch_to_d3(struct iwl_mvm *mvm)
604 {
605         iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_REGULAR, true);
606
607         iwl_mvm_stop_device(mvm);
608         /*
609          * Set the HW restart bit -- this is mostly true as we're
610          * going to load new firmware and reprogram that, though
611          * the reprogramming is going to be manual to avoid adding
612          * all the MACs that aren't support.
613          * We don't have to clear up everything though because the
614          * reprogramming is manual. When we resume, we'll actually
615          * go through a proper restart sequence again to switch
616          * back to the runtime firmware image.
617          */
618         set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
619
620         /* the fw is reset, so all the keys are cleared */
621         memset(mvm->fw_key_table, 0, sizeof(mvm->fw_key_table));
622
623         mvm->ptk_ivlen = 0;
624         mvm->ptk_icvlen = 0;
625         mvm->ptk_ivlen = 0;
626         mvm->ptk_icvlen = 0;
627
628         return iwl_mvm_load_d3_fw(mvm);
629 }
630
631 static int
632 iwl_mvm_get_wowlan_config(struct iwl_mvm *mvm,
633                           struct cfg80211_wowlan *wowlan,
634                           struct iwl_wowlan_config_cmd *wowlan_config_cmd,
635                           struct ieee80211_vif *vif, struct iwl_mvm_vif *mvmvif,
636                           struct ieee80211_sta *ap_sta)
637 {
638         int ret;
639         struct iwl_mvm_sta *mvm_ap_sta = iwl_mvm_sta_from_mac80211(ap_sta);
640
641         /* TODO: wowlan_config_cmd->wowlan_ba_teardown_tids */
642
643         wowlan_config_cmd->is_11n_connection =
644                                         ap_sta->ht_cap.ht_supported;
645         wowlan_config_cmd->flags = ENABLE_L3_FILTERING |
646                 ENABLE_NBNS_FILTERING | ENABLE_DHCP_FILTERING;
647
648         /* Query the last used seqno and set it */
649         ret = iwl_mvm_get_last_nonqos_seq(mvm, vif);
650         if (ret < 0)
651                 return ret;
652
653         wowlan_config_cmd->non_qos_seq = cpu_to_le16(ret);
654
655         iwl_mvm_set_wowlan_qos_seq(mvm_ap_sta, wowlan_config_cmd);
656
657         if (wowlan->disconnect)
658                 wowlan_config_cmd->wakeup_filter |=
659                         cpu_to_le32(IWL_WOWLAN_WAKEUP_BEACON_MISS |
660                                     IWL_WOWLAN_WAKEUP_LINK_CHANGE);
661         if (wowlan->magic_pkt)
662                 wowlan_config_cmd->wakeup_filter |=
663                         cpu_to_le32(IWL_WOWLAN_WAKEUP_MAGIC_PACKET);
664         if (wowlan->gtk_rekey_failure)
665                 wowlan_config_cmd->wakeup_filter |=
666                         cpu_to_le32(IWL_WOWLAN_WAKEUP_GTK_REKEY_FAIL);
667         if (wowlan->eap_identity_req)
668                 wowlan_config_cmd->wakeup_filter |=
669                         cpu_to_le32(IWL_WOWLAN_WAKEUP_EAP_IDENT_REQ);
670         if (wowlan->four_way_handshake)
671                 wowlan_config_cmd->wakeup_filter |=
672                         cpu_to_le32(IWL_WOWLAN_WAKEUP_4WAY_HANDSHAKE);
673         if (wowlan->n_patterns)
674                 wowlan_config_cmd->wakeup_filter |=
675                         cpu_to_le32(IWL_WOWLAN_WAKEUP_PATTERN_MATCH);
676
677         if (wowlan->rfkill_release)
678                 wowlan_config_cmd->wakeup_filter |=
679                         cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT);
680
681         if (wowlan->tcp) {
682                 /*
683                  * Set the "link change" (really "link lost") flag as well
684                  * since that implies losing the TCP connection.
685                  */
686                 wowlan_config_cmd->wakeup_filter |=
687                         cpu_to_le32(IWL_WOWLAN_WAKEUP_REMOTE_LINK_LOSS |
688                                     IWL_WOWLAN_WAKEUP_REMOTE_SIGNATURE_TABLE |
689                                     IWL_WOWLAN_WAKEUP_REMOTE_WAKEUP_PACKET |
690                                     IWL_WOWLAN_WAKEUP_LINK_CHANGE);
691         }
692
693         if (wowlan->any) {
694                 wowlan_config_cmd->wakeup_filter |=
695                         cpu_to_le32(IWL_WOWLAN_WAKEUP_BEACON_MISS |
696                                     IWL_WOWLAN_WAKEUP_LINK_CHANGE |
697                                     IWL_WOWLAN_WAKEUP_RX_FRAME |
698                                     IWL_WOWLAN_WAKEUP_BCN_FILTERING);
699         }
700
701         return 0;
702 }
703
704 static void
705 iwl_mvm_iter_d0i3_ap_keys(struct iwl_mvm *mvm,
706                           struct ieee80211_vif *vif,
707                           void (*iter)(struct ieee80211_hw *hw,
708                                        struct ieee80211_vif *vif,
709                                        struct ieee80211_sta *sta,
710                                        struct ieee80211_key_conf *key,
711                                        void *data),
712                           void *data)
713 {
714         struct ieee80211_sta *ap_sta;
715
716         rcu_read_lock();
717
718         ap_sta = rcu_dereference(mvm->fw_id_to_mac_id[mvm->d0i3_ap_sta_id]);
719         if (IS_ERR_OR_NULL(ap_sta))
720                 goto out;
721
722         ieee80211_iter_keys_rcu(mvm->hw, vif, iter, data);
723 out:
724         rcu_read_unlock();
725 }
726
727 int iwl_mvm_wowlan_config_key_params(struct iwl_mvm *mvm,
728                                      struct ieee80211_vif *vif,
729                                      bool d0i3,
730                                      u32 cmd_flags)
731 {
732         struct iwl_wowlan_kek_kck_material_cmd kek_kck_cmd = {};
733         struct iwl_wowlan_tkip_params_cmd tkip_cmd = {};
734         bool unified = fw_has_capa(&mvm->fw->ucode_capa,
735                                    IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
736         struct wowlan_key_data key_data = {
737                 .configure_keys = !d0i3 && !unified,
738                 .use_rsc_tsc = false,
739                 .tkip = &tkip_cmd,
740                 .use_tkip = false,
741         };
742         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
743         int ret;
744
745         key_data.rsc_tsc = kzalloc(sizeof(*key_data.rsc_tsc), GFP_KERNEL);
746         if (!key_data.rsc_tsc)
747                 return -ENOMEM;
748
749         /*
750          * if we have to configure keys, call ieee80211_iter_keys(),
751          * as we need non-atomic context in order to take the
752          * required locks.
753          * for the d0i3 we can't use ieee80211_iter_keys(), as
754          * taking (almost) any mutex might result in deadlock.
755          */
756         if (!d0i3) {
757                 /*
758                  * Note that currently we don't propagate cmd_flags
759                  * to the iterator. In case of key_data.configure_keys,
760                  * all the configured commands are SYNC, and
761                  * iwl_mvm_wowlan_program_keys() will take care of
762                  * locking/unlocking mvm->mutex.
763                  */
764                 ieee80211_iter_keys(mvm->hw, vif,
765                                     iwl_mvm_wowlan_program_keys,
766                                     &key_data);
767         } else {
768                 iwl_mvm_iter_d0i3_ap_keys(mvm, vif,
769                                           iwl_mvm_wowlan_program_keys,
770                                           &key_data);
771         }
772
773         if (key_data.error) {
774                 ret = -EIO;
775                 goto out;
776         }
777
778         if (key_data.use_rsc_tsc) {
779                 ret = iwl_mvm_send_cmd_pdu(mvm,
780                                            WOWLAN_TSC_RSC_PARAM, cmd_flags,
781                                            sizeof(*key_data.rsc_tsc),
782                                            key_data.rsc_tsc);
783                 if (ret)
784                         goto out;
785         }
786
787         if (key_data.use_tkip &&
788             !fw_has_api(&mvm->fw->ucode_capa,
789                         IWL_UCODE_TLV_API_TKIP_MIC_KEYS)) {
790                 ret = iwl_mvm_send_cmd_pdu(mvm,
791                                            WOWLAN_TKIP_PARAM,
792                                            cmd_flags, sizeof(tkip_cmd),
793                                            &tkip_cmd);
794                 if (ret)
795                         goto out;
796         }
797
798         /* configure rekey data only if offloaded rekey is supported (d3) */
799         if (mvmvif->rekey_data.valid && !d0i3) {
800                 memset(&kek_kck_cmd, 0, sizeof(kek_kck_cmd));
801                 memcpy(kek_kck_cmd.kck, mvmvif->rekey_data.kck,
802                        NL80211_KCK_LEN);
803                 kek_kck_cmd.kck_len = cpu_to_le16(NL80211_KCK_LEN);
804                 memcpy(kek_kck_cmd.kek, mvmvif->rekey_data.kek,
805                        NL80211_KEK_LEN);
806                 kek_kck_cmd.kek_len = cpu_to_le16(NL80211_KEK_LEN);
807                 kek_kck_cmd.replay_ctr = mvmvif->rekey_data.replay_ctr;
808
809                 ret = iwl_mvm_send_cmd_pdu(mvm,
810                                            WOWLAN_KEK_KCK_MATERIAL, cmd_flags,
811                                            sizeof(kek_kck_cmd),
812                                            &kek_kck_cmd);
813                 if (ret)
814                         goto out;
815         }
816         ret = 0;
817 out:
818         kfree(key_data.rsc_tsc);
819         return ret;
820 }
821
822 static int
823 iwl_mvm_wowlan_config(struct iwl_mvm *mvm,
824                       struct cfg80211_wowlan *wowlan,
825                       struct iwl_wowlan_config_cmd *wowlan_config_cmd,
826                       struct ieee80211_vif *vif, struct iwl_mvm_vif *mvmvif,
827                       struct ieee80211_sta *ap_sta)
828 {
829         int ret;
830         bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
831                                          IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
832
833         if (!unified_image) {
834                 ret = iwl_mvm_switch_to_d3(mvm);
835                 if (ret)
836                         return ret;
837
838                 ret = iwl_mvm_d3_reprogram(mvm, vif, ap_sta);
839                 if (ret)
840                         return ret;
841         }
842
843         if (!iwlwifi_mod_params.swcrypto) {
844                 /*
845                  * This needs to be unlocked due to lock ordering
846                  * constraints. Since we're in the suspend path
847                  * that isn't really a problem though.
848                  */
849                 mutex_unlock(&mvm->mutex);
850                 ret = iwl_mvm_wowlan_config_key_params(mvm, vif, false,
851                                                        CMD_ASYNC);
852                 mutex_lock(&mvm->mutex);
853                 if (ret)
854                         return ret;
855         }
856
857         ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION, 0,
858                                    sizeof(*wowlan_config_cmd),
859                                    wowlan_config_cmd);
860         if (ret)
861                 return ret;
862
863         ret = iwl_mvm_send_patterns(mvm, wowlan);
864         if (ret)
865                 return ret;
866
867         return iwl_mvm_send_proto_offload(mvm, vif, false, true, 0);
868 }
869
870 static int
871 iwl_mvm_netdetect_config(struct iwl_mvm *mvm,
872                          struct cfg80211_wowlan *wowlan,
873                          struct cfg80211_sched_scan_request *nd_config,
874                          struct ieee80211_vif *vif)
875 {
876         struct iwl_wowlan_config_cmd wowlan_config_cmd = {};
877         int ret;
878         bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
879                                          IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
880
881         if (!unified_image) {
882                 ret = iwl_mvm_switch_to_d3(mvm);
883                 if (ret)
884                         return ret;
885         } else {
886                 /* In theory, we wouldn't have to stop a running sched
887                  * scan in order to start another one (for
888                  * net-detect).  But in practice this doesn't seem to
889                  * work properly, so stop any running sched_scan now.
890                  */
891                 ret = iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_SCHED, true);
892                 if (ret)
893                         return ret;
894         }
895
896         /* rfkill release can be either for wowlan or netdetect */
897         if (wowlan->rfkill_release)
898                 wowlan_config_cmd.wakeup_filter |=
899                         cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT);
900
901         ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION, 0,
902                                    sizeof(wowlan_config_cmd),
903                                    &wowlan_config_cmd);
904         if (ret)
905                 return ret;
906
907         ret = iwl_mvm_sched_scan_start(mvm, vif, nd_config, &mvm->nd_ies,
908                                        IWL_MVM_SCAN_NETDETECT);
909         if (ret)
910                 return ret;
911
912         if (WARN_ON(mvm->nd_match_sets || mvm->nd_channels))
913                 return -EBUSY;
914
915         /* save the sched scan matchsets... */
916         if (nd_config->n_match_sets) {
917                 mvm->nd_match_sets = kmemdup(nd_config->match_sets,
918                                              sizeof(*nd_config->match_sets) *
919                                              nd_config->n_match_sets,
920                                              GFP_KERNEL);
921                 if (mvm->nd_match_sets)
922                         mvm->n_nd_match_sets = nd_config->n_match_sets;
923         }
924
925         /* ...and the sched scan channels for later reporting */
926         mvm->nd_channels = kmemdup(nd_config->channels,
927                                    sizeof(*nd_config->channels) *
928                                    nd_config->n_channels,
929                                    GFP_KERNEL);
930         if (mvm->nd_channels)
931                 mvm->n_nd_channels = nd_config->n_channels;
932
933         return 0;
934 }
935
936 static void iwl_mvm_free_nd(struct iwl_mvm *mvm)
937 {
938         kfree(mvm->nd_match_sets);
939         mvm->nd_match_sets = NULL;
940         mvm->n_nd_match_sets = 0;
941         kfree(mvm->nd_channels);
942         mvm->nd_channels = NULL;
943         mvm->n_nd_channels = 0;
944 }
945
946 static int __iwl_mvm_suspend(struct ieee80211_hw *hw,
947                              struct cfg80211_wowlan *wowlan,
948                              bool test)
949 {
950         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
951         struct ieee80211_vif *vif = NULL;
952         struct iwl_mvm_vif *mvmvif = NULL;
953         struct ieee80211_sta *ap_sta = NULL;
954         struct iwl_d3_manager_config d3_cfg_cmd_data = {
955                 /*
956                  * Program the minimum sleep time to 10 seconds, as many
957                  * platforms have issues processing a wakeup signal while
958                  * still being in the process of suspending.
959                  */
960                 .min_sleep_time = cpu_to_le32(10 * 1000 * 1000),
961         };
962         struct iwl_host_cmd d3_cfg_cmd = {
963                 .id = D3_CONFIG_CMD,
964                 .flags = CMD_WANT_SKB,
965                 .data[0] = &d3_cfg_cmd_data,
966                 .len[0] = sizeof(d3_cfg_cmd_data),
967         };
968         int ret;
969         int len __maybe_unused;
970         bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
971                                          IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
972
973         if (!wowlan) {
974                 /*
975                  * mac80211 shouldn't get here, but for D3 test
976                  * it doesn't warrant a warning
977                  */
978                 WARN_ON(!test);
979                 return -EINVAL;
980         }
981
982         mutex_lock(&mvm->mutex);
983
984         vif = iwl_mvm_get_bss_vif(mvm);
985         if (IS_ERR_OR_NULL(vif)) {
986                 ret = 1;
987                 goto out_noreset;
988         }
989
990         mvmvif = iwl_mvm_vif_from_mac80211(vif);
991
992         if (mvmvif->ap_sta_id == IWL_MVM_INVALID_STA) {
993                 /* if we're not associated, this must be netdetect */
994                 if (!wowlan->nd_config) {
995                         ret = 1;
996                         goto out_noreset;
997                 }
998
999                 ret = iwl_mvm_netdetect_config(
1000                         mvm, wowlan, wowlan->nd_config, vif);
1001                 if (ret)
1002                         goto out;
1003
1004                 mvm->net_detect = true;
1005         } else {
1006                 struct iwl_wowlan_config_cmd wowlan_config_cmd = {};
1007
1008                 ap_sta = rcu_dereference_protected(
1009                         mvm->fw_id_to_mac_id[mvmvif->ap_sta_id],
1010                         lockdep_is_held(&mvm->mutex));
1011                 if (IS_ERR_OR_NULL(ap_sta)) {
1012                         ret = -EINVAL;
1013                         goto out_noreset;
1014                 }
1015
1016                 ret = iwl_mvm_get_wowlan_config(mvm, wowlan, &wowlan_config_cmd,
1017                                                 vif, mvmvif, ap_sta);
1018                 if (ret)
1019                         goto out_noreset;
1020                 ret = iwl_mvm_wowlan_config(mvm, wowlan, &wowlan_config_cmd,
1021                                             vif, mvmvif, ap_sta);
1022                 if (ret)
1023                         goto out;
1024
1025                 mvm->net_detect = false;
1026         }
1027
1028         ret = iwl_mvm_power_update_device(mvm);
1029         if (ret)
1030                 goto out;
1031
1032         ret = iwl_mvm_power_update_mac(mvm);
1033         if (ret)
1034                 goto out;
1035
1036 #ifdef CONFIG_IWLWIFI_DEBUGFS
1037         if (mvm->d3_wake_sysassert)
1038                 d3_cfg_cmd_data.wakeup_flags |=
1039                         cpu_to_le32(IWL_WAKEUP_D3_CONFIG_FW_ERROR);
1040 #endif
1041
1042         /*
1043          * TODO: this is needed because the firmware is not stopping
1044          * the recording automatically before entering D3.  This can
1045          * be removed once the FW starts doing that.
1046          */
1047         iwl_fw_dbg_stop_recording(&mvm->fwrt);
1048
1049         /* must be last -- this switches firmware state */
1050         ret = iwl_mvm_send_cmd(mvm, &d3_cfg_cmd);
1051         if (ret)
1052                 goto out;
1053 #ifdef CONFIG_IWLWIFI_DEBUGFS
1054         len = iwl_rx_packet_payload_len(d3_cfg_cmd.resp_pkt);
1055         if (len >= sizeof(u32)) {
1056                 mvm->d3_test_pme_ptr =
1057                         le32_to_cpup((__le32 *)d3_cfg_cmd.resp_pkt->data);
1058         }
1059 #endif
1060         iwl_free_resp(&d3_cfg_cmd);
1061
1062         clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1063
1064         iwl_trans_d3_suspend(mvm->trans, test, !unified_image);
1065  out:
1066         if (ret < 0) {
1067                 iwl_mvm_free_nd(mvm);
1068
1069                 if (!unified_image) {
1070                         iwl_mvm_ref(mvm, IWL_MVM_REF_UCODE_DOWN);
1071                         if (mvm->fw_restart > 0) {
1072                                 mvm->fw_restart--;
1073                                 ieee80211_restart_hw(mvm->hw);
1074                         }
1075                 }
1076         }
1077  out_noreset:
1078         mutex_unlock(&mvm->mutex);
1079
1080         return ret;
1081 }
1082
1083 static int iwl_mvm_enter_d0i3_sync(struct iwl_mvm *mvm)
1084 {
1085         struct iwl_notification_wait wait_d3;
1086         static const u16 d3_notif[] = { D3_CONFIG_CMD };
1087         int ret;
1088
1089         iwl_init_notification_wait(&mvm->notif_wait, &wait_d3,
1090                                    d3_notif, ARRAY_SIZE(d3_notif),
1091                                    NULL, NULL);
1092
1093         ret = iwl_mvm_enter_d0i3(mvm->hw->priv);
1094         if (ret)
1095                 goto remove_notif;
1096
1097         ret = iwl_wait_notification(&mvm->notif_wait, &wait_d3, HZ);
1098         WARN_ON_ONCE(ret);
1099         return ret;
1100
1101 remove_notif:
1102         iwl_remove_notification(&mvm->notif_wait, &wait_d3);
1103         return ret;
1104 }
1105
1106 int iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan)
1107 {
1108         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1109         struct iwl_trans *trans = mvm->trans;
1110         int ret;
1111
1112         /* make sure the d0i3 exit work is not pending */
1113         flush_work(&mvm->d0i3_exit_work);
1114         iwl_mvm_pause_tcm(mvm, true);
1115
1116         iwl_fw_runtime_suspend(&mvm->fwrt);
1117
1118         ret = iwl_trans_suspend(trans);
1119         if (ret)
1120                 return ret;
1121
1122         if (wowlan->any) {
1123                 trans->system_pm_mode = IWL_PLAT_PM_MODE_D0I3;
1124
1125                 if (iwl_mvm_enter_d0i3_on_suspend(mvm)) {
1126                         ret = iwl_mvm_enter_d0i3_sync(mvm);
1127
1128                         if (ret)
1129                                 return ret;
1130                 }
1131
1132                 mutex_lock(&mvm->d0i3_suspend_mutex);
1133                 __set_bit(D0I3_DEFER_WAKEUP, &mvm->d0i3_suspend_flags);
1134                 mutex_unlock(&mvm->d0i3_suspend_mutex);
1135
1136                 iwl_trans_d3_suspend(trans, false, false);
1137
1138                 return 0;
1139         }
1140
1141         trans->system_pm_mode = IWL_PLAT_PM_MODE_D3;
1142
1143         return __iwl_mvm_suspend(hw, wowlan, false);
1144 }
1145
1146 /* converted data from the different status responses */
1147 struct iwl_wowlan_status_data {
1148         u16 pattern_number;
1149         u16 qos_seq_ctr[8];
1150         u32 wakeup_reasons;
1151         u32 wake_packet_length;
1152         u32 wake_packet_bufsize;
1153         const u8 *wake_packet;
1154 };
1155
1156 static void iwl_mvm_report_wakeup_reasons(struct iwl_mvm *mvm,
1157                                           struct ieee80211_vif *vif,
1158                                           struct iwl_wowlan_status_data *status)
1159 {
1160         struct sk_buff *pkt = NULL;
1161         struct cfg80211_wowlan_wakeup wakeup = {
1162                 .pattern_idx = -1,
1163         };
1164         struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup;
1165         u32 reasons = status->wakeup_reasons;
1166
1167         if (reasons == IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS) {
1168                 wakeup_report = NULL;
1169                 goto report;
1170         }
1171
1172         pm_wakeup_event(mvm->dev, 0);
1173
1174         if (reasons & IWL_WOWLAN_WAKEUP_BY_MAGIC_PACKET)
1175                 wakeup.magic_pkt = true;
1176
1177         if (reasons & IWL_WOWLAN_WAKEUP_BY_PATTERN)
1178                 wakeup.pattern_idx =
1179                         status->pattern_number;
1180
1181         if (reasons & (IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON |
1182                        IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH))
1183                 wakeup.disconnect = true;
1184
1185         if (reasons & IWL_WOWLAN_WAKEUP_BY_GTK_REKEY_FAILURE)
1186                 wakeup.gtk_rekey_failure = true;
1187
1188         if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED)
1189                 wakeup.rfkill_release = true;
1190
1191         if (reasons & IWL_WOWLAN_WAKEUP_BY_EAPOL_REQUEST)
1192                 wakeup.eap_identity_req = true;
1193
1194         if (reasons & IWL_WOWLAN_WAKEUP_BY_FOUR_WAY_HANDSHAKE)
1195                 wakeup.four_way_handshake = true;
1196
1197         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_LINK_LOSS)
1198                 wakeup.tcp_connlost = true;
1199
1200         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_SIGNATURE_TABLE)
1201                 wakeup.tcp_nomoretokens = true;
1202
1203         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_WAKEUP_PACKET)
1204                 wakeup.tcp_match = true;
1205
1206         if (status->wake_packet_bufsize) {
1207                 int pktsize = status->wake_packet_bufsize;
1208                 int pktlen = status->wake_packet_length;
1209                 const u8 *pktdata = status->wake_packet;
1210                 struct ieee80211_hdr *hdr = (void *)pktdata;
1211                 int truncated = pktlen - pktsize;
1212
1213                 /* this would be a firmware bug */
1214                 if (WARN_ON_ONCE(truncated < 0))
1215                         truncated = 0;
1216
1217                 if (ieee80211_is_data(hdr->frame_control)) {
1218                         int hdrlen = ieee80211_hdrlen(hdr->frame_control);
1219                         int ivlen = 0, icvlen = 4; /* also FCS */
1220
1221                         pkt = alloc_skb(pktsize, GFP_KERNEL);
1222                         if (!pkt)
1223                                 goto report;
1224
1225                         skb_put_data(pkt, pktdata, hdrlen);
1226                         pktdata += hdrlen;
1227                         pktsize -= hdrlen;
1228
1229                         if (ieee80211_has_protected(hdr->frame_control)) {
1230                                 /*
1231                                  * This is unlocked and using gtk_i(c)vlen,
1232                                  * but since everything is under RTNL still
1233                                  * that's not really a problem - changing
1234                                  * it would be difficult.
1235                                  */
1236                                 if (is_multicast_ether_addr(hdr->addr1)) {
1237                                         ivlen = mvm->gtk_ivlen;
1238                                         icvlen += mvm->gtk_icvlen;
1239                                 } else {
1240                                         ivlen = mvm->ptk_ivlen;
1241                                         icvlen += mvm->ptk_icvlen;
1242                                 }
1243                         }
1244
1245                         /* if truncated, FCS/ICV is (partially) gone */
1246                         if (truncated >= icvlen) {
1247                                 icvlen = 0;
1248                                 truncated -= icvlen;
1249                         } else {
1250                                 icvlen -= truncated;
1251                                 truncated = 0;
1252                         }
1253
1254                         pktsize -= ivlen + icvlen;
1255                         pktdata += ivlen;
1256
1257                         skb_put_data(pkt, pktdata, pktsize);
1258
1259                         if (ieee80211_data_to_8023(pkt, vif->addr, vif->type))
1260                                 goto report;
1261                         wakeup.packet = pkt->data;
1262                         wakeup.packet_present_len = pkt->len;
1263                         wakeup.packet_len = pkt->len - truncated;
1264                         wakeup.packet_80211 = false;
1265                 } else {
1266                         int fcslen = 4;
1267
1268                         if (truncated >= 4) {
1269                                 truncated -= 4;
1270                                 fcslen = 0;
1271                         } else {
1272                                 fcslen -= truncated;
1273                                 truncated = 0;
1274                         }
1275                         pktsize -= fcslen;
1276                         wakeup.packet = status->wake_packet;
1277                         wakeup.packet_present_len = pktsize;
1278                         wakeup.packet_len = pktlen - truncated;
1279                         wakeup.packet_80211 = true;
1280                 }
1281         }
1282
1283  report:
1284         ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL);
1285         kfree_skb(pkt);
1286 }
1287
1288 static void iwl_mvm_aes_sc_to_seq(struct aes_sc *sc,
1289                                   struct ieee80211_key_seq *seq)
1290 {
1291         u64 pn;
1292
1293         pn = le64_to_cpu(sc->pn);
1294         seq->ccmp.pn[0] = pn >> 40;
1295         seq->ccmp.pn[1] = pn >> 32;
1296         seq->ccmp.pn[2] = pn >> 24;
1297         seq->ccmp.pn[3] = pn >> 16;
1298         seq->ccmp.pn[4] = pn >> 8;
1299         seq->ccmp.pn[5] = pn;
1300 }
1301
1302 static void iwl_mvm_tkip_sc_to_seq(struct tkip_sc *sc,
1303                                    struct ieee80211_key_seq *seq)
1304 {
1305         seq->tkip.iv32 = le32_to_cpu(sc->iv32);
1306         seq->tkip.iv16 = le16_to_cpu(sc->iv16);
1307 }
1308
1309 static void iwl_mvm_set_aes_rx_seq(struct iwl_mvm *mvm, struct aes_sc *scs,
1310                                    struct ieee80211_sta *sta,
1311                                    struct ieee80211_key_conf *key)
1312 {
1313         int tid;
1314
1315         BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS);
1316
1317         if (sta && iwl_mvm_has_new_rx_api(mvm)) {
1318                 struct iwl_mvm_sta *mvmsta;
1319                 struct iwl_mvm_key_pn *ptk_pn;
1320
1321                 mvmsta = iwl_mvm_sta_from_mac80211(sta);
1322
1323                 ptk_pn = rcu_dereference_protected(mvmsta->ptk_pn[key->keyidx],
1324                                                    lockdep_is_held(&mvm->mutex));
1325                 if (WARN_ON(!ptk_pn))
1326                         return;
1327
1328                 for (tid = 0; tid < IWL_MAX_TID_COUNT; tid++) {
1329                         struct ieee80211_key_seq seq = {};
1330                         int i;
1331
1332                         iwl_mvm_aes_sc_to_seq(&scs[tid], &seq);
1333                         ieee80211_set_key_rx_seq(key, tid, &seq);
1334                         for (i = 1; i < mvm->trans->num_rx_queues; i++)
1335                                 memcpy(ptk_pn->q[i].pn[tid],
1336                                        seq.ccmp.pn, IEEE80211_CCMP_PN_LEN);
1337                 }
1338         } else {
1339                 for (tid = 0; tid < IWL_NUM_RSC; tid++) {
1340                         struct ieee80211_key_seq seq = {};
1341
1342                         iwl_mvm_aes_sc_to_seq(&scs[tid], &seq);
1343                         ieee80211_set_key_rx_seq(key, tid, &seq);
1344                 }
1345         }
1346 }
1347
1348 static void iwl_mvm_set_tkip_rx_seq(struct tkip_sc *scs,
1349                                     struct ieee80211_key_conf *key)
1350 {
1351         int tid;
1352
1353         BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS);
1354
1355         for (tid = 0; tid < IWL_NUM_RSC; tid++) {
1356                 struct ieee80211_key_seq seq = {};
1357
1358                 iwl_mvm_tkip_sc_to_seq(&scs[tid], &seq);
1359                 ieee80211_set_key_rx_seq(key, tid, &seq);
1360         }
1361 }
1362
1363 static void iwl_mvm_set_key_rx_seq(struct iwl_mvm *mvm,
1364                                    struct ieee80211_key_conf *key,
1365                                    struct iwl_wowlan_status *status)
1366 {
1367         union iwl_all_tsc_rsc *rsc = &status->gtk.rsc.all_tsc_rsc;
1368
1369         switch (key->cipher) {
1370         case WLAN_CIPHER_SUITE_CCMP:
1371                 iwl_mvm_set_aes_rx_seq(mvm, rsc->aes.multicast_rsc, NULL, key);
1372                 break;
1373         case WLAN_CIPHER_SUITE_TKIP:
1374                 iwl_mvm_set_tkip_rx_seq(rsc->tkip.multicast_rsc, key);
1375                 break;
1376         default:
1377                 WARN_ON(1);
1378         }
1379 }
1380
1381 struct iwl_mvm_d3_gtk_iter_data {
1382         struct iwl_mvm *mvm;
1383         struct iwl_wowlan_status *status;
1384         void *last_gtk;
1385         u32 cipher;
1386         bool find_phase, unhandled_cipher;
1387         int num_keys;
1388 };
1389
1390 static void iwl_mvm_d3_update_keys(struct ieee80211_hw *hw,
1391                                    struct ieee80211_vif *vif,
1392                                    struct ieee80211_sta *sta,
1393                                    struct ieee80211_key_conf *key,
1394                                    void *_data)
1395 {
1396         struct iwl_mvm_d3_gtk_iter_data *data = _data;
1397
1398         if (data->unhandled_cipher)
1399                 return;
1400
1401         switch (key->cipher) {
1402         case WLAN_CIPHER_SUITE_WEP40:
1403         case WLAN_CIPHER_SUITE_WEP104:
1404                 /* ignore WEP completely, nothing to do */
1405                 return;
1406         case WLAN_CIPHER_SUITE_CCMP:
1407         case WLAN_CIPHER_SUITE_TKIP:
1408                 /* we support these */
1409                 break;
1410         default:
1411                 /* everything else (even CMAC for MFP) - disconnect from AP */
1412                 data->unhandled_cipher = true;
1413                 return;
1414         }
1415
1416         data->num_keys++;
1417
1418         /*
1419          * pairwise key - update sequence counters only;
1420          * note that this assumes no TDLS sessions are active
1421          */
1422         if (sta) {
1423                 struct ieee80211_key_seq seq = {};
1424                 union iwl_all_tsc_rsc *sc = &data->status->gtk.rsc.all_tsc_rsc;
1425
1426                 if (data->find_phase)
1427                         return;
1428
1429                 switch (key->cipher) {
1430                 case WLAN_CIPHER_SUITE_CCMP:
1431                         iwl_mvm_set_aes_rx_seq(data->mvm, sc->aes.unicast_rsc,
1432                                                sta, key);
1433                         atomic64_set(&key->tx_pn, le64_to_cpu(sc->aes.tsc.pn));
1434                         break;
1435                 case WLAN_CIPHER_SUITE_TKIP:
1436                         iwl_mvm_tkip_sc_to_seq(&sc->tkip.tsc, &seq);
1437                         iwl_mvm_set_tkip_rx_seq(sc->tkip.unicast_rsc, key);
1438                         atomic64_set(&key->tx_pn,
1439                                      (u64)seq.tkip.iv16 |
1440                                      ((u64)seq.tkip.iv32 << 16));
1441                         break;
1442                 }
1443
1444                 /* that's it for this key */
1445                 return;
1446         }
1447
1448         if (data->find_phase) {
1449                 data->last_gtk = key;
1450                 data->cipher = key->cipher;
1451                 return;
1452         }
1453
1454         if (data->status->num_of_gtk_rekeys)
1455                 ieee80211_remove_key(key);
1456         else if (data->last_gtk == key)
1457                 iwl_mvm_set_key_rx_seq(data->mvm, key, data->status);
1458 }
1459
1460 static bool iwl_mvm_setup_connection_keep(struct iwl_mvm *mvm,
1461                                           struct ieee80211_vif *vif,
1462                                           struct iwl_wowlan_status *status)
1463 {
1464         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1465         struct iwl_mvm_d3_gtk_iter_data gtkdata = {
1466                 .mvm = mvm,
1467                 .status = status,
1468         };
1469         u32 disconnection_reasons =
1470                 IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON |
1471                 IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH;
1472
1473         if (!status || !vif->bss_conf.bssid)
1474                 return false;
1475
1476         if (le32_to_cpu(status->wakeup_reasons) & disconnection_reasons)
1477                 return false;
1478
1479         /* find last GTK that we used initially, if any */
1480         gtkdata.find_phase = true;
1481         ieee80211_iter_keys(mvm->hw, vif,
1482                             iwl_mvm_d3_update_keys, &gtkdata);
1483         /* not trying to keep connections with MFP/unhandled ciphers */
1484         if (gtkdata.unhandled_cipher)
1485                 return false;
1486         if (!gtkdata.num_keys)
1487                 goto out;
1488         if (!gtkdata.last_gtk)
1489                 return false;
1490
1491         /*
1492          * invalidate all other GTKs that might still exist and update
1493          * the one that we used
1494          */
1495         gtkdata.find_phase = false;
1496         ieee80211_iter_keys(mvm->hw, vif,
1497                             iwl_mvm_d3_update_keys, &gtkdata);
1498
1499         if (status->num_of_gtk_rekeys) {
1500                 struct ieee80211_key_conf *key;
1501                 struct {
1502                         struct ieee80211_key_conf conf;
1503                         u8 key[32];
1504                 } conf = {
1505                         .conf.cipher = gtkdata.cipher,
1506                         .conf.keyidx = status->gtk.key_index,
1507                 };
1508
1509                 switch (gtkdata.cipher) {
1510                 case WLAN_CIPHER_SUITE_CCMP:
1511                         conf.conf.keylen = WLAN_KEY_LEN_CCMP;
1512                         memcpy(conf.conf.key, status->gtk.decrypt_key,
1513                                WLAN_KEY_LEN_CCMP);
1514                         break;
1515                 case WLAN_CIPHER_SUITE_TKIP:
1516                         conf.conf.keylen = WLAN_KEY_LEN_TKIP;
1517                         memcpy(conf.conf.key, status->gtk.decrypt_key, 16);
1518                         /* leave TX MIC key zeroed, we don't use it anyway */
1519                         memcpy(conf.conf.key +
1520                                NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY,
1521                                status->gtk.tkip_mic_key, 8);
1522                         break;
1523                 }
1524
1525                 key = ieee80211_gtk_rekey_add(vif, &conf.conf);
1526                 if (IS_ERR(key))
1527                         return false;
1528                 iwl_mvm_set_key_rx_seq(mvm, key, status);
1529         }
1530
1531         if (status->num_of_gtk_rekeys) {
1532                 __be64 replay_ctr =
1533                         cpu_to_be64(le64_to_cpu(status->replay_ctr));
1534                 ieee80211_gtk_rekey_notify(vif, vif->bss_conf.bssid,
1535                                            (void *)&replay_ctr, GFP_KERNEL);
1536         }
1537
1538 out:
1539         mvmvif->seqno_valid = true;
1540         /* +0x10 because the set API expects next-to-use, not last-used */
1541         mvmvif->seqno = le16_to_cpu(status->non_qos_seq_ctr) + 0x10;
1542
1543         return true;
1544 }
1545
1546 static struct iwl_wowlan_status *
1547 iwl_mvm_get_wakeup_status(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1548 {
1549         u32 base = mvm->error_event_table[0];
1550         struct error_table_start {
1551                 /* cf. struct iwl_error_event_table */
1552                 u32 valid;
1553                 u32 error_id;
1554         } err_info;
1555         struct iwl_host_cmd cmd = {
1556                 .id = WOWLAN_GET_STATUSES,
1557                 .flags = CMD_WANT_SKB,
1558         };
1559         struct iwl_wowlan_status *status, *fw_status;
1560         int ret, len, status_size;
1561
1562         iwl_trans_read_mem_bytes(mvm->trans, base,
1563                                  &err_info, sizeof(err_info));
1564
1565         if (err_info.valid) {
1566                 IWL_INFO(mvm, "error table is valid (%d) with error (%d)\n",
1567                          err_info.valid, err_info.error_id);
1568                 if (err_info.error_id == RF_KILL_INDICATOR_FOR_WOWLAN) {
1569                         struct cfg80211_wowlan_wakeup wakeup = {
1570                                 .rfkill_release = true,
1571                         };
1572                         ieee80211_report_wowlan_wakeup(vif, &wakeup,
1573                                                        GFP_KERNEL);
1574                 }
1575                 return ERR_PTR(-EIO);
1576         }
1577
1578         /* only for tracing for now */
1579         ret = iwl_mvm_send_cmd_pdu(mvm, OFFLOADS_QUERY_CMD, 0, 0, NULL);
1580         if (ret)
1581                 IWL_ERR(mvm, "failed to query offload statistics (%d)\n", ret);
1582
1583         ret = iwl_mvm_send_cmd(mvm, &cmd);
1584         if (ret) {
1585                 IWL_ERR(mvm, "failed to query status (%d)\n", ret);
1586                 return ERR_PTR(ret);
1587         }
1588
1589         status_size = sizeof(*fw_status);
1590
1591         len = iwl_rx_packet_payload_len(cmd.resp_pkt);
1592         if (len < status_size) {
1593                 IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1594                 fw_status = ERR_PTR(-EIO);
1595                 goto out_free_resp;
1596         }
1597
1598         status = (void *)cmd.resp_pkt->data;
1599         if (len != (status_size +
1600                     ALIGN(le32_to_cpu(status->wake_packet_bufsize), 4))) {
1601                 IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1602                 fw_status = ERR_PTR(-EIO);
1603                 goto out_free_resp;
1604         }
1605
1606         fw_status = kmemdup(status, len, GFP_KERNEL);
1607
1608 out_free_resp:
1609         iwl_free_resp(&cmd);
1610         return fw_status;
1611 }
1612
1613 /* releases the MVM mutex */
1614 static bool iwl_mvm_query_wakeup_reasons(struct iwl_mvm *mvm,
1615                                          struct ieee80211_vif *vif)
1616 {
1617         struct iwl_wowlan_status_data status;
1618         struct iwl_wowlan_status *fw_status;
1619         int i;
1620         bool keep;
1621         struct iwl_mvm_sta *mvm_ap_sta;
1622
1623         fw_status = iwl_mvm_get_wakeup_status(mvm, vif);
1624         if (IS_ERR_OR_NULL(fw_status))
1625                 goto out_unlock;
1626
1627         status.pattern_number = le16_to_cpu(fw_status->pattern_number);
1628         for (i = 0; i < 8; i++)
1629                 status.qos_seq_ctr[i] =
1630                         le16_to_cpu(fw_status->qos_seq_ctr[i]);
1631         status.wakeup_reasons = le32_to_cpu(fw_status->wakeup_reasons);
1632         status.wake_packet_length =
1633                 le32_to_cpu(fw_status->wake_packet_length);
1634         status.wake_packet_bufsize =
1635                 le32_to_cpu(fw_status->wake_packet_bufsize);
1636         status.wake_packet = fw_status->wake_packet;
1637
1638         /* still at hard-coded place 0 for D3 image */
1639         mvm_ap_sta = iwl_mvm_sta_from_staid_protected(mvm, 0);
1640         if (!mvm_ap_sta)
1641                 goto out_free;
1642
1643         for (i = 0; i < IWL_MAX_TID_COUNT; i++) {
1644                 u16 seq = status.qos_seq_ctr[i];
1645                 /* firmware stores last-used value, we store next value */
1646                 seq += 0x10;
1647                 mvm_ap_sta->tid_data[i].seq_number = seq;
1648         }
1649
1650         /* now we have all the data we need, unlock to avoid mac80211 issues */
1651         mutex_unlock(&mvm->mutex);
1652
1653         iwl_mvm_report_wakeup_reasons(mvm, vif, &status);
1654
1655         keep = iwl_mvm_setup_connection_keep(mvm, vif, fw_status);
1656
1657         kfree(fw_status);
1658         return keep;
1659
1660 out_free:
1661         kfree(fw_status);
1662 out_unlock:
1663         mutex_unlock(&mvm->mutex);
1664         return false;
1665 }
1666
1667 void iwl_mvm_d0i3_update_keys(struct iwl_mvm *mvm,
1668                               struct ieee80211_vif *vif,
1669                               struct iwl_wowlan_status *status)
1670 {
1671         struct iwl_mvm_d3_gtk_iter_data gtkdata = {
1672                 .mvm = mvm,
1673                 .status = status,
1674         };
1675
1676         /*
1677          * rekey handling requires taking locks that can't be taken now.
1678          * however, d0i3 doesn't offload rekey, so we're fine.
1679          */
1680         if (WARN_ON_ONCE(status->num_of_gtk_rekeys))
1681                 return;
1682
1683         /* find last GTK that we used initially, if any */
1684         gtkdata.find_phase = true;
1685         iwl_mvm_iter_d0i3_ap_keys(mvm, vif, iwl_mvm_d3_update_keys, &gtkdata);
1686
1687         gtkdata.find_phase = false;
1688         iwl_mvm_iter_d0i3_ap_keys(mvm, vif, iwl_mvm_d3_update_keys, &gtkdata);
1689 }
1690
1691 struct iwl_mvm_nd_query_results {
1692         u32 matched_profiles;
1693         struct iwl_scan_offload_profile_match matches[IWL_SCAN_MAX_PROFILES];
1694 };
1695
1696 static int
1697 iwl_mvm_netdetect_query_results(struct iwl_mvm *mvm,
1698                                 struct iwl_mvm_nd_query_results *results)
1699 {
1700         struct iwl_scan_offload_profiles_query *query;
1701         struct iwl_host_cmd cmd = {
1702                 .id = SCAN_OFFLOAD_PROFILES_QUERY_CMD,
1703                 .flags = CMD_WANT_SKB,
1704         };
1705         int ret, len;
1706
1707         ret = iwl_mvm_send_cmd(mvm, &cmd);
1708         if (ret) {
1709                 IWL_ERR(mvm, "failed to query matched profiles (%d)\n", ret);
1710                 return ret;
1711         }
1712
1713         len = iwl_rx_packet_payload_len(cmd.resp_pkt);
1714         if (len < sizeof(*query)) {
1715                 IWL_ERR(mvm, "Invalid scan offload profiles query response!\n");
1716                 ret = -EIO;
1717                 goto out_free_resp;
1718         }
1719
1720         query = (void *)cmd.resp_pkt->data;
1721
1722         results->matched_profiles = le32_to_cpu(query->matched_profiles);
1723         memcpy(results->matches, query->matches, sizeof(results->matches));
1724
1725 #ifdef CONFIG_IWLWIFI_DEBUGFS
1726         mvm->last_netdetect_scans = le32_to_cpu(query->n_scans_done);
1727 #endif
1728
1729 out_free_resp:
1730         iwl_free_resp(&cmd);
1731         return ret;
1732 }
1733
1734 static void iwl_mvm_query_netdetect_reasons(struct iwl_mvm *mvm,
1735                                             struct ieee80211_vif *vif)
1736 {
1737         struct cfg80211_wowlan_nd_info *net_detect = NULL;
1738         struct cfg80211_wowlan_wakeup wakeup = {
1739                 .pattern_idx = -1,
1740         };
1741         struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup;
1742         struct iwl_mvm_nd_query_results query;
1743         struct iwl_wowlan_status *fw_status;
1744         unsigned long matched_profiles;
1745         u32 reasons = 0;
1746         int i, j, n_matches, ret;
1747
1748         fw_status = iwl_mvm_get_wakeup_status(mvm, vif);
1749         if (!IS_ERR_OR_NULL(fw_status)) {
1750                 reasons = le32_to_cpu(fw_status->wakeup_reasons);
1751                 kfree(fw_status);
1752         }
1753
1754         if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED)
1755                 wakeup.rfkill_release = true;
1756
1757         if (reasons != IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS)
1758                 goto out;
1759
1760         ret = iwl_mvm_netdetect_query_results(mvm, &query);
1761         if (ret || !query.matched_profiles) {
1762                 wakeup_report = NULL;
1763                 goto out;
1764         }
1765
1766         matched_profiles = query.matched_profiles;
1767         if (mvm->n_nd_match_sets) {
1768                 n_matches = hweight_long(matched_profiles);
1769         } else {
1770                 IWL_ERR(mvm, "no net detect match information available\n");
1771                 n_matches = 0;
1772         }
1773
1774         net_detect = kzalloc(sizeof(*net_detect) +
1775                              (n_matches * sizeof(net_detect->matches[0])),
1776                              GFP_KERNEL);
1777         if (!net_detect || !n_matches)
1778                 goto out_report_nd;
1779
1780         for_each_set_bit(i, &matched_profiles, mvm->n_nd_match_sets) {
1781                 struct iwl_scan_offload_profile_match *fw_match;
1782                 struct cfg80211_wowlan_nd_match *match;
1783                 int idx, n_channels = 0;
1784
1785                 fw_match = &query.matches[i];
1786
1787                 for (j = 0; j < SCAN_OFFLOAD_MATCHING_CHANNELS_LEN; j++)
1788                         n_channels += hweight8(fw_match->matching_channels[j]);
1789
1790                 match = kzalloc(sizeof(*match) +
1791                                 (n_channels * sizeof(*match->channels)),
1792                                 GFP_KERNEL);
1793                 if (!match)
1794                         goto out_report_nd;
1795
1796                 net_detect->matches[net_detect->n_matches++] = match;
1797
1798                 /* We inverted the order of the SSIDs in the scan
1799                  * request, so invert the index here.
1800                  */
1801                 idx = mvm->n_nd_match_sets - i - 1;
1802                 match->ssid.ssid_len = mvm->nd_match_sets[idx].ssid.ssid_len;
1803                 memcpy(match->ssid.ssid, mvm->nd_match_sets[idx].ssid.ssid,
1804                        match->ssid.ssid_len);
1805
1806                 if (mvm->n_nd_channels < n_channels)
1807                         continue;
1808
1809                 for (j = 0; j < SCAN_OFFLOAD_MATCHING_CHANNELS_LEN * 8; j++)
1810                         if (fw_match->matching_channels[j / 8] & (BIT(j % 8)))
1811                                 match->channels[match->n_channels++] =
1812                                         mvm->nd_channels[j]->center_freq;
1813         }
1814
1815 out_report_nd:
1816         wakeup.net_detect = net_detect;
1817 out:
1818         iwl_mvm_free_nd(mvm);
1819
1820         mutex_unlock(&mvm->mutex);
1821         ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL);
1822
1823         if (net_detect) {
1824                 for (i = 0; i < net_detect->n_matches; i++)
1825                         kfree(net_detect->matches[i]);
1826                 kfree(net_detect);
1827         }
1828 }
1829
1830 static void iwl_mvm_read_d3_sram(struct iwl_mvm *mvm)
1831 {
1832 #ifdef CONFIG_IWLWIFI_DEBUGFS
1833         const struct fw_img *img = &mvm->fw->img[IWL_UCODE_WOWLAN];
1834         u32 len = img->sec[IWL_UCODE_SECTION_DATA].len;
1835         u32 offs = img->sec[IWL_UCODE_SECTION_DATA].offset;
1836
1837         if (!mvm->store_d3_resume_sram)
1838                 return;
1839
1840         if (!mvm->d3_resume_sram) {
1841                 mvm->d3_resume_sram = kzalloc(len, GFP_KERNEL);
1842                 if (!mvm->d3_resume_sram)
1843                         return;
1844         }
1845
1846         iwl_trans_read_mem_bytes(mvm->trans, offs, mvm->d3_resume_sram, len);
1847 #endif
1848 }
1849
1850 static void iwl_mvm_d3_disconnect_iter(void *data, u8 *mac,
1851                                        struct ieee80211_vif *vif)
1852 {
1853         /* skip the one we keep connection on */
1854         if (data == vif)
1855                 return;
1856
1857         if (vif->type == NL80211_IFTYPE_STATION)
1858                 ieee80211_resume_disconnect(vif);
1859 }
1860
1861 static int __iwl_mvm_resume(struct iwl_mvm *mvm, bool test)
1862 {
1863         struct ieee80211_vif *vif = NULL;
1864         int ret = 1;
1865         enum iwl_d3_status d3_status;
1866         bool keep = false;
1867         bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
1868                                          IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
1869         bool d0i3_first = fw_has_capa(&mvm->fw->ucode_capa,
1870                                       IWL_UCODE_TLV_CAPA_D0I3_END_FIRST);
1871
1872         mutex_lock(&mvm->mutex);
1873
1874         /* get the BSS vif pointer again */
1875         vif = iwl_mvm_get_bss_vif(mvm);
1876         if (IS_ERR_OR_NULL(vif))
1877                 goto err;
1878
1879         ret = iwl_trans_d3_resume(mvm->trans, &d3_status, test, !unified_image);
1880         if (ret)
1881                 goto err;
1882
1883         if (d3_status != IWL_D3_STATUS_ALIVE) {
1884                 IWL_INFO(mvm, "Device was reset during suspend\n");
1885                 goto err;
1886         }
1887
1888         /* query SRAM first in case we want event logging */
1889         iwl_mvm_read_d3_sram(mvm);
1890
1891         if (d0i3_first) {
1892                 ret = iwl_mvm_send_cmd_pdu(mvm, D0I3_END_CMD, 0, 0, NULL);
1893                 if (ret < 0) {
1894                         IWL_ERR(mvm, "Failed to send D0I3_END_CMD first (%d)\n",
1895                                 ret);
1896                         goto err;
1897                 }
1898         }
1899
1900         /*
1901          * Query the current location and source from the D3 firmware so we
1902          * can play it back when we re-intiailize the D0 firmware
1903          */
1904         iwl_mvm_update_changed_regdom(mvm);
1905
1906         if (!unified_image)
1907                 /*  Re-configure default SAR profile */
1908                 iwl_mvm_sar_select_profile(mvm, 1, 1);
1909
1910         if (mvm->net_detect) {
1911                 /* If this is a non-unified image, we restart the FW,
1912                  * so no need to stop the netdetect scan.  If that
1913                  * fails, continue and try to get the wake-up reasons,
1914                  * but trigger a HW restart by keeping a failure code
1915                  * in ret.
1916                  */
1917                 if (unified_image)
1918                         ret = iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_NETDETECT,
1919                                                 false);
1920
1921                 iwl_mvm_query_netdetect_reasons(mvm, vif);
1922                 /* has unlocked the mutex, so skip that */
1923                 goto out;
1924         } else {
1925                 keep = iwl_mvm_query_wakeup_reasons(mvm, vif);
1926 #ifdef CONFIG_IWLWIFI_DEBUGFS
1927                 if (keep)
1928                         mvm->keep_vif = vif;
1929 #endif
1930                 /* has unlocked the mutex, so skip that */
1931                 goto out_iterate;
1932         }
1933
1934 err:
1935         iwl_mvm_free_nd(mvm);
1936         mutex_unlock(&mvm->mutex);
1937
1938 out_iterate:
1939         if (!test)
1940                 ieee80211_iterate_active_interfaces_rtnl(mvm->hw,
1941                         IEEE80211_IFACE_ITER_NORMAL,
1942                         iwl_mvm_d3_disconnect_iter, keep ? vif : NULL);
1943
1944 out:
1945         /* no need to reset the device in unified images, if successful */
1946         if (unified_image && !ret) {
1947                 /* nothing else to do if we already sent D0I3_END_CMD */
1948                 if (d0i3_first)
1949                         return 0;
1950
1951                 ret = iwl_mvm_send_cmd_pdu(mvm, D0I3_END_CMD, 0, 0, NULL);
1952                 if (!ret)
1953                         return 0;
1954         }
1955
1956         /*
1957          * Reconfigure the device in one of the following cases:
1958          * 1. We are not using a unified image
1959          * 2. We are using a unified image but had an error while exiting D3
1960          */
1961         set_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED, &mvm->status);
1962         set_bit(IWL_MVM_STATUS_D3_RECONFIG, &mvm->status);
1963         /*
1964          * When switching images we return 1, which causes mac80211
1965          * to do a reconfig with IEEE80211_RECONFIG_TYPE_RESTART.
1966          * This type of reconfig calls iwl_mvm_restart_complete(),
1967          * where we unref the IWL_MVM_REF_UCODE_DOWN, so we need
1968          * to take the reference here.
1969          */
1970         iwl_mvm_ref(mvm, IWL_MVM_REF_UCODE_DOWN);
1971
1972         return 1;
1973 }
1974
1975 static int iwl_mvm_resume_d3(struct iwl_mvm *mvm)
1976 {
1977         iwl_trans_resume(mvm->trans);
1978
1979         return __iwl_mvm_resume(mvm, false);
1980 }
1981
1982 static int iwl_mvm_resume_d0i3(struct iwl_mvm *mvm)
1983 {
1984         bool exit_now;
1985         enum iwl_d3_status d3_status;
1986         struct iwl_trans *trans = mvm->trans;
1987
1988         iwl_trans_d3_resume(trans, &d3_status, false, false);
1989
1990         /*
1991          * make sure to clear D0I3_DEFER_WAKEUP before
1992          * calling iwl_trans_resume(), which might wait
1993          * for d0i3 exit completion.
1994          */
1995         mutex_lock(&mvm->d0i3_suspend_mutex);
1996         __clear_bit(D0I3_DEFER_WAKEUP, &mvm->d0i3_suspend_flags);
1997         exit_now = __test_and_clear_bit(D0I3_PENDING_WAKEUP,
1998                                         &mvm->d0i3_suspend_flags);
1999         mutex_unlock(&mvm->d0i3_suspend_mutex);
2000         if (exit_now) {
2001                 IWL_DEBUG_RPM(mvm, "Run deferred d0i3 exit\n");
2002                 _iwl_mvm_exit_d0i3(mvm);
2003         }
2004
2005         iwl_trans_resume(trans);
2006
2007         if (iwl_mvm_enter_d0i3_on_suspend(mvm)) {
2008                 int ret = iwl_mvm_exit_d0i3(mvm->hw->priv);
2009
2010                 if (ret)
2011                         return ret;
2012                 /*
2013                  * d0i3 exit will be deferred until reconfig_complete.
2014                  * make sure there we are out of d0i3.
2015                  */
2016         }
2017         return 0;
2018 }
2019
2020 int iwl_mvm_resume(struct ieee80211_hw *hw)
2021 {
2022         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2023         int ret;
2024
2025         if (mvm->trans->system_pm_mode == IWL_PLAT_PM_MODE_D0I3)
2026                 ret = iwl_mvm_resume_d0i3(mvm);
2027         else
2028                 ret = iwl_mvm_resume_d3(mvm);
2029
2030         mvm->trans->system_pm_mode = IWL_PLAT_PM_MODE_DISABLED;
2031
2032         iwl_mvm_resume_tcm(mvm);
2033
2034         iwl_fw_runtime_resume(&mvm->fwrt);
2035
2036         return ret;
2037 }
2038
2039 void iwl_mvm_set_wakeup(struct ieee80211_hw *hw, bool enabled)
2040 {
2041         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2042
2043         device_set_wakeup_enable(mvm->trans->dev, enabled);
2044 }
2045
2046 #ifdef CONFIG_IWLWIFI_DEBUGFS
2047 static int iwl_mvm_d3_test_open(struct inode *inode, struct file *file)
2048 {
2049         struct iwl_mvm *mvm = inode->i_private;
2050         int err;
2051
2052         if (mvm->d3_test_active)
2053                 return -EBUSY;
2054
2055         file->private_data = inode->i_private;
2056
2057         ieee80211_stop_queues(mvm->hw);
2058         synchronize_net();
2059
2060         mvm->trans->system_pm_mode = IWL_PLAT_PM_MODE_D3;
2061
2062         iwl_mvm_pause_tcm(mvm, true);
2063
2064         iwl_fw_runtime_suspend(&mvm->fwrt);
2065
2066         /* start pseudo D3 */
2067         rtnl_lock();
2068         err = __iwl_mvm_suspend(mvm->hw, mvm->hw->wiphy->wowlan_config, true);
2069         rtnl_unlock();
2070         if (err > 0)
2071                 err = -EINVAL;
2072         if (err) {
2073                 ieee80211_wake_queues(mvm->hw);
2074                 return err;
2075         }
2076         mvm->d3_test_active = true;
2077         mvm->keep_vif = NULL;
2078         return 0;
2079 }
2080
2081 static ssize_t iwl_mvm_d3_test_read(struct file *file, char __user *user_buf,
2082                                     size_t count, loff_t *ppos)
2083 {
2084         struct iwl_mvm *mvm = file->private_data;
2085         u32 pme_asserted;
2086
2087         while (true) {
2088                 /* read pme_ptr if available */
2089                 if (mvm->d3_test_pme_ptr) {
2090                         pme_asserted = iwl_trans_read_mem32(mvm->trans,
2091                                                 mvm->d3_test_pme_ptr);
2092                         if (pme_asserted)
2093                                 break;
2094                 }
2095
2096                 if (msleep_interruptible(100))
2097                         break;
2098         }
2099
2100         return 0;
2101 }
2102
2103 static void iwl_mvm_d3_test_disconn_work_iter(void *_data, u8 *mac,
2104                                               struct ieee80211_vif *vif)
2105 {
2106         /* skip the one we keep connection on */
2107         if (_data == vif)
2108                 return;
2109
2110         if (vif->type == NL80211_IFTYPE_STATION)
2111                 ieee80211_connection_loss(vif);
2112 }
2113
2114 static int iwl_mvm_d3_test_release(struct inode *inode, struct file *file)
2115 {
2116         struct iwl_mvm *mvm = inode->i_private;
2117         bool unified_image = fw_has_capa(&mvm->fw->ucode_capa,
2118                                          IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
2119
2120         mvm->d3_test_active = false;
2121
2122         rtnl_lock();
2123         __iwl_mvm_resume(mvm, true);
2124         rtnl_unlock();
2125
2126         iwl_mvm_resume_tcm(mvm);
2127
2128         iwl_fw_runtime_resume(&mvm->fwrt);
2129
2130         mvm->trans->system_pm_mode = IWL_PLAT_PM_MODE_DISABLED;
2131
2132         iwl_abort_notification_waits(&mvm->notif_wait);
2133         if (!unified_image) {
2134                 int remaining_time = 10;
2135
2136                 ieee80211_restart_hw(mvm->hw);
2137
2138                 /* wait for restart and disconnect all interfaces */
2139                 while (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) &&
2140                        remaining_time > 0) {
2141                         remaining_time--;
2142                         msleep(1000);
2143                 }
2144
2145                 if (remaining_time == 0)
2146                         IWL_ERR(mvm, "Timed out waiting for HW restart!\n");
2147         }
2148
2149         ieee80211_iterate_active_interfaces_atomic(
2150                 mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
2151                 iwl_mvm_d3_test_disconn_work_iter, mvm->keep_vif);
2152
2153         ieee80211_wake_queues(mvm->hw);
2154
2155         return 0;
2156 }
2157
2158 const struct file_operations iwl_dbgfs_d3_test_ops = {
2159         .llseek = no_llseek,
2160         .open = iwl_mvm_d3_test_open,
2161         .read = iwl_mvm_d3_test_read,
2162         .release = iwl_mvm_d3_test_release,
2163 };
2164 #endif