Merge branch 'acpi-cleanup'
[firefly-linux-kernel-4.4.55.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 - 2013 Intel Corporation. All rights reserved.
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of version 2 of the GNU General Public License as
12  * published by the Free Software Foundation.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
22  * USA
23  *
24  * The full GNU General Public License is included in this distribution
25  * in the file called COPYING.
26  *
27  * Contact Information:
28  *  Intel Linux Wireless <ilw@linux.intel.com>
29  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
30  *
31  * BSD LICENSE
32  *
33  * Copyright(c) 2012 - 2013 Intel Corporation. All rights reserved.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  *
40  *  * Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  *  * Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in
44  *    the documentation and/or other materials provided with the
45  *    distribution.
46  *  * Neither the name Intel Corporation nor the names of its
47  *    contributors may be used to endorse or promote products derived
48  *    from this software without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
54  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
55  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
56  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
57  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
58  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
59  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
60  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61  *
62  *****************************************************************************/
63
64 #include <linux/etherdevice.h>
65 #include <linux/ip.h>
66 #include <linux/fs.h>
67 #include <net/cfg80211.h>
68 #include <net/ipv6.h>
69 #include <net/tcp.h>
70 #include "iwl-modparams.h"
71 #include "fw-api.h"
72 #include "mvm.h"
73
74 void iwl_mvm_set_rekey_data(struct ieee80211_hw *hw,
75                             struct ieee80211_vif *vif,
76                             struct cfg80211_gtk_rekey_data *data)
77 {
78         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
79         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
80
81         if (iwlwifi_mod_params.sw_crypto)
82                 return;
83
84         mutex_lock(&mvm->mutex);
85
86         memcpy(mvmvif->rekey_data.kek, data->kek, NL80211_KEK_LEN);
87         memcpy(mvmvif->rekey_data.kck, data->kck, NL80211_KCK_LEN);
88         mvmvif->rekey_data.replay_ctr =
89                 cpu_to_le64(be64_to_cpup((__be64 *)&data->replay_ctr));
90         mvmvif->rekey_data.valid = true;
91
92         mutex_unlock(&mvm->mutex);
93 }
94
95 #if IS_ENABLED(CONFIG_IPV6)
96 void iwl_mvm_ipv6_addr_change(struct ieee80211_hw *hw,
97                               struct ieee80211_vif *vif,
98                               struct inet6_dev *idev)
99 {
100         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
101         struct inet6_ifaddr *ifa;
102         int idx = 0;
103
104         read_lock_bh(&idev->lock);
105         list_for_each_entry(ifa, &idev->addr_list, if_list) {
106                 mvmvif->target_ipv6_addrs[idx] = ifa->addr;
107                 idx++;
108                 if (idx >= IWL_PROTO_OFFLOAD_NUM_IPV6_ADDRS)
109                         break;
110         }
111         read_unlock_bh(&idev->lock);
112
113         mvmvif->num_target_ipv6_addrs = idx;
114 }
115 #endif
116
117 void iwl_mvm_set_default_unicast_key(struct ieee80211_hw *hw,
118                                      struct ieee80211_vif *vif, int idx)
119 {
120         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
121
122         mvmvif->tx_key_idx = idx;
123 }
124
125 static void iwl_mvm_convert_p1k(u16 *p1k, __le16 *out)
126 {
127         int i;
128
129         for (i = 0; i < IWL_P1K_SIZE; i++)
130                 out[i] = cpu_to_le16(p1k[i]);
131 }
132
133 struct wowlan_key_data {
134         struct iwl_wowlan_rsc_tsc_params_cmd *rsc_tsc;
135         struct iwl_wowlan_tkip_params_cmd *tkip;
136         bool error, use_rsc_tsc, use_tkip;
137         int wep_key_idx;
138 };
139
140 static void iwl_mvm_wowlan_program_keys(struct ieee80211_hw *hw,
141                                         struct ieee80211_vif *vif,
142                                         struct ieee80211_sta *sta,
143                                         struct ieee80211_key_conf *key,
144                                         void *_data)
145 {
146         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
147         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
148         struct wowlan_key_data *data = _data;
149         struct aes_sc *aes_sc, *aes_tx_sc = NULL;
150         struct tkip_sc *tkip_sc, *tkip_tx_sc = NULL;
151         struct iwl_p1k_cache *rx_p1ks;
152         u8 *rx_mic_key;
153         struct ieee80211_key_seq seq;
154         u32 cur_rx_iv32 = 0;
155         u16 p1k[IWL_P1K_SIZE];
156         int ret, i;
157
158         mutex_lock(&mvm->mutex);
159
160         switch (key->cipher) {
161         case WLAN_CIPHER_SUITE_WEP40:
162         case WLAN_CIPHER_SUITE_WEP104: { /* hack it for now */
163                 struct {
164                         struct iwl_mvm_wep_key_cmd wep_key_cmd;
165                         struct iwl_mvm_wep_key wep_key;
166                 } __packed wkc = {
167                         .wep_key_cmd.mac_id_n_color =
168                                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
169                                                                 mvmvif->color)),
170                         .wep_key_cmd.num_keys = 1,
171                         /* firmware sets STA_KEY_FLG_WEP_13BYTES */
172                         .wep_key_cmd.decryption_type = STA_KEY_FLG_WEP,
173                         .wep_key.key_index = key->keyidx,
174                         .wep_key.key_size = key->keylen,
175                 };
176
177                 /*
178                  * This will fail -- the key functions don't set support
179                  * pairwise WEP keys. However, that's better than silently
180                  * failing WoWLAN. Or maybe not?
181                  */
182                 if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE)
183                         break;
184
185                 memcpy(&wkc.wep_key.key[3], key->key, key->keylen);
186                 if (key->keyidx == mvmvif->tx_key_idx) {
187                         /* TX key must be at offset 0 */
188                         wkc.wep_key.key_offset = 0;
189                 } else {
190                         /* others start at 1 */
191                         data->wep_key_idx++;
192                         wkc.wep_key.key_offset = data->wep_key_idx;
193                 }
194
195                 ret = iwl_mvm_send_cmd_pdu(mvm, WEP_KEY, CMD_SYNC,
196                                            sizeof(wkc), &wkc);
197                 data->error = ret != 0;
198
199                 mvm->ptk_ivlen = key->iv_len;
200                 mvm->ptk_icvlen = key->icv_len;
201                 mvm->gtk_ivlen = key->iv_len;
202                 mvm->gtk_icvlen = key->icv_len;
203
204                 /* don't upload key again */
205                 goto out_unlock;
206         }
207         default:
208                 data->error = true;
209                 goto out_unlock;
210         case WLAN_CIPHER_SUITE_AES_CMAC:
211                 /*
212                  * Ignore CMAC keys -- the WoWLAN firmware doesn't support them
213                  * but we also shouldn't abort suspend due to that. It does have
214                  * support for the IGTK key renewal, but doesn't really use the
215                  * IGTK for anything. This means we could spuriously wake up or
216                  * be deauthenticated, but that was considered acceptable.
217                  */
218                 goto out_unlock;
219         case WLAN_CIPHER_SUITE_TKIP:
220                 if (sta) {
221                         tkip_sc = data->rsc_tsc->all_tsc_rsc.tkip.unicast_rsc;
222                         tkip_tx_sc = &data->rsc_tsc->all_tsc_rsc.tkip.tsc;
223
224                         rx_p1ks = data->tkip->rx_uni;
225
226                         ieee80211_get_key_tx_seq(key, &seq);
227                         tkip_tx_sc->iv16 = cpu_to_le16(seq.tkip.iv16);
228                         tkip_tx_sc->iv32 = cpu_to_le32(seq.tkip.iv32);
229
230                         ieee80211_get_tkip_p1k_iv(key, seq.tkip.iv32, p1k);
231                         iwl_mvm_convert_p1k(p1k, data->tkip->tx.p1k);
232
233                         memcpy(data->tkip->mic_keys.tx,
234                                &key->key[NL80211_TKIP_DATA_OFFSET_TX_MIC_KEY],
235                                IWL_MIC_KEY_SIZE);
236
237                         rx_mic_key = data->tkip->mic_keys.rx_unicast;
238                 } else {
239                         tkip_sc =
240                                 data->rsc_tsc->all_tsc_rsc.tkip.multicast_rsc;
241                         rx_p1ks = data->tkip->rx_multi;
242                         rx_mic_key = data->tkip->mic_keys.rx_mcast;
243                 }
244
245                 /*
246                  * For non-QoS this relies on the fact that both the uCode and
247                  * mac80211 use TID 0 (as they need to to avoid replay attacks)
248                  * for checking the IV in the frames.
249                  */
250                 for (i = 0; i < IWL_NUM_RSC; i++) {
251                         ieee80211_get_key_rx_seq(key, i, &seq);
252                         tkip_sc[i].iv16 = cpu_to_le16(seq.tkip.iv16);
253                         tkip_sc[i].iv32 = cpu_to_le32(seq.tkip.iv32);
254                         /* wrapping isn't allowed, AP must rekey */
255                         if (seq.tkip.iv32 > cur_rx_iv32)
256                                 cur_rx_iv32 = seq.tkip.iv32;
257                 }
258
259                 ieee80211_get_tkip_rx_p1k(key, vif->bss_conf.bssid,
260                                           cur_rx_iv32, p1k);
261                 iwl_mvm_convert_p1k(p1k, rx_p1ks[0].p1k);
262                 ieee80211_get_tkip_rx_p1k(key, vif->bss_conf.bssid,
263                                           cur_rx_iv32 + 1, p1k);
264                 iwl_mvm_convert_p1k(p1k, rx_p1ks[1].p1k);
265
266                 memcpy(rx_mic_key,
267                        &key->key[NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY],
268                        IWL_MIC_KEY_SIZE);
269
270                 data->use_tkip = true;
271                 data->use_rsc_tsc = true;
272                 break;
273         case WLAN_CIPHER_SUITE_CCMP:
274                 if (sta) {
275                         u8 *pn = seq.ccmp.pn;
276
277                         aes_sc = data->rsc_tsc->all_tsc_rsc.aes.unicast_rsc;
278                         aes_tx_sc = &data->rsc_tsc->all_tsc_rsc.aes.tsc;
279
280                         ieee80211_get_key_tx_seq(key, &seq);
281                         aes_tx_sc->pn = cpu_to_le64((u64)pn[5] |
282                                                     ((u64)pn[4] << 8) |
283                                                     ((u64)pn[3] << 16) |
284                                                     ((u64)pn[2] << 24) |
285                                                     ((u64)pn[1] << 32) |
286                                                     ((u64)pn[0] << 40));
287                 } else {
288                         aes_sc = data->rsc_tsc->all_tsc_rsc.aes.multicast_rsc;
289                 }
290
291                 /*
292                  * For non-QoS this relies on the fact that both the uCode and
293                  * mac80211 use TID 0 for checking the IV in the frames.
294                  */
295                 for (i = 0; i < IWL_NUM_RSC; i++) {
296                         u8 *pn = seq.ccmp.pn;
297
298                         ieee80211_get_key_rx_seq(key, i, &seq);
299                         aes_sc->pn = cpu_to_le64((u64)pn[5] |
300                                                  ((u64)pn[4] << 8) |
301                                                  ((u64)pn[3] << 16) |
302                                                  ((u64)pn[2] << 24) |
303                                                  ((u64)pn[1] << 32) |
304                                                  ((u64)pn[0] << 40));
305                 }
306                 data->use_rsc_tsc = true;
307                 break;
308         }
309
310         /*
311          * The D3 firmware hardcodes the key offset 0 as the key it uses
312          * to transmit packets to the AP, i.e. the PTK.
313          */
314         if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) {
315                 key->hw_key_idx = 0;
316                 mvm->ptk_ivlen = key->iv_len;
317                 mvm->ptk_icvlen = key->icv_len;
318         } else {
319                 /*
320                  * firmware only supports TSC/RSC for a single key,
321                  * so if there are multiple keep overwriting them
322                  * with new ones -- this relies on mac80211 doing
323                  * list_add_tail().
324                  */
325                 key->hw_key_idx = 1;
326                 mvm->gtk_ivlen = key->iv_len;
327                 mvm->gtk_icvlen = key->icv_len;
328         }
329
330         ret = iwl_mvm_set_sta_key(mvm, vif, sta, key, true);
331         data->error = ret != 0;
332 out_unlock:
333         mutex_unlock(&mvm->mutex);
334 }
335
336 static int iwl_mvm_send_patterns(struct iwl_mvm *mvm,
337                                  struct cfg80211_wowlan *wowlan)
338 {
339         struct iwl_wowlan_patterns_cmd *pattern_cmd;
340         struct iwl_host_cmd cmd = {
341                 .id = WOWLAN_PATTERNS,
342                 .dataflags[0] = IWL_HCMD_DFL_NOCOPY,
343                 .flags = CMD_SYNC,
344         };
345         int i, err;
346
347         if (!wowlan->n_patterns)
348                 return 0;
349
350         cmd.len[0] = sizeof(*pattern_cmd) +
351                 wowlan->n_patterns * sizeof(struct iwl_wowlan_pattern);
352
353         pattern_cmd = kmalloc(cmd.len[0], GFP_KERNEL);
354         if (!pattern_cmd)
355                 return -ENOMEM;
356
357         pattern_cmd->n_patterns = cpu_to_le32(wowlan->n_patterns);
358
359         for (i = 0; i < wowlan->n_patterns; i++) {
360                 int mask_len = DIV_ROUND_UP(wowlan->patterns[i].pattern_len, 8);
361
362                 memcpy(&pattern_cmd->patterns[i].mask,
363                        wowlan->patterns[i].mask, mask_len);
364                 memcpy(&pattern_cmd->patterns[i].pattern,
365                        wowlan->patterns[i].pattern,
366                        wowlan->patterns[i].pattern_len);
367                 pattern_cmd->patterns[i].mask_size = mask_len;
368                 pattern_cmd->patterns[i].pattern_size =
369                         wowlan->patterns[i].pattern_len;
370         }
371
372         cmd.data[0] = pattern_cmd;
373         err = iwl_mvm_send_cmd(mvm, &cmd);
374         kfree(pattern_cmd);
375         return err;
376 }
377
378 static int iwl_mvm_send_proto_offload(struct iwl_mvm *mvm,
379                                       struct ieee80211_vif *vif)
380 {
381         struct iwl_proto_offload_cmd cmd = {};
382 #if IS_ENABLED(CONFIG_IPV6)
383         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
384         int i;
385
386         if (mvmvif->num_target_ipv6_addrs) {
387                 cmd.enabled |= cpu_to_le32(IWL_D3_PROTO_OFFLOAD_NS);
388                 memcpy(cmd.ndp_mac_addr, vif->addr, ETH_ALEN);
389         }
390
391         BUILD_BUG_ON(sizeof(cmd.target_ipv6_addr[i]) !=
392                      sizeof(mvmvif->target_ipv6_addrs[i]));
393
394         for (i = 0; i < mvmvif->num_target_ipv6_addrs; i++)
395                 memcpy(cmd.target_ipv6_addr[i],
396                        &mvmvif->target_ipv6_addrs[i],
397                        sizeof(cmd.target_ipv6_addr[i]));
398 #endif
399
400         if (vif->bss_conf.arp_addr_cnt) {
401                 cmd.enabled |= cpu_to_le32(IWL_D3_PROTO_OFFLOAD_ARP);
402                 cmd.host_ipv4_addr = vif->bss_conf.arp_addr_list[0];
403                 memcpy(cmd.arp_mac_addr, vif->addr, ETH_ALEN);
404         }
405
406         if (!cmd.enabled)
407                 return 0;
408
409         return iwl_mvm_send_cmd_pdu(mvm, PROT_OFFLOAD_CONFIG_CMD, CMD_SYNC,
410                                     sizeof(cmd), &cmd);
411 }
412
413 enum iwl_mvm_tcp_packet_type {
414         MVM_TCP_TX_SYN,
415         MVM_TCP_RX_SYNACK,
416         MVM_TCP_TX_DATA,
417         MVM_TCP_RX_ACK,
418         MVM_TCP_RX_WAKE,
419         MVM_TCP_TX_FIN,
420 };
421
422 static __le16 pseudo_hdr_check(int len, __be32 saddr, __be32 daddr)
423 {
424         __sum16 check = tcp_v4_check(len, saddr, daddr, 0);
425         return cpu_to_le16(be16_to_cpu((__force __be16)check));
426 }
427
428 static void iwl_mvm_build_tcp_packet(struct ieee80211_vif *vif,
429                                      struct cfg80211_wowlan_tcp *tcp,
430                                      void *_pkt, u8 *mask,
431                                      __le16 *pseudo_hdr_csum,
432                                      enum iwl_mvm_tcp_packet_type ptype)
433 {
434         struct {
435                 struct ethhdr eth;
436                 struct iphdr ip;
437                 struct tcphdr tcp;
438                 u8 data[];
439         } __packed *pkt = _pkt;
440         u16 ip_tot_len = sizeof(struct iphdr) + sizeof(struct tcphdr);
441         int i;
442
443         pkt->eth.h_proto = cpu_to_be16(ETH_P_IP),
444         pkt->ip.version = 4;
445         pkt->ip.ihl = 5;
446         pkt->ip.protocol = IPPROTO_TCP;
447
448         switch (ptype) {
449         case MVM_TCP_TX_SYN:
450         case MVM_TCP_TX_DATA:
451         case MVM_TCP_TX_FIN:
452                 memcpy(pkt->eth.h_dest, tcp->dst_mac, ETH_ALEN);
453                 memcpy(pkt->eth.h_source, vif->addr, ETH_ALEN);
454                 pkt->ip.ttl = 128;
455                 pkt->ip.saddr = tcp->src;
456                 pkt->ip.daddr = tcp->dst;
457                 pkt->tcp.source = cpu_to_be16(tcp->src_port);
458                 pkt->tcp.dest = cpu_to_be16(tcp->dst_port);
459                 /* overwritten for TX SYN later */
460                 pkt->tcp.doff = sizeof(struct tcphdr) / 4;
461                 pkt->tcp.window = cpu_to_be16(65000);
462                 break;
463         case MVM_TCP_RX_SYNACK:
464         case MVM_TCP_RX_ACK:
465         case MVM_TCP_RX_WAKE:
466                 memcpy(pkt->eth.h_dest, vif->addr, ETH_ALEN);
467                 memcpy(pkt->eth.h_source, tcp->dst_mac, ETH_ALEN);
468                 pkt->ip.saddr = tcp->dst;
469                 pkt->ip.daddr = tcp->src;
470                 pkt->tcp.source = cpu_to_be16(tcp->dst_port);
471                 pkt->tcp.dest = cpu_to_be16(tcp->src_port);
472                 break;
473         default:
474                 WARN_ON(1);
475                 return;
476         }
477
478         switch (ptype) {
479         case MVM_TCP_TX_SYN:
480                 /* firmware assumes 8 option bytes - 8 NOPs for now */
481                 memset(pkt->data, 0x01, 8);
482                 ip_tot_len += 8;
483                 pkt->tcp.doff = (sizeof(struct tcphdr) + 8) / 4;
484                 pkt->tcp.syn = 1;
485                 break;
486         case MVM_TCP_TX_DATA:
487                 ip_tot_len += tcp->payload_len;
488                 memcpy(pkt->data, tcp->payload, tcp->payload_len);
489                 pkt->tcp.psh = 1;
490                 pkt->tcp.ack = 1;
491                 break;
492         case MVM_TCP_TX_FIN:
493                 pkt->tcp.fin = 1;
494                 pkt->tcp.ack = 1;
495                 break;
496         case MVM_TCP_RX_SYNACK:
497                 pkt->tcp.syn = 1;
498                 pkt->tcp.ack = 1;
499                 break;
500         case MVM_TCP_RX_ACK:
501                 pkt->tcp.ack = 1;
502                 break;
503         case MVM_TCP_RX_WAKE:
504                 ip_tot_len += tcp->wake_len;
505                 pkt->tcp.psh = 1;
506                 pkt->tcp.ack = 1;
507                 memcpy(pkt->data, tcp->wake_data, tcp->wake_len);
508                 break;
509         }
510
511         switch (ptype) {
512         case MVM_TCP_TX_SYN:
513         case MVM_TCP_TX_DATA:
514         case MVM_TCP_TX_FIN:
515                 pkt->ip.tot_len = cpu_to_be16(ip_tot_len);
516                 pkt->ip.check = ip_fast_csum(&pkt->ip, pkt->ip.ihl);
517                 break;
518         case MVM_TCP_RX_WAKE:
519                 for (i = 0; i < DIV_ROUND_UP(tcp->wake_len, 8); i++) {
520                         u8 tmp = tcp->wake_mask[i];
521                         mask[i + 6] |= tmp << 6;
522                         if (i + 1 < DIV_ROUND_UP(tcp->wake_len, 8))
523                                 mask[i + 7] = tmp >> 2;
524                 }
525                 /* fall through for ethernet/IP/TCP headers mask */
526         case MVM_TCP_RX_SYNACK:
527         case MVM_TCP_RX_ACK:
528                 mask[0] = 0xff; /* match ethernet */
529                 /*
530                  * match ethernet, ip.version, ip.ihl
531                  * the ip.ihl half byte is really masked out by firmware
532                  */
533                 mask[1] = 0x7f;
534                 mask[2] = 0x80; /* match ip.protocol */
535                 mask[3] = 0xfc; /* match ip.saddr, ip.daddr */
536                 mask[4] = 0x3f; /* match ip.daddr, tcp.source, tcp.dest */
537                 mask[5] = 0x80; /* match tcp flags */
538                 /* leave rest (0 or set for MVM_TCP_RX_WAKE) */
539                 break;
540         };
541
542         *pseudo_hdr_csum = pseudo_hdr_check(ip_tot_len - sizeof(struct iphdr),
543                                             pkt->ip.saddr, pkt->ip.daddr);
544 }
545
546 static int iwl_mvm_send_remote_wake_cfg(struct iwl_mvm *mvm,
547                                         struct ieee80211_vif *vif,
548                                         struct cfg80211_wowlan_tcp *tcp)
549 {
550         struct iwl_wowlan_remote_wake_config *cfg;
551         struct iwl_host_cmd cmd = {
552                 .id = REMOTE_WAKE_CONFIG_CMD,
553                 .len = { sizeof(*cfg), },
554                 .dataflags = { IWL_HCMD_DFL_NOCOPY, },
555                 .flags = CMD_SYNC,
556         };
557         int ret;
558
559         if (!tcp)
560                 return 0;
561
562         cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
563         if (!cfg)
564                 return -ENOMEM;
565         cmd.data[0] = cfg;
566
567         cfg->max_syn_retries = 10;
568         cfg->max_data_retries = 10;
569         cfg->tcp_syn_ack_timeout = 1; /* seconds */
570         cfg->tcp_ack_timeout = 1; /* seconds */
571
572         /* SYN (TX) */
573         iwl_mvm_build_tcp_packet(
574                 vif, tcp, cfg->syn_tx.data, NULL,
575                 &cfg->syn_tx.info.tcp_pseudo_header_checksum,
576                 MVM_TCP_TX_SYN);
577         cfg->syn_tx.info.tcp_payload_length = 0;
578
579         /* SYN/ACK (RX) */
580         iwl_mvm_build_tcp_packet(
581                 vif, tcp, cfg->synack_rx.data, cfg->synack_rx.rx_mask,
582                 &cfg->synack_rx.info.tcp_pseudo_header_checksum,
583                 MVM_TCP_RX_SYNACK);
584         cfg->synack_rx.info.tcp_payload_length = 0;
585
586         /* KEEPALIVE/ACK (TX) */
587         iwl_mvm_build_tcp_packet(
588                 vif, tcp, cfg->keepalive_tx.data, NULL,
589                 &cfg->keepalive_tx.info.tcp_pseudo_header_checksum,
590                 MVM_TCP_TX_DATA);
591         cfg->keepalive_tx.info.tcp_payload_length =
592                 cpu_to_le16(tcp->payload_len);
593         cfg->sequence_number_offset = tcp->payload_seq.offset;
594         /* length must be 0..4, the field is little endian */
595         cfg->sequence_number_length = tcp->payload_seq.len;
596         cfg->initial_sequence_number = cpu_to_le32(tcp->payload_seq.start);
597         cfg->keepalive_interval = cpu_to_le16(tcp->data_interval);
598         if (tcp->payload_tok.len) {
599                 cfg->token_offset = tcp->payload_tok.offset;
600                 cfg->token_length = tcp->payload_tok.len;
601                 cfg->num_tokens =
602                         cpu_to_le16(tcp->tokens_size % tcp->payload_tok.len);
603                 memcpy(cfg->tokens, tcp->payload_tok.token_stream,
604                        tcp->tokens_size);
605         } else {
606                 /* set tokens to max value to almost never run out */
607                 cfg->num_tokens = cpu_to_le16(65535);
608         }
609
610         /* ACK (RX) */
611         iwl_mvm_build_tcp_packet(
612                 vif, tcp, cfg->keepalive_ack_rx.data,
613                 cfg->keepalive_ack_rx.rx_mask,
614                 &cfg->keepalive_ack_rx.info.tcp_pseudo_header_checksum,
615                 MVM_TCP_RX_ACK);
616         cfg->keepalive_ack_rx.info.tcp_payload_length = 0;
617
618         /* WAKEUP (RX) */
619         iwl_mvm_build_tcp_packet(
620                 vif, tcp, cfg->wake_rx.data, cfg->wake_rx.rx_mask,
621                 &cfg->wake_rx.info.tcp_pseudo_header_checksum,
622                 MVM_TCP_RX_WAKE);
623         cfg->wake_rx.info.tcp_payload_length =
624                 cpu_to_le16(tcp->wake_len);
625
626         /* FIN */
627         iwl_mvm_build_tcp_packet(
628                 vif, tcp, cfg->fin_tx.data, NULL,
629                 &cfg->fin_tx.info.tcp_pseudo_header_checksum,
630                 MVM_TCP_TX_FIN);
631         cfg->fin_tx.info.tcp_payload_length = 0;
632
633         ret = iwl_mvm_send_cmd(mvm, &cmd);
634         kfree(cfg);
635
636         return ret;
637 }
638
639 struct iwl_d3_iter_data {
640         struct iwl_mvm *mvm;
641         struct ieee80211_vif *vif;
642         bool error;
643 };
644
645 static void iwl_mvm_d3_iface_iterator(void *_data, u8 *mac,
646                                       struct ieee80211_vif *vif)
647 {
648         struct iwl_d3_iter_data *data = _data;
649         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
650
651         if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
652                 return;
653
654         if (mvmvif->ap_sta_id == IWL_MVM_STATION_COUNT)
655                 return;
656
657         if (data->vif) {
658                 IWL_ERR(data->mvm, "More than one managed interface active!\n");
659                 data->error = true;
660                 return;
661         }
662
663         data->vif = vif;
664 }
665
666 static int iwl_mvm_d3_reprogram(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
667                                 struct ieee80211_sta *ap_sta)
668 {
669         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
670         struct ieee80211_chanctx_conf *ctx;
671         u8 chains_static, chains_dynamic;
672         struct cfg80211_chan_def chandef;
673         int ret, i;
674         struct iwl_binding_cmd binding_cmd = {};
675         struct iwl_time_quota_cmd quota_cmd = {};
676         u32 status;
677
678         /* add back the PHY */
679         if (WARN_ON(!mvmvif->phy_ctxt))
680                 return -EINVAL;
681
682         rcu_read_lock();
683         ctx = rcu_dereference(vif->chanctx_conf);
684         if (WARN_ON(!ctx)) {
685                 rcu_read_unlock();
686                 return -EINVAL;
687         }
688         chandef = ctx->def;
689         chains_static = ctx->rx_chains_static;
690         chains_dynamic = ctx->rx_chains_dynamic;
691         rcu_read_unlock();
692
693         ret = iwl_mvm_phy_ctxt_add(mvm, mvmvif->phy_ctxt, &chandef,
694                                    chains_static, chains_dynamic);
695         if (ret)
696                 return ret;
697
698         /* add back the MAC */
699         mvmvif->uploaded = false;
700
701         if (WARN_ON(!vif->bss_conf.assoc))
702                 return -EINVAL;
703         /* hack */
704         vif->bss_conf.assoc = false;
705         ret = iwl_mvm_mac_ctxt_add(mvm, vif);
706         vif->bss_conf.assoc = true;
707         if (ret)
708                 return ret;
709
710         /* add back binding - XXX refactor? */
711         binding_cmd.id_and_color =
712                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
713                                                 mvmvif->phy_ctxt->color));
714         binding_cmd.action = cpu_to_le32(FW_CTXT_ACTION_ADD);
715         binding_cmd.phy =
716                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
717                                                 mvmvif->phy_ctxt->color));
718         binding_cmd.macs[0] = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
719                                                               mvmvif->color));
720         for (i = 1; i < MAX_MACS_IN_BINDING; i++)
721                 binding_cmd.macs[i] = cpu_to_le32(FW_CTXT_INVALID);
722
723         status = 0;
724         ret = iwl_mvm_send_cmd_pdu_status(mvm, BINDING_CONTEXT_CMD,
725                                           sizeof(binding_cmd), &binding_cmd,
726                                           &status);
727         if (ret) {
728                 IWL_ERR(mvm, "Failed to add binding: %d\n", ret);
729                 return ret;
730         }
731
732         if (status) {
733                 IWL_ERR(mvm, "Binding command failed: %u\n", status);
734                 return -EIO;
735         }
736
737         ret = iwl_mvm_sta_send_to_fw(mvm, ap_sta, false);
738         if (ret)
739                 return ret;
740         rcu_assign_pointer(mvm->fw_id_to_mac_id[mvmvif->ap_sta_id], ap_sta);
741
742         ret = iwl_mvm_mac_ctxt_changed(mvm, vif);
743         if (ret)
744                 return ret;
745
746         /* and some quota */
747         quota_cmd.quotas[0].id_and_color =
748                 cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->phy_ctxt->id,
749                                                 mvmvif->phy_ctxt->color));
750         quota_cmd.quotas[0].quota = cpu_to_le32(100);
751         quota_cmd.quotas[0].max_duration = cpu_to_le32(1000);
752
753         for (i = 1; i < MAX_BINDINGS; i++)
754                 quota_cmd.quotas[i].id_and_color = cpu_to_le32(FW_CTXT_INVALID);
755
756         ret = iwl_mvm_send_cmd_pdu(mvm, TIME_QUOTA_CMD, CMD_SYNC,
757                                    sizeof(quota_cmd), &quota_cmd);
758         if (ret)
759                 IWL_ERR(mvm, "Failed to send quota: %d\n", ret);
760
761         return 0;
762 }
763
764 static int __iwl_mvm_suspend(struct ieee80211_hw *hw,
765                              struct cfg80211_wowlan *wowlan,
766                              bool test)
767 {
768         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
769         struct iwl_d3_iter_data suspend_iter_data = {
770                 .mvm = mvm,
771         };
772         struct ieee80211_vif *vif;
773         struct iwl_mvm_vif *mvmvif;
774         struct ieee80211_sta *ap_sta;
775         struct iwl_mvm_sta *mvm_ap_sta;
776         struct iwl_wowlan_config_cmd wowlan_config_cmd = {};
777         struct iwl_wowlan_kek_kck_material_cmd kek_kck_cmd = {};
778         struct iwl_wowlan_tkip_params_cmd tkip_cmd = {};
779         struct iwl_d3_manager_config d3_cfg_cmd_data = {
780                 /*
781                  * Program the minimum sleep time to 10 seconds, as many
782                  * platforms have issues processing a wakeup signal while
783                  * still being in the process of suspending.
784                  */
785                 .min_sleep_time = cpu_to_le32(10 * 1000 * 1000),
786         };
787         struct iwl_host_cmd d3_cfg_cmd = {
788                 .id = D3_CONFIG_CMD,
789                 .flags = CMD_SYNC | CMD_WANT_SKB,
790                 .data[0] = &d3_cfg_cmd_data,
791                 .len[0] = sizeof(d3_cfg_cmd_data),
792         };
793         struct wowlan_key_data key_data = {
794                 .use_rsc_tsc = false,
795                 .tkip = &tkip_cmd,
796                 .use_tkip = false,
797         };
798         int ret, i;
799         int len __maybe_unused;
800         u16 seq;
801         u8 old_aux_sta_id, old_ap_sta_id = IWL_MVM_STATION_COUNT;
802
803         if (!wowlan) {
804                 /*
805                  * mac80211 shouldn't get here, but for D3 test
806                  * it doesn't warrant a warning
807                  */
808                 WARN_ON(!test);
809                 return -EINVAL;
810         }
811
812         key_data.rsc_tsc = kzalloc(sizeof(*key_data.rsc_tsc), GFP_KERNEL);
813         if (!key_data.rsc_tsc)
814                 return -ENOMEM;
815
816         mutex_lock(&mvm->mutex);
817
818         old_aux_sta_id = mvm->aux_sta.sta_id;
819
820         /* see if there's only a single BSS vif and it's associated */
821         ieee80211_iterate_active_interfaces_atomic(
822                 mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
823                 iwl_mvm_d3_iface_iterator, &suspend_iter_data);
824
825         if (suspend_iter_data.error || !suspend_iter_data.vif) {
826                 ret = 1;
827                 goto out_noreset;
828         }
829
830         vif = suspend_iter_data.vif;
831         mvmvif = iwl_mvm_vif_from_mac80211(vif);
832
833         ap_sta = rcu_dereference_protected(
834                         mvm->fw_id_to_mac_id[mvmvif->ap_sta_id],
835                         lockdep_is_held(&mvm->mutex));
836         if (IS_ERR_OR_NULL(ap_sta)) {
837                 ret = -EINVAL;
838                 goto out_noreset;
839         }
840
841         mvm_ap_sta = (struct iwl_mvm_sta *)ap_sta->drv_priv;
842
843         /*
844          * The D3 firmware still hardcodes the AP station ID for the
845          * BSS we're associated with as 0. Store the real STA ID here
846          * and assign 0. When we leave this function, we'll restore
847          * the original value for the resume code.
848          */
849         old_ap_sta_id = mvm_ap_sta->sta_id;
850         mvm_ap_sta->sta_id = 0;
851         mvmvif->ap_sta_id = 0;
852
853         /* TODO: wowlan_config_cmd.wowlan_ba_teardown_tids */
854
855         wowlan_config_cmd.is_11n_connection = ap_sta->ht_cap.ht_supported;
856
857         /*
858          * We know the last used seqno, and the uCode expects to know that
859          * one, it will increment before TX.
860          */
861         seq = mvm_ap_sta->last_seq_ctl & IEEE80211_SCTL_SEQ;
862         wowlan_config_cmd.non_qos_seq = cpu_to_le16(seq);
863
864         /*
865          * For QoS counters, we store the one to use next, so subtract 0x10
866          * since the uCode will add 0x10 *before* using the value while we
867          * increment after using the value (i.e. store the next value to use).
868          */
869         for (i = 0; i < IWL_MAX_TID_COUNT; i++) {
870                 seq = mvm_ap_sta->tid_data[i].seq_number;
871                 seq -= 0x10;
872                 wowlan_config_cmd.qos_seq[i] = cpu_to_le16(seq);
873         }
874
875         if (wowlan->disconnect)
876                 wowlan_config_cmd.wakeup_filter |=
877                         cpu_to_le32(IWL_WOWLAN_WAKEUP_BEACON_MISS |
878                                     IWL_WOWLAN_WAKEUP_LINK_CHANGE);
879         if (wowlan->magic_pkt)
880                 wowlan_config_cmd.wakeup_filter |=
881                         cpu_to_le32(IWL_WOWLAN_WAKEUP_MAGIC_PACKET);
882         if (wowlan->gtk_rekey_failure)
883                 wowlan_config_cmd.wakeup_filter |=
884                         cpu_to_le32(IWL_WOWLAN_WAKEUP_GTK_REKEY_FAIL);
885         if (wowlan->eap_identity_req)
886                 wowlan_config_cmd.wakeup_filter |=
887                         cpu_to_le32(IWL_WOWLAN_WAKEUP_EAP_IDENT_REQ);
888         if (wowlan->four_way_handshake)
889                 wowlan_config_cmd.wakeup_filter |=
890                         cpu_to_le32(IWL_WOWLAN_WAKEUP_4WAY_HANDSHAKE);
891         if (wowlan->n_patterns)
892                 wowlan_config_cmd.wakeup_filter |=
893                         cpu_to_le32(IWL_WOWLAN_WAKEUP_PATTERN_MATCH);
894
895         if (wowlan->rfkill_release)
896                 wowlan_config_cmd.wakeup_filter |=
897                         cpu_to_le32(IWL_WOWLAN_WAKEUP_RF_KILL_DEASSERT);
898
899         if (wowlan->tcp) {
900                 /*
901                  * Set the "link change" (really "link lost") flag as well
902                  * since that implies losing the TCP connection.
903                  */
904                 wowlan_config_cmd.wakeup_filter |=
905                         cpu_to_le32(IWL_WOWLAN_WAKEUP_REMOTE_LINK_LOSS |
906                                     IWL_WOWLAN_WAKEUP_REMOTE_SIGNATURE_TABLE |
907                                     IWL_WOWLAN_WAKEUP_REMOTE_WAKEUP_PACKET |
908                                     IWL_WOWLAN_WAKEUP_LINK_CHANGE);
909         }
910
911         iwl_mvm_cancel_scan(mvm);
912
913         iwl_trans_stop_device(mvm->trans);
914
915         /*
916          * Set the HW restart bit -- this is mostly true as we're
917          * going to load new firmware and reprogram that, though
918          * the reprogramming is going to be manual to avoid adding
919          * all the MACs that aren't support.
920          * We don't have to clear up everything though because the
921          * reprogramming is manual. When we resume, we'll actually
922          * go through a proper restart sequence again to switch
923          * back to the runtime firmware image.
924          */
925         set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
926
927         /* We reprogram keys and shouldn't allocate new key indices */
928         memset(mvm->fw_key_table, 0, sizeof(mvm->fw_key_table));
929
930         mvm->ptk_ivlen = 0;
931         mvm->ptk_icvlen = 0;
932         mvm->ptk_ivlen = 0;
933         mvm->ptk_icvlen = 0;
934
935         /*
936          * The D3 firmware still hardcodes the AP station ID for the
937          * BSS we're associated with as 0. As a result, we have to move
938          * the auxiliary station to ID 1 so the ID 0 remains free for
939          * the AP station for later.
940          * We set the sta_id to 1 here, and reset it to its previous
941          * value (that we stored above) later.
942          */
943         mvm->aux_sta.sta_id = 1;
944
945         ret = iwl_mvm_load_d3_fw(mvm);
946         if (ret)
947                 goto out;
948
949         ret = iwl_mvm_d3_reprogram(mvm, vif, ap_sta);
950         if (ret)
951                 goto out;
952
953         if (!iwlwifi_mod_params.sw_crypto) {
954                 /*
955                  * This needs to be unlocked due to lock ordering
956                  * constraints. Since we're in the suspend path
957                  * that isn't really a problem though.
958                  */
959                 mutex_unlock(&mvm->mutex);
960                 ieee80211_iter_keys(mvm->hw, vif,
961                                     iwl_mvm_wowlan_program_keys,
962                                     &key_data);
963                 mutex_lock(&mvm->mutex);
964                 if (key_data.error) {
965                         ret = -EIO;
966                         goto out;
967                 }
968
969                 if (key_data.use_rsc_tsc) {
970                         struct iwl_host_cmd rsc_tsc_cmd = {
971                                 .id = WOWLAN_TSC_RSC_PARAM,
972                                 .flags = CMD_SYNC,
973                                 .data[0] = key_data.rsc_tsc,
974                                 .dataflags[0] = IWL_HCMD_DFL_NOCOPY,
975                                 .len[0] = sizeof(*key_data.rsc_tsc),
976                         };
977
978                         ret = iwl_mvm_send_cmd(mvm, &rsc_tsc_cmd);
979                         if (ret)
980                                 goto out;
981                 }
982
983                 if (key_data.use_tkip) {
984                         ret = iwl_mvm_send_cmd_pdu(mvm,
985                                                    WOWLAN_TKIP_PARAM,
986                                                    CMD_SYNC, sizeof(tkip_cmd),
987                                                    &tkip_cmd);
988                         if (ret)
989                                 goto out;
990                 }
991
992                 if (mvmvif->rekey_data.valid) {
993                         memset(&kek_kck_cmd, 0, sizeof(kek_kck_cmd));
994                         memcpy(kek_kck_cmd.kck, mvmvif->rekey_data.kck,
995                                NL80211_KCK_LEN);
996                         kek_kck_cmd.kck_len = cpu_to_le16(NL80211_KCK_LEN);
997                         memcpy(kek_kck_cmd.kek, mvmvif->rekey_data.kek,
998                                NL80211_KEK_LEN);
999                         kek_kck_cmd.kek_len = cpu_to_le16(NL80211_KEK_LEN);
1000                         kek_kck_cmd.replay_ctr = mvmvif->rekey_data.replay_ctr;
1001
1002                         ret = iwl_mvm_send_cmd_pdu(mvm,
1003                                                    WOWLAN_KEK_KCK_MATERIAL,
1004                                                    CMD_SYNC,
1005                                                    sizeof(kek_kck_cmd),
1006                                                    &kek_kck_cmd);
1007                         if (ret)
1008                                 goto out;
1009                 }
1010         }
1011
1012         ret = iwl_mvm_send_cmd_pdu(mvm, WOWLAN_CONFIGURATION,
1013                                    CMD_SYNC, sizeof(wowlan_config_cmd),
1014                                    &wowlan_config_cmd);
1015         if (ret)
1016                 goto out;
1017
1018         ret = iwl_mvm_send_patterns(mvm, wowlan);
1019         if (ret)
1020                 goto out;
1021
1022         ret = iwl_mvm_send_proto_offload(mvm, vif);
1023         if (ret)
1024                 goto out;
1025
1026         ret = iwl_mvm_send_remote_wake_cfg(mvm, vif, wowlan->tcp);
1027         if (ret)
1028                 goto out;
1029
1030         ret = iwl_mvm_power_update_mode(mvm, vif);
1031         if (ret)
1032                 goto out;
1033
1034 #ifdef CONFIG_IWLWIFI_DEBUGFS
1035         if (mvm->d3_wake_sysassert)
1036                 d3_cfg_cmd_data.wakeup_flags |=
1037                         cpu_to_le32(IWL_WAKEUP_D3_CONFIG_FW_ERROR);
1038 #endif
1039
1040         /* must be last -- this switches firmware state */
1041         ret = iwl_mvm_send_cmd(mvm, &d3_cfg_cmd);
1042         if (ret)
1043                 goto out;
1044 #ifdef CONFIG_IWLWIFI_DEBUGFS
1045         len = le32_to_cpu(d3_cfg_cmd.resp_pkt->len_n_flags) &
1046                 FH_RSCSR_FRAME_SIZE_MSK;
1047         if (len >= sizeof(u32) * 2) {
1048                 mvm->d3_test_pme_ptr =
1049                         le32_to_cpup((__le32 *)d3_cfg_cmd.resp_pkt->data);
1050         } else if (test) {
1051                 /* in test mode we require the pointer */
1052                 ret = -EIO;
1053                 goto out;
1054         }
1055 #endif
1056         iwl_free_resp(&d3_cfg_cmd);
1057
1058         clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1059
1060         iwl_trans_d3_suspend(mvm->trans, test);
1061  out:
1062         mvm->aux_sta.sta_id = old_aux_sta_id;
1063         mvm_ap_sta->sta_id = old_ap_sta_id;
1064         mvmvif->ap_sta_id = old_ap_sta_id;
1065  out_noreset:
1066         kfree(key_data.rsc_tsc);
1067         if (ret < 0)
1068                 ieee80211_restart_hw(mvm->hw);
1069
1070         mutex_unlock(&mvm->mutex);
1071
1072         return ret;
1073 }
1074
1075 int iwl_mvm_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wowlan)
1076 {
1077         return __iwl_mvm_suspend(hw, wowlan, false);
1078 }
1079
1080 static void iwl_mvm_query_wakeup_reasons(struct iwl_mvm *mvm,
1081                                          struct ieee80211_vif *vif)
1082 {
1083         u32 base = mvm->error_event_table;
1084         struct error_table_start {
1085                 /* cf. struct iwl_error_event_table */
1086                 u32 valid;
1087                 u32 error_id;
1088         } err_info;
1089         struct cfg80211_wowlan_wakeup wakeup = {
1090                 .pattern_idx = -1,
1091         };
1092         struct cfg80211_wowlan_wakeup *wakeup_report = &wakeup;
1093         struct iwl_host_cmd cmd = {
1094                 .id = WOWLAN_GET_STATUSES,
1095                 .flags = CMD_SYNC | CMD_WANT_SKB,
1096         };
1097         struct iwl_wowlan_status *status;
1098         u32 reasons;
1099         int ret, len;
1100         struct sk_buff *pkt = NULL;
1101
1102         iwl_trans_read_mem_bytes(mvm->trans, base,
1103                                  &err_info, sizeof(err_info));
1104
1105         if (err_info.valid) {
1106                 IWL_INFO(mvm, "error table is valid (%d)\n",
1107                          err_info.valid);
1108                 if (err_info.error_id == RF_KILL_INDICATOR_FOR_WOWLAN) {
1109                         wakeup.rfkill_release = true;
1110                         ieee80211_report_wowlan_wakeup(vif, &wakeup,
1111                                                        GFP_KERNEL);
1112                 }
1113                 return;
1114         }
1115
1116         /* only for tracing for now */
1117         ret = iwl_mvm_send_cmd_pdu(mvm, OFFLOADS_QUERY_CMD, CMD_SYNC, 0, NULL);
1118         if (ret)
1119                 IWL_ERR(mvm, "failed to query offload statistics (%d)\n", ret);
1120
1121         ret = iwl_mvm_send_cmd(mvm, &cmd);
1122         if (ret) {
1123                 IWL_ERR(mvm, "failed to query status (%d)\n", ret);
1124                 return;
1125         }
1126
1127         /* RF-kill already asserted again... */
1128         if (!cmd.resp_pkt)
1129                 return;
1130
1131         len = le32_to_cpu(cmd.resp_pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK;
1132         if (len - sizeof(struct iwl_cmd_header) < sizeof(*status)) {
1133                 IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1134                 goto out;
1135         }
1136
1137         status = (void *)cmd.resp_pkt->data;
1138
1139         if (len - sizeof(struct iwl_cmd_header) !=
1140             sizeof(*status) +
1141             ALIGN(le32_to_cpu(status->wake_packet_bufsize), 4)) {
1142                 IWL_ERR(mvm, "Invalid WoWLAN status response!\n");
1143                 goto out;
1144         }
1145
1146         reasons = le32_to_cpu(status->wakeup_reasons);
1147
1148         if (reasons == IWL_WOWLAN_WAKEUP_BY_NON_WIRELESS) {
1149                 wakeup_report = NULL;
1150                 goto report;
1151         }
1152
1153         if (reasons & IWL_WOWLAN_WAKEUP_BY_MAGIC_PACKET)
1154                 wakeup.magic_pkt = true;
1155
1156         if (reasons & IWL_WOWLAN_WAKEUP_BY_PATTERN)
1157                 wakeup.pattern_idx =
1158                         le16_to_cpu(status->pattern_number);
1159
1160         if (reasons & (IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_MISSED_BEACON |
1161                        IWL_WOWLAN_WAKEUP_BY_DISCONNECTION_ON_DEAUTH))
1162                 wakeup.disconnect = true;
1163
1164         if (reasons & IWL_WOWLAN_WAKEUP_BY_GTK_REKEY_FAILURE)
1165                 wakeup.gtk_rekey_failure = true;
1166
1167         if (reasons & IWL_WOWLAN_WAKEUP_BY_RFKILL_DEASSERTED)
1168                 wakeup.rfkill_release = true;
1169
1170         if (reasons & IWL_WOWLAN_WAKEUP_BY_EAPOL_REQUEST)
1171                 wakeup.eap_identity_req = true;
1172
1173         if (reasons & IWL_WOWLAN_WAKEUP_BY_FOUR_WAY_HANDSHAKE)
1174                 wakeup.four_way_handshake = true;
1175
1176         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_LINK_LOSS)
1177                 wakeup.tcp_connlost = true;
1178
1179         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_SIGNATURE_TABLE)
1180                 wakeup.tcp_nomoretokens = true;
1181
1182         if (reasons & IWL_WOWLAN_WAKEUP_BY_REM_WAKE_WAKEUP_PACKET)
1183                 wakeup.tcp_match = true;
1184
1185         if (status->wake_packet_bufsize) {
1186                 int pktsize = le32_to_cpu(status->wake_packet_bufsize);
1187                 int pktlen = le32_to_cpu(status->wake_packet_length);
1188                 const u8 *pktdata = status->wake_packet;
1189                 struct ieee80211_hdr *hdr = (void *)pktdata;
1190                 int truncated = pktlen - pktsize;
1191
1192                 /* this would be a firmware bug */
1193                 if (WARN_ON_ONCE(truncated < 0))
1194                         truncated = 0;
1195
1196                 if (ieee80211_is_data(hdr->frame_control)) {
1197                         int hdrlen = ieee80211_hdrlen(hdr->frame_control);
1198                         int ivlen = 0, icvlen = 4; /* also FCS */
1199
1200                         pkt = alloc_skb(pktsize, GFP_KERNEL);
1201                         if (!pkt)
1202                                 goto report;
1203
1204                         memcpy(skb_put(pkt, hdrlen), pktdata, hdrlen);
1205                         pktdata += hdrlen;
1206                         pktsize -= hdrlen;
1207
1208                         if (ieee80211_has_protected(hdr->frame_control)) {
1209                                 if (is_multicast_ether_addr(hdr->addr1)) {
1210                                         ivlen = mvm->gtk_ivlen;
1211                                         icvlen += mvm->gtk_icvlen;
1212                                 } else {
1213                                         ivlen = mvm->ptk_ivlen;
1214                                         icvlen += mvm->ptk_icvlen;
1215                                 }
1216                         }
1217
1218                         /* if truncated, FCS/ICV is (partially) gone */
1219                         if (truncated >= icvlen) {
1220                                 icvlen = 0;
1221                                 truncated -= icvlen;
1222                         } else {
1223                                 icvlen -= truncated;
1224                                 truncated = 0;
1225                         }
1226
1227                         pktsize -= ivlen + icvlen;
1228                         pktdata += ivlen;
1229
1230                         memcpy(skb_put(pkt, pktsize), pktdata, pktsize);
1231
1232                         if (ieee80211_data_to_8023(pkt, vif->addr, vif->type))
1233                                 goto report;
1234                         wakeup.packet = pkt->data;
1235                         wakeup.packet_present_len = pkt->len;
1236                         wakeup.packet_len = pkt->len - truncated;
1237                         wakeup.packet_80211 = false;
1238                 } else {
1239                         int fcslen = 4;
1240
1241                         if (truncated >= 4) {
1242                                 truncated -= 4;
1243                                 fcslen = 0;
1244                         } else {
1245                                 fcslen -= truncated;
1246                                 truncated = 0;
1247                         }
1248                         pktsize -= fcslen;
1249                         wakeup.packet = status->wake_packet;
1250                         wakeup.packet_present_len = pktsize;
1251                         wakeup.packet_len = pktlen - truncated;
1252                         wakeup.packet_80211 = true;
1253                 }
1254         }
1255
1256  report:
1257         ieee80211_report_wowlan_wakeup(vif, wakeup_report, GFP_KERNEL);
1258         kfree_skb(pkt);
1259
1260  out:
1261         iwl_free_resp(&cmd);
1262 }
1263
1264 static void iwl_mvm_read_d3_sram(struct iwl_mvm *mvm)
1265 {
1266 #ifdef CONFIG_IWLWIFI_DEBUGFS
1267         const struct fw_img *img = &mvm->fw->img[IWL_UCODE_WOWLAN];
1268         u32 len = img->sec[IWL_UCODE_SECTION_DATA].len;
1269         u32 offs = img->sec[IWL_UCODE_SECTION_DATA].offset;
1270
1271         if (!mvm->store_d3_resume_sram)
1272                 return;
1273
1274         if (!mvm->d3_resume_sram) {
1275                 mvm->d3_resume_sram = kzalloc(len, GFP_KERNEL);
1276                 if (!mvm->d3_resume_sram)
1277                         return;
1278         }
1279
1280         iwl_trans_read_mem_bytes(mvm->trans, offs, mvm->d3_resume_sram, len);
1281 #endif
1282 }
1283
1284 static int __iwl_mvm_resume(struct iwl_mvm *mvm, bool test)
1285 {
1286         struct iwl_d3_iter_data resume_iter_data = {
1287                 .mvm = mvm,
1288         };
1289         struct ieee80211_vif *vif = NULL;
1290         int ret;
1291         enum iwl_d3_status d3_status;
1292
1293         mutex_lock(&mvm->mutex);
1294
1295         /* get the BSS vif pointer again */
1296         ieee80211_iterate_active_interfaces_atomic(
1297                 mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1298                 iwl_mvm_d3_iface_iterator, &resume_iter_data);
1299
1300         if (WARN_ON(resume_iter_data.error || !resume_iter_data.vif))
1301                 goto out_unlock;
1302
1303         vif = resume_iter_data.vif;
1304
1305         ret = iwl_trans_d3_resume(mvm->trans, &d3_status, test);
1306         if (ret)
1307                 goto out_unlock;
1308
1309         if (d3_status != IWL_D3_STATUS_ALIVE) {
1310                 IWL_INFO(mvm, "Device was reset during suspend\n");
1311                 goto out_unlock;
1312         }
1313
1314         /* query SRAM first in case we want event logging */
1315         iwl_mvm_read_d3_sram(mvm);
1316
1317         iwl_mvm_query_wakeup_reasons(mvm, vif);
1318
1319  out_unlock:
1320         mutex_unlock(&mvm->mutex);
1321
1322         if (!test && vif)
1323                 ieee80211_resume_disconnect(vif);
1324
1325         /* return 1 to reconfigure the device */
1326         set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1327         return 1;
1328 }
1329
1330 int iwl_mvm_resume(struct ieee80211_hw *hw)
1331 {
1332         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1333
1334         return __iwl_mvm_resume(mvm, false);
1335 }
1336
1337 void iwl_mvm_set_wakeup(struct ieee80211_hw *hw, bool enabled)
1338 {
1339         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1340
1341         device_set_wakeup_enable(mvm->trans->dev, enabled);
1342 }
1343
1344 #ifdef CONFIG_IWLWIFI_DEBUGFS
1345 static int iwl_mvm_d3_test_open(struct inode *inode, struct file *file)
1346 {
1347         struct iwl_mvm *mvm = inode->i_private;
1348         int err;
1349
1350         if (mvm->d3_test_active)
1351                 return -EBUSY;
1352
1353         file->private_data = inode->i_private;
1354
1355         ieee80211_stop_queues(mvm->hw);
1356         synchronize_net();
1357
1358         /* start pseudo D3 */
1359         rtnl_lock();
1360         err = __iwl_mvm_suspend(mvm->hw, mvm->hw->wiphy->wowlan_config, true);
1361         rtnl_unlock();
1362         if (err > 0)
1363                 err = -EINVAL;
1364         if (err) {
1365                 ieee80211_wake_queues(mvm->hw);
1366                 return err;
1367         }
1368         mvm->d3_test_active = true;
1369         return 0;
1370 }
1371
1372 static ssize_t iwl_mvm_d3_test_read(struct file *file, char __user *user_buf,
1373                                     size_t count, loff_t *ppos)
1374 {
1375         struct iwl_mvm *mvm = file->private_data;
1376         u32 pme_asserted;
1377
1378         while (true) {
1379                 pme_asserted = iwl_trans_read_mem32(mvm->trans,
1380                                                     mvm->d3_test_pme_ptr);
1381                 if (pme_asserted)
1382                         break;
1383                 if (msleep_interruptible(100))
1384                         break;
1385         }
1386
1387         return 0;
1388 }
1389
1390 static void iwl_mvm_d3_test_disconn_work_iter(void *_data, u8 *mac,
1391                                               struct ieee80211_vif *vif)
1392 {
1393         if (vif->type == NL80211_IFTYPE_STATION)
1394                 ieee80211_connection_loss(vif);
1395 }
1396
1397 static int iwl_mvm_d3_test_release(struct inode *inode, struct file *file)
1398 {
1399         struct iwl_mvm *mvm = inode->i_private;
1400         int remaining_time = 10;
1401
1402         mvm->d3_test_active = false;
1403         __iwl_mvm_resume(mvm, true);
1404         iwl_abort_notification_waits(&mvm->notif_wait);
1405         ieee80211_restart_hw(mvm->hw);
1406
1407         /* wait for restart and disconnect all interfaces */
1408         while (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) &&
1409                remaining_time > 0) {
1410                 remaining_time--;
1411                 msleep(1000);
1412         }
1413
1414         if (remaining_time == 0)
1415                 IWL_ERR(mvm, "Timed out waiting for HW restart to finish!\n");
1416
1417         ieee80211_iterate_active_interfaces_atomic(
1418                 mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1419                 iwl_mvm_d3_test_disconn_work_iter, NULL);
1420
1421         ieee80211_wake_queues(mvm->hw);
1422
1423         return 0;
1424 }
1425
1426 const struct file_operations iwl_dbgfs_d3_test_ops = {
1427         .llseek = no_llseek,
1428         .open = iwl_mvm_d3_test_open,
1429         .read = iwl_mvm_d3_test_read,
1430         .release = iwl_mvm_d3_test_release,
1431 };
1432 #endif