Merge tag 'iwlwifi-next-for-kalle-2014-12-30' of https://git.kernel.org/pub/scm/linux...
[cascardo/linux.git] / 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 - 2014 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 - 2014 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                         u8 *pn = seq.ccmp.pn;
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                         ieee80211_get_key_tx_seq(key, &seq);
283                         aes_tx_sc->pn = cpu_to_le64((u64)pn[5] |
284                                                     ((u64)pn[4] << 8) |
285                                                     ((u64)pn[3] << 16) |
286                                                     ((u64)pn[2] << 24) |
287                                                     ((u64)pn[1] << 32) |
288                                                     ((u64)pn[0] << 40));
289                 } else {
290                         aes_sc = data->rsc_tsc->all_tsc_rsc.aes.multicast_rsc;
291                 }
292
293                 /*
294                  * For non-QoS this relies on the fact that both the uCode and
295                  * mac80211 use TID 0 for checking the IV in the frames.
296                  */
297                 for (i = 0; i < IWL_NUM_RSC; i++) {
298                         u8 *pn = seq.ccmp.pn;
299
300                         ieee80211_get_key_rx_seq(key, i, &seq);
301                         aes_sc->pn = cpu_to_le64((u64)pn[5] |
302                                                  ((u64)pn[4] << 8) |
303                                                  ((u64)pn[3] << 16) |
304                                                  ((u64)pn[2] << 24) |
305                                                  ((u64)pn[1] << 32) |
306                                                  ((u64)pn[0] << 40));
307                 }
308                 data->use_rsc_tsc = true;
309                 break;
310         }
311
312         /*
313          * The D3 firmware hardcodes the key offset 0 as the key it uses
314          * to transmit packets to the AP, i.e. the PTK.
315          */
316         if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) {
317                 key->hw_key_idx = 0;
318                 mvm->ptk_ivlen = key->iv_len;
319                 mvm->ptk_icvlen = key->icv_len;
320         } else {
321                 /*
322                  * firmware only supports TSC/RSC for a single key,
323                  * so if there are multiple keep overwriting them
324                  * with new ones -- this relies on mac80211 doing
325                  * list_add_tail().
326                  */
327                 key->hw_key_idx = 1;
328                 mvm->gtk_ivlen = key->iv_len;
329                 mvm->gtk_icvlen = key->icv_len;
330         }
331
332         ret = iwl_mvm_set_sta_key(mvm, vif, sta, key, true);
333         data->error = ret != 0;
334 out_unlock:
335         mutex_unlock(&mvm->mutex);
336 }
337
338 static int iwl_mvm_send_patterns(struct iwl_mvm *mvm,
339                                  struct cfg80211_wowlan *wowlan)
340 {
341         struct iwl_wowlan_patterns_cmd *pattern_cmd;
342         struct iwl_host_cmd cmd = {
343                 .id = WOWLAN_PATTERNS,
344                 .dataflags[0] = IWL_HCMD_DFL_NOCOPY,
345         };
346         int i, err;
347
348         if (!wowlan->n_patterns)
349                 return 0;
350
351         cmd.len[0] = sizeof(*pattern_cmd) +
352                 wowlan->n_patterns * sizeof(struct iwl_wowlan_pattern);
353
354         pattern_cmd = kmalloc(cmd.len[0], GFP_KERNEL);
355         if (!pattern_cmd)
356                 return -ENOMEM;
357
358         pattern_cmd->n_patterns = cpu_to_le32(wowlan->n_patterns);
359
360         for (i = 0; i < wowlan->n_patterns; i++) {
361                 int mask_len = DIV_ROUND_UP(wowlan->patterns[i].pattern_len, 8);
362
363                 memcpy(&pattern_cmd->patterns[i].mask,
364                        wowlan->patterns[i].mask, mask_len);
365                 memcpy(&pattern_cmd->patterns[i].pattern,
366                        wowlan->patterns[i].pattern,
367                        wowlan->patterns[i].pattern_len);
368                 pattern_cmd->patterns[i].mask_size = mask_len;
369                 pattern_cmd->patterns[i].pattern_size =
370                         wowlan->patterns[i].pattern_len;
371         }
372
373         cmd.data[0] = pattern_cmd;
374         err = iwl_mvm_send_cmd(mvm, &cmd);
375         kfree(pattern_cmd);
376         return err;
377 }
378
379 enum iwl_mvm_tcp_packet_type {
380         MVM_TCP_TX_SYN,
381         MVM_TCP_RX_SYNACK,
382         MVM_TCP_TX_DATA,
383         MVM_TCP_RX_ACK,
384         MVM_TCP_RX_WAKE,
385         MVM_TCP_TX_FIN,
386 };
387
388 static __le16 pseudo_hdr_check(int len, __be32 saddr, __be32 daddr)
389 {
390         __sum16 check = tcp_v4_check(len, saddr, daddr, 0);
391         return cpu_to_le16(be16_to_cpu((__force __be16)check));
392 }
393
394 static void iwl_mvm_build_tcp_packet(struct ieee80211_vif *vif,
395                                      struct cfg80211_wowlan_tcp *tcp,
396                                      void *_pkt, u8 *mask,
397                                      __le16 *pseudo_hdr_csum,
398                                      enum iwl_mvm_tcp_packet_type ptype)
399 {
400         struct {
401                 struct ethhdr eth;
402                 struct iphdr ip;
403                 struct tcphdr tcp;
404                 u8 data[];
405         } __packed *pkt = _pkt;
406         u16 ip_tot_len = sizeof(struct iphdr) + sizeof(struct tcphdr);
407         int i;
408
409         pkt->eth.h_proto = cpu_to_be16(ETH_P_IP),
410         pkt->ip.version = 4;
411         pkt->ip.ihl = 5;
412         pkt->ip.protocol = IPPROTO_TCP;
413
414         switch (ptype) {
415         case MVM_TCP_TX_SYN:
416         case MVM_TCP_TX_DATA:
417         case MVM_TCP_TX_FIN:
418                 memcpy(pkt->eth.h_dest, tcp->dst_mac, ETH_ALEN);
419                 memcpy(pkt->eth.h_source, vif->addr, ETH_ALEN);
420                 pkt->ip.ttl = 128;
421                 pkt->ip.saddr = tcp->src;
422                 pkt->ip.daddr = tcp->dst;
423                 pkt->tcp.source = cpu_to_be16(tcp->src_port);
424                 pkt->tcp.dest = cpu_to_be16(tcp->dst_port);
425                 /* overwritten for TX SYN later */
426                 pkt->tcp.doff = sizeof(struct tcphdr) / 4;
427                 pkt->tcp.window = cpu_to_be16(65000);
428                 break;
429         case MVM_TCP_RX_SYNACK:
430         case MVM_TCP_RX_ACK:
431         case MVM_TCP_RX_WAKE:
432                 memcpy(pkt->eth.h_dest, vif->addr, ETH_ALEN);
433                 memcpy(pkt->eth.h_source, tcp->dst_mac, ETH_ALEN);
434                 pkt->ip.saddr = tcp->dst;
435                 pkt->ip.daddr = tcp->src;
436                 pkt->tcp.source = cpu_to_be16(tcp->dst_port);
437                 pkt->tcp.dest = cpu_to_be16(tcp->src_port);
438                 break;
439         default:
440                 WARN_ON(1);
441                 return;
442         }
443
444         switch (ptype) {
445         case MVM_TCP_TX_SYN:
446                 /* firmware assumes 8 option bytes - 8 NOPs for now */
447                 memset(pkt->data, 0x01, 8);
448                 ip_tot_len += 8;
449                 pkt->tcp.doff = (sizeof(struct tcphdr) + 8) / 4;
450                 pkt->tcp.syn = 1;
451                 break;
452         case MVM_TCP_TX_DATA:
453                 ip_tot_len += tcp->payload_len;
454                 memcpy(pkt->data, tcp->payload, tcp->payload_len);
455                 pkt->tcp.psh = 1;
456                 pkt->tcp.ack = 1;
457                 break;
458         case MVM_TCP_TX_FIN:
459                 pkt->tcp.fin = 1;
460                 pkt->tcp.ack = 1;
461                 break;
462         case MVM_TCP_RX_SYNACK:
463                 pkt->tcp.syn = 1;
464                 pkt->tcp.ack = 1;
465                 break;
466         case MVM_TCP_RX_ACK:
467                 pkt->tcp.ack = 1;
468                 break;
469         case MVM_TCP_RX_WAKE:
470                 ip_tot_len += tcp->wake_len;
471                 pkt->tcp.psh = 1;
472                 pkt->tcp.ack = 1;
473                 memcpy(pkt->data, tcp->wake_data, tcp->wake_len);
474                 break;
475         }
476
477         switch (ptype) {
478         case MVM_TCP_TX_SYN:
479         case MVM_TCP_TX_DATA:
480         case MVM_TCP_TX_FIN:
481                 pkt->ip.tot_len = cpu_to_be16(ip_tot_len);
482                 pkt->ip.check = ip_fast_csum(&pkt->ip, pkt->ip.ihl);
483                 break;
484         case MVM_TCP_RX_WAKE:
485                 for (i = 0; i < DIV_ROUND_UP(tcp->wake_len, 8); i++) {
486                         u8 tmp = tcp->wake_mask[i];
487                         mask[i + 6] |= tmp << 6;
488                         if (i + 1 < DIV_ROUND_UP(tcp->wake_len, 8))
489                                 mask[i + 7] = tmp >> 2;
490                 }
491                 /* fall through for ethernet/IP/TCP headers mask */
492         case MVM_TCP_RX_SYNACK:
493         case MVM_TCP_RX_ACK:
494                 mask[0] = 0xff; /* match ethernet */
495                 /*
496                  * match ethernet, ip.version, ip.ihl
497                  * the ip.ihl half byte is really masked out by firmware
498                  */
499                 mask[1] = 0x7f;
500                 mask[2] = 0x80; /* match ip.protocol */
501                 mask[3] = 0xfc; /* match ip.saddr, ip.daddr */
502                 mask[4] = 0x3f; /* match ip.daddr, tcp.source, tcp.dest */
503                 mask[5] = 0x80; /* match tcp flags */
504                 /* leave rest (0 or set for MVM_TCP_RX_WAKE) */
505                 break;
506         };
507
508         *pseudo_hdr_csum = pseudo_hdr_check(ip_tot_len - sizeof(struct iphdr),
509                                             pkt->ip.saddr, pkt->ip.daddr);
510 }
511
512 static int iwl_mvm_send_remote_wake_cfg(struct iwl_mvm *mvm,
513                                         struct ieee80211_vif *vif,
514                                         struct cfg80211_wowlan_tcp *tcp)
515 {
516         struct iwl_wowlan_remote_wake_config *cfg;
517         struct iwl_host_cmd cmd = {
518                 .id = REMOTE_WAKE_CONFIG_CMD,
519                 .len = { sizeof(*cfg), },
520                 .dataflags = { IWL_HCMD_DFL_NOCOPY, },
521         };
522         int ret;
523
524         if (!tcp)
525                 return 0;
526
527         cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
528         if (!cfg)
529                 return -ENOMEM;
530         cmd.data[0] = cfg;
531
532         cfg->max_syn_retries = 10;
533         cfg->max_data_retries = 10;
534         cfg->tcp_syn_ack_timeout = 1; /* seconds */
535         cfg->tcp_ack_timeout = 1; /* seconds */
536
537         /* SYN (TX) */
538         iwl_mvm_build_tcp_packet(
539                 vif, tcp, cfg->syn_tx.data, NULL,
540                 &cfg->syn_tx.info.tcp_pseudo_header_checksum,
541                 MVM_TCP_TX_SYN);
542         cfg->syn_tx.info.tcp_payload_length = 0;
543
544         /* SYN/ACK (RX) */
545         iwl_mvm_build_tcp_packet(
546                 vif, tcp, cfg->synack_rx.data, cfg->synack_rx.rx_mask,
547                 &cfg->synack_rx.info.tcp_pseudo_header_checksum,
548                 MVM_TCP_RX_SYNACK);
549         cfg->synack_rx.info.tcp_payload_length = 0;
550
551         /* KEEPALIVE/ACK (TX) */
552         iwl_mvm_build_tcp_packet(
553                 vif, tcp, cfg->keepalive_tx.data, NULL,
554                 &cfg->keepalive_tx.info.tcp_pseudo_header_checksum,
555                 MVM_TCP_TX_DATA);
556         cfg->keepalive_tx.info.tcp_payload_length =
557                 cpu_to_le16(tcp->payload_len);
558         cfg->sequence_number_offset = tcp->payload_seq.offset;
559         /* length must be 0..4, the field is little endian */
560         cfg->sequence_number_length = tcp->payload_seq.len;
561         cfg->initial_sequence_number = cpu_to_le32(tcp->payload_seq.start);
562         cfg->keepalive_interval = cpu_to_le16(tcp->data_interval);
563         if (tcp->payload_tok.len) {
564                 cfg->token_offset = tcp->payload_tok.offset;
565                 cfg->token_length = tcp->payload_tok.len;
566                 cfg->num_tokens =
567                         cpu_to_le16(tcp->tokens_size % tcp->payload_tok.len);
568                 memcpy(cfg->tokens, tcp->payload_tok.token_stream,
569                        tcp->tokens_size);
570         } else {
571                 /* set tokens to max value to almost never run out */
572                 cfg->num_tokens = cpu_to_le16(65535);
573         }
574
575         /* ACK (RX) */
576         iwl_mvm_build_tcp_packet(
577                 vif, tcp, cfg->keepalive_ack_rx.data,
578                 cfg->keepalive_ack_rx.rx_mask,
579                 &cfg->keepalive_ack_rx.info.tcp_pseudo_header_checksum,
580                 MVM_TCP_RX_ACK);
581         cfg->keepalive_ack_rx.info.tcp_payload_length = 0;
582
583         /* WAKEUP (RX) */
584         iwl_mvm_build_tcp_packet(
585                 vif, tcp, cfg->wake_rx.data, cfg->wake_rx.rx_mask,
586                 &cfg->wake_rx.info.tcp_pseudo_header_checksum,
587                 MVM_TCP_RX_WAKE);
588         cfg->wake_rx.info.tcp_payload_length =
589                 cpu_to_le16(tcp->wake_len);
590
591         /* FIN */
592         iwl_mvm_build_tcp_packet(
593                 vif, tcp, cfg->fin_tx.data, NULL,
594                 &cfg->fin_tx.info.tcp_pseudo_header_checksum,
595                 MVM_TCP_TX_FIN);
596         cfg->fin_tx.info.tcp_payload_length = 0;
597
598         ret = iwl_mvm_send_cmd(mvm, &cmd);
599         kfree(cfg);
600
601         return ret;
602 }
603
604 static int iwl_mvm_d3_reprogram(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
605                                 struct ieee80211_sta *ap_sta)
606 {
607         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
608         struct ieee80211_chanctx_conf *ctx;
609         u8 chains_static, chains_dynamic;
610         struct cfg80211_chan_def chandef;
611         int ret, i;
612         struct iwl_binding_cmd binding_cmd = {};
613         struct iwl_time_quota_cmd quota_cmd = {};
614         u32 status;
615
616         /* add back the PHY */
617         if (WARN_ON(!mvmvif->phy_ctxt))
618                 return -EINVAL;
619
620         rcu_read_lock();
621         ctx = rcu_dereference(vif->chanctx_conf);
622         if (WARN_ON(!ctx)) {
623                 rcu_read_unlock();
624                 return -EINVAL;
625         }
626         chandef = ctx->def;
627         chains_static = ctx->rx_chains_static;
628         chains_dynamic = ctx->rx_chains_dynamic;
629         rcu_read_unlock();
630
631         ret = iwl_mvm_phy_ctxt_add(mvm, mvmvif->phy_ctxt, &chandef,
632                                    chains_static, chains_dynamic);
633         if (ret)
634                 return ret;
635
636         /* add back the MAC */
637         mvmvif->uploaded = false;
638
639         if (WARN_ON(!vif->bss_conf.assoc))
640                 return -EINVAL;
641
642         ret = iwl_mvm_mac_ctxt_add(mvm, vif);
643         if (ret)
644                 return ret;
645
646         /* add back binding - XXX refactor? */
647         binding_cmd.id_and_color =
648                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
649                                                 mvmvif->phy_ctxt->color));
650         binding_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD);
651         binding_cmd.phy =
652                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
653                                                 mvmvif->phy_ctxt->color));
654         binding_cmd.macs[0] = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
655                                                               mvmvif->color));
656         for (i = 1; i < MAX_MACS_IN_BINDING; i++)
657                 binding_cmd.macs[i] = cpu_to_le32(FW_CTXT_INVALID);
658
659         status = 0;
660         ret = iwl_mvm_send_cmd_pdu_status(mvm, BINDING_CONTEXT_CMD,
661                                           sizeof(binding_cmd), &binding_cmd,
662                                           &status);
663         if (ret) {
664                 IWL_ERR(mvm, "Failed to add binding: %d\n", ret);
665                 return ret;
666         }
667
668         if (status) {
669                 IWL_ERR(mvm, "Binding command failed: %u\n", status);
670                 return -EIO;
671         }
672
673         ret = iwl_mvm_sta_send_to_fw(mvm, ap_sta, false);
674         if (ret)
675                 return ret;
676         rcu_assign_pointer(mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], ap_sta);
677
678         ret = iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
679         if (ret)
680                 return ret;
681
682         /* and some quota */
683         quota_cmd.quotas[0].id_and_color =
684                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
685                                                 mvmvif->phy_ctxt->color));
686         quota_cmd.quotas[0].quota = cpu_to_le32(IWL_MVM_MAX_QUOTA);
687         quota_cmd.quotas[0].max_duration = cpu_to_le32(IWL_MVM_MAX_QUOTA);
688
689         for (i = 1; i < MAX_BINDINGS; i++)
690                 quota_cmd.quotas[i].id_and_color = cpu_to_le32(FW_CTXT_INVALID);
691
692         ret = iwl_mvm_send_cmd_pdu(mvm, TIME_QUOTA_CMD, 0,
693                                    sizeof(quota_cmd), &quota_cmd);
694         if (ret)
695                 IWL_ERR(mvm, "Failed to send quota: %d\n", ret);
696
697         return 0;
698 }
699
700 static int iwl_mvm_get_last_nonqos_seq(struct iwl_mvm *mvm,
701                                        struct ieee80211_vif *vif)
702 {
703         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
704         struct iwl_nonqos_seq_query_cmd query_cmd = {
705                 .get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_GET),
706                 .mac_id_n_color =
707                         cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
708                                                         mvmvif->color)),
709         };
710         struct iwl_host_cmd cmd = {
711                 .id = NON_QOS_TX_COUNTER_CMD,
712                 .flags = CMD_WANT_SKB,
713         };
714         int err;
715         u32 size;
716
717         cmd.data[0] = &query_cmd;
718         cmd.len[0] = sizeof(query_cmd);
719
720         err = iwl_mvm_send_cmd(mvm, &cmd);
721         if (err)
722                 return err;
723
724         size = iwl_rx_packet_payload_len(cmd.resp_pkt);
725         if (size < sizeof(__le16)) {
726                 err = -EINVAL;
727         } else {
728                 err = le16_to_cpup((__le16 *)cmd.resp_pkt->data);
729                 /* firmware returns next, not last-used seqno */
730                 err = (u16) (err - 0x10);
731         }
732
733         iwl_free_resp(&cmd);
734         return err;
735 }
736
737 void iwl_mvm_set_last_nonqos_seq(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
738 {
739         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
740         struct iwl_nonqos_seq_query_cmd query_cmd = {
741                 .get_set_flag = cpu_to_le32(IWL_NONQOS_SEQ_SET),
742                 .mac_id_n_color =
743                         cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
744                                                         mvmvif->color)),
745                 .value = cpu_to_le16(mvmvif->seqno),
746         };
747
748         /* return if called during restart, not resume from D3 */
749         if (!mvmvif->seqno_valid)
750                 return;
751
752         mvmvif->seqno_valid = false;
753
754         if (iwl_mvm_send_cmd_pdu(mvm, NON_QOS_TX_COUNTER_CMD, 0,
755                                  sizeof(query_cmd), &query_cmd))
756                 IWL_ERR(mvm, "failed to set non-QoS seqno\n");
757 }
758
759 static int iwl_mvm_switch_to_d3(struct iwl_mvm *mvm)
760 {
761         iwl_mvm_cancel_scan(mvm);
762
763         iwl_trans_stop_device(mvm->trans);
764
765         /*
766          * Set the HW restart bit -- this is mostly true as we're
767          * going to load new firmware and reprogram that, though
768          * the reprogramming is going to be manual to avoid adding
769          * all the MACs that aren't support.
770          * We don't have to clear up everything though because the
771          * reprogramming is manual. When we resume, we'll actually
772          * go through a proper restart sequence again to switch
773          * back to the runtime firmware image.
774          */
775         set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
776
777         /* We reprogram keys and shouldn't allocate new key indices */
778         memset(mvm->fw_key_table, 0, sizeof(mvm->fw_key_table));
779
780         mvm->ptk_ivlen = 0;
781         mvm->ptk_icvlen = 0;
782         mvm->ptk_ivlen = 0;
783         mvm->ptk_icvlen = 0;
784
785         return iwl_mvm_load_d3_fw(mvm);
786 }
787
788 static int
789 iwl_mvm_get_wowlan_config(struct iwl_mvm *mvm,
790                           struct cfg80211_wowlan *wowlan,
791                           struct iwl_wowlan_config_cmd *wowlan_config_cmd,
792                           struct ieee80211_vif *vif, struct iwl_mvm_vif *mvmvif,
793                           struct ieee80211_sta *ap_sta)
794 {
795         int ret;
796         struct iwl_mvm_sta *mvm_ap_sta = iwl_mvm_sta_from_mac80211(ap_sta);
797
798         /* TODO: wowlan_config_cmd->wowlan_ba_teardown_tids */
799
800         wowlan_config_cmd->is_11n_connection =
801                                         ap_sta->ht_cap.ht_supported;
802
803         /* Query the last used seqno and set it */
804         ret = iwl_mvm_get_last_nonqos_seq(mvm, vif);
805         if (ret < 0)
806                 return ret;
807
808         wowlan_config_cmd->non_qos_seq = cpu_to_le16(ret);
809
810         iwl_mvm_set_wowlan_qos_seq(mvm_ap_sta, wowlan_config_cmd);
811
812         if (wowlan->disconnect)
813                 wowlan_config_cmd->wakeup_filter |=
814                         cpu_to_le32(IWL_WOWLAN_WAKEUP_BEACON_MISS |
815                                     IWL_WOWLAN_WAKEUP_LINK_CHANGE);
816         if (wowlan->magic_pkt)
817                 wowlan_config_cmd->wakeup_filter |=
818                         cpu_to_le32(IWL_WOWLAN_WAKEUP_MAGIC_PACKET);
819         if (wowlan->gtk_rekey_failure)
820                 wowlan_config_cmd->wakeup_filter |=
821                         cpu_to_le32(IWL_WOWLAN_WAKEUP_GTK_REKEY_FAIL);
822         if (wowlan->eap_identity_req)
823                 wowlan_config_cmd->wakeup_filter |=
824                         cpu_to_le32(IWL_WOWLAN_WAKEUP_EAP_IDENT_REQ);
825         if (wowlan->four_way_handshake)
826                 wowlan_config_cmd->wakeup_filter |=
827                         cpu_to_le32(IWL_WOWLAN_WAKEUP_4WAY_HANDSHAKE);
828         if (wowlan->n_patterns)
829                 wowlan_config_cmd->wakeup_filter |=
830                         cpu_to_le32(IWL_WOWLAN_WAKEUP_PATTERN_MATCH);
831
832         if (wowlan->rfkill_release)
833                 wowlan_config_cmd->wakeup_filter |=
834                         cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT);
835
836         if (wowlan->tcp) {
837                 /*
838                  * Set the "link change" (really "link lost") flag as well
839                  * since that implies losing the TCP connection.
840                  */
841                 wowlan_config_cmd->wakeup_filter |=
842                         cpu_to_le32(IWL_WOWLAN_WAKEUP_REMOTE_LINK_LOSS |
843                                     IWL_WOWLAN_WAKEUP_REMOTE_SIGNATURE_TABLE |
844                                     IWL_WOWLAN_WAKEUP_REMOTE_WAKEUP_PACKET |
845                                     IWL_WOWLAN_WAKEUP_LINK_CHANGE);
846         }
847
848         return 0;
849 }
850
851 static int
852 iwl_mvm_wowlan_config(struct iwl_mvm *mvm,
853                       struct cfg80211_wowlan *wowlan,
854                       struct iwl_wowlan_config_cmd *wowlan_config_cmd,
855                       struct ieee80211_vif *vif, struct iwl_mvm_vif *mvmvif,
856                       struct ieee80211_sta *ap_sta)
857 {
858         struct iwl_wowlan_kek_kck_material_cmd kek_kck_cmd = {};
859         struct iwl_wowlan_tkip_params_cmd tkip_cmd = {};
860         struct wowlan_key_data key_data = {
861                 .use_rsc_tsc = false,
862                 .tkip = &tkip_cmd,
863                 .use_tkip = false,
864         };
865         int ret;
866
867         ret = iwl_mvm_switch_to_d3(mvm);
868         if (ret)
869                 return ret;
870
871         ret = iwl_mvm_d3_reprogram(mvm, vif, ap_sta);
872         if (ret)
873                 return ret;
874
875         key_data.rsc_tsc = kzalloc(sizeof(*key_data.rsc_tsc), GFP_KERNEL);
876         if (!key_data.rsc_tsc)
877                 return -ENOMEM;
878
879         if (!iwlwifi_mod_params.sw_crypto) {
880                 /*
881                  * This needs to be unlocked due to lock ordering
882                  * constraints. Since we're in the suspend path
883                  * that isn't really a problem though.
884                  */
885                 mutex_unlock(&mvm->mutex);
886                 ieee80211_iter_keys(mvm->hw, vif,
887                                     iwl_mvm_wowlan_program_keys,
888                                     &key_data);
889                 mutex_lock(&mvm->mutex);
890                 if (key_data.error) {
891                         ret = -EIO;
892                         goto out;
893                 }
894
895                 if (key_data.use_rsc_tsc) {
896                         struct iwl_host_cmd rsc_tsc_cmd = {
897                                 .id = WOWLAN_TSC_RSC_PARAM,
898                                 .data[0] = key_data.rsc_tsc,
899                                 .dataflags[0] = IWL_HCMD_DFL_NOCOPY,
900                                 .len[0] = sizeof(*key_data.rsc_tsc),
901                         };
902
903                         ret = iwl_mvm_send_cmd(mvm, &rsc_tsc_cmd);
904                         if (ret)
905                                 goto out;
906                 }
907
908                 if (key_data.use_tkip) {
909                         ret = iwl_mvm_send_cmd_pdu(mvm,
910                                                    WOWLAN_TKIP_PARAM,
911                                                    0, sizeof(tkip_cmd),
912                                                    &tkip_cmd);
913                         if (ret)
914                                 goto out;
915                 }
916
917                 if (mvmvif->rekey_data.valid) {
918                         memset(&kek_kck_cmd, 0, sizeof(kek_kck_cmd));
919                         memcpy(kek_kck_cmd.kck, mvmvif->rekey_data.kck,
920                                NL80211_KCK_LEN);
921                         kek_kck_cmd.kck_len = cpu_to_le16(NL80211_KCK_LEN);
922                         memcpy(kek_kck_cmd.kek, mvmvif->rekey_data.kek,
923                                NL80211_KEK_LEN);
924                         kek_kck_cmd.kek_len = cpu_to_le16(NL80211_KEK_LEN);
925                         kek_kck_cmd.replay_ctr = mvmvif->rekey_data.replay_ctr;
926
927                         ret = iwl_mvm_send_cmd_pdu(mvm,
928                                                    WOWLAN_KEK_KCK_MATERIAL, 0,
929                                                    sizeof(kek_kck_cmd),
930                                                    &kek_kck_cmd);
931                         if (ret)
932                                 goto out;
933                 }
934         }
935
936         ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION, 0,
937                                    sizeof(*wowlan_config_cmd),
938                                    wowlan_config_cmd);
939         if (ret)
940                 goto out;
941
942         ret = iwl_mvm_send_patterns(mvm, wowlan);
943         if (ret)
944                 goto out;
945
946         ret = iwl_mvm_send_proto_offload(mvm, vif, false, 0);
947         if (ret)
948                 goto out;
949
950         ret = iwl_mvm_send_remote_wake_cfg(mvm, vif, wowlan->tcp);
951
952 out:
953         kfree(key_data.rsc_tsc);
954         return ret;
955 }
956
957 static int
958 iwl_mvm_netdetect_config(struct iwl_mvm *mvm,
959                          struct cfg80211_wowlan *wowlan,
960                          struct cfg80211_sched_scan_request *nd_config,
961                          struct ieee80211_vif *vif)
962 {
963         struct iwl_wowlan_config_cmd wowlan_config_cmd = {};
964         int ret;
965
966         ret = iwl_mvm_switch_to_d3(mvm);
967         if (ret)
968                 return ret;
969
970         /* rfkill release can be either for wowlan or netdetect */
971         if (wowlan->rfkill_release)
972                 wowlan_config_cmd.wakeup_filter |=
973                         cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT);
974
975         ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION, 0,
976                                    sizeof(wowlan_config_cmd),
977                                    &wowlan_config_cmd);
978         if (ret)
979                 return ret;
980
981         ret = iwl_mvm_scan_offload_start(mvm, vif, nd_config, &mvm->nd_ies);
982         if (ret)
983                 return ret;
984
985         if (WARN_ON(mvm->nd_match_sets || mvm->nd_channels))
986                 return -EBUSY;
987
988         /* save the sched scan matchsets... */
989         if (nd_config->n_match_sets) {
990                 mvm->nd_match_sets = kmemdup(nd_config->match_sets,
991                                              sizeof(*nd_config->match_sets) *
992                                              nd_config->n_match_sets,
993                                              GFP_KERNEL);
994                 if (mvm->nd_match_sets)
995                         mvm->n_nd_match_sets = nd_config->n_match_sets;
996         }
997
998         /* ...and the sched scan channels for later reporting */
999         mvm->nd_channels = kmemdup(nd_config->channels,
1000                                    sizeof(*nd_config->channels) *
1001                                    nd_config->n_channels,
1002                                    GFP_KERNEL);
1003         if (mvm->nd_channels)
1004                 mvm->n_nd_channels = nd_config->n_channels;
1005
1006         return 0;
1007 }
1008
1009 static void iwl_mvm_free_nd(struct iwl_mvm *mvm)
1010 {
1011         kfree(mvm->nd_match_sets);
1012         mvm->nd_match_sets = NULL;
1013         mvm->n_nd_match_sets = 0;
1014         kfree(mvm->nd_channels);
1015         mvm->nd_channels = NULL;
1016         mvm->n_nd_channels = 0;
1017 }
1018
1019 static int __iwl_mvm_suspend(struct ieee80211_hw *hw,
1020                              struct cfg80211_wowlan *wowlan,
1021                              bool test)
1022 {
1023         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1024         struct ieee80211_vif *vif = NULL;
1025         struct iwl_mvm_vif *mvmvif = NULL;
1026         struct ieee80211_sta *ap_sta = NULL;
1027         struct iwl_d3_manager_config d3_cfg_cmd_data = {
1028                 /*
1029                  * Program the minimum sleep time to 10 seconds, as many
1030                  * platforms have issues processing a wakeup signal while
1031                  * still being in the process of suspending.
1032                  */
1033                 .min_sleep_time = cpu_to_le32(10 * 1000 * 1000),
1034         };
1035         struct iwl_host_cmd d3_cfg_cmd = {
1036                 .id = D3_CONFIG_CMD,
1037                 .flags = CMD_WANT_SKB,
1038                 .data[0] = &d3_cfg_cmd_data,
1039                 .len[0] = sizeof(d3_cfg_cmd_data),
1040         };
1041         int ret;
1042         int len __maybe_unused;
1043
1044         if (!wowlan) {
1045                 /*
1046                  * mac80211 shouldn't get here, but for D3 test
1047                  * it doesn't warrant a warning
1048                  */
1049                 WARN_ON(!test);
1050                 return -EINVAL;
1051         }
1052
1053         mutex_lock(&mvm->mutex);
1054
1055         vif = iwl_mvm_get_bss_vif(mvm);
1056         if (IS_ERR_OR_NULL(vif)) {
1057                 ret = 1;
1058                 goto out_noreset;
1059         }
1060
1061         mvmvif = iwl_mvm_vif_from_mac80211(vif);
1062
1063         if (mvmvif->ap_sta_id == IWL_MVM_STATION_COUNT) {
1064                 /* if we're not associated, this must be netdetect */
1065                 if (!wowlan->nd_config && !mvm->nd_config) {
1066                         ret = 1;
1067                         goto out_noreset;
1068                 }
1069
1070                 ret = iwl_mvm_netdetect_config(
1071                         mvm, wowlan, wowlan->nd_config ?: mvm->nd_config, vif);
1072                 if (ret)
1073                         goto out;
1074
1075                 mvm->net_detect = true;
1076         } else {
1077                 struct iwl_wowlan_config_cmd wowlan_config_cmd = {};
1078
1079                 ap_sta = rcu_dereference_protected(
1080                         mvm->fw_id_to_mac_id[mvmvif->ap_sta_id],
1081                         lockdep_is_held(&mvm->mutex));
1082                 if (IS_ERR_OR_NULL(ap_sta)) {
1083                         ret = -EINVAL;
1084                         goto out_noreset;
1085                 }
1086
1087                 ret = iwl_mvm_get_wowlan_config(mvm, wowlan, &wowlan_config_cmd,
1088                                                 vif, mvmvif, ap_sta);
1089                 if (ret)
1090                         goto out_noreset;
1091                 ret = iwl_mvm_wowlan_config(mvm, wowlan, &wowlan_config_cmd,
1092                                             vif, mvmvif, ap_sta);
1093                 if (ret)
1094                         goto out;
1095
1096                 mvm->net_detect = false;
1097         }
1098
1099         ret = iwl_mvm_power_update_device(mvm);
1100         if (ret)
1101                 goto out;
1102
1103         ret = iwl_mvm_power_update_mac(mvm);
1104         if (ret)
1105                 goto out;
1106
1107 #ifdef CONFIG_IWLWIFI_DEBUGFS
1108         if (mvm->d3_wake_sysassert)
1109                 d3_cfg_cmd_data.wakeup_flags |=
1110                         cpu_to_le32(IWL_WAKEUP_D3_CONFIG_FW_ERROR);
1111 #endif
1112
1113         /* must be last -- this switches firmware state */
1114         ret = iwl_mvm_send_cmd(mvm, &d3_cfg_cmd);
1115         if (ret)
1116                 goto out;
1117 #ifdef CONFIG_IWLWIFI_DEBUGFS
1118         len = iwl_rx_packet_payload_len(d3_cfg_cmd.resp_pkt);
1119         if (len >= sizeof(u32)) {
1120                 mvm->d3_test_pme_ptr =
1121                         le32_to_cpup((__le32 *)d3_cfg_cmd.resp_pkt->data);
1122         }
1123 #endif
1124         iwl_free_resp(&d3_cfg_cmd);
1125
1126         clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1127
1128         iwl_trans_d3_suspend(mvm->trans, test);
1129  out:
1130         if (ret < 0) {
1131                 ieee80211_restart_hw(mvm->hw);
1132                 iwl_mvm_free_nd(mvm);
1133         }
1134  out_noreset:
1135         mutex_unlock(&mvm->mutex);
1136
1137         return ret;
1138 }
1139
1140 static int iwl_mvm_enter_d0i3_sync(struct iwl_mvm *mvm)
1141 {
1142         struct iwl_notification_wait wait_d3;
1143         static const u8 d3_notif[] = { D3_CONFIG_CMD };
1144         int ret;
1145
1146         iwl_init_notification_wait(&mvm->notif_wait, &wait_d3,
1147                                    d3_notif, ARRAY_SIZE(d3_notif),
1148                                    NULL, NULL);
1149
1150         ret = iwl_mvm_enter_d0i3(mvm->hw->priv);
1151         if (ret)
1152                 goto remove_notif;
1153
1154         ret = iwl_wait_notification(&mvm->notif_wait, &wait_d3, HZ);
1155         WARN_ON_ONCE(ret);
1156         return ret;
1157
1158 remove_notif:
1159         iwl_remove_notification(&mvm->notif_wait, &wait_d3);
1160         return ret;
1161 }
1162
1163 int iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan)
1164 {
1165         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1166
1167         iwl_trans_suspend(mvm->trans);
1168         if (wowlan->any) {
1169                 /* 'any' trigger means d0i3 usage */
1170                 if (mvm->trans->d0i3_mode == IWL_D0I3_MODE_ON_SUSPEND) {
1171                         int ret = iwl_mvm_enter_d0i3_sync(mvm);
1172
1173                         if (ret)
1174                                 return ret;
1175                 }
1176
1177                 mutex_lock(&mvm->d0i3_suspend_mutex);
1178                 __set_bit(D0I3_DEFER_WAKEUP, &mvm->d0i3_suspend_flags);
1179                 mutex_unlock(&mvm->d0i3_suspend_mutex);
1180                 return 0;
1181         }
1182
1183         return __iwl_mvm_suspend(hw, wowlan, false);
1184 }
1185
1186 /* converted data from the different status responses */
1187 struct iwl_wowlan_status_data {
1188         u16 pattern_number;
1189         u16 qos_seq_ctr[8];
1190         u32 wakeup_reasons;
1191         u32 wake_packet_length;
1192         u32 wake_packet_bufsize;
1193         const u8 *wake_packet;
1194 };
1195
1196 static void iwl_mvm_report_wakeup_reasons(struct iwl_mvm *mvm,
1197                                           struct ieee80211_vif *vif,
1198                                           struct iwl_wowlan_status_data *status)
1199 {
1200         struct sk_buff *pkt = NULL;
1201         struct cfg80211_wowlan_wakeup wakeup = {
1202                 .pattern_idx = -1,
1203         };
1204         struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup;
1205         u32 reasons = status->wakeup_reasons;
1206
1207         if (reasons == IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS) {
1208                 wakeup_report = NULL;
1209                 goto report;
1210         }
1211
1212         if (reasons & IWL_WOWLAN_WAKEUP_BY_MAGIC_PACKET)
1213                 wakeup.magic_pkt = true;
1214
1215         if (reasons & IWL_WOWLAN_WAKEUP_BY_PATTERN)
1216                 wakeup.pattern_idx =
1217                         status->pattern_number;
1218
1219         if (reasons & (IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON |
1220                        IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH))
1221                 wakeup.disconnect = true;
1222
1223         if (reasons & IWL_WOWLAN_WAKEUP_BY_GTK_REKEY_FAILURE)
1224                 wakeup.gtk_rekey_failure = true;
1225
1226         if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED)
1227                 wakeup.rfkill_release = true;
1228
1229         if (reasons & IWL_WOWLAN_WAKEUP_BY_EAPOL_REQUEST)
1230                 wakeup.eap_identity_req = true;
1231
1232         if (reasons & IWL_WOWLAN_WAKEUP_BY_FOUR_WAY_HANDSHAKE)
1233                 wakeup.four_way_handshake = true;
1234
1235         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_LINK_LOSS)
1236                 wakeup.tcp_connlost = true;
1237
1238         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_SIGNATURE_TABLE)
1239                 wakeup.tcp_nomoretokens = true;
1240
1241         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_WAKEUP_PACKET)
1242                 wakeup.tcp_match = true;
1243
1244         if (status->wake_packet_bufsize) {
1245                 int pktsize = status->wake_packet_bufsize;
1246                 int pktlen = status->wake_packet_length;
1247                 const u8 *pktdata = status->wake_packet;
1248                 struct ieee80211_hdr *hdr = (void *)pktdata;
1249                 int truncated = pktlen - pktsize;
1250
1251                 /* this would be a firmware bug */
1252                 if (WARN_ON_ONCE(truncated < 0))
1253                         truncated = 0;
1254
1255                 if (ieee80211_is_data(hdr->frame_control)) {
1256                         int hdrlen = ieee80211_hdrlen(hdr->frame_control);
1257                         int ivlen = 0, icvlen = 4; /* also FCS */
1258
1259                         pkt = alloc_skb(pktsize, GFP_KERNEL);
1260                         if (!pkt)
1261                                 goto report;
1262
1263                         memcpy(skb_put(pkt, hdrlen), pktdata, hdrlen);
1264                         pktdata += hdrlen;
1265                         pktsize -= hdrlen;
1266
1267                         if (ieee80211_has_protected(hdr->frame_control)) {
1268                                 /*
1269                                  * This is unlocked and using gtk_i(c)vlen,
1270                                  * but since everything is under RTNL still
1271                                  * that's not really a problem - changing
1272                                  * it would be difficult.
1273                                  */
1274                                 if (is_multicast_ether_addr(hdr->addr1)) {
1275                                         ivlen = mvm->gtk_ivlen;
1276                                         icvlen += mvm->gtk_icvlen;
1277                                 } else {
1278                                         ivlen = mvm->ptk_ivlen;
1279                                         icvlen += mvm->ptk_icvlen;
1280                                 }
1281                         }
1282
1283                         /* if truncated, FCS/ICV is (partially) gone */
1284                         if (truncated >= icvlen) {
1285                                 icvlen = 0;
1286                                 truncated -= icvlen;
1287                         } else {
1288                                 icvlen -= truncated;
1289                                 truncated = 0;
1290                         }
1291
1292                         pktsize -= ivlen + icvlen;
1293                         pktdata += ivlen;
1294
1295                         memcpy(skb_put(pkt, pktsize), pktdata, pktsize);
1296
1297                         if (ieee80211_data_to_8023(pkt, vif->addr, vif->type))
1298                                 goto report;
1299                         wakeup.packet = pkt->data;
1300                         wakeup.packet_present_len = pkt->len;
1301                         wakeup.packet_len = pkt->len - truncated;
1302                         wakeup.packet_80211 = false;
1303                 } else {
1304                         int fcslen = 4;
1305
1306                         if (truncated >= 4) {
1307                                 truncated -= 4;
1308                                 fcslen = 0;
1309                         } else {
1310                                 fcslen -= truncated;
1311                                 truncated = 0;
1312                         }
1313                         pktsize -= fcslen;
1314                         wakeup.packet = status->wake_packet;
1315                         wakeup.packet_present_len = pktsize;
1316                         wakeup.packet_len = pktlen - truncated;
1317                         wakeup.packet_80211 = true;
1318                 }
1319         }
1320
1321  report:
1322         ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL);
1323         kfree_skb(pkt);
1324 }
1325
1326 static void iwl_mvm_aes_sc_to_seq(struct aes_sc *sc,
1327                                   struct ieee80211_key_seq *seq)
1328 {
1329         u64 pn;
1330
1331         pn = le64_to_cpu(sc->pn);
1332         seq->ccmp.pn[0] = pn >> 40;
1333         seq->ccmp.pn[1] = pn >> 32;
1334         seq->ccmp.pn[2] = pn >> 24;
1335         seq->ccmp.pn[3] = pn >> 16;
1336         seq->ccmp.pn[4] = pn >> 8;
1337         seq->ccmp.pn[5] = pn;
1338 }
1339
1340 static void iwl_mvm_tkip_sc_to_seq(struct tkip_sc *sc,
1341                                    struct ieee80211_key_seq *seq)
1342 {
1343         seq->tkip.iv32 = le32_to_cpu(sc->iv32);
1344         seq->tkip.iv16 = le16_to_cpu(sc->iv16);
1345 }
1346
1347 static void iwl_mvm_set_aes_rx_seq(struct aes_sc *scs,
1348                                    struct ieee80211_key_conf *key)
1349 {
1350         int tid;
1351
1352         BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS);
1353
1354         for (tid = 0; tid < IWL_NUM_RSC; tid++) {
1355                 struct ieee80211_key_seq seq = {};
1356
1357                 iwl_mvm_aes_sc_to_seq(&scs[tid], &seq);
1358                 ieee80211_set_key_rx_seq(key, tid, &seq);
1359         }
1360 }
1361
1362 static void iwl_mvm_set_tkip_rx_seq(struct tkip_sc *scs,
1363                                     struct ieee80211_key_conf *key)
1364 {
1365         int tid;
1366
1367         BUILD_BUG_ON(IWL_NUM_RSC != IEEE80211_NUM_TIDS);
1368
1369         for (tid = 0; tid < IWL_NUM_RSC; tid++) {
1370                 struct ieee80211_key_seq seq = {};
1371
1372                 iwl_mvm_tkip_sc_to_seq(&scs[tid], &seq);
1373                 ieee80211_set_key_rx_seq(key, tid, &seq);
1374         }
1375 }
1376
1377 static void iwl_mvm_set_key_rx_seq(struct ieee80211_key_conf *key,
1378                                    struct iwl_wowlan_status *status)
1379 {
1380         union iwl_all_tsc_rsc *rsc = &status->gtk.rsc.all_tsc_rsc;
1381
1382         switch (key->cipher) {
1383         case WLAN_CIPHER_SUITE_CCMP:
1384                 iwl_mvm_set_aes_rx_seq(rsc->aes.multicast_rsc, key);
1385                 break;
1386         case WLAN_CIPHER_SUITE_TKIP:
1387                 iwl_mvm_set_tkip_rx_seq(rsc->tkip.multicast_rsc, key);
1388                 break;
1389         default:
1390                 WARN_ON(1);
1391         }
1392 }
1393
1394 struct iwl_mvm_d3_gtk_iter_data {
1395         struct iwl_wowlan_status *status;
1396         void *last_gtk;
1397         u32 cipher;
1398         bool find_phase, unhandled_cipher;
1399         int num_keys;
1400 };
1401
1402 static void iwl_mvm_d3_update_gtks(struct ieee80211_hw *hw,
1403                                    struct ieee80211_vif *vif,
1404                                    struct ieee80211_sta *sta,
1405                                    struct ieee80211_key_conf *key,
1406                                    void *_data)
1407 {
1408         struct iwl_mvm_d3_gtk_iter_data *data = _data;
1409
1410         if (data->unhandled_cipher)
1411                 return;
1412
1413         switch (key->cipher) {
1414         case WLAN_CIPHER_SUITE_WEP40:
1415         case WLAN_CIPHER_SUITE_WEP104:
1416                 /* ignore WEP completely, nothing to do */
1417                 return;
1418         case WLAN_CIPHER_SUITE_CCMP:
1419         case WLAN_CIPHER_SUITE_TKIP:
1420                 /* we support these */
1421                 break;
1422         default:
1423                 /* everything else (even CMAC for MFP) - disconnect from AP */
1424                 data->unhandled_cipher = true;
1425                 return;
1426         }
1427
1428         data->num_keys++;
1429
1430         /*
1431          * pairwise key - update sequence counters only;
1432          * note that this assumes no TDLS sessions are active
1433          */
1434         if (sta) {
1435                 struct ieee80211_key_seq seq = {};
1436                 union iwl_all_tsc_rsc *sc = &data->status->gtk.rsc.all_tsc_rsc;
1437
1438                 if (data->find_phase)
1439                         return;
1440
1441                 switch (key->cipher) {
1442                 case WLAN_CIPHER_SUITE_CCMP:
1443                         iwl_mvm_aes_sc_to_seq(&sc->aes.tsc, &seq);
1444                         iwl_mvm_set_aes_rx_seq(sc->aes.unicast_rsc, key);
1445                         break;
1446                 case WLAN_CIPHER_SUITE_TKIP:
1447                         iwl_mvm_tkip_sc_to_seq(&sc->tkip.tsc, &seq);
1448                         iwl_mvm_set_tkip_rx_seq(sc->tkip.unicast_rsc, key);
1449                         break;
1450                 }
1451                 ieee80211_set_key_tx_seq(key, &seq);
1452
1453                 /* that's it for this key */
1454                 return;
1455         }
1456
1457         if (data->find_phase) {
1458                 data->last_gtk = key;
1459                 data->cipher = key->cipher;
1460                 return;
1461         }
1462
1463         if (data->status->num_of_gtk_rekeys)
1464                 ieee80211_remove_key(key);
1465         else if (data->last_gtk == key)
1466                 iwl_mvm_set_key_rx_seq(key, data->status);
1467 }
1468
1469 static bool iwl_mvm_setup_connection_keep(struct iwl_mvm *mvm,
1470                                           struct ieee80211_vif *vif,
1471                                           struct iwl_wowlan_status *status)
1472 {
1473         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1474         struct iwl_mvm_d3_gtk_iter_data gtkdata = {
1475                 .status = status,
1476         };
1477         u32 disconnection_reasons =
1478                 IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON |
1479                 IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH;
1480
1481         if (!status || !vif->bss_conf.bssid)
1482                 return false;
1483
1484         if (le32_to_cpu(status->wakeup_reasons) & disconnection_reasons)
1485                 return false;
1486
1487         /* find last GTK that we used initially, if any */
1488         gtkdata.find_phase = true;
1489         ieee80211_iter_keys(mvm->hw, vif,
1490                             iwl_mvm_d3_update_gtks, &gtkdata);
1491         /* not trying to keep connections with MFP/unhandled ciphers */
1492         if (gtkdata.unhandled_cipher)
1493                 return false;
1494         if (!gtkdata.num_keys)
1495                 goto out;
1496         if (!gtkdata.last_gtk)
1497                 return false;
1498
1499         /*
1500          * invalidate all other GTKs that might still exist and update
1501          * the one that we used
1502          */
1503         gtkdata.find_phase = false;
1504         ieee80211_iter_keys(mvm->hw, vif,
1505                             iwl_mvm_d3_update_gtks, &gtkdata);
1506
1507         if (status->num_of_gtk_rekeys) {
1508                 struct ieee80211_key_conf *key;
1509                 struct {
1510                         struct ieee80211_key_conf conf;
1511                         u8 key[32];
1512                 } conf = {
1513                         .conf.cipher = gtkdata.cipher,
1514                         .conf.keyidx = status->gtk.key_index,
1515                 };
1516
1517                 switch (gtkdata.cipher) {
1518                 case WLAN_CIPHER_SUITE_CCMP:
1519                         conf.conf.keylen = WLAN_KEY_LEN_CCMP;
1520                         memcpy(conf.conf.key, status->gtk.decrypt_key,
1521                                WLAN_KEY_LEN_CCMP);
1522                         break;
1523                 case WLAN_CIPHER_SUITE_TKIP:
1524                         conf.conf.keylen = WLAN_KEY_LEN_TKIP;
1525                         memcpy(conf.conf.key, status->gtk.decrypt_key, 16);
1526                         /* leave TX MIC key zeroed, we don't use it anyway */
1527                         memcpy(conf.conf.key +
1528                                NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY,
1529                                status->gtk.tkip_mic_key, 8);
1530                         break;
1531                 }
1532
1533                 key = ieee80211_gtk_rekey_add(vif, &conf.conf);
1534                 if (IS_ERR(key))
1535                         return false;
1536                 iwl_mvm_set_key_rx_seq(key, status);
1537         }
1538
1539         if (status->num_of_gtk_rekeys) {
1540                 __be64 replay_ctr =
1541                         cpu_to_be64(le64_to_cpu(status->replay_ctr));
1542                 ieee80211_gtk_rekey_notify(vif, vif->bss_conf.bssid,
1543                                            (void *)&replay_ctr, GFP_KERNEL);
1544         }
1545
1546 out:
1547         mvmvif->seqno_valid = true;
1548         /* +0x10 because the set API expects next-to-use, not last-used */
1549         mvmvif->seqno = le16_to_cpu(status->non_qos_seq_ctr) + 0x10;
1550
1551         return true;
1552 }
1553
1554 static struct iwl_wowlan_status *
1555 iwl_mvm_get_wakeup_status(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1556 {
1557         u32 base = mvm->error_event_table;
1558         struct error_table_start {
1559                 /* cf. struct iwl_error_event_table */
1560                 u32 valid;
1561                 u32 error_id;
1562         } err_info;
1563         struct iwl_host_cmd cmd = {
1564                 .id = WOWLAN_GET_STATUSES,
1565                 .flags = CMD_WANT_SKB,
1566         };
1567         struct iwl_wowlan_status *status, *fw_status;
1568         int ret, len, status_size;
1569
1570         iwl_trans_read_mem_bytes(mvm->trans, base,
1571                                  &err_info, sizeof(err_info));
1572
1573         if (err_info.valid) {
1574                 IWL_INFO(mvm, "error table is valid (%d) with error (%d)\n",
1575                          err_info.valid, err_info.error_id);
1576                 if (err_info.error_id == RF_KILL_INDICATOR_FOR_WOWLAN) {
1577                         struct cfg80211_wowlan_wakeup wakeup = {
1578                                 .rfkill_release = true,
1579                         };
1580                         ieee80211_report_wowlan_wakeup(vif, &wakeup,
1581                                                        GFP_KERNEL);
1582                 }
1583                 return ERR_PTR(-EIO);
1584         }
1585
1586         /* only for tracing for now */
1587         ret = iwl_mvm_send_cmd_pdu(mvm, OFFLOADS_QUERY_CMD, 0, 0, NULL);
1588         if (ret)
1589                 IWL_ERR(mvm, "failed to query offload statistics (%d)\n", ret);
1590
1591         ret = iwl_mvm_send_cmd(mvm, &cmd);
1592         if (ret) {
1593                 IWL_ERR(mvm, "failed to query status (%d)\n", ret);
1594                 return ERR_PTR(ret);
1595         }
1596
1597         /* RF-kill already asserted again... */
1598         if (!cmd.resp_pkt) {
1599                 ret = -ERFKILL;
1600                 goto out_free_resp;
1601         }
1602
1603         status_size = sizeof(*fw_status);
1604
1605         len = iwl_rx_packet_payload_len(cmd.resp_pkt);
1606         if (len < status_size) {
1607                 IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1608                 ret = -EIO;
1609                 goto out_free_resp;
1610         }
1611
1612         status = (void *)cmd.resp_pkt->data;
1613         if (len != (status_size +
1614                     ALIGN(le32_to_cpu(status->wake_packet_bufsize), 4))) {
1615                 IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1616                 ret = -EIO;
1617                 goto out_free_resp;
1618         }
1619
1620         fw_status = kmemdup(status, len, GFP_KERNEL);
1621
1622 out_free_resp:
1623         iwl_free_resp(&cmd);
1624         return ret ? ERR_PTR(ret) : fw_status;
1625 }
1626
1627 /* releases the MVM mutex */
1628 static bool iwl_mvm_query_wakeup_reasons(struct iwl_mvm *mvm,
1629                                          struct ieee80211_vif *vif)
1630 {
1631         struct iwl_wowlan_status_data status;
1632         struct iwl_wowlan_status *fw_status;
1633         int i;
1634         bool keep;
1635         struct ieee80211_sta *ap_sta;
1636         struct iwl_mvm_sta *mvm_ap_sta;
1637
1638         fw_status = iwl_mvm_get_wakeup_status(mvm, vif);
1639         if (IS_ERR_OR_NULL(fw_status))
1640                 goto out_unlock;
1641
1642         status.pattern_number = le16_to_cpu(fw_status->pattern_number);
1643         for (i = 0; i < 8; i++)
1644                 status.qos_seq_ctr[i] =
1645                         le16_to_cpu(fw_status->qos_seq_ctr[i]);
1646         status.wakeup_reasons = le32_to_cpu(fw_status->wakeup_reasons);
1647         status.wake_packet_length =
1648                 le32_to_cpu(fw_status->wake_packet_length);
1649         status.wake_packet_bufsize =
1650                 le32_to_cpu(fw_status->wake_packet_bufsize);
1651         status.wake_packet = fw_status->wake_packet;
1652
1653         /* still at hard-coded place 0 for D3 image */
1654         ap_sta = rcu_dereference_protected(
1655                         mvm->fw_id_to_mac_id[0],
1656                         lockdep_is_held(&mvm->mutex));
1657         if (IS_ERR_OR_NULL(ap_sta))
1658                 goto out_free;
1659
1660         mvm_ap_sta = iwl_mvm_sta_from_mac80211(ap_sta);
1661         for (i = 0; i < IWL_MAX_TID_COUNT; i++) {
1662                 u16 seq = status.qos_seq_ctr[i];
1663                 /* firmware stores last-used value, we store next value */
1664                 seq += 0x10;
1665                 mvm_ap_sta->tid_data[i].seq_number = seq;
1666         }
1667
1668         /* now we have all the data we need, unlock to avoid mac80211 issues */
1669         mutex_unlock(&mvm->mutex);
1670
1671         iwl_mvm_report_wakeup_reasons(mvm, vif, &status);
1672
1673         keep = iwl_mvm_setup_connection_keep(mvm, vif, fw_status);
1674
1675         kfree(fw_status);
1676         return keep;
1677
1678 out_free:
1679         kfree(fw_status);
1680 out_unlock:
1681         mutex_unlock(&mvm->mutex);
1682         return false;
1683 }
1684
1685 struct iwl_mvm_nd_query_results {
1686         u32 matched_profiles;
1687         struct iwl_scan_offload_profile_match matches[IWL_SCAN_MAX_PROFILES];
1688 };
1689
1690 static int
1691 iwl_mvm_netdetect_query_results(struct iwl_mvm *mvm,
1692                                 struct iwl_mvm_nd_query_results *results)
1693 {
1694         struct iwl_scan_offload_profiles_query *query;
1695         struct iwl_host_cmd cmd = {
1696                 .id = SCAN_OFFLOAD_PROFILES_QUERY_CMD,
1697                 .flags = CMD_WANT_SKB,
1698         };
1699         int ret, len;
1700
1701         ret = iwl_mvm_send_cmd(mvm, &cmd);
1702         if (ret) {
1703                 IWL_ERR(mvm, "failed to query matched profiles (%d)\n", ret);
1704                 return ret;
1705         }
1706
1707         /* RF-kill already asserted again... */
1708         if (!cmd.resp_pkt) {
1709                 ret = -ERFKILL;
1710                 goto out_free_resp;
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 out_free_resp:
1726         iwl_free_resp(&cmd);
1727         return ret;
1728 }
1729
1730 static void iwl_mvm_query_netdetect_reasons(struct iwl_mvm *mvm,
1731                                             struct ieee80211_vif *vif)
1732 {
1733         struct cfg80211_wowlan_nd_info *net_detect = NULL;
1734         struct cfg80211_wowlan_wakeup wakeup = {
1735                 .pattern_idx = -1,
1736         };
1737         struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup;
1738         struct iwl_mvm_nd_query_results query;
1739         struct iwl_wowlan_status *fw_status;
1740         unsigned long matched_profiles;
1741         u32 reasons = 0;
1742         int i, j, n_matches, ret;
1743
1744         fw_status = iwl_mvm_get_wakeup_status(mvm, vif);
1745         if (!IS_ERR_OR_NULL(fw_status))
1746                 reasons = le32_to_cpu(fw_status->wakeup_reasons);
1747
1748         if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED)
1749                 wakeup.rfkill_release = true;
1750
1751         if (reasons != IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS)
1752                 goto out;
1753
1754         ret = iwl_mvm_netdetect_query_results(mvm, &query);
1755         if (ret || !query.matched_profiles) {
1756                 wakeup_report = NULL;
1757                 goto out;
1758         }
1759
1760         matched_profiles = query.matched_profiles;
1761         if (mvm->n_nd_match_sets) {
1762                 n_matches = hweight_long(matched_profiles);
1763         } else {
1764                 IWL_ERR(mvm, "no net detect match information available\n");
1765                 n_matches = 0;
1766         }
1767
1768         net_detect = kzalloc(sizeof(*net_detect) +
1769                              (n_matches * sizeof(net_detect->matches[0])),
1770                              GFP_KERNEL);
1771         if (!net_detect || !n_matches)
1772                 goto out_report_nd;
1773
1774         for_each_set_bit(i, &matched_profiles, mvm->n_nd_match_sets) {
1775                 struct iwl_scan_offload_profile_match *fw_match;
1776                 struct cfg80211_wowlan_nd_match *match;
1777                 int n_channels = 0;
1778
1779                 fw_match = &query.matches[i];
1780
1781                 for (j = 0; j < SCAN_OFFLOAD_MATCHING_CHANNELS_LEN; j++)
1782                         n_channels += hweight8(fw_match->matching_channels[j]);
1783
1784                 match = kzalloc(sizeof(*match) +
1785                                 (n_channels * sizeof(*match->channels)),
1786                                 GFP_KERNEL);
1787                 if (!match)
1788                         goto out_report_nd;
1789
1790                 net_detect->matches[net_detect->n_matches++] = match;
1791
1792                 match->ssid.ssid_len = mvm->nd_match_sets[i].ssid.ssid_len;
1793                 memcpy(match->ssid.ssid, mvm->nd_match_sets[i].ssid.ssid,
1794                        match->ssid.ssid_len);
1795
1796                 if (mvm->n_nd_channels < n_channels)
1797                         continue;
1798
1799                 for (j = 0; j < SCAN_OFFLOAD_MATCHING_CHANNELS_LEN * 8; j++)
1800                         if (fw_match->matching_channels[j / 8] & (BIT(j % 8)))
1801                                 match->channels[match->n_channels++] =
1802                                         mvm->nd_channels[j]->center_freq;
1803         }
1804
1805 out_report_nd:
1806         wakeup.net_detect = net_detect;
1807 out:
1808         iwl_mvm_free_nd(mvm);
1809
1810         mutex_unlock(&mvm->mutex);
1811         ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL);
1812
1813         if (net_detect) {
1814                 for (i = 0; i < net_detect->n_matches; i++)
1815                         kfree(net_detect->matches[i]);
1816                 kfree(net_detect);
1817         }
1818 }
1819
1820 static void iwl_mvm_read_d3_sram(struct iwl_mvm *mvm)
1821 {
1822 #ifdef CONFIG_IWLWIFI_DEBUGFS
1823         const struct fw_img *img = &mvm->fw->img[IWL_UCODE_WOWLAN];
1824         u32 len = img->sec[IWL_UCODE_SECTION_DATA].len;
1825         u32 offs = img->sec[IWL_UCODE_SECTION_DATA].offset;
1826
1827         if (!mvm->store_d3_resume_sram)
1828                 return;
1829
1830         if (!mvm->d3_resume_sram) {
1831                 mvm->d3_resume_sram = kzalloc(len, GFP_KERNEL);
1832                 if (!mvm->d3_resume_sram)
1833                         return;
1834         }
1835
1836         iwl_trans_read_mem_bytes(mvm->trans, offs, mvm->d3_resume_sram, len);
1837 #endif
1838 }
1839
1840 static void iwl_mvm_d3_disconnect_iter(void *data, u8 *mac,
1841                                        struct ieee80211_vif *vif)
1842 {
1843         /* skip the one we keep connection on */
1844         if (data == vif)
1845                 return;
1846
1847         if (vif->type == NL80211_IFTYPE_STATION)
1848                 ieee80211_resume_disconnect(vif);
1849 }
1850
1851 static int __iwl_mvm_resume(struct iwl_mvm *mvm, bool test)
1852 {
1853         struct ieee80211_vif *vif = NULL;
1854         int ret;
1855         enum iwl_d3_status d3_status;
1856         bool keep = false;
1857
1858         mutex_lock(&mvm->mutex);
1859
1860         /* get the BSS vif pointer again */
1861         vif = iwl_mvm_get_bss_vif(mvm);
1862         if (IS_ERR_OR_NULL(vif))
1863                 goto out_unlock;
1864
1865         ret = iwl_trans_d3_resume(mvm->trans, &d3_status, test);
1866         if (ret)
1867                 goto out_unlock;
1868
1869         if (d3_status != IWL_D3_STATUS_ALIVE) {
1870                 IWL_INFO(mvm, "Device was reset during suspend\n");
1871                 goto out_unlock;
1872         }
1873
1874         /* query SRAM first in case we want event logging */
1875         iwl_mvm_read_d3_sram(mvm);
1876
1877         if (mvm->net_detect) {
1878                 iwl_mvm_query_netdetect_reasons(mvm, vif);
1879         } else {
1880                 keep = iwl_mvm_query_wakeup_reasons(mvm, vif);
1881 #ifdef CONFIG_IWLWIFI_DEBUGFS
1882                 if (keep)
1883                         mvm->keep_vif = vif;
1884 #endif
1885         }
1886         /* has unlocked the mutex, so skip that */
1887         goto out;
1888
1889  out_unlock:
1890         mutex_unlock(&mvm->mutex);
1891
1892  out:
1893         if (!test)
1894                 ieee80211_iterate_active_interfaces_rtnl(mvm->hw,
1895                         IEEE80211_IFACE_ITER_NORMAL,
1896                         iwl_mvm_d3_disconnect_iter, keep ? vif : NULL);
1897
1898         /* return 1 to reconfigure the device */
1899         set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1900         set_bit(IWL_MVM_STATUS_D3_RECONFIG, &mvm->status);
1901         return 1;
1902 }
1903
1904 int iwl_mvm_resume(struct ieee80211_hw *hw)
1905 {
1906         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1907
1908         iwl_trans_resume(mvm->trans);
1909
1910         if (mvm->hw->wiphy->wowlan_config->any) {
1911                 /* 'any' trigger means d0i3 usage */
1912                 if (mvm->trans->d0i3_mode == IWL_D0I3_MODE_ON_SUSPEND) {
1913                         int ret = iwl_mvm_exit_d0i3(hw->priv);
1914
1915                         if (ret)
1916                                 return ret;
1917                         /*
1918                          * d0i3 exit will be deferred until reconfig_complete.
1919                          * make sure there we are out of d0i3.
1920                          */
1921                 }
1922                 return 0;
1923         }
1924
1925         return __iwl_mvm_resume(mvm, false);
1926 }
1927
1928 void iwl_mvm_set_wakeup(struct ieee80211_hw *hw, bool enabled)
1929 {
1930         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1931
1932         device_set_wakeup_enable(mvm->trans->dev, enabled);
1933 }
1934
1935 #ifdef CONFIG_IWLWIFI_DEBUGFS
1936 static int iwl_mvm_d3_test_open(struct inode *inode, struct file *file)
1937 {
1938         struct iwl_mvm *mvm = inode->i_private;
1939         int err;
1940
1941         if (mvm->d3_test_active)
1942                 return -EBUSY;
1943
1944         file->private_data = inode->i_private;
1945
1946         ieee80211_stop_queues(mvm->hw);
1947         synchronize_net();
1948
1949         /* start pseudo D3 */
1950         rtnl_lock();
1951         err = __iwl_mvm_suspend(mvm->hw, mvm->hw->wiphy->wowlan_config, true);
1952         rtnl_unlock();
1953         if (err > 0)
1954                 err = -EINVAL;
1955         if (err) {
1956                 ieee80211_wake_queues(mvm->hw);
1957                 return err;
1958         }
1959         mvm->d3_test_active = true;
1960         mvm->keep_vif = NULL;
1961         return 0;
1962 }
1963
1964 static ssize_t iwl_mvm_d3_test_read(struct file *file, char __user *user_buf,
1965                                     size_t count, loff_t *ppos)
1966 {
1967         struct iwl_mvm *mvm = file->private_data;
1968         u32 pme_asserted;
1969
1970         while (true) {
1971                 /* read pme_ptr if available */
1972                 if (mvm->d3_test_pme_ptr) {
1973                         pme_asserted = iwl_trans_read_mem32(mvm->trans,
1974                                                 mvm->d3_test_pme_ptr);
1975                         if (pme_asserted)
1976                                 break;
1977                 }
1978
1979                 if (msleep_interruptible(100))
1980                         break;
1981         }
1982
1983         return 0;
1984 }
1985
1986 static void iwl_mvm_d3_test_disconn_work_iter(void *_data, u8 *mac,
1987                                               struct ieee80211_vif *vif)
1988 {
1989         /* skip the one we keep connection on */
1990         if (_data == vif)
1991                 return;
1992
1993         if (vif->type == NL80211_IFTYPE_STATION)
1994                 ieee80211_connection_loss(vif);
1995 }
1996
1997 static int iwl_mvm_d3_test_release(struct inode *inode, struct file *file)
1998 {
1999         struct iwl_mvm *mvm = inode->i_private;
2000         int remaining_time = 10;
2001
2002         mvm->d3_test_active = false;
2003         rtnl_lock();
2004         __iwl_mvm_resume(mvm, true);
2005         rtnl_unlock();
2006         iwl_abort_notification_waits(&mvm->notif_wait);
2007         ieee80211_restart_hw(mvm->hw);
2008
2009         /* wait for restart and disconnect all interfaces */
2010         while (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) &&
2011                remaining_time > 0) {
2012                 remaining_time--;
2013                 msleep(1000);
2014         }
2015
2016         if (remaining_time == 0)
2017                 IWL_ERR(mvm, "Timed out waiting for HW restart to finish!\n");
2018
2019         ieee80211_iterate_active_interfaces_atomic(
2020                 mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
2021                 iwl_mvm_d3_test_disconn_work_iter, mvm->keep_vif);
2022
2023         ieee80211_wake_queues(mvm->hw);
2024
2025         return 0;
2026 }
2027
2028 const struct file_operations iwl_dbgfs_d3_test_ops = {
2029         .llseek = no_llseek,
2030         .open = iwl_mvm_d3_test_open,
2031         .read = iwl_mvm_d3_test_read,
2032         .release = iwl_mvm_d3_test_release,
2033 };
2034 #endif