1/*
2 * Mac80211 STA API for ST-Ericsson CW1200 drivers
3 *
4 * Copyright (c) 2010, ST-Ericsson
5 * Author: Dmitry Tarnyagin <dmitry.tarnyagin@lockless.no>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
10 */
11
12#include <linux/vmalloc.h>
13#include <linux/sched.h>
14#include <linux/firmware.h>
15#include <linux/module.h>
16#include <linux/etherdevice.h>
17
18#include "cw1200.h"
19#include "sta.h"
20#include "fwio.h"
21#include "bh.h"
22#include "debug.h"
23
24#ifndef ERP_INFO_BYTE_OFFSET
25#define ERP_INFO_BYTE_OFFSET 2
26#endif
27
28static void cw1200_do_join(struct cw1200_common *priv);
29static void cw1200_do_unjoin(struct cw1200_common *priv);
30
31static int cw1200_upload_beacon(struct cw1200_common *priv);
32static int cw1200_upload_pspoll(struct cw1200_common *priv);
33static int cw1200_upload_null(struct cw1200_common *priv);
34static int cw1200_upload_qosnull(struct cw1200_common *priv);
35static int cw1200_start_ap(struct cw1200_common *priv);
36static int cw1200_update_beaconing(struct cw1200_common *priv);
37static int cw1200_enable_beaconing(struct cw1200_common *priv,
38				   bool enable);
39static void __cw1200_sta_notify(struct ieee80211_hw *dev,
40				struct ieee80211_vif *vif,
41				enum sta_notify_cmd notify_cmd,
42				int link_id);
43static int __cw1200_flush(struct cw1200_common *priv, bool drop);
44
45static inline void __cw1200_free_event_queue(struct list_head *list)
46{
47	struct cw1200_wsm_event *event, *tmp;
48	list_for_each_entry_safe(event, tmp, list, link) {
49		list_del(&event->link);
50		kfree(event);
51	}
52}
53
54/* ******************************************************************** */
55/* STA API								*/
56
57int cw1200_start(struct ieee80211_hw *dev)
58{
59	struct cw1200_common *priv = dev->priv;
60	int ret = 0;
61
62	cw1200_pm_stay_awake(&priv->pm_state, HZ);
63
64	mutex_lock(&priv->conf_mutex);
65
66	/* default EDCA */
67	WSM_EDCA_SET(&priv->edca, 0, 0x0002, 0x0003, 0x0007, 47, 0xc8, false);
68	WSM_EDCA_SET(&priv->edca, 1, 0x0002, 0x0007, 0x000f, 94, 0xc8, false);
69	WSM_EDCA_SET(&priv->edca, 2, 0x0003, 0x000f, 0x03ff, 0, 0xc8, false);
70	WSM_EDCA_SET(&priv->edca, 3, 0x0007, 0x000f, 0x03ff, 0, 0xc8, false);
71	ret = wsm_set_edca_params(priv, &priv->edca);
72	if (ret)
73		goto out;
74
75	ret = cw1200_set_uapsd_param(priv, &priv->edca);
76	if (ret)
77		goto out;
78
79	priv->setbssparams_done = false;
80
81	memcpy(priv->mac_addr, dev->wiphy->perm_addr, ETH_ALEN);
82	priv->mode = NL80211_IFTYPE_MONITOR;
83	priv->wep_default_key_id = -1;
84
85	priv->cqm_beacon_loss_count = 10;
86
87	ret = cw1200_setup_mac(priv);
88	if (ret)
89		goto out;
90
91out:
92	mutex_unlock(&priv->conf_mutex);
93	return ret;
94}
95
96void cw1200_stop(struct ieee80211_hw *dev)
97{
98	struct cw1200_common *priv = dev->priv;
99	LIST_HEAD(list);
100	int i;
101
102	wsm_lock_tx(priv);
103
104	while (down_trylock(&priv->scan.lock)) {
105		/* Scan is in progress. Force it to stop. */
106		priv->scan.req = NULL;
107		schedule();
108	}
109	up(&priv->scan.lock);
110
111	cancel_delayed_work_sync(&priv->scan.probe_work);
112	cancel_delayed_work_sync(&priv->scan.timeout);
113	cancel_delayed_work_sync(&priv->clear_recent_scan_work);
114	cancel_delayed_work_sync(&priv->join_timeout);
115	cw1200_cqm_bssloss_sm(priv, 0, 0, 0);
116	cancel_work_sync(&priv->unjoin_work);
117	cancel_delayed_work_sync(&priv->link_id_gc_work);
118	flush_workqueue(priv->workqueue);
119	del_timer_sync(&priv->mcast_timeout);
120	mutex_lock(&priv->conf_mutex);
121	priv->mode = NL80211_IFTYPE_UNSPECIFIED;
122	priv->listening = false;
123
124	spin_lock(&priv->event_queue_lock);
125	list_splice_init(&priv->event_queue, &list);
126	spin_unlock(&priv->event_queue_lock);
127	__cw1200_free_event_queue(&list);
128
129
130	priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
131	priv->join_pending = false;
132
133	for (i = 0; i < 4; i++)
134		cw1200_queue_clear(&priv->tx_queue[i]);
135	mutex_unlock(&priv->conf_mutex);
136	tx_policy_clean(priv);
137
138	/* HACK! */
139	if (atomic_xchg(&priv->tx_lock, 1) != 1)
140		pr_debug("[STA] TX is force-unlocked due to stop request.\n");
141
142	wsm_unlock_tx(priv);
143	atomic_xchg(&priv->tx_lock, 0); /* for recovery to work */
144}
145
146static int cw1200_bssloss_mitigation = 1;
147module_param(cw1200_bssloss_mitigation, int, 0644);
148MODULE_PARM_DESC(cw1200_bssloss_mitigation, "BSS Loss mitigation. 0 == disabled, 1 == enabled (default)");
149
150
151void __cw1200_cqm_bssloss_sm(struct cw1200_common *priv,
152			     int init, int good, int bad)
153{
154	int tx = 0;
155
156	priv->delayed_link_loss = 0;
157	cancel_work_sync(&priv->bss_params_work);
158
159	pr_debug("[STA] CQM BSSLOSS_SM: state: %d init %d good %d bad: %d txlock: %d uj: %d\n",
160		 priv->bss_loss_state,
161		 init, good, bad,
162		 atomic_read(&priv->tx_lock),
163		 priv->delayed_unjoin);
164
165	/* If we have a pending unjoin */
166	if (priv->delayed_unjoin)
167		return;
168
169	if (init) {
170		queue_delayed_work(priv->workqueue,
171				   &priv->bss_loss_work,
172				   HZ);
173		priv->bss_loss_state = 0;
174
175		/* Skip the confimration procedure in P2P case */
176		if (!priv->vif->p2p && !atomic_read(&priv->tx_lock))
177			tx = 1;
178	} else if (good) {
179		cancel_delayed_work_sync(&priv->bss_loss_work);
180		priv->bss_loss_state = 0;
181		queue_work(priv->workqueue, &priv->bss_params_work);
182	} else if (bad) {
183		/* XXX Should we just keep going until we time out? */
184		if (priv->bss_loss_state < 3)
185			tx = 1;
186	} else {
187		cancel_delayed_work_sync(&priv->bss_loss_work);
188		priv->bss_loss_state = 0;
189	}
190
191	/* Bypass mitigation if it's disabled */
192	if (!cw1200_bssloss_mitigation)
193		tx = 0;
194
195	/* Spit out a NULL packet to our AP if necessary */
196	if (tx) {
197		struct sk_buff *skb;
198
199		priv->bss_loss_state++;
200
201		skb = ieee80211_nullfunc_get(priv->hw, priv->vif);
202		WARN_ON(!skb);
203		if (skb)
204			cw1200_tx(priv->hw, NULL, skb);
205	}
206}
207
208int cw1200_add_interface(struct ieee80211_hw *dev,
209			 struct ieee80211_vif *vif)
210{
211	int ret;
212	struct cw1200_common *priv = dev->priv;
213	/* __le32 auto_calibration_mode = __cpu_to_le32(1); */
214
215	vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER |
216			     IEEE80211_VIF_SUPPORTS_UAPSD |
217			     IEEE80211_VIF_SUPPORTS_CQM_RSSI;
218
219	mutex_lock(&priv->conf_mutex);
220
221	if (priv->mode != NL80211_IFTYPE_MONITOR) {
222		mutex_unlock(&priv->conf_mutex);
223		return -EOPNOTSUPP;
224	}
225
226	switch (vif->type) {
227	case NL80211_IFTYPE_STATION:
228	case NL80211_IFTYPE_ADHOC:
229	case NL80211_IFTYPE_MESH_POINT:
230	case NL80211_IFTYPE_AP:
231		priv->mode = vif->type;
232		break;
233	default:
234		mutex_unlock(&priv->conf_mutex);
235		return -EOPNOTSUPP;
236	}
237
238	priv->vif = vif;
239	memcpy(priv->mac_addr, vif->addr, ETH_ALEN);
240	ret = cw1200_setup_mac(priv);
241	/* Enable auto-calibration */
242	/* Exception in subsequent channel switch; disabled.
243	 *  wsm_write_mib(priv, WSM_MIB_ID_SET_AUTO_CALIBRATION_MODE,
244	 *      &auto_calibration_mode, sizeof(auto_calibration_mode));
245	*/
246
247	mutex_unlock(&priv->conf_mutex);
248	return ret;
249}
250
251void cw1200_remove_interface(struct ieee80211_hw *dev,
252			     struct ieee80211_vif *vif)
253{
254	struct cw1200_common *priv = dev->priv;
255	struct wsm_reset reset = {
256		.reset_statistics = true,
257	};
258	int i;
259
260	mutex_lock(&priv->conf_mutex);
261	switch (priv->join_status) {
262	case CW1200_JOIN_STATUS_JOINING:
263	case CW1200_JOIN_STATUS_PRE_STA:
264	case CW1200_JOIN_STATUS_STA:
265	case CW1200_JOIN_STATUS_IBSS:
266		wsm_lock_tx(priv);
267		if (queue_work(priv->workqueue, &priv->unjoin_work) <= 0)
268			wsm_unlock_tx(priv);
269		break;
270	case CW1200_JOIN_STATUS_AP:
271		for (i = 0; priv->link_id_map; ++i) {
272			if (priv->link_id_map & BIT(i)) {
273				reset.link_id = i;
274				wsm_reset(priv, &reset);
275				priv->link_id_map &= ~BIT(i);
276			}
277		}
278		memset(priv->link_id_db, 0, sizeof(priv->link_id_db));
279		priv->sta_asleep_mask = 0;
280		priv->enable_beacon = false;
281		priv->tx_multicast = false;
282		priv->aid0_bit_set = false;
283		priv->buffered_multicasts = false;
284		priv->pspoll_mask = 0;
285		reset.link_id = 0;
286		wsm_reset(priv, &reset);
287		break;
288	case CW1200_JOIN_STATUS_MONITOR:
289		cw1200_update_listening(priv, false);
290		break;
291	default:
292		break;
293	}
294	priv->vif = NULL;
295	priv->mode = NL80211_IFTYPE_MONITOR;
296	eth_zero_addr(priv->mac_addr);
297	memset(&priv->p2p_ps_modeinfo, 0, sizeof(priv->p2p_ps_modeinfo));
298	cw1200_free_keys(priv);
299	cw1200_setup_mac(priv);
300	priv->listening = false;
301	priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
302	if (!__cw1200_flush(priv, true))
303		wsm_unlock_tx(priv);
304
305	mutex_unlock(&priv->conf_mutex);
306}
307
308int cw1200_change_interface(struct ieee80211_hw *dev,
309			    struct ieee80211_vif *vif,
310			    enum nl80211_iftype new_type,
311			    bool p2p)
312{
313	int ret = 0;
314	pr_debug("change_interface new: %d (%d), old: %d (%d)\n", new_type,
315		 p2p, vif->type, vif->p2p);
316
317	if (new_type != vif->type || vif->p2p != p2p) {
318		cw1200_remove_interface(dev, vif);
319		vif->type = new_type;
320		vif->p2p = p2p;
321		ret = cw1200_add_interface(dev, vif);
322	}
323
324	return ret;
325}
326
327int cw1200_config(struct ieee80211_hw *dev, u32 changed)
328{
329	int ret = 0;
330	struct cw1200_common *priv = dev->priv;
331	struct ieee80211_conf *conf = &dev->conf;
332
333	pr_debug("CONFIG CHANGED:  %08x\n", changed);
334
335	down(&priv->scan.lock);
336	mutex_lock(&priv->conf_mutex);
337	/* TODO: IEEE80211_CONF_CHANGE_QOS */
338	/* TODO: IEEE80211_CONF_CHANGE_LISTEN_INTERVAL */
339
340	if (changed & IEEE80211_CONF_CHANGE_POWER) {
341		priv->output_power = conf->power_level;
342		pr_debug("[STA] TX power: %d\n", priv->output_power);
343		wsm_set_output_power(priv, priv->output_power * 10);
344	}
345
346	if ((changed & IEEE80211_CONF_CHANGE_CHANNEL) &&
347	    (priv->channel != conf->chandef.chan)) {
348		struct ieee80211_channel *ch = conf->chandef.chan;
349		struct wsm_switch_channel channel = {
350			.channel_number = ch->hw_value,
351		};
352		pr_debug("[STA] Freq %d (wsm ch: %d).\n",
353			 ch->center_freq, ch->hw_value);
354
355		/* __cw1200_flush() implicitly locks tx, if successful */
356		if (!__cw1200_flush(priv, false)) {
357			if (!wsm_switch_channel(priv, &channel)) {
358				ret = wait_event_timeout(priv->channel_switch_done,
359							 !priv->channel_switch_in_progress,
360							 3 * HZ);
361				if (ret) {
362					/* Already unlocks if successful */
363					priv->channel = ch;
364					ret = 0;
365				} else {
366					ret = -ETIMEDOUT;
367				}
368			} else {
369				/* Unlock if switch channel fails */
370				wsm_unlock_tx(priv);
371			}
372		}
373	}
374
375	if (changed & IEEE80211_CONF_CHANGE_PS) {
376		if (!(conf->flags & IEEE80211_CONF_PS))
377			priv->powersave_mode.mode = WSM_PSM_ACTIVE;
378		else if (conf->dynamic_ps_timeout <= 0)
379			priv->powersave_mode.mode = WSM_PSM_PS;
380		else
381			priv->powersave_mode.mode = WSM_PSM_FAST_PS;
382
383		/* Firmware requires that value for this 1-byte field must
384		 * be specified in units of 500us. Values above the 128ms
385		 * threshold are not supported.
386		 */
387		if (conf->dynamic_ps_timeout >= 0x80)
388			priv->powersave_mode.fast_psm_idle_period = 0xFF;
389		else
390			priv->powersave_mode.fast_psm_idle_period =
391					conf->dynamic_ps_timeout << 1;
392
393		if (priv->join_status == CW1200_JOIN_STATUS_STA &&
394		    priv->bss_params.aid)
395			cw1200_set_pm(priv, &priv->powersave_mode);
396	}
397
398	if (changed & IEEE80211_CONF_CHANGE_MONITOR) {
399		/* TBD: It looks like it's transparent
400		 * there's a monitor interface present -- use this
401		 * to determine for example whether to calculate
402		 * timestamps for packets or not, do not use instead
403		 * of filter flags!
404		 */
405	}
406
407	if (changed & IEEE80211_CONF_CHANGE_IDLE) {
408		struct wsm_operational_mode mode = {
409			.power_mode = cw1200_power_mode,
410			.disable_more_flag_usage = true,
411		};
412
413		wsm_lock_tx(priv);
414		/* Disable p2p-dev mode forced by TX request */
415		if ((priv->join_status == CW1200_JOIN_STATUS_MONITOR) &&
416		    (conf->flags & IEEE80211_CONF_IDLE) &&
417		    !priv->listening) {
418			cw1200_disable_listening(priv);
419			priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
420		}
421		wsm_set_operational_mode(priv, &mode);
422		wsm_unlock_tx(priv);
423	}
424
425	if (changed & IEEE80211_CONF_CHANGE_RETRY_LIMITS) {
426		pr_debug("[STA] Retry limits: %d (long), %d (short).\n",
427			 conf->long_frame_max_tx_count,
428			 conf->short_frame_max_tx_count);
429		spin_lock_bh(&priv->tx_policy_cache.lock);
430		priv->long_frame_max_tx_count = conf->long_frame_max_tx_count;
431		priv->short_frame_max_tx_count =
432			(conf->short_frame_max_tx_count < 0x0F) ?
433			conf->short_frame_max_tx_count : 0x0F;
434		priv->hw->max_rate_tries = priv->short_frame_max_tx_count;
435		spin_unlock_bh(&priv->tx_policy_cache.lock);
436	}
437	mutex_unlock(&priv->conf_mutex);
438	up(&priv->scan.lock);
439	return ret;
440}
441
442void cw1200_update_filtering(struct cw1200_common *priv)
443{
444	int ret;
445	bool bssid_filtering = !priv->rx_filter.bssid;
446	bool is_p2p = priv->vif && priv->vif->p2p;
447	bool is_sta = priv->vif && NL80211_IFTYPE_STATION == priv->vif->type;
448
449	static struct wsm_beacon_filter_control bf_ctrl;
450	static struct wsm_mib_beacon_filter_table bf_tbl = {
451		.entry[0].ie_id = WLAN_EID_VENDOR_SPECIFIC,
452		.entry[0].flags = WSM_BEACON_FILTER_IE_HAS_CHANGED |
453					WSM_BEACON_FILTER_IE_NO_LONGER_PRESENT |
454					WSM_BEACON_FILTER_IE_HAS_APPEARED,
455		.entry[0].oui[0] = 0x50,
456		.entry[0].oui[1] = 0x6F,
457		.entry[0].oui[2] = 0x9A,
458		.entry[1].ie_id = WLAN_EID_HT_OPERATION,
459		.entry[1].flags = WSM_BEACON_FILTER_IE_HAS_CHANGED |
460					WSM_BEACON_FILTER_IE_NO_LONGER_PRESENT |
461					WSM_BEACON_FILTER_IE_HAS_APPEARED,
462		.entry[2].ie_id = WLAN_EID_ERP_INFO,
463		.entry[2].flags = WSM_BEACON_FILTER_IE_HAS_CHANGED |
464					WSM_BEACON_FILTER_IE_NO_LONGER_PRESENT |
465					WSM_BEACON_FILTER_IE_HAS_APPEARED,
466	};
467
468	if (priv->join_status == CW1200_JOIN_STATUS_PASSIVE)
469		return;
470	else if (priv->join_status == CW1200_JOIN_STATUS_MONITOR)
471		bssid_filtering = false;
472
473	if (priv->disable_beacon_filter) {
474		bf_ctrl.enabled = 0;
475		bf_ctrl.bcn_count = 1;
476		bf_tbl.num = __cpu_to_le32(0);
477	} else if (is_p2p || !is_sta) {
478		bf_ctrl.enabled = WSM_BEACON_FILTER_ENABLE |
479			WSM_BEACON_FILTER_AUTO_ERP;
480		bf_ctrl.bcn_count = 0;
481		bf_tbl.num = __cpu_to_le32(2);
482	} else {
483		bf_ctrl.enabled = WSM_BEACON_FILTER_ENABLE;
484		bf_ctrl.bcn_count = 0;
485		bf_tbl.num = __cpu_to_le32(3);
486	}
487
488	/* When acting as p2p client being connected to p2p GO, in order to
489	 * receive frames from a different p2p device, turn off bssid filter.
490	 *
491	 * WARNING: FW dependency!
492	 * This can only be used with FW WSM371 and its successors.
493	 * In that FW version even with bssid filter turned off,
494	 * device will block most of the unwanted frames.
495	 */
496	if (is_p2p)
497		bssid_filtering = false;
498
499	ret = wsm_set_rx_filter(priv, &priv->rx_filter);
500	if (!ret)
501		ret = wsm_set_beacon_filter_table(priv, &bf_tbl);
502	if (!ret)
503		ret = wsm_beacon_filter_control(priv, &bf_ctrl);
504	if (!ret)
505		ret = wsm_set_bssid_filtering(priv, bssid_filtering);
506	if (!ret)
507		ret = wsm_set_multicast_filter(priv, &priv->multicast_filter);
508	if (ret)
509		wiphy_err(priv->hw->wiphy,
510			  "Update filtering failed: %d.\n", ret);
511	return;
512}
513
514void cw1200_update_filtering_work(struct work_struct *work)
515{
516	struct cw1200_common *priv =
517		container_of(work, struct cw1200_common,
518			     update_filtering_work);
519
520	cw1200_update_filtering(priv);
521}
522
523void cw1200_set_beacon_wakeup_period_work(struct work_struct *work)
524{
525	struct cw1200_common *priv =
526		container_of(work, struct cw1200_common,
527			     set_beacon_wakeup_period_work);
528
529	wsm_set_beacon_wakeup_period(priv,
530				     priv->beacon_int * priv->join_dtim_period >
531				     MAX_BEACON_SKIP_TIME_MS ? 1 :
532				     priv->join_dtim_period, 0);
533}
534
535u64 cw1200_prepare_multicast(struct ieee80211_hw *hw,
536			     struct netdev_hw_addr_list *mc_list)
537{
538	static u8 broadcast_ipv6[ETH_ALEN] = {
539		0x33, 0x33, 0x00, 0x00, 0x00, 0x01
540	};
541	static u8 broadcast_ipv4[ETH_ALEN] = {
542		0x01, 0x00, 0x5e, 0x00, 0x00, 0x01
543	};
544	struct cw1200_common *priv = hw->priv;
545	struct netdev_hw_addr *ha;
546	int count = 0;
547
548	/* Disable multicast filtering */
549	priv->has_multicast_subscription = false;
550	memset(&priv->multicast_filter, 0x00, sizeof(priv->multicast_filter));
551
552	if (netdev_hw_addr_list_count(mc_list) > WSM_MAX_GRP_ADDRTABLE_ENTRIES)
553		return 0;
554
555	/* Enable if requested */
556	netdev_hw_addr_list_for_each(ha, mc_list) {
557		pr_debug("[STA] multicast: %pM\n", ha->addr);
558		memcpy(&priv->multicast_filter.macaddrs[count],
559		       ha->addr, ETH_ALEN);
560		if (!ether_addr_equal(ha->addr, broadcast_ipv4) &&
561		    !ether_addr_equal(ha->addr, broadcast_ipv6))
562			priv->has_multicast_subscription = true;
563		count++;
564	}
565
566	if (count) {
567		priv->multicast_filter.enable = __cpu_to_le32(1);
568		priv->multicast_filter.num_addrs = __cpu_to_le32(count);
569	}
570
571	return netdev_hw_addr_list_count(mc_list);
572}
573
574void cw1200_configure_filter(struct ieee80211_hw *dev,
575			     unsigned int changed_flags,
576			     unsigned int *total_flags,
577			     u64 multicast)
578{
579	struct cw1200_common *priv = dev->priv;
580	bool listening = !!(*total_flags &
581			    (FIF_PROMISC_IN_BSS |
582			     FIF_OTHER_BSS |
583			     FIF_BCN_PRBRESP_PROMISC |
584			     FIF_PROBE_REQ));
585
586	*total_flags &= FIF_PROMISC_IN_BSS |
587			FIF_OTHER_BSS |
588			FIF_FCSFAIL |
589			FIF_BCN_PRBRESP_PROMISC |
590			FIF_PROBE_REQ;
591
592	down(&priv->scan.lock);
593	mutex_lock(&priv->conf_mutex);
594
595	priv->rx_filter.promiscuous = (*total_flags & FIF_PROMISC_IN_BSS)
596			? 1 : 0;
597	priv->rx_filter.bssid = (*total_flags & (FIF_OTHER_BSS |
598			FIF_PROBE_REQ)) ? 1 : 0;
599	priv->rx_filter.fcs = (*total_flags & FIF_FCSFAIL) ? 1 : 0;
600	priv->disable_beacon_filter = !(*total_flags &
601					(FIF_BCN_PRBRESP_PROMISC |
602					 FIF_PROMISC_IN_BSS |
603					 FIF_PROBE_REQ));
604	if (priv->listening != listening) {
605		priv->listening = listening;
606		wsm_lock_tx(priv);
607		cw1200_update_listening(priv, listening);
608		wsm_unlock_tx(priv);
609	}
610	cw1200_update_filtering(priv);
611	mutex_unlock(&priv->conf_mutex);
612	up(&priv->scan.lock);
613}
614
615int cw1200_conf_tx(struct ieee80211_hw *dev, struct ieee80211_vif *vif,
616		   u16 queue, const struct ieee80211_tx_queue_params *params)
617{
618	struct cw1200_common *priv = dev->priv;
619	int ret = 0;
620	/* To prevent re-applying PM request OID again and again*/
621	bool old_uapsd_flags;
622
623	mutex_lock(&priv->conf_mutex);
624
625	if (queue < dev->queues) {
626		old_uapsd_flags = le16_to_cpu(priv->uapsd_info.uapsd_flags);
627
628		WSM_TX_QUEUE_SET(&priv->tx_queue_params, queue, 0, 0, 0);
629		ret = wsm_set_tx_queue_params(priv,
630					      &priv->tx_queue_params.params[queue], queue);
631		if (ret) {
632			ret = -EINVAL;
633			goto out;
634		}
635
636		WSM_EDCA_SET(&priv->edca, queue, params->aifs,
637			     params->cw_min, params->cw_max,
638			     params->txop, 0xc8,
639			     params->uapsd);
640		ret = wsm_set_edca_params(priv, &priv->edca);
641		if (ret) {
642			ret = -EINVAL;
643			goto out;
644		}
645
646		if (priv->mode == NL80211_IFTYPE_STATION) {
647			ret = cw1200_set_uapsd_param(priv, &priv->edca);
648			if (!ret && priv->setbssparams_done &&
649			    (priv->join_status == CW1200_JOIN_STATUS_STA) &&
650			    (old_uapsd_flags != le16_to_cpu(priv->uapsd_info.uapsd_flags)))
651				ret = cw1200_set_pm(priv, &priv->powersave_mode);
652		}
653	} else {
654		ret = -EINVAL;
655	}
656
657out:
658	mutex_unlock(&priv->conf_mutex);
659	return ret;
660}
661
662int cw1200_get_stats(struct ieee80211_hw *dev,
663		     struct ieee80211_low_level_stats *stats)
664{
665	struct cw1200_common *priv = dev->priv;
666
667	memcpy(stats, &priv->stats, sizeof(*stats));
668	return 0;
669}
670
671int cw1200_set_pm(struct cw1200_common *priv, const struct wsm_set_pm *arg)
672{
673	struct wsm_set_pm pm = *arg;
674
675	if (priv->uapsd_info.uapsd_flags != 0)
676		pm.mode &= ~WSM_PSM_FAST_PS_FLAG;
677
678	if (memcmp(&pm, &priv->firmware_ps_mode,
679		   sizeof(struct wsm_set_pm))) {
680		priv->firmware_ps_mode = pm;
681		return wsm_set_pm(priv, &pm);
682	} else {
683		return 0;
684	}
685}
686
687int cw1200_set_key(struct ieee80211_hw *dev, enum set_key_cmd cmd,
688		   struct ieee80211_vif *vif, struct ieee80211_sta *sta,
689		   struct ieee80211_key_conf *key)
690{
691	int ret = -EOPNOTSUPP;
692	struct cw1200_common *priv = dev->priv;
693	struct ieee80211_key_seq seq;
694
695	mutex_lock(&priv->conf_mutex);
696
697	if (cmd == SET_KEY) {
698		u8 *peer_addr = NULL;
699		int pairwise = (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) ?
700			1 : 0;
701		int idx = cw1200_alloc_key(priv);
702		struct wsm_add_key *wsm_key = &priv->keys[idx];
703
704		if (idx < 0) {
705			ret = -EINVAL;
706			goto finally;
707		}
708
709		if (sta)
710			peer_addr = sta->addr;
711
712		key->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE |
713			      IEEE80211_KEY_FLAG_RESERVE_TAILROOM;
714
715		switch (key->cipher) {
716		case WLAN_CIPHER_SUITE_WEP40:
717		case WLAN_CIPHER_SUITE_WEP104:
718			if (key->keylen > 16) {
719				cw1200_free_key(priv, idx);
720				ret = -EINVAL;
721				goto finally;
722			}
723
724			if (pairwise) {
725				wsm_key->type = WSM_KEY_TYPE_WEP_PAIRWISE;
726				memcpy(wsm_key->wep_pairwise.peer,
727				       peer_addr, ETH_ALEN);
728				memcpy(wsm_key->wep_pairwise.keydata,
729				       &key->key[0], key->keylen);
730				wsm_key->wep_pairwise.keylen = key->keylen;
731			} else {
732				wsm_key->type = WSM_KEY_TYPE_WEP_DEFAULT;
733				memcpy(wsm_key->wep_group.keydata,
734				       &key->key[0], key->keylen);
735				wsm_key->wep_group.keylen = key->keylen;
736				wsm_key->wep_group.keyid = key->keyidx;
737			}
738			break;
739		case WLAN_CIPHER_SUITE_TKIP:
740			ieee80211_get_key_rx_seq(key, 0, &seq);
741			if (pairwise) {
742				wsm_key->type = WSM_KEY_TYPE_TKIP_PAIRWISE;
743				memcpy(wsm_key->tkip_pairwise.peer,
744				       peer_addr, ETH_ALEN);
745				memcpy(wsm_key->tkip_pairwise.keydata,
746				       &key->key[0], 16);
747				memcpy(wsm_key->tkip_pairwise.tx_mic_key,
748				       &key->key[16], 8);
749				memcpy(wsm_key->tkip_pairwise.rx_mic_key,
750				       &key->key[24], 8);
751			} else {
752				size_t mic_offset =
753					(priv->mode == NL80211_IFTYPE_AP) ?
754					16 : 24;
755				wsm_key->type = WSM_KEY_TYPE_TKIP_GROUP;
756				memcpy(wsm_key->tkip_group.keydata,
757				       &key->key[0], 16);
758				memcpy(wsm_key->tkip_group.rx_mic_key,
759				       &key->key[mic_offset], 8);
760
761				wsm_key->tkip_group.rx_seqnum[0] = seq.tkip.iv16 & 0xff;
762				wsm_key->tkip_group.rx_seqnum[1] = (seq.tkip.iv16 >> 8) & 0xff;
763				wsm_key->tkip_group.rx_seqnum[2] = seq.tkip.iv32 & 0xff;
764				wsm_key->tkip_group.rx_seqnum[3] = (seq.tkip.iv32 >> 8) & 0xff;
765				wsm_key->tkip_group.rx_seqnum[4] = (seq.tkip.iv32 >> 16) & 0xff;
766				wsm_key->tkip_group.rx_seqnum[5] = (seq.tkip.iv32 >> 24) & 0xff;
767				wsm_key->tkip_group.rx_seqnum[6] = 0;
768				wsm_key->tkip_group.rx_seqnum[7] = 0;
769
770				wsm_key->tkip_group.keyid = key->keyidx;
771			}
772			break;
773		case WLAN_CIPHER_SUITE_CCMP:
774			ieee80211_get_key_rx_seq(key, 0, &seq);
775			if (pairwise) {
776				wsm_key->type = WSM_KEY_TYPE_AES_PAIRWISE;
777				memcpy(wsm_key->aes_pairwise.peer,
778				       peer_addr, ETH_ALEN);
779				memcpy(wsm_key->aes_pairwise.keydata,
780				       &key->key[0], 16);
781			} else {
782				wsm_key->type = WSM_KEY_TYPE_AES_GROUP;
783				memcpy(wsm_key->aes_group.keydata,
784				       &key->key[0], 16);
785
786				wsm_key->aes_group.rx_seqnum[0] = seq.ccmp.pn[5];
787				wsm_key->aes_group.rx_seqnum[1] = seq.ccmp.pn[4];
788				wsm_key->aes_group.rx_seqnum[2] = seq.ccmp.pn[3];
789				wsm_key->aes_group.rx_seqnum[3] = seq.ccmp.pn[2];
790				wsm_key->aes_group.rx_seqnum[4] = seq.ccmp.pn[1];
791				wsm_key->aes_group.rx_seqnum[5] = seq.ccmp.pn[0];
792				wsm_key->aes_group.rx_seqnum[6] = 0;
793				wsm_key->aes_group.rx_seqnum[7] = 0;
794				wsm_key->aes_group.keyid = key->keyidx;
795			}
796			break;
797		case WLAN_CIPHER_SUITE_SMS4:
798			if (pairwise) {
799				wsm_key->type = WSM_KEY_TYPE_WAPI_PAIRWISE;
800				memcpy(wsm_key->wapi_pairwise.peer,
801				       peer_addr, ETH_ALEN);
802				memcpy(wsm_key->wapi_pairwise.keydata,
803				       &key->key[0], 16);
804				memcpy(wsm_key->wapi_pairwise.mic_key,
805				       &key->key[16], 16);
806				wsm_key->wapi_pairwise.keyid = key->keyidx;
807			} else {
808				wsm_key->type = WSM_KEY_TYPE_WAPI_GROUP;
809				memcpy(wsm_key->wapi_group.keydata,
810				       &key->key[0],  16);
811				memcpy(wsm_key->wapi_group.mic_key,
812				       &key->key[16], 16);
813				wsm_key->wapi_group.keyid = key->keyidx;
814			}
815			break;
816		default:
817			pr_warn("Unhandled key type %d\n", key->cipher);
818			cw1200_free_key(priv, idx);
819			ret = -EOPNOTSUPP;
820			goto finally;
821		}
822		ret = wsm_add_key(priv, wsm_key);
823		if (!ret)
824			key->hw_key_idx = idx;
825		else
826			cw1200_free_key(priv, idx);
827	} else if (cmd == DISABLE_KEY) {
828		struct wsm_remove_key wsm_key = {
829			.index = key->hw_key_idx,
830		};
831
832		if (wsm_key.index > WSM_KEY_MAX_INDEX) {
833			ret = -EINVAL;
834			goto finally;
835		}
836
837		cw1200_free_key(priv, wsm_key.index);
838		ret = wsm_remove_key(priv, &wsm_key);
839	} else {
840		pr_warn("Unhandled key command %d\n", cmd);
841	}
842
843finally:
844	mutex_unlock(&priv->conf_mutex);
845	return ret;
846}
847
848void cw1200_wep_key_work(struct work_struct *work)
849{
850	struct cw1200_common *priv =
851		container_of(work, struct cw1200_common, wep_key_work);
852	u8 queue_id = cw1200_queue_get_queue_id(priv->pending_frame_id);
853	struct cw1200_queue *queue = &priv->tx_queue[queue_id];
854	__le32 wep_default_key_id = __cpu_to_le32(
855		priv->wep_default_key_id);
856
857	pr_debug("[STA] Setting default WEP key: %d\n",
858		 priv->wep_default_key_id);
859	wsm_flush_tx(priv);
860	wsm_write_mib(priv, WSM_MIB_ID_DOT11_WEP_DEFAULT_KEY_ID,
861		      &wep_default_key_id, sizeof(wep_default_key_id));
862	cw1200_queue_requeue(queue, priv->pending_frame_id);
863	wsm_unlock_tx(priv);
864}
865
866int cw1200_set_rts_threshold(struct ieee80211_hw *hw, u32 value)
867{
868	int ret = 0;
869	__le32 val32;
870	struct cw1200_common *priv = hw->priv;
871
872	if (priv->mode == NL80211_IFTYPE_UNSPECIFIED)
873		return 0;
874
875	if (value != (u32) -1)
876		val32 = __cpu_to_le32(value);
877	else
878		val32 = 0; /* disabled */
879
880	if (priv->mode == NL80211_IFTYPE_UNSPECIFIED) {
881		/* device is down, can _not_ set threshold */
882		ret = -ENODEV;
883		goto out;
884	}
885
886	if (priv->rts_threshold == value)
887		goto out;
888
889	pr_debug("[STA] Setting RTS threshold: %d\n",
890		 priv->rts_threshold);
891
892	/* mutex_lock(&priv->conf_mutex); */
893	ret = wsm_write_mib(priv, WSM_MIB_ID_DOT11_RTS_THRESHOLD,
894			    &val32, sizeof(val32));
895	if (!ret)
896		priv->rts_threshold = value;
897	/* mutex_unlock(&priv->conf_mutex); */
898
899out:
900	return ret;
901}
902
903/* If successful, LOCKS the TX queue! */
904static int __cw1200_flush(struct cw1200_common *priv, bool drop)
905{
906	int i, ret;
907
908	for (;;) {
909		/* TODO: correct flush handling is required when dev_stop.
910		 * Temporary workaround: 2s
911		 */
912		if (drop) {
913			for (i = 0; i < 4; ++i)
914				cw1200_queue_clear(&priv->tx_queue[i]);
915		} else {
916			ret = wait_event_timeout(
917				priv->tx_queue_stats.wait_link_id_empty,
918				cw1200_queue_stats_is_empty(
919					&priv->tx_queue_stats, -1),
920				2 * HZ);
921		}
922
923		if (!drop && ret <= 0) {
924			ret = -ETIMEDOUT;
925			break;
926		} else {
927			ret = 0;
928		}
929
930		wsm_lock_tx(priv);
931		if (!cw1200_queue_stats_is_empty(&priv->tx_queue_stats, -1)) {
932			/* Highly unlikely: WSM requeued frames. */
933			wsm_unlock_tx(priv);
934			continue;
935		}
936		break;
937	}
938	return ret;
939}
940
941void cw1200_flush(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
942		  u32 queues, bool drop)
943{
944	struct cw1200_common *priv = hw->priv;
945
946	switch (priv->mode) {
947	case NL80211_IFTYPE_MONITOR:
948		drop = true;
949		break;
950	case NL80211_IFTYPE_AP:
951		if (!priv->enable_beacon)
952			drop = true;
953		break;
954	}
955
956	if (!__cw1200_flush(priv, drop))
957		wsm_unlock_tx(priv);
958
959	return;
960}
961
962/* ******************************************************************** */
963/* WSM callbacks							*/
964
965void cw1200_free_event_queue(struct cw1200_common *priv)
966{
967	LIST_HEAD(list);
968
969	spin_lock(&priv->event_queue_lock);
970	list_splice_init(&priv->event_queue, &list);
971	spin_unlock(&priv->event_queue_lock);
972
973	__cw1200_free_event_queue(&list);
974}
975
976void cw1200_event_handler(struct work_struct *work)
977{
978	struct cw1200_common *priv =
979		container_of(work, struct cw1200_common, event_handler);
980	struct cw1200_wsm_event *event;
981	LIST_HEAD(list);
982
983	spin_lock(&priv->event_queue_lock);
984	list_splice_init(&priv->event_queue, &list);
985	spin_unlock(&priv->event_queue_lock);
986
987	list_for_each_entry(event, &list, link) {
988		switch (event->evt.id) {
989		case WSM_EVENT_ERROR:
990			pr_err("Unhandled WSM Error from LMAC\n");
991			break;
992		case WSM_EVENT_BSS_LOST:
993			pr_debug("[CQM] BSS lost.\n");
994			cancel_work_sync(&priv->unjoin_work);
995			if (!down_trylock(&priv->scan.lock)) {
996				cw1200_cqm_bssloss_sm(priv, 1, 0, 0);
997				up(&priv->scan.lock);
998			} else {
999				/* Scan is in progress. Delay reporting.
1000				 * Scan complete will trigger bss_loss_work
1001				 */
1002				priv->delayed_link_loss = 1;
1003				/* Also start a watchdog. */
1004				queue_delayed_work(priv->workqueue,
1005						   &priv->bss_loss_work, 5*HZ);
1006			}
1007			break;
1008		case WSM_EVENT_BSS_REGAINED:
1009			pr_debug("[CQM] BSS regained.\n");
1010			cw1200_cqm_bssloss_sm(priv, 0, 0, 0);
1011			cancel_work_sync(&priv->unjoin_work);
1012			break;
1013		case WSM_EVENT_RADAR_DETECTED:
1014			wiphy_info(priv->hw->wiphy, "radar pulse detected\n");
1015			break;
1016		case WSM_EVENT_RCPI_RSSI:
1017		{
1018			/* RSSI: signed Q8.0, RCPI: unsigned Q7.1
1019			 * RSSI = RCPI / 2 - 110
1020			 */
1021			int rcpi_rssi = (int)(event->evt.data & 0xFF);
1022			int cqm_evt;
1023			if (priv->cqm_use_rssi)
1024				rcpi_rssi = (s8)rcpi_rssi;
1025			else
1026				rcpi_rssi =  rcpi_rssi / 2 - 110;
1027
1028			cqm_evt = (rcpi_rssi <= priv->cqm_rssi_thold) ?
1029				NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW :
1030				NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH;
1031			pr_debug("[CQM] RSSI event: %d.\n", rcpi_rssi);
1032			ieee80211_cqm_rssi_notify(priv->vif, cqm_evt,
1033						  GFP_KERNEL);
1034			break;
1035		}
1036		case WSM_EVENT_BT_INACTIVE:
1037			pr_warn("Unhandled BT INACTIVE from LMAC\n");
1038			break;
1039		case WSM_EVENT_BT_ACTIVE:
1040			pr_warn("Unhandled BT ACTIVE from LMAC\n");
1041			break;
1042		}
1043	}
1044	__cw1200_free_event_queue(&list);
1045}
1046
1047void cw1200_bss_loss_work(struct work_struct *work)
1048{
1049	struct cw1200_common *priv =
1050		container_of(work, struct cw1200_common, bss_loss_work.work);
1051
1052	pr_debug("[CQM] Reporting connection loss.\n");
1053	wsm_lock_tx(priv);
1054	if (queue_work(priv->workqueue, &priv->unjoin_work) <= 0)
1055		wsm_unlock_tx(priv);
1056}
1057
1058void cw1200_bss_params_work(struct work_struct *work)
1059{
1060	struct cw1200_common *priv =
1061		container_of(work, struct cw1200_common, bss_params_work);
1062	mutex_lock(&priv->conf_mutex);
1063
1064	priv->bss_params.reset_beacon_loss = 1;
1065	wsm_set_bss_params(priv, &priv->bss_params);
1066	priv->bss_params.reset_beacon_loss = 0;
1067
1068	mutex_unlock(&priv->conf_mutex);
1069}
1070
1071/* ******************************************************************** */
1072/* Internal API								*/
1073
1074/* This function is called to Parse the SDD file
1075 * to extract listen_interval and PTA related information
1076 * sdd is a TLV: u8 id, u8 len, u8 data[]
1077 */
1078static int cw1200_parse_sdd_file(struct cw1200_common *priv)
1079{
1080	const u8 *p = priv->sdd->data;
1081	int ret = 0;
1082
1083	while (p + 2 <= priv->sdd->data + priv->sdd->size) {
1084		if (p + p[1] + 2 > priv->sdd->data + priv->sdd->size) {
1085			pr_warn("Malformed sdd structure\n");
1086			return -1;
1087		}
1088		switch (p[0]) {
1089		case SDD_PTA_CFG_ELT_ID: {
1090			u16 v;
1091			if (p[1] < 4) {
1092				pr_warn("SDD_PTA_CFG_ELT_ID malformed\n");
1093				ret = -1;
1094				break;
1095			}
1096			v = le16_to_cpu(*((__le16 *)(p + 2)));
1097			if (!v)  /* non-zero means this is enabled */
1098				break;
1099
1100			v = le16_to_cpu(*((__le16 *)(p + 4)));
1101			priv->conf_listen_interval = (v >> 7) & 0x1F;
1102			pr_debug("PTA found; Listen Interval %d\n",
1103				 priv->conf_listen_interval);
1104			break;
1105		}
1106		case SDD_REFERENCE_FREQUENCY_ELT_ID: {
1107			u16 clk = le16_to_cpu(*((__le16 *)(p + 2)));
1108			if (clk != priv->hw_refclk)
1109				pr_warn("SDD file doesn't match configured refclk (%d vs %d)\n",
1110					clk, priv->hw_refclk);
1111			break;
1112		}
1113		default:
1114			break;
1115		}
1116		p += p[1] + 2;
1117	}
1118
1119	if (!priv->bt_present) {
1120		pr_debug("PTA element NOT found.\n");
1121		priv->conf_listen_interval = 0;
1122	}
1123	return ret;
1124}
1125
1126int cw1200_setup_mac(struct cw1200_common *priv)
1127{
1128	int ret = 0;
1129
1130	/* NOTE: There is a bug in FW: it reports signal
1131	 * as RSSI if RSSI subscription is enabled.
1132	 * It's not enough to set WSM_RCPI_RSSI_USE_RSSI.
1133	 *
1134	 * NOTE2: RSSI based reports have been switched to RCPI, since
1135	 * FW has a bug and RSSI reported values are not stable,
1136	 * what can leads to signal level oscilations in user-end applications
1137	 */
1138	struct wsm_rcpi_rssi_threshold threshold = {
1139		.rssiRcpiMode = WSM_RCPI_RSSI_THRESHOLD_ENABLE |
1140		WSM_RCPI_RSSI_DONT_USE_UPPER |
1141		WSM_RCPI_RSSI_DONT_USE_LOWER,
1142		.rollingAverageCount = 16,
1143	};
1144
1145	struct wsm_configuration cfg = {
1146		.dot11StationId = &priv->mac_addr[0],
1147	};
1148
1149	/* Remember the decission here to make sure, we will handle
1150	 * the RCPI/RSSI value correctly on WSM_EVENT_RCPI_RSS
1151	 */
1152	if (threshold.rssiRcpiMode & WSM_RCPI_RSSI_USE_RSSI)
1153		priv->cqm_use_rssi = true;
1154
1155	if (!priv->sdd) {
1156		ret = request_firmware(&priv->sdd, priv->sdd_path, priv->pdev);
1157		if (ret) {
1158			pr_err("Can't load sdd file %s.\n", priv->sdd_path);
1159			return ret;
1160		}
1161		cw1200_parse_sdd_file(priv);
1162	}
1163
1164	cfg.dpdData = priv->sdd->data;
1165	cfg.dpdData_size = priv->sdd->size;
1166	ret = wsm_configuration(priv, &cfg);
1167	if (ret)
1168		return ret;
1169
1170	/* Configure RSSI/SCPI reporting as RSSI. */
1171	wsm_set_rcpi_rssi_threshold(priv, &threshold);
1172
1173	return 0;
1174}
1175
1176static void cw1200_join_complete(struct cw1200_common *priv)
1177{
1178	pr_debug("[STA] Join complete (%d)\n", priv->join_complete_status);
1179
1180	priv->join_pending = false;
1181	if (priv->join_complete_status) {
1182		priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
1183		cw1200_update_listening(priv, priv->listening);
1184		cw1200_do_unjoin(priv);
1185		ieee80211_connection_loss(priv->vif);
1186	} else {
1187		if (priv->mode == NL80211_IFTYPE_ADHOC)
1188			priv->join_status = CW1200_JOIN_STATUS_IBSS;
1189		else
1190			priv->join_status = CW1200_JOIN_STATUS_PRE_STA;
1191	}
1192	wsm_unlock_tx(priv); /* Clearing the lock held before do_join() */
1193}
1194
1195void cw1200_join_complete_work(struct work_struct *work)
1196{
1197	struct cw1200_common *priv =
1198		container_of(work, struct cw1200_common, join_complete_work);
1199	mutex_lock(&priv->conf_mutex);
1200	cw1200_join_complete(priv);
1201	mutex_unlock(&priv->conf_mutex);
1202}
1203
1204void cw1200_join_complete_cb(struct cw1200_common *priv,
1205			     struct wsm_join_complete *arg)
1206{
1207	pr_debug("[STA] cw1200_join_complete_cb called, status=%d.\n",
1208		 arg->status);
1209
1210	if (cancel_delayed_work(&priv->join_timeout)) {
1211		priv->join_complete_status = arg->status;
1212		queue_work(priv->workqueue, &priv->join_complete_work);
1213	}
1214}
1215
1216/* MUST be called with tx_lock held!  It will be unlocked for us. */
1217static void cw1200_do_join(struct cw1200_common *priv)
1218{
1219	const u8 *bssid;
1220	struct ieee80211_bss_conf *conf = &priv->vif->bss_conf;
1221	struct cfg80211_bss *bss = NULL;
1222	struct wsm_protected_mgmt_policy mgmt_policy;
1223	struct wsm_join join = {
1224		.mode = conf->ibss_joined ?
1225				WSM_JOIN_MODE_IBSS : WSM_JOIN_MODE_BSS,
1226		.preamble_type = WSM_JOIN_PREAMBLE_LONG,
1227		.probe_for_join = 1,
1228		.atim_window = 0,
1229		.basic_rate_set = cw1200_rate_mask_to_wsm(priv,
1230							  conf->basic_rates),
1231	};
1232	if (delayed_work_pending(&priv->join_timeout)) {
1233		pr_warn("[STA] - Join request already pending, skipping..\n");
1234		wsm_unlock_tx(priv);
1235		return;
1236	}
1237
1238	if (priv->join_status)
1239		cw1200_do_unjoin(priv);
1240
1241	bssid = priv->vif->bss_conf.bssid;
1242
1243	bss = cfg80211_get_bss(priv->hw->wiphy, priv->channel, bssid, NULL, 0,
1244			       IEEE80211_BSS_TYPE_ANY, IEEE80211_PRIVACY_ANY);
1245
1246	if (!bss && !conf->ibss_joined) {
1247		wsm_unlock_tx(priv);
1248		return;
1249	}
1250
1251	mutex_lock(&priv->conf_mutex);
1252
1253	/* Under the conf lock: check scan status and
1254	 * bail out if it is in progress.
1255	 */
1256	if (atomic_read(&priv->scan.in_progress)) {
1257		wsm_unlock_tx(priv);
1258		goto done_put;
1259	}
1260
1261	priv->join_pending = true;
1262
1263	/* Sanity check basic rates */
1264	if (!join.basic_rate_set)
1265		join.basic_rate_set = 7;
1266
1267	/* Sanity check beacon interval */
1268	if (!priv->beacon_int)
1269		priv->beacon_int = 1;
1270
1271	join.beacon_interval = priv->beacon_int;
1272
1273	/* BT Coex related changes */
1274	if (priv->bt_present) {
1275		if (((priv->conf_listen_interval * 100) %
1276		     priv->beacon_int) == 0)
1277			priv->listen_interval =
1278				((priv->conf_listen_interval * 100) /
1279				 priv->beacon_int);
1280		else
1281			priv->listen_interval =
1282				((priv->conf_listen_interval * 100) /
1283				 priv->beacon_int + 1);
1284	}
1285
1286	if (priv->hw->conf.ps_dtim_period)
1287		priv->join_dtim_period = priv->hw->conf.ps_dtim_period;
1288	join.dtim_period = priv->join_dtim_period;
1289
1290	join.channel_number = priv->channel->hw_value;
1291	join.band = (priv->channel->band == IEEE80211_BAND_5GHZ) ?
1292		WSM_PHY_BAND_5G : WSM_PHY_BAND_2_4G;
1293
1294	memcpy(join.bssid, bssid, sizeof(join.bssid));
1295
1296	pr_debug("[STA] Join BSSID: %pM DTIM: %d, interval: %d\n",
1297		 join.bssid,
1298		 join.dtim_period, priv->beacon_int);
1299
1300	if (!conf->ibss_joined) {
1301		const u8 *ssidie;
1302		rcu_read_lock();
1303		ssidie = ieee80211_bss_get_ie(bss, WLAN_EID_SSID);
1304		if (ssidie) {
1305			join.ssid_len = ssidie[1];
1306			memcpy(join.ssid, &ssidie[2], join.ssid_len);
1307		}
1308		rcu_read_unlock();
1309	}
1310
1311	if (priv->vif->p2p) {
1312		join.flags |= WSM_JOIN_FLAGS_P2P_GO;
1313		join.basic_rate_set =
1314			cw1200_rate_mask_to_wsm(priv, 0xFF0);
1315	}
1316
1317	/* Enable asynchronous join calls */
1318	if (!conf->ibss_joined) {
1319		join.flags |= WSM_JOIN_FLAGS_FORCE;
1320		join.flags |= WSM_JOIN_FLAGS_FORCE_WITH_COMPLETE_IND;
1321	}
1322
1323	wsm_flush_tx(priv);
1324
1325	/* Stay Awake for Join and Auth Timeouts and a bit more */
1326	cw1200_pm_stay_awake(&priv->pm_state,
1327			     CW1200_JOIN_TIMEOUT + CW1200_AUTH_TIMEOUT);
1328
1329	cw1200_update_listening(priv, false);
1330
1331	/* Turn on Block ACKs */
1332	wsm_set_block_ack_policy(priv, priv->ba_tx_tid_mask,
1333				 priv->ba_rx_tid_mask);
1334
1335	/* Set up timeout */
1336	if (join.flags & WSM_JOIN_FLAGS_FORCE_WITH_COMPLETE_IND) {
1337		priv->join_status = CW1200_JOIN_STATUS_JOINING;
1338		queue_delayed_work(priv->workqueue,
1339				   &priv->join_timeout,
1340				   CW1200_JOIN_TIMEOUT);
1341	}
1342
1343	/* 802.11w protected mgmt frames */
1344	mgmt_policy.protectedMgmtEnable = 0;
1345	mgmt_policy.unprotectedMgmtFramesAllowed = 1;
1346	mgmt_policy.encryptionForAuthFrame = 1;
1347	wsm_set_protected_mgmt_policy(priv, &mgmt_policy);
1348
1349	/* Perform actual join */
1350	if (wsm_join(priv, &join)) {
1351		pr_err("[STA] cw1200_join_work: wsm_join failed!\n");
1352		cancel_delayed_work_sync(&priv->join_timeout);
1353		cw1200_update_listening(priv, priv->listening);
1354		/* Tx lock still held, unjoin will clear it. */
1355		if (queue_work(priv->workqueue, &priv->unjoin_work) <= 0)
1356			wsm_unlock_tx(priv);
1357	} else {
1358		if (!(join.flags & WSM_JOIN_FLAGS_FORCE_WITH_COMPLETE_IND))
1359			cw1200_join_complete(priv); /* Will clear tx_lock */
1360
1361		/* Upload keys */
1362		cw1200_upload_keys(priv);
1363
1364		/* Due to beacon filtering it is possible that the
1365		 * AP's beacon is not known for the mac80211 stack.
1366		 * Disable filtering temporary to make sure the stack
1367		 * receives at least one
1368		 */
1369		priv->disable_beacon_filter = true;
1370	}
1371	cw1200_update_filtering(priv);
1372
1373done_put:
1374	mutex_unlock(&priv->conf_mutex);
1375	if (bss)
1376		cfg80211_put_bss(priv->hw->wiphy, bss);
1377}
1378
1379void cw1200_join_timeout(struct work_struct *work)
1380{
1381	struct cw1200_common *priv =
1382		container_of(work, struct cw1200_common, join_timeout.work);
1383	pr_debug("[WSM] Join timed out.\n");
1384	wsm_lock_tx(priv);
1385	if (queue_work(priv->workqueue, &priv->unjoin_work) <= 0)
1386		wsm_unlock_tx(priv);
1387}
1388
1389static void cw1200_do_unjoin(struct cw1200_common *priv)
1390{
1391	struct wsm_reset reset = {
1392		.reset_statistics = true,
1393	};
1394
1395	cancel_delayed_work_sync(&priv->join_timeout);
1396
1397	mutex_lock(&priv->conf_mutex);
1398	priv->join_pending = false;
1399
1400	if (atomic_read(&priv->scan.in_progress)) {
1401		if (priv->delayed_unjoin)
1402			wiphy_dbg(priv->hw->wiphy, "Delayed unjoin is already scheduled.\n");
1403		else
1404			priv->delayed_unjoin = true;
1405		goto done;
1406	}
1407
1408	priv->delayed_link_loss = false;
1409
1410	if (!priv->join_status)
1411		goto done;
1412
1413	if (priv->join_status == CW1200_JOIN_STATUS_AP)
1414		goto done;
1415
1416	cancel_work_sync(&priv->update_filtering_work);
1417	cancel_work_sync(&priv->set_beacon_wakeup_period_work);
1418	priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
1419
1420	/* Unjoin is a reset. */
1421	wsm_flush_tx(priv);
1422	wsm_keep_alive_period(priv, 0);
1423	wsm_reset(priv, &reset);
1424	wsm_set_output_power(priv, priv->output_power * 10);
1425	priv->join_dtim_period = 0;
1426	cw1200_setup_mac(priv);
1427	cw1200_free_event_queue(priv);
1428	cancel_work_sync(&priv->event_handler);
1429	cw1200_update_listening(priv, priv->listening);
1430	cw1200_cqm_bssloss_sm(priv, 0, 0, 0);
1431
1432	/* Disable Block ACKs */
1433	wsm_set_block_ack_policy(priv, 0, 0);
1434
1435	priv->disable_beacon_filter = false;
1436	cw1200_update_filtering(priv);
1437	memset(&priv->association_mode, 0,
1438	       sizeof(priv->association_mode));
1439	memset(&priv->bss_params, 0, sizeof(priv->bss_params));
1440	priv->setbssparams_done = false;
1441	memset(&priv->firmware_ps_mode, 0,
1442	       sizeof(priv->firmware_ps_mode));
1443
1444	pr_debug("[STA] Unjoin completed.\n");
1445
1446done:
1447	mutex_unlock(&priv->conf_mutex);
1448}
1449
1450void cw1200_unjoin_work(struct work_struct *work)
1451{
1452	struct cw1200_common *priv =
1453		container_of(work, struct cw1200_common, unjoin_work);
1454
1455	cw1200_do_unjoin(priv);
1456
1457	/* Tell the stack we're dead */
1458	ieee80211_connection_loss(priv->vif);
1459
1460	wsm_unlock_tx(priv);
1461}
1462
1463int cw1200_enable_listening(struct cw1200_common *priv)
1464{
1465	struct wsm_start start = {
1466		.mode = WSM_START_MODE_P2P_DEV,
1467		.band = WSM_PHY_BAND_2_4G,
1468		.beacon_interval = 100,
1469		.dtim_period = 1,
1470		.probe_delay = 0,
1471		.basic_rate_set = 0x0F,
1472	};
1473
1474	if (priv->channel) {
1475		start.band = priv->channel->band == IEEE80211_BAND_5GHZ ?
1476			     WSM_PHY_BAND_5G : WSM_PHY_BAND_2_4G;
1477		start.channel_number = priv->channel->hw_value;
1478	} else {
1479		start.band = WSM_PHY_BAND_2_4G;
1480		start.channel_number = 1;
1481	}
1482
1483	return wsm_start(priv, &start);
1484}
1485
1486int cw1200_disable_listening(struct cw1200_common *priv)
1487{
1488	int ret;
1489	struct wsm_reset reset = {
1490		.reset_statistics = true,
1491	};
1492	ret = wsm_reset(priv, &reset);
1493	return ret;
1494}
1495
1496void cw1200_update_listening(struct cw1200_common *priv, bool enabled)
1497{
1498	if (enabled) {
1499		if (priv->join_status == CW1200_JOIN_STATUS_PASSIVE) {
1500			if (!cw1200_enable_listening(priv))
1501				priv->join_status = CW1200_JOIN_STATUS_MONITOR;
1502			wsm_set_probe_responder(priv, true);
1503		}
1504	} else {
1505		if (priv->join_status == CW1200_JOIN_STATUS_MONITOR) {
1506			if (!cw1200_disable_listening(priv))
1507				priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
1508			wsm_set_probe_responder(priv, false);
1509		}
1510	}
1511}
1512
1513int cw1200_set_uapsd_param(struct cw1200_common *priv,
1514			   const struct wsm_edca_params *arg)
1515{
1516	int ret;
1517	u16 uapsd_flags = 0;
1518
1519	/* Here's the mapping AC [queue, bit]
1520	 *  VO [0,3], VI [1, 2], BE [2, 1], BK [3, 0]
1521	 */
1522
1523	if (arg->uapsd_enable[0])
1524		uapsd_flags |= 1 << 3;
1525
1526	if (arg->uapsd_enable[1])
1527		uapsd_flags |= 1 << 2;
1528
1529	if (arg->uapsd_enable[2])
1530		uapsd_flags |= 1 << 1;
1531
1532	if (arg->uapsd_enable[3])
1533		uapsd_flags |= 1;
1534
1535	/* Currently pseudo U-APSD operation is not supported, so setting
1536	 * MinAutoTriggerInterval, MaxAutoTriggerInterval and
1537	 * AutoTriggerStep to 0
1538	 */
1539
1540	priv->uapsd_info.uapsd_flags = cpu_to_le16(uapsd_flags);
1541	priv->uapsd_info.min_auto_trigger_interval = 0;
1542	priv->uapsd_info.max_auto_trigger_interval = 0;
1543	priv->uapsd_info.auto_trigger_step = 0;
1544
1545	ret = wsm_set_uapsd_info(priv, &priv->uapsd_info);
1546	return ret;
1547}
1548
1549/* ******************************************************************** */
1550/* AP API								*/
1551
1552int cw1200_sta_add(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
1553		   struct ieee80211_sta *sta)
1554{
1555	struct cw1200_common *priv = hw->priv;
1556	struct cw1200_sta_priv *sta_priv =
1557			(struct cw1200_sta_priv *)&sta->drv_priv;
1558	struct cw1200_link_entry *entry;
1559	struct sk_buff *skb;
1560
1561	if (priv->mode != NL80211_IFTYPE_AP)
1562		return 0;
1563
1564	sta_priv->link_id = cw1200_find_link_id(priv, sta->addr);
1565	if (WARN_ON(!sta_priv->link_id)) {
1566		wiphy_info(priv->hw->wiphy,
1567			   "[AP] No more link IDs available.\n");
1568		return -ENOENT;
1569	}
1570
1571	entry = &priv->link_id_db[sta_priv->link_id - 1];
1572	spin_lock_bh(&priv->ps_state_lock);
1573	if ((sta->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_MASK) ==
1574					IEEE80211_WMM_IE_STA_QOSINFO_AC_MASK)
1575		priv->sta_asleep_mask |= BIT(sta_priv->link_id);
1576	entry->status = CW1200_LINK_HARD;
1577	while ((skb = skb_dequeue(&entry->rx_queue)))
1578		ieee80211_rx_irqsafe(priv->hw, skb);
1579	spin_unlock_bh(&priv->ps_state_lock);
1580	return 0;
1581}
1582
1583int cw1200_sta_remove(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
1584		      struct ieee80211_sta *sta)
1585{
1586	struct cw1200_common *priv = hw->priv;
1587	struct cw1200_sta_priv *sta_priv =
1588			(struct cw1200_sta_priv *)&sta->drv_priv;
1589	struct cw1200_link_entry *entry;
1590
1591	if (priv->mode != NL80211_IFTYPE_AP || !sta_priv->link_id)
1592		return 0;
1593
1594	entry = &priv->link_id_db[sta_priv->link_id - 1];
1595	spin_lock_bh(&priv->ps_state_lock);
1596	entry->status = CW1200_LINK_RESERVE;
1597	entry->timestamp = jiffies;
1598	wsm_lock_tx_async(priv);
1599	if (queue_work(priv->workqueue, &priv->link_id_work) <= 0)
1600		wsm_unlock_tx(priv);
1601	spin_unlock_bh(&priv->ps_state_lock);
1602	flush_workqueue(priv->workqueue);
1603	return 0;
1604}
1605
1606static void __cw1200_sta_notify(struct ieee80211_hw *dev,
1607				struct ieee80211_vif *vif,
1608				enum sta_notify_cmd notify_cmd,
1609				int link_id)
1610{
1611	struct cw1200_common *priv = dev->priv;
1612	u32 bit, prev;
1613
1614	/* Zero link id means "for all link IDs" */
1615	if (link_id)
1616		bit = BIT(link_id);
1617	else if (WARN_ON_ONCE(notify_cmd != STA_NOTIFY_AWAKE))
1618		bit = 0;
1619	else
1620		bit = priv->link_id_map;
1621	prev = priv->sta_asleep_mask & bit;
1622
1623	switch (notify_cmd) {
1624	case STA_NOTIFY_SLEEP:
1625		if (!prev) {
1626			if (priv->buffered_multicasts &&
1627			    !priv->sta_asleep_mask)
1628				queue_work(priv->workqueue,
1629					   &priv->multicast_start_work);
1630			priv->sta_asleep_mask |= bit;
1631		}
1632		break;
1633	case STA_NOTIFY_AWAKE:
1634		if (prev) {
1635			priv->sta_asleep_mask &= ~bit;
1636			priv->pspoll_mask &= ~bit;
1637			if (priv->tx_multicast && link_id &&
1638			    !priv->sta_asleep_mask)
1639				queue_work(priv->workqueue,
1640					   &priv->multicast_stop_work);
1641			cw1200_bh_wakeup(priv);
1642		}
1643		break;
1644	}
1645}
1646
1647void cw1200_sta_notify(struct ieee80211_hw *dev,
1648		       struct ieee80211_vif *vif,
1649		       enum sta_notify_cmd notify_cmd,
1650		       struct ieee80211_sta *sta)
1651{
1652	struct cw1200_common *priv = dev->priv;
1653	struct cw1200_sta_priv *sta_priv =
1654		(struct cw1200_sta_priv *)&sta->drv_priv;
1655
1656	spin_lock_bh(&priv->ps_state_lock);
1657	__cw1200_sta_notify(dev, vif, notify_cmd, sta_priv->link_id);
1658	spin_unlock_bh(&priv->ps_state_lock);
1659}
1660
1661static void cw1200_ps_notify(struct cw1200_common *priv,
1662		      int link_id, bool ps)
1663{
1664	if (link_id > CW1200_MAX_STA_IN_AP_MODE)
1665		return;
1666
1667	pr_debug("%s for LinkId: %d. STAs asleep: %.8X\n",
1668		 ps ? "Stop" : "Start",
1669		 link_id, priv->sta_asleep_mask);
1670
1671	__cw1200_sta_notify(priv->hw, priv->vif,
1672			    ps ? STA_NOTIFY_SLEEP : STA_NOTIFY_AWAKE, link_id);
1673}
1674
1675static int cw1200_set_tim_impl(struct cw1200_common *priv, bool aid0_bit_set)
1676{
1677	struct sk_buff *skb;
1678	struct wsm_update_ie update_ie = {
1679		.what = WSM_UPDATE_IE_BEACON,
1680		.count = 1,
1681	};
1682	u16 tim_offset, tim_length;
1683
1684	pr_debug("[AP] mcast: %s.\n", aid0_bit_set ? "ena" : "dis");
1685
1686	skb = ieee80211_beacon_get_tim(priv->hw, priv->vif,
1687			&tim_offset, &tim_length);
1688	if (!skb) {
1689		if (!__cw1200_flush(priv, true))
1690			wsm_unlock_tx(priv);
1691		return -ENOENT;
1692	}
1693
1694	if (tim_offset && tim_length >= 6) {
1695		/* Ignore DTIM count from mac80211:
1696		 * firmware handles DTIM internally.
1697		 */
1698		skb->data[tim_offset + 2] = 0;
1699
1700		/* Set/reset aid0 bit */
1701		if (aid0_bit_set)
1702			skb->data[tim_offset + 4] |= 1;
1703		else
1704			skb->data[tim_offset + 4] &= ~1;
1705	}
1706
1707	update_ie.ies = &skb->data[tim_offset];
1708	update_ie.length = tim_length;
1709	wsm_update_ie(priv, &update_ie);
1710
1711	dev_kfree_skb(skb);
1712
1713	return 0;
1714}
1715
1716void cw1200_set_tim_work(struct work_struct *work)
1717{
1718	struct cw1200_common *priv =
1719		container_of(work, struct cw1200_common, set_tim_work);
1720	(void)cw1200_set_tim_impl(priv, priv->aid0_bit_set);
1721}
1722
1723int cw1200_set_tim(struct ieee80211_hw *dev, struct ieee80211_sta *sta,
1724		   bool set)
1725{
1726	struct cw1200_common *priv = dev->priv;
1727	queue_work(priv->workqueue, &priv->set_tim_work);
1728	return 0;
1729}
1730
1731void cw1200_set_cts_work(struct work_struct *work)
1732{
1733	struct cw1200_common *priv =
1734		container_of(work, struct cw1200_common, set_cts_work);
1735
1736	u8 erp_ie[3] = {WLAN_EID_ERP_INFO, 0x1, 0};
1737	struct wsm_update_ie update_ie = {
1738		.what = WSM_UPDATE_IE_BEACON,
1739		.count = 1,
1740		.ies = erp_ie,
1741		.length = 3,
1742	};
1743	u32 erp_info;
1744	__le32 use_cts_prot;
1745	mutex_lock(&priv->conf_mutex);
1746	erp_info = priv->erp_info;
1747	mutex_unlock(&priv->conf_mutex);
1748	use_cts_prot =
1749		erp_info & WLAN_ERP_USE_PROTECTION ?
1750		__cpu_to_le32(1) : 0;
1751
1752	erp_ie[ERP_INFO_BYTE_OFFSET] = erp_info;
1753
1754	pr_debug("[STA] ERP information 0x%x\n", erp_info);
1755
1756	wsm_write_mib(priv, WSM_MIB_ID_NON_ERP_PROTECTION,
1757		      &use_cts_prot, sizeof(use_cts_prot));
1758	wsm_update_ie(priv, &update_ie);
1759
1760	return;
1761}
1762
1763static int cw1200_set_btcoexinfo(struct cw1200_common *priv)
1764{
1765	struct wsm_override_internal_txrate arg;
1766	int ret = 0;
1767
1768	if (priv->mode == NL80211_IFTYPE_STATION) {
1769		/* Plumb PSPOLL and NULL template */
1770		cw1200_upload_pspoll(priv);
1771		cw1200_upload_null(priv);
1772		cw1200_upload_qosnull(priv);
1773	} else {
1774		return 0;
1775	}
1776
1777	memset(&arg, 0, sizeof(struct wsm_override_internal_txrate));
1778
1779	if (!priv->vif->p2p) {
1780		/* STATION mode */
1781		if (priv->bss_params.operational_rate_set & ~0xF) {
1782			pr_debug("[STA] STA has ERP rates\n");
1783			/* G or BG mode */
1784			arg.internalTxRate = (__ffs(
1785			priv->bss_params.operational_rate_set & ~0xF));
1786		} else {
1787			pr_debug("[STA] STA has non ERP rates\n");
1788			/* B only mode */
1789			arg.internalTxRate = (__ffs(le32_to_cpu(priv->association_mode.basic_rate_set)));
1790		}
1791		arg.nonErpInternalTxRate = (__ffs(le32_to_cpu(priv->association_mode.basic_rate_set)));
1792	} else {
1793		/* P2P mode */
1794		arg.internalTxRate = (__ffs(priv->bss_params.operational_rate_set & ~0xF));
1795		arg.nonErpInternalTxRate = (__ffs(priv->bss_params.operational_rate_set & ~0xF));
1796	}
1797
1798	pr_debug("[STA] BTCOEX_INFO MODE %d, internalTxRate : %x, nonErpInternalTxRate: %x\n",
1799		 priv->mode,
1800		 arg.internalTxRate,
1801		 arg.nonErpInternalTxRate);
1802
1803	ret = wsm_write_mib(priv, WSM_MIB_ID_OVERRIDE_INTERNAL_TX_RATE,
1804			    &arg, sizeof(arg));
1805
1806	return ret;
1807}
1808
1809void cw1200_bss_info_changed(struct ieee80211_hw *dev,
1810			     struct ieee80211_vif *vif,
1811			     struct ieee80211_bss_conf *info,
1812			     u32 changed)
1813{
1814	struct cw1200_common *priv = dev->priv;
1815	bool do_join = false;
1816
1817	mutex_lock(&priv->conf_mutex);
1818
1819	pr_debug("BSS CHANGED:  %08x\n", changed);
1820
1821	/* TODO: BSS_CHANGED_QOS */
1822	/* TODO: BSS_CHANGED_TXPOWER */
1823
1824	if (changed & BSS_CHANGED_ARP_FILTER) {
1825		struct wsm_mib_arp_ipv4_filter filter = {0};
1826		int i;
1827
1828		pr_debug("[STA] BSS_CHANGED_ARP_FILTER cnt: %d\n",
1829			 info->arp_addr_cnt);
1830
1831		/* Currently only one IP address is supported by firmware.
1832		 * In case of more IPs arp filtering will be disabled.
1833		 */
1834		if (info->arp_addr_cnt > 0 &&
1835		    info->arp_addr_cnt <= WSM_MAX_ARP_IP_ADDRTABLE_ENTRIES) {
1836			for (i = 0; i < info->arp_addr_cnt; i++) {
1837				filter.ipv4addrs[i] = info->arp_addr_list[i];
1838				pr_debug("[STA] addr[%d]: 0x%X\n",
1839					 i, filter.ipv4addrs[i]);
1840			}
1841			filter.enable = __cpu_to_le32(1);
1842		}
1843
1844		pr_debug("[STA] arp ip filter enable: %d\n",
1845			 __le32_to_cpu(filter.enable));
1846
1847		wsm_set_arp_ipv4_filter(priv, &filter);
1848	}
1849
1850	if (changed &
1851	    (BSS_CHANGED_BEACON |
1852	     BSS_CHANGED_AP_PROBE_RESP |
1853	     BSS_CHANGED_BSSID |
1854	     BSS_CHANGED_SSID |
1855	     BSS_CHANGED_IBSS)) {
1856		pr_debug("BSS_CHANGED_BEACON\n");
1857		priv->beacon_int = info->beacon_int;
1858		cw1200_update_beaconing(priv);
1859		cw1200_upload_beacon(priv);
1860	}
1861
1862	if (changed & BSS_CHANGED_BEACON_ENABLED) {
1863		pr_debug("BSS_CHANGED_BEACON_ENABLED (%d)\n", info->enable_beacon);
1864
1865		if (priv->enable_beacon != info->enable_beacon) {
1866			cw1200_enable_beaconing(priv, info->enable_beacon);
1867			priv->enable_beacon = info->enable_beacon;
1868		}
1869	}
1870
1871	if (changed & BSS_CHANGED_BEACON_INT) {
1872		pr_debug("CHANGED_BEACON_INT\n");
1873		if (info->ibss_joined)
1874			do_join = true;
1875		else if (priv->join_status == CW1200_JOIN_STATUS_AP)
1876			cw1200_update_beaconing(priv);
1877	}
1878
1879	/* assoc/disassoc, or maybe AID changed */
1880	if (changed & BSS_CHANGED_ASSOC) {
1881		wsm_lock_tx(priv);
1882		priv->wep_default_key_id = -1;
1883		wsm_unlock_tx(priv);
1884	}
1885
1886	if (changed & BSS_CHANGED_BSSID) {
1887		pr_debug("BSS_CHANGED_BSSID\n");
1888		do_join = true;
1889	}
1890
1891	if (changed &
1892	    (BSS_CHANGED_ASSOC |
1893	     BSS_CHANGED_BSSID |
1894	     BSS_CHANGED_IBSS |
1895	     BSS_CHANGED_BASIC_RATES |
1896	     BSS_CHANGED_HT)) {
1897		pr_debug("BSS_CHANGED_ASSOC\n");
1898		if (info->assoc) {
1899			if (priv->join_status < CW1200_JOIN_STATUS_PRE_STA) {
1900				ieee80211_connection_loss(vif);
1901				mutex_unlock(&priv->conf_mutex);
1902				return;
1903			} else if (priv->join_status == CW1200_JOIN_STATUS_PRE_STA) {
1904				priv->join_status = CW1200_JOIN_STATUS_STA;
1905			}
1906		} else {
1907			do_join = true;
1908		}
1909
1910		if (info->assoc || info->ibss_joined) {
1911			struct ieee80211_sta *sta = NULL;
1912			__le32 htprot = 0;
1913
1914			if (info->dtim_period)
1915				priv->join_dtim_period = info->dtim_period;
1916			priv->beacon_int = info->beacon_int;
1917
1918			rcu_read_lock();
1919
1920			if (info->bssid && !info->ibss_joined)
1921				sta = ieee80211_find_sta(vif, info->bssid);
1922			if (sta) {
1923				priv->ht_info.ht_cap = sta->ht_cap;
1924				priv->bss_params.operational_rate_set =
1925					cw1200_rate_mask_to_wsm(priv,
1926								sta->supp_rates[priv->channel->band]);
1927				priv->ht_info.channel_type = cfg80211_get_chandef_type(&dev->conf.chandef);
1928				priv->ht_info.operation_mode = info->ht_operation_mode;
1929			} else {
1930				memset(&priv->ht_info, 0,
1931				       sizeof(priv->ht_info));
1932				priv->bss_params.operational_rate_set = -1;
1933			}
1934			rcu_read_unlock();
1935
1936			/* Non Greenfield stations present */
1937			if (priv->ht_info.operation_mode &
1938			    IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT)
1939				htprot |= cpu_to_le32(WSM_NON_GREENFIELD_STA_PRESENT);
1940
1941			/* Set HT protection method */
1942			htprot |= cpu_to_le32((priv->ht_info.operation_mode & IEEE80211_HT_OP_MODE_PROTECTION) << 2);
1943
1944			/* TODO:
1945			 * STBC_param.dual_cts
1946			 *  STBC_param.LSIG_TXOP_FILL
1947			 */
1948
1949			wsm_write_mib(priv, WSM_MIB_ID_SET_HT_PROTECTION,
1950				      &htprot, sizeof(htprot));
1951
1952			priv->association_mode.greenfield =
1953				cw1200_ht_greenfield(&priv->ht_info);
1954			priv->association_mode.flags =
1955				WSM_ASSOCIATION_MODE_SNOOP_ASSOC_FRAMES |
1956				WSM_ASSOCIATION_MODE_USE_PREAMBLE_TYPE |
1957				WSM_ASSOCIATION_MODE_USE_HT_MODE |
1958				WSM_ASSOCIATION_MODE_USE_BASIC_RATE_SET |
1959				WSM_ASSOCIATION_MODE_USE_MPDU_START_SPACING;
1960			priv->association_mode.preamble =
1961				info->use_short_preamble ?
1962				WSM_JOIN_PREAMBLE_SHORT :
1963				WSM_JOIN_PREAMBLE_LONG;
1964			priv->association_mode.basic_rate_set = __cpu_to_le32(
1965				cw1200_rate_mask_to_wsm(priv,
1966							info->basic_rates));
1967			priv->association_mode.mpdu_start_spacing =
1968				cw1200_ht_ampdu_density(&priv->ht_info);
1969
1970			cw1200_cqm_bssloss_sm(priv, 0, 0, 0);
1971			cancel_work_sync(&priv->unjoin_work);
1972
1973			priv->bss_params.beacon_lost_count = priv->cqm_beacon_loss_count;
1974			priv->bss_params.aid = info->aid;
1975
1976			if (priv->join_dtim_period < 1)
1977				priv->join_dtim_period = 1;
1978
1979			pr_debug("[STA] DTIM %d, interval: %d\n",
1980				 priv->join_dtim_period, priv->beacon_int);
1981			pr_debug("[STA] Preamble: %d, Greenfield: %d, Aid: %d, Rates: 0x%.8X, Basic: 0x%.8X\n",
1982				 priv->association_mode.preamble,
1983				 priv->association_mode.greenfield,
1984				 priv->bss_params.aid,
1985				 priv->bss_params.operational_rate_set,
1986				 priv->association_mode.basic_rate_set);
1987			wsm_set_association_mode(priv, &priv->association_mode);
1988
1989			if (!info->ibss_joined) {
1990				wsm_keep_alive_period(priv, 30 /* sec */);
1991				wsm_set_bss_params(priv, &priv->bss_params);
1992				priv->setbssparams_done = true;
1993				cw1200_set_beacon_wakeup_period_work(&priv->set_beacon_wakeup_period_work);
1994				cw1200_set_pm(priv, &priv->powersave_mode);
1995			}
1996			if (priv->vif->p2p) {
1997				pr_debug("[STA] Setting p2p powersave configuration.\n");
1998				wsm_set_p2p_ps_modeinfo(priv,
1999							&priv->p2p_ps_modeinfo);
2000			}
2001			if (priv->bt_present)
2002				cw1200_set_btcoexinfo(priv);
2003		} else {
2004			memset(&priv->association_mode, 0,
2005			       sizeof(priv->association_mode));
2006			memset(&priv->bss_params, 0, sizeof(priv->bss_params));
2007		}
2008	}
2009
2010	/* ERP Protection */
2011	if (changed & (BSS_CHANGED_ASSOC |
2012		       BSS_CHANGED_ERP_CTS_PROT |
2013		       BSS_CHANGED_ERP_PREAMBLE)) {
2014		u32 prev_erp_info = priv->erp_info;
2015		if (info->use_cts_prot)
2016			priv->erp_info |= WLAN_ERP_USE_PROTECTION;
2017		else if (!(prev_erp_info & WLAN_ERP_NON_ERP_PRESENT))
2018			priv->erp_info &= ~WLAN_ERP_USE_PROTECTION;
2019
2020		if (info->use_short_preamble)
2021			priv->erp_info |= WLAN_ERP_BARKER_PREAMBLE;
2022		else
2023			priv->erp_info &= ~WLAN_ERP_BARKER_PREAMBLE;
2024
2025		pr_debug("[STA] ERP Protection: %x\n", priv->erp_info);
2026
2027		if (prev_erp_info != priv->erp_info)
2028			queue_work(priv->workqueue, &priv->set_cts_work);
2029	}
2030
2031	/* ERP Slottime */
2032	if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_ERP_SLOT)) {
2033		__le32 slot_time = info->use_short_slot ?
2034			__cpu_to_le32(9) : __cpu_to_le32(20);
2035		pr_debug("[STA] Slot time: %d us.\n",
2036			 __le32_to_cpu(slot_time));
2037		wsm_write_mib(priv, WSM_MIB_ID_DOT11_SLOT_TIME,
2038			      &slot_time, sizeof(slot_time));
2039	}
2040
2041	if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_CQM)) {
2042		struct wsm_rcpi_rssi_threshold threshold = {
2043			.rollingAverageCount = 8,
2044		};
2045		pr_debug("[CQM] RSSI threshold subscribe: %d +- %d\n",
2046			 info->cqm_rssi_thold, info->cqm_rssi_hyst);
2047		priv->cqm_rssi_thold = info->cqm_rssi_thold;
2048		priv->cqm_rssi_hyst = info->cqm_rssi_hyst;
2049
2050		if (info->cqm_rssi_thold || info->cqm_rssi_hyst) {
2051			/* RSSI subscription enabled */
2052			/* TODO: It's not a correct way of setting threshold.
2053			 * Upper and lower must be set equal here and adjusted
2054			 * in callback. However current implementation is much
2055			 * more relaible and stable.
2056			 */
2057
2058			/* RSSI: signed Q8.0, RCPI: unsigned Q7.1
2059			 * RSSI = RCPI / 2 - 110
2060			 */
2061			if (priv->cqm_use_rssi) {
2062				threshold.upperThreshold =
2063					info->cqm_rssi_thold + info->cqm_rssi_hyst;
2064				threshold.lowerThreshold =
2065					info->cqm_rssi_thold;
2066				threshold.rssiRcpiMode |= WSM_RCPI_RSSI_USE_RSSI;
2067			} else {
2068				threshold.upperThreshold = (info->cqm_rssi_thold + info->cqm_rssi_hyst + 110) * 2;
2069				threshold.lowerThreshold = (info->cqm_rssi_thold + 110) * 2;
2070			}
2071			threshold.rssiRcpiMode |= WSM_RCPI_RSSI_THRESHOLD_ENABLE;
2072		} else {
2073			/* There is a bug in FW, see sta.c. We have to enable
2074			 * dummy subscription to get correct RSSI values.
2075			 */
2076			threshold.rssiRcpiMode |=
2077				WSM_RCPI_RSSI_THRESHOLD_ENABLE |
2078				WSM_RCPI_RSSI_DONT_USE_UPPER |
2079				WSM_RCPI_RSSI_DONT_USE_LOWER;
2080			if (priv->cqm_use_rssi)
2081				threshold.rssiRcpiMode |= WSM_RCPI_RSSI_USE_RSSI;
2082		}
2083		wsm_set_rcpi_rssi_threshold(priv, &threshold);
2084	}
2085	mutex_unlock(&priv->conf_mutex);
2086
2087	if (do_join) {
2088		wsm_lock_tx(priv);
2089		cw1200_do_join(priv); /* Will unlock it for us */
2090	}
2091}
2092
2093void cw1200_multicast_start_work(struct work_struct *work)
2094{
2095	struct cw1200_common *priv =
2096		container_of(work, struct cw1200_common, multicast_start_work);
2097	long tmo = priv->join_dtim_period *
2098			(priv->beacon_int + 20) * HZ / 1024;
2099
2100	cancel_work_sync(&priv->multicast_stop_work);
2101
2102	if (!priv->aid0_bit_set) {
2103		wsm_lock_tx(priv);
2104		cw1200_set_tim_impl(priv, true);
2105		priv->aid0_bit_set = true;
2106		mod_timer(&priv->mcast_timeout, jiffies + tmo);
2107		wsm_unlock_tx(priv);
2108	}
2109}
2110
2111void cw1200_multicast_stop_work(struct work_struct *work)
2112{
2113	struct cw1200_common *priv =
2114		container_of(work, struct cw1200_common, multicast_stop_work);
2115
2116	if (priv->aid0_bit_set) {
2117		del_timer_sync(&priv->mcast_timeout);
2118		wsm_lock_tx(priv);
2119		priv->aid0_bit_set = false;
2120		cw1200_set_tim_impl(priv, false);
2121		wsm_unlock_tx(priv);
2122	}
2123}
2124
2125void cw1200_mcast_timeout(unsigned long arg)
2126{
2127	struct cw1200_common *priv =
2128		(struct cw1200_common *)arg;
2129
2130	wiphy_warn(priv->hw->wiphy,
2131		   "Multicast delivery timeout.\n");
2132	spin_lock_bh(&priv->ps_state_lock);
2133	priv->tx_multicast = priv->aid0_bit_set &&
2134			priv->buffered_multicasts;
2135	if (priv->tx_multicast)
2136		cw1200_bh_wakeup(priv);
2137	spin_unlock_bh(&priv->ps_state_lock);
2138}
2139
2140int cw1200_ampdu_action(struct ieee80211_hw *hw,
2141			struct ieee80211_vif *vif,
2142			enum ieee80211_ampdu_mlme_action action,
2143			struct ieee80211_sta *sta, u16 tid, u16 *ssn,
2144			u8 buf_size)
2145{
2146	/* Aggregation is implemented fully in firmware,
2147	 * including block ack negotiation. Do not allow
2148	 * mac80211 stack to do anything: it interferes with
2149	 * the firmware.
2150	 */
2151
2152	/* Note that we still need this function stubbed. */
2153	return -ENOTSUPP;
2154}
2155
2156/* ******************************************************************** */
2157/* WSM callback								*/
2158void cw1200_suspend_resume(struct cw1200_common *priv,
2159			  struct wsm_suspend_resume *arg)
2160{
2161	pr_debug("[AP] %s: %s\n",
2162		 arg->stop ? "stop" : "start",
2163		 arg->multicast ? "broadcast" : "unicast");
2164
2165	if (arg->multicast) {
2166		bool cancel_tmo = false;
2167		spin_lock_bh(&priv->ps_state_lock);
2168		if (arg->stop) {
2169			priv->tx_multicast = false;
2170		} else {
2171			/* Firmware sends this indication every DTIM if there
2172			 * is a STA in powersave connected. There is no reason
2173			 * to suspend, following wakeup will consume much more
2174			 * power than it could be saved.
2175			 */
2176			cw1200_pm_stay_awake(&priv->pm_state,
2177					     priv->join_dtim_period *
2178					     (priv->beacon_int + 20) * HZ / 1024);
2179			priv->tx_multicast = (priv->aid0_bit_set &&
2180					      priv->buffered_multicasts);
2181			if (priv->tx_multicast) {
2182				cancel_tmo = true;
2183				cw1200_bh_wakeup(priv);
2184			}
2185		}
2186		spin_unlock_bh(&priv->ps_state_lock);
2187		if (cancel_tmo)
2188			del_timer_sync(&priv->mcast_timeout);
2189	} else {
2190		spin_lock_bh(&priv->ps_state_lock);
2191		cw1200_ps_notify(priv, arg->link_id, arg->stop);
2192		spin_unlock_bh(&priv->ps_state_lock);
2193		if (!arg->stop)
2194			cw1200_bh_wakeup(priv);
2195	}
2196	return;
2197}
2198
2199/* ******************************************************************** */
2200/* AP privates								*/
2201
2202static int cw1200_upload_beacon(struct cw1200_common *priv)
2203{
2204	int ret = 0;
2205	struct ieee80211_mgmt *mgmt;
2206	struct wsm_template_frame frame = {
2207		.frame_type = WSM_FRAME_TYPE_BEACON,
2208	};
2209
2210	u16 tim_offset;
2211	u16 tim_len;
2212
2213	if (priv->mode == NL80211_IFTYPE_STATION ||
2214	    priv->mode == NL80211_IFTYPE_MONITOR ||
2215	    priv->mode == NL80211_IFTYPE_UNSPECIFIED)
2216		goto done;
2217
2218	if (priv->vif->p2p)
2219		frame.rate = WSM_TRANSMIT_RATE_6;
2220
2221	frame.skb = ieee80211_beacon_get_tim(priv->hw, priv->vif,
2222					     &tim_offset, &tim_len);
2223	if (!frame.skb)
2224		return -ENOMEM;
2225
2226	ret = wsm_set_template_frame(priv, &frame);
2227
2228	if (ret)
2229		goto done;
2230
2231	/* TODO: Distill probe resp; remove TIM
2232	 * and any other beacon-specific IEs
2233	 */
2234	mgmt = (void *)frame.skb->data;
2235	mgmt->frame_control =
2236		__cpu_to_le16(IEEE80211_FTYPE_MGMT |
2237			      IEEE80211_STYPE_PROBE_RESP);
2238
2239	frame.frame_type = WSM_FRAME_TYPE_PROBE_RESPONSE;
2240	if (priv->vif->p2p) {
2241		ret = wsm_set_probe_responder(priv, true);
2242	} else {
2243		ret = wsm_set_template_frame(priv, &frame);
2244		wsm_set_probe_responder(priv, false);
2245	}
2246
2247done:
2248	dev_kfree_skb(frame.skb);
2249
2250	return ret;
2251}
2252
2253static int cw1200_upload_pspoll(struct cw1200_common *priv)
2254{
2255	int ret = 0;
2256	struct wsm_template_frame frame = {
2257		.frame_type = WSM_FRAME_TYPE_PS_POLL,
2258		.rate = 0xFF,
2259	};
2260
2261
2262	frame.skb = ieee80211_pspoll_get(priv->hw, priv->vif);
2263	if (!frame.skb)
2264		return -ENOMEM;
2265
2266	ret = wsm_set_template_frame(priv, &frame);
2267
2268	dev_kfree_skb(frame.skb);
2269
2270	return ret;
2271}
2272
2273static int cw1200_upload_null(struct cw1200_common *priv)
2274{
2275	int ret = 0;
2276	struct wsm_template_frame frame = {
2277		.frame_type = WSM_FRAME_TYPE_NULL,
2278		.rate = 0xFF,
2279	};
2280
2281	frame.skb = ieee80211_nullfunc_get(priv->hw, priv->vif);
2282	if (!frame.skb)
2283		return -ENOMEM;
2284
2285	ret = wsm_set_template_frame(priv, &frame);
2286
2287	dev_kfree_skb(frame.skb);
2288
2289	return ret;
2290}
2291
2292static int cw1200_upload_qosnull(struct cw1200_common *priv)
2293{
2294	/* TODO:  This needs to be implemented
2295
2296	struct wsm_template_frame frame = {
2297		.frame_type = WSM_FRAME_TYPE_QOS_NULL,
2298		.rate = 0xFF,
2299	};
2300
2301	frame.skb = ieee80211_qosnullfunc_get(priv->hw, priv->vif);
2302	if (!frame.skb)
2303		return -ENOMEM;
2304
2305	ret = wsm_set_template_frame(priv, &frame);
2306
2307	dev_kfree_skb(frame.skb);
2308
2309	*/
2310	return 0;
2311}
2312
2313static int cw1200_enable_beaconing(struct cw1200_common *priv,
2314				   bool enable)
2315{
2316	struct wsm_beacon_transmit transmit = {
2317		.enable_beaconing = enable,
2318	};
2319
2320	return wsm_beacon_transmit(priv, &transmit);
2321}
2322
2323static int cw1200_start_ap(struct cw1200_common *priv)
2324{
2325	int ret;
2326	struct ieee80211_bss_conf *conf = &priv->vif->bss_conf;
2327	struct wsm_start start = {
2328		.mode = priv->vif->p2p ?
2329				WSM_START_MODE_P2P_GO : WSM_START_MODE_AP,
2330		.band = (priv->channel->band == IEEE80211_BAND_5GHZ) ?
2331				WSM_PHY_BAND_5G : WSM_PHY_BAND_2_4G,
2332		.channel_number = priv->channel->hw_value,
2333		.beacon_interval = conf->beacon_int,
2334		.dtim_period = conf->dtim_period,
2335		.preamble = conf->use_short_preamble ?
2336				WSM_JOIN_PREAMBLE_SHORT :
2337				WSM_JOIN_PREAMBLE_LONG,
2338		.probe_delay = 100,
2339		.basic_rate_set = cw1200_rate_mask_to_wsm(priv,
2340				conf->basic_rates),
2341	};
2342	struct wsm_operational_mode mode = {
2343		.power_mode = cw1200_power_mode,
2344		.disable_more_flag_usage = true,
2345	};
2346
2347	memset(start.ssid, 0, sizeof(start.ssid));
2348	if (!conf->hidden_ssid) {
2349		start.ssid_len = conf->ssid_len;
2350		memcpy(start.ssid, conf->ssid, start.ssid_len);
2351	}
2352
2353	priv->beacon_int = conf->beacon_int;
2354	priv->join_dtim_period = conf->dtim_period;
2355
2356	memset(&priv->link_id_db, 0, sizeof(priv->link_id_db));
2357
2358	pr_debug("[AP] ch: %d(%d), bcn: %d(%d), brt: 0x%.8X, ssid: %.*s.\n",
2359		 start.channel_number, start.band,
2360		 start.beacon_interval, start.dtim_period,
2361		 start.basic_rate_set,
2362		 start.ssid_len, start.ssid);
2363	ret = wsm_start(priv, &start);
2364	if (!ret)
2365		ret = cw1200_upload_keys(priv);
2366	if (!ret && priv->vif->p2p) {
2367		pr_debug("[AP] Setting p2p powersave configuration.\n");
2368		wsm_set_p2p_ps_modeinfo(priv, &priv->p2p_ps_modeinfo);
2369	}
2370	if (!ret) {
2371		wsm_set_block_ack_policy(priv, 0, 0);
2372		priv->join_status = CW1200_JOIN_STATUS_AP;
2373		cw1200_update_filtering(priv);
2374	}
2375	wsm_set_operational_mode(priv, &mode);
2376	return ret;
2377}
2378
2379static int cw1200_update_beaconing(struct cw1200_common *priv)
2380{
2381	struct ieee80211_bss_conf *conf = &priv->vif->bss_conf;
2382	struct wsm_reset reset = {
2383		.link_id = 0,
2384		.reset_statistics = true,
2385	};
2386
2387	if (priv->mode == NL80211_IFTYPE_AP) {
2388		/* TODO: check if changed channel, band */
2389		if (priv->join_status != CW1200_JOIN_STATUS_AP ||
2390		    priv->beacon_int != conf->beacon_int) {
2391			pr_debug("ap restarting\n");
2392			wsm_lock_tx(priv);
2393			if (priv->join_status != CW1200_JOIN_STATUS_PASSIVE)
2394				wsm_reset(priv, &reset);
2395			priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
2396			cw1200_start_ap(priv);
2397			wsm_unlock_tx(priv);
2398		} else
2399			pr_debug("ap started join_status: %d\n",
2400				 priv->join_status);
2401	}
2402	return 0;
2403}
2404