Merge tag 'for-5.3-rc8-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave...
[sfrench/cifs-2.6.git] / drivers / net / wireless / intel / iwlwifi / mvm / mac80211.c
1 /******************************************************************************
2  *
3  * This file is provided under a dual BSD/GPLv2 license.  When using or
4  * redistributing this file, you may do so under either license.
5  *
6  * GPL LICENSE SUMMARY
7  *
8  * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
9  * Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH
10  * Copyright(c) 2016 - 2017 Intel Deutschland GmbH
11  * Copyright(c) 2018 - 2019 Intel Corporation
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of version 2 of the GNU General Public License as
15  * published by the Free Software Foundation.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * The full GNU General Public License is included in this distribution
23  * in the file called COPYING.
24  *
25  * Contact Information:
26  *  Intel Linux Wireless <linuxwifi@intel.com>
27  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
28  *
29  * BSD LICENSE
30  *
31  * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
32  * Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH
33  * Copyright(c) 2016 - 2017 Intel Deutschland GmbH
34  * Copyright(c) 2018 - 2019 Intel Corporation
35  * All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  *
41  *  * Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  *  * Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in
45  *    the documentation and/or other materials provided with the
46  *    distribution.
47  *  * Neither the name Intel Corporation nor the names of its
48  *    contributors may be used to endorse or promote products derived
49  *    from this software without specific prior written permission.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
52  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
53  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
54  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
55  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
56  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
57  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
58  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
59  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
60  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
61  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62  *
63  *****************************************************************************/
64 #include <linux/kernel.h>
65 #include <linux/slab.h>
66 #include <linux/skbuff.h>
67 #include <linux/netdevice.h>
68 #include <linux/etherdevice.h>
69 #include <linux/ip.h>
70 #include <linux/if_arp.h>
71 #include <linux/time.h>
72 #include <net/mac80211.h>
73 #include <net/ieee80211_radiotap.h>
74 #include <net/tcp.h>
75
76 #include "iwl-op-mode.h"
77 #include "iwl-io.h"
78 #include "mvm.h"
79 #include "sta.h"
80 #include "time-event.h"
81 #include "iwl-eeprom-parse.h"
82 #include "iwl-phy-db.h"
83 #include "testmode.h"
84 #include "fw/error-dump.h"
85 #include "iwl-prph.h"
86 #include "iwl-nvm-parse.h"
87
88 static const struct ieee80211_iface_limit iwl_mvm_limits[] = {
89         {
90                 .max = 1,
91                 .types = BIT(NL80211_IFTYPE_STATION),
92         },
93         {
94                 .max = 1,
95                 .types = BIT(NL80211_IFTYPE_AP) |
96                         BIT(NL80211_IFTYPE_P2P_CLIENT) |
97                         BIT(NL80211_IFTYPE_P2P_GO),
98         },
99         {
100                 .max = 1,
101                 .types = BIT(NL80211_IFTYPE_P2P_DEVICE),
102         },
103 };
104
105 static const struct ieee80211_iface_combination iwl_mvm_iface_combinations[] = {
106         {
107                 .num_different_channels = 2,
108                 .max_interfaces = 3,
109                 .limits = iwl_mvm_limits,
110                 .n_limits = ARRAY_SIZE(iwl_mvm_limits),
111         },
112 };
113
114 #ifdef CONFIG_IWLWIFI_BCAST_FILTERING
115 /*
116  * Use the reserved field to indicate magic values.
117  * these values will only be used internally by the driver,
118  * and won't make it to the fw (reserved will be 0).
119  * BC_FILTER_MAGIC_IP - configure the val of this attribute to
120  *      be the vif's ip address. in case there is not a single
121  *      ip address (0, or more than 1), this attribute will
122  *      be skipped.
123  * BC_FILTER_MAGIC_MAC - set the val of this attribute to
124  *      the LSB bytes of the vif's mac address
125  */
126 enum {
127         BC_FILTER_MAGIC_NONE = 0,
128         BC_FILTER_MAGIC_IP,
129         BC_FILTER_MAGIC_MAC,
130 };
131
132 static const struct iwl_fw_bcast_filter iwl_mvm_default_bcast_filters[] = {
133         {
134                 /* arp */
135                 .discard = 0,
136                 .frame_type = BCAST_FILTER_FRAME_TYPE_ALL,
137                 .attrs = {
138                         {
139                                 /* frame type - arp, hw type - ethernet */
140                                 .offset_type =
141                                         BCAST_FILTER_OFFSET_PAYLOAD_START,
142                                 .offset = sizeof(rfc1042_header),
143                                 .val = cpu_to_be32(0x08060001),
144                                 .mask = cpu_to_be32(0xffffffff),
145                         },
146                         {
147                                 /* arp dest ip */
148                                 .offset_type =
149                                         BCAST_FILTER_OFFSET_PAYLOAD_START,
150                                 .offset = sizeof(rfc1042_header) + 2 +
151                                           sizeof(struct arphdr) +
152                                           ETH_ALEN + sizeof(__be32) +
153                                           ETH_ALEN,
154                                 .mask = cpu_to_be32(0xffffffff),
155                                 /* mark it as special field */
156                                 .reserved1 = cpu_to_le16(BC_FILTER_MAGIC_IP),
157                         },
158                 },
159         },
160         {
161                 /* dhcp offer bcast */
162                 .discard = 0,
163                 .frame_type = BCAST_FILTER_FRAME_TYPE_IPV4,
164                 .attrs = {
165                         {
166                                 /* udp dest port - 68 (bootp client)*/
167                                 .offset_type = BCAST_FILTER_OFFSET_IP_END,
168                                 .offset = offsetof(struct udphdr, dest),
169                                 .val = cpu_to_be32(0x00440000),
170                                 .mask = cpu_to_be32(0xffff0000),
171                         },
172                         {
173                                 /* dhcp - lsb bytes of client hw address */
174                                 .offset_type = BCAST_FILTER_OFFSET_IP_END,
175                                 .offset = 38,
176                                 .mask = cpu_to_be32(0xffffffff),
177                                 /* mark it as special field */
178                                 .reserved1 = cpu_to_le16(BC_FILTER_MAGIC_MAC),
179                         },
180                 },
181         },
182         /* last filter must be empty */
183         {},
184 };
185 #endif
186
187 static const struct cfg80211_pmsr_capabilities iwl_mvm_pmsr_capa = {
188         .max_peers = IWL_MVM_TOF_MAX_APS,
189         .report_ap_tsf = 1,
190         .randomize_mac_addr = 1,
191
192         .ftm = {
193                 .supported = 1,
194                 .asap = 1,
195                 .non_asap = 1,
196                 .request_lci = 1,
197                 .request_civicloc = 1,
198                 .max_bursts_exponent = -1, /* all supported */
199                 .max_ftms_per_burst = 0, /* no limits */
200                 .bandwidths = BIT(NL80211_CHAN_WIDTH_20_NOHT) |
201                               BIT(NL80211_CHAN_WIDTH_20) |
202                               BIT(NL80211_CHAN_WIDTH_40) |
203                               BIT(NL80211_CHAN_WIDTH_80),
204                 .preambles = BIT(NL80211_PREAMBLE_LEGACY) |
205                              BIT(NL80211_PREAMBLE_HT) |
206                              BIT(NL80211_PREAMBLE_VHT),
207         },
208 };
209
210 static int __iwl_mvm_mac_set_key(struct ieee80211_hw *hw,
211                                  enum set_key_cmd cmd,
212                                  struct ieee80211_vif *vif,
213                                  struct ieee80211_sta *sta,
214                                  struct ieee80211_key_conf *key);
215
216 void iwl_mvm_ref(struct iwl_mvm *mvm, enum iwl_mvm_ref_type ref_type)
217 {
218         if (!iwl_mvm_is_d0i3_supported(mvm))
219                 return;
220
221         IWL_DEBUG_RPM(mvm, "Take mvm reference - type %d\n", ref_type);
222         spin_lock_bh(&mvm->refs_lock);
223         mvm->refs[ref_type]++;
224         spin_unlock_bh(&mvm->refs_lock);
225         iwl_trans_ref(mvm->trans);
226 }
227
228 void iwl_mvm_unref(struct iwl_mvm *mvm, enum iwl_mvm_ref_type ref_type)
229 {
230         if (!iwl_mvm_is_d0i3_supported(mvm))
231                 return;
232
233         IWL_DEBUG_RPM(mvm, "Leave mvm reference - type %d\n", ref_type);
234         spin_lock_bh(&mvm->refs_lock);
235         if (WARN_ON(!mvm->refs[ref_type])) {
236                 spin_unlock_bh(&mvm->refs_lock);
237                 return;
238         }
239         mvm->refs[ref_type]--;
240         spin_unlock_bh(&mvm->refs_lock);
241         iwl_trans_unref(mvm->trans);
242 }
243
244 static void iwl_mvm_unref_all_except(struct iwl_mvm *mvm,
245                                      enum iwl_mvm_ref_type except_ref)
246 {
247         int i, j;
248
249         if (!iwl_mvm_is_d0i3_supported(mvm))
250                 return;
251
252         spin_lock_bh(&mvm->refs_lock);
253         for (i = 0; i < IWL_MVM_REF_COUNT; i++) {
254                 if (except_ref == i || !mvm->refs[i])
255                         continue;
256
257                 IWL_DEBUG_RPM(mvm, "Cleanup: remove mvm ref type %d (%d)\n",
258                               i, mvm->refs[i]);
259                 for (j = 0; j < mvm->refs[i]; j++)
260                         iwl_trans_unref(mvm->trans);
261                 mvm->refs[i] = 0;
262         }
263         spin_unlock_bh(&mvm->refs_lock);
264 }
265
266 bool iwl_mvm_ref_taken(struct iwl_mvm *mvm)
267 {
268         int i;
269         bool taken = false;
270
271         if (!iwl_mvm_is_d0i3_supported(mvm))
272                 return true;
273
274         spin_lock_bh(&mvm->refs_lock);
275         for (i = 0; i < IWL_MVM_REF_COUNT; i++) {
276                 if (mvm->refs[i]) {
277                         taken = true;
278                         break;
279                 }
280         }
281         spin_unlock_bh(&mvm->refs_lock);
282
283         return taken;
284 }
285
286 int iwl_mvm_ref_sync(struct iwl_mvm *mvm, enum iwl_mvm_ref_type ref_type)
287 {
288         iwl_mvm_ref(mvm, ref_type);
289
290         if (!wait_event_timeout(mvm->d0i3_exit_waitq,
291                                 !test_bit(IWL_MVM_STATUS_IN_D0I3, &mvm->status),
292                                 HZ)) {
293                 WARN_ON_ONCE(1);
294                 iwl_mvm_unref(mvm, ref_type);
295                 return -EIO;
296         }
297
298         return 0;
299 }
300
301 static void iwl_mvm_reset_phy_ctxts(struct iwl_mvm *mvm)
302 {
303         int i;
304
305         memset(mvm->phy_ctxts, 0, sizeof(mvm->phy_ctxts));
306         for (i = 0; i < NUM_PHY_CTX; i++) {
307                 mvm->phy_ctxts[i].id = i;
308                 mvm->phy_ctxts[i].ref = 0;
309         }
310 }
311
312 struct ieee80211_regdomain *iwl_mvm_get_regdomain(struct wiphy *wiphy,
313                                                   const char *alpha2,
314                                                   enum iwl_mcc_source src_id,
315                                                   bool *changed)
316 {
317         struct ieee80211_regdomain *regd = NULL;
318         struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
319         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
320         struct iwl_mcc_update_resp *resp;
321
322         IWL_DEBUG_LAR(mvm, "Getting regdomain data for %s from FW\n", alpha2);
323
324         lockdep_assert_held(&mvm->mutex);
325
326         resp = iwl_mvm_update_mcc(mvm, alpha2, src_id);
327         if (IS_ERR_OR_NULL(resp)) {
328                 IWL_DEBUG_LAR(mvm, "Could not get update from FW %d\n",
329                               PTR_ERR_OR_ZERO(resp));
330                 goto out;
331         }
332
333         if (changed) {
334                 u32 status = le32_to_cpu(resp->status);
335
336                 *changed = (status == MCC_RESP_NEW_CHAN_PROFILE ||
337                             status == MCC_RESP_ILLEGAL);
338         }
339
340         regd = iwl_parse_nvm_mcc_info(mvm->trans->dev, mvm->cfg,
341                                       __le32_to_cpu(resp->n_channels),
342                                       resp->channels,
343                                       __le16_to_cpu(resp->mcc),
344                                       __le16_to_cpu(resp->geo_info));
345         /* Store the return source id */
346         src_id = resp->source_id;
347         kfree(resp);
348         if (IS_ERR_OR_NULL(regd)) {
349                 IWL_DEBUG_LAR(mvm, "Could not get parse update from FW %d\n",
350                               PTR_ERR_OR_ZERO(regd));
351                 goto out;
352         }
353
354         IWL_DEBUG_LAR(mvm, "setting alpha2 from FW to %s (0x%x, 0x%x) src=%d\n",
355                       regd->alpha2, regd->alpha2[0], regd->alpha2[1], src_id);
356         mvm->lar_regdom_set = true;
357         mvm->mcc_src = src_id;
358
359 out:
360         return regd;
361 }
362
363 void iwl_mvm_update_changed_regdom(struct iwl_mvm *mvm)
364 {
365         bool changed;
366         struct ieee80211_regdomain *regd;
367
368         if (!iwl_mvm_is_lar_supported(mvm))
369                 return;
370
371         regd = iwl_mvm_get_current_regdomain(mvm, &changed);
372         if (!IS_ERR_OR_NULL(regd)) {
373                 /* only update the regulatory core if changed */
374                 if (changed)
375                         regulatory_set_wiphy_regd(mvm->hw->wiphy, regd);
376
377                 kfree(regd);
378         }
379 }
380
381 struct ieee80211_regdomain *iwl_mvm_get_current_regdomain(struct iwl_mvm *mvm,
382                                                           bool *changed)
383 {
384         return iwl_mvm_get_regdomain(mvm->hw->wiphy, "ZZ",
385                                      iwl_mvm_is_wifi_mcc_supported(mvm) ?
386                                      MCC_SOURCE_GET_CURRENT :
387                                      MCC_SOURCE_OLD_FW, changed);
388 }
389
390 int iwl_mvm_init_fw_regd(struct iwl_mvm *mvm)
391 {
392         enum iwl_mcc_source used_src;
393         struct ieee80211_regdomain *regd;
394         int ret;
395         bool changed;
396         const struct ieee80211_regdomain *r =
397                         rtnl_dereference(mvm->hw->wiphy->regd);
398
399         if (!r)
400                 return -ENOENT;
401
402         /* save the last source in case we overwrite it below */
403         used_src = mvm->mcc_src;
404         if (iwl_mvm_is_wifi_mcc_supported(mvm)) {
405                 /* Notify the firmware we support wifi location updates */
406                 regd = iwl_mvm_get_current_regdomain(mvm, NULL);
407                 if (!IS_ERR_OR_NULL(regd))
408                         kfree(regd);
409         }
410
411         /* Now set our last stored MCC and source */
412         regd = iwl_mvm_get_regdomain(mvm->hw->wiphy, r->alpha2, used_src,
413                                      &changed);
414         if (IS_ERR_OR_NULL(regd))
415                 return -EIO;
416
417         /* update cfg80211 if the regdomain was changed */
418         if (changed)
419                 ret = regulatory_set_wiphy_regd_sync_rtnl(mvm->hw->wiphy, regd);
420         else
421                 ret = 0;
422
423         kfree(regd);
424         return ret;
425 }
426
427 const static u8 he_if_types_ext_capa_sta[] = {
428          [0] = WLAN_EXT_CAPA1_EXT_CHANNEL_SWITCHING,
429          [2] = WLAN_EXT_CAPA3_MULTI_BSSID_SUPPORT,
430          [7] = WLAN_EXT_CAPA8_OPMODE_NOTIF,
431          [9] = WLAN_EXT_CAPA10_TWT_REQUESTER_SUPPORT,
432 };
433
434 const static struct wiphy_iftype_ext_capab he_iftypes_ext_capa[] = {
435         {
436                 .iftype = NL80211_IFTYPE_STATION,
437                 .extended_capabilities = he_if_types_ext_capa_sta,
438                 .extended_capabilities_mask = he_if_types_ext_capa_sta,
439                 .extended_capabilities_len = sizeof(he_if_types_ext_capa_sta),
440         },
441 };
442
443 int iwl_mvm_mac_setup_register(struct iwl_mvm *mvm)
444 {
445         struct ieee80211_hw *hw = mvm->hw;
446         int num_mac, ret, i;
447         static const u32 mvm_ciphers[] = {
448                 WLAN_CIPHER_SUITE_WEP40,
449                 WLAN_CIPHER_SUITE_WEP104,
450                 WLAN_CIPHER_SUITE_TKIP,
451                 WLAN_CIPHER_SUITE_CCMP,
452         };
453 #ifdef CONFIG_PM_SLEEP
454         bool unified = fw_has_capa(&mvm->fw->ucode_capa,
455                                    IWL_UCODE_TLV_CAPA_CNSLDTD_D3_D0_IMG);
456 #endif
457
458         /* Tell mac80211 our characteristics */
459         ieee80211_hw_set(hw, SIGNAL_DBM);
460         ieee80211_hw_set(hw, SPECTRUM_MGMT);
461         ieee80211_hw_set(hw, REPORTS_TX_ACK_STATUS);
462         ieee80211_hw_set(hw, WANT_MONITOR_VIF);
463         ieee80211_hw_set(hw, SUPPORTS_PS);
464         ieee80211_hw_set(hw, SUPPORTS_DYNAMIC_PS);
465         ieee80211_hw_set(hw, AMPDU_AGGREGATION);
466         ieee80211_hw_set(hw, TIMING_BEACON_ONLY);
467         ieee80211_hw_set(hw, CONNECTION_MONITOR);
468         ieee80211_hw_set(hw, CHANCTX_STA_CSA);
469         ieee80211_hw_set(hw, SUPPORT_FAST_XMIT);
470         ieee80211_hw_set(hw, SUPPORTS_CLONED_SKBS);
471         ieee80211_hw_set(hw, SUPPORTS_AMSDU_IN_AMPDU);
472         ieee80211_hw_set(hw, NEEDS_UNIQUE_STA_ADDR);
473         ieee80211_hw_set(hw, DEAUTH_NEED_MGD_TX_PREP);
474         ieee80211_hw_set(hw, SUPPORTS_VHT_EXT_NSS_BW);
475         ieee80211_hw_set(hw, BUFF_MMPDU_TXQ);
476         ieee80211_hw_set(hw, STA_MMPDU_TXQ);
477         /*
478          * On older devices, enabling TX A-MSDU occasionally leads to
479          * something getting messed up, the command read from the FIFO
480          * gets out of sync and isn't a TX command, so that we have an
481          * assert EDC.
482          *
483          * It's not clear where the bug is, but since we didn't used to
484          * support A-MSDU until moving the mac80211 iTXQs, just leave it
485          * for older devices. We also don't see this issue on any newer
486          * devices.
487          */
488         if (mvm->cfg->device_family >= IWL_DEVICE_FAMILY_9000)
489                 ieee80211_hw_set(hw, TX_AMSDU);
490         ieee80211_hw_set(hw, TX_FRAG_LIST);
491
492         if (iwl_mvm_has_tlc_offload(mvm)) {
493                 ieee80211_hw_set(hw, TX_AMPDU_SETUP_IN_HW);
494                 ieee80211_hw_set(hw, HAS_RATE_CONTROL);
495         }
496
497         if (iwl_mvm_has_new_rx_api(mvm))
498                 ieee80211_hw_set(hw, SUPPORTS_REORDERING_BUFFER);
499
500         if (fw_has_capa(&mvm->fw->ucode_capa,
501                         IWL_UCODE_TLV_CAPA_STA_PM_NOTIF)) {
502                 ieee80211_hw_set(hw, AP_LINK_PS);
503         } else if (WARN_ON(iwl_mvm_has_new_tx_api(mvm))) {
504                 /*
505                  * we absolutely need this for the new TX API since that comes
506                  * with many more queues than the current code can deal with
507                  * for station powersave
508                  */
509                 return -EINVAL;
510         }
511
512         if (mvm->trans->num_rx_queues > 1)
513                 ieee80211_hw_set(hw, USES_RSS);
514
515         if (mvm->trans->max_skb_frags)
516                 hw->netdev_features = NETIF_F_HIGHDMA | NETIF_F_SG;
517
518         hw->queues = IEEE80211_MAX_QUEUES;
519         hw->offchannel_tx_hw_queue = IWL_MVM_OFFCHANNEL_QUEUE;
520         hw->radiotap_mcs_details |= IEEE80211_RADIOTAP_MCS_HAVE_FEC |
521                                     IEEE80211_RADIOTAP_MCS_HAVE_STBC;
522         hw->radiotap_vht_details |= IEEE80211_RADIOTAP_VHT_KNOWN_STBC |
523                 IEEE80211_RADIOTAP_VHT_KNOWN_BEAMFORMED;
524
525         hw->radiotap_timestamp.units_pos =
526                 IEEE80211_RADIOTAP_TIMESTAMP_UNIT_US |
527                 IEEE80211_RADIOTAP_TIMESTAMP_SPOS_PLCP_SIG_ACQ;
528         /* this is the case for CCK frames, it's better (only 8) for OFDM */
529         hw->radiotap_timestamp.accuracy = 22;
530
531         if (!iwl_mvm_has_tlc_offload(mvm))
532                 hw->rate_control_algorithm = RS_NAME;
533
534         hw->uapsd_queues = IWL_MVM_UAPSD_QUEUES;
535         hw->uapsd_max_sp_len = IWL_UAPSD_MAX_SP;
536         hw->max_tx_fragments = mvm->trans->max_skb_frags;
537
538         BUILD_BUG_ON(ARRAY_SIZE(mvm->ciphers) < ARRAY_SIZE(mvm_ciphers) + 6);
539         memcpy(mvm->ciphers, mvm_ciphers, sizeof(mvm_ciphers));
540         hw->wiphy->n_cipher_suites = ARRAY_SIZE(mvm_ciphers);
541         hw->wiphy->cipher_suites = mvm->ciphers;
542
543         if (iwl_mvm_has_new_rx_api(mvm)) {
544                 mvm->ciphers[hw->wiphy->n_cipher_suites] =
545                         WLAN_CIPHER_SUITE_GCMP;
546                 hw->wiphy->n_cipher_suites++;
547                 mvm->ciphers[hw->wiphy->n_cipher_suites] =
548                         WLAN_CIPHER_SUITE_GCMP_256;
549                 hw->wiphy->n_cipher_suites++;
550         }
551
552         /* Enable 11w if software crypto is not enabled (as the
553          * firmware will interpret some mgmt packets, so enabling it
554          * with software crypto isn't safe).
555          */
556         if (!iwlwifi_mod_params.swcrypto) {
557                 ieee80211_hw_set(hw, MFP_CAPABLE);
558                 mvm->ciphers[hw->wiphy->n_cipher_suites] =
559                         WLAN_CIPHER_SUITE_AES_CMAC;
560                 hw->wiphy->n_cipher_suites++;
561                 if (iwl_mvm_has_new_rx_api(mvm)) {
562                         mvm->ciphers[hw->wiphy->n_cipher_suites] =
563                                 WLAN_CIPHER_SUITE_BIP_GMAC_128;
564                         hw->wiphy->n_cipher_suites++;
565                         mvm->ciphers[hw->wiphy->n_cipher_suites] =
566                                 WLAN_CIPHER_SUITE_BIP_GMAC_256;
567                         hw->wiphy->n_cipher_suites++;
568                 }
569         }
570
571         /* currently FW API supports only one optional cipher scheme */
572         if (mvm->fw->cs[0].cipher) {
573                 const struct iwl_fw_cipher_scheme *fwcs = &mvm->fw->cs[0];
574                 struct ieee80211_cipher_scheme *cs = &mvm->cs[0];
575
576                 mvm->hw->n_cipher_schemes = 1;
577
578                 cs->cipher = le32_to_cpu(fwcs->cipher);
579                 cs->iftype = BIT(NL80211_IFTYPE_STATION);
580                 cs->hdr_len = fwcs->hdr_len;
581                 cs->pn_len = fwcs->pn_len;
582                 cs->pn_off = fwcs->pn_off;
583                 cs->key_idx_off = fwcs->key_idx_off;
584                 cs->key_idx_mask = fwcs->key_idx_mask;
585                 cs->key_idx_shift = fwcs->key_idx_shift;
586                 cs->mic_len = fwcs->mic_len;
587
588                 mvm->hw->cipher_schemes = mvm->cs;
589                 mvm->ciphers[hw->wiphy->n_cipher_suites] = cs->cipher;
590                 hw->wiphy->n_cipher_suites++;
591         }
592
593         if (fw_has_capa(&mvm->fw->ucode_capa,
594                         IWL_UCODE_TLV_CAPA_FTM_CALIBRATED)) {
595                 wiphy_ext_feature_set(hw->wiphy,
596                                       NL80211_EXT_FEATURE_ENABLE_FTM_RESPONDER);
597                 hw->wiphy->pmsr_capa = &iwl_mvm_pmsr_capa;
598         }
599
600         ieee80211_hw_set(hw, SINGLE_SCAN_ON_ALL_BANDS);
601         hw->wiphy->features |=
602                 NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR |
603                 NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR |
604                 NL80211_FEATURE_ND_RANDOM_MAC_ADDR;
605
606         hw->sta_data_size = sizeof(struct iwl_mvm_sta);
607         hw->vif_data_size = sizeof(struct iwl_mvm_vif);
608         hw->chanctx_data_size = sizeof(u16);
609         hw->txq_data_size = sizeof(struct iwl_mvm_txq);
610
611         hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
612                 BIT(NL80211_IFTYPE_P2P_CLIENT) |
613                 BIT(NL80211_IFTYPE_AP) |
614                 BIT(NL80211_IFTYPE_P2P_GO) |
615                 BIT(NL80211_IFTYPE_P2P_DEVICE) |
616                 BIT(NL80211_IFTYPE_ADHOC);
617
618         hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN;
619         wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_VHT_IBSS);
620         hw->wiphy->features |= NL80211_FEATURE_HT_IBSS;
621
622         hw->wiphy->regulatory_flags |= REGULATORY_ENABLE_RELAX_NO_IR;
623         if (iwl_mvm_is_lar_supported(mvm))
624                 hw->wiphy->regulatory_flags |= REGULATORY_WIPHY_SELF_MANAGED;
625         else
626                 hw->wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG |
627                                                REGULATORY_DISABLE_BEACON_HINTS;
628
629         hw->wiphy->flags |= WIPHY_FLAG_AP_UAPSD;
630         hw->wiphy->flags |= WIPHY_FLAG_HAS_CHANNEL_SWITCH;
631
632         hw->wiphy->iface_combinations = iwl_mvm_iface_combinations;
633         hw->wiphy->n_iface_combinations =
634                 ARRAY_SIZE(iwl_mvm_iface_combinations);
635
636         hw->wiphy->max_remain_on_channel_duration = 10000;
637         hw->max_listen_interval = IWL_CONN_MAX_LISTEN_INTERVAL;
638
639         /* Extract MAC address */
640         memcpy(mvm->addresses[0].addr, mvm->nvm_data->hw_addr, ETH_ALEN);
641         hw->wiphy->addresses = mvm->addresses;
642         hw->wiphy->n_addresses = 1;
643
644         /* Extract additional MAC addresses if available */
645         num_mac = (mvm->nvm_data->n_hw_addrs > 1) ?
646                 min(IWL_MVM_MAX_ADDRESSES, mvm->nvm_data->n_hw_addrs) : 1;
647
648         for (i = 1; i < num_mac; i++) {
649                 memcpy(mvm->addresses[i].addr, mvm->addresses[i-1].addr,
650                        ETH_ALEN);
651                 mvm->addresses[i].addr[5]++;
652                 hw->wiphy->n_addresses++;
653         }
654
655         iwl_mvm_reset_phy_ctxts(mvm);
656
657         hw->wiphy->max_scan_ie_len = iwl_mvm_max_scan_ie_len(mvm);
658
659         hw->wiphy->max_scan_ssids = PROBE_OPTION_MAX;
660
661         BUILD_BUG_ON(IWL_MVM_SCAN_STOPPING_MASK & IWL_MVM_SCAN_MASK);
662         BUILD_BUG_ON(IWL_MVM_MAX_UMAC_SCANS > HWEIGHT32(IWL_MVM_SCAN_MASK) ||
663                      IWL_MVM_MAX_LMAC_SCANS > HWEIGHT32(IWL_MVM_SCAN_MASK));
664
665         if (fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_UMAC_SCAN))
666                 mvm->max_scans = IWL_MVM_MAX_UMAC_SCANS;
667         else
668                 mvm->max_scans = IWL_MVM_MAX_LMAC_SCANS;
669
670         if (mvm->nvm_data->bands[NL80211_BAND_2GHZ].n_channels)
671                 hw->wiphy->bands[NL80211_BAND_2GHZ] =
672                         &mvm->nvm_data->bands[NL80211_BAND_2GHZ];
673         if (mvm->nvm_data->bands[NL80211_BAND_5GHZ].n_channels) {
674                 hw->wiphy->bands[NL80211_BAND_5GHZ] =
675                         &mvm->nvm_data->bands[NL80211_BAND_5GHZ];
676
677                 if (fw_has_capa(&mvm->fw->ucode_capa,
678                                 IWL_UCODE_TLV_CAPA_BEAMFORMER) &&
679                     fw_has_api(&mvm->fw->ucode_capa,
680                                IWL_UCODE_TLV_API_LQ_SS_PARAMS))
681                         hw->wiphy->bands[NL80211_BAND_5GHZ]->vht_cap.cap |=
682                                 IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE;
683         }
684
685         hw->wiphy->hw_version = mvm->trans->hw_id;
686
687         if (iwlmvm_mod_params.power_scheme != IWL_POWER_SCHEME_CAM)
688                 hw->wiphy->flags |= WIPHY_FLAG_PS_ON_BY_DEFAULT;
689         else
690                 hw->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
691
692         hw->wiphy->max_sched_scan_reqs = 1;
693         hw->wiphy->max_sched_scan_ssids = PROBE_OPTION_MAX;
694         hw->wiphy->max_match_sets = IWL_SCAN_MAX_PROFILES;
695         /* we create the 802.11 header and zero length SSID IE. */
696         hw->wiphy->max_sched_scan_ie_len =
697                 SCAN_OFFLOAD_PROBE_REQ_SIZE - 24 - 2;
698         hw->wiphy->max_sched_scan_plans = IWL_MAX_SCHED_SCAN_PLANS;
699         hw->wiphy->max_sched_scan_plan_interval = U16_MAX;
700
701         /*
702          * the firmware uses u8 for num of iterations, but 0xff is saved for
703          * infinite loop, so the maximum number of iterations is actually 254.
704          */
705         hw->wiphy->max_sched_scan_plan_iterations = 254;
706
707         hw->wiphy->features |= NL80211_FEATURE_P2P_GO_CTWIN |
708                                NL80211_FEATURE_LOW_PRIORITY_SCAN |
709                                NL80211_FEATURE_P2P_GO_OPPPS |
710                                NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE |
711                                NL80211_FEATURE_DYNAMIC_SMPS |
712                                NL80211_FEATURE_STATIC_SMPS |
713                                NL80211_FEATURE_SUPPORTS_WMM_ADMISSION;
714
715         if (fw_has_capa(&mvm->fw->ucode_capa,
716                         IWL_UCODE_TLV_CAPA_TXPOWER_INSERTION_SUPPORT))
717                 hw->wiphy->features |= NL80211_FEATURE_TX_POWER_INSERTION;
718         if (fw_has_capa(&mvm->fw->ucode_capa,
719                         IWL_UCODE_TLV_CAPA_QUIET_PERIOD_SUPPORT))
720                 hw->wiphy->features |= NL80211_FEATURE_QUIET;
721
722         if (fw_has_capa(&mvm->fw->ucode_capa,
723                         IWL_UCODE_TLV_CAPA_DS_PARAM_SET_IE_SUPPORT))
724                 hw->wiphy->features |=
725                         NL80211_FEATURE_DS_PARAM_SET_IE_IN_PROBES;
726
727         if (fw_has_capa(&mvm->fw->ucode_capa,
728                         IWL_UCODE_TLV_CAPA_WFA_TPC_REP_IE_SUPPORT))
729                 hw->wiphy->features |= NL80211_FEATURE_WFA_TPC_IE_IN_PROBES;
730
731         if (fw_has_api(&mvm->fw->ucode_capa,
732                        IWL_UCODE_TLV_API_SCAN_TSF_REPORT)) {
733                 wiphy_ext_feature_set(hw->wiphy,
734                                       NL80211_EXT_FEATURE_SCAN_START_TIME);
735                 wiphy_ext_feature_set(hw->wiphy,
736                                       NL80211_EXT_FEATURE_BSS_PARENT_TSF);
737                 wiphy_ext_feature_set(hw->wiphy,
738                                       NL80211_EXT_FEATURE_SET_SCAN_DWELL);
739         }
740
741         if (iwl_mvm_is_oce_supported(mvm)) {
742                 wiphy_ext_feature_set(hw->wiphy,
743                         NL80211_EXT_FEATURE_ACCEPT_BCAST_PROBE_RESP);
744                 wiphy_ext_feature_set(hw->wiphy,
745                         NL80211_EXT_FEATURE_FILS_MAX_CHANNEL_TIME);
746                 wiphy_ext_feature_set(hw->wiphy,
747                         NL80211_EXT_FEATURE_OCE_PROBE_REQ_DEFERRAL_SUPPRESSION);
748                 wiphy_ext_feature_set(hw->wiphy,
749                         NL80211_EXT_FEATURE_OCE_PROBE_REQ_HIGH_TX_RATE);
750         }
751
752         if (mvm->nvm_data->sku_cap_11ax_enable &&
753             !iwlwifi_mod_params.disable_11ax) {
754                 hw->wiphy->iftype_ext_capab = he_iftypes_ext_capa;
755                 hw->wiphy->num_iftype_ext_capab =
756                         ARRAY_SIZE(he_iftypes_ext_capa);
757
758                 ieee80211_hw_set(hw, SUPPORTS_MULTI_BSSID);
759                 ieee80211_hw_set(hw, SUPPORTS_ONLY_HE_MULTI_BSSID);
760         }
761
762         mvm->rts_threshold = IEEE80211_MAX_RTS_THRESHOLD;
763
764 #ifdef CONFIG_PM_SLEEP
765         if (iwl_mvm_is_d0i3_supported(mvm) &&
766             device_can_wakeup(mvm->trans->dev)) {
767                 mvm->wowlan.flags = WIPHY_WOWLAN_ANY;
768                 hw->wiphy->wowlan = &mvm->wowlan;
769         }
770
771         if ((unified || mvm->fw->img[IWL_UCODE_WOWLAN].num_sec) &&
772             mvm->trans->ops->d3_suspend &&
773             mvm->trans->ops->d3_resume &&
774             device_can_wakeup(mvm->trans->dev)) {
775                 mvm->wowlan.flags |= WIPHY_WOWLAN_MAGIC_PKT |
776                                      WIPHY_WOWLAN_DISCONNECT |
777                                      WIPHY_WOWLAN_EAP_IDENTITY_REQ |
778                                      WIPHY_WOWLAN_RFKILL_RELEASE |
779                                      WIPHY_WOWLAN_NET_DETECT;
780                 if (!iwlwifi_mod_params.swcrypto)
781                         mvm->wowlan.flags |= WIPHY_WOWLAN_SUPPORTS_GTK_REKEY |
782                                              WIPHY_WOWLAN_GTK_REKEY_FAILURE |
783                                              WIPHY_WOWLAN_4WAY_HANDSHAKE;
784
785                 mvm->wowlan.n_patterns = IWL_WOWLAN_MAX_PATTERNS;
786                 mvm->wowlan.pattern_min_len = IWL_WOWLAN_MIN_PATTERN_LEN;
787                 mvm->wowlan.pattern_max_len = IWL_WOWLAN_MAX_PATTERN_LEN;
788                 mvm->wowlan.max_nd_match_sets = IWL_SCAN_MAX_PROFILES;
789                 hw->wiphy->wowlan = &mvm->wowlan;
790         }
791 #endif
792
793 #ifdef CONFIG_IWLWIFI_BCAST_FILTERING
794         /* assign default bcast filtering configuration */
795         mvm->bcast_filters = iwl_mvm_default_bcast_filters;
796 #endif
797
798         ret = iwl_mvm_leds_init(mvm);
799         if (ret)
800                 return ret;
801
802         if (fw_has_capa(&mvm->fw->ucode_capa,
803                         IWL_UCODE_TLV_CAPA_TDLS_SUPPORT)) {
804                 IWL_DEBUG_TDLS(mvm, "TDLS supported\n");
805                 hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS;
806                 ieee80211_hw_set(hw, TDLS_WIDER_BW);
807         }
808
809         if (fw_has_capa(&mvm->fw->ucode_capa,
810                         IWL_UCODE_TLV_CAPA_TDLS_CHANNEL_SWITCH)) {
811                 IWL_DEBUG_TDLS(mvm, "TDLS channel switch supported\n");
812                 hw->wiphy->features |= NL80211_FEATURE_TDLS_CHANNEL_SWITCH;
813         }
814
815         hw->netdev_features |= mvm->cfg->features;
816         if (!iwl_mvm_is_csum_supported(mvm)) {
817                 hw->netdev_features &= ~(IWL_TX_CSUM_NETIF_FLAGS |
818                                          NETIF_F_RXCSUM);
819                 /* We may support SW TX CSUM */
820                 if (IWL_MVM_SW_TX_CSUM_OFFLOAD)
821                         hw->netdev_features |= IWL_TX_CSUM_NETIF_FLAGS;
822         }
823
824         if (mvm->cfg->vht_mu_mimo_supported)
825                 wiphy_ext_feature_set(hw->wiphy,
826                                       NL80211_EXT_FEATURE_MU_MIMO_AIR_SNIFFER);
827
828         ret = ieee80211_register_hw(mvm->hw);
829         if (ret) {
830                 iwl_mvm_leds_exit(mvm);
831         }
832
833         return ret;
834 }
835
836 static bool iwl_mvm_defer_tx(struct iwl_mvm *mvm,
837                              struct ieee80211_sta *sta,
838                              struct sk_buff *skb)
839 {
840         struct iwl_mvm_sta *mvmsta;
841         bool defer = false;
842
843         /*
844          * double check the IN_D0I3 flag both before and after
845          * taking the spinlock, in order to prevent taking
846          * the spinlock when not needed.
847          */
848         if (likely(!test_bit(IWL_MVM_STATUS_IN_D0I3, &mvm->status)))
849                 return false;
850
851         spin_lock(&mvm->d0i3_tx_lock);
852         /*
853          * testing the flag again ensures the skb dequeue
854          * loop (on d0i3 exit) hasn't run yet.
855          */
856         if (!test_bit(IWL_MVM_STATUS_IN_D0I3, &mvm->status))
857                 goto out;
858
859         mvmsta = iwl_mvm_sta_from_mac80211(sta);
860         if (mvmsta->sta_id == IWL_MVM_INVALID_STA ||
861             mvmsta->sta_id != mvm->d0i3_ap_sta_id)
862                 goto out;
863
864         __skb_queue_tail(&mvm->d0i3_tx, skb);
865
866         /* trigger wakeup */
867         iwl_mvm_ref(mvm, IWL_MVM_REF_TX);
868         iwl_mvm_unref(mvm, IWL_MVM_REF_TX);
869
870         defer = true;
871 out:
872         spin_unlock(&mvm->d0i3_tx_lock);
873         return defer;
874 }
875
876 static void iwl_mvm_mac_tx(struct ieee80211_hw *hw,
877                            struct ieee80211_tx_control *control,
878                            struct sk_buff *skb)
879 {
880         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
881         struct ieee80211_sta *sta = control->sta;
882         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
883         struct ieee80211_hdr *hdr = (void *)skb->data;
884         bool offchannel = IEEE80211_SKB_CB(skb)->flags &
885                 IEEE80211_TX_CTL_TX_OFFCHAN;
886
887         if (iwl_mvm_is_radio_killed(mvm)) {
888                 IWL_DEBUG_DROP(mvm, "Dropping - RF/CT KILL\n");
889                 goto drop;
890         }
891
892         if (offchannel &&
893             !test_bit(IWL_MVM_STATUS_ROC_RUNNING, &mvm->status) &&
894             !test_bit(IWL_MVM_STATUS_ROC_AUX_RUNNING, &mvm->status))
895                 goto drop;
896
897         /* treat non-bufferable MMPDUs on AP interfaces as broadcast */
898         if ((info->control.vif->type == NL80211_IFTYPE_AP ||
899              info->control.vif->type == NL80211_IFTYPE_ADHOC) &&
900             ieee80211_is_mgmt(hdr->frame_control) &&
901             !ieee80211_is_bufferable_mmpdu(hdr->frame_control))
902                 sta = NULL;
903
904         /* If there is no sta, and it's not offchannel - send through AP */
905         if (!sta && info->control.vif->type == NL80211_IFTYPE_STATION &&
906             !offchannel) {
907                 struct iwl_mvm_vif *mvmvif =
908                         iwl_mvm_vif_from_mac80211(info->control.vif);
909                 u8 ap_sta_id = READ_ONCE(mvmvif->ap_sta_id);
910
911                 if (ap_sta_id < IWL_MVM_STATION_COUNT) {
912                         /* mac80211 holds rcu read lock */
913                         sta = rcu_dereference(mvm->fw_id_to_mac_id[ap_sta_id]);
914                         if (IS_ERR_OR_NULL(sta))
915                                 goto drop;
916                 }
917         }
918
919         if (sta) {
920                 if (iwl_mvm_defer_tx(mvm, sta, skb))
921                         return;
922                 if (iwl_mvm_tx_skb(mvm, skb, sta))
923                         goto drop;
924                 return;
925         }
926
927         if (iwl_mvm_tx_skb_non_sta(mvm, skb))
928                 goto drop;
929         return;
930  drop:
931         ieee80211_free_txskb(hw, skb);
932 }
933
934 void iwl_mvm_mac_itxq_xmit(struct ieee80211_hw *hw, struct ieee80211_txq *txq)
935 {
936         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
937         struct iwl_mvm_txq *mvmtxq = iwl_mvm_txq_from_mac80211(txq);
938         struct sk_buff *skb = NULL;
939
940         /*
941          * No need for threads to be pending here, they can leave the first
942          * taker all the work.
943          *
944          * mvmtxq->tx_request logic:
945          *
946          * If 0, no one is currently TXing, set to 1 to indicate current thread
947          * will now start TX and other threads should quit.
948          *
949          * If 1, another thread is currently TXing, set to 2 to indicate to
950          * that thread that there was another request. Since that request may
951          * have raced with the check whether the queue is empty, the TXing
952          * thread should check the queue's status one more time before leaving.
953          * This check is done in order to not leave any TX hanging in the queue
954          * until the next TX invocation (which may not even happen).
955          *
956          * If 2, another thread is currently TXing, and it will already double
957          * check the queue, so do nothing.
958          */
959         if (atomic_fetch_add_unless(&mvmtxq->tx_request, 1, 2))
960                 return;
961
962         rcu_read_lock();
963         do {
964                 while (likely(!mvmtxq->stopped &&
965                               (mvm->trans->system_pm_mode ==
966                                IWL_PLAT_PM_MODE_DISABLED))) {
967                         skb = ieee80211_tx_dequeue(hw, txq);
968
969                         if (!skb) {
970                                 if (txq->sta)
971                                         IWL_DEBUG_TX(mvm,
972                                                      "TXQ of sta %pM tid %d is now empty\n",
973                                                      txq->sta->addr,
974                                                      txq->tid);
975                                 break;
976                         }
977
978                         if (!txq->sta)
979                                 iwl_mvm_tx_skb_non_sta(mvm, skb);
980                         else
981                                 iwl_mvm_tx_skb(mvm, skb, txq->sta);
982                 }
983         } while (atomic_dec_return(&mvmtxq->tx_request));
984         rcu_read_unlock();
985 }
986
987 static void iwl_mvm_mac_wake_tx_queue(struct ieee80211_hw *hw,
988                                       struct ieee80211_txq *txq)
989 {
990         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
991         struct iwl_mvm_txq *mvmtxq = iwl_mvm_txq_from_mac80211(txq);
992
993         /*
994          * Please note that racing is handled very carefully here:
995          * mvmtxq->txq_id is updated during allocation, and mvmtxq->list is
996          * deleted afterwards.
997          * This means that if:
998          * mvmtxq->txq_id != INVALID_QUEUE && list_empty(&mvmtxq->list):
999          *      queue is allocated and we can TX.
1000          * mvmtxq->txq_id != INVALID_QUEUE && !list_empty(&mvmtxq->list):
1001          *      a race, should defer the frame.
1002          * mvmtxq->txq_id == INVALID_QUEUE && list_empty(&mvmtxq->list):
1003          *      need to allocate the queue and defer the frame.
1004          * mvmtxq->txq_id == INVALID_QUEUE && !list_empty(&mvmtxq->list):
1005          *      queue is already scheduled for allocation, no need to allocate,
1006          *      should defer the frame.
1007          */
1008
1009         /* If the queue is allocated TX and return. */
1010         if (!txq->sta || mvmtxq->txq_id != IWL_MVM_INVALID_QUEUE) {
1011                 /*
1012                  * Check that list is empty to avoid a race where txq_id is
1013                  * already updated, but the queue allocation work wasn't
1014                  * finished
1015                  */
1016                 if (unlikely(txq->sta && !list_empty(&mvmtxq->list)))
1017                         return;
1018
1019                 iwl_mvm_mac_itxq_xmit(hw, txq);
1020                 return;
1021         }
1022
1023         /* The list is being deleted only after the queue is fully allocated. */
1024         if (!list_empty(&mvmtxq->list))
1025                 return;
1026
1027         list_add_tail(&mvmtxq->list, &mvm->add_stream_txqs);
1028         schedule_work(&mvm->add_stream_wk);
1029 }
1030
1031 #define CHECK_BA_TRIGGER(_mvm, _trig, _tid_bm, _tid, _fmt...)           \
1032         do {                                                            \
1033                 if (!(le16_to_cpu(_tid_bm) & BIT(_tid)))                \
1034                         break;                                          \
1035                 iwl_fw_dbg_collect_trig(&(_mvm)->fwrt, _trig, _fmt);    \
1036         } while (0)
1037
1038 static void
1039 iwl_mvm_ampdu_check_trigger(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
1040                             struct ieee80211_sta *sta, u16 tid, u16 rx_ba_ssn,
1041                             enum ieee80211_ampdu_mlme_action action)
1042 {
1043         struct iwl_fw_dbg_trigger_tlv *trig;
1044         struct iwl_fw_dbg_trigger_ba *ba_trig;
1045
1046         trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
1047                                      FW_DBG_TRIGGER_BA);
1048         if (!trig)
1049                 return;
1050
1051         ba_trig = (void *)trig->data;
1052
1053         switch (action) {
1054         case IEEE80211_AMPDU_TX_OPERATIONAL: {
1055                 struct iwl_mvm_sta *mvmsta = iwl_mvm_sta_from_mac80211(sta);
1056                 struct iwl_mvm_tid_data *tid_data = &mvmsta->tid_data[tid];
1057
1058                 CHECK_BA_TRIGGER(mvm, trig, ba_trig->tx_ba_start, tid,
1059                                  "TX AGG START: MAC %pM tid %d ssn %d\n",
1060                                  sta->addr, tid, tid_data->ssn);
1061                 break;
1062                 }
1063         case IEEE80211_AMPDU_TX_STOP_CONT:
1064                 CHECK_BA_TRIGGER(mvm, trig, ba_trig->tx_ba_stop, tid,
1065                                  "TX AGG STOP: MAC %pM tid %d\n",
1066                                  sta->addr, tid);
1067                 break;
1068         case IEEE80211_AMPDU_RX_START:
1069                 CHECK_BA_TRIGGER(mvm, trig, ba_trig->rx_ba_start, tid,
1070                                  "RX AGG START: MAC %pM tid %d ssn %d\n",
1071                                  sta->addr, tid, rx_ba_ssn);
1072                 break;
1073         case IEEE80211_AMPDU_RX_STOP:
1074                 CHECK_BA_TRIGGER(mvm, trig, ba_trig->rx_ba_stop, tid,
1075                                  "RX AGG STOP: MAC %pM tid %d\n",
1076                                  sta->addr, tid);
1077                 break;
1078         default:
1079                 break;
1080         }
1081 }
1082
1083 static int iwl_mvm_mac_ampdu_action(struct ieee80211_hw *hw,
1084                                     struct ieee80211_vif *vif,
1085                                     struct ieee80211_ampdu_params *params)
1086 {
1087         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1088         int ret;
1089         bool tx_agg_ref = false;
1090         struct ieee80211_sta *sta = params->sta;
1091         enum ieee80211_ampdu_mlme_action action = params->action;
1092         u16 tid = params->tid;
1093         u16 *ssn = &params->ssn;
1094         u16 buf_size = params->buf_size;
1095         bool amsdu = params->amsdu;
1096         u16 timeout = params->timeout;
1097
1098         IWL_DEBUG_HT(mvm, "A-MPDU action on addr %pM tid %d: action %d\n",
1099                      sta->addr, tid, action);
1100
1101         if (!(mvm->nvm_data->sku_cap_11n_enable))
1102                 return -EACCES;
1103
1104         /* return from D0i3 before starting a new Tx aggregation */
1105         switch (action) {
1106         case IEEE80211_AMPDU_TX_START:
1107         case IEEE80211_AMPDU_TX_STOP_CONT:
1108         case IEEE80211_AMPDU_TX_STOP_FLUSH:
1109         case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT:
1110         case IEEE80211_AMPDU_TX_OPERATIONAL:
1111                 /*
1112                  * for tx start, wait synchronously until D0i3 exit to
1113                  * get the correct sequence number for the tid.
1114                  * additionally, some other ampdu actions use direct
1115                  * target access, which is not handled automatically
1116                  * by the trans layer (unlike commands), so wait for
1117                  * d0i3 exit in these cases as well.
1118                  */
1119                 ret = iwl_mvm_ref_sync(mvm, IWL_MVM_REF_TX_AGG);
1120                 if (ret)
1121                         return ret;
1122
1123                 tx_agg_ref = true;
1124                 break;
1125         default:
1126                 break;
1127         }
1128
1129         mutex_lock(&mvm->mutex);
1130
1131         switch (action) {
1132         case IEEE80211_AMPDU_RX_START:
1133                 if (iwl_mvm_vif_from_mac80211(vif)->ap_sta_id ==
1134                                 iwl_mvm_sta_from_mac80211(sta)->sta_id) {
1135                         struct iwl_mvm_vif *mvmvif;
1136                         u16 macid = iwl_mvm_vif_from_mac80211(vif)->id;
1137                         struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[macid];
1138
1139                         mdata->opened_rx_ba_sessions = true;
1140                         mvmvif = iwl_mvm_vif_from_mac80211(vif);
1141                         cancel_delayed_work(&mvmvif->uapsd_nonagg_detected_wk);
1142                 }
1143                 if (!iwl_enable_rx_ampdu()) {
1144                         ret = -EINVAL;
1145                         break;
1146                 }
1147                 ret = iwl_mvm_sta_rx_agg(mvm, sta, tid, *ssn, true, buf_size,
1148                                          timeout);
1149                 break;
1150         case IEEE80211_AMPDU_RX_STOP:
1151                 ret = iwl_mvm_sta_rx_agg(mvm, sta, tid, 0, false, buf_size,
1152                                          timeout);
1153                 break;
1154         case IEEE80211_AMPDU_TX_START:
1155                 if (!iwl_enable_tx_ampdu()) {
1156                         ret = -EINVAL;
1157                         break;
1158                 }
1159                 ret = iwl_mvm_sta_tx_agg_start(mvm, vif, sta, tid, ssn);
1160                 break;
1161         case IEEE80211_AMPDU_TX_STOP_CONT:
1162                 ret = iwl_mvm_sta_tx_agg_stop(mvm, vif, sta, tid);
1163                 break;
1164         case IEEE80211_AMPDU_TX_STOP_FLUSH:
1165         case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT:
1166                 ret = iwl_mvm_sta_tx_agg_flush(mvm, vif, sta, tid);
1167                 break;
1168         case IEEE80211_AMPDU_TX_OPERATIONAL:
1169                 ret = iwl_mvm_sta_tx_agg_oper(mvm, vif, sta, tid,
1170                                               buf_size, amsdu);
1171                 break;
1172         default:
1173                 WARN_ON_ONCE(1);
1174                 ret = -EINVAL;
1175                 break;
1176         }
1177
1178         if (!ret) {
1179                 u16 rx_ba_ssn = 0;
1180
1181                 if (action == IEEE80211_AMPDU_RX_START)
1182                         rx_ba_ssn = *ssn;
1183
1184                 iwl_mvm_ampdu_check_trigger(mvm, vif, sta, tid,
1185                                             rx_ba_ssn, action);
1186         }
1187         mutex_unlock(&mvm->mutex);
1188
1189         /*
1190          * If the tid is marked as started, we won't use it for offloaded
1191          * traffic on the next D0i3 entry. It's safe to unref.
1192          */
1193         if (tx_agg_ref)
1194                 iwl_mvm_unref(mvm, IWL_MVM_REF_TX_AGG);
1195
1196         return ret;
1197 }
1198
1199 static void iwl_mvm_cleanup_iterator(void *data, u8 *mac,
1200                                      struct ieee80211_vif *vif)
1201 {
1202         struct iwl_mvm *mvm = data;
1203         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1204
1205         mvmvif->uploaded = false;
1206         mvmvif->ap_sta_id = IWL_MVM_INVALID_STA;
1207
1208         spin_lock_bh(&mvm->time_event_lock);
1209         iwl_mvm_te_clear_data(mvm, &mvmvif->time_event_data);
1210         spin_unlock_bh(&mvm->time_event_lock);
1211
1212         mvmvif->phy_ctxt = NULL;
1213         memset(&mvmvif->bf_data, 0, sizeof(mvmvif->bf_data));
1214         memset(&mvmvif->probe_resp_data, 0, sizeof(mvmvif->probe_resp_data));
1215 }
1216
1217 static void iwl_mvm_restart_cleanup(struct iwl_mvm *mvm)
1218 {
1219         /* cleanup all stale references (scan, roc), but keep the
1220          * ucode_down ref until reconfig is complete
1221          */
1222         iwl_mvm_unref_all_except(mvm, IWL_MVM_REF_UCODE_DOWN);
1223
1224         iwl_mvm_stop_device(mvm);
1225
1226         mvm->cur_aid = 0;
1227
1228         mvm->scan_status = 0;
1229         mvm->ps_disabled = false;
1230         mvm->rfkill_safe_init_done = false;
1231
1232         /* just in case one was running */
1233         iwl_mvm_cleanup_roc_te(mvm);
1234         ieee80211_remain_on_channel_expired(mvm->hw);
1235
1236         iwl_mvm_ftm_restart(mvm);
1237
1238         /*
1239          * cleanup all interfaces, even inactive ones, as some might have
1240          * gone down during the HW restart
1241          */
1242         ieee80211_iterate_interfaces(mvm->hw, 0, iwl_mvm_cleanup_iterator, mvm);
1243
1244         mvm->p2p_device_vif = NULL;
1245         mvm->d0i3_ap_sta_id = IWL_MVM_INVALID_STA;
1246
1247         iwl_mvm_reset_phy_ctxts(mvm);
1248         memset(mvm->fw_key_table, 0, sizeof(mvm->fw_key_table));
1249         memset(&mvm->last_bt_notif, 0, sizeof(mvm->last_bt_notif));
1250         memset(&mvm->last_bt_ci_cmd, 0, sizeof(mvm->last_bt_ci_cmd));
1251
1252         ieee80211_wake_queues(mvm->hw);
1253
1254         /* clear any stale d0i3 state */
1255         clear_bit(IWL_MVM_STATUS_IN_D0I3, &mvm->status);
1256
1257         mvm->vif_count = 0;
1258         mvm->rx_ba_sessions = 0;
1259         mvm->fwrt.dump.conf = FW_DBG_INVALID;
1260         mvm->monitor_on = false;
1261
1262         /* keep statistics ticking */
1263         iwl_mvm_accu_radio_stats(mvm);
1264 }
1265
1266 int __iwl_mvm_mac_start(struct iwl_mvm *mvm)
1267 {
1268         int ret;
1269
1270         lockdep_assert_held(&mvm->mutex);
1271
1272         if (test_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED, &mvm->status)) {
1273                 /*
1274                  * Now convert the HW_RESTART_REQUESTED flag to IN_HW_RESTART
1275                  * so later code will - from now on - see that we're doing it.
1276                  */
1277                 set_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1278                 clear_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED, &mvm->status);
1279                 /* Clean up some internal and mac80211 state on restart */
1280                 iwl_mvm_restart_cleanup(mvm);
1281         } else {
1282                 /* Hold the reference to prevent runtime suspend while
1283                  * the start procedure runs.  It's a bit confusing
1284                  * that the UCODE_DOWN reference is taken, but it just
1285                  * means "UCODE is not UP yet". ( TODO: rename this
1286                  * reference).
1287                  */
1288                 iwl_mvm_ref(mvm, IWL_MVM_REF_UCODE_DOWN);
1289         }
1290         ret = iwl_mvm_up(mvm);
1291
1292         iwl_fw_dbg_apply_point(&mvm->fwrt, IWL_FW_INI_APPLY_POST_INIT);
1293
1294         if (ret && test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status)) {
1295                 /* Something went wrong - we need to finish some cleanup
1296                  * that normally iwl_mvm_mac_restart_complete() below
1297                  * would do.
1298                  */
1299                 clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1300 #ifdef CONFIG_PM
1301                 iwl_mvm_d0i3_enable_tx(mvm, NULL);
1302 #endif
1303         }
1304
1305         return ret;
1306 }
1307
1308 static int iwl_mvm_mac_start(struct ieee80211_hw *hw)
1309 {
1310         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1311         int ret;
1312
1313         /* Some hw restart cleanups must not hold the mutex */
1314         if (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status)) {
1315                 /*
1316                  * Make sure we are out of d0i3. This is needed
1317                  * to make sure the reference accounting is correct
1318                  * (and there is no stale d0i3_exit_work).
1319                  */
1320                 wait_event_timeout(mvm->d0i3_exit_waitq,
1321                                    !test_bit(IWL_MVM_STATUS_IN_D0I3,
1322                                              &mvm->status),
1323                                    HZ);
1324         }
1325
1326         mutex_lock(&mvm->mutex);
1327         ret = __iwl_mvm_mac_start(mvm);
1328         mutex_unlock(&mvm->mutex);
1329
1330         return ret;
1331 }
1332
1333 static void iwl_mvm_restart_complete(struct iwl_mvm *mvm)
1334 {
1335         int ret;
1336
1337         mutex_lock(&mvm->mutex);
1338
1339         clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status);
1340 #ifdef CONFIG_PM
1341         iwl_mvm_d0i3_enable_tx(mvm, NULL);
1342 #endif
1343         ret = iwl_mvm_update_quotas(mvm, true, NULL);
1344         if (ret)
1345                 IWL_ERR(mvm, "Failed to update quotas after restart (%d)\n",
1346                         ret);
1347
1348         /* allow transport/FW low power modes */
1349         iwl_mvm_unref(mvm, IWL_MVM_REF_UCODE_DOWN);
1350
1351         iwl_mvm_send_recovery_cmd(mvm, ERROR_RECOVERY_END_OF_RECOVERY);
1352
1353         /*
1354          * If we have TDLS peers, remove them. We don't know the last seqno/PN
1355          * of packets the FW sent out, so we must reconnect.
1356          */
1357         iwl_mvm_teardown_tdls_peers(mvm);
1358
1359         mutex_unlock(&mvm->mutex);
1360 }
1361
1362 static void iwl_mvm_resume_complete(struct iwl_mvm *mvm)
1363 {
1364         if (iwl_mvm_is_d0i3_supported(mvm) &&
1365             iwl_mvm_enter_d0i3_on_suspend(mvm))
1366                 WARN_ONCE(!wait_event_timeout(mvm->d0i3_exit_waitq,
1367                                               !test_bit(IWL_MVM_STATUS_IN_D0I3,
1368                                                         &mvm->status),
1369                                               HZ),
1370                           "D0i3 exit on resume timed out\n");
1371 }
1372
1373 static void
1374 iwl_mvm_mac_reconfig_complete(struct ieee80211_hw *hw,
1375                               enum ieee80211_reconfig_type reconfig_type)
1376 {
1377         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1378
1379         switch (reconfig_type) {
1380         case IEEE80211_RECONFIG_TYPE_RESTART:
1381                 iwl_mvm_restart_complete(mvm);
1382                 break;
1383         case IEEE80211_RECONFIG_TYPE_SUSPEND:
1384                 iwl_mvm_resume_complete(mvm);
1385                 break;
1386         }
1387 }
1388
1389 void __iwl_mvm_mac_stop(struct iwl_mvm *mvm)
1390 {
1391         lockdep_assert_held(&mvm->mutex);
1392
1393         /* firmware counters are obviously reset now, but we shouldn't
1394          * partially track so also clear the fw_reset_accu counters.
1395          */
1396         memset(&mvm->accu_radio_stats, 0, sizeof(mvm->accu_radio_stats));
1397
1398         /* async_handlers_wk is now blocked */
1399
1400         /*
1401          * The work item could be running or queued if the
1402          * ROC time event stops just as we get here.
1403          */
1404         flush_work(&mvm->roc_done_wk);
1405
1406         iwl_mvm_stop_device(mvm);
1407
1408         iwl_mvm_async_handlers_purge(mvm);
1409         /* async_handlers_list is empty and will stay empty: HW is stopped */
1410
1411         /* the fw is stopped, the aux sta is dead: clean up driver state */
1412         iwl_mvm_del_aux_sta(mvm);
1413
1414         /*
1415          * Clear IN_HW_RESTART and HW_RESTART_REQUESTED flag when stopping the
1416          * hw (as restart_complete() won't be called in this case) and mac80211
1417          * won't execute the restart.
1418          * But make sure to cleanup interfaces that have gone down before/during
1419          * HW restart was requested.
1420          */
1421         if (test_and_clear_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) ||
1422             test_and_clear_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED,
1423                                &mvm->status))
1424                 ieee80211_iterate_interfaces(mvm->hw, 0,
1425                                              iwl_mvm_cleanup_iterator, mvm);
1426
1427         /* We shouldn't have any UIDs still set.  Loop over all the UIDs to
1428          * make sure there's nothing left there and warn if any is found.
1429          */
1430         if (fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_UMAC_SCAN)) {
1431                 int i;
1432
1433                 for (i = 0; i < mvm->max_scans; i++) {
1434                         if (WARN_ONCE(mvm->scan_uid_status[i],
1435                                       "UMAC scan UID %d status was not cleaned\n",
1436                                       i))
1437                                 mvm->scan_uid_status[i] = 0;
1438                 }
1439         }
1440 }
1441
1442 static void iwl_mvm_mac_stop(struct ieee80211_hw *hw)
1443 {
1444         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1445
1446         flush_work(&mvm->d0i3_exit_work);
1447         flush_work(&mvm->async_handlers_wk);
1448         flush_work(&mvm->add_stream_wk);
1449
1450         /*
1451          * Lock and clear the firmware running bit here already, so that
1452          * new commands coming in elsewhere, e.g. from debugfs, will not
1453          * be able to proceed. This is important here because one of those
1454          * debugfs files causes the firmware dump to be triggered, and if we
1455          * don't stop debugfs accesses before canceling that it could be
1456          * retriggered after we flush it but before we've cleared the bit.
1457          */
1458         clear_bit(IWL_MVM_STATUS_FIRMWARE_RUNNING, &mvm->status);
1459
1460         iwl_fw_cancel_dumps(&mvm->fwrt);
1461         cancel_delayed_work_sync(&mvm->cs_tx_unblock_dwork);
1462         cancel_delayed_work_sync(&mvm->scan_timeout_dwork);
1463         iwl_fw_free_dump_desc(&mvm->fwrt);
1464
1465         mutex_lock(&mvm->mutex);
1466         __iwl_mvm_mac_stop(mvm);
1467         mutex_unlock(&mvm->mutex);
1468
1469         /*
1470          * The worker might have been waiting for the mutex, let it run and
1471          * discover that its list is now empty.
1472          */
1473         cancel_work_sync(&mvm->async_handlers_wk);
1474 }
1475
1476 static struct iwl_mvm_phy_ctxt *iwl_mvm_get_free_phy_ctxt(struct iwl_mvm *mvm)
1477 {
1478         u16 i;
1479
1480         lockdep_assert_held(&mvm->mutex);
1481
1482         for (i = 0; i < NUM_PHY_CTX; i++)
1483                 if (!mvm->phy_ctxts[i].ref)
1484                         return &mvm->phy_ctxts[i];
1485
1486         IWL_ERR(mvm, "No available PHY context\n");
1487         return NULL;
1488 }
1489
1490 static int iwl_mvm_set_tx_power(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
1491                                 s16 tx_power)
1492 {
1493         int len;
1494         union {
1495                 struct iwl_dev_tx_power_cmd v5;
1496                 struct iwl_dev_tx_power_cmd_v4 v4;
1497         } cmd = {
1498                 .v5.v3.set_mode = cpu_to_le32(IWL_TX_POWER_MODE_SET_MAC),
1499                 .v5.v3.mac_context_id =
1500                         cpu_to_le32(iwl_mvm_vif_from_mac80211(vif)->id),
1501                 .v5.v3.pwr_restriction = cpu_to_le16(8 * tx_power),
1502         };
1503
1504         if (tx_power == IWL_DEFAULT_MAX_TX_POWER)
1505                 cmd.v5.v3.pwr_restriction = cpu_to_le16(IWL_DEV_MAX_TX_POWER);
1506
1507         if (fw_has_api(&mvm->fw->ucode_capa,
1508                        IWL_UCODE_TLV_API_REDUCE_TX_POWER))
1509                 len = sizeof(cmd.v5);
1510         else if (fw_has_capa(&mvm->fw->ucode_capa,
1511                              IWL_UCODE_TLV_CAPA_TX_POWER_ACK))
1512                 len = sizeof(cmd.v4);
1513         else
1514                 len = sizeof(cmd.v4.v3);
1515
1516         return iwl_mvm_send_cmd_pdu(mvm, REDUCE_TX_POWER_CMD, 0, len, &cmd);
1517 }
1518
1519 static int iwl_mvm_post_channel_switch(struct ieee80211_hw *hw,
1520                                        struct ieee80211_vif *vif)
1521 {
1522         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1523         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1524         int ret;
1525
1526         mutex_lock(&mvm->mutex);
1527
1528         if (mvmvif->csa_failed) {
1529                 mvmvif->csa_failed = false;
1530                 ret = -EIO;
1531                 goto out_unlock;
1532         }
1533
1534         if (vif->type == NL80211_IFTYPE_STATION) {
1535                 struct iwl_mvm_sta *mvmsta;
1536
1537                 mvmvif->csa_bcn_pending = false;
1538                 mvmsta = iwl_mvm_sta_from_staid_protected(mvm,
1539                                                           mvmvif->ap_sta_id);
1540
1541                 if (WARN_ON(!mvmsta)) {
1542                         ret = -EIO;
1543                         goto out_unlock;
1544                 }
1545
1546                 iwl_mvm_sta_modify_disable_tx(mvm, mvmsta, false);
1547
1548                 iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
1549
1550                 ret = iwl_mvm_enable_beacon_filter(mvm, vif, 0);
1551                 if (ret)
1552                         goto out_unlock;
1553
1554                 iwl_mvm_stop_session_protection(mvm, vif);
1555         }
1556
1557         mvmvif->ps_disabled = false;
1558
1559         ret = iwl_mvm_power_update_ps(mvm);
1560
1561 out_unlock:
1562         mutex_unlock(&mvm->mutex);
1563
1564         return ret;
1565 }
1566
1567 static void iwl_mvm_abort_channel_switch(struct ieee80211_hw *hw,
1568                                          struct ieee80211_vif *vif)
1569 {
1570         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1571         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1572         struct iwl_chan_switch_te_cmd cmd = {
1573                 .mac_id = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
1574                                                           mvmvif->color)),
1575                 .action = cpu_to_le32(FW_CTXT_ACTION_REMOVE),
1576         };
1577
1578         IWL_DEBUG_MAC80211(mvm, "Abort CSA on mac %d\n", mvmvif->id);
1579
1580         mutex_lock(&mvm->mutex);
1581         WARN_ON(iwl_mvm_send_cmd_pdu(mvm,
1582                                      WIDE_ID(MAC_CONF_GROUP,
1583                                              CHANNEL_SWITCH_TIME_EVENT_CMD),
1584                                      0, sizeof(cmd), &cmd));
1585         mutex_unlock(&mvm->mutex);
1586
1587         WARN_ON(iwl_mvm_post_channel_switch(hw, vif));
1588 }
1589
1590 static void iwl_mvm_channel_switch_disconnect_wk(struct work_struct *wk)
1591 {
1592         struct iwl_mvm *mvm;
1593         struct iwl_mvm_vif *mvmvif;
1594         struct ieee80211_vif *vif;
1595
1596         mvmvif = container_of(wk, struct iwl_mvm_vif, csa_work.work);
1597         vif = container_of((void *)mvmvif, struct ieee80211_vif, drv_priv);
1598         mvm = mvmvif->mvm;
1599
1600         iwl_mvm_abort_channel_switch(mvm->hw, vif);
1601         ieee80211_chswitch_done(vif, false);
1602 }
1603
1604 static int iwl_mvm_mac_add_interface(struct ieee80211_hw *hw,
1605                                      struct ieee80211_vif *vif)
1606 {
1607         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1608         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1609         int ret;
1610
1611         mvmvif->mvm = mvm;
1612         RCU_INIT_POINTER(mvmvif->probe_resp_data, NULL);
1613
1614         /*
1615          * make sure D0i3 exit is completed, otherwise a target access
1616          * during tx queue configuration could be done when still in
1617          * D0i3 state.
1618          */
1619         ret = iwl_mvm_ref_sync(mvm, IWL_MVM_REF_ADD_IF);
1620         if (ret)
1621                 return ret;
1622
1623         /*
1624          * Not much to do here. The stack will not allow interface
1625          * types or combinations that we didn't advertise, so we
1626          * don't really have to check the types.
1627          */
1628
1629         mutex_lock(&mvm->mutex);
1630
1631         /* make sure that beacon statistics don't go backwards with FW reset */
1632         if (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status))
1633                 mvmvif->beacon_stats.accu_num_beacons +=
1634                         mvmvif->beacon_stats.num_beacons;
1635
1636         /* Allocate resources for the MAC context, and add it to the fw  */
1637         ret = iwl_mvm_mac_ctxt_init(mvm, vif);
1638         if (ret)
1639                 goto out_unlock;
1640
1641         rcu_assign_pointer(mvm->vif_id_to_mac[mvmvif->id], vif);
1642
1643         /* Counting number of interfaces is needed for legacy PM */
1644         if (vif->type != NL80211_IFTYPE_P2P_DEVICE)
1645                 mvm->vif_count++;
1646
1647         /*
1648          * The AP binding flow can be done only after the beacon
1649          * template is configured (which happens only in the mac80211
1650          * start_ap() flow), and adding the broadcast station can happen
1651          * only after the binding.
1652          * In addition, since modifying the MAC before adding a bcast
1653          * station is not allowed by the FW, delay the adding of MAC context to
1654          * the point where we can also add the bcast station.
1655          * In short: there's not much we can do at this point, other than
1656          * allocating resources :)
1657          */
1658         if (vif->type == NL80211_IFTYPE_AP ||
1659             vif->type == NL80211_IFTYPE_ADHOC) {
1660                 ret = iwl_mvm_alloc_bcast_sta(mvm, vif);
1661                 if (ret) {
1662                         IWL_ERR(mvm, "Failed to allocate bcast sta\n");
1663                         goto out_release;
1664                 }
1665
1666                 /*
1667                  * Only queue for this station is the mcast queue,
1668                  * which shouldn't be in TFD mask anyway
1669                  */
1670                 ret = iwl_mvm_allocate_int_sta(mvm, &mvmvif->mcast_sta,
1671                                                0, vif->type,
1672                                                IWL_STA_MULTICAST);
1673                 if (ret)
1674                         goto out_release;
1675
1676                 iwl_mvm_vif_dbgfs_register(mvm, vif);
1677                 goto out_unlock;
1678         }
1679
1680         mvmvif->features |= hw->netdev_features;
1681
1682         ret = iwl_mvm_mac_ctxt_add(mvm, vif);
1683         if (ret)
1684                 goto out_release;
1685
1686         ret = iwl_mvm_power_update_mac(mvm);
1687         if (ret)
1688                 goto out_remove_mac;
1689
1690         /* beacon filtering */
1691         ret = iwl_mvm_disable_beacon_filter(mvm, vif, 0);
1692         if (ret)
1693                 goto out_remove_mac;
1694
1695         if (!mvm->bf_allowed_vif &&
1696             vif->type == NL80211_IFTYPE_STATION && !vif->p2p) {
1697                 mvm->bf_allowed_vif = mvmvif;
1698                 vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER |
1699                                      IEEE80211_VIF_SUPPORTS_CQM_RSSI;
1700         }
1701
1702         /*
1703          * P2P_DEVICE interface does not have a channel context assigned to it,
1704          * so a dedicated PHY context is allocated to it and the corresponding
1705          * MAC context is bound to it at this stage.
1706          */
1707         if (vif->type == NL80211_IFTYPE_P2P_DEVICE) {
1708
1709                 mvmvif->phy_ctxt = iwl_mvm_get_free_phy_ctxt(mvm);
1710                 if (!mvmvif->phy_ctxt) {
1711                         ret = -ENOSPC;
1712                         goto out_free_bf;
1713                 }
1714
1715                 iwl_mvm_phy_ctxt_ref(mvm, mvmvif->phy_ctxt);
1716                 ret = iwl_mvm_binding_add_vif(mvm, vif);
1717                 if (ret)
1718                         goto out_unref_phy;
1719
1720                 ret = iwl_mvm_add_p2p_bcast_sta(mvm, vif);
1721                 if (ret)
1722                         goto out_unbind;
1723
1724                 /* Save a pointer to p2p device vif, so it can later be used to
1725                  * update the p2p device MAC when a GO is started/stopped */
1726                 mvm->p2p_device_vif = vif;
1727         }
1728
1729         iwl_mvm_tcm_add_vif(mvm, vif);
1730         INIT_DELAYED_WORK(&mvmvif->csa_work,
1731                           iwl_mvm_channel_switch_disconnect_wk);
1732
1733         if (vif->type == NL80211_IFTYPE_MONITOR)
1734                 mvm->monitor_on = true;
1735
1736         iwl_mvm_vif_dbgfs_register(mvm, vif);
1737         goto out_unlock;
1738
1739  out_unbind:
1740         iwl_mvm_binding_remove_vif(mvm, vif);
1741  out_unref_phy:
1742         iwl_mvm_phy_ctxt_unref(mvm, mvmvif->phy_ctxt);
1743  out_free_bf:
1744         if (mvm->bf_allowed_vif == mvmvif) {
1745                 mvm->bf_allowed_vif = NULL;
1746                 vif->driver_flags &= ~(IEEE80211_VIF_BEACON_FILTER |
1747                                        IEEE80211_VIF_SUPPORTS_CQM_RSSI);
1748         }
1749  out_remove_mac:
1750         mvmvif->phy_ctxt = NULL;
1751         iwl_mvm_mac_ctxt_remove(mvm, vif);
1752  out_release:
1753         if (vif->type != NL80211_IFTYPE_P2P_DEVICE)
1754                 mvm->vif_count--;
1755  out_unlock:
1756         mutex_unlock(&mvm->mutex);
1757
1758         iwl_mvm_unref(mvm, IWL_MVM_REF_ADD_IF);
1759
1760         return ret;
1761 }
1762
1763 static void iwl_mvm_prepare_mac_removal(struct iwl_mvm *mvm,
1764                                         struct ieee80211_vif *vif)
1765 {
1766         if (vif->type == NL80211_IFTYPE_P2P_DEVICE) {
1767                 /*
1768                  * Flush the ROC worker which will flush the OFFCHANNEL queue.
1769                  * We assume here that all the packets sent to the OFFCHANNEL
1770                  * queue are sent in ROC session.
1771                  */
1772                 flush_work(&mvm->roc_done_wk);
1773         }
1774 }
1775
1776 static void iwl_mvm_mac_remove_interface(struct ieee80211_hw *hw,
1777                                          struct ieee80211_vif *vif)
1778 {
1779         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1780         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1781         struct iwl_probe_resp_data *probe_data;
1782
1783         iwl_mvm_prepare_mac_removal(mvm, vif);
1784
1785         if (!(vif->type == NL80211_IFTYPE_AP ||
1786               vif->type == NL80211_IFTYPE_ADHOC))
1787                 iwl_mvm_tcm_rm_vif(mvm, vif);
1788
1789         mutex_lock(&mvm->mutex);
1790
1791         probe_data = rcu_dereference_protected(mvmvif->probe_resp_data,
1792                                                lockdep_is_held(&mvm->mutex));
1793         RCU_INIT_POINTER(mvmvif->probe_resp_data, NULL);
1794         if (probe_data)
1795                 kfree_rcu(probe_data, rcu_head);
1796
1797         if (mvm->bf_allowed_vif == mvmvif) {
1798                 mvm->bf_allowed_vif = NULL;
1799                 vif->driver_flags &= ~(IEEE80211_VIF_BEACON_FILTER |
1800                                        IEEE80211_VIF_SUPPORTS_CQM_RSSI);
1801         }
1802
1803         if (vif->bss_conf.ftm_responder)
1804                 memset(&mvm->ftm_resp_stats, 0, sizeof(mvm->ftm_resp_stats));
1805
1806         iwl_mvm_vif_dbgfs_clean(mvm, vif);
1807
1808         /*
1809          * For AP/GO interface, the tear down of the resources allocated to the
1810          * interface is be handled as part of the stop_ap flow.
1811          */
1812         if (vif->type == NL80211_IFTYPE_AP ||
1813             vif->type == NL80211_IFTYPE_ADHOC) {
1814 #ifdef CONFIG_NL80211_TESTMODE
1815                 if (vif == mvm->noa_vif) {
1816                         mvm->noa_vif = NULL;
1817                         mvm->noa_duration = 0;
1818                 }
1819 #endif
1820                 iwl_mvm_dealloc_int_sta(mvm, &mvmvif->mcast_sta);
1821                 iwl_mvm_dealloc_bcast_sta(mvm, vif);
1822                 goto out_release;
1823         }
1824
1825         if (vif->type == NL80211_IFTYPE_P2P_DEVICE) {
1826                 mvm->p2p_device_vif = NULL;
1827                 iwl_mvm_rm_p2p_bcast_sta(mvm, vif);
1828                 iwl_mvm_binding_remove_vif(mvm, vif);
1829                 iwl_mvm_phy_ctxt_unref(mvm, mvmvif->phy_ctxt);
1830                 mvmvif->phy_ctxt = NULL;
1831         }
1832
1833         if (mvm->vif_count && vif->type != NL80211_IFTYPE_P2P_DEVICE)
1834                 mvm->vif_count--;
1835
1836         iwl_mvm_power_update_mac(mvm);
1837         iwl_mvm_mac_ctxt_remove(mvm, vif);
1838
1839         RCU_INIT_POINTER(mvm->vif_id_to_mac[mvmvif->id], NULL);
1840
1841         if (vif->type == NL80211_IFTYPE_MONITOR)
1842                 mvm->monitor_on = false;
1843
1844 out_release:
1845         mutex_unlock(&mvm->mutex);
1846 }
1847
1848 static int iwl_mvm_mac_config(struct ieee80211_hw *hw, u32 changed)
1849 {
1850         return 0;
1851 }
1852
1853 struct iwl_mvm_mc_iter_data {
1854         struct iwl_mvm *mvm;
1855         int port_id;
1856 };
1857
1858 static void iwl_mvm_mc_iface_iterator(void *_data, u8 *mac,
1859                                       struct ieee80211_vif *vif)
1860 {
1861         struct iwl_mvm_mc_iter_data *data = _data;
1862         struct iwl_mvm *mvm = data->mvm;
1863         struct iwl_mcast_filter_cmd *cmd = mvm->mcast_filter_cmd;
1864         struct iwl_host_cmd hcmd = {
1865                 .id = MCAST_FILTER_CMD,
1866                 .flags = CMD_ASYNC,
1867                 .dataflags[0] = IWL_HCMD_DFL_NOCOPY,
1868         };
1869         int ret, len;
1870
1871         /* if we don't have free ports, mcast frames will be dropped */
1872         if (WARN_ON_ONCE(data->port_id >= MAX_PORT_ID_NUM))
1873                 return;
1874
1875         if (vif->type != NL80211_IFTYPE_STATION ||
1876             !vif->bss_conf.assoc)
1877                 return;
1878
1879         cmd->port_id = data->port_id++;
1880         memcpy(cmd->bssid, vif->bss_conf.bssid, ETH_ALEN);
1881         len = roundup(sizeof(*cmd) + cmd->count * ETH_ALEN, 4);
1882
1883         hcmd.len[0] = len;
1884         hcmd.data[0] = cmd;
1885
1886         ret = iwl_mvm_send_cmd(mvm, &hcmd);
1887         if (ret)
1888                 IWL_ERR(mvm, "mcast filter cmd error. ret=%d\n", ret);
1889 }
1890
1891 static void iwl_mvm_recalc_multicast(struct iwl_mvm *mvm)
1892 {
1893         struct iwl_mvm_mc_iter_data iter_data = {
1894                 .mvm = mvm,
1895         };
1896
1897         lockdep_assert_held(&mvm->mutex);
1898
1899         if (WARN_ON_ONCE(!mvm->mcast_filter_cmd))
1900                 return;
1901
1902         ieee80211_iterate_active_interfaces_atomic(
1903                 mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1904                 iwl_mvm_mc_iface_iterator, &iter_data);
1905 }
1906
1907 static u64 iwl_mvm_prepare_multicast(struct ieee80211_hw *hw,
1908                                      struct netdev_hw_addr_list *mc_list)
1909 {
1910         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1911         struct iwl_mcast_filter_cmd *cmd;
1912         struct netdev_hw_addr *addr;
1913         int addr_count;
1914         bool pass_all;
1915         int len;
1916
1917         addr_count = netdev_hw_addr_list_count(mc_list);
1918         pass_all = addr_count > MAX_MCAST_FILTERING_ADDRESSES ||
1919                    IWL_MVM_FW_MCAST_FILTER_PASS_ALL;
1920         if (pass_all)
1921                 addr_count = 0;
1922
1923         len = roundup(sizeof(*cmd) + addr_count * ETH_ALEN, 4);
1924         cmd = kzalloc(len, GFP_ATOMIC);
1925         if (!cmd)
1926                 return 0;
1927
1928         if (pass_all) {
1929                 cmd->pass_all = 1;
1930                 return (u64)(unsigned long)cmd;
1931         }
1932
1933         netdev_hw_addr_list_for_each(addr, mc_list) {
1934                 IWL_DEBUG_MAC80211(mvm, "mcast addr (%d): %pM\n",
1935                                    cmd->count, addr->addr);
1936                 memcpy(&cmd->addr_list[cmd->count * ETH_ALEN],
1937                        addr->addr, ETH_ALEN);
1938                 cmd->count++;
1939         }
1940
1941         return (u64)(unsigned long)cmd;
1942 }
1943
1944 static void iwl_mvm_configure_filter(struct ieee80211_hw *hw,
1945                                      unsigned int changed_flags,
1946                                      unsigned int *total_flags,
1947                                      u64 multicast)
1948 {
1949         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1950         struct iwl_mcast_filter_cmd *cmd = (void *)(unsigned long)multicast;
1951
1952         mutex_lock(&mvm->mutex);
1953
1954         /* replace previous configuration */
1955         kfree(mvm->mcast_filter_cmd);
1956         mvm->mcast_filter_cmd = cmd;
1957
1958         if (!cmd)
1959                 goto out;
1960
1961         if (changed_flags & FIF_ALLMULTI)
1962                 cmd->pass_all = !!(*total_flags & FIF_ALLMULTI);
1963
1964         if (cmd->pass_all)
1965                 cmd->count = 0;
1966
1967         iwl_mvm_recalc_multicast(mvm);
1968 out:
1969         mutex_unlock(&mvm->mutex);
1970         *total_flags = 0;
1971 }
1972
1973 static void iwl_mvm_config_iface_filter(struct ieee80211_hw *hw,
1974                                         struct ieee80211_vif *vif,
1975                                         unsigned int filter_flags,
1976                                         unsigned int changed_flags)
1977 {
1978         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
1979
1980         /* We support only filter for probe requests */
1981         if (!(changed_flags & FIF_PROBE_REQ))
1982                 return;
1983
1984         /* Supported only for p2p client interfaces */
1985         if (vif->type != NL80211_IFTYPE_STATION || !vif->bss_conf.assoc ||
1986             !vif->p2p)
1987                 return;
1988
1989         mutex_lock(&mvm->mutex);
1990         iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
1991         mutex_unlock(&mvm->mutex);
1992 }
1993
1994 #ifdef CONFIG_IWLWIFI_BCAST_FILTERING
1995 struct iwl_bcast_iter_data {
1996         struct iwl_mvm *mvm;
1997         struct iwl_bcast_filter_cmd *cmd;
1998         u8 current_filter;
1999 };
2000
2001 static void
2002 iwl_mvm_set_bcast_filter(struct ieee80211_vif *vif,
2003                          const struct iwl_fw_bcast_filter *in_filter,
2004                          struct iwl_fw_bcast_filter *out_filter)
2005 {
2006         struct iwl_fw_bcast_filter_attr *attr;
2007         int i;
2008
2009         memcpy(out_filter, in_filter, sizeof(*out_filter));
2010
2011         for (i = 0; i < ARRAY_SIZE(out_filter->attrs); i++) {
2012                 attr = &out_filter->attrs[i];
2013
2014                 if (!attr->mask)
2015                         break;
2016
2017                 switch (attr->reserved1) {
2018                 case cpu_to_le16(BC_FILTER_MAGIC_IP):
2019                         if (vif->bss_conf.arp_addr_cnt != 1) {
2020                                 attr->mask = 0;
2021                                 continue;
2022                         }
2023
2024                         attr->val = vif->bss_conf.arp_addr_list[0];
2025                         break;
2026                 case cpu_to_le16(BC_FILTER_MAGIC_MAC):
2027                         attr->val = *(__be32 *)&vif->addr[2];
2028                         break;
2029                 default:
2030                         break;
2031                 }
2032                 attr->reserved1 = 0;
2033                 out_filter->num_attrs++;
2034         }
2035 }
2036
2037 static void iwl_mvm_bcast_filter_iterator(void *_data, u8 *mac,
2038                                           struct ieee80211_vif *vif)
2039 {
2040         struct iwl_bcast_iter_data *data = _data;
2041         struct iwl_mvm *mvm = data->mvm;
2042         struct iwl_bcast_filter_cmd *cmd = data->cmd;
2043         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
2044         struct iwl_fw_bcast_mac *bcast_mac;
2045         int i;
2046
2047         if (WARN_ON(mvmvif->id >= ARRAY_SIZE(cmd->macs)))
2048                 return;
2049
2050         bcast_mac = &cmd->macs[mvmvif->id];
2051
2052         /*
2053          * enable filtering only for associated stations, but not for P2P
2054          * Clients
2055          */
2056         if (vif->type != NL80211_IFTYPE_STATION || vif->p2p ||
2057             !vif->bss_conf.assoc)
2058                 return;
2059
2060         bcast_mac->default_discard = 1;
2061
2062         /* copy all configured filters */
2063         for (i = 0; mvm->bcast_filters[i].attrs[0].mask; i++) {
2064                 /*
2065                  * Make sure we don't exceed our filters limit.
2066                  * if there is still a valid filter to be configured,
2067                  * be on the safe side and just allow bcast for this mac.
2068                  */
2069                 if (WARN_ON_ONCE(data->current_filter >=
2070                                  ARRAY_SIZE(cmd->filters))) {
2071                         bcast_mac->default_discard = 0;
2072                         bcast_mac->attached_filters = 0;
2073                         break;
2074                 }
2075
2076                 iwl_mvm_set_bcast_filter(vif,
2077                                          &mvm->bcast_filters[i],
2078                                          &cmd->filters[data->current_filter]);
2079
2080                 /* skip current filter if it contains no attributes */
2081                 if (!cmd->filters[data->current_filter].num_attrs)
2082                         continue;
2083
2084                 /* attach the filter to current mac */
2085                 bcast_mac->attached_filters |=
2086                                 cpu_to_le16(BIT(data->current_filter));
2087
2088                 data->current_filter++;
2089         }
2090 }
2091
2092 bool iwl_mvm_bcast_filter_build_cmd(struct iwl_mvm *mvm,
2093                                     struct iwl_bcast_filter_cmd *cmd)
2094 {
2095         struct iwl_bcast_iter_data iter_data = {
2096                 .mvm = mvm,
2097                 .cmd = cmd,
2098         };
2099
2100         if (IWL_MVM_FW_BCAST_FILTER_PASS_ALL)
2101                 return false;
2102
2103         memset(cmd, 0, sizeof(*cmd));
2104         cmd->max_bcast_filters = ARRAY_SIZE(cmd->filters);
2105         cmd->max_macs = ARRAY_SIZE(cmd->macs);
2106
2107 #ifdef CONFIG_IWLWIFI_DEBUGFS
2108         /* use debugfs filters/macs if override is configured */
2109         if (mvm->dbgfs_bcast_filtering.override) {
2110                 memcpy(cmd->filters, &mvm->dbgfs_bcast_filtering.cmd.filters,
2111                        sizeof(cmd->filters));
2112                 memcpy(cmd->macs, &mvm->dbgfs_bcast_filtering.cmd.macs,
2113                        sizeof(cmd->macs));
2114                 return true;
2115         }
2116 #endif
2117
2118         /* if no filters are configured, do nothing */
2119         if (!mvm->bcast_filters)
2120                 return false;
2121
2122         /* configure and attach these filters for each associated sta vif */
2123         ieee80211_iterate_active_interfaces(
2124                 mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
2125                 iwl_mvm_bcast_filter_iterator, &iter_data);
2126
2127         return true;
2128 }
2129
2130 static int iwl_mvm_configure_bcast_filter(struct iwl_mvm *mvm)
2131 {
2132         struct iwl_bcast_filter_cmd cmd;
2133
2134         if (!(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_BCAST_FILTERING))
2135                 return 0;
2136
2137         if (!iwl_mvm_bcast_filter_build_cmd(mvm, &cmd))
2138                 return 0;
2139
2140         return iwl_mvm_send_cmd_pdu(mvm, BCAST_FILTER_CMD, 0,
2141                                     sizeof(cmd), &cmd);
2142 }
2143 #else
2144 static inline int iwl_mvm_configure_bcast_filter(struct iwl_mvm *mvm)
2145 {
2146         return 0;
2147 }
2148 #endif
2149
2150 static int iwl_mvm_update_mu_groups(struct iwl_mvm *mvm,
2151                                     struct ieee80211_vif *vif)
2152 {
2153         struct iwl_mu_group_mgmt_cmd cmd = {};
2154
2155         memcpy(cmd.membership_status, vif->bss_conf.mu_group.membership,
2156                WLAN_MEMBERSHIP_LEN);
2157         memcpy(cmd.user_position, vif->bss_conf.mu_group.position,
2158                WLAN_USER_POSITION_LEN);
2159
2160         return iwl_mvm_send_cmd_pdu(mvm,
2161                                     WIDE_ID(DATA_PATH_GROUP,
2162                                             UPDATE_MU_GROUPS_CMD),
2163                                     0, sizeof(cmd), &cmd);
2164 }
2165
2166 static void iwl_mvm_mu_mimo_iface_iterator(void *_data, u8 *mac,
2167                                            struct ieee80211_vif *vif)
2168 {
2169         if (vif->mu_mimo_owner) {
2170                 struct iwl_mu_group_mgmt_notif *notif = _data;
2171
2172                 /*
2173                  * MU-MIMO Group Id action frame is little endian. We treat
2174                  * the data received from firmware as if it came from the
2175                  * action frame, so no conversion is needed.
2176                  */
2177                 ieee80211_update_mu_groups(vif,
2178                                            (u8 *)&notif->membership_status,
2179                                            (u8 *)&notif->user_position);
2180         }
2181 }
2182
2183 void iwl_mvm_mu_mimo_grp_notif(struct iwl_mvm *mvm,
2184                                struct iwl_rx_cmd_buffer *rxb)
2185 {
2186         struct iwl_rx_packet *pkt = rxb_addr(rxb);
2187         struct iwl_mu_group_mgmt_notif *notif = (void *)pkt->data;
2188
2189         ieee80211_iterate_active_interfaces_atomic(
2190                         mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
2191                         iwl_mvm_mu_mimo_iface_iterator, notif);
2192 }
2193
2194 static u8 iwl_mvm_he_get_ppe_val(u8 *ppe, u8 ppe_pos_bit)
2195 {
2196         u8 byte_num = ppe_pos_bit / 8;
2197         u8 bit_num = ppe_pos_bit % 8;
2198         u8 residue_bits;
2199         u8 res;
2200
2201         if (bit_num <= 5)
2202                 return (ppe[byte_num] >> bit_num) &
2203                        (BIT(IEEE80211_PPE_THRES_INFO_PPET_SIZE) - 1);
2204
2205         /*
2206          * If bit_num > 5, we have to combine bits with next byte.
2207          * Calculate how many bits we need to take from current byte (called
2208          * here "residue_bits"), and add them to bits from next byte.
2209          */
2210
2211         residue_bits = 8 - bit_num;
2212
2213         res = (ppe[byte_num + 1] &
2214                (BIT(IEEE80211_PPE_THRES_INFO_PPET_SIZE - residue_bits) - 1)) <<
2215               residue_bits;
2216         res += (ppe[byte_num] >> bit_num) & (BIT(residue_bits) - 1);
2217
2218         return res;
2219 }
2220
2221 static void iwl_mvm_cfg_he_sta(struct iwl_mvm *mvm,
2222                                struct ieee80211_vif *vif, u8 sta_id)
2223 {
2224         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
2225         struct iwl_he_sta_context_cmd sta_ctxt_cmd = {
2226                 .sta_id = sta_id,
2227                 .tid_limit = IWL_MAX_TID_COUNT,
2228                 .bss_color = vif->bss_conf.bss_color,
2229                 .htc_trig_based_pkt_ext = vif->bss_conf.htc_trig_based_pkt_ext,
2230                 .frame_time_rts_th =
2231                         cpu_to_le16(vif->bss_conf.frame_time_rts_th),
2232         };
2233         int size = fw_has_api(&mvm->fw->ucode_capa,
2234                               IWL_UCODE_TLV_API_MBSSID_HE) ?
2235                    sizeof(sta_ctxt_cmd) :
2236                    sizeof(struct iwl_he_sta_context_cmd_v1);
2237         struct ieee80211_sta *sta;
2238         u32 flags;
2239         int i;
2240
2241         rcu_read_lock();
2242
2243         sta = rcu_dereference(mvm->fw_id_to_mac_id[sta_ctxt_cmd.sta_id]);
2244         if (IS_ERR(sta)) {
2245                 rcu_read_unlock();
2246                 WARN(1, "Can't find STA to configure HE\n");
2247                 return;
2248         }
2249
2250         if (!sta->he_cap.has_he) {
2251                 rcu_read_unlock();
2252                 return;
2253         }
2254
2255         flags = 0;
2256
2257         /* HTC flags */
2258         if (sta->he_cap.he_cap_elem.mac_cap_info[0] &
2259             IEEE80211_HE_MAC_CAP0_HTC_HE)
2260                 sta_ctxt_cmd.htc_flags |= cpu_to_le32(IWL_HE_HTC_SUPPORT);
2261         if ((sta->he_cap.he_cap_elem.mac_cap_info[1] &
2262               IEEE80211_HE_MAC_CAP1_LINK_ADAPTATION) ||
2263             (sta->he_cap.he_cap_elem.mac_cap_info[2] &
2264               IEEE80211_HE_MAC_CAP2_LINK_ADAPTATION)) {
2265                 u8 link_adap =
2266                         ((sta->he_cap.he_cap_elem.mac_cap_info[2] &
2267                           IEEE80211_HE_MAC_CAP2_LINK_ADAPTATION) << 1) +
2268                          (sta->he_cap.he_cap_elem.mac_cap_info[1] &
2269                           IEEE80211_HE_MAC_CAP1_LINK_ADAPTATION);
2270
2271                 if (link_adap == 2)
2272                         sta_ctxt_cmd.htc_flags |=
2273                                 cpu_to_le32(IWL_HE_HTC_LINK_ADAP_UNSOLICITED);
2274                 else if (link_adap == 3)
2275                         sta_ctxt_cmd.htc_flags |=
2276                                 cpu_to_le32(IWL_HE_HTC_LINK_ADAP_BOTH);
2277         }
2278         if (sta->he_cap.he_cap_elem.mac_cap_info[2] & IEEE80211_HE_MAC_CAP2_BSR)
2279                 sta_ctxt_cmd.htc_flags |= cpu_to_le32(IWL_HE_HTC_BSR_SUPP);
2280         if (sta->he_cap.he_cap_elem.mac_cap_info[3] &
2281             IEEE80211_HE_MAC_CAP3_OMI_CONTROL)
2282                 sta_ctxt_cmd.htc_flags |= cpu_to_le32(IWL_HE_HTC_OMI_SUPP);
2283         if (sta->he_cap.he_cap_elem.mac_cap_info[4] & IEEE80211_HE_MAC_CAP4_BQR)
2284                 sta_ctxt_cmd.htc_flags |= cpu_to_le32(IWL_HE_HTC_BQR_SUPP);
2285
2286         /*
2287          * Initialize the PPE thresholds to "None" (7), as described in Table
2288          * 9-262ac of 80211.ax/D3.0.
2289          */
2290         memset(&sta_ctxt_cmd.pkt_ext, 7, sizeof(sta_ctxt_cmd.pkt_ext));
2291
2292         /* If PPE Thresholds exist, parse them into a FW-familiar format. */
2293         if (sta->he_cap.he_cap_elem.phy_cap_info[6] &
2294             IEEE80211_HE_PHY_CAP6_PPE_THRESHOLD_PRESENT) {
2295                 u8 nss = (sta->he_cap.ppe_thres[0] &
2296                           IEEE80211_PPE_THRES_NSS_MASK) + 1;
2297                 u8 ru_index_bitmap =
2298                         (sta->he_cap.ppe_thres[0] &
2299                          IEEE80211_PPE_THRES_RU_INDEX_BITMASK_MASK) >>
2300                         IEEE80211_PPE_THRES_RU_INDEX_BITMASK_POS;
2301                 u8 *ppe = &sta->he_cap.ppe_thres[0];
2302                 u8 ppe_pos_bit = 7; /* Starting after PPE header */
2303
2304                 /*
2305                  * FW currently supports only nss == MAX_HE_SUPP_NSS
2306                  *
2307                  * If nss > MAX: we can ignore values we don't support
2308                  * If nss < MAX: we can set zeros in other streams
2309                  */
2310                 if (nss > MAX_HE_SUPP_NSS) {
2311                         IWL_INFO(mvm, "Got NSS = %d - trimming to %d\n", nss,
2312                                  MAX_HE_SUPP_NSS);
2313                         nss = MAX_HE_SUPP_NSS;
2314                 }
2315
2316                 for (i = 0; i < nss; i++) {
2317                         u8 ru_index_tmp = ru_index_bitmap << 1;
2318                         u8 bw;
2319
2320                         for (bw = 0; bw < MAX_HE_CHANNEL_BW_INDX; bw++) {
2321                                 ru_index_tmp >>= 1;
2322                                 if (!(ru_index_tmp & 1))
2323                                         continue;
2324
2325                                 sta_ctxt_cmd.pkt_ext.pkt_ext_qam_th[i][bw][1] =
2326                                         iwl_mvm_he_get_ppe_val(ppe,
2327                                                                ppe_pos_bit);
2328                                 ppe_pos_bit +=
2329                                         IEEE80211_PPE_THRES_INFO_PPET_SIZE;
2330                                 sta_ctxt_cmd.pkt_ext.pkt_ext_qam_th[i][bw][0] =
2331                                         iwl_mvm_he_get_ppe_val(ppe,
2332                                                                ppe_pos_bit);
2333                                 ppe_pos_bit +=
2334                                         IEEE80211_PPE_THRES_INFO_PPET_SIZE;
2335                         }
2336                 }
2337
2338                 flags |= STA_CTXT_HE_PACKET_EXT;
2339         } else if ((sta->he_cap.he_cap_elem.phy_cap_info[9] &
2340                     IEEE80211_HE_PHY_CAP9_NOMIMAL_PKT_PADDING_MASK) !=
2341                   IEEE80211_HE_PHY_CAP9_NOMIMAL_PKT_PADDING_RESERVED) {
2342                 int low_th = -1;
2343                 int high_th = -1;
2344
2345                 /* Take the PPE thresholds from the nominal padding info */
2346                 switch (sta->he_cap.he_cap_elem.phy_cap_info[9] &
2347                         IEEE80211_HE_PHY_CAP9_NOMIMAL_PKT_PADDING_MASK) {
2348                 case IEEE80211_HE_PHY_CAP9_NOMIMAL_PKT_PADDING_0US:
2349                         low_th = IWL_HE_PKT_EXT_NONE;
2350                         high_th = IWL_HE_PKT_EXT_NONE;
2351                         break;
2352                 case IEEE80211_HE_PHY_CAP9_NOMIMAL_PKT_PADDING_8US:
2353                         low_th = IWL_HE_PKT_EXT_BPSK;
2354                         high_th = IWL_HE_PKT_EXT_NONE;
2355                         break;
2356                 case IEEE80211_HE_PHY_CAP9_NOMIMAL_PKT_PADDING_16US:
2357                         low_th = IWL_HE_PKT_EXT_NONE;
2358                         high_th = IWL_HE_PKT_EXT_BPSK;
2359                         break;
2360                 }
2361
2362                 /* Set the PPE thresholds accordingly */
2363                 if (low_th >= 0 && high_th >= 0) {
2364                         struct iwl_he_pkt_ext *pkt_ext =
2365                                 (struct iwl_he_pkt_ext *)&sta_ctxt_cmd.pkt_ext;
2366
2367                         for (i = 0; i < MAX_HE_SUPP_NSS; i++) {
2368                                 u8 bw;
2369
2370                                 for (bw = 0; bw < MAX_HE_CHANNEL_BW_INDX;
2371                                      bw++) {
2372                                         pkt_ext->pkt_ext_qam_th[i][bw][0] =
2373                                                 low_th;
2374                                         pkt_ext->pkt_ext_qam_th[i][bw][1] =
2375                                                 high_th;
2376                                 }
2377                         }
2378
2379                         flags |= STA_CTXT_HE_PACKET_EXT;
2380                 }
2381         }
2382         rcu_read_unlock();
2383
2384         /* Mark MU EDCA as enabled, unless none detected on some AC */
2385         flags |= STA_CTXT_HE_MU_EDCA_CW;
2386         for (i = 0; i < IEEE80211_NUM_ACS; i++) {
2387                 struct ieee80211_he_mu_edca_param_ac_rec *mu_edca =
2388                         &mvmvif->queue_params[i].mu_edca_param_rec;
2389                 u8 ac = iwl_mvm_mac80211_ac_to_ucode_ac(i);
2390
2391                 if (!mvmvif->queue_params[i].mu_edca) {
2392                         flags &= ~STA_CTXT_HE_MU_EDCA_CW;
2393                         break;
2394                 }
2395
2396                 sta_ctxt_cmd.trig_based_txf[ac].cwmin =
2397                         cpu_to_le16(mu_edca->ecw_min_max & 0xf);
2398                 sta_ctxt_cmd.trig_based_txf[ac].cwmax =
2399                         cpu_to_le16((mu_edca->ecw_min_max & 0xf0) >> 4);
2400                 sta_ctxt_cmd.trig_based_txf[ac].aifsn =
2401                         cpu_to_le16(mu_edca->aifsn);
2402                 sta_ctxt_cmd.trig_based_txf[ac].mu_time =
2403                         cpu_to_le16(mu_edca->mu_edca_timer);
2404         }
2405
2406         if (vif->bss_conf.multi_sta_back_32bit)
2407                 flags |= STA_CTXT_HE_32BIT_BA_BITMAP;
2408
2409         if (vif->bss_conf.ack_enabled)
2410                 flags |= STA_CTXT_HE_ACK_ENABLED;
2411
2412         if (vif->bss_conf.uora_exists) {
2413                 flags |= STA_CTXT_HE_TRIG_RND_ALLOC;
2414
2415                 sta_ctxt_cmd.rand_alloc_ecwmin =
2416                         vif->bss_conf.uora_ocw_range & 0x7;
2417                 sta_ctxt_cmd.rand_alloc_ecwmax =
2418                         (vif->bss_conf.uora_ocw_range >> 3) & 0x7;
2419         }
2420
2421         if (vif->bss_conf.nontransmitted) {
2422                 flags |= STA_CTXT_HE_REF_BSSID_VALID;
2423                 ether_addr_copy(sta_ctxt_cmd.ref_bssid_addr,
2424                                 vif->bss_conf.transmitter_bssid);
2425                 sta_ctxt_cmd.max_bssid_indicator =
2426                         vif->bss_conf.bssid_indicator;
2427                 sta_ctxt_cmd.bssid_index = vif->bss_conf.bssid_index;
2428                 sta_ctxt_cmd.ema_ap = vif->bss_conf.ema_ap;
2429                 sta_ctxt_cmd.profile_periodicity =
2430                         vif->bss_conf.profile_periodicity;
2431         }
2432
2433         sta_ctxt_cmd.flags = cpu_to_le32(flags);
2434
2435         if (iwl_mvm_send_cmd_pdu(mvm, iwl_cmd_id(STA_HE_CTXT_CMD,
2436                                                  DATA_PATH_GROUP, 0),
2437                                  0, size, &sta_ctxt_cmd))
2438                 IWL_ERR(mvm, "Failed to config FW to work HE!\n");
2439 }
2440
2441 static void iwl_mvm_bss_info_changed_station(struct iwl_mvm *mvm,
2442                                              struct ieee80211_vif *vif,
2443                                              struct ieee80211_bss_conf *bss_conf,
2444                                              u32 changes)
2445 {
2446         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
2447         int ret;
2448
2449         /*
2450          * Re-calculate the tsf id, as the master-slave relations depend on the
2451          * beacon interval, which was not known when the station interface was
2452          * added.
2453          */
2454         if (changes & BSS_CHANGED_ASSOC && bss_conf->assoc) {
2455                 if (vif->bss_conf.he_support &&
2456                     !iwlwifi_mod_params.disable_11ax)
2457                         iwl_mvm_cfg_he_sta(mvm, vif, mvmvif->ap_sta_id);
2458
2459                 iwl_mvm_mac_ctxt_recalc_tsf_id(mvm, vif);
2460         }
2461
2462         /* Update MU EDCA params */
2463         if (changes & BSS_CHANGED_QOS && mvmvif->associated &&
2464             bss_conf->assoc && vif->bss_conf.he_support &&
2465             !iwlwifi_mod_params.disable_11ax)
2466                 iwl_mvm_cfg_he_sta(mvm, vif, mvmvif->ap_sta_id);
2467
2468         /*
2469          * If we're not associated yet, take the (new) BSSID before associating
2470          * so the firmware knows. If we're already associated, then use the old
2471          * BSSID here, and we'll send a cleared one later in the CHANGED_ASSOC
2472          * branch for disassociation below.
2473          */
2474         if (changes & BSS_CHANGED_BSSID && !mvmvif->associated)
2475                 memcpy(mvmvif->bssid, bss_conf->bssid, ETH_ALEN);
2476
2477         ret = iwl_mvm_mac_ctxt_changed(mvm, vif, false, mvmvif->bssid);
2478         if (ret)
2479                 IWL_ERR(mvm, "failed to update MAC %pM\n", vif->addr);
2480
2481         /* after sending it once, adopt mac80211 data */
2482         memcpy(mvmvif->bssid, bss_conf->bssid, ETH_ALEN);
2483         mvmvif->associated = bss_conf->assoc;
2484
2485         if (changes & BSS_CHANGED_ASSOC) {
2486                 if (bss_conf->assoc) {
2487                         /* clear statistics to get clean beacon counter */
2488                         iwl_mvm_request_statistics(mvm, true);
2489                         memset(&mvmvif->beacon_stats, 0,
2490                                sizeof(mvmvif->beacon_stats));
2491
2492                         /* add quota for this interface */
2493                         ret = iwl_mvm_update_quotas(mvm, true, NULL);
2494                         if (ret) {
2495                                 IWL_ERR(mvm, "failed to update quotas\n");
2496                                 return;
2497                         }
2498
2499                         if (test_bit(IWL_MVM_STATUS_IN_HW_RESTART,
2500                                      &mvm->status)) {
2501                                 /*
2502                                  * If we're restarting then the firmware will
2503                                  * obviously have lost synchronisation with
2504                                  * the AP. It will attempt to synchronise by
2505                                  * itself, but we can make it more reliable by
2506                                  * scheduling a session protection time event.
2507                                  *
2508                                  * The firmware needs to receive a beacon to
2509                                  * catch up with synchronisation, use 110% of
2510                                  * the beacon interval.
2511                                  *
2512                                  * Set a large maximum delay to allow for more
2513                                  * than a single interface.
2514                                  */
2515                                 u32 dur = (11 * vif->bss_conf.beacon_int) / 10;
2516                                 iwl_mvm_protect_session(mvm, vif, dur, dur,
2517                                                         5 * dur, false);
2518                         }
2519
2520                         iwl_mvm_sf_update(mvm, vif, false);
2521                         iwl_mvm_power_vif_assoc(mvm, vif);
2522                         if (vif->p2p) {
2523                                 iwl_mvm_ref(mvm, IWL_MVM_REF_P2P_CLIENT);
2524                                 iwl_mvm_update_smps(mvm, vif,
2525                                                     IWL_MVM_SMPS_REQ_PROT,
2526                                                     IEEE80211_SMPS_DYNAMIC);
2527                         }
2528                 } else if (mvmvif->ap_sta_id != IWL_MVM_INVALID_STA) {
2529                         /*
2530                          * If update fails - SF might be running in associated
2531                          * mode while disassociated - which is forbidden.
2532                          */
2533                         ret = iwl_mvm_sf_update(mvm, vif, false);
2534                         WARN_ONCE(ret &&
2535                                   !test_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED,
2536                                             &mvm->status),
2537                                   "Failed to update SF upon disassociation\n");
2538
2539                         /*
2540                          * If we get an assert during the connection (after the
2541                          * station has been added, but before the vif is set
2542                          * to associated), mac80211 will re-add the station and
2543                          * then configure the vif. Since the vif is not
2544                          * associated, we would remove the station here and
2545                          * this would fail the recovery.
2546                          */
2547                         if (!test_bit(IWL_MVM_STATUS_IN_HW_RESTART,
2548                                       &mvm->status)) {
2549                                 /*
2550                                  * Remove AP station now that
2551                                  * the MAC is unassoc
2552                                  */
2553                                 ret = iwl_mvm_rm_sta_id(mvm, vif,
2554                                                         mvmvif->ap_sta_id);
2555                                 if (ret)
2556                                         IWL_ERR(mvm,
2557                                                 "failed to remove AP station\n");
2558
2559                                 if (mvm->d0i3_ap_sta_id == mvmvif->ap_sta_id)
2560                                         mvm->d0i3_ap_sta_id =
2561                                                 IWL_MVM_INVALID_STA;
2562                                 mvmvif->ap_sta_id = IWL_MVM_INVALID_STA;
2563                         }
2564
2565                         /* remove quota for this interface */
2566                         ret = iwl_mvm_update_quotas(mvm, false, NULL);
2567                         if (ret)
2568                                 IWL_ERR(mvm, "failed to update quotas\n");
2569
2570                         if (vif->p2p)
2571                                 iwl_mvm_unref(mvm, IWL_MVM_REF_P2P_CLIENT);
2572
2573                         /* this will take the cleared BSSID from bss_conf */
2574                         ret = iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
2575                         if (ret)
2576                                 IWL_ERR(mvm,
2577                                         "failed to update MAC %pM (clear after unassoc)\n",
2578                                         vif->addr);
2579                 }
2580
2581                 /*
2582                  * The firmware tracks the MU-MIMO group on its own.
2583                  * However, on HW restart we should restore this data.
2584                  */
2585                 if (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) &&
2586                     (changes & BSS_CHANGED_MU_GROUPS) && vif->mu_mimo_owner) {
2587                         ret = iwl_mvm_update_mu_groups(mvm, vif);
2588                         if (ret)
2589                                 IWL_ERR(mvm,
2590                                         "failed to update VHT MU_MIMO groups\n");
2591                 }
2592
2593                 iwl_mvm_recalc_multicast(mvm);
2594                 iwl_mvm_configure_bcast_filter(mvm);
2595
2596                 /* reset rssi values */
2597                 mvmvif->bf_data.ave_beacon_signal = 0;
2598
2599                 iwl_mvm_bt_coex_vif_change(mvm);
2600                 iwl_mvm_update_smps(mvm, vif, IWL_MVM_SMPS_REQ_TT,
2601                                     IEEE80211_SMPS_AUTOMATIC);
2602                 if (fw_has_capa(&mvm->fw->ucode_capa,
2603                                 IWL_UCODE_TLV_CAPA_UMAC_SCAN))
2604                         iwl_mvm_config_scan(mvm);
2605         }
2606
2607         if (changes & BSS_CHANGED_BEACON_INFO) {
2608                 /*
2609                  * We received a beacon from the associated AP so
2610                  * remove the session protection.
2611                  */
2612                 iwl_mvm_stop_session_protection(mvm, vif);
2613
2614                 iwl_mvm_sf_update(mvm, vif, false);
2615                 WARN_ON(iwl_mvm_enable_beacon_filter(mvm, vif, 0));
2616         }
2617
2618         if (changes & (BSS_CHANGED_PS | BSS_CHANGED_P2P_PS | BSS_CHANGED_QOS |
2619                        /*
2620                         * Send power command on every beacon change,
2621                         * because we may have not enabled beacon abort yet.
2622                         */
2623                        BSS_CHANGED_BEACON_INFO)) {
2624                 ret = iwl_mvm_power_update_mac(mvm);
2625                 if (ret)
2626                         IWL_ERR(mvm, "failed to update power mode\n");
2627         }
2628
2629         if (changes & BSS_CHANGED_TXPOWER) {
2630                 IWL_DEBUG_CALIB(mvm, "Changing TX Power to %d\n",
2631                                 bss_conf->txpower);
2632                 iwl_mvm_set_tx_power(mvm, vif, bss_conf->txpower);
2633         }
2634
2635         if (changes & BSS_CHANGED_CQM) {
2636                 IWL_DEBUG_MAC80211(mvm, "cqm info_changed\n");
2637                 /* reset cqm events tracking */
2638                 mvmvif->bf_data.last_cqm_event = 0;
2639                 if (mvmvif->bf_data.bf_enabled) {
2640                         ret = iwl_mvm_enable_beacon_filter(mvm, vif, 0);
2641                         if (ret)
2642                                 IWL_ERR(mvm,
2643                                         "failed to update CQM thresholds\n");
2644                 }
2645         }
2646
2647         if (changes & BSS_CHANGED_ARP_FILTER) {
2648                 IWL_DEBUG_MAC80211(mvm, "arp filter changed\n");
2649                 iwl_mvm_configure_bcast_filter(mvm);
2650         }
2651 }
2652
2653 static int iwl_mvm_start_ap_ibss(struct ieee80211_hw *hw,
2654                                  struct ieee80211_vif *vif)
2655 {
2656         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2657         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
2658         int ret, i;
2659
2660         /*
2661          * iwl_mvm_mac_ctxt_add() might read directly from the device
2662          * (the system time), so make sure it is available.
2663          */
2664         ret = iwl_mvm_ref_sync(mvm, IWL_MVM_REF_START_AP);
2665         if (ret)
2666                 return ret;
2667
2668         mutex_lock(&mvm->mutex);
2669
2670         /* Send the beacon template */
2671         ret = iwl_mvm_mac_ctxt_beacon_changed(mvm, vif);
2672         if (ret)
2673                 goto out_unlock;
2674
2675         /*
2676          * Re-calculate the tsf id, as the master-slave relations depend on the
2677          * beacon interval, which was not known when the AP interface was added.
2678          */
2679         if (vif->type == NL80211_IFTYPE_AP)
2680                 iwl_mvm_mac_ctxt_recalc_tsf_id(mvm, vif);
2681
2682         mvmvif->ap_assoc_sta_count = 0;
2683
2684         /* Add the mac context */
2685         ret = iwl_mvm_mac_ctxt_add(mvm, vif);
2686         if (ret)
2687                 goto out_unlock;
2688
2689         /* Perform the binding */
2690         ret = iwl_mvm_binding_add_vif(mvm, vif);
2691         if (ret)
2692                 goto out_remove;
2693
2694         /*
2695          * This is not very nice, but the simplest:
2696          * For older FWs adding the mcast sta before the bcast station may
2697          * cause assert 0x2b00.
2698          * This is fixed in later FW so make the order of removal depend on
2699          * the TLV
2700          */
2701         if (fw_has_api(&mvm->fw->ucode_capa, IWL_UCODE_TLV_API_STA_TYPE)) {
2702                 ret = iwl_mvm_add_mcast_sta(mvm, vif);
2703                 if (ret)
2704                         goto out_unbind;
2705                 /*
2706                  * Send the bcast station. At this stage the TBTT and DTIM time
2707                  * events are added and applied to the scheduler
2708                  */
2709                 ret = iwl_mvm_send_add_bcast_sta(mvm, vif);
2710                 if (ret) {
2711                         iwl_mvm_rm_mcast_sta(mvm, vif);
2712                         goto out_unbind;
2713                 }
2714         } else {
2715                 /*
2716                  * Send the bcast station. At this stage the TBTT and DTIM time
2717                  * events are added and applied to the scheduler
2718                  */
2719                 ret = iwl_mvm_send_add_bcast_sta(mvm, vif);
2720                 if (ret)
2721                         goto out_unbind;
2722                 ret = iwl_mvm_add_mcast_sta(mvm, vif);
2723                 if (ret) {
2724                         iwl_mvm_send_rm_bcast_sta(mvm, vif);
2725                         goto out_unbind;
2726                 }
2727         }
2728
2729         /* must be set before quota calculations */
2730         mvmvif->ap_ibss_active = true;
2731
2732         /* send all the early keys to the device now */
2733         for (i = 0; i < ARRAY_SIZE(mvmvif->ap_early_keys); i++) {
2734                 struct ieee80211_key_conf *key = mvmvif->ap_early_keys[i];
2735
2736                 if (!key)
2737                         continue;
2738
2739                 mvmvif->ap_early_keys[i] = NULL;
2740
2741                 ret = __iwl_mvm_mac_set_key(hw, SET_KEY, vif, NULL, key);
2742                 if (ret)
2743                         goto out_quota_failed;
2744         }
2745
2746         if (vif->type == NL80211_IFTYPE_AP && !vif->p2p) {
2747                 iwl_mvm_vif_set_low_latency(mvmvif, true,
2748                                             LOW_LATENCY_VIF_TYPE);
2749                 iwl_mvm_send_low_latency_cmd(mvm, true, mvmvif->id);
2750         }
2751
2752         /* power updated needs to be done before quotas */
2753         iwl_mvm_power_update_mac(mvm);
2754
2755         ret = iwl_mvm_update_quotas(mvm, false, NULL);
2756         if (ret)
2757                 goto out_quota_failed;
2758
2759         /* Need to update the P2P Device MAC (only GO, IBSS is single vif) */
2760         if (vif->p2p && mvm->p2p_device_vif)
2761                 iwl_mvm_mac_ctxt_changed(mvm, mvm->p2p_device_vif, false, NULL);
2762
2763         iwl_mvm_ref(mvm, IWL_MVM_REF_AP_IBSS);
2764
2765         iwl_mvm_bt_coex_vif_change(mvm);
2766
2767         /* we don't support TDLS during DCM */
2768         if (iwl_mvm_phy_ctx_count(mvm) > 1)
2769                 iwl_mvm_teardown_tdls_peers(mvm);
2770
2771         iwl_mvm_ftm_restart_responder(mvm, vif);
2772
2773         goto out_unlock;
2774
2775 out_quota_failed:
2776         iwl_mvm_power_update_mac(mvm);
2777         mvmvif->ap_ibss_active = false;
2778         iwl_mvm_send_rm_bcast_sta(mvm, vif);
2779         iwl_mvm_rm_mcast_sta(mvm, vif);
2780 out_unbind:
2781         iwl_mvm_binding_remove_vif(mvm, vif);
2782 out_remove:
2783         iwl_mvm_mac_ctxt_remove(mvm, vif);
2784 out_unlock:
2785         mutex_unlock(&mvm->mutex);
2786         iwl_mvm_unref(mvm, IWL_MVM_REF_START_AP);
2787         return ret;
2788 }
2789
2790 static void iwl_mvm_stop_ap_ibss(struct ieee80211_hw *hw,
2791                                  struct ieee80211_vif *vif)
2792 {
2793         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2794         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
2795
2796         iwl_mvm_prepare_mac_removal(mvm, vif);
2797
2798         mutex_lock(&mvm->mutex);
2799
2800         /* Handle AP stop while in CSA */
2801         if (rcu_access_pointer(mvm->csa_vif) == vif) {
2802                 iwl_mvm_remove_time_event(mvm, mvmvif,
2803                                           &mvmvif->time_event_data);
2804                 RCU_INIT_POINTER(mvm->csa_vif, NULL);
2805                 mvmvif->csa_countdown = false;
2806         }
2807
2808         if (rcu_access_pointer(mvm->csa_tx_blocked_vif) == vif) {
2809                 RCU_INIT_POINTER(mvm->csa_tx_blocked_vif, NULL);
2810                 mvm->csa_tx_block_bcn_timeout = 0;
2811         }
2812
2813         mvmvif->ap_ibss_active = false;
2814         mvm->ap_last_beacon_gp2 = 0;
2815
2816         if (vif->type == NL80211_IFTYPE_AP && !vif->p2p) {
2817                 iwl_mvm_vif_set_low_latency(mvmvif, false,
2818                                             LOW_LATENCY_VIF_TYPE);
2819                 iwl_mvm_send_low_latency_cmd(mvm, false,  mvmvif->id);
2820         }
2821
2822         iwl_mvm_bt_coex_vif_change(mvm);
2823
2824         iwl_mvm_unref(mvm, IWL_MVM_REF_AP_IBSS);
2825
2826         /* Need to update the P2P Device MAC (only GO, IBSS is single vif) */
2827         if (vif->p2p && mvm->p2p_device_vif)
2828                 iwl_mvm_mac_ctxt_changed(mvm, mvm->p2p_device_vif, false, NULL);
2829
2830         iwl_mvm_update_quotas(mvm, false, NULL);
2831
2832         /*
2833          * This is not very nice, but the simplest:
2834          * For older FWs removing the mcast sta before the bcast station may
2835          * cause assert 0x2b00.
2836          * This is fixed in later FW (which will stop beaconing when removing
2837          * bcast station).
2838          * So make the order of removal depend on the TLV
2839          */
2840         if (!fw_has_api(&mvm->fw->ucode_capa, IWL_UCODE_TLV_API_STA_TYPE))
2841                 iwl_mvm_rm_mcast_sta(mvm, vif);
2842         iwl_mvm_send_rm_bcast_sta(mvm, vif);
2843         if (fw_has_api(&mvm->fw->ucode_capa, IWL_UCODE_TLV_API_STA_TYPE))
2844                 iwl_mvm_rm_mcast_sta(mvm, vif);
2845         iwl_mvm_binding_remove_vif(mvm, vif);
2846
2847         iwl_mvm_power_update_mac(mvm);
2848
2849         iwl_mvm_mac_ctxt_remove(mvm, vif);
2850
2851         mutex_unlock(&mvm->mutex);
2852 }
2853
2854 static void
2855 iwl_mvm_bss_info_changed_ap_ibss(struct iwl_mvm *mvm,
2856                                  struct ieee80211_vif *vif,
2857                                  struct ieee80211_bss_conf *bss_conf,
2858                                  u32 changes)
2859 {
2860         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
2861
2862         /* Changes will be applied when the AP/IBSS is started */
2863         if (!mvmvif->ap_ibss_active)
2864                 return;
2865
2866         if (changes & (BSS_CHANGED_ERP_CTS_PROT | BSS_CHANGED_HT |
2867                        BSS_CHANGED_BANDWIDTH | BSS_CHANGED_QOS) &&
2868             iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL))
2869                 IWL_ERR(mvm, "failed to update MAC %pM\n", vif->addr);
2870
2871         /* Need to send a new beacon template to the FW */
2872         if (changes & BSS_CHANGED_BEACON &&
2873             iwl_mvm_mac_ctxt_beacon_changed(mvm, vif))
2874                 IWL_WARN(mvm, "Failed updating beacon data\n");
2875
2876         if (changes & BSS_CHANGED_TXPOWER) {
2877                 IWL_DEBUG_CALIB(mvm, "Changing TX Power to %d\n",
2878                                 bss_conf->txpower);
2879                 iwl_mvm_set_tx_power(mvm, vif, bss_conf->txpower);
2880         }
2881
2882         if (changes & BSS_CHANGED_FTM_RESPONDER) {
2883                 int ret = iwl_mvm_ftm_start_responder(mvm, vif);
2884
2885                 if (ret)
2886                         IWL_WARN(mvm, "Failed to enable FTM responder (%d)\n",
2887                                  ret);
2888         }
2889
2890 }
2891
2892 static void iwl_mvm_bss_info_changed(struct ieee80211_hw *hw,
2893                                      struct ieee80211_vif *vif,
2894                                      struct ieee80211_bss_conf *bss_conf,
2895                                      u32 changes)
2896 {
2897         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2898
2899         /*
2900          * iwl_mvm_bss_info_changed_station() might call
2901          * iwl_mvm_protect_session(), which reads directly from
2902          * the device (the system time), so make sure it is available.
2903          */
2904         if (iwl_mvm_ref_sync(mvm, IWL_MVM_REF_BSS_CHANGED))
2905                 return;
2906
2907         mutex_lock(&mvm->mutex);
2908
2909         if (changes & BSS_CHANGED_IDLE && !bss_conf->idle)
2910                 iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_SCHED, true);
2911
2912         switch (vif->type) {
2913         case NL80211_IFTYPE_STATION:
2914                 iwl_mvm_bss_info_changed_station(mvm, vif, bss_conf, changes);
2915                 break;
2916         case NL80211_IFTYPE_AP:
2917         case NL80211_IFTYPE_ADHOC:
2918                 iwl_mvm_bss_info_changed_ap_ibss(mvm, vif, bss_conf, changes);
2919                 break;
2920         case NL80211_IFTYPE_MONITOR:
2921                 if (changes & BSS_CHANGED_MU_GROUPS)
2922                         iwl_mvm_update_mu_groups(mvm, vif);
2923                 break;
2924         default:
2925                 /* shouldn't happen */
2926                 WARN_ON_ONCE(1);
2927         }
2928
2929         mutex_unlock(&mvm->mutex);
2930         iwl_mvm_unref(mvm, IWL_MVM_REF_BSS_CHANGED);
2931 }
2932
2933 static int iwl_mvm_mac_hw_scan(struct ieee80211_hw *hw,
2934                                struct ieee80211_vif *vif,
2935                                struct ieee80211_scan_request *hw_req)
2936 {
2937         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2938         int ret;
2939
2940         if (hw_req->req.n_channels == 0 ||
2941             hw_req->req.n_channels > mvm->fw->ucode_capa.n_scan_channels)
2942                 return -EINVAL;
2943
2944         mutex_lock(&mvm->mutex);
2945         ret = iwl_mvm_reg_scan_start(mvm, vif, &hw_req->req, &hw_req->ies);
2946         mutex_unlock(&mvm->mutex);
2947
2948         return ret;
2949 }
2950
2951 static void iwl_mvm_mac_cancel_hw_scan(struct ieee80211_hw *hw,
2952                                        struct ieee80211_vif *vif)
2953 {
2954         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2955
2956         mutex_lock(&mvm->mutex);
2957
2958         /* Due to a race condition, it's possible that mac80211 asks
2959          * us to stop a hw_scan when it's already stopped.  This can
2960          * happen, for instance, if we stopped the scan ourselves,
2961          * called ieee80211_scan_completed() and the userspace called
2962          * cancel scan scan before ieee80211_scan_work() could run.
2963          * To handle that, simply return if the scan is not running.
2964         */
2965         if (mvm->scan_status & IWL_MVM_SCAN_REGULAR)
2966                 iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_REGULAR, true);
2967
2968         mutex_unlock(&mvm->mutex);
2969 }
2970
2971 static void
2972 iwl_mvm_mac_allow_buffered_frames(struct ieee80211_hw *hw,
2973                                   struct ieee80211_sta *sta, u16 tids,
2974                                   int num_frames,
2975                                   enum ieee80211_frame_release_type reason,
2976                                   bool more_data)
2977 {
2978         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2979
2980         /* Called when we need to transmit (a) frame(s) from mac80211 */
2981
2982         iwl_mvm_sta_modify_sleep_tx_count(mvm, sta, reason, num_frames,
2983                                           tids, more_data, false);
2984 }
2985
2986 static void
2987 iwl_mvm_mac_release_buffered_frames(struct ieee80211_hw *hw,
2988                                     struct ieee80211_sta *sta, u16 tids,
2989                                     int num_frames,
2990                                     enum ieee80211_frame_release_type reason,
2991                                     bool more_data)
2992 {
2993         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
2994
2995         /* Called when we need to transmit (a) frame(s) from agg or dqa queue */
2996
2997         iwl_mvm_sta_modify_sleep_tx_count(mvm, sta, reason, num_frames,
2998                                           tids, more_data, true);
2999 }
3000
3001 static void __iwl_mvm_mac_sta_notify(struct ieee80211_hw *hw,
3002                                      enum sta_notify_cmd cmd,
3003                                      struct ieee80211_sta *sta)
3004 {
3005         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3006         struct iwl_mvm_sta *mvmsta = iwl_mvm_sta_from_mac80211(sta);
3007         unsigned long txqs = 0, tids = 0;
3008         int tid;
3009
3010         /*
3011          * If we have TVQM then we get too high queue numbers - luckily
3012          * we really shouldn't get here with that because such hardware
3013          * should have firmware supporting buffer station offload.
3014          */
3015         if (WARN_ON(iwl_mvm_has_new_tx_api(mvm)))
3016                 return;
3017
3018         spin_lock_bh(&mvmsta->lock);
3019         for (tid = 0; tid < ARRAY_SIZE(mvmsta->tid_data); tid++) {
3020                 struct iwl_mvm_tid_data *tid_data = &mvmsta->tid_data[tid];
3021
3022                 if (tid_data->txq_id == IWL_MVM_INVALID_QUEUE)
3023                         continue;
3024
3025                 __set_bit(tid_data->txq_id, &txqs);
3026
3027                 if (iwl_mvm_tid_queued(mvm, tid_data) == 0)
3028                         continue;
3029
3030                 __set_bit(tid, &tids);
3031         }
3032
3033         switch (cmd) {
3034         case STA_NOTIFY_SLEEP:
3035                 for_each_set_bit(tid, &tids, IWL_MAX_TID_COUNT)
3036                         ieee80211_sta_set_buffered(sta, tid, true);
3037
3038                 if (txqs)
3039                         iwl_trans_freeze_txq_timer(mvm->trans, txqs, true);
3040                 /*
3041                  * The fw updates the STA to be asleep. Tx packets on the Tx
3042                  * queues to this station will not be transmitted. The fw will
3043                  * send a Tx response with TX_STATUS_FAIL_DEST_PS.
3044                  */
3045                 break;
3046         case STA_NOTIFY_AWAKE:
3047                 if (WARN_ON(mvmsta->sta_id == IWL_MVM_INVALID_STA))
3048                         break;
3049
3050                 if (txqs)
3051                         iwl_trans_freeze_txq_timer(mvm->trans, txqs, false);
3052                 iwl_mvm_sta_modify_ps_wake(mvm, sta);
3053                 break;
3054         default:
3055                 break;
3056         }
3057         spin_unlock_bh(&mvmsta->lock);
3058 }
3059
3060 static void iwl_mvm_mac_sta_notify(struct ieee80211_hw *hw,
3061                                    struct ieee80211_vif *vif,
3062                                    enum sta_notify_cmd cmd,
3063                                    struct ieee80211_sta *sta)
3064 {
3065         __iwl_mvm_mac_sta_notify(hw, cmd, sta);
3066 }
3067
3068 void iwl_mvm_sta_pm_notif(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb)
3069 {
3070         struct iwl_rx_packet *pkt = rxb_addr(rxb);
3071         struct iwl_mvm_pm_state_notification *notif = (void *)pkt->data;
3072         struct ieee80211_sta *sta;
3073         struct iwl_mvm_sta *mvmsta;
3074         bool sleeping = (notif->type != IWL_MVM_PM_EVENT_AWAKE);
3075
3076         if (WARN_ON(notif->sta_id >= ARRAY_SIZE(mvm->fw_id_to_mac_id)))
3077                 return;
3078
3079         rcu_read_lock();
3080         sta = rcu_dereference(mvm->fw_id_to_mac_id[notif->sta_id]);
3081         if (WARN_ON(IS_ERR_OR_NULL(sta))) {
3082                 rcu_read_unlock();
3083                 return;
3084         }
3085
3086         mvmsta = iwl_mvm_sta_from_mac80211(sta);
3087
3088         if (!mvmsta->vif ||
3089             mvmsta->vif->type != NL80211_IFTYPE_AP) {
3090                 rcu_read_unlock();
3091                 return;
3092         }
3093
3094         if (mvmsta->sleeping != sleeping) {
3095                 mvmsta->sleeping = sleeping;
3096                 __iwl_mvm_mac_sta_notify(mvm->hw,
3097                         sleeping ? STA_NOTIFY_SLEEP : STA_NOTIFY_AWAKE,
3098                         sta);
3099                 ieee80211_sta_ps_transition(sta, sleeping);
3100         }
3101
3102         if (sleeping) {
3103                 switch (notif->type) {
3104                 case IWL_MVM_PM_EVENT_AWAKE:
3105                 case IWL_MVM_PM_EVENT_ASLEEP:
3106                         break;
3107                 case IWL_MVM_PM_EVENT_UAPSD:
3108                         ieee80211_sta_uapsd_trigger(sta, IEEE80211_NUM_TIDS);
3109                         break;
3110                 case IWL_MVM_PM_EVENT_PS_POLL:
3111                         ieee80211_sta_pspoll(sta);
3112                         break;
3113                 default:
3114                         break;
3115                 }
3116         }
3117
3118         rcu_read_unlock();
3119 }
3120
3121 static void iwl_mvm_sta_pre_rcu_remove(struct ieee80211_hw *hw,
3122                                        struct ieee80211_vif *vif,
3123                                        struct ieee80211_sta *sta)
3124 {
3125         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3126         struct iwl_mvm_sta *mvm_sta = iwl_mvm_sta_from_mac80211(sta);
3127
3128         /*
3129          * This is called before mac80211 does RCU synchronisation,
3130          * so here we already invalidate our internal RCU-protected
3131          * station pointer. The rest of the code will thus no longer
3132          * be able to find the station this way, and we don't rely
3133          * on further RCU synchronisation after the sta_state()
3134          * callback deleted the station.
3135          */
3136         mutex_lock(&mvm->mutex);
3137         if (sta == rcu_access_pointer(mvm->fw_id_to_mac_id[mvm_sta->sta_id]))
3138                 rcu_assign_pointer(mvm->fw_id_to_mac_id[mvm_sta->sta_id],
3139                                    ERR_PTR(-ENOENT));
3140
3141         mutex_unlock(&mvm->mutex);
3142 }
3143
3144 static void iwl_mvm_check_uapsd(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
3145                                 const u8 *bssid)
3146 {
3147         int i;
3148
3149         if (!test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status)) {
3150                 struct iwl_mvm_tcm_mac *mdata;
3151
3152                 mdata = &mvm->tcm.data[iwl_mvm_vif_from_mac80211(vif)->id];
3153                 ewma_rate_init(&mdata->uapsd_nonagg_detect.rate);
3154                 mdata->opened_rx_ba_sessions = false;
3155         }
3156
3157         if (!(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_UAPSD_SUPPORT))
3158                 return;
3159
3160         if (vif->p2p && !iwl_mvm_is_p2p_scm_uapsd_supported(mvm)) {
3161                 vif->driver_flags &= ~IEEE80211_VIF_SUPPORTS_UAPSD;
3162                 return;
3163         }
3164
3165         if (!vif->p2p &&
3166             (iwlwifi_mod_params.uapsd_disable & IWL_DISABLE_UAPSD_BSS)) {
3167                 vif->driver_flags &= ~IEEE80211_VIF_SUPPORTS_UAPSD;
3168                 return;
3169         }
3170
3171         for (i = 0; i < IWL_MVM_UAPSD_NOAGG_LIST_LEN; i++) {
3172                 if (ether_addr_equal(mvm->uapsd_noagg_bssids[i].addr, bssid)) {
3173                         vif->driver_flags &= ~IEEE80211_VIF_SUPPORTS_UAPSD;
3174                         return;
3175                 }
3176         }
3177
3178         vif->driver_flags |= IEEE80211_VIF_SUPPORTS_UAPSD;
3179 }
3180
3181 static void
3182 iwl_mvm_tdls_check_trigger(struct iwl_mvm *mvm,
3183                            struct ieee80211_vif *vif, u8 *peer_addr,
3184                            enum nl80211_tdls_operation action)
3185 {
3186         struct iwl_fw_dbg_trigger_tlv *trig;
3187         struct iwl_fw_dbg_trigger_tdls *tdls_trig;
3188
3189         trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
3190                                      FW_DBG_TRIGGER_TDLS);
3191         if (!trig)
3192                 return;
3193
3194         tdls_trig = (void *)trig->data;
3195
3196         if (!(tdls_trig->action_bitmap & BIT(action)))
3197                 return;
3198
3199         if (tdls_trig->peer_mode &&
3200             memcmp(tdls_trig->peer, peer_addr, ETH_ALEN) != 0)
3201                 return;
3202
3203         iwl_fw_dbg_collect_trig(&mvm->fwrt, trig,
3204                                 "TDLS event occurred, peer %pM, action %d",
3205                                 peer_addr, action);
3206 }
3207
3208 static int iwl_mvm_mac_sta_state(struct ieee80211_hw *hw,
3209                                  struct ieee80211_vif *vif,
3210                                  struct ieee80211_sta *sta,
3211                                  enum ieee80211_sta_state old_state,
3212                                  enum ieee80211_sta_state new_state)
3213 {
3214         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3215         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
3216         struct iwl_mvm_sta *mvm_sta = iwl_mvm_sta_from_mac80211(sta);
3217         int ret;
3218
3219         IWL_DEBUG_MAC80211(mvm, "station %pM state change %d->%d\n",
3220                            sta->addr, old_state, new_state);
3221
3222         /* this would be a mac80211 bug ... but don't crash */
3223         if (WARN_ON_ONCE(!mvmvif->phy_ctxt))
3224                 return -EINVAL;
3225
3226         /*
3227          * If we are in a STA removal flow and in DQA mode:
3228          *
3229          * This is after the sync_rcu part, so the queues have already been
3230          * flushed. No more TXs on their way in mac80211's path, and no more in
3231          * the queues.
3232          * Also, we won't be getting any new TX frames for this station.
3233          * What we might have are deferred TX frames that need to be taken care
3234          * of.
3235          *
3236          * Drop any still-queued deferred-frame before removing the STA, and
3237          * make sure the worker is no longer handling frames for this STA.
3238          */
3239         if (old_state == IEEE80211_STA_NONE &&
3240             new_state == IEEE80211_STA_NOTEXIST) {
3241                 flush_work(&mvm->add_stream_wk);
3242
3243                 /*
3244                  * No need to make sure deferred TX indication is off since the
3245                  * worker will already remove it if it was on
3246                  */
3247         }
3248
3249         mutex_lock(&mvm->mutex);
3250         /* track whether or not the station is associated */
3251         mvm_sta->sta_state = new_state;
3252
3253         if (old_state == IEEE80211_STA_NOTEXIST &&
3254             new_state == IEEE80211_STA_NONE) {
3255                 /*
3256                  * Firmware bug - it'll crash if the beacon interval is less
3257                  * than 16. We can't avoid connecting at all, so refuse the
3258                  * station state change, this will cause mac80211 to abandon
3259                  * attempts to connect to this AP, and eventually wpa_s will
3260                  * blacklist the AP...
3261                  */
3262                 if (vif->type == NL80211_IFTYPE_STATION &&
3263                     vif->bss_conf.beacon_int < 16) {
3264                         IWL_ERR(mvm,
3265                                 "AP %pM beacon interval is %d, refusing due to firmware bug!\n",
3266                                 sta->addr, vif->bss_conf.beacon_int);
3267                         ret = -EINVAL;
3268                         goto out_unlock;
3269                 }
3270
3271                 if (sta->tdls &&
3272                     (vif->p2p ||
3273                      iwl_mvm_tdls_sta_count(mvm, NULL) ==
3274                                                 IWL_MVM_TDLS_STA_COUNT ||
3275                      iwl_mvm_phy_ctx_count(mvm) > 1)) {
3276                         IWL_DEBUG_MAC80211(mvm, "refusing TDLS sta\n");
3277                         ret = -EBUSY;
3278                         goto out_unlock;
3279                 }
3280
3281                 ret = iwl_mvm_add_sta(mvm, vif, sta);
3282                 if (sta->tdls && ret == 0) {
3283                         iwl_mvm_recalc_tdls_state(mvm, vif, true);
3284                         iwl_mvm_tdls_check_trigger(mvm, vif, sta->addr,
3285                                                    NL80211_TDLS_SETUP);
3286                 }
3287
3288                 sta->max_rc_amsdu_len = 1;
3289         } else if (old_state == IEEE80211_STA_NONE &&
3290                    new_state == IEEE80211_STA_AUTH) {
3291                 /*
3292                  * EBS may be disabled due to previous failures reported by FW.
3293                  * Reset EBS status here assuming environment has been changed.
3294                  */
3295                 mvm->last_ebs_successful = true;
3296                 iwl_mvm_check_uapsd(mvm, vif, sta->addr);
3297                 ret = 0;
3298         } else if (old_state == IEEE80211_STA_AUTH &&
3299                    new_state == IEEE80211_STA_ASSOC) {
3300                 if (vif->type == NL80211_IFTYPE_AP) {
3301                         vif->bss_conf.he_support = sta->he_cap.has_he;
3302                         mvmvif->ap_assoc_sta_count++;
3303                         iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
3304                         if (vif->bss_conf.he_support &&
3305                             !iwlwifi_mod_params.disable_11ax)
3306                                 iwl_mvm_cfg_he_sta(mvm, vif, mvm_sta->sta_id);
3307                 } else if (vif->type == NL80211_IFTYPE_STATION) {
3308                         vif->bss_conf.he_support = sta->he_cap.has_he;
3309                         iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
3310                 }
3311
3312                 iwl_mvm_rs_rate_init(mvm, sta, mvmvif->phy_ctxt->channel->band,
3313                                      false);
3314                 ret = iwl_mvm_update_sta(mvm, vif, sta);
3315         } else if (old_state == IEEE80211_STA_ASSOC &&
3316                    new_state == IEEE80211_STA_AUTHORIZED) {
3317                 ret = 0;
3318
3319                 /* we don't support TDLS during DCM */
3320                 if (iwl_mvm_phy_ctx_count(mvm) > 1)
3321                         iwl_mvm_teardown_tdls_peers(mvm);
3322
3323                 if (sta->tdls)
3324                         iwl_mvm_tdls_check_trigger(mvm, vif, sta->addr,
3325                                                    NL80211_TDLS_ENABLE_LINK);
3326
3327                 /* enable beacon filtering */
3328                 WARN_ON(iwl_mvm_enable_beacon_filter(mvm, vif, 0));
3329
3330                 /*
3331                  * Now that the station is authorized, i.e., keys were already
3332                  * installed, need to indicate to the FW that
3333                  * multicast data frames can be forwarded to the driver
3334                  */
3335                 iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
3336
3337                 iwl_mvm_rs_rate_init(mvm, sta, mvmvif->phy_ctxt->channel->band,
3338                                      true);
3339         } else if (old_state == IEEE80211_STA_AUTHORIZED &&
3340                    new_state == IEEE80211_STA_ASSOC) {
3341                 /* Multicast data frames are no longer allowed */
3342                 iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
3343
3344                 /* disable beacon filtering */
3345                 ret = iwl_mvm_disable_beacon_filter(mvm, vif, 0);
3346                 WARN_ON(ret &&
3347                         !test_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED,
3348                                   &mvm->status));
3349                 ret = 0;
3350         } else if (old_state == IEEE80211_STA_ASSOC &&
3351                    new_state == IEEE80211_STA_AUTH) {
3352                 if (vif->type == NL80211_IFTYPE_AP) {
3353                         mvmvif->ap_assoc_sta_count--;
3354                         iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
3355                 }
3356                 ret = 0;
3357         } else if (old_state == IEEE80211_STA_AUTH &&
3358                    new_state == IEEE80211_STA_NONE) {
3359                 ret = 0;
3360         } else if (old_state == IEEE80211_STA_NONE &&
3361                    new_state == IEEE80211_STA_NOTEXIST) {
3362                 ret = iwl_mvm_rm_sta(mvm, vif, sta);
3363                 if (sta->tdls) {
3364                         iwl_mvm_recalc_tdls_state(mvm, vif, false);
3365                         iwl_mvm_tdls_check_trigger(mvm, vif, sta->addr,
3366                                                    NL80211_TDLS_DISABLE_LINK);
3367                 }
3368
3369                 if (unlikely(ret &&
3370                              test_bit(IWL_MVM_STATUS_HW_RESTART_REQUESTED,
3371                                       &mvm->status)))
3372                         ret = 0;
3373         } else {
3374                 ret = -EIO;
3375         }
3376  out_unlock:
3377         mutex_unlock(&mvm->mutex);
3378
3379         if (sta->tdls && ret == 0) {
3380                 if (old_state == IEEE80211_STA_NOTEXIST &&
3381                     new_state == IEEE80211_STA_NONE)
3382                         ieee80211_reserve_tid(sta, IWL_MVM_TDLS_FW_TID);
3383                 else if (old_state == IEEE80211_STA_NONE &&
3384                          new_state == IEEE80211_STA_NOTEXIST)
3385                         ieee80211_unreserve_tid(sta, IWL_MVM_TDLS_FW_TID);
3386         }
3387
3388         return ret;
3389 }
3390
3391 static int iwl_mvm_mac_set_rts_threshold(struct ieee80211_hw *hw, u32 value)
3392 {
3393         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3394
3395         mvm->rts_threshold = value;
3396
3397         return 0;
3398 }
3399
3400 static void iwl_mvm_sta_rc_update(struct ieee80211_hw *hw,
3401                                   struct ieee80211_vif *vif,
3402                                   struct ieee80211_sta *sta, u32 changed)
3403 {
3404         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3405         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
3406
3407         if (changed & (IEEE80211_RC_BW_CHANGED |
3408                        IEEE80211_RC_SUPP_RATES_CHANGED |
3409                        IEEE80211_RC_NSS_CHANGED))
3410                 iwl_mvm_rs_rate_init(mvm, sta, mvmvif->phy_ctxt->channel->band,
3411                                      true);
3412
3413         if (vif->type == NL80211_IFTYPE_STATION &&
3414             changed & IEEE80211_RC_NSS_CHANGED)
3415                 iwl_mvm_sf_update(mvm, vif, false);
3416 }
3417
3418 static int iwl_mvm_mac_conf_tx(struct ieee80211_hw *hw,
3419                                struct ieee80211_vif *vif, u16 ac,
3420                                const struct ieee80211_tx_queue_params *params)
3421 {
3422         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3423         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
3424
3425         mvmvif->queue_params[ac] = *params;
3426
3427         /*
3428          * No need to update right away, we'll get BSS_CHANGED_QOS
3429          * The exception is P2P_DEVICE interface which needs immediate update.
3430          */
3431         if (vif->type == NL80211_IFTYPE_P2P_DEVICE) {
3432                 int ret;
3433
3434                 mutex_lock(&mvm->mutex);
3435                 ret = iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
3436                 mutex_unlock(&mvm->mutex);
3437                 return ret;
3438         }
3439         return 0;
3440 }
3441
3442 static void iwl_mvm_mac_mgd_prepare_tx(struct ieee80211_hw *hw,
3443                                        struct ieee80211_vif *vif,
3444                                        u16 req_duration)
3445 {
3446         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3447         u32 duration = IWL_MVM_TE_SESSION_PROTECTION_MAX_TIME_MS;
3448         u32 min_duration = IWL_MVM_TE_SESSION_PROTECTION_MIN_TIME_MS;
3449
3450         /*
3451          * iwl_mvm_protect_session() reads directly from the device
3452          * (the system time), so make sure it is available.
3453          */
3454         if (iwl_mvm_ref_sync(mvm, IWL_MVM_REF_PREPARE_TX))
3455                 return;
3456
3457         if (req_duration > duration)
3458                 duration = req_duration;
3459
3460         mutex_lock(&mvm->mutex);
3461         /* Try really hard to protect the session and hear a beacon */
3462         iwl_mvm_protect_session(mvm, vif, duration, min_duration, 500, false);
3463         mutex_unlock(&mvm->mutex);
3464
3465         iwl_mvm_unref(mvm, IWL_MVM_REF_PREPARE_TX);
3466 }
3467
3468 static int iwl_mvm_mac_sched_scan_start(struct ieee80211_hw *hw,
3469                                         struct ieee80211_vif *vif,
3470                                         struct cfg80211_sched_scan_request *req,
3471                                         struct ieee80211_scan_ies *ies)
3472 {
3473         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3474
3475         int ret;
3476
3477         mutex_lock(&mvm->mutex);
3478
3479         if (!vif->bss_conf.idle) {
3480                 ret = -EBUSY;
3481                 goto out;
3482         }
3483
3484         ret = iwl_mvm_sched_scan_start(mvm, vif, req, ies, IWL_MVM_SCAN_SCHED);
3485
3486 out:
3487         mutex_unlock(&mvm->mutex);
3488         return ret;
3489 }
3490
3491 static int iwl_mvm_mac_sched_scan_stop(struct ieee80211_hw *hw,
3492                                        struct ieee80211_vif *vif)
3493 {
3494         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3495         int ret;
3496
3497         mutex_lock(&mvm->mutex);
3498
3499         /* Due to a race condition, it's possible that mac80211 asks
3500          * us to stop a sched_scan when it's already stopped.  This
3501          * can happen, for instance, if we stopped the scan ourselves,
3502          * called ieee80211_sched_scan_stopped() and the userspace called
3503          * stop sched scan scan before ieee80211_sched_scan_stopped_work()
3504          * could run.  To handle this, simply return if the scan is
3505          * not running.
3506         */
3507         if (!(mvm->scan_status & IWL_MVM_SCAN_SCHED)) {
3508                 mutex_unlock(&mvm->mutex);
3509                 return 0;
3510         }
3511
3512         ret = iwl_mvm_scan_stop(mvm, IWL_MVM_SCAN_SCHED, false);
3513         mutex_unlock(&mvm->mutex);
3514         iwl_mvm_wait_for_async_handlers(mvm);
3515
3516         return ret;
3517 }
3518
3519 static int __iwl_mvm_mac_set_key(struct ieee80211_hw *hw,
3520                                  enum set_key_cmd cmd,
3521                                  struct ieee80211_vif *vif,
3522                                  struct ieee80211_sta *sta,
3523                                  struct ieee80211_key_conf *key)
3524 {
3525         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
3526         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3527         struct iwl_mvm_sta *mvmsta;
3528         struct iwl_mvm_key_pn *ptk_pn;
3529         int keyidx = key->keyidx;
3530         int ret, i;
3531         u8 key_offset;
3532
3533         if (iwlwifi_mod_params.swcrypto) {
3534                 IWL_DEBUG_MAC80211(mvm, "leave - hwcrypto disabled\n");
3535                 return -EOPNOTSUPP;
3536         }
3537
3538         switch (key->cipher) {
3539         case WLAN_CIPHER_SUITE_TKIP:
3540                 if (!mvm->trans->cfg->gen2) {
3541                         key->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC;
3542                         key->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE;
3543                 } else if (vif->type == NL80211_IFTYPE_STATION) {
3544                         key->flags |= IEEE80211_KEY_FLAG_PUT_MIC_SPACE;
3545                 } else {
3546                         IWL_DEBUG_MAC80211(mvm, "Use SW encryption for TKIP\n");
3547                         return -EOPNOTSUPP;
3548                 }
3549                 break;
3550         case WLAN_CIPHER_SUITE_CCMP:
3551         case WLAN_CIPHER_SUITE_GCMP:
3552         case WLAN_CIPHER_SUITE_GCMP_256:
3553                 if (!iwl_mvm_has_new_tx_api(mvm))
3554                         key->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE;
3555                 break;
3556         case WLAN_CIPHER_SUITE_AES_CMAC:
3557         case WLAN_CIPHER_SUITE_BIP_GMAC_128:
3558         case WLAN_CIPHER_SUITE_BIP_GMAC_256:
3559                 WARN_ON_ONCE(!ieee80211_hw_check(hw, MFP_CAPABLE));
3560                 break;
3561         case WLAN_CIPHER_SUITE_WEP40:
3562         case WLAN_CIPHER_SUITE_WEP104:
3563                 if (vif->type == NL80211_IFTYPE_STATION)
3564                         break;
3565                 if (iwl_mvm_has_new_tx_api(mvm))
3566                         return -EOPNOTSUPP;
3567                 /* support HW crypto on TX */
3568                 return 0;
3569         default:
3570                 /* currently FW supports only one optional cipher scheme */
3571                 if (hw->n_cipher_schemes &&
3572                     hw->cipher_schemes->cipher == key->cipher)
3573                         key->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE;
3574                 else
3575                         return -EOPNOTSUPP;
3576         }
3577
3578         switch (cmd) {
3579         case SET_KEY:
3580                 if ((vif->type == NL80211_IFTYPE_ADHOC ||
3581                      vif->type == NL80211_IFTYPE_AP) && !sta) {
3582                         /*
3583                          * GTK on AP interface is a TX-only key, return 0;
3584                          * on IBSS they're per-station and because we're lazy
3585                          * we don't support them for RX, so do the same.
3586                          * CMAC/GMAC in AP/IBSS modes must be done in software.
3587                          */
3588                         if (key->cipher == WLAN_CIPHER_SUITE_AES_CMAC ||
3589                             key->cipher == WLAN_CIPHER_SUITE_BIP_GMAC_128 ||
3590                             key->cipher == WLAN_CIPHER_SUITE_BIP_GMAC_256)
3591                                 ret = -EOPNOTSUPP;
3592                         else
3593                                 ret = 0;
3594
3595                         if (key->cipher != WLAN_CIPHER_SUITE_GCMP &&
3596                             key->cipher != WLAN_CIPHER_SUITE_GCMP_256 &&
3597                             !iwl_mvm_has_new_tx_api(mvm)) {
3598                                 key->hw_key_idx = STA_KEY_IDX_INVALID;
3599                                 break;
3600                         }
3601
3602                         if (!mvmvif->ap_ibss_active) {
3603                                 for (i = 0;
3604                                      i < ARRAY_SIZE(mvmvif->ap_early_keys);
3605                                      i++) {
3606                                         if (!mvmvif->ap_early_keys[i]) {
3607                                                 mvmvif->ap_early_keys[i] = key;
3608                                                 break;
3609                                         }
3610                                 }
3611
3612                                 if (i >= ARRAY_SIZE(mvmvif->ap_early_keys))
3613                                         ret = -ENOSPC;
3614
3615                                 break;
3616                         }
3617                 }
3618
3619                 /* During FW restart, in order to restore the state as it was,
3620                  * don't try to reprogram keys we previously failed for.
3621                  */
3622                 if (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) &&
3623                     key->hw_key_idx == STA_KEY_IDX_INVALID) {
3624                         IWL_DEBUG_MAC80211(mvm,
3625                                            "skip invalid idx key programming during restart\n");
3626                         ret = 0;
3627                         break;
3628                 }
3629
3630                 if (!test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status) &&
3631                     sta && iwl_mvm_has_new_rx_api(mvm) &&
3632                     key->flags & IEEE80211_KEY_FLAG_PAIRWISE &&
3633                     (key->cipher == WLAN_CIPHER_SUITE_CCMP ||
3634                      key->cipher == WLAN_CIPHER_SUITE_GCMP ||
3635                      key->cipher == WLAN_CIPHER_SUITE_GCMP_256)) {
3636                         struct ieee80211_key_seq seq;
3637                         int tid, q;
3638
3639                         mvmsta = iwl_mvm_sta_from_mac80211(sta);
3640                         WARN_ON(rcu_access_pointer(mvmsta->ptk_pn[keyidx]));
3641                         ptk_pn = kzalloc(struct_size(ptk_pn, q,
3642                                                      mvm->trans->num_rx_queues),
3643                                          GFP_KERNEL);
3644                         if (!ptk_pn) {
3645                                 ret = -ENOMEM;
3646                                 break;
3647                         }
3648
3649                         for (tid = 0; tid < IWL_MAX_TID_COUNT; tid++) {
3650                                 ieee80211_get_key_rx_seq(key, tid, &seq);
3651                                 for (q = 0; q < mvm->trans->num_rx_queues; q++)
3652                                         memcpy(ptk_pn->q[q].pn[tid],
3653                                                seq.ccmp.pn,
3654                                                IEEE80211_CCMP_PN_LEN);
3655                         }
3656
3657                         rcu_assign_pointer(mvmsta->ptk_pn[keyidx], ptk_pn);
3658                 }
3659
3660                 /* in HW restart reuse the index, otherwise request a new one */
3661                 if (test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status))
3662                         key_offset = key->hw_key_idx;
3663                 else
3664                         key_offset = STA_KEY_IDX_INVALID;
3665
3666                 IWL_DEBUG_MAC80211(mvm, "set hwcrypto key\n");
3667                 ret = iwl_mvm_set_sta_key(mvm, vif, sta, key, key_offset);
3668                 if (ret) {
3669                         IWL_WARN(mvm, "set key failed\n");
3670                         key->hw_key_idx = STA_KEY_IDX_INVALID;
3671                         /*
3672                          * can't add key for RX, but we don't need it
3673                          * in the device for TX so still return 0,
3674                          * unless we have new TX API where we cannot
3675                          * put key material into the TX_CMD
3676                          */
3677                         if (iwl_mvm_has_new_tx_api(mvm))
3678                                 ret = -EOPNOTSUPP;
3679                         else
3680                                 ret = 0;
3681                 }
3682
3683                 break;
3684         case DISABLE_KEY:
3685                 ret = -ENOENT;
3686                 for (i = 0; i < ARRAY_SIZE(mvmvif->ap_early_keys); i++) {
3687                         if (mvmvif->ap_early_keys[i] == key) {
3688                                 mvmvif->ap_early_keys[i] = NULL;
3689                                 ret = 0;
3690                         }
3691                 }
3692
3693                 /* found in pending list - don't do anything else */
3694                 if (ret == 0)
3695                         break;
3696
3697                 if (key->hw_key_idx == STA_KEY_IDX_INVALID) {
3698                         ret = 0;
3699                         break;
3700                 }
3701
3702                 if (sta && iwl_mvm_has_new_rx_api(mvm) &&
3703                     key->flags & IEEE80211_KEY_FLAG_PAIRWISE &&
3704                     (key->cipher == WLAN_CIPHER_SUITE_CCMP ||
3705                      key->cipher == WLAN_CIPHER_SUITE_GCMP ||
3706                      key->cipher == WLAN_CIPHER_SUITE_GCMP_256)) {
3707                         mvmsta = iwl_mvm_sta_from_mac80211(sta);
3708                         ptk_pn = rcu_dereference_protected(
3709                                                 mvmsta->ptk_pn[keyidx],
3710                                                 lockdep_is_held(&mvm->mutex));
3711                         RCU_INIT_POINTER(mvmsta->ptk_pn[keyidx], NULL);
3712                         if (ptk_pn)
3713                                 kfree_rcu(ptk_pn, rcu_head);
3714                 }
3715
3716                 IWL_DEBUG_MAC80211(mvm, "disable hwcrypto key\n");
3717                 ret = iwl_mvm_remove_sta_key(mvm, vif, sta, key);
3718                 break;
3719         default:
3720                 ret = -EINVAL;
3721         }
3722
3723         return ret;
3724 }
3725
3726 static int iwl_mvm_mac_set_key(struct ieee80211_hw *hw,
3727                                enum set_key_cmd cmd,
3728                                struct ieee80211_vif *vif,
3729                                struct ieee80211_sta *sta,
3730                                struct ieee80211_key_conf *key)
3731 {
3732         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3733         int ret;
3734
3735         mutex_lock(&mvm->mutex);
3736         ret = __iwl_mvm_mac_set_key(hw, cmd, vif, sta, key);
3737         mutex_unlock(&mvm->mutex);
3738
3739         return ret;
3740 }
3741
3742 static void iwl_mvm_mac_update_tkip_key(struct ieee80211_hw *hw,
3743                                         struct ieee80211_vif *vif,
3744                                         struct ieee80211_key_conf *keyconf,
3745                                         struct ieee80211_sta *sta,
3746                                         u32 iv32, u16 *phase1key)
3747 {
3748         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3749
3750         if (keyconf->hw_key_idx == STA_KEY_IDX_INVALID)
3751                 return;
3752
3753         iwl_mvm_update_tkip_key(mvm, vif, keyconf, sta, iv32, phase1key);
3754 }
3755
3756
3757 static bool iwl_mvm_rx_aux_roc(struct iwl_notif_wait_data *notif_wait,
3758                                struct iwl_rx_packet *pkt, void *data)
3759 {
3760         struct iwl_mvm *mvm =
3761                 container_of(notif_wait, struct iwl_mvm, notif_wait);
3762         struct iwl_hs20_roc_res *resp;
3763         int resp_len = iwl_rx_packet_payload_len(pkt);
3764         struct iwl_mvm_time_event_data *te_data = data;
3765
3766         if (WARN_ON(pkt->hdr.cmd != HOT_SPOT_CMD))
3767                 return true;
3768
3769         if (WARN_ON_ONCE(resp_len != sizeof(*resp))) {
3770                 IWL_ERR(mvm, "Invalid HOT_SPOT_CMD response\n");
3771                 return true;
3772         }
3773
3774         resp = (void *)pkt->data;
3775
3776         IWL_DEBUG_TE(mvm,
3777                      "Aux ROC: Received response from ucode: status=%d uid=%d\n",
3778                      resp->status, resp->event_unique_id);
3779
3780         te_data->uid = le32_to_cpu(resp->event_unique_id);
3781         IWL_DEBUG_TE(mvm, "TIME_EVENT_CMD response - UID = 0x%x\n",
3782                      te_data->uid);
3783
3784         spin_lock_bh(&mvm->time_event_lock);
3785         list_add_tail(&te_data->list, &mvm->aux_roc_te_list);
3786         spin_unlock_bh(&mvm->time_event_lock);
3787
3788         return true;
3789 }
3790
3791 #define AUX_ROC_MIN_DURATION MSEC_TO_TU(100)
3792 #define AUX_ROC_MIN_DELAY MSEC_TO_TU(200)
3793 #define AUX_ROC_MAX_DELAY MSEC_TO_TU(600)
3794 #define AUX_ROC_SAFETY_BUFFER MSEC_TO_TU(20)
3795 #define AUX_ROC_MIN_SAFETY_BUFFER MSEC_TO_TU(10)
3796 static int iwl_mvm_send_aux_roc_cmd(struct iwl_mvm *mvm,
3797                                     struct ieee80211_channel *channel,
3798                                     struct ieee80211_vif *vif,
3799                                     int duration)
3800 {
3801         int res;
3802         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
3803         struct iwl_mvm_time_event_data *te_data = &mvmvif->hs_time_event_data;
3804         static const u16 time_event_response[] = { HOT_SPOT_CMD };
3805         struct iwl_notification_wait wait_time_event;
3806         u32 dtim_interval = vif->bss_conf.dtim_period *
3807                 vif->bss_conf.beacon_int;
3808         u32 req_dur, delay;
3809         struct iwl_hs20_roc_req aux_roc_req = {
3810                 .action = cpu_to_le32(FW_CTXT_ACTION_ADD),
3811                 .id_and_color =
3812                         cpu_to_le32(FW_CMD_ID_AND_COLOR(MAC_INDEX_AUX, 0)),
3813                 .sta_id_and_color = cpu_to_le32(mvm->aux_sta.sta_id),
3814         };
3815         struct iwl_hs20_roc_req_tail *tail = iwl_mvm_chan_info_cmd_tail(mvm,
3816                 &aux_roc_req.channel_info);
3817         u16 len = sizeof(aux_roc_req) - iwl_mvm_chan_info_padding(mvm);
3818
3819         /* Set the channel info data */
3820         iwl_mvm_set_chan_info(mvm, &aux_roc_req.channel_info, channel->hw_value,
3821                               (channel->band == NL80211_BAND_2GHZ) ?
3822                                PHY_BAND_24 : PHY_BAND_5,
3823                               PHY_VHT_CHANNEL_MODE20,
3824                               0);
3825
3826         /* Set the time and duration */
3827         tail->apply_time = cpu_to_le32(iwl_mvm_get_systime(mvm));
3828
3829         delay = AUX_ROC_MIN_DELAY;
3830         req_dur = MSEC_TO_TU(duration);
3831
3832         /*
3833          * If we are associated we want the delay time to be at least one
3834          * dtim interval so that the FW can wait until after the DTIM and
3835          * then start the time event, this will potentially allow us to
3836          * remain off-channel for the max duration.
3837          * Since we want to use almost a whole dtim interval we would also
3838          * like the delay to be for 2-3 dtim intervals, in case there are
3839          * other time events with higher priority.
3840          */
3841         if (vif->bss_conf.assoc) {
3842                 delay = min_t(u32, dtim_interval * 3, AUX_ROC_MAX_DELAY);
3843                 /* We cannot remain off-channel longer than the DTIM interval */
3844                 if (dtim_interval <= req_dur) {
3845                         req_dur = dtim_interval - AUX_ROC_SAFETY_BUFFER;
3846                         if (req_dur <= AUX_ROC_MIN_DURATION)
3847                                 req_dur = dtim_interval -
3848                                         AUX_ROC_MIN_SAFETY_BUFFER;
3849                 }
3850         }
3851
3852         tail->duration = cpu_to_le32(req_dur);
3853         tail->apply_time_max_delay = cpu_to_le32(delay);
3854
3855         IWL_DEBUG_TE(mvm,
3856                      "ROC: Requesting to remain on channel %u for %ums (requested = %ums, max_delay = %ums, dtim_interval = %ums)\n",
3857                      channel->hw_value, req_dur, duration, delay,
3858                      dtim_interval);
3859         /* Set the node address */
3860         memcpy(tail->node_addr, vif->addr, ETH_ALEN);
3861
3862         lockdep_assert_held(&mvm->mutex);
3863
3864         spin_lock_bh(&mvm->time_event_lock);
3865
3866         if (WARN_ON(te_data->id == HOT_SPOT_CMD)) {
3867                 spin_unlock_bh(&mvm->time_event_lock);
3868                 return -EIO;
3869         }
3870
3871         te_data->vif = vif;
3872         te_data->duration = duration;
3873         te_data->id = HOT_SPOT_CMD;
3874
3875         spin_unlock_bh(&mvm->time_event_lock);
3876
3877         /*
3878          * Use a notification wait, which really just processes the
3879          * command response and doesn't wait for anything, in order
3880          * to be able to process the response and get the UID inside
3881          * the RX path. Using CMD_WANT_SKB doesn't work because it
3882          * stores the buffer and then wakes up this thread, by which
3883          * time another notification (that the time event started)
3884          * might already be processed unsuccessfully.
3885          */
3886         iwl_init_notification_wait(&mvm->notif_wait, &wait_time_event,
3887                                    time_event_response,
3888                                    ARRAY_SIZE(time_event_response),
3889                                    iwl_mvm_rx_aux_roc, te_data);
3890
3891         res = iwl_mvm_send_cmd_pdu(mvm, HOT_SPOT_CMD, 0, len,
3892                                    &aux_roc_req);
3893
3894         if (res) {
3895                 IWL_ERR(mvm, "Couldn't send HOT_SPOT_CMD: %d\n", res);
3896                 iwl_remove_notification(&mvm->notif_wait, &wait_time_event);
3897                 goto out_clear_te;
3898         }
3899
3900         /* No need to wait for anything, so just pass 1 (0 isn't valid) */
3901         res = iwl_wait_notification(&mvm->notif_wait, &wait_time_event, 1);
3902         /* should never fail */
3903         WARN_ON_ONCE(res);
3904
3905         if (res) {
3906  out_clear_te:
3907                 spin_lock_bh(&mvm->time_event_lock);
3908                 iwl_mvm_te_clear_data(mvm, te_data);
3909                 spin_unlock_bh(&mvm->time_event_lock);
3910         }
3911
3912         return res;
3913 }
3914
3915 static int iwl_mvm_roc(struct ieee80211_hw *hw,
3916                        struct ieee80211_vif *vif,
3917                        struct ieee80211_channel *channel,
3918                        int duration,
3919                        enum ieee80211_roc_type type)
3920 {
3921         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
3922         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
3923         struct cfg80211_chan_def chandef;
3924         struct iwl_mvm_phy_ctxt *phy_ctxt;
3925         int ret, i;
3926
3927         IWL_DEBUG_MAC80211(mvm, "enter (%d, %d, %d)\n", channel->hw_value,
3928                            duration, type);
3929
3930         /*
3931          * Flush the done work, just in case it's still pending, so that
3932          * the work it does can complete and we can accept new frames.
3933          */
3934         flush_work(&mvm->roc_done_wk);
3935
3936         mutex_lock(&mvm->mutex);
3937
3938         switch (vif->type) {
3939         case NL80211_IFTYPE_STATION:
3940                 if (fw_has_capa(&mvm->fw->ucode_capa,
3941                                 IWL_UCODE_TLV_CAPA_HOTSPOT_SUPPORT)) {
3942                         /* Use aux roc framework (HS20) */
3943                         ret = iwl_mvm_send_aux_roc_cmd(mvm, channel,
3944                                                        vif, duration);
3945                         goto out_unlock;
3946                 }
3947                 IWL_ERR(mvm, "hotspot not supported\n");
3948                 ret = -EINVAL;
3949                 goto out_unlock;
3950         case NL80211_IFTYPE_P2P_DEVICE:
3951                 /* handle below */
3952                 break;
3953         default:
3954                 IWL_ERR(mvm, "vif isn't P2P_DEVICE: %d\n", vif->type);
3955                 ret = -EINVAL;
3956                 goto out_unlock;
3957         }
3958
3959         for (i = 0; i < NUM_PHY_CTX; i++) {
3960                 phy_ctxt = &mvm->phy_ctxts[i];
3961                 if (phy_ctxt->ref == 0 || mvmvif->phy_ctxt == phy_ctxt)
3962                         continue;
3963
3964                 if (phy_ctxt->ref && channel == phy_ctxt->channel) {
3965                         /*
3966                          * Unbind the P2P_DEVICE from the current PHY context,
3967                          * and if the PHY context is not used remove it.
3968                          */
3969                         ret = iwl_mvm_binding_remove_vif(mvm, vif);
3970                         if (WARN(ret, "Failed unbinding P2P_DEVICE\n"))
3971                                 goto out_unlock;
3972
3973                         iwl_mvm_phy_ctxt_unref(mvm, mvmvif->phy_ctxt);
3974
3975                         /* Bind the P2P_DEVICE to the current PHY Context */
3976                         mvmvif->phy_ctxt = phy_ctxt;
3977
3978                         ret = iwl_mvm_binding_add_vif(mvm, vif);
3979                         if (WARN(ret, "Failed binding P2P_DEVICE\n"))
3980                                 goto out_unlock;
3981
3982                         iwl_mvm_phy_ctxt_ref(mvm, mvmvif->phy_ctxt);
3983                         goto schedule_time_event;
3984                 }
3985         }
3986
3987         /* Need to update the PHY context only if the ROC channel changed */
3988         if (channel == mvmvif->phy_ctxt->channel)
3989                 goto schedule_time_event;
3990
3991         cfg80211_chandef_create(&chandef, channel, NL80211_CHAN_NO_HT);
3992
3993         /*
3994          * Change the PHY context configuration as it is currently referenced
3995          * only by the P2P Device MAC
3996          */
3997         if (mvmvif->phy_ctxt->ref == 1) {
3998                 ret = iwl_mvm_phy_ctxt_changed(mvm, mvmvif->phy_ctxt,
3999                                                &chandef, 1, 1);
4000                 if (ret)
4001                         goto out_unlock;
4002         } else {
4003                 /*
4004                  * The PHY context is shared with other MACs. Need to remove the
4005                  * P2P Device from the binding, allocate an new PHY context and
4006                  * create a new binding
4007                  */
4008                 phy_ctxt = iwl_mvm_get_free_phy_ctxt(mvm);
4009                 if (!phy_ctxt) {
4010                         ret = -ENOSPC;
4011                         goto out_unlock;
4012                 }
4013
4014                 ret = iwl_mvm_phy_ctxt_changed(mvm, phy_ctxt, &chandef,
4015                                                1, 1);
4016                 if (ret) {
4017                         IWL_ERR(mvm, "Failed to change PHY context\n");
4018                         goto out_unlock;
4019                 }
4020
4021                 /* Unbind the P2P_DEVICE from the current PHY context */
4022                 ret = iwl_mvm_binding_remove_vif(mvm, vif);
4023                 if (WARN(ret, "Failed unbinding P2P_DEVICE\n"))
4024                         goto out_unlock;
4025
4026                 iwl_mvm_phy_ctxt_unref(mvm, mvmvif->phy_ctxt);
4027
4028                 /* Bind the P2P_DEVICE to the new allocated PHY context */
4029                 mvmvif->phy_ctxt = phy_ctxt;
4030
4031                 ret = iwl_mvm_binding_add_vif(mvm, vif);
4032                 if (WARN(ret, "Failed binding P2P_DEVICE\n"))
4033                         goto out_unlock;
4034
4035                 iwl_mvm_phy_ctxt_ref(mvm, mvmvif->phy_ctxt);
4036         }
4037
4038 schedule_time_event:
4039         /* Schedule the time events */
4040         ret = iwl_mvm_start_p2p_roc(mvm, vif, duration, type);
4041
4042 out_unlock:
4043         mutex_unlock(&mvm->mutex);
4044         IWL_DEBUG_MAC80211(mvm, "leave\n");
4045         return ret;
4046 }
4047
4048 static int iwl_mvm_cancel_roc(struct ieee80211_hw *hw)
4049 {
4050         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4051
4052         IWL_DEBUG_MAC80211(mvm, "enter\n");
4053
4054         mutex_lock(&mvm->mutex);
4055         iwl_mvm_stop_roc(mvm);
4056         mutex_unlock(&mvm->mutex);
4057
4058         IWL_DEBUG_MAC80211(mvm, "leave\n");
4059         return 0;
4060 }
4061
4062 struct iwl_mvm_ftm_responder_iter_data {
4063         bool responder;
4064         struct ieee80211_chanctx_conf *ctx;
4065 };
4066
4067 static void iwl_mvm_ftm_responder_chanctx_iter(void *_data, u8 *mac,
4068                                                struct ieee80211_vif *vif)
4069 {
4070         struct iwl_mvm_ftm_responder_iter_data *data = _data;
4071
4072         if (rcu_access_pointer(vif->chanctx_conf) == data->ctx &&
4073             vif->type == NL80211_IFTYPE_AP && vif->bss_conf.ftmr_params)
4074                 data->responder = true;
4075 }
4076
4077 static bool iwl_mvm_is_ftm_responder_chanctx(struct iwl_mvm *mvm,
4078                                              struct ieee80211_chanctx_conf *ctx)
4079 {
4080         struct iwl_mvm_ftm_responder_iter_data data = {
4081                 .responder = false,
4082                 .ctx = ctx,
4083         };
4084
4085         ieee80211_iterate_active_interfaces_atomic(mvm->hw,
4086                                         IEEE80211_IFACE_ITER_NORMAL,
4087                                         iwl_mvm_ftm_responder_chanctx_iter,
4088                                         &data);
4089         return data.responder;
4090 }
4091
4092 static int __iwl_mvm_add_chanctx(struct iwl_mvm *mvm,
4093                                  struct ieee80211_chanctx_conf *ctx)
4094 {
4095         u16 *phy_ctxt_id = (u16 *)ctx->drv_priv;
4096         struct iwl_mvm_phy_ctxt *phy_ctxt;
4097         bool responder = iwl_mvm_is_ftm_responder_chanctx(mvm, ctx);
4098         struct cfg80211_chan_def *def = responder ? &ctx->def : &ctx->min_def;
4099         int ret;
4100
4101         lockdep_assert_held(&mvm->mutex);
4102
4103         IWL_DEBUG_MAC80211(mvm, "Add channel context\n");
4104
4105         phy_ctxt = iwl_mvm_get_free_phy_ctxt(mvm);
4106         if (!phy_ctxt) {
4107                 ret = -ENOSPC;
4108                 goto out;
4109         }
4110
4111         ret = iwl_mvm_phy_ctxt_changed(mvm, phy_ctxt, def,
4112                                        ctx->rx_chains_static,
4113                                        ctx->rx_chains_dynamic);
4114         if (ret) {
4115                 IWL_ERR(mvm, "Failed to add PHY context\n");
4116                 goto out;
4117         }
4118
4119         iwl_mvm_phy_ctxt_ref(mvm, phy_ctxt);
4120         *phy_ctxt_id = phy_ctxt->id;
4121 out:
4122         return ret;
4123 }
4124
4125 static int iwl_mvm_add_chanctx(struct ieee80211_hw *hw,
4126                                struct ieee80211_chanctx_conf *ctx)
4127 {
4128         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4129         int ret;
4130
4131         mutex_lock(&mvm->mutex);
4132         ret = __iwl_mvm_add_chanctx(mvm, ctx);
4133         mutex_unlock(&mvm->mutex);
4134
4135         return ret;
4136 }
4137
4138 static void __iwl_mvm_remove_chanctx(struct iwl_mvm *mvm,
4139                                      struct ieee80211_chanctx_conf *ctx)
4140 {
4141         u16 *phy_ctxt_id = (u16 *)ctx->drv_priv;
4142         struct iwl_mvm_phy_ctxt *phy_ctxt = &mvm->phy_ctxts[*phy_ctxt_id];
4143
4144         lockdep_assert_held(&mvm->mutex);
4145
4146         iwl_mvm_phy_ctxt_unref(mvm, phy_ctxt);
4147 }
4148
4149 static void iwl_mvm_remove_chanctx(struct ieee80211_hw *hw,
4150                                    struct ieee80211_chanctx_conf *ctx)
4151 {
4152         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4153
4154         mutex_lock(&mvm->mutex);
4155         __iwl_mvm_remove_chanctx(mvm, ctx);
4156         mutex_unlock(&mvm->mutex);
4157 }
4158
4159 static void iwl_mvm_change_chanctx(struct ieee80211_hw *hw,
4160                                    struct ieee80211_chanctx_conf *ctx,
4161                                    u32 changed)
4162 {
4163         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4164         u16 *phy_ctxt_id = (u16 *)ctx->drv_priv;
4165         struct iwl_mvm_phy_ctxt *phy_ctxt = &mvm->phy_ctxts[*phy_ctxt_id];
4166         bool responder = iwl_mvm_is_ftm_responder_chanctx(mvm, ctx);
4167         struct cfg80211_chan_def *def = responder ? &ctx->def : &ctx->min_def;
4168
4169         if (WARN_ONCE((phy_ctxt->ref > 1) &&
4170                       (changed & ~(IEEE80211_CHANCTX_CHANGE_WIDTH |
4171                                    IEEE80211_CHANCTX_CHANGE_RX_CHAINS |
4172                                    IEEE80211_CHANCTX_CHANGE_RADAR |
4173                                    IEEE80211_CHANCTX_CHANGE_MIN_WIDTH)),
4174                       "Cannot change PHY. Ref=%d, changed=0x%X\n",
4175                       phy_ctxt->ref, changed))
4176                 return;
4177
4178         mutex_lock(&mvm->mutex);
4179
4180         /* we are only changing the min_width, may be a noop */
4181         if (changed == IEEE80211_CHANCTX_CHANGE_MIN_WIDTH) {
4182                 if (phy_ctxt->width == def->width)
4183                         goto out_unlock;
4184
4185                 /* we are just toggling between 20_NOHT and 20 */
4186                 if (phy_ctxt->width <= NL80211_CHAN_WIDTH_20 &&
4187                     def->width <= NL80211_CHAN_WIDTH_20)
4188                         goto out_unlock;
4189         }
4190
4191         iwl_mvm_bt_coex_vif_change(mvm);
4192         iwl_mvm_phy_ctxt_changed(mvm, phy_ctxt, def,
4193                                  ctx->rx_chains_static,
4194                                  ctx->rx_chains_dynamic);
4195
4196 out_unlock:
4197         mutex_unlock(&mvm->mutex);
4198 }
4199
4200 static int __iwl_mvm_assign_vif_chanctx(struct iwl_mvm *mvm,
4201                                         struct ieee80211_vif *vif,
4202                                         struct ieee80211_chanctx_conf *ctx,
4203                                         bool switching_chanctx)
4204 {
4205         u16 *phy_ctxt_id = (u16 *)ctx->drv_priv;
4206         struct iwl_mvm_phy_ctxt *phy_ctxt = &mvm->phy_ctxts[*phy_ctxt_id];
4207         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
4208         int ret;
4209
4210         lockdep_assert_held(&mvm->mutex);
4211
4212         mvmvif->phy_ctxt = phy_ctxt;
4213
4214         switch (vif->type) {
4215         case NL80211_IFTYPE_AP:
4216                 /* only needed if we're switching chanctx (i.e. during CSA) */
4217                 if (switching_chanctx) {
4218                         mvmvif->ap_ibss_active = true;
4219                         break;
4220                 }
4221                 /* fall through */
4222         case NL80211_IFTYPE_ADHOC:
4223                 /*
4224                  * The AP binding flow is handled as part of the start_ap flow
4225                  * (in bss_info_changed), similarly for IBSS.
4226                  */
4227                 ret = 0;
4228                 goto out;
4229         case NL80211_IFTYPE_STATION:
4230                 mvmvif->csa_bcn_pending = false;
4231                 break;
4232         case NL80211_IFTYPE_MONITOR:
4233                 /* always disable PS when a monitor interface is active */
4234                 mvmvif->ps_disabled = true;
4235                 break;
4236         default:
4237                 ret = -EINVAL;
4238                 goto out;
4239         }
4240
4241         ret = iwl_mvm_binding_add_vif(mvm, vif);
4242         if (ret)
4243                 goto out;
4244
4245         /*
4246          * Power state must be updated before quotas,
4247          * otherwise fw will complain.
4248          */
4249         iwl_mvm_power_update_mac(mvm);
4250
4251         /* Setting the quota at this stage is only required for monitor
4252          * interfaces. For the other types, the bss_info changed flow
4253          * will handle quota settings.
4254          */
4255         if (vif->type == NL80211_IFTYPE_MONITOR) {
4256                 mvmvif->monitor_active = true;
4257                 ret = iwl_mvm_update_quotas(mvm, false, NULL);
4258                 if (ret)
4259                         goto out_remove_binding;
4260
4261                 ret = iwl_mvm_add_snif_sta(mvm, vif);
4262                 if (ret)
4263                         goto out_remove_binding;
4264
4265         }
4266
4267         /* Handle binding during CSA */
4268         if (vif->type == NL80211_IFTYPE_AP) {
4269                 iwl_mvm_update_quotas(mvm, false, NULL);
4270                 iwl_mvm_mac_ctxt_changed(mvm, vif, false, NULL);
4271         }
4272
4273         if (switching_chanctx && vif->type == NL80211_IFTYPE_STATION) {
4274                 mvmvif->csa_bcn_pending = true;
4275
4276                 if (!fw_has_capa(&mvm->fw->ucode_capa,
4277                                  IWL_UCODE_TLV_CAPA_CHANNEL_SWITCH_CMD)) {
4278                         u32 duration = 3 * vif->bss_conf.beacon_int;
4279
4280
4281                         /* iwl_mvm_protect_session() reads directly from the
4282                          * device (the system time), so make sure it is
4283                          * available.
4284                          */
4285                         ret = iwl_mvm_ref_sync(mvm, IWL_MVM_REF_PROTECT_CSA);
4286                         if (ret)
4287                                 goto out_remove_binding;
4288
4289                         /* Protect the session to make sure we hear the first
4290                          * beacon on the new channel.
4291                          */
4292                         iwl_mvm_protect_session(mvm, vif, duration, duration,
4293                                                 vif->bss_conf.beacon_int / 2,
4294                                                 true);
4295
4296                         iwl_mvm_unref(mvm, IWL_MVM_REF_PROTECT_CSA);
4297                 }
4298
4299                 iwl_mvm_update_quotas(mvm, false, NULL);
4300         }
4301
4302         goto out;
4303
4304 out_remove_binding:
4305         iwl_mvm_binding_remove_vif(mvm, vif);
4306         iwl_mvm_power_update_mac(mvm);
4307 out:
4308         if (ret)
4309                 mvmvif->phy_ctxt = NULL;
4310         return ret;
4311 }
4312 static int iwl_mvm_assign_vif_chanctx(struct ieee80211_hw *hw,
4313                                       struct ieee80211_vif *vif,
4314                                       struct ieee80211_chanctx_conf *ctx)
4315 {
4316         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4317         int ret;
4318
4319         mutex_lock(&mvm->mutex);
4320         ret = __iwl_mvm_assign_vif_chanctx(mvm, vif, ctx, false);
4321         mutex_unlock(&mvm->mutex);
4322
4323         return ret;
4324 }
4325
4326 static void __iwl_mvm_unassign_vif_chanctx(struct iwl_mvm *mvm,
4327                                            struct ieee80211_vif *vif,
4328                                            struct ieee80211_chanctx_conf *ctx,
4329                                            bool switching_chanctx)
4330 {
4331         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
4332         struct ieee80211_vif *disabled_vif = NULL;
4333
4334         lockdep_assert_held(&mvm->mutex);
4335
4336         iwl_mvm_remove_time_event(mvm, mvmvif, &mvmvif->time_event_data);
4337
4338         switch (vif->type) {
4339         case NL80211_IFTYPE_ADHOC:
4340                 goto out;
4341         case NL80211_IFTYPE_MONITOR:
4342                 mvmvif->monitor_active = false;
4343                 mvmvif->ps_disabled = false;
4344                 iwl_mvm_rm_snif_sta(mvm, vif);
4345                 break;
4346         case NL80211_IFTYPE_AP:
4347                 /* This part is triggered only during CSA */
4348                 if (!switching_chanctx || !mvmvif->ap_ibss_active)
4349                         goto out;
4350
4351                 mvmvif->csa_countdown = false;
4352
4353                 /* Set CS bit on all the stations */
4354                 iwl_mvm_modify_all_sta_disable_tx(mvm, mvmvif, true);
4355
4356                 /* Save blocked iface, the timeout is set on the next beacon */
4357                 rcu_assign_pointer(mvm->csa_tx_blocked_vif, vif);
4358
4359                 mvmvif->ap_ibss_active = false;
4360                 break;
4361         case NL80211_IFTYPE_STATION:
4362                 if (!switching_chanctx)
4363                         break;
4364
4365                 disabled_vif = vif;
4366
4367                 if (!fw_has_capa(&mvm->fw->ucode_capa,
4368                                  IWL_UCODE_TLV_CAPA_CHANNEL_SWITCH_CMD))
4369                         iwl_mvm_mac_ctxt_changed(mvm, vif, true, NULL);
4370                 break;
4371         default:
4372                 break;
4373         }
4374
4375         iwl_mvm_update_quotas(mvm, false, disabled_vif);
4376         iwl_mvm_binding_remove_vif(mvm, vif);
4377
4378 out:
4379         mvmvif->phy_ctxt = NULL;
4380         iwl_mvm_power_update_mac(mvm);
4381 }
4382
4383 static void iwl_mvm_unassign_vif_chanctx(struct ieee80211_hw *hw,
4384                                          struct ieee80211_vif *vif,
4385                                          struct ieee80211_chanctx_conf *ctx)
4386 {
4387         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4388
4389         mutex_lock(&mvm->mutex);
4390         __iwl_mvm_unassign_vif_chanctx(mvm, vif, ctx, false);
4391         mutex_unlock(&mvm->mutex);
4392 }
4393
4394 static int
4395 iwl_mvm_switch_vif_chanctx_swap(struct iwl_mvm *mvm,
4396                                 struct ieee80211_vif_chanctx_switch *vifs)
4397 {
4398         int ret;
4399
4400         mutex_lock(&mvm->mutex);
4401         __iwl_mvm_unassign_vif_chanctx(mvm, vifs[0].vif, vifs[0].old_ctx, true);
4402         __iwl_mvm_remove_chanctx(mvm, vifs[0].old_ctx);
4403
4404         ret = __iwl_mvm_add_chanctx(mvm, vifs[0].new_ctx);
4405         if (ret) {
4406                 IWL_ERR(mvm, "failed to add new_ctx during channel switch\n");
4407                 goto out_reassign;
4408         }
4409
4410         ret = __iwl_mvm_assign_vif_chanctx(mvm, vifs[0].vif, vifs[0].new_ctx,
4411                                            true);
4412         if (ret) {
4413                 IWL_ERR(mvm,
4414                         "failed to assign new_ctx during channel switch\n");
4415                 goto out_remove;
4416         }
4417
4418         /* we don't support TDLS during DCM - can be caused by channel switch */
4419         if (iwl_mvm_phy_ctx_count(mvm) > 1)
4420                 iwl_mvm_teardown_tdls_peers(mvm);
4421
4422         goto out;
4423
4424 out_remove:
4425         __iwl_mvm_remove_chanctx(mvm, vifs[0].new_ctx);
4426
4427 out_reassign:
4428         if (__iwl_mvm_add_chanctx(mvm, vifs[0].old_ctx)) {
4429                 IWL_ERR(mvm, "failed to add old_ctx back after failure.\n");
4430                 goto out_restart;
4431         }
4432
4433         if (__iwl_mvm_assign_vif_chanctx(mvm, vifs[0].vif, vifs[0].old_ctx,
4434                                          true)) {
4435                 IWL_ERR(mvm, "failed to reassign old_ctx after failure.\n");
4436                 goto out_restart;
4437         }
4438
4439         goto out;
4440
4441 out_restart:
4442         /* things keep failing, better restart the hw */
4443         iwl_mvm_nic_restart(mvm, false);
4444
4445 out:
4446         mutex_unlock(&mvm->mutex);
4447
4448         return ret;
4449 }
4450
4451 static int
4452 iwl_mvm_switch_vif_chanctx_reassign(struct iwl_mvm *mvm,
4453                                     struct ieee80211_vif_chanctx_switch *vifs)
4454 {
4455         int ret;
4456
4457         mutex_lock(&mvm->mutex);
4458         __iwl_mvm_unassign_vif_chanctx(mvm, vifs[0].vif, vifs[0].old_ctx, true);
4459
4460         ret = __iwl_mvm_assign_vif_chanctx(mvm, vifs[0].vif, vifs[0].new_ctx,
4461                                            true);
4462         if (ret) {
4463                 IWL_ERR(mvm,
4464                         "failed to assign new_ctx during channel switch\n");
4465                 goto out_reassign;
4466         }
4467
4468         goto out;
4469
4470 out_reassign:
4471         if (__iwl_mvm_assign_vif_chanctx(mvm, vifs[0].vif, vifs[0].old_ctx,
4472                                          true)) {
4473                 IWL_ERR(mvm, "failed to reassign old_ctx after failure.\n");
4474                 goto out_restart;
4475         }
4476
4477         goto out;
4478
4479 out_restart:
4480         /* things keep failing, better restart the hw */
4481         iwl_mvm_nic_restart(mvm, false);
4482
4483 out:
4484         mutex_unlock(&mvm->mutex);
4485
4486         return ret;
4487 }
4488
4489 static int iwl_mvm_switch_vif_chanctx(struct ieee80211_hw *hw,
4490                                       struct ieee80211_vif_chanctx_switch *vifs,
4491                                       int n_vifs,
4492                                       enum ieee80211_chanctx_switch_mode mode)
4493 {
4494         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4495         int ret;
4496
4497         /* we only support a single-vif right now */
4498         if (n_vifs > 1)
4499                 return -EOPNOTSUPP;
4500
4501         switch (mode) {
4502         case CHANCTX_SWMODE_SWAP_CONTEXTS:
4503                 ret = iwl_mvm_switch_vif_chanctx_swap(mvm, vifs);
4504                 break;
4505         case CHANCTX_SWMODE_REASSIGN_VIF:
4506                 ret = iwl_mvm_switch_vif_chanctx_reassign(mvm, vifs);
4507                 break;
4508         default:
4509                 ret = -EOPNOTSUPP;
4510                 break;
4511         }
4512
4513         return ret;
4514 }
4515
4516 static int iwl_mvm_tx_last_beacon(struct ieee80211_hw *hw)
4517 {
4518         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4519
4520         return mvm->ibss_manager;
4521 }
4522
4523 static int iwl_mvm_set_tim(struct ieee80211_hw *hw,
4524                            struct ieee80211_sta *sta,
4525                            bool set)
4526 {
4527         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4528         struct iwl_mvm_sta *mvm_sta = iwl_mvm_sta_from_mac80211(sta);
4529
4530         if (!mvm_sta || !mvm_sta->vif) {
4531                 IWL_ERR(mvm, "Station is not associated to a vif\n");
4532                 return -EINVAL;
4533         }
4534
4535         return iwl_mvm_mac_ctxt_beacon_changed(mvm, mvm_sta->vif);
4536 }
4537
4538 #ifdef CONFIG_NL80211_TESTMODE
4539 static const struct nla_policy iwl_mvm_tm_policy[IWL_MVM_TM_ATTR_MAX + 1] = {
4540         [IWL_MVM_TM_ATTR_CMD] = { .type = NLA_U32 },
4541         [IWL_MVM_TM_ATTR_NOA_DURATION] = { .type = NLA_U32 },
4542         [IWL_MVM_TM_ATTR_BEACON_FILTER_STATE] = { .type = NLA_U32 },
4543 };
4544
4545 static int __iwl_mvm_mac_testmode_cmd(struct iwl_mvm *mvm,
4546                                       struct ieee80211_vif *vif,
4547                                       void *data, int len)
4548 {
4549         struct nlattr *tb[IWL_MVM_TM_ATTR_MAX + 1];
4550         int err;
4551         u32 noa_duration;
4552
4553         err = nla_parse_deprecated(tb, IWL_MVM_TM_ATTR_MAX, data, len,
4554                                    iwl_mvm_tm_policy, NULL);
4555         if (err)
4556                 return err;
4557
4558         if (!tb[IWL_MVM_TM_ATTR_CMD])
4559                 return -EINVAL;
4560
4561         switch (nla_get_u32(tb[IWL_MVM_TM_ATTR_CMD])) {
4562         case IWL_MVM_TM_CMD_SET_NOA:
4563                 if (!vif || vif->type != NL80211_IFTYPE_AP || !vif->p2p ||
4564                     !vif->bss_conf.enable_beacon ||
4565                     !tb[IWL_MVM_TM_ATTR_NOA_DURATION])
4566                         return -EINVAL;
4567
4568                 noa_duration = nla_get_u32(tb[IWL_MVM_TM_ATTR_NOA_DURATION]);
4569                 if (noa_duration >= vif->bss_conf.beacon_int)
4570                         return -EINVAL;
4571
4572                 mvm->noa_duration = noa_duration;
4573                 mvm->noa_vif = vif;
4574
4575                 return iwl_mvm_update_quotas(mvm, true, NULL);
4576         case IWL_MVM_TM_CMD_SET_BEACON_FILTER:
4577                 /* must be associated client vif - ignore authorized */
4578                 if (!vif || vif->type != NL80211_IFTYPE_STATION ||
4579                     !vif->bss_conf.assoc || !vif->bss_conf.dtim_period ||
4580                     !tb[IWL_MVM_TM_ATTR_BEACON_FILTER_STATE])
4581                         return -EINVAL;
4582
4583                 if (nla_get_u32(tb[IWL_MVM_TM_ATTR_BEACON_FILTER_STATE]))
4584                         return iwl_mvm_enable_beacon_filter(mvm, vif, 0);
4585                 return iwl_mvm_disable_beacon_filter(mvm, vif, 0);
4586         }
4587
4588         return -EOPNOTSUPP;
4589 }
4590
4591 static int iwl_mvm_mac_testmode_cmd(struct ieee80211_hw *hw,
4592                                     struct ieee80211_vif *vif,
4593                                     void *data, int len)
4594 {
4595         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4596         int err;
4597
4598         mutex_lock(&mvm->mutex);
4599         err = __iwl_mvm_mac_testmode_cmd(mvm, vif, data, len);
4600         mutex_unlock(&mvm->mutex);
4601
4602         return err;
4603 }
4604 #endif
4605
4606 static void iwl_mvm_channel_switch(struct ieee80211_hw *hw,
4607                                    struct ieee80211_vif *vif,
4608                                    struct ieee80211_channel_switch *chsw)
4609 {
4610         /* By implementing this operation, we prevent mac80211 from
4611          * starting its own channel switch timer, so that we can call
4612          * ieee80211_chswitch_done() ourselves at the right time
4613          * (which is when the absence time event starts).
4614          */
4615
4616         IWL_DEBUG_MAC80211(IWL_MAC80211_GET_MVM(hw),
4617                            "dummy channel switch op\n");
4618 }
4619
4620 static int iwl_mvm_schedule_client_csa(struct iwl_mvm *mvm,
4621                                        struct ieee80211_vif *vif,
4622                                        struct ieee80211_channel_switch *chsw)
4623 {
4624         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
4625         struct iwl_chan_switch_te_cmd cmd = {
4626                 .mac_id = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
4627                                                           mvmvif->color)),
4628                 .action = cpu_to_le32(FW_CTXT_ACTION_ADD),
4629                 .tsf = cpu_to_le32(chsw->timestamp),
4630                 .cs_count = chsw->count,
4631                 .cs_mode = chsw->block_tx,
4632         };
4633
4634         lockdep_assert_held(&mvm->mutex);
4635
4636         if (chsw->delay)
4637                 cmd.cs_delayed_bcn_count =
4638                         DIV_ROUND_UP(chsw->delay, vif->bss_conf.beacon_int);
4639
4640         return iwl_mvm_send_cmd_pdu(mvm,
4641                                     WIDE_ID(MAC_CONF_GROUP,
4642                                             CHANNEL_SWITCH_TIME_EVENT_CMD),
4643                                     0, sizeof(cmd), &cmd);
4644 }
4645
4646 #define IWL_MAX_CSA_BLOCK_TX 1500
4647 static int iwl_mvm_pre_channel_switch(struct ieee80211_hw *hw,
4648                                       struct ieee80211_vif *vif,
4649                                       struct ieee80211_channel_switch *chsw)
4650 {
4651         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4652         struct ieee80211_vif *csa_vif;
4653         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
4654         u32 apply_time;
4655         int ret;
4656
4657         mutex_lock(&mvm->mutex);
4658
4659         mvmvif->csa_failed = false;
4660
4661         IWL_DEBUG_MAC80211(mvm, "pre CSA to freq %d\n",
4662                            chsw->chandef.center_freq1);
4663
4664         iwl_fw_dbg_trigger_simple_stop(&mvm->fwrt,
4665                                        ieee80211_vif_to_wdev(vif),
4666                                        FW_DBG_TRIGGER_CHANNEL_SWITCH);
4667
4668         switch (vif->type) {
4669         case NL80211_IFTYPE_AP:
4670                 csa_vif =
4671                         rcu_dereference_protected(mvm->csa_vif,
4672                                                   lockdep_is_held(&mvm->mutex));
4673                 if (WARN_ONCE(csa_vif && csa_vif->csa_active,
4674                               "Another CSA is already in progress")) {
4675                         ret = -EBUSY;
4676                         goto out_unlock;
4677                 }
4678
4679                 /* we still didn't unblock tx. prevent new CS meanwhile */
4680                 if (rcu_dereference_protected(mvm->csa_tx_blocked_vif,
4681                                               lockdep_is_held(&mvm->mutex))) {
4682                         ret = -EBUSY;
4683                         goto out_unlock;
4684                 }
4685
4686                 rcu_assign_pointer(mvm->csa_vif, vif);
4687
4688                 if (WARN_ONCE(mvmvif->csa_countdown,
4689                               "Previous CSA countdown didn't complete")) {
4690                         ret = -EBUSY;
4691                         goto out_unlock;
4692                 }
4693
4694                 mvmvif->csa_target_freq = chsw->chandef.chan->center_freq;
4695
4696                 break;
4697         case NL80211_IFTYPE_STATION:
4698                 /* Schedule the time event to a bit before beacon 1,
4699                  * to make sure we're in the new channel when the
4700                  * GO/AP arrives. In case count <= 1 immediately schedule the
4701                  * TE (this might result with some packet loss or connection
4702                  * loss).
4703                  */
4704                 if (chsw->count <= 1)
4705                         apply_time = 0;
4706                 else
4707                         apply_time = chsw->device_timestamp +
4708                                 ((vif->bss_conf.beacon_int * (chsw->count - 1) -
4709                                   IWL_MVM_CHANNEL_SWITCH_TIME_CLIENT) * 1024);
4710
4711                 if (chsw->block_tx) {
4712                         iwl_mvm_csa_client_absent(mvm, vif);
4713                         /*
4714                          * In case of undetermined / long time with immediate
4715                          * quiet monitor status to gracefully disconnect
4716                          */
4717                         if (!chsw->count ||
4718                             chsw->count * vif->bss_conf.beacon_int >
4719                             IWL_MAX_CSA_BLOCK_TX)
4720                                 schedule_delayed_work(&mvmvif->csa_work,
4721                                                       msecs_to_jiffies(IWL_MAX_CSA_BLOCK_TX));
4722                 }
4723
4724                 if (mvmvif->bf_data.bf_enabled) {
4725                         ret = iwl_mvm_disable_beacon_filter(mvm, vif, 0);
4726                         if (ret)
4727                                 goto out_unlock;
4728                 }
4729
4730                 if (fw_has_capa(&mvm->fw->ucode_capa,
4731                                 IWL_UCODE_TLV_CAPA_CHANNEL_SWITCH_CMD))
4732                         iwl_mvm_schedule_client_csa(mvm, vif, chsw);
4733                 else
4734                         iwl_mvm_schedule_csa_period(mvm, vif,
4735                                                     vif->bss_conf.beacon_int,
4736                                                     apply_time);
4737
4738                 mvmvif->csa_count = chsw->count;
4739                 mvmvif->csa_misbehave = false;
4740                 break;
4741         default:
4742                 break;
4743         }
4744
4745         mvmvif->ps_disabled = true;
4746
4747         ret = iwl_mvm_power_update_ps(mvm);
4748         if (ret)
4749                 goto out_unlock;
4750
4751         /* we won't be on this channel any longer */
4752         iwl_mvm_teardown_tdls_peers(mvm);
4753
4754 out_unlock:
4755         mutex_unlock(&mvm->mutex);
4756
4757         return ret;
4758 }
4759
4760 static void iwl_mvm_channel_switch_rx_beacon(struct ieee80211_hw *hw,
4761                                              struct ieee80211_vif *vif,
4762                                              struct ieee80211_channel_switch *chsw)
4763 {
4764         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4765         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
4766         struct iwl_chan_switch_te_cmd cmd = {
4767                 .mac_id = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
4768                                                           mvmvif->color)),
4769                 .action = cpu_to_le32(FW_CTXT_ACTION_MODIFY),
4770                 .tsf = cpu_to_le32(chsw->timestamp),
4771                 .cs_count = chsw->count,
4772                 .cs_mode = chsw->block_tx,
4773         };
4774
4775         if (!fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_CS_MODIFY))
4776                 return;
4777
4778         if (chsw->count >= mvmvif->csa_count && chsw->block_tx) {
4779                 if (mvmvif->csa_misbehave) {
4780                         /* Second time, give up on this AP*/
4781                         iwl_mvm_abort_channel_switch(hw, vif);
4782                         ieee80211_chswitch_done(vif, false);
4783                         mvmvif->csa_misbehave = false;
4784                         return;
4785                 }
4786                 mvmvif->csa_misbehave = true;
4787         }
4788         mvmvif->csa_count = chsw->count;
4789
4790         IWL_DEBUG_MAC80211(mvm, "Modify CSA on mac %d\n", mvmvif->id);
4791
4792         WARN_ON(iwl_mvm_send_cmd_pdu(mvm,
4793                                      WIDE_ID(MAC_CONF_GROUP,
4794                                              CHANNEL_SWITCH_TIME_EVENT_CMD),
4795                                      CMD_ASYNC, sizeof(cmd), &cmd));
4796 }
4797
4798 static void iwl_mvm_flush_no_vif(struct iwl_mvm *mvm, u32 queues, bool drop)
4799 {
4800         int i;
4801
4802         if (!iwl_mvm_has_new_tx_api(mvm)) {
4803                 if (drop) {
4804                         mutex_lock(&mvm->mutex);
4805                         iwl_mvm_flush_tx_path(mvm,
4806                                 iwl_mvm_flushable_queues(mvm) & queues, 0);
4807                         mutex_unlock(&mvm->mutex);
4808                 } else {
4809                         iwl_trans_wait_tx_queues_empty(mvm->trans, queues);
4810                 }
4811                 return;
4812         }
4813
4814         mutex_lock(&mvm->mutex);
4815         for (i = 0; i < ARRAY_SIZE(mvm->fw_id_to_mac_id); i++) {
4816                 struct ieee80211_sta *sta;
4817
4818                 sta = rcu_dereference_protected(mvm->fw_id_to_mac_id[i],
4819                                                 lockdep_is_held(&mvm->mutex));
4820                 if (IS_ERR_OR_NULL(sta))
4821                         continue;
4822
4823                 if (drop)
4824                         iwl_mvm_flush_sta_tids(mvm, i, 0xFF, 0);
4825                 else
4826                         iwl_mvm_wait_sta_queues_empty(mvm,
4827                                         iwl_mvm_sta_from_mac80211(sta));
4828         }
4829         mutex_unlock(&mvm->mutex);
4830 }
4831
4832 static void iwl_mvm_mac_flush(struct ieee80211_hw *hw,
4833                               struct ieee80211_vif *vif, u32 queues, bool drop)
4834 {
4835         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4836         struct iwl_mvm_vif *mvmvif;
4837         struct iwl_mvm_sta *mvmsta;
4838         struct ieee80211_sta *sta;
4839         int i;
4840         u32 msk = 0;
4841
4842         if (!vif) {
4843                 iwl_mvm_flush_no_vif(mvm, queues, drop);
4844                 return;
4845         }
4846
4847         if (vif->type != NL80211_IFTYPE_STATION)
4848                 return;
4849
4850         /* Make sure we're done with the deferred traffic before flushing */
4851         flush_work(&mvm->add_stream_wk);
4852
4853         mutex_lock(&mvm->mutex);
4854         mvmvif = iwl_mvm_vif_from_mac80211(vif);
4855
4856         /* flush the AP-station and all TDLS peers */
4857         for (i = 0; i < ARRAY_SIZE(mvm->fw_id_to_mac_id); i++) {
4858                 sta = rcu_dereference_protected(mvm->fw_id_to_mac_id[i],
4859                                                 lockdep_is_held(&mvm->mutex));
4860                 if (IS_ERR_OR_NULL(sta))
4861                         continue;
4862
4863                 mvmsta = iwl_mvm_sta_from_mac80211(sta);
4864                 if (mvmsta->vif != vif)
4865                         continue;
4866
4867                 /* make sure only TDLS peers or the AP are flushed */
4868                 WARN_ON(i != mvmvif->ap_sta_id && !sta->tdls);
4869
4870                 if (drop) {
4871                         if (iwl_mvm_flush_sta(mvm, mvmsta, false, 0))
4872                                 IWL_ERR(mvm, "flush request fail\n");
4873                 } else {
4874                         msk |= mvmsta->tfd_queue_msk;
4875                         if (iwl_mvm_has_new_tx_api(mvm))
4876                                 iwl_mvm_wait_sta_queues_empty(mvm, mvmsta);
4877                 }
4878         }
4879
4880         mutex_unlock(&mvm->mutex);
4881
4882         /* this can take a while, and we may need/want other operations
4883          * to succeed while doing this, so do it without the mutex held
4884          */
4885         if (!drop && !iwl_mvm_has_new_tx_api(mvm))
4886                 iwl_trans_wait_tx_queues_empty(mvm->trans, msk);
4887 }
4888
4889 static int iwl_mvm_mac_get_survey(struct ieee80211_hw *hw, int idx,
4890                                   struct survey_info *survey)
4891 {
4892         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4893         int ret;
4894
4895         memset(survey, 0, sizeof(*survey));
4896
4897         /* only support global statistics right now */
4898         if (idx != 0)
4899                 return -ENOENT;
4900
4901         if (!fw_has_capa(&mvm->fw->ucode_capa,
4902                          IWL_UCODE_TLV_CAPA_RADIO_BEACON_STATS))
4903                 return -ENOENT;
4904
4905         mutex_lock(&mvm->mutex);
4906
4907         if (iwl_mvm_firmware_running(mvm)) {
4908                 ret = iwl_mvm_request_statistics(mvm, false);
4909                 if (ret)
4910                         goto out;
4911         }
4912
4913         survey->filled = SURVEY_INFO_TIME |
4914                          SURVEY_INFO_TIME_RX |
4915                          SURVEY_INFO_TIME_TX |
4916                          SURVEY_INFO_TIME_SCAN;
4917         survey->time = mvm->accu_radio_stats.on_time_rf +
4918                        mvm->radio_stats.on_time_rf;
4919         do_div(survey->time, USEC_PER_MSEC);
4920
4921         survey->time_rx = mvm->accu_radio_stats.rx_time +
4922                           mvm->radio_stats.rx_time;
4923         do_div(survey->time_rx, USEC_PER_MSEC);
4924
4925         survey->time_tx = mvm->accu_radio_stats.tx_time +
4926                           mvm->radio_stats.tx_time;
4927         do_div(survey->time_tx, USEC_PER_MSEC);
4928
4929         survey->time_scan = mvm->accu_radio_stats.on_time_scan +
4930                             mvm->radio_stats.on_time_scan;
4931         do_div(survey->time_scan, USEC_PER_MSEC);
4932
4933         ret = 0;
4934  out:
4935         mutex_unlock(&mvm->mutex);
4936         return ret;
4937 }
4938
4939 static void iwl_mvm_mac_sta_statistics(struct ieee80211_hw *hw,
4940                                        struct ieee80211_vif *vif,
4941                                        struct ieee80211_sta *sta,
4942                                        struct station_info *sinfo)
4943 {
4944         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
4945         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
4946         struct iwl_mvm_sta *mvmsta = iwl_mvm_sta_from_mac80211(sta);
4947
4948         if (mvmsta->avg_energy) {
4949                 sinfo->signal_avg = mvmsta->avg_energy;
4950                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL_AVG);
4951         }
4952
4953         /* if beacon filtering isn't on mac80211 does it anyway */
4954         if (!(vif->driver_flags & IEEE80211_VIF_BEACON_FILTER))
4955                 return;
4956
4957         if (!vif->bss_conf.assoc)
4958                 return;
4959
4960         mutex_lock(&mvm->mutex);
4961
4962         if (mvmvif->ap_sta_id != mvmsta->sta_id)
4963                 goto unlock;
4964
4965         if (iwl_mvm_request_statistics(mvm, false))
4966                 goto unlock;
4967
4968         sinfo->rx_beacon = mvmvif->beacon_stats.num_beacons +
4969                            mvmvif->beacon_stats.accu_num_beacons;
4970         sinfo->filled |= BIT_ULL(NL80211_STA_INFO_BEACON_RX);
4971         if (mvmvif->beacon_stats.avg_signal) {
4972                 /* firmware only reports a value after RXing a few beacons */
4973                 sinfo->rx_beacon_signal_avg = mvmvif->beacon_stats.avg_signal;
4974                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_BEACON_SIGNAL_AVG);
4975         }
4976  unlock:
4977         mutex_unlock(&mvm->mutex);
4978 }
4979
4980 static void iwl_mvm_event_mlme_callback(struct iwl_mvm *mvm,
4981                                         struct ieee80211_vif *vif,
4982                                         const struct ieee80211_event *event)
4983 {
4984 #define CHECK_MLME_TRIGGER(_cnt, _fmt...)                               \
4985         do {                                                            \
4986                 if ((trig_mlme->_cnt) && --(trig_mlme->_cnt))           \
4987                         break;                                          \
4988                 iwl_fw_dbg_collect_trig(&(mvm)->fwrt, trig, _fmt);      \
4989         } while (0)
4990
4991         struct iwl_fw_dbg_trigger_tlv *trig;
4992         struct iwl_fw_dbg_trigger_mlme *trig_mlme;
4993
4994         trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
4995                                      FW_DBG_TRIGGER_MLME);
4996         if (!trig)
4997                 return;
4998
4999         trig_mlme = (void *)trig->data;
5000
5001         if (event->u.mlme.data == ASSOC_EVENT) {
5002                 if (event->u.mlme.status == MLME_DENIED)
5003                         CHECK_MLME_TRIGGER(stop_assoc_denied,
5004                                            "DENIED ASSOC: reason %d",
5005                                             event->u.mlme.reason);
5006                 else if (event->u.mlme.status == MLME_TIMEOUT)
5007                         CHECK_MLME_TRIGGER(stop_assoc_timeout,
5008                                            "ASSOC TIMEOUT");
5009         } else if (event->u.mlme.data == AUTH_EVENT) {
5010                 if (event->u.mlme.status == MLME_DENIED)
5011                         CHECK_MLME_TRIGGER(stop_auth_denied,
5012                                            "DENIED AUTH: reason %d",
5013                                            event->u.mlme.reason);
5014                 else if (event->u.mlme.status == MLME_TIMEOUT)
5015                         CHECK_MLME_TRIGGER(stop_auth_timeout,
5016                                            "AUTH TIMEOUT");
5017         } else if (event->u.mlme.data == DEAUTH_RX_EVENT) {
5018                 CHECK_MLME_TRIGGER(stop_rx_deauth,
5019                                    "DEAUTH RX %d", event->u.mlme.reason);
5020         } else if (event->u.mlme.data == DEAUTH_TX_EVENT) {
5021                 CHECK_MLME_TRIGGER(stop_tx_deauth,
5022                                    "DEAUTH TX %d", event->u.mlme.reason);
5023         }
5024 #undef CHECK_MLME_TRIGGER
5025 }
5026
5027 static void iwl_mvm_event_bar_rx_callback(struct iwl_mvm *mvm,
5028                                           struct ieee80211_vif *vif,
5029                                           const struct ieee80211_event *event)
5030 {
5031         struct iwl_fw_dbg_trigger_tlv *trig;
5032         struct iwl_fw_dbg_trigger_ba *ba_trig;
5033
5034         trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
5035                                      FW_DBG_TRIGGER_BA);
5036         if (!trig)
5037                 return;
5038
5039         ba_trig = (void *)trig->data;
5040
5041         if (!(le16_to_cpu(ba_trig->rx_bar) & BIT(event->u.ba.tid)))
5042                 return;
5043
5044         iwl_fw_dbg_collect_trig(&mvm->fwrt, trig,
5045                                 "BAR received from %pM, tid %d, ssn %d",
5046                                 event->u.ba.sta->addr, event->u.ba.tid,
5047                                 event->u.ba.ssn);
5048 }
5049
5050 static void iwl_mvm_mac_event_callback(struct ieee80211_hw *hw,
5051                                        struct ieee80211_vif *vif,
5052                                        const struct ieee80211_event *event)
5053 {
5054         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
5055
5056         switch (event->type) {
5057         case MLME_EVENT:
5058                 iwl_mvm_event_mlme_callback(mvm, vif, event);
5059                 break;
5060         case BAR_RX_EVENT:
5061                 iwl_mvm_event_bar_rx_callback(mvm, vif, event);
5062                 break;
5063         case BA_FRAME_TIMEOUT:
5064                 iwl_mvm_event_frame_timeout_callback(mvm, vif, event->u.ba.sta,
5065                                                      event->u.ba.tid);
5066                 break;
5067         default:
5068                 break;
5069         }
5070 }
5071
5072 void iwl_mvm_sync_rx_queues_internal(struct iwl_mvm *mvm,
5073                                      struct iwl_mvm_internal_rxq_notif *notif,
5074                                      u32 size)
5075 {
5076         u32 qmask = BIT(mvm->trans->num_rx_queues) - 1;
5077         int ret;
5078
5079
5080         if (!iwl_mvm_has_new_rx_api(mvm))
5081                 return;
5082
5083         notif->cookie = mvm->queue_sync_cookie;
5084
5085         if (notif->sync)
5086                 atomic_set(&mvm->queue_sync_counter,
5087                            mvm->trans->num_rx_queues);
5088
5089         ret = iwl_mvm_notify_rx_queue(mvm, qmask, (u8 *)notif,
5090                                       size, !notif->sync);
5091         if (ret) {
5092                 IWL_ERR(mvm, "Failed to trigger RX queues sync (%d)\n", ret);
5093                 goto out;
5094         }
5095
5096         if (notif->sync) {
5097                 lockdep_assert_held(&mvm->mutex);
5098                 ret = wait_event_timeout(mvm->rx_sync_waitq,
5099                                          atomic_read(&mvm->queue_sync_counter) == 0 ||
5100                                          iwl_mvm_is_radio_killed(mvm),
5101                                          HZ);
5102                 WARN_ON_ONCE(!ret && !iwl_mvm_is_radio_killed(mvm));
5103         }
5104
5105 out:
5106         atomic_set(&mvm->queue_sync_counter, 0);
5107         mvm->queue_sync_cookie++;
5108 }
5109
5110 static void iwl_mvm_sync_rx_queues(struct ieee80211_hw *hw)
5111 {
5112         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
5113         struct iwl_mvm_internal_rxq_notif data = {
5114                 .type = IWL_MVM_RXQ_EMPTY,
5115                 .sync = 1,
5116         };
5117
5118         mutex_lock(&mvm->mutex);
5119         iwl_mvm_sync_rx_queues_internal(mvm, &data, sizeof(data));
5120         mutex_unlock(&mvm->mutex);
5121 }
5122
5123 static int
5124 iwl_mvm_mac_get_ftm_responder_stats(struct ieee80211_hw *hw,
5125                                     struct ieee80211_vif *vif,
5126                                     struct cfg80211_ftm_responder_stats *stats)
5127 {
5128         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
5129         struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
5130
5131         if (vif->p2p || vif->type != NL80211_IFTYPE_AP ||
5132             !mvmvif->ap_ibss_active || !vif->bss_conf.ftm_responder)
5133                 return -EINVAL;
5134
5135         mutex_lock(&mvm->mutex);
5136         *stats = mvm->ftm_resp_stats;
5137         mutex_unlock(&mvm->mutex);
5138
5139         stats->filled = BIT(NL80211_FTM_STATS_SUCCESS_NUM) |
5140                         BIT(NL80211_FTM_STATS_PARTIAL_NUM) |
5141                         BIT(NL80211_FTM_STATS_FAILED_NUM) |
5142                         BIT(NL80211_FTM_STATS_ASAP_NUM) |
5143                         BIT(NL80211_FTM_STATS_NON_ASAP_NUM) |
5144                         BIT(NL80211_FTM_STATS_TOTAL_DURATION_MSEC) |
5145                         BIT(NL80211_FTM_STATS_UNKNOWN_TRIGGERS_NUM) |
5146                         BIT(NL80211_FTM_STATS_RESCHEDULE_REQUESTS_NUM) |
5147                         BIT(NL80211_FTM_STATS_OUT_OF_WINDOW_TRIGGERS_NUM);
5148
5149         return 0;
5150 }
5151
5152 static int iwl_mvm_start_pmsr(struct ieee80211_hw *hw,
5153                               struct ieee80211_vif *vif,
5154                               struct cfg80211_pmsr_request *request)
5155 {
5156         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
5157         int ret;
5158
5159         mutex_lock(&mvm->mutex);
5160         ret = iwl_mvm_ftm_start(mvm, vif, request);
5161         mutex_unlock(&mvm->mutex);
5162
5163         return ret;
5164 }
5165
5166 static void iwl_mvm_abort_pmsr(struct ieee80211_hw *hw,
5167                                struct ieee80211_vif *vif,
5168                                struct cfg80211_pmsr_request *request)
5169 {
5170         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
5171
5172         mutex_lock(&mvm->mutex);
5173         iwl_mvm_ftm_abort(mvm, request);
5174         mutex_unlock(&mvm->mutex);
5175 }
5176
5177 static bool iwl_mvm_can_hw_csum(struct sk_buff *skb)
5178 {
5179         u8 protocol = ip_hdr(skb)->protocol;
5180
5181         if (!IS_ENABLED(CONFIG_INET))
5182                 return false;
5183
5184         return protocol == IPPROTO_TCP || protocol == IPPROTO_UDP;
5185 }
5186
5187 static bool iwl_mvm_mac_can_aggregate(struct ieee80211_hw *hw,
5188                                       struct sk_buff *head,
5189                                       struct sk_buff *skb)
5190 {
5191         struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
5192
5193         /* For now don't aggregate IPv6 in AMSDU */
5194         if (skb->protocol != htons(ETH_P_IP))
5195                 return false;
5196
5197         if (!iwl_mvm_is_csum_supported(mvm))
5198                 return true;
5199
5200         return iwl_mvm_can_hw_csum(skb) == iwl_mvm_can_hw_csum(head);
5201 }
5202
5203 const struct ieee80211_ops iwl_mvm_hw_ops = {
5204         .tx = iwl_mvm_mac_tx,
5205         .wake_tx_queue = iwl_mvm_mac_wake_tx_queue,
5206         .ampdu_action = iwl_mvm_mac_ampdu_action,
5207         .start = iwl_mvm_mac_start,
5208         .reconfig_complete = iwl_mvm_mac_reconfig_complete,
5209         .stop = iwl_mvm_mac_stop,
5210         .add_interface = iwl_mvm_mac_add_interface,
5211         .remove_interface = iwl_mvm_mac_remove_interface,
5212         .config = iwl_mvm_mac_config,
5213         .prepare_multicast = iwl_mvm_prepare_multicast,
5214         .configure_filter = iwl_mvm_configure_filter,
5215         .config_iface_filter = iwl_mvm_config_iface_filter,
5216         .bss_info_changed = iwl_mvm_bss_info_changed,
5217         .hw_scan = iwl_mvm_mac_hw_scan,
5218         .cancel_hw_scan = iwl_mvm_mac_cancel_hw_scan,
5219         .sta_pre_rcu_remove = iwl_mvm_sta_pre_rcu_remove,
5220         .sta_state = iwl_mvm_mac_sta_state,
5221         .sta_notify = iwl_mvm_mac_sta_notify,
5222         .allow_buffered_frames = iwl_mvm_mac_allow_buffered_frames,
5223         .release_buffered_frames = iwl_mvm_mac_release_buffered_frames,
5224         .set_rts_threshold = iwl_mvm_mac_set_rts_threshold,
5225         .sta_rc_update = iwl_mvm_sta_rc_update,
5226         .conf_tx = iwl_mvm_mac_conf_tx,
5227         .mgd_prepare_tx = iwl_mvm_mac_mgd_prepare_tx,
5228         .mgd_protect_tdls_discover = iwl_mvm_mac_mgd_protect_tdls_discover,
5229         .flush = iwl_mvm_mac_flush,
5230         .sched_scan_start = iwl_mvm_mac_sched_scan_start,
5231         .sched_scan_stop = iwl_mvm_mac_sched_scan_stop,
5232         .set_key = iwl_mvm_mac_set_key,
5233         .update_tkip_key = iwl_mvm_mac_update_tkip_key,
5234         .remain_on_channel = iwl_mvm_roc,
5235         .cancel_remain_on_channel = iwl_mvm_cancel_roc,
5236         .add_chanctx = iwl_mvm_add_chanctx,
5237         .remove_chanctx = iwl_mvm_remove_chanctx,
5238         .change_chanctx = iwl_mvm_change_chanctx,
5239         .assign_vif_chanctx = iwl_mvm_assign_vif_chanctx,
5240         .unassign_vif_chanctx = iwl_mvm_unassign_vif_chanctx,
5241         .switch_vif_chanctx = iwl_mvm_switch_vif_chanctx,
5242
5243         .start_ap = iwl_mvm_start_ap_ibss,
5244         .stop_ap = iwl_mvm_stop_ap_ibss,
5245         .join_ibss = iwl_mvm_start_ap_ibss,
5246         .leave_ibss = iwl_mvm_stop_ap_ibss,
5247
5248         .tx_last_beacon = iwl_mvm_tx_last_beacon,
5249
5250         .set_tim = iwl_mvm_set_tim,
5251
5252         .channel_switch = iwl_mvm_channel_switch,
5253         .pre_channel_switch = iwl_mvm_pre_channel_switch,
5254         .post_channel_switch = iwl_mvm_post_channel_switch,
5255         .abort_channel_switch = iwl_mvm_abort_channel_switch,
5256         .channel_switch_rx_beacon = iwl_mvm_channel_switch_rx_beacon,
5257
5258         .tdls_channel_switch = iwl_mvm_tdls_channel_switch,
5259         .tdls_cancel_channel_switch = iwl_mvm_tdls_cancel_channel_switch,
5260         .tdls_recv_channel_switch = iwl_mvm_tdls_recv_channel_switch,
5261
5262         .event_callback = iwl_mvm_mac_event_callback,
5263
5264         .sync_rx_queues = iwl_mvm_sync_rx_queues,
5265
5266         CFG80211_TESTMODE_CMD(iwl_mvm_mac_testmode_cmd)
5267
5268 #ifdef CONFIG_PM_SLEEP
5269         /* look at d3.c */
5270         .suspend = iwl_mvm_suspend,
5271         .resume = iwl_mvm_resume,
5272         .set_wakeup = iwl_mvm_set_wakeup,
5273         .set_rekey_data = iwl_mvm_set_rekey_data,
5274 #if IS_ENABLED(CONFIG_IPV6)
5275         .ipv6_addr_change = iwl_mvm_ipv6_addr_change,
5276 #endif
5277         .set_default_unicast_key = iwl_mvm_set_default_unicast_key,
5278 #endif
5279         .get_survey = iwl_mvm_mac_get_survey,
5280         .sta_statistics = iwl_mvm_mac_sta_statistics,
5281         .get_ftm_responder_stats = iwl_mvm_mac_get_ftm_responder_stats,
5282         .start_pmsr = iwl_mvm_start_pmsr,
5283         .abort_pmsr = iwl_mvm_abort_pmsr,
5284
5285         .can_aggregate_in_amsdu = iwl_mvm_mac_can_aggregate,
5286 #ifdef CONFIG_IWLWIFI_DEBUGFS
5287         .sta_add_debugfs = iwl_mvm_sta_add_debugfs,
5288 #endif
5289 };