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_OTHER_BSS |
582			     FIF_BCN_PRBRESP_PROMISC |
583			     FIF_PROBE_REQ));
584
585	*total_flags &= FIF_OTHER_BSS |
586			FIF_FCSFAIL |
587			FIF_BCN_PRBRESP_PROMISC |
588			FIF_PROBE_REQ;
589
590	down(&priv->scan.lock);
591	mutex_lock(&priv->conf_mutex);
592
593	priv->rx_filter.promiscuous = 0;
594	priv->rx_filter.bssid = (*total_flags & (FIF_OTHER_BSS |
595			FIF_PROBE_REQ)) ? 1 : 0;
596	priv->rx_filter.fcs = (*total_flags & FIF_FCSFAIL) ? 1 : 0;
597	priv->disable_beacon_filter = !(*total_flags &
598					(FIF_BCN_PRBRESP_PROMISC |
599					 FIF_PROBE_REQ));
600	if (priv->listening != listening) {
601		priv->listening = listening;
602		wsm_lock_tx(priv);
603		cw1200_update_listening(priv, listening);
604		wsm_unlock_tx(priv);
605	}
606	cw1200_update_filtering(priv);
607	mutex_unlock(&priv->conf_mutex);
608	up(&priv->scan.lock);
609}
610
611int cw1200_conf_tx(struct ieee80211_hw *dev, struct ieee80211_vif *vif,
612		   u16 queue, const struct ieee80211_tx_queue_params *params)
613{
614	struct cw1200_common *priv = dev->priv;
615	int ret = 0;
616	/* To prevent re-applying PM request OID again and again*/
617	bool old_uapsd_flags;
618
619	mutex_lock(&priv->conf_mutex);
620
621	if (queue < dev->queues) {
622		old_uapsd_flags = le16_to_cpu(priv->uapsd_info.uapsd_flags);
623
624		WSM_TX_QUEUE_SET(&priv->tx_queue_params, queue, 0, 0, 0);
625		ret = wsm_set_tx_queue_params(priv,
626					      &priv->tx_queue_params.params[queue], queue);
627		if (ret) {
628			ret = -EINVAL;
629			goto out;
630		}
631
632		WSM_EDCA_SET(&priv->edca, queue, params->aifs,
633			     params->cw_min, params->cw_max,
634			     params->txop, 0xc8,
635			     params->uapsd);
636		ret = wsm_set_edca_params(priv, &priv->edca);
637		if (ret) {
638			ret = -EINVAL;
639			goto out;
640		}
641
642		if (priv->mode == NL80211_IFTYPE_STATION) {
643			ret = cw1200_set_uapsd_param(priv, &priv->edca);
644			if (!ret && priv->setbssparams_done &&
645			    (priv->join_status == CW1200_JOIN_STATUS_STA) &&
646			    (old_uapsd_flags != le16_to_cpu(priv->uapsd_info.uapsd_flags)))
647				ret = cw1200_set_pm(priv, &priv->powersave_mode);
648		}
649	} else {
650		ret = -EINVAL;
651	}
652
653out:
654	mutex_unlock(&priv->conf_mutex);
655	return ret;
656}
657
658int cw1200_get_stats(struct ieee80211_hw *dev,
659		     struct ieee80211_low_level_stats *stats)
660{
661	struct cw1200_common *priv = dev->priv;
662
663	memcpy(stats, &priv->stats, sizeof(*stats));
664	return 0;
665}
666
667int cw1200_set_pm(struct cw1200_common *priv, const struct wsm_set_pm *arg)
668{
669	struct wsm_set_pm pm = *arg;
670
671	if (priv->uapsd_info.uapsd_flags != 0)
672		pm.mode &= ~WSM_PSM_FAST_PS_FLAG;
673
674	if (memcmp(&pm, &priv->firmware_ps_mode,
675		   sizeof(struct wsm_set_pm))) {
676		priv->firmware_ps_mode = pm;
677		return wsm_set_pm(priv, &pm);
678	} else {
679		return 0;
680	}
681}
682
683int cw1200_set_key(struct ieee80211_hw *dev, enum set_key_cmd cmd,
684		   struct ieee80211_vif *vif, struct ieee80211_sta *sta,
685		   struct ieee80211_key_conf *key)
686{
687	int ret = -EOPNOTSUPP;
688	struct cw1200_common *priv = dev->priv;
689	struct ieee80211_key_seq seq;
690
691	mutex_lock(&priv->conf_mutex);
692
693	if (cmd == SET_KEY) {
694		u8 *peer_addr = NULL;
695		int pairwise = (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) ?
696			1 : 0;
697		int idx = cw1200_alloc_key(priv);
698		struct wsm_add_key *wsm_key = &priv->keys[idx];
699
700		if (idx < 0) {
701			ret = -EINVAL;
702			goto finally;
703		}
704
705		if (sta)
706			peer_addr = sta->addr;
707
708		key->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE |
709			      IEEE80211_KEY_FLAG_RESERVE_TAILROOM;
710
711		switch (key->cipher) {
712		case WLAN_CIPHER_SUITE_WEP40:
713		case WLAN_CIPHER_SUITE_WEP104:
714			if (key->keylen > 16) {
715				cw1200_free_key(priv, idx);
716				ret = -EINVAL;
717				goto finally;
718			}
719
720			if (pairwise) {
721				wsm_key->type = WSM_KEY_TYPE_WEP_PAIRWISE;
722				memcpy(wsm_key->wep_pairwise.peer,
723				       peer_addr, ETH_ALEN);
724				memcpy(wsm_key->wep_pairwise.keydata,
725				       &key->key[0], key->keylen);
726				wsm_key->wep_pairwise.keylen = key->keylen;
727			} else {
728				wsm_key->type = WSM_KEY_TYPE_WEP_DEFAULT;
729				memcpy(wsm_key->wep_group.keydata,
730				       &key->key[0], key->keylen);
731				wsm_key->wep_group.keylen = key->keylen;
732				wsm_key->wep_group.keyid = key->keyidx;
733			}
734			break;
735		case WLAN_CIPHER_SUITE_TKIP:
736			ieee80211_get_key_rx_seq(key, 0, &seq);
737			if (pairwise) {
738				wsm_key->type = WSM_KEY_TYPE_TKIP_PAIRWISE;
739				memcpy(wsm_key->tkip_pairwise.peer,
740				       peer_addr, ETH_ALEN);
741				memcpy(wsm_key->tkip_pairwise.keydata,
742				       &key->key[0], 16);
743				memcpy(wsm_key->tkip_pairwise.tx_mic_key,
744				       &key->key[16], 8);
745				memcpy(wsm_key->tkip_pairwise.rx_mic_key,
746				       &key->key[24], 8);
747			} else {
748				size_t mic_offset =
749					(priv->mode == NL80211_IFTYPE_AP) ?
750					16 : 24;
751				wsm_key->type = WSM_KEY_TYPE_TKIP_GROUP;
752				memcpy(wsm_key->tkip_group.keydata,
753				       &key->key[0], 16);
754				memcpy(wsm_key->tkip_group.rx_mic_key,
755				       &key->key[mic_offset], 8);
756
757				wsm_key->tkip_group.rx_seqnum[0] = seq.tkip.iv16 & 0xff;
758				wsm_key->tkip_group.rx_seqnum[1] = (seq.tkip.iv16 >> 8) & 0xff;
759				wsm_key->tkip_group.rx_seqnum[2] = seq.tkip.iv32 & 0xff;
760				wsm_key->tkip_group.rx_seqnum[3] = (seq.tkip.iv32 >> 8) & 0xff;
761				wsm_key->tkip_group.rx_seqnum[4] = (seq.tkip.iv32 >> 16) & 0xff;
762				wsm_key->tkip_group.rx_seqnum[5] = (seq.tkip.iv32 >> 24) & 0xff;
763				wsm_key->tkip_group.rx_seqnum[6] = 0;
764				wsm_key->tkip_group.rx_seqnum[7] = 0;
765
766				wsm_key->tkip_group.keyid = key->keyidx;
767			}
768			break;
769		case WLAN_CIPHER_SUITE_CCMP:
770			ieee80211_get_key_rx_seq(key, 0, &seq);
771			if (pairwise) {
772				wsm_key->type = WSM_KEY_TYPE_AES_PAIRWISE;
773				memcpy(wsm_key->aes_pairwise.peer,
774				       peer_addr, ETH_ALEN);
775				memcpy(wsm_key->aes_pairwise.keydata,
776				       &key->key[0], 16);
777			} else {
778				wsm_key->type = WSM_KEY_TYPE_AES_GROUP;
779				memcpy(wsm_key->aes_group.keydata,
780				       &key->key[0], 16);
781
782				wsm_key->aes_group.rx_seqnum[0] = seq.ccmp.pn[5];
783				wsm_key->aes_group.rx_seqnum[1] = seq.ccmp.pn[4];
784				wsm_key->aes_group.rx_seqnum[2] = seq.ccmp.pn[3];
785				wsm_key->aes_group.rx_seqnum[3] = seq.ccmp.pn[2];
786				wsm_key->aes_group.rx_seqnum[4] = seq.ccmp.pn[1];
787				wsm_key->aes_group.rx_seqnum[5] = seq.ccmp.pn[0];
788				wsm_key->aes_group.rx_seqnum[6] = 0;
789				wsm_key->aes_group.rx_seqnum[7] = 0;
790				wsm_key->aes_group.keyid = key->keyidx;
791			}
792			break;
793		case WLAN_CIPHER_SUITE_SMS4:
794			if (pairwise) {
795				wsm_key->type = WSM_KEY_TYPE_WAPI_PAIRWISE;
796				memcpy(wsm_key->wapi_pairwise.peer,
797				       peer_addr, ETH_ALEN);
798				memcpy(wsm_key->wapi_pairwise.keydata,
799				       &key->key[0], 16);
800				memcpy(wsm_key->wapi_pairwise.mic_key,
801				       &key->key[16], 16);
802				wsm_key->wapi_pairwise.keyid = key->keyidx;
803			} else {
804				wsm_key->type = WSM_KEY_TYPE_WAPI_GROUP;
805				memcpy(wsm_key->wapi_group.keydata,
806				       &key->key[0],  16);
807				memcpy(wsm_key->wapi_group.mic_key,
808				       &key->key[16], 16);
809				wsm_key->wapi_group.keyid = key->keyidx;
810			}
811			break;
812		default:
813			pr_warn("Unhandled key type %d\n", key->cipher);
814			cw1200_free_key(priv, idx);
815			ret = -EOPNOTSUPP;
816			goto finally;
817		}
818		ret = wsm_add_key(priv, wsm_key);
819		if (!ret)
820			key->hw_key_idx = idx;
821		else
822			cw1200_free_key(priv, idx);
823	} else if (cmd == DISABLE_KEY) {
824		struct wsm_remove_key wsm_key = {
825			.index = key->hw_key_idx,
826		};
827
828		if (wsm_key.index > WSM_KEY_MAX_INDEX) {
829			ret = -EINVAL;
830			goto finally;
831		}
832
833		cw1200_free_key(priv, wsm_key.index);
834		ret = wsm_remove_key(priv, &wsm_key);
835	} else {
836		pr_warn("Unhandled key command %d\n", cmd);
837	}
838
839finally:
840	mutex_unlock(&priv->conf_mutex);
841	return ret;
842}
843
844void cw1200_wep_key_work(struct work_struct *work)
845{
846	struct cw1200_common *priv =
847		container_of(work, struct cw1200_common, wep_key_work);
848	u8 queue_id = cw1200_queue_get_queue_id(priv->pending_frame_id);
849	struct cw1200_queue *queue = &priv->tx_queue[queue_id];
850	__le32 wep_default_key_id = __cpu_to_le32(
851		priv->wep_default_key_id);
852
853	pr_debug("[STA] Setting default WEP key: %d\n",
854		 priv->wep_default_key_id);
855	wsm_flush_tx(priv);
856	wsm_write_mib(priv, WSM_MIB_ID_DOT11_WEP_DEFAULT_KEY_ID,
857		      &wep_default_key_id, sizeof(wep_default_key_id));
858	cw1200_queue_requeue(queue, priv->pending_frame_id);
859	wsm_unlock_tx(priv);
860}
861
862int cw1200_set_rts_threshold(struct ieee80211_hw *hw, u32 value)
863{
864	int ret = 0;
865	__le32 val32;
866	struct cw1200_common *priv = hw->priv;
867
868	if (priv->mode == NL80211_IFTYPE_UNSPECIFIED)
869		return 0;
870
871	if (value != (u32) -1)
872		val32 = __cpu_to_le32(value);
873	else
874		val32 = 0; /* disabled */
875
876	if (priv->mode == NL80211_IFTYPE_UNSPECIFIED) {
877		/* device is down, can _not_ set threshold */
878		ret = -ENODEV;
879		goto out;
880	}
881
882	if (priv->rts_threshold == value)
883		goto out;
884
885	pr_debug("[STA] Setting RTS threshold: %d\n",
886		 priv->rts_threshold);
887
888	/* mutex_lock(&priv->conf_mutex); */
889	ret = wsm_write_mib(priv, WSM_MIB_ID_DOT11_RTS_THRESHOLD,
890			    &val32, sizeof(val32));
891	if (!ret)
892		priv->rts_threshold = value;
893	/* mutex_unlock(&priv->conf_mutex); */
894
895out:
896	return ret;
897}
898
899/* If successful, LOCKS the TX queue! */
900static int __cw1200_flush(struct cw1200_common *priv, bool drop)
901{
902	int i, ret;
903
904	for (;;) {
905		/* TODO: correct flush handling is required when dev_stop.
906		 * Temporary workaround: 2s
907		 */
908		if (drop) {
909			for (i = 0; i < 4; ++i)
910				cw1200_queue_clear(&priv->tx_queue[i]);
911		} else {
912			ret = wait_event_timeout(
913				priv->tx_queue_stats.wait_link_id_empty,
914				cw1200_queue_stats_is_empty(
915					&priv->tx_queue_stats, -1),
916				2 * HZ);
917		}
918
919		if (!drop && ret <= 0) {
920			ret = -ETIMEDOUT;
921			break;
922		} else {
923			ret = 0;
924		}
925
926		wsm_lock_tx(priv);
927		if (!cw1200_queue_stats_is_empty(&priv->tx_queue_stats, -1)) {
928			/* Highly unlikely: WSM requeued frames. */
929			wsm_unlock_tx(priv);
930			continue;
931		}
932		break;
933	}
934	return ret;
935}
936
937void cw1200_flush(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
938		  u32 queues, bool drop)
939{
940	struct cw1200_common *priv = hw->priv;
941
942	switch (priv->mode) {
943	case NL80211_IFTYPE_MONITOR:
944		drop = true;
945		break;
946	case NL80211_IFTYPE_AP:
947		if (!priv->enable_beacon)
948			drop = true;
949		break;
950	}
951
952	if (!__cw1200_flush(priv, drop))
953		wsm_unlock_tx(priv);
954
955	return;
956}
957
958/* ******************************************************************** */
959/* WSM callbacks							*/
960
961void cw1200_free_event_queue(struct cw1200_common *priv)
962{
963	LIST_HEAD(list);
964
965	spin_lock(&priv->event_queue_lock);
966	list_splice_init(&priv->event_queue, &list);
967	spin_unlock(&priv->event_queue_lock);
968
969	__cw1200_free_event_queue(&list);
970}
971
972void cw1200_event_handler(struct work_struct *work)
973{
974	struct cw1200_common *priv =
975		container_of(work, struct cw1200_common, event_handler);
976	struct cw1200_wsm_event *event;
977	LIST_HEAD(list);
978
979	spin_lock(&priv->event_queue_lock);
980	list_splice_init(&priv->event_queue, &list);
981	spin_unlock(&priv->event_queue_lock);
982
983	list_for_each_entry(event, &list, link) {
984		switch (event->evt.id) {
985		case WSM_EVENT_ERROR:
986			pr_err("Unhandled WSM Error from LMAC\n");
987			break;
988		case WSM_EVENT_BSS_LOST:
989			pr_debug("[CQM] BSS lost.\n");
990			cancel_work_sync(&priv->unjoin_work);
991			if (!down_trylock(&priv->scan.lock)) {
992				cw1200_cqm_bssloss_sm(priv, 1, 0, 0);
993				up(&priv->scan.lock);
994			} else {
995				/* Scan is in progress. Delay reporting.
996				 * Scan complete will trigger bss_loss_work
997				 */
998				priv->delayed_link_loss = 1;
999				/* Also start a watchdog. */
1000				queue_delayed_work(priv->workqueue,
1001						   &priv->bss_loss_work, 5*HZ);
1002			}
1003			break;
1004		case WSM_EVENT_BSS_REGAINED:
1005			pr_debug("[CQM] BSS regained.\n");
1006			cw1200_cqm_bssloss_sm(priv, 0, 0, 0);
1007			cancel_work_sync(&priv->unjoin_work);
1008			break;
1009		case WSM_EVENT_RADAR_DETECTED:
1010			wiphy_info(priv->hw->wiphy, "radar pulse detected\n");
1011			break;
1012		case WSM_EVENT_RCPI_RSSI:
1013		{
1014			/* RSSI: signed Q8.0, RCPI: unsigned Q7.1
1015			 * RSSI = RCPI / 2 - 110
1016			 */
1017			int rcpi_rssi = (int)(event->evt.data & 0xFF);
1018			int cqm_evt;
1019			if (priv->cqm_use_rssi)
1020				rcpi_rssi = (s8)rcpi_rssi;
1021			else
1022				rcpi_rssi =  rcpi_rssi / 2 - 110;
1023
1024			cqm_evt = (rcpi_rssi <= priv->cqm_rssi_thold) ?
1025				NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW :
1026				NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH;
1027			pr_debug("[CQM] RSSI event: %d.\n", rcpi_rssi);
1028			ieee80211_cqm_rssi_notify(priv->vif, cqm_evt,
1029						  GFP_KERNEL);
1030			break;
1031		}
1032		case WSM_EVENT_BT_INACTIVE:
1033			pr_warn("Unhandled BT INACTIVE from LMAC\n");
1034			break;
1035		case WSM_EVENT_BT_ACTIVE:
1036			pr_warn("Unhandled BT ACTIVE from LMAC\n");
1037			break;
1038		}
1039	}
1040	__cw1200_free_event_queue(&list);
1041}
1042
1043void cw1200_bss_loss_work(struct work_struct *work)
1044{
1045	struct cw1200_common *priv =
1046		container_of(work, struct cw1200_common, bss_loss_work.work);
1047
1048	pr_debug("[CQM] Reporting connection loss.\n");
1049	wsm_lock_tx(priv);
1050	if (queue_work(priv->workqueue, &priv->unjoin_work) <= 0)
1051		wsm_unlock_tx(priv);
1052}
1053
1054void cw1200_bss_params_work(struct work_struct *work)
1055{
1056	struct cw1200_common *priv =
1057		container_of(work, struct cw1200_common, bss_params_work);
1058	mutex_lock(&priv->conf_mutex);
1059
1060	priv->bss_params.reset_beacon_loss = 1;
1061	wsm_set_bss_params(priv, &priv->bss_params);
1062	priv->bss_params.reset_beacon_loss = 0;
1063
1064	mutex_unlock(&priv->conf_mutex);
1065}
1066
1067/* ******************************************************************** */
1068/* Internal API								*/
1069
1070/* This function is called to Parse the SDD file
1071 * to extract listen_interval and PTA related information
1072 * sdd is a TLV: u8 id, u8 len, u8 data[]
1073 */
1074static int cw1200_parse_sdd_file(struct cw1200_common *priv)
1075{
1076	const u8 *p = priv->sdd->data;
1077	int ret = 0;
1078
1079	while (p + 2 <= priv->sdd->data + priv->sdd->size) {
1080		if (p + p[1] + 2 > priv->sdd->data + priv->sdd->size) {
1081			pr_warn("Malformed sdd structure\n");
1082			return -1;
1083		}
1084		switch (p[0]) {
1085		case SDD_PTA_CFG_ELT_ID: {
1086			u16 v;
1087			if (p[1] < 4) {
1088				pr_warn("SDD_PTA_CFG_ELT_ID malformed\n");
1089				ret = -1;
1090				break;
1091			}
1092			v = le16_to_cpu(*((__le16 *)(p + 2)));
1093			if (!v)  /* non-zero means this is enabled */
1094				break;
1095
1096			v = le16_to_cpu(*((__le16 *)(p + 4)));
1097			priv->conf_listen_interval = (v >> 7) & 0x1F;
1098			pr_debug("PTA found; Listen Interval %d\n",
1099				 priv->conf_listen_interval);
1100			break;
1101		}
1102		case SDD_REFERENCE_FREQUENCY_ELT_ID: {
1103			u16 clk = le16_to_cpu(*((__le16 *)(p + 2)));
1104			if (clk != priv->hw_refclk)
1105				pr_warn("SDD file doesn't match configured refclk (%d vs %d)\n",
1106					clk, priv->hw_refclk);
1107			break;
1108		}
1109		default:
1110			break;
1111		}
1112		p += p[1] + 2;
1113	}
1114
1115	if (!priv->bt_present) {
1116		pr_debug("PTA element NOT found.\n");
1117		priv->conf_listen_interval = 0;
1118	}
1119	return ret;
1120}
1121
1122int cw1200_setup_mac(struct cw1200_common *priv)
1123{
1124	int ret = 0;
1125
1126	/* NOTE: There is a bug in FW: it reports signal
1127	 * as RSSI if RSSI subscription is enabled.
1128	 * It's not enough to set WSM_RCPI_RSSI_USE_RSSI.
1129	 *
1130	 * NOTE2: RSSI based reports have been switched to RCPI, since
1131	 * FW has a bug and RSSI reported values are not stable,
1132	 * what can leads to signal level oscilations in user-end applications
1133	 */
1134	struct wsm_rcpi_rssi_threshold threshold = {
1135		.rssiRcpiMode = WSM_RCPI_RSSI_THRESHOLD_ENABLE |
1136		WSM_RCPI_RSSI_DONT_USE_UPPER |
1137		WSM_RCPI_RSSI_DONT_USE_LOWER,
1138		.rollingAverageCount = 16,
1139	};
1140
1141	struct wsm_configuration cfg = {
1142		.dot11StationId = &priv->mac_addr[0],
1143	};
1144
1145	/* Remember the decission here to make sure, we will handle
1146	 * the RCPI/RSSI value correctly on WSM_EVENT_RCPI_RSS
1147	 */
1148	if (threshold.rssiRcpiMode & WSM_RCPI_RSSI_USE_RSSI)
1149		priv->cqm_use_rssi = true;
1150
1151	if (!priv->sdd) {
1152		ret = request_firmware(&priv->sdd, priv->sdd_path, priv->pdev);
1153		if (ret) {
1154			pr_err("Can't load sdd file %s.\n", priv->sdd_path);
1155			return ret;
1156		}
1157		cw1200_parse_sdd_file(priv);
1158	}
1159
1160	cfg.dpdData = priv->sdd->data;
1161	cfg.dpdData_size = priv->sdd->size;
1162	ret = wsm_configuration(priv, &cfg);
1163	if (ret)
1164		return ret;
1165
1166	/* Configure RSSI/SCPI reporting as RSSI. */
1167	wsm_set_rcpi_rssi_threshold(priv, &threshold);
1168
1169	return 0;
1170}
1171
1172static void cw1200_join_complete(struct cw1200_common *priv)
1173{
1174	pr_debug("[STA] Join complete (%d)\n", priv->join_complete_status);
1175
1176	priv->join_pending = false;
1177	if (priv->join_complete_status) {
1178		priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
1179		cw1200_update_listening(priv, priv->listening);
1180		cw1200_do_unjoin(priv);
1181		ieee80211_connection_loss(priv->vif);
1182	} else {
1183		if (priv->mode == NL80211_IFTYPE_ADHOC)
1184			priv->join_status = CW1200_JOIN_STATUS_IBSS;
1185		else
1186			priv->join_status = CW1200_JOIN_STATUS_PRE_STA;
1187	}
1188	wsm_unlock_tx(priv); /* Clearing the lock held before do_join() */
1189}
1190
1191void cw1200_join_complete_work(struct work_struct *work)
1192{
1193	struct cw1200_common *priv =
1194		container_of(work, struct cw1200_common, join_complete_work);
1195	mutex_lock(&priv->conf_mutex);
1196	cw1200_join_complete(priv);
1197	mutex_unlock(&priv->conf_mutex);
1198}
1199
1200void cw1200_join_complete_cb(struct cw1200_common *priv,
1201			     struct wsm_join_complete *arg)
1202{
1203	pr_debug("[STA] cw1200_join_complete_cb called, status=%d.\n",
1204		 arg->status);
1205
1206	if (cancel_delayed_work(&priv->join_timeout)) {
1207		priv->join_complete_status = arg->status;
1208		queue_work(priv->workqueue, &priv->join_complete_work);
1209	}
1210}
1211
1212/* MUST be called with tx_lock held!  It will be unlocked for us. */
1213static void cw1200_do_join(struct cw1200_common *priv)
1214{
1215	const u8 *bssid;
1216	struct ieee80211_bss_conf *conf = &priv->vif->bss_conf;
1217	struct cfg80211_bss *bss = NULL;
1218	struct wsm_protected_mgmt_policy mgmt_policy;
1219	struct wsm_join join = {
1220		.mode = conf->ibss_joined ?
1221				WSM_JOIN_MODE_IBSS : WSM_JOIN_MODE_BSS,
1222		.preamble_type = WSM_JOIN_PREAMBLE_LONG,
1223		.probe_for_join = 1,
1224		.atim_window = 0,
1225		.basic_rate_set = cw1200_rate_mask_to_wsm(priv,
1226							  conf->basic_rates),
1227	};
1228	if (delayed_work_pending(&priv->join_timeout)) {
1229		pr_warn("[STA] - Join request already pending, skipping..\n");
1230		wsm_unlock_tx(priv);
1231		return;
1232	}
1233
1234	if (priv->join_status)
1235		cw1200_do_unjoin(priv);
1236
1237	bssid = priv->vif->bss_conf.bssid;
1238
1239	bss = cfg80211_get_bss(priv->hw->wiphy, priv->channel, bssid, NULL, 0,
1240			       IEEE80211_BSS_TYPE_ANY, IEEE80211_PRIVACY_ANY);
1241
1242	if (!bss && !conf->ibss_joined) {
1243		wsm_unlock_tx(priv);
1244		return;
1245	}
1246
1247	mutex_lock(&priv->conf_mutex);
1248
1249	/* Under the conf lock: check scan status and
1250	 * bail out if it is in progress.
1251	 */
1252	if (atomic_read(&priv->scan.in_progress)) {
1253		wsm_unlock_tx(priv);
1254		goto done_put;
1255	}
1256
1257	priv->join_pending = true;
1258
1259	/* Sanity check basic rates */
1260	if (!join.basic_rate_set)
1261		join.basic_rate_set = 7;
1262
1263	/* Sanity check beacon interval */
1264	if (!priv->beacon_int)
1265		priv->beacon_int = 1;
1266
1267	join.beacon_interval = priv->beacon_int;
1268
1269	/* BT Coex related changes */
1270	if (priv->bt_present) {
1271		if (((priv->conf_listen_interval * 100) %
1272		     priv->beacon_int) == 0)
1273			priv->listen_interval =
1274				((priv->conf_listen_interval * 100) /
1275				 priv->beacon_int);
1276		else
1277			priv->listen_interval =
1278				((priv->conf_listen_interval * 100) /
1279				 priv->beacon_int + 1);
1280	}
1281
1282	if (priv->hw->conf.ps_dtim_period)
1283		priv->join_dtim_period = priv->hw->conf.ps_dtim_period;
1284	join.dtim_period = priv->join_dtim_period;
1285
1286	join.channel_number = priv->channel->hw_value;
1287	join.band = (priv->channel->band == IEEE80211_BAND_5GHZ) ?
1288		WSM_PHY_BAND_5G : WSM_PHY_BAND_2_4G;
1289
1290	memcpy(join.bssid, bssid, sizeof(join.bssid));
1291
1292	pr_debug("[STA] Join BSSID: %pM DTIM: %d, interval: %d\n",
1293		 join.bssid,
1294		 join.dtim_period, priv->beacon_int);
1295
1296	if (!conf->ibss_joined) {
1297		const u8 *ssidie;
1298		rcu_read_lock();
1299		ssidie = ieee80211_bss_get_ie(bss, WLAN_EID_SSID);
1300		if (ssidie) {
1301			join.ssid_len = ssidie[1];
1302			memcpy(join.ssid, &ssidie[2], join.ssid_len);
1303		}
1304		rcu_read_unlock();
1305	}
1306
1307	if (priv->vif->p2p) {
1308		join.flags |= WSM_JOIN_FLAGS_P2P_GO;
1309		join.basic_rate_set =
1310			cw1200_rate_mask_to_wsm(priv, 0xFF0);
1311	}
1312
1313	/* Enable asynchronous join calls */
1314	if (!conf->ibss_joined) {
1315		join.flags |= WSM_JOIN_FLAGS_FORCE;
1316		join.flags |= WSM_JOIN_FLAGS_FORCE_WITH_COMPLETE_IND;
1317	}
1318
1319	wsm_flush_tx(priv);
1320
1321	/* Stay Awake for Join and Auth Timeouts and a bit more */
1322	cw1200_pm_stay_awake(&priv->pm_state,
1323			     CW1200_JOIN_TIMEOUT + CW1200_AUTH_TIMEOUT);
1324
1325	cw1200_update_listening(priv, false);
1326
1327	/* Turn on Block ACKs */
1328	wsm_set_block_ack_policy(priv, priv->ba_tx_tid_mask,
1329				 priv->ba_rx_tid_mask);
1330
1331	/* Set up timeout */
1332	if (join.flags & WSM_JOIN_FLAGS_FORCE_WITH_COMPLETE_IND) {
1333		priv->join_status = CW1200_JOIN_STATUS_JOINING;
1334		queue_delayed_work(priv->workqueue,
1335				   &priv->join_timeout,
1336				   CW1200_JOIN_TIMEOUT);
1337	}
1338
1339	/* 802.11w protected mgmt frames */
1340	mgmt_policy.protectedMgmtEnable = 0;
1341	mgmt_policy.unprotectedMgmtFramesAllowed = 1;
1342	mgmt_policy.encryptionForAuthFrame = 1;
1343	wsm_set_protected_mgmt_policy(priv, &mgmt_policy);
1344
1345	/* Perform actual join */
1346	if (wsm_join(priv, &join)) {
1347		pr_err("[STA] cw1200_join_work: wsm_join failed!\n");
1348		cancel_delayed_work_sync(&priv->join_timeout);
1349		cw1200_update_listening(priv, priv->listening);
1350		/* Tx lock still held, unjoin will clear it. */
1351		if (queue_work(priv->workqueue, &priv->unjoin_work) <= 0)
1352			wsm_unlock_tx(priv);
1353	} else {
1354		if (!(join.flags & WSM_JOIN_FLAGS_FORCE_WITH_COMPLETE_IND))
1355			cw1200_join_complete(priv); /* Will clear tx_lock */
1356
1357		/* Upload keys */
1358		cw1200_upload_keys(priv);
1359
1360		/* Due to beacon filtering it is possible that the
1361		 * AP's beacon is not known for the mac80211 stack.
1362		 * Disable filtering temporary to make sure the stack
1363		 * receives at least one
1364		 */
1365		priv->disable_beacon_filter = true;
1366	}
1367	cw1200_update_filtering(priv);
1368
1369done_put:
1370	mutex_unlock(&priv->conf_mutex);
1371	if (bss)
1372		cfg80211_put_bss(priv->hw->wiphy, bss);
1373}
1374
1375void cw1200_join_timeout(struct work_struct *work)
1376{
1377	struct cw1200_common *priv =
1378		container_of(work, struct cw1200_common, join_timeout.work);
1379	pr_debug("[WSM] Join timed out.\n");
1380	wsm_lock_tx(priv);
1381	if (queue_work(priv->workqueue, &priv->unjoin_work) <= 0)
1382		wsm_unlock_tx(priv);
1383}
1384
1385static void cw1200_do_unjoin(struct cw1200_common *priv)
1386{
1387	struct wsm_reset reset = {
1388		.reset_statistics = true,
1389	};
1390
1391	cancel_delayed_work_sync(&priv->join_timeout);
1392
1393	mutex_lock(&priv->conf_mutex);
1394	priv->join_pending = false;
1395
1396	if (atomic_read(&priv->scan.in_progress)) {
1397		if (priv->delayed_unjoin)
1398			wiphy_dbg(priv->hw->wiphy, "Delayed unjoin is already scheduled.\n");
1399		else
1400			priv->delayed_unjoin = true;
1401		goto done;
1402	}
1403
1404	priv->delayed_link_loss = false;
1405
1406	if (!priv->join_status)
1407		goto done;
1408
1409	if (priv->join_status == CW1200_JOIN_STATUS_AP)
1410		goto done;
1411
1412	cancel_work_sync(&priv->update_filtering_work);
1413	cancel_work_sync(&priv->set_beacon_wakeup_period_work);
1414	priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
1415
1416	/* Unjoin is a reset. */
1417	wsm_flush_tx(priv);
1418	wsm_keep_alive_period(priv, 0);
1419	wsm_reset(priv, &reset);
1420	wsm_set_output_power(priv, priv->output_power * 10);
1421	priv->join_dtim_period = 0;
1422	cw1200_setup_mac(priv);
1423	cw1200_free_event_queue(priv);
1424	cancel_work_sync(&priv->event_handler);
1425	cw1200_update_listening(priv, priv->listening);
1426	cw1200_cqm_bssloss_sm(priv, 0, 0, 0);
1427
1428	/* Disable Block ACKs */
1429	wsm_set_block_ack_policy(priv, 0, 0);
1430
1431	priv->disable_beacon_filter = false;
1432	cw1200_update_filtering(priv);
1433	memset(&priv->association_mode, 0,
1434	       sizeof(priv->association_mode));
1435	memset(&priv->bss_params, 0, sizeof(priv->bss_params));
1436	priv->setbssparams_done = false;
1437	memset(&priv->firmware_ps_mode, 0,
1438	       sizeof(priv->firmware_ps_mode));
1439
1440	pr_debug("[STA] Unjoin completed.\n");
1441
1442done:
1443	mutex_unlock(&priv->conf_mutex);
1444}
1445
1446void cw1200_unjoin_work(struct work_struct *work)
1447{
1448	struct cw1200_common *priv =
1449		container_of(work, struct cw1200_common, unjoin_work);
1450
1451	cw1200_do_unjoin(priv);
1452
1453	/* Tell the stack we're dead */
1454	ieee80211_connection_loss(priv->vif);
1455
1456	wsm_unlock_tx(priv);
1457}
1458
1459int cw1200_enable_listening(struct cw1200_common *priv)
1460{
1461	struct wsm_start start = {
1462		.mode = WSM_START_MODE_P2P_DEV,
1463		.band = WSM_PHY_BAND_2_4G,
1464		.beacon_interval = 100,
1465		.dtim_period = 1,
1466		.probe_delay = 0,
1467		.basic_rate_set = 0x0F,
1468	};
1469
1470	if (priv->channel) {
1471		start.band = priv->channel->band == IEEE80211_BAND_5GHZ ?
1472			     WSM_PHY_BAND_5G : WSM_PHY_BAND_2_4G;
1473		start.channel_number = priv->channel->hw_value;
1474	} else {
1475		start.band = WSM_PHY_BAND_2_4G;
1476		start.channel_number = 1;
1477	}
1478
1479	return wsm_start(priv, &start);
1480}
1481
1482int cw1200_disable_listening(struct cw1200_common *priv)
1483{
1484	int ret;
1485	struct wsm_reset reset = {
1486		.reset_statistics = true,
1487	};
1488	ret = wsm_reset(priv, &reset);
1489	return ret;
1490}
1491
1492void cw1200_update_listening(struct cw1200_common *priv, bool enabled)
1493{
1494	if (enabled) {
1495		if (priv->join_status == CW1200_JOIN_STATUS_PASSIVE) {
1496			if (!cw1200_enable_listening(priv))
1497				priv->join_status = CW1200_JOIN_STATUS_MONITOR;
1498			wsm_set_probe_responder(priv, true);
1499		}
1500	} else {
1501		if (priv->join_status == CW1200_JOIN_STATUS_MONITOR) {
1502			if (!cw1200_disable_listening(priv))
1503				priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
1504			wsm_set_probe_responder(priv, false);
1505		}
1506	}
1507}
1508
1509int cw1200_set_uapsd_param(struct cw1200_common *priv,
1510			   const struct wsm_edca_params *arg)
1511{
1512	int ret;
1513	u16 uapsd_flags = 0;
1514
1515	/* Here's the mapping AC [queue, bit]
1516	 *  VO [0,3], VI [1, 2], BE [2, 1], BK [3, 0]
1517	 */
1518
1519	if (arg->uapsd_enable[0])
1520		uapsd_flags |= 1 << 3;
1521
1522	if (arg->uapsd_enable[1])
1523		uapsd_flags |= 1 << 2;
1524
1525	if (arg->uapsd_enable[2])
1526		uapsd_flags |= 1 << 1;
1527
1528	if (arg->uapsd_enable[3])
1529		uapsd_flags |= 1;
1530
1531	/* Currently pseudo U-APSD operation is not supported, so setting
1532	 * MinAutoTriggerInterval, MaxAutoTriggerInterval and
1533	 * AutoTriggerStep to 0
1534	 */
1535
1536	priv->uapsd_info.uapsd_flags = cpu_to_le16(uapsd_flags);
1537	priv->uapsd_info.min_auto_trigger_interval = 0;
1538	priv->uapsd_info.max_auto_trigger_interval = 0;
1539	priv->uapsd_info.auto_trigger_step = 0;
1540
1541	ret = wsm_set_uapsd_info(priv, &priv->uapsd_info);
1542	return ret;
1543}
1544
1545/* ******************************************************************** */
1546/* AP API								*/
1547
1548int cw1200_sta_add(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
1549		   struct ieee80211_sta *sta)
1550{
1551	struct cw1200_common *priv = hw->priv;
1552	struct cw1200_sta_priv *sta_priv =
1553			(struct cw1200_sta_priv *)&sta->drv_priv;
1554	struct cw1200_link_entry *entry;
1555	struct sk_buff *skb;
1556
1557	if (priv->mode != NL80211_IFTYPE_AP)
1558		return 0;
1559
1560	sta_priv->link_id = cw1200_find_link_id(priv, sta->addr);
1561	if (WARN_ON(!sta_priv->link_id)) {
1562		wiphy_info(priv->hw->wiphy,
1563			   "[AP] No more link IDs available.\n");
1564		return -ENOENT;
1565	}
1566
1567	entry = &priv->link_id_db[sta_priv->link_id - 1];
1568	spin_lock_bh(&priv->ps_state_lock);
1569	if ((sta->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_MASK) ==
1570					IEEE80211_WMM_IE_STA_QOSINFO_AC_MASK)
1571		priv->sta_asleep_mask |= BIT(sta_priv->link_id);
1572	entry->status = CW1200_LINK_HARD;
1573	while ((skb = skb_dequeue(&entry->rx_queue)))
1574		ieee80211_rx_irqsafe(priv->hw, skb);
1575	spin_unlock_bh(&priv->ps_state_lock);
1576	return 0;
1577}
1578
1579int cw1200_sta_remove(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
1580		      struct ieee80211_sta *sta)
1581{
1582	struct cw1200_common *priv = hw->priv;
1583	struct cw1200_sta_priv *sta_priv =
1584			(struct cw1200_sta_priv *)&sta->drv_priv;
1585	struct cw1200_link_entry *entry;
1586
1587	if (priv->mode != NL80211_IFTYPE_AP || !sta_priv->link_id)
1588		return 0;
1589
1590	entry = &priv->link_id_db[sta_priv->link_id - 1];
1591	spin_lock_bh(&priv->ps_state_lock);
1592	entry->status = CW1200_LINK_RESERVE;
1593	entry->timestamp = jiffies;
1594	wsm_lock_tx_async(priv);
1595	if (queue_work(priv->workqueue, &priv->link_id_work) <= 0)
1596		wsm_unlock_tx(priv);
1597	spin_unlock_bh(&priv->ps_state_lock);
1598	flush_workqueue(priv->workqueue);
1599	return 0;
1600}
1601
1602static void __cw1200_sta_notify(struct ieee80211_hw *dev,
1603				struct ieee80211_vif *vif,
1604				enum sta_notify_cmd notify_cmd,
1605				int link_id)
1606{
1607	struct cw1200_common *priv = dev->priv;
1608	u32 bit, prev;
1609
1610	/* Zero link id means "for all link IDs" */
1611	if (link_id)
1612		bit = BIT(link_id);
1613	else if (WARN_ON_ONCE(notify_cmd != STA_NOTIFY_AWAKE))
1614		bit = 0;
1615	else
1616		bit = priv->link_id_map;
1617	prev = priv->sta_asleep_mask & bit;
1618
1619	switch (notify_cmd) {
1620	case STA_NOTIFY_SLEEP:
1621		if (!prev) {
1622			if (priv->buffered_multicasts &&
1623			    !priv->sta_asleep_mask)
1624				queue_work(priv->workqueue,
1625					   &priv->multicast_start_work);
1626			priv->sta_asleep_mask |= bit;
1627		}
1628		break;
1629	case STA_NOTIFY_AWAKE:
1630		if (prev) {
1631			priv->sta_asleep_mask &= ~bit;
1632			priv->pspoll_mask &= ~bit;
1633			if (priv->tx_multicast && link_id &&
1634			    !priv->sta_asleep_mask)
1635				queue_work(priv->workqueue,
1636					   &priv->multicast_stop_work);
1637			cw1200_bh_wakeup(priv);
1638		}
1639		break;
1640	}
1641}
1642
1643void cw1200_sta_notify(struct ieee80211_hw *dev,
1644		       struct ieee80211_vif *vif,
1645		       enum sta_notify_cmd notify_cmd,
1646		       struct ieee80211_sta *sta)
1647{
1648	struct cw1200_common *priv = dev->priv;
1649	struct cw1200_sta_priv *sta_priv =
1650		(struct cw1200_sta_priv *)&sta->drv_priv;
1651
1652	spin_lock_bh(&priv->ps_state_lock);
1653	__cw1200_sta_notify(dev, vif, notify_cmd, sta_priv->link_id);
1654	spin_unlock_bh(&priv->ps_state_lock);
1655}
1656
1657static void cw1200_ps_notify(struct cw1200_common *priv,
1658		      int link_id, bool ps)
1659{
1660	if (link_id > CW1200_MAX_STA_IN_AP_MODE)
1661		return;
1662
1663	pr_debug("%s for LinkId: %d. STAs asleep: %.8X\n",
1664		 ps ? "Stop" : "Start",
1665		 link_id, priv->sta_asleep_mask);
1666
1667	__cw1200_sta_notify(priv->hw, priv->vif,
1668			    ps ? STA_NOTIFY_SLEEP : STA_NOTIFY_AWAKE, link_id);
1669}
1670
1671static int cw1200_set_tim_impl(struct cw1200_common *priv, bool aid0_bit_set)
1672{
1673	struct sk_buff *skb;
1674	struct wsm_update_ie update_ie = {
1675		.what = WSM_UPDATE_IE_BEACON,
1676		.count = 1,
1677	};
1678	u16 tim_offset, tim_length;
1679
1680	pr_debug("[AP] mcast: %s.\n", aid0_bit_set ? "ena" : "dis");
1681
1682	skb = ieee80211_beacon_get_tim(priv->hw, priv->vif,
1683			&tim_offset, &tim_length);
1684	if (!skb) {
1685		if (!__cw1200_flush(priv, true))
1686			wsm_unlock_tx(priv);
1687		return -ENOENT;
1688	}
1689
1690	if (tim_offset && tim_length >= 6) {
1691		/* Ignore DTIM count from mac80211:
1692		 * firmware handles DTIM internally.
1693		 */
1694		skb->data[tim_offset + 2] = 0;
1695
1696		/* Set/reset aid0 bit */
1697		if (aid0_bit_set)
1698			skb->data[tim_offset + 4] |= 1;
1699		else
1700			skb->data[tim_offset + 4] &= ~1;
1701	}
1702
1703	update_ie.ies = &skb->data[tim_offset];
1704	update_ie.length = tim_length;
1705	wsm_update_ie(priv, &update_ie);
1706
1707	dev_kfree_skb(skb);
1708
1709	return 0;
1710}
1711
1712void cw1200_set_tim_work(struct work_struct *work)
1713{
1714	struct cw1200_common *priv =
1715		container_of(work, struct cw1200_common, set_tim_work);
1716	(void)cw1200_set_tim_impl(priv, priv->aid0_bit_set);
1717}
1718
1719int cw1200_set_tim(struct ieee80211_hw *dev, struct ieee80211_sta *sta,
1720		   bool set)
1721{
1722	struct cw1200_common *priv = dev->priv;
1723	queue_work(priv->workqueue, &priv->set_tim_work);
1724	return 0;
1725}
1726
1727void cw1200_set_cts_work(struct work_struct *work)
1728{
1729	struct cw1200_common *priv =
1730		container_of(work, struct cw1200_common, set_cts_work);
1731
1732	u8 erp_ie[3] = {WLAN_EID_ERP_INFO, 0x1, 0};
1733	struct wsm_update_ie update_ie = {
1734		.what = WSM_UPDATE_IE_BEACON,
1735		.count = 1,
1736		.ies = erp_ie,
1737		.length = 3,
1738	};
1739	u32 erp_info;
1740	__le32 use_cts_prot;
1741	mutex_lock(&priv->conf_mutex);
1742	erp_info = priv->erp_info;
1743	mutex_unlock(&priv->conf_mutex);
1744	use_cts_prot =
1745		erp_info & WLAN_ERP_USE_PROTECTION ?
1746		__cpu_to_le32(1) : 0;
1747
1748	erp_ie[ERP_INFO_BYTE_OFFSET] = erp_info;
1749
1750	pr_debug("[STA] ERP information 0x%x\n", erp_info);
1751
1752	wsm_write_mib(priv, WSM_MIB_ID_NON_ERP_PROTECTION,
1753		      &use_cts_prot, sizeof(use_cts_prot));
1754	wsm_update_ie(priv, &update_ie);
1755
1756	return;
1757}
1758
1759static int cw1200_set_btcoexinfo(struct cw1200_common *priv)
1760{
1761	struct wsm_override_internal_txrate arg;
1762	int ret = 0;
1763
1764	if (priv->mode == NL80211_IFTYPE_STATION) {
1765		/* Plumb PSPOLL and NULL template */
1766		cw1200_upload_pspoll(priv);
1767		cw1200_upload_null(priv);
1768		cw1200_upload_qosnull(priv);
1769	} else {
1770		return 0;
1771	}
1772
1773	memset(&arg, 0, sizeof(struct wsm_override_internal_txrate));
1774
1775	if (!priv->vif->p2p) {
1776		/* STATION mode */
1777		if (priv->bss_params.operational_rate_set & ~0xF) {
1778			pr_debug("[STA] STA has ERP rates\n");
1779			/* G or BG mode */
1780			arg.internalTxRate = (__ffs(
1781			priv->bss_params.operational_rate_set & ~0xF));
1782		} else {
1783			pr_debug("[STA] STA has non ERP rates\n");
1784			/* B only mode */
1785			arg.internalTxRate = (__ffs(le32_to_cpu(priv->association_mode.basic_rate_set)));
1786		}
1787		arg.nonErpInternalTxRate = (__ffs(le32_to_cpu(priv->association_mode.basic_rate_set)));
1788	} else {
1789		/* P2P mode */
1790		arg.internalTxRate = (__ffs(priv->bss_params.operational_rate_set & ~0xF));
1791		arg.nonErpInternalTxRate = (__ffs(priv->bss_params.operational_rate_set & ~0xF));
1792	}
1793
1794	pr_debug("[STA] BTCOEX_INFO MODE %d, internalTxRate : %x, nonErpInternalTxRate: %x\n",
1795		 priv->mode,
1796		 arg.internalTxRate,
1797		 arg.nonErpInternalTxRate);
1798
1799	ret = wsm_write_mib(priv, WSM_MIB_ID_OVERRIDE_INTERNAL_TX_RATE,
1800			    &arg, sizeof(arg));
1801
1802	return ret;
1803}
1804
1805void cw1200_bss_info_changed(struct ieee80211_hw *dev,
1806			     struct ieee80211_vif *vif,
1807			     struct ieee80211_bss_conf *info,
1808			     u32 changed)
1809{
1810	struct cw1200_common *priv = dev->priv;
1811	bool do_join = false;
1812
1813	mutex_lock(&priv->conf_mutex);
1814
1815	pr_debug("BSS CHANGED:  %08x\n", changed);
1816
1817	/* TODO: BSS_CHANGED_QOS */
1818	/* TODO: BSS_CHANGED_TXPOWER */
1819
1820	if (changed & BSS_CHANGED_ARP_FILTER) {
1821		struct wsm_mib_arp_ipv4_filter filter = {0};
1822		int i;
1823
1824		pr_debug("[STA] BSS_CHANGED_ARP_FILTER cnt: %d\n",
1825			 info->arp_addr_cnt);
1826
1827		/* Currently only one IP address is supported by firmware.
1828		 * In case of more IPs arp filtering will be disabled.
1829		 */
1830		if (info->arp_addr_cnt > 0 &&
1831		    info->arp_addr_cnt <= WSM_MAX_ARP_IP_ADDRTABLE_ENTRIES) {
1832			for (i = 0; i < info->arp_addr_cnt; i++) {
1833				filter.ipv4addrs[i] = info->arp_addr_list[i];
1834				pr_debug("[STA] addr[%d]: 0x%X\n",
1835					 i, filter.ipv4addrs[i]);
1836			}
1837			filter.enable = __cpu_to_le32(1);
1838		}
1839
1840		pr_debug("[STA] arp ip filter enable: %d\n",
1841			 __le32_to_cpu(filter.enable));
1842
1843		wsm_set_arp_ipv4_filter(priv, &filter);
1844	}
1845
1846	if (changed &
1847	    (BSS_CHANGED_BEACON |
1848	     BSS_CHANGED_AP_PROBE_RESP |
1849	     BSS_CHANGED_BSSID |
1850	     BSS_CHANGED_SSID |
1851	     BSS_CHANGED_IBSS)) {
1852		pr_debug("BSS_CHANGED_BEACON\n");
1853		priv->beacon_int = info->beacon_int;
1854		cw1200_update_beaconing(priv);
1855		cw1200_upload_beacon(priv);
1856	}
1857
1858	if (changed & BSS_CHANGED_BEACON_ENABLED) {
1859		pr_debug("BSS_CHANGED_BEACON_ENABLED (%d)\n", info->enable_beacon);
1860
1861		if (priv->enable_beacon != info->enable_beacon) {
1862			cw1200_enable_beaconing(priv, info->enable_beacon);
1863			priv->enable_beacon = info->enable_beacon;
1864		}
1865	}
1866
1867	if (changed & BSS_CHANGED_BEACON_INT) {
1868		pr_debug("CHANGED_BEACON_INT\n");
1869		if (info->ibss_joined)
1870			do_join = true;
1871		else if (priv->join_status == CW1200_JOIN_STATUS_AP)
1872			cw1200_update_beaconing(priv);
1873	}
1874
1875	/* assoc/disassoc, or maybe AID changed */
1876	if (changed & BSS_CHANGED_ASSOC) {
1877		wsm_lock_tx(priv);
1878		priv->wep_default_key_id = -1;
1879		wsm_unlock_tx(priv);
1880	}
1881
1882	if (changed & BSS_CHANGED_BSSID) {
1883		pr_debug("BSS_CHANGED_BSSID\n");
1884		do_join = true;
1885	}
1886
1887	if (changed &
1888	    (BSS_CHANGED_ASSOC |
1889	     BSS_CHANGED_BSSID |
1890	     BSS_CHANGED_IBSS |
1891	     BSS_CHANGED_BASIC_RATES |
1892	     BSS_CHANGED_HT)) {
1893		pr_debug("BSS_CHANGED_ASSOC\n");
1894		if (info->assoc) {
1895			if (priv->join_status < CW1200_JOIN_STATUS_PRE_STA) {
1896				ieee80211_connection_loss(vif);
1897				mutex_unlock(&priv->conf_mutex);
1898				return;
1899			} else if (priv->join_status == CW1200_JOIN_STATUS_PRE_STA) {
1900				priv->join_status = CW1200_JOIN_STATUS_STA;
1901			}
1902		} else {
1903			do_join = true;
1904		}
1905
1906		if (info->assoc || info->ibss_joined) {
1907			struct ieee80211_sta *sta = NULL;
1908			__le32 htprot = 0;
1909
1910			if (info->dtim_period)
1911				priv->join_dtim_period = info->dtim_period;
1912			priv->beacon_int = info->beacon_int;
1913
1914			rcu_read_lock();
1915
1916			if (info->bssid && !info->ibss_joined)
1917				sta = ieee80211_find_sta(vif, info->bssid);
1918			if (sta) {
1919				priv->ht_info.ht_cap = sta->ht_cap;
1920				priv->bss_params.operational_rate_set =
1921					cw1200_rate_mask_to_wsm(priv,
1922								sta->supp_rates[priv->channel->band]);
1923				priv->ht_info.channel_type = cfg80211_get_chandef_type(&dev->conf.chandef);
1924				priv->ht_info.operation_mode = info->ht_operation_mode;
1925			} else {
1926				memset(&priv->ht_info, 0,
1927				       sizeof(priv->ht_info));
1928				priv->bss_params.operational_rate_set = -1;
1929			}
1930			rcu_read_unlock();
1931
1932			/* Non Greenfield stations present */
1933			if (priv->ht_info.operation_mode &
1934			    IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT)
1935				htprot |= cpu_to_le32(WSM_NON_GREENFIELD_STA_PRESENT);
1936
1937			/* Set HT protection method */
1938			htprot |= cpu_to_le32((priv->ht_info.operation_mode & IEEE80211_HT_OP_MODE_PROTECTION) << 2);
1939
1940			/* TODO:
1941			 * STBC_param.dual_cts
1942			 *  STBC_param.LSIG_TXOP_FILL
1943			 */
1944
1945			wsm_write_mib(priv, WSM_MIB_ID_SET_HT_PROTECTION,
1946				      &htprot, sizeof(htprot));
1947
1948			priv->association_mode.greenfield =
1949				cw1200_ht_greenfield(&priv->ht_info);
1950			priv->association_mode.flags =
1951				WSM_ASSOCIATION_MODE_SNOOP_ASSOC_FRAMES |
1952				WSM_ASSOCIATION_MODE_USE_PREAMBLE_TYPE |
1953				WSM_ASSOCIATION_MODE_USE_HT_MODE |
1954				WSM_ASSOCIATION_MODE_USE_BASIC_RATE_SET |
1955				WSM_ASSOCIATION_MODE_USE_MPDU_START_SPACING;
1956			priv->association_mode.preamble =
1957				info->use_short_preamble ?
1958				WSM_JOIN_PREAMBLE_SHORT :
1959				WSM_JOIN_PREAMBLE_LONG;
1960			priv->association_mode.basic_rate_set = __cpu_to_le32(
1961				cw1200_rate_mask_to_wsm(priv,
1962							info->basic_rates));
1963			priv->association_mode.mpdu_start_spacing =
1964				cw1200_ht_ampdu_density(&priv->ht_info);
1965
1966			cw1200_cqm_bssloss_sm(priv, 0, 0, 0);
1967			cancel_work_sync(&priv->unjoin_work);
1968
1969			priv->bss_params.beacon_lost_count = priv->cqm_beacon_loss_count;
1970			priv->bss_params.aid = info->aid;
1971
1972			if (priv->join_dtim_period < 1)
1973				priv->join_dtim_period = 1;
1974
1975			pr_debug("[STA] DTIM %d, interval: %d\n",
1976				 priv->join_dtim_period, priv->beacon_int);
1977			pr_debug("[STA] Preamble: %d, Greenfield: %d, Aid: %d, Rates: 0x%.8X, Basic: 0x%.8X\n",
1978				 priv->association_mode.preamble,
1979				 priv->association_mode.greenfield,
1980				 priv->bss_params.aid,
1981				 priv->bss_params.operational_rate_set,
1982				 priv->association_mode.basic_rate_set);
1983			wsm_set_association_mode(priv, &priv->association_mode);
1984
1985			if (!info->ibss_joined) {
1986				wsm_keep_alive_period(priv, 30 /* sec */);
1987				wsm_set_bss_params(priv, &priv->bss_params);
1988				priv->setbssparams_done = true;
1989				cw1200_set_beacon_wakeup_period_work(&priv->set_beacon_wakeup_period_work);
1990				cw1200_set_pm(priv, &priv->powersave_mode);
1991			}
1992			if (priv->vif->p2p) {
1993				pr_debug("[STA] Setting p2p powersave configuration.\n");
1994				wsm_set_p2p_ps_modeinfo(priv,
1995							&priv->p2p_ps_modeinfo);
1996			}
1997			if (priv->bt_present)
1998				cw1200_set_btcoexinfo(priv);
1999		} else {
2000			memset(&priv->association_mode, 0,
2001			       sizeof(priv->association_mode));
2002			memset(&priv->bss_params, 0, sizeof(priv->bss_params));
2003		}
2004	}
2005
2006	/* ERP Protection */
2007	if (changed & (BSS_CHANGED_ASSOC |
2008		       BSS_CHANGED_ERP_CTS_PROT |
2009		       BSS_CHANGED_ERP_PREAMBLE)) {
2010		u32 prev_erp_info = priv->erp_info;
2011		if (info->use_cts_prot)
2012			priv->erp_info |= WLAN_ERP_USE_PROTECTION;
2013		else if (!(prev_erp_info & WLAN_ERP_NON_ERP_PRESENT))
2014			priv->erp_info &= ~WLAN_ERP_USE_PROTECTION;
2015
2016		if (info->use_short_preamble)
2017			priv->erp_info |= WLAN_ERP_BARKER_PREAMBLE;
2018		else
2019			priv->erp_info &= ~WLAN_ERP_BARKER_PREAMBLE;
2020
2021		pr_debug("[STA] ERP Protection: %x\n", priv->erp_info);
2022
2023		if (prev_erp_info != priv->erp_info)
2024			queue_work(priv->workqueue, &priv->set_cts_work);
2025	}
2026
2027	/* ERP Slottime */
2028	if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_ERP_SLOT)) {
2029		__le32 slot_time = info->use_short_slot ?
2030			__cpu_to_le32(9) : __cpu_to_le32(20);
2031		pr_debug("[STA] Slot time: %d us.\n",
2032			 __le32_to_cpu(slot_time));
2033		wsm_write_mib(priv, WSM_MIB_ID_DOT11_SLOT_TIME,
2034			      &slot_time, sizeof(slot_time));
2035	}
2036
2037	if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_CQM)) {
2038		struct wsm_rcpi_rssi_threshold threshold = {
2039			.rollingAverageCount = 8,
2040		};
2041		pr_debug("[CQM] RSSI threshold subscribe: %d +- %d\n",
2042			 info->cqm_rssi_thold, info->cqm_rssi_hyst);
2043		priv->cqm_rssi_thold = info->cqm_rssi_thold;
2044		priv->cqm_rssi_hyst = info->cqm_rssi_hyst;
2045
2046		if (info->cqm_rssi_thold || info->cqm_rssi_hyst) {
2047			/* RSSI subscription enabled */
2048			/* TODO: It's not a correct way of setting threshold.
2049			 * Upper and lower must be set equal here and adjusted
2050			 * in callback. However current implementation is much
2051			 * more relaible and stable.
2052			 */
2053
2054			/* RSSI: signed Q8.0, RCPI: unsigned Q7.1
2055			 * RSSI = RCPI / 2 - 110
2056			 */
2057			if (priv->cqm_use_rssi) {
2058				threshold.upperThreshold =
2059					info->cqm_rssi_thold + info->cqm_rssi_hyst;
2060				threshold.lowerThreshold =
2061					info->cqm_rssi_thold;
2062				threshold.rssiRcpiMode |= WSM_RCPI_RSSI_USE_RSSI;
2063			} else {
2064				threshold.upperThreshold = (info->cqm_rssi_thold + info->cqm_rssi_hyst + 110) * 2;
2065				threshold.lowerThreshold = (info->cqm_rssi_thold + 110) * 2;
2066			}
2067			threshold.rssiRcpiMode |= WSM_RCPI_RSSI_THRESHOLD_ENABLE;
2068		} else {
2069			/* There is a bug in FW, see sta.c. We have to enable
2070			 * dummy subscription to get correct RSSI values.
2071			 */
2072			threshold.rssiRcpiMode |=
2073				WSM_RCPI_RSSI_THRESHOLD_ENABLE |
2074				WSM_RCPI_RSSI_DONT_USE_UPPER |
2075				WSM_RCPI_RSSI_DONT_USE_LOWER;
2076			if (priv->cqm_use_rssi)
2077				threshold.rssiRcpiMode |= WSM_RCPI_RSSI_USE_RSSI;
2078		}
2079		wsm_set_rcpi_rssi_threshold(priv, &threshold);
2080	}
2081	mutex_unlock(&priv->conf_mutex);
2082
2083	if (do_join) {
2084		wsm_lock_tx(priv);
2085		cw1200_do_join(priv); /* Will unlock it for us */
2086	}
2087}
2088
2089void cw1200_multicast_start_work(struct work_struct *work)
2090{
2091	struct cw1200_common *priv =
2092		container_of(work, struct cw1200_common, multicast_start_work);
2093	long tmo = priv->join_dtim_period *
2094			(priv->beacon_int + 20) * HZ / 1024;
2095
2096	cancel_work_sync(&priv->multicast_stop_work);
2097
2098	if (!priv->aid0_bit_set) {
2099		wsm_lock_tx(priv);
2100		cw1200_set_tim_impl(priv, true);
2101		priv->aid0_bit_set = true;
2102		mod_timer(&priv->mcast_timeout, jiffies + tmo);
2103		wsm_unlock_tx(priv);
2104	}
2105}
2106
2107void cw1200_multicast_stop_work(struct work_struct *work)
2108{
2109	struct cw1200_common *priv =
2110		container_of(work, struct cw1200_common, multicast_stop_work);
2111
2112	if (priv->aid0_bit_set) {
2113		del_timer_sync(&priv->mcast_timeout);
2114		wsm_lock_tx(priv);
2115		priv->aid0_bit_set = false;
2116		cw1200_set_tim_impl(priv, false);
2117		wsm_unlock_tx(priv);
2118	}
2119}
2120
2121void cw1200_mcast_timeout(unsigned long arg)
2122{
2123	struct cw1200_common *priv =
2124		(struct cw1200_common *)arg;
2125
2126	wiphy_warn(priv->hw->wiphy,
2127		   "Multicast delivery timeout.\n");
2128	spin_lock_bh(&priv->ps_state_lock);
2129	priv->tx_multicast = priv->aid0_bit_set &&
2130			priv->buffered_multicasts;
2131	if (priv->tx_multicast)
2132		cw1200_bh_wakeup(priv);
2133	spin_unlock_bh(&priv->ps_state_lock);
2134}
2135
2136int cw1200_ampdu_action(struct ieee80211_hw *hw,
2137			struct ieee80211_vif *vif,
2138			enum ieee80211_ampdu_mlme_action action,
2139			struct ieee80211_sta *sta, u16 tid, u16 *ssn,
2140			u8 buf_size, bool amsdu)
2141{
2142	/* Aggregation is implemented fully in firmware,
2143	 * including block ack negotiation. Do not allow
2144	 * mac80211 stack to do anything: it interferes with
2145	 * the firmware.
2146	 */
2147
2148	/* Note that we still need this function stubbed. */
2149	return -ENOTSUPP;
2150}
2151
2152/* ******************************************************************** */
2153/* WSM callback								*/
2154void cw1200_suspend_resume(struct cw1200_common *priv,
2155			  struct wsm_suspend_resume *arg)
2156{
2157	pr_debug("[AP] %s: %s\n",
2158		 arg->stop ? "stop" : "start",
2159		 arg->multicast ? "broadcast" : "unicast");
2160
2161	if (arg->multicast) {
2162		bool cancel_tmo = false;
2163		spin_lock_bh(&priv->ps_state_lock);
2164		if (arg->stop) {
2165			priv->tx_multicast = false;
2166		} else {
2167			/* Firmware sends this indication every DTIM if there
2168			 * is a STA in powersave connected. There is no reason
2169			 * to suspend, following wakeup will consume much more
2170			 * power than it could be saved.
2171			 */
2172			cw1200_pm_stay_awake(&priv->pm_state,
2173					     priv->join_dtim_period *
2174					     (priv->beacon_int + 20) * HZ / 1024);
2175			priv->tx_multicast = (priv->aid0_bit_set &&
2176					      priv->buffered_multicasts);
2177			if (priv->tx_multicast) {
2178				cancel_tmo = true;
2179				cw1200_bh_wakeup(priv);
2180			}
2181		}
2182		spin_unlock_bh(&priv->ps_state_lock);
2183		if (cancel_tmo)
2184			del_timer_sync(&priv->mcast_timeout);
2185	} else {
2186		spin_lock_bh(&priv->ps_state_lock);
2187		cw1200_ps_notify(priv, arg->link_id, arg->stop);
2188		spin_unlock_bh(&priv->ps_state_lock);
2189		if (!arg->stop)
2190			cw1200_bh_wakeup(priv);
2191	}
2192	return;
2193}
2194
2195/* ******************************************************************** */
2196/* AP privates								*/
2197
2198static int cw1200_upload_beacon(struct cw1200_common *priv)
2199{
2200	int ret = 0;
2201	struct ieee80211_mgmt *mgmt;
2202	struct wsm_template_frame frame = {
2203		.frame_type = WSM_FRAME_TYPE_BEACON,
2204	};
2205
2206	u16 tim_offset;
2207	u16 tim_len;
2208
2209	if (priv->mode == NL80211_IFTYPE_STATION ||
2210	    priv->mode == NL80211_IFTYPE_MONITOR ||
2211	    priv->mode == NL80211_IFTYPE_UNSPECIFIED)
2212		goto done;
2213
2214	if (priv->vif->p2p)
2215		frame.rate = WSM_TRANSMIT_RATE_6;
2216
2217	frame.skb = ieee80211_beacon_get_tim(priv->hw, priv->vif,
2218					     &tim_offset, &tim_len);
2219	if (!frame.skb)
2220		return -ENOMEM;
2221
2222	ret = wsm_set_template_frame(priv, &frame);
2223
2224	if (ret)
2225		goto done;
2226
2227	/* TODO: Distill probe resp; remove TIM
2228	 * and any other beacon-specific IEs
2229	 */
2230	mgmt = (void *)frame.skb->data;
2231	mgmt->frame_control =
2232		__cpu_to_le16(IEEE80211_FTYPE_MGMT |
2233			      IEEE80211_STYPE_PROBE_RESP);
2234
2235	frame.frame_type = WSM_FRAME_TYPE_PROBE_RESPONSE;
2236	if (priv->vif->p2p) {
2237		ret = wsm_set_probe_responder(priv, true);
2238	} else {
2239		ret = wsm_set_template_frame(priv, &frame);
2240		wsm_set_probe_responder(priv, false);
2241	}
2242
2243done:
2244	dev_kfree_skb(frame.skb);
2245
2246	return ret;
2247}
2248
2249static int cw1200_upload_pspoll(struct cw1200_common *priv)
2250{
2251	int ret = 0;
2252	struct wsm_template_frame frame = {
2253		.frame_type = WSM_FRAME_TYPE_PS_POLL,
2254		.rate = 0xFF,
2255	};
2256
2257
2258	frame.skb = ieee80211_pspoll_get(priv->hw, priv->vif);
2259	if (!frame.skb)
2260		return -ENOMEM;
2261
2262	ret = wsm_set_template_frame(priv, &frame);
2263
2264	dev_kfree_skb(frame.skb);
2265
2266	return ret;
2267}
2268
2269static int cw1200_upload_null(struct cw1200_common *priv)
2270{
2271	int ret = 0;
2272	struct wsm_template_frame frame = {
2273		.frame_type = WSM_FRAME_TYPE_NULL,
2274		.rate = 0xFF,
2275	};
2276
2277	frame.skb = ieee80211_nullfunc_get(priv->hw, priv->vif);
2278	if (!frame.skb)
2279		return -ENOMEM;
2280
2281	ret = wsm_set_template_frame(priv, &frame);
2282
2283	dev_kfree_skb(frame.skb);
2284
2285	return ret;
2286}
2287
2288static int cw1200_upload_qosnull(struct cw1200_common *priv)
2289{
2290	/* TODO:  This needs to be implemented
2291
2292	struct wsm_template_frame frame = {
2293		.frame_type = WSM_FRAME_TYPE_QOS_NULL,
2294		.rate = 0xFF,
2295	};
2296
2297	frame.skb = ieee80211_qosnullfunc_get(priv->hw, priv->vif);
2298	if (!frame.skb)
2299		return -ENOMEM;
2300
2301	ret = wsm_set_template_frame(priv, &frame);
2302
2303	dev_kfree_skb(frame.skb);
2304
2305	*/
2306	return 0;
2307}
2308
2309static int cw1200_enable_beaconing(struct cw1200_common *priv,
2310				   bool enable)
2311{
2312	struct wsm_beacon_transmit transmit = {
2313		.enable_beaconing = enable,
2314	};
2315
2316	return wsm_beacon_transmit(priv, &transmit);
2317}
2318
2319static int cw1200_start_ap(struct cw1200_common *priv)
2320{
2321	int ret;
2322	struct ieee80211_bss_conf *conf = &priv->vif->bss_conf;
2323	struct wsm_start start = {
2324		.mode = priv->vif->p2p ?
2325				WSM_START_MODE_P2P_GO : WSM_START_MODE_AP,
2326		.band = (priv->channel->band == IEEE80211_BAND_5GHZ) ?
2327				WSM_PHY_BAND_5G : WSM_PHY_BAND_2_4G,
2328		.channel_number = priv->channel->hw_value,
2329		.beacon_interval = conf->beacon_int,
2330		.dtim_period = conf->dtim_period,
2331		.preamble = conf->use_short_preamble ?
2332				WSM_JOIN_PREAMBLE_SHORT :
2333				WSM_JOIN_PREAMBLE_LONG,
2334		.probe_delay = 100,
2335		.basic_rate_set = cw1200_rate_mask_to_wsm(priv,
2336				conf->basic_rates),
2337	};
2338	struct wsm_operational_mode mode = {
2339		.power_mode = cw1200_power_mode,
2340		.disable_more_flag_usage = true,
2341	};
2342
2343	memset(start.ssid, 0, sizeof(start.ssid));
2344	if (!conf->hidden_ssid) {
2345		start.ssid_len = conf->ssid_len;
2346		memcpy(start.ssid, conf->ssid, start.ssid_len);
2347	}
2348
2349	priv->beacon_int = conf->beacon_int;
2350	priv->join_dtim_period = conf->dtim_period;
2351
2352	memset(&priv->link_id_db, 0, sizeof(priv->link_id_db));
2353
2354	pr_debug("[AP] ch: %d(%d), bcn: %d(%d), brt: 0x%.8X, ssid: %.*s.\n",
2355		 start.channel_number, start.band,
2356		 start.beacon_interval, start.dtim_period,
2357		 start.basic_rate_set,
2358		 start.ssid_len, start.ssid);
2359	ret = wsm_start(priv, &start);
2360	if (!ret)
2361		ret = cw1200_upload_keys(priv);
2362	if (!ret && priv->vif->p2p) {
2363		pr_debug("[AP] Setting p2p powersave configuration.\n");
2364		wsm_set_p2p_ps_modeinfo(priv, &priv->p2p_ps_modeinfo);
2365	}
2366	if (!ret) {
2367		wsm_set_block_ack_policy(priv, 0, 0);
2368		priv->join_status = CW1200_JOIN_STATUS_AP;
2369		cw1200_update_filtering(priv);
2370	}
2371	wsm_set_operational_mode(priv, &mode);
2372	return ret;
2373}
2374
2375static int cw1200_update_beaconing(struct cw1200_common *priv)
2376{
2377	struct ieee80211_bss_conf *conf = &priv->vif->bss_conf;
2378	struct wsm_reset reset = {
2379		.link_id = 0,
2380		.reset_statistics = true,
2381	};
2382
2383	if (priv->mode == NL80211_IFTYPE_AP) {
2384		/* TODO: check if changed channel, band */
2385		if (priv->join_status != CW1200_JOIN_STATUS_AP ||
2386		    priv->beacon_int != conf->beacon_int) {
2387			pr_debug("ap restarting\n");
2388			wsm_lock_tx(priv);
2389			if (priv->join_status != CW1200_JOIN_STATUS_PASSIVE)
2390				wsm_reset(priv, &reset);
2391			priv->join_status = CW1200_JOIN_STATUS_PASSIVE;
2392			cw1200_start_ap(priv);
2393			wsm_unlock_tx(priv);
2394		} else
2395			pr_debug("ap started join_status: %d\n",
2396				 priv->join_status);
2397	}
2398	return 0;
2399}
2400