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