1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* ZD1211 USB-WLAN driver for Linux
3  *
4  * Copyright (C) 2005-2007 Ulrich Kunitz <kune@deine-taler.de>
5  * Copyright (C) 2006-2007 Daniel Drake <dsd@gentoo.org>
6  * Copyright (C) 2006-2007 Michael Wu <flamingice@sourmilk.net>
7  * Copyright (C) 2007-2008 Luis R. Rodriguez <mcgrof@winlab.rutgers.edu>
8  */
9 
10 #include <linux/netdevice.h>
11 #include <linux/etherdevice.h>
12 #include <linux/slab.h>
13 #include <linux/usb.h>
14 #include <linux/jiffies.h>
15 #include <net/ieee80211_radiotap.h>
16 
17 #include "zd_def.h"
18 #include "zd_chip.h"
19 #include "zd_mac.h"
20 #include "zd_rf.h"
21 
22 struct zd_reg_alpha2_map {
23 	u32 reg;
24 	char alpha2[2];
25 };
26 
27 static struct zd_reg_alpha2_map reg_alpha2_map[] = {
28 	{ ZD_REGDOMAIN_FCC, "US" },
29 	{ ZD_REGDOMAIN_IC, "CA" },
30 	{ ZD_REGDOMAIN_ETSI, "DE" }, /* Generic ETSI, use most restrictive */
31 	{ ZD_REGDOMAIN_JAPAN, "JP" },
32 	{ ZD_REGDOMAIN_JAPAN_2, "JP" },
33 	{ ZD_REGDOMAIN_JAPAN_3, "JP" },
34 	{ ZD_REGDOMAIN_SPAIN, "ES" },
35 	{ ZD_REGDOMAIN_FRANCE, "FR" },
36 };
37 
38 /* This table contains the hardware specific values for the modulation rates. */
39 static const struct ieee80211_rate zd_rates[] = {
40 	{ .bitrate = 10,
41 	  .hw_value = ZD_CCK_RATE_1M, },
42 	{ .bitrate = 20,
43 	  .hw_value = ZD_CCK_RATE_2M,
44 	  .hw_value_short = ZD_CCK_RATE_2M | ZD_CCK_PREA_SHORT,
45 	  .flags = IEEE80211_RATE_SHORT_PREAMBLE },
46 	{ .bitrate = 55,
47 	  .hw_value = ZD_CCK_RATE_5_5M,
48 	  .hw_value_short = ZD_CCK_RATE_5_5M | ZD_CCK_PREA_SHORT,
49 	  .flags = IEEE80211_RATE_SHORT_PREAMBLE },
50 	{ .bitrate = 110,
51 	  .hw_value = ZD_CCK_RATE_11M,
52 	  .hw_value_short = ZD_CCK_RATE_11M | ZD_CCK_PREA_SHORT,
53 	  .flags = IEEE80211_RATE_SHORT_PREAMBLE },
54 	{ .bitrate = 60,
55 	  .hw_value = ZD_OFDM_RATE_6M,
56 	  .flags = 0 },
57 	{ .bitrate = 90,
58 	  .hw_value = ZD_OFDM_RATE_9M,
59 	  .flags = 0 },
60 	{ .bitrate = 120,
61 	  .hw_value = ZD_OFDM_RATE_12M,
62 	  .flags = 0 },
63 	{ .bitrate = 180,
64 	  .hw_value = ZD_OFDM_RATE_18M,
65 	  .flags = 0 },
66 	{ .bitrate = 240,
67 	  .hw_value = ZD_OFDM_RATE_24M,
68 	  .flags = 0 },
69 	{ .bitrate = 360,
70 	  .hw_value = ZD_OFDM_RATE_36M,
71 	  .flags = 0 },
72 	{ .bitrate = 480,
73 	  .hw_value = ZD_OFDM_RATE_48M,
74 	  .flags = 0 },
75 	{ .bitrate = 540,
76 	  .hw_value = ZD_OFDM_RATE_54M,
77 	  .flags = 0 },
78 };
79 
80 /*
81  * Zydas retry rates table. Each line is listed in the same order as
82  * in zd_rates[] and contains all the rate used when a packet is sent
83  * starting with a given rates. Let's consider an example :
84  *
85  * "11 Mbits : 4, 3, 2, 1, 0" means :
86  * - packet is sent using 4 different rates
87  * - 1st rate is index 3 (ie 11 Mbits)
88  * - 2nd rate is index 2 (ie 5.5 Mbits)
89  * - 3rd rate is index 1 (ie 2 Mbits)
90  * - 4th rate is index 0 (ie 1 Mbits)
91  */
92 
93 static const struct tx_retry_rate zd_retry_rates[] = {
94 	{ /*  1 Mbits */	1, { 0 }},
95 	{ /*  2 Mbits */	2, { 1,  0 }},
96 	{ /*  5.5 Mbits */	3, { 2,  1, 0 }},
97 	{ /* 11 Mbits */	4, { 3,  2, 1, 0 }},
98 	{ /*  6 Mbits */	5, { 4,  3, 2, 1, 0 }},
99 	{ /*  9 Mbits */	6, { 5,  4, 3, 2, 1, 0}},
100 	{ /* 12 Mbits */	5, { 6,  3, 2, 1, 0 }},
101 	{ /* 18 Mbits */	6, { 7,  6, 3, 2, 1, 0 }},
102 	{ /* 24 Mbits */	6, { 8,  6, 3, 2, 1, 0 }},
103 	{ /* 36 Mbits */	7, { 9,  8, 6, 3, 2, 1, 0 }},
104 	{ /* 48 Mbits */	8, {10,  9, 8, 6, 3, 2, 1, 0 }},
105 	{ /* 54 Mbits */	9, {11, 10, 9, 8, 6, 3, 2, 1, 0 }}
106 };
107 
108 static const struct ieee80211_channel zd_channels[] = {
109 	{ .center_freq = 2412, .hw_value = 1 },
110 	{ .center_freq = 2417, .hw_value = 2 },
111 	{ .center_freq = 2422, .hw_value = 3 },
112 	{ .center_freq = 2427, .hw_value = 4 },
113 	{ .center_freq = 2432, .hw_value = 5 },
114 	{ .center_freq = 2437, .hw_value = 6 },
115 	{ .center_freq = 2442, .hw_value = 7 },
116 	{ .center_freq = 2447, .hw_value = 8 },
117 	{ .center_freq = 2452, .hw_value = 9 },
118 	{ .center_freq = 2457, .hw_value = 10 },
119 	{ .center_freq = 2462, .hw_value = 11 },
120 	{ .center_freq = 2467, .hw_value = 12 },
121 	{ .center_freq = 2472, .hw_value = 13 },
122 	{ .center_freq = 2484, .hw_value = 14 },
123 };
124 
125 static void housekeeping_init(struct zd_mac *mac);
126 static void housekeeping_enable(struct zd_mac *mac);
127 static void housekeeping_disable(struct zd_mac *mac);
128 static void beacon_init(struct zd_mac *mac);
129 static void beacon_enable(struct zd_mac *mac);
130 static void beacon_disable(struct zd_mac *mac);
131 static void set_rts_cts(struct zd_mac *mac, unsigned int short_preamble);
132 static int zd_mac_config_beacon(struct ieee80211_hw *hw,
133 				struct sk_buff *beacon, bool in_intr);
134 
135 static int zd_reg2alpha2(u8 regdomain, char *alpha2)
136 {
137 	unsigned int i;
138 	struct zd_reg_alpha2_map *reg_map;
139 	for (i = 0; i < ARRAY_SIZE(reg_alpha2_map); i++) {
140 		reg_map = &reg_alpha2_map[i];
141 		if (regdomain == reg_map->reg) {
142 			alpha2[0] = reg_map->alpha2[0];
143 			alpha2[1] = reg_map->alpha2[1];
144 			return 0;
145 		}
146 	}
147 	return 1;
148 }
149 
150 static int zd_check_signal(struct ieee80211_hw *hw, int signal)
151 {
152 	struct zd_mac *mac = zd_hw_mac(hw);
153 
154 	dev_dbg_f_cond(zd_mac_dev(mac), signal < 0 || signal > 100,
155 			"%s: signal value from device not in range 0..100, "
156 			"but %d.\n", __func__, signal);
157 
158 	if (signal < 0)
159 		signal = 0;
160 	else if (signal > 100)
161 		signal = 100;
162 
163 	return signal;
164 }
165 
166 int zd_mac_preinit_hw(struct ieee80211_hw *hw)
167 {
168 	int r;
169 	u8 addr[ETH_ALEN];
170 	struct zd_mac *mac = zd_hw_mac(hw);
171 
172 	r = zd_chip_read_mac_addr_fw(&mac->chip, addr);
173 	if (r)
174 		return r;
175 
176 	SET_IEEE80211_PERM_ADDR(hw, addr);
177 
178 	return 0;
179 }
180 
181 int zd_mac_init_hw(struct ieee80211_hw *hw)
182 {
183 	int r;
184 	struct zd_mac *mac = zd_hw_mac(hw);
185 	struct zd_chip *chip = &mac->chip;
186 	char alpha2[2];
187 	u8 default_regdomain;
188 
189 	r = zd_chip_enable_int(chip);
190 	if (r)
191 		goto out;
192 	r = zd_chip_init_hw(chip);
193 	if (r)
194 		goto disable_int;
195 
196 	ZD_ASSERT(!irqs_disabled());
197 
198 	r = zd_read_regdomain(chip, &default_regdomain);
199 	if (r)
200 		goto disable_int;
201 	spin_lock_irq(&mac->lock);
202 	mac->regdomain = mac->default_regdomain = default_regdomain;
203 	spin_unlock_irq(&mac->lock);
204 
205 	/* We must inform the device that we are doing encryption/decryption in
206 	 * software at the moment. */
207 	r = zd_set_encryption_type(chip, ENC_SNIFFER);
208 	if (r)
209 		goto disable_int;
210 
211 	r = zd_reg2alpha2(mac->regdomain, alpha2);
212 	if (r)
213 		goto disable_int;
214 
215 	r = regulatory_hint(hw->wiphy, alpha2);
216 disable_int:
217 	zd_chip_disable_int(chip);
218 out:
219 	return r;
220 }
221 
222 void zd_mac_clear(struct zd_mac *mac)
223 {
224 	flush_workqueue(zd_workqueue);
225 	zd_chip_clear(&mac->chip);
226 	lockdep_assert_held(&mac->lock);
227 	ZD_MEMCLEAR(mac, sizeof(struct zd_mac));
228 }
229 
230 static int set_rx_filter(struct zd_mac *mac)
231 {
232 	unsigned long flags;
233 	u32 filter = STA_RX_FILTER;
234 
235 	spin_lock_irqsave(&mac->lock, flags);
236 	if (mac->pass_ctrl)
237 		filter |= RX_FILTER_CTRL;
238 	spin_unlock_irqrestore(&mac->lock, flags);
239 
240 	return zd_iowrite32(&mac->chip, CR_RX_FILTER, filter);
241 }
242 
243 static int set_mac_and_bssid(struct zd_mac *mac)
244 {
245 	int r;
246 
247 	if (!mac->vif)
248 		return -1;
249 
250 	r = zd_write_mac_addr(&mac->chip, mac->vif->addr);
251 	if (r)
252 		return r;
253 
254 	/* Vendor driver after setting MAC either sets BSSID for AP or
255 	 * filter for other modes.
256 	 */
257 	if (mac->type != NL80211_IFTYPE_AP)
258 		return set_rx_filter(mac);
259 	else
260 		return zd_write_bssid(&mac->chip, mac->vif->addr);
261 }
262 
263 static int set_mc_hash(struct zd_mac *mac)
264 {
265 	struct zd_mc_hash hash;
266 	zd_mc_clear(&hash);
267 	return zd_chip_set_multicast_hash(&mac->chip, &hash);
268 }
269 
270 int zd_op_start(struct ieee80211_hw *hw)
271 {
272 	struct zd_mac *mac = zd_hw_mac(hw);
273 	struct zd_chip *chip = &mac->chip;
274 	struct zd_usb *usb = &chip->usb;
275 	int r;
276 
277 	if (!usb->initialized) {
278 		r = zd_usb_init_hw(usb);
279 		if (r)
280 			goto out;
281 	}
282 
283 	r = zd_chip_enable_int(chip);
284 	if (r < 0)
285 		goto out;
286 
287 	r = zd_chip_set_basic_rates(chip, CR_RATES_80211B | CR_RATES_80211G);
288 	if (r < 0)
289 		goto disable_int;
290 	r = set_rx_filter(mac);
291 	if (r)
292 		goto disable_int;
293 	r = set_mc_hash(mac);
294 	if (r)
295 		goto disable_int;
296 
297 	/* Wait after setting the multicast hash table and powering on
298 	 * the radio otherwise interface bring up will fail. This matches
299 	 * what the vendor driver did.
300 	 */
301 	msleep(10);
302 
303 	r = zd_chip_switch_radio_on(chip);
304 	if (r < 0) {
305 		dev_err(zd_chip_dev(chip),
306 			"%s: failed to set radio on\n", __func__);
307 		goto disable_int;
308 	}
309 	r = zd_chip_enable_rxtx(chip);
310 	if (r < 0)
311 		goto disable_radio;
312 	r = zd_chip_enable_hwint(chip);
313 	if (r < 0)
314 		goto disable_rxtx;
315 
316 	housekeeping_enable(mac);
317 	beacon_enable(mac);
318 	set_bit(ZD_DEVICE_RUNNING, &mac->flags);
319 	return 0;
320 disable_rxtx:
321 	zd_chip_disable_rxtx(chip);
322 disable_radio:
323 	zd_chip_switch_radio_off(chip);
324 disable_int:
325 	zd_chip_disable_int(chip);
326 out:
327 	return r;
328 }
329 
330 void zd_op_stop(struct ieee80211_hw *hw)
331 {
332 	struct zd_mac *mac = zd_hw_mac(hw);
333 	struct zd_chip *chip = &mac->chip;
334 	struct sk_buff *skb;
335 	struct sk_buff_head *ack_wait_queue = &mac->ack_wait_queue;
336 
337 	clear_bit(ZD_DEVICE_RUNNING, &mac->flags);
338 
339 	/* The order here deliberately is a little different from the open()
340 	 * method, since we need to make sure there is no opportunity for RX
341 	 * frames to be processed by mac80211 after we have stopped it.
342 	 */
343 
344 	zd_chip_disable_rxtx(chip);
345 	beacon_disable(mac);
346 	housekeeping_disable(mac);
347 	flush_workqueue(zd_workqueue);
348 
349 	zd_chip_disable_hwint(chip);
350 	zd_chip_switch_radio_off(chip);
351 	zd_chip_disable_int(chip);
352 
353 
354 	while ((skb = skb_dequeue(ack_wait_queue)))
355 		dev_kfree_skb_any(skb);
356 }
357 
358 int zd_restore_settings(struct zd_mac *mac)
359 {
360 	struct sk_buff *beacon;
361 	struct zd_mc_hash multicast_hash;
362 	unsigned int short_preamble;
363 	int r, beacon_interval, beacon_period;
364 	u8 channel;
365 
366 	dev_dbg_f(zd_mac_dev(mac), "\n");
367 
368 	spin_lock_irq(&mac->lock);
369 	multicast_hash = mac->multicast_hash;
370 	short_preamble = mac->short_preamble;
371 	beacon_interval = mac->beacon.interval;
372 	beacon_period = mac->beacon.period;
373 	channel = mac->channel;
374 	spin_unlock_irq(&mac->lock);
375 
376 	r = set_mac_and_bssid(mac);
377 	if (r < 0) {
378 		dev_dbg_f(zd_mac_dev(mac), "set_mac_and_bssid failed, %d\n", r);
379 		return r;
380 	}
381 
382 	r = zd_chip_set_channel(&mac->chip, channel);
383 	if (r < 0) {
384 		dev_dbg_f(zd_mac_dev(mac), "zd_chip_set_channel failed, %d\n",
385 			  r);
386 		return r;
387 	}
388 
389 	set_rts_cts(mac, short_preamble);
390 
391 	r = zd_chip_set_multicast_hash(&mac->chip, &multicast_hash);
392 	if (r < 0) {
393 		dev_dbg_f(zd_mac_dev(mac),
394 			  "zd_chip_set_multicast_hash failed, %d\n", r);
395 		return r;
396 	}
397 
398 	if (mac->type == NL80211_IFTYPE_MESH_POINT ||
399 	    mac->type == NL80211_IFTYPE_ADHOC ||
400 	    mac->type == NL80211_IFTYPE_AP) {
401 		if (mac->vif != NULL) {
402 			beacon = ieee80211_beacon_get(mac->hw, mac->vif);
403 			if (beacon)
404 				zd_mac_config_beacon(mac->hw, beacon, false);
405 		}
406 
407 		zd_set_beacon_interval(&mac->chip, beacon_interval,
408 					beacon_period, mac->type);
409 
410 		spin_lock_irq(&mac->lock);
411 		mac->beacon.last_update = jiffies;
412 		spin_unlock_irq(&mac->lock);
413 	}
414 
415 	return 0;
416 }
417 
418 /**
419  * zd_mac_tx_status - reports tx status of a packet if required
420  * @hw - a &struct ieee80211_hw pointer
421  * @skb - a sk-buffer
422  * @flags: extra flags to set in the TX status info
423  * @ackssi: ACK signal strength
424  * @success - True for successful transmission of the frame
425  *
426  * This information calls ieee80211_tx_status_irqsafe() if required by the
427  * control information. It copies the control information into the status
428  * information.
429  *
430  * If no status information has been requested, the skb is freed.
431  */
432 static void zd_mac_tx_status(struct ieee80211_hw *hw, struct sk_buff *skb,
433 		      int ackssi, struct tx_status *tx_status)
434 {
435 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
436 	int i;
437 	int success = 1, retry = 1;
438 	int first_idx;
439 	const struct tx_retry_rate *retries;
440 
441 	ieee80211_tx_info_clear_status(info);
442 
443 	if (tx_status) {
444 		success = !tx_status->failure;
445 		retry = tx_status->retry + success;
446 	}
447 
448 	if (success) {
449 		/* success */
450 		info->flags |= IEEE80211_TX_STAT_ACK;
451 	} else {
452 		/* failure */
453 		info->flags &= ~IEEE80211_TX_STAT_ACK;
454 	}
455 
456 	first_idx = info->status.rates[0].idx;
457 	ZD_ASSERT(0<=first_idx && first_idx<ARRAY_SIZE(zd_retry_rates));
458 	retries = &zd_retry_rates[first_idx];
459 	ZD_ASSERT(1 <= retry && retry <= retries->count);
460 
461 	info->status.rates[0].idx = retries->rate[0];
462 	info->status.rates[0].count = 1; // (retry > 1 ? 2 : 1);
463 
464 	for (i=1; i<IEEE80211_TX_MAX_RATES-1 && i<retry; i++) {
465 		info->status.rates[i].idx = retries->rate[i];
466 		info->status.rates[i].count = 1; // ((i==retry-1) && success ? 1:2);
467 	}
468 	for (; i<IEEE80211_TX_MAX_RATES && i<retry; i++) {
469 		info->status.rates[i].idx = retries->rate[retry - 1];
470 		info->status.rates[i].count = 1; // (success ? 1:2);
471 	}
472 	if (i<IEEE80211_TX_MAX_RATES)
473 		info->status.rates[i].idx = -1; /* terminate */
474 
475 	info->status.ack_signal = zd_check_signal(hw, ackssi);
476 	ieee80211_tx_status_irqsafe(hw, skb);
477 }
478 
479 /**
480  * zd_mac_tx_failed - callback for failed frames
481  * @dev: the mac80211 wireless device
482  *
483  * This function is called if a frame couldn't be successfully
484  * transferred. The first frame from the tx queue, will be selected and
485  * reported as error to the upper layers.
486  */
487 void zd_mac_tx_failed(struct urb *urb)
488 {
489 	struct ieee80211_hw * hw = zd_usb_to_hw(urb->context);
490 	struct zd_mac *mac = zd_hw_mac(hw);
491 	struct sk_buff_head *q = &mac->ack_wait_queue;
492 	struct sk_buff *skb;
493 	struct tx_status *tx_status = (struct tx_status *)urb->transfer_buffer;
494 	unsigned long flags;
495 	int success = !tx_status->failure;
496 	int retry = tx_status->retry + success;
497 	int found = 0;
498 	int i, position = 0;
499 
500 	spin_lock_irqsave(&q->lock, flags);
501 
502 	skb_queue_walk(q, skb) {
503 		struct ieee80211_hdr *tx_hdr;
504 		struct ieee80211_tx_info *info;
505 		int first_idx, final_idx;
506 		const struct tx_retry_rate *retries;
507 		u8 final_rate;
508 
509 		position ++;
510 
511 		/* if the hardware reports a failure and we had a 802.11 ACK
512 		 * pending, then we skip the first skb when searching for a
513 		 * matching frame */
514 		if (tx_status->failure && mac->ack_pending &&
515 		    skb_queue_is_first(q, skb)) {
516 			continue;
517 		}
518 
519 		tx_hdr = (struct ieee80211_hdr *)skb->data;
520 
521 		/* we skip all frames not matching the reported destination */
522 		if (unlikely(!ether_addr_equal(tx_hdr->addr1, tx_status->mac)))
523 			continue;
524 
525 		/* we skip all frames not matching the reported final rate */
526 
527 		info = IEEE80211_SKB_CB(skb);
528 		first_idx = info->status.rates[0].idx;
529 		ZD_ASSERT(0<=first_idx && first_idx<ARRAY_SIZE(zd_retry_rates));
530 		retries = &zd_retry_rates[first_idx];
531 		if (retry <= 0 || retry > retries->count)
532 			continue;
533 
534 		final_idx = retries->rate[retry - 1];
535 		final_rate = zd_rates[final_idx].hw_value;
536 
537 		if (final_rate != tx_status->rate) {
538 			continue;
539 		}
540 
541 		found = 1;
542 		break;
543 	}
544 
545 	if (found) {
546 		for (i=1; i<=position; i++) {
547 			skb = __skb_dequeue(q);
548 			zd_mac_tx_status(hw, skb,
549 					 mac->ack_pending ? mac->ack_signal : 0,
550 					 i == position ? tx_status : NULL);
551 			mac->ack_pending = 0;
552 		}
553 	}
554 
555 	spin_unlock_irqrestore(&q->lock, flags);
556 }
557 
558 /**
559  * zd_mac_tx_to_dev - callback for USB layer
560  * @skb: a &sk_buff pointer
561  * @error: error value, 0 if transmission successful
562  *
563  * Informs the MAC layer that the frame has successfully transferred to the
564  * device. If an ACK is required and the transfer to the device has been
565  * successful, the packets are put on the @ack_wait_queue with
566  * the control set removed.
567  */
568 void zd_mac_tx_to_dev(struct sk_buff *skb, int error)
569 {
570 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
571 	struct ieee80211_hw *hw = info->rate_driver_data[0];
572 	struct zd_mac *mac = zd_hw_mac(hw);
573 
574 	ieee80211_tx_info_clear_status(info);
575 
576 	skb_pull(skb, sizeof(struct zd_ctrlset));
577 	if (unlikely(error ||
578 	    (info->flags & IEEE80211_TX_CTL_NO_ACK))) {
579 		/*
580 		 * FIXME : do we need to fill in anything ?
581 		 */
582 		ieee80211_tx_status_irqsafe(hw, skb);
583 	} else {
584 		struct sk_buff_head *q = &mac->ack_wait_queue;
585 
586 		skb_queue_tail(q, skb);
587 		while (skb_queue_len(q) > ZD_MAC_MAX_ACK_WAITERS) {
588 			zd_mac_tx_status(hw, skb_dequeue(q),
589 					 mac->ack_pending ? mac->ack_signal : 0,
590 					 NULL);
591 			mac->ack_pending = 0;
592 		}
593 	}
594 }
595 
596 static int zd_calc_tx_length_us(u8 *service, u8 zd_rate, u16 tx_length)
597 {
598 	/* ZD_PURE_RATE() must be used to remove the modulation type flag of
599 	 * the zd-rate values.
600 	 */
601 	static const u8 rate_divisor[] = {
602 		[ZD_PURE_RATE(ZD_CCK_RATE_1M)]   =  1,
603 		[ZD_PURE_RATE(ZD_CCK_RATE_2M)]	 =  2,
604 		/* Bits must be doubled. */
605 		[ZD_PURE_RATE(ZD_CCK_RATE_5_5M)] = 11,
606 		[ZD_PURE_RATE(ZD_CCK_RATE_11M)]	 = 11,
607 		[ZD_PURE_RATE(ZD_OFDM_RATE_6M)]  =  6,
608 		[ZD_PURE_RATE(ZD_OFDM_RATE_9M)]  =  9,
609 		[ZD_PURE_RATE(ZD_OFDM_RATE_12M)] = 12,
610 		[ZD_PURE_RATE(ZD_OFDM_RATE_18M)] = 18,
611 		[ZD_PURE_RATE(ZD_OFDM_RATE_24M)] = 24,
612 		[ZD_PURE_RATE(ZD_OFDM_RATE_36M)] = 36,
613 		[ZD_PURE_RATE(ZD_OFDM_RATE_48M)] = 48,
614 		[ZD_PURE_RATE(ZD_OFDM_RATE_54M)] = 54,
615 	};
616 
617 	u32 bits = (u32)tx_length * 8;
618 	u32 divisor;
619 
620 	divisor = rate_divisor[ZD_PURE_RATE(zd_rate)];
621 	if (divisor == 0)
622 		return -EINVAL;
623 
624 	switch (zd_rate) {
625 	case ZD_CCK_RATE_5_5M:
626 		bits = (2*bits) + 10; /* round up to the next integer */
627 		break;
628 	case ZD_CCK_RATE_11M:
629 		if (service) {
630 			u32 t = bits % 11;
631 			*service &= ~ZD_PLCP_SERVICE_LENGTH_EXTENSION;
632 			if (0 < t && t <= 3) {
633 				*service |= ZD_PLCP_SERVICE_LENGTH_EXTENSION;
634 			}
635 		}
636 		bits += 10; /* round up to the next integer */
637 		break;
638 	}
639 
640 	return bits/divisor;
641 }
642 
643 static void cs_set_control(struct zd_mac *mac, struct zd_ctrlset *cs,
644 	                   struct ieee80211_hdr *header,
645 	                   struct ieee80211_tx_info *info)
646 {
647 	/*
648 	 * CONTROL TODO:
649 	 * - if backoff needed, enable bit 0
650 	 * - if burst (backoff not needed) disable bit 0
651 	 */
652 
653 	cs->control = 0;
654 
655 	/* First fragment */
656 	if (info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT)
657 		cs->control |= ZD_CS_NEED_RANDOM_BACKOFF;
658 
659 	/* No ACK expected (multicast, etc.) */
660 	if (info->flags & IEEE80211_TX_CTL_NO_ACK)
661 		cs->control |= ZD_CS_NO_ACK;
662 
663 	/* PS-POLL */
664 	if (ieee80211_is_pspoll(header->frame_control))
665 		cs->control |= ZD_CS_PS_POLL_FRAME;
666 
667 	if (info->control.rates[0].flags & IEEE80211_TX_RC_USE_RTS_CTS)
668 		cs->control |= ZD_CS_RTS;
669 
670 	if (info->control.rates[0].flags & IEEE80211_TX_RC_USE_CTS_PROTECT)
671 		cs->control |= ZD_CS_SELF_CTS;
672 
673 	/* FIXME: Management frame? */
674 }
675 
676 static bool zd_mac_match_cur_beacon(struct zd_mac *mac, struct sk_buff *beacon)
677 {
678 	if (!mac->beacon.cur_beacon)
679 		return false;
680 
681 	if (mac->beacon.cur_beacon->len != beacon->len)
682 		return false;
683 
684 	return !memcmp(beacon->data, mac->beacon.cur_beacon->data, beacon->len);
685 }
686 
687 static void zd_mac_free_cur_beacon_locked(struct zd_mac *mac)
688 {
689 	ZD_ASSERT(mutex_is_locked(&mac->chip.mutex));
690 
691 	kfree_skb(mac->beacon.cur_beacon);
692 	mac->beacon.cur_beacon = NULL;
693 }
694 
695 static void zd_mac_free_cur_beacon(struct zd_mac *mac)
696 {
697 	mutex_lock(&mac->chip.mutex);
698 	zd_mac_free_cur_beacon_locked(mac);
699 	mutex_unlock(&mac->chip.mutex);
700 }
701 
702 static int zd_mac_config_beacon(struct ieee80211_hw *hw, struct sk_buff *beacon,
703 				bool in_intr)
704 {
705 	struct zd_mac *mac = zd_hw_mac(hw);
706 	int r, ret, num_cmds, req_pos = 0;
707 	u32 tmp, j = 0;
708 	/* 4 more bytes for tail CRC */
709 	u32 full_len = beacon->len + 4;
710 	unsigned long end_jiffies, message_jiffies;
711 	struct zd_ioreq32 *ioreqs;
712 
713 	mutex_lock(&mac->chip.mutex);
714 
715 	/* Check if hw already has this beacon. */
716 	if (zd_mac_match_cur_beacon(mac, beacon)) {
717 		r = 0;
718 		goto out_nofree;
719 	}
720 
721 	/* Alloc memory for full beacon write at once. */
722 	num_cmds = 1 + zd_chip_is_zd1211b(&mac->chip) + full_len;
723 	ioreqs = kmalloc_array(num_cmds, sizeof(struct zd_ioreq32),
724 			       GFP_KERNEL);
725 	if (!ioreqs) {
726 		r = -ENOMEM;
727 		goto out_nofree;
728 	}
729 
730 	r = zd_iowrite32_locked(&mac->chip, 0, CR_BCN_FIFO_SEMAPHORE);
731 	if (r < 0)
732 		goto out;
733 	r = zd_ioread32_locked(&mac->chip, &tmp, CR_BCN_FIFO_SEMAPHORE);
734 	if (r < 0)
735 		goto release_sema;
736 	if (in_intr && tmp & 0x2) {
737 		r = -EBUSY;
738 		goto release_sema;
739 	}
740 
741 	end_jiffies = jiffies + HZ / 2; /*~500ms*/
742 	message_jiffies = jiffies + HZ / 10; /*~100ms*/
743 	while (tmp & 0x2) {
744 		r = zd_ioread32_locked(&mac->chip, &tmp, CR_BCN_FIFO_SEMAPHORE);
745 		if (r < 0)
746 			goto release_sema;
747 		if (time_is_before_eq_jiffies(message_jiffies)) {
748 			message_jiffies = jiffies + HZ / 10;
749 			dev_err(zd_mac_dev(mac),
750 					"CR_BCN_FIFO_SEMAPHORE not ready\n");
751 			if (time_is_before_eq_jiffies(end_jiffies))  {
752 				dev_err(zd_mac_dev(mac),
753 						"Giving up beacon config.\n");
754 				r = -ETIMEDOUT;
755 				goto reset_device;
756 			}
757 		}
758 		msleep(20);
759 	}
760 
761 	ioreqs[req_pos].addr = CR_BCN_FIFO;
762 	ioreqs[req_pos].value = full_len - 1;
763 	req_pos++;
764 	if (zd_chip_is_zd1211b(&mac->chip)) {
765 		ioreqs[req_pos].addr = CR_BCN_LENGTH;
766 		ioreqs[req_pos].value = full_len - 1;
767 		req_pos++;
768 	}
769 
770 	for (j = 0 ; j < beacon->len; j++) {
771 		ioreqs[req_pos].addr = CR_BCN_FIFO;
772 		ioreqs[req_pos].value = *((u8 *)(beacon->data + j));
773 		req_pos++;
774 	}
775 
776 	for (j = 0; j < 4; j++) {
777 		ioreqs[req_pos].addr = CR_BCN_FIFO;
778 		ioreqs[req_pos].value = 0x0;
779 		req_pos++;
780 	}
781 
782 	BUG_ON(req_pos != num_cmds);
783 
784 	r = zd_iowrite32a_locked(&mac->chip, ioreqs, num_cmds);
785 
786 release_sema:
787 	/*
788 	 * Try very hard to release device beacon semaphore, as otherwise
789 	 * device/driver can be left in unusable state.
790 	 */
791 	end_jiffies = jiffies + HZ / 2; /*~500ms*/
792 	ret = zd_iowrite32_locked(&mac->chip, 1, CR_BCN_FIFO_SEMAPHORE);
793 	while (ret < 0) {
794 		if (in_intr || time_is_before_eq_jiffies(end_jiffies)) {
795 			ret = -ETIMEDOUT;
796 			break;
797 		}
798 
799 		msleep(20);
800 		ret = zd_iowrite32_locked(&mac->chip, 1, CR_BCN_FIFO_SEMAPHORE);
801 	}
802 
803 	if (ret < 0)
804 		dev_err(zd_mac_dev(mac), "Could not release "
805 					 "CR_BCN_FIFO_SEMAPHORE!\n");
806 	if (r < 0 || ret < 0) {
807 		if (r >= 0)
808 			r = ret;
809 
810 		/* We don't know if beacon was written successfully or not,
811 		 * so clear current. */
812 		zd_mac_free_cur_beacon_locked(mac);
813 
814 		goto out;
815 	}
816 
817 	/* Beacon has now been written successfully, update current. */
818 	zd_mac_free_cur_beacon_locked(mac);
819 	mac->beacon.cur_beacon = beacon;
820 	beacon = NULL;
821 
822 	/* 802.11b/g 2.4G CCK 1Mb
823 	 * 802.11a, not yet implemented, uses different values (see GPL vendor
824 	 * driver)
825 	 */
826 	r = zd_iowrite32_locked(&mac->chip, 0x00000400 | (full_len << 19),
827 				CR_BCN_PLCP_CFG);
828 out:
829 	kfree(ioreqs);
830 out_nofree:
831 	kfree_skb(beacon);
832 	mutex_unlock(&mac->chip.mutex);
833 
834 	return r;
835 
836 reset_device:
837 	zd_mac_free_cur_beacon_locked(mac);
838 	kfree_skb(beacon);
839 
840 	mutex_unlock(&mac->chip.mutex);
841 	kfree(ioreqs);
842 
843 	/* semaphore stuck, reset device to avoid fw freeze later */
844 	dev_warn(zd_mac_dev(mac), "CR_BCN_FIFO_SEMAPHORE stuck, "
845 				  "resetting device...");
846 	usb_queue_reset_device(mac->chip.usb.intf);
847 
848 	return r;
849 }
850 
851 static int fill_ctrlset(struct zd_mac *mac,
852 			struct sk_buff *skb)
853 {
854 	int r;
855 	struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
856 	unsigned int frag_len = skb->len + FCS_LEN;
857 	unsigned int packet_length;
858 	struct ieee80211_rate *txrate;
859 	struct zd_ctrlset *cs = skb_push(skb, sizeof(struct zd_ctrlset));
860 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
861 
862 	ZD_ASSERT(frag_len <= 0xffff);
863 
864 	/*
865 	 * Firmware computes the duration itself (for all frames except PSPoll)
866 	 * and needs the field set to 0 at input, otherwise firmware messes up
867 	 * duration_id and sets bits 14 and 15 on.
868 	 */
869 	if (!ieee80211_is_pspoll(hdr->frame_control))
870 		hdr->duration_id = 0;
871 
872 	txrate = ieee80211_get_tx_rate(mac->hw, info);
873 
874 	cs->modulation = txrate->hw_value;
875 	if (info->control.rates[0].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE)
876 		cs->modulation = txrate->hw_value_short;
877 
878 	cs->tx_length = cpu_to_le16(frag_len);
879 
880 	cs_set_control(mac, cs, hdr, info);
881 
882 	packet_length = frag_len + sizeof(struct zd_ctrlset) + 10;
883 	ZD_ASSERT(packet_length <= 0xffff);
884 	/* ZD1211B: Computing the length difference this way, gives us
885 	 * flexibility to compute the packet length.
886 	 */
887 	cs->packet_length = cpu_to_le16(zd_chip_is_zd1211b(&mac->chip) ?
888 			packet_length - frag_len : packet_length);
889 
890 	/*
891 	 * CURRENT LENGTH:
892 	 * - transmit frame length in microseconds
893 	 * - seems to be derived from frame length
894 	 * - see Cal_Us_Service() in zdinlinef.h
895 	 * - if macp->bTxBurstEnable is enabled, then multiply by 4
896 	 *  - bTxBurstEnable is never set in the vendor driver
897 	 *
898 	 * SERVICE:
899 	 * - "for PLCP configuration"
900 	 * - always 0 except in some situations at 802.11b 11M
901 	 * - see line 53 of zdinlinef.h
902 	 */
903 	cs->service = 0;
904 	r = zd_calc_tx_length_us(&cs->service, ZD_RATE(cs->modulation),
905 		                 le16_to_cpu(cs->tx_length));
906 	if (r < 0)
907 		return r;
908 	cs->current_length = cpu_to_le16(r);
909 	cs->next_frame_length = 0;
910 
911 	return 0;
912 }
913 
914 /**
915  * zd_op_tx - transmits a network frame to the device
916  *
917  * @dev: mac80211 hardware device
918  * @skb: socket buffer
919  * @control: the control structure
920  *
921  * This function transmit an IEEE 802.11 network frame to the device. The
922  * control block of the skbuff will be initialized. If necessary the incoming
923  * mac80211 queues will be stopped.
924  */
925 static void zd_op_tx(struct ieee80211_hw *hw,
926 		     struct ieee80211_tx_control *control,
927 		     struct sk_buff *skb)
928 {
929 	struct zd_mac *mac = zd_hw_mac(hw);
930 	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
931 	int r;
932 
933 	r = fill_ctrlset(mac, skb);
934 	if (r)
935 		goto fail;
936 
937 	info->rate_driver_data[0] = hw;
938 
939 	r = zd_usb_tx(&mac->chip.usb, skb);
940 	if (r)
941 		goto fail;
942 	return;
943 
944 fail:
945 	dev_kfree_skb(skb);
946 }
947 
948 /**
949  * filter_ack - filters incoming packets for acknowledgements
950  * @dev: the mac80211 device
951  * @rx_hdr: received header
952  * @stats: the status for the received packet
953  *
954  * This functions looks for ACK packets and tries to match them with the
955  * frames in the tx queue. If a match is found the frame will be dequeued and
956  * the upper layers is informed about the successful transmission. If
957  * mac80211 queues have been stopped and the number of frames still to be
958  * transmitted is low the queues will be opened again.
959  *
960  * Returns 1 if the frame was an ACK, 0 if it was ignored.
961  */
962 static int filter_ack(struct ieee80211_hw *hw, struct ieee80211_hdr *rx_hdr,
963 		      struct ieee80211_rx_status *stats)
964 {
965 	struct zd_mac *mac = zd_hw_mac(hw);
966 	struct sk_buff *skb;
967 	struct sk_buff_head *q;
968 	unsigned long flags;
969 	int found = 0;
970 	int i, position = 0;
971 
972 	if (!ieee80211_is_ack(rx_hdr->frame_control))
973 		return 0;
974 
975 	q = &mac->ack_wait_queue;
976 	spin_lock_irqsave(&q->lock, flags);
977 	skb_queue_walk(q, skb) {
978 		struct ieee80211_hdr *tx_hdr;
979 
980 		position ++;
981 
982 		if (mac->ack_pending && skb_queue_is_first(q, skb))
983 		    continue;
984 
985 		tx_hdr = (struct ieee80211_hdr *)skb->data;
986 		if (likely(ether_addr_equal(tx_hdr->addr2, rx_hdr->addr1)))
987 		{
988 			found = 1;
989 			break;
990 		}
991 	}
992 
993 	if (found) {
994 		for (i=1; i<position; i++) {
995 			skb = __skb_dequeue(q);
996 			zd_mac_tx_status(hw, skb,
997 					 mac->ack_pending ? mac->ack_signal : 0,
998 					 NULL);
999 			mac->ack_pending = 0;
1000 		}
1001 
1002 		mac->ack_pending = 1;
1003 		mac->ack_signal = stats->signal;
1004 
1005 		/* Prevent pending tx-packet on AP-mode */
1006 		if (mac->type == NL80211_IFTYPE_AP) {
1007 			skb = __skb_dequeue(q);
1008 			zd_mac_tx_status(hw, skb, mac->ack_signal, NULL);
1009 			mac->ack_pending = 0;
1010 		}
1011 	}
1012 
1013 	spin_unlock_irqrestore(&q->lock, flags);
1014 	return 1;
1015 }
1016 
1017 int zd_mac_rx(struct ieee80211_hw *hw, const u8 *buffer, unsigned int length)
1018 {
1019 	struct zd_mac *mac = zd_hw_mac(hw);
1020 	struct ieee80211_rx_status stats;
1021 	const struct rx_status *status;
1022 	struct sk_buff *skb;
1023 	int bad_frame = 0;
1024 	__le16 fc;
1025 	int need_padding;
1026 	int i;
1027 	u8 rate;
1028 
1029 	if (length < ZD_PLCP_HEADER_SIZE + 10 /* IEEE80211_1ADDR_LEN */ +
1030 	             FCS_LEN + sizeof(struct rx_status))
1031 		return -EINVAL;
1032 
1033 	memset(&stats, 0, sizeof(stats));
1034 
1035 	/* Note about pass_failed_fcs and pass_ctrl access below:
1036 	 * mac locking intentionally omitted here, as this is the only unlocked
1037 	 * reader and the only writer is configure_filter. Plus, if there were
1038 	 * any races accessing these variables, it wouldn't really matter.
1039 	 * If mac80211 ever provides a way for us to access filter flags
1040 	 * from outside configure_filter, we could improve on this. Also, this
1041 	 * situation may change once we implement some kind of DMA-into-skb
1042 	 * RX path. */
1043 
1044 	/* Caller has to ensure that length >= sizeof(struct rx_status). */
1045 	status = (struct rx_status *)
1046 		(buffer + (length - sizeof(struct rx_status)));
1047 	if (status->frame_status & ZD_RX_ERROR) {
1048 		if (mac->pass_failed_fcs &&
1049 				(status->frame_status & ZD_RX_CRC32_ERROR)) {
1050 			stats.flag |= RX_FLAG_FAILED_FCS_CRC;
1051 			bad_frame = 1;
1052 		} else {
1053 			return -EINVAL;
1054 		}
1055 	}
1056 
1057 	stats.freq = zd_channels[_zd_chip_get_channel(&mac->chip) - 1].center_freq;
1058 	stats.band = NL80211_BAND_2GHZ;
1059 	stats.signal = zd_check_signal(hw, status->signal_strength);
1060 
1061 	rate = zd_rx_rate(buffer, status);
1062 
1063 	/* todo: return index in the big switches in zd_rx_rate instead */
1064 	for (i = 0; i < mac->band.n_bitrates; i++)
1065 		if (rate == mac->band.bitrates[i].hw_value)
1066 			stats.rate_idx = i;
1067 
1068 	length -= ZD_PLCP_HEADER_SIZE + sizeof(struct rx_status);
1069 	buffer += ZD_PLCP_HEADER_SIZE;
1070 
1071 	/* Except for bad frames, filter each frame to see if it is an ACK, in
1072 	 * which case our internal TX tracking is updated. Normally we then
1073 	 * bail here as there's no need to pass ACKs on up to the stack, but
1074 	 * there is also the case where the stack has requested us to pass
1075 	 * control frames on up (pass_ctrl) which we must consider. */
1076 	if (!bad_frame &&
1077 			filter_ack(hw, (struct ieee80211_hdr *)buffer, &stats)
1078 			&& !mac->pass_ctrl)
1079 		return 0;
1080 
1081 	fc = get_unaligned((__le16*)buffer);
1082 	need_padding = ieee80211_is_data_qos(fc) ^ ieee80211_has_a4(fc);
1083 
1084 	skb = dev_alloc_skb(length + (need_padding ? 2 : 0));
1085 	if (skb == NULL)
1086 		return -ENOMEM;
1087 	if (need_padding) {
1088 		/* Make sure the payload data is 4 byte aligned. */
1089 		skb_reserve(skb, 2);
1090 	}
1091 
1092 	/* FIXME : could we avoid this big memcpy ? */
1093 	skb_put_data(skb, buffer, length);
1094 
1095 	memcpy(IEEE80211_SKB_RXCB(skb), &stats, sizeof(stats));
1096 	ieee80211_rx_irqsafe(hw, skb);
1097 	return 0;
1098 }
1099 
1100 static int zd_op_add_interface(struct ieee80211_hw *hw,
1101 				struct ieee80211_vif *vif)
1102 {
1103 	struct zd_mac *mac = zd_hw_mac(hw);
1104 
1105 	/* using NL80211_IFTYPE_UNSPECIFIED to indicate no mode selected */
1106 	if (mac->type != NL80211_IFTYPE_UNSPECIFIED)
1107 		return -EOPNOTSUPP;
1108 
1109 	switch (vif->type) {
1110 	case NL80211_IFTYPE_MONITOR:
1111 	case NL80211_IFTYPE_MESH_POINT:
1112 	case NL80211_IFTYPE_STATION:
1113 	case NL80211_IFTYPE_ADHOC:
1114 	case NL80211_IFTYPE_AP:
1115 		mac->type = vif->type;
1116 		break;
1117 	default:
1118 		return -EOPNOTSUPP;
1119 	}
1120 
1121 	mac->vif = vif;
1122 
1123 	return set_mac_and_bssid(mac);
1124 }
1125 
1126 static void zd_op_remove_interface(struct ieee80211_hw *hw,
1127 				    struct ieee80211_vif *vif)
1128 {
1129 	struct zd_mac *mac = zd_hw_mac(hw);
1130 	mac->type = NL80211_IFTYPE_UNSPECIFIED;
1131 	mac->vif = NULL;
1132 	zd_set_beacon_interval(&mac->chip, 0, 0, NL80211_IFTYPE_UNSPECIFIED);
1133 	zd_write_mac_addr(&mac->chip, NULL);
1134 
1135 	zd_mac_free_cur_beacon(mac);
1136 }
1137 
1138 static int zd_op_config(struct ieee80211_hw *hw, u32 changed)
1139 {
1140 	struct zd_mac *mac = zd_hw_mac(hw);
1141 	struct ieee80211_conf *conf = &hw->conf;
1142 
1143 	spin_lock_irq(&mac->lock);
1144 	mac->channel = conf->chandef.chan->hw_value;
1145 	spin_unlock_irq(&mac->lock);
1146 
1147 	return zd_chip_set_channel(&mac->chip, conf->chandef.chan->hw_value);
1148 }
1149 
1150 static void zd_beacon_done(struct zd_mac *mac)
1151 {
1152 	struct sk_buff *skb, *beacon;
1153 
1154 	if (!test_bit(ZD_DEVICE_RUNNING, &mac->flags))
1155 		return;
1156 	if (!mac->vif || mac->vif->type != NL80211_IFTYPE_AP)
1157 		return;
1158 
1159 	/*
1160 	 * Send out buffered broad- and multicast frames.
1161 	 */
1162 	while (!ieee80211_queue_stopped(mac->hw, 0)) {
1163 		skb = ieee80211_get_buffered_bc(mac->hw, mac->vif);
1164 		if (!skb)
1165 			break;
1166 		zd_op_tx(mac->hw, NULL, skb);
1167 	}
1168 
1169 	/*
1170 	 * Fetch next beacon so that tim_count is updated.
1171 	 */
1172 	beacon = ieee80211_beacon_get(mac->hw, mac->vif);
1173 	if (beacon)
1174 		zd_mac_config_beacon(mac->hw, beacon, true);
1175 
1176 	spin_lock_irq(&mac->lock);
1177 	mac->beacon.last_update = jiffies;
1178 	spin_unlock_irq(&mac->lock);
1179 }
1180 
1181 static void zd_process_intr(struct work_struct *work)
1182 {
1183 	u16 int_status;
1184 	unsigned long flags;
1185 	struct zd_mac *mac = container_of(work, struct zd_mac, process_intr);
1186 
1187 	spin_lock_irqsave(&mac->lock, flags);
1188 	int_status = le16_to_cpu(*(__le16 *)(mac->intr_buffer + 4));
1189 	spin_unlock_irqrestore(&mac->lock, flags);
1190 
1191 	if (int_status & INT_CFG_NEXT_BCN) {
1192 		/*dev_dbg_f_limit(zd_mac_dev(mac), "INT_CFG_NEXT_BCN\n");*/
1193 		zd_beacon_done(mac);
1194 	} else {
1195 		dev_dbg_f(zd_mac_dev(mac), "Unsupported interrupt\n");
1196 	}
1197 
1198 	zd_chip_enable_hwint(&mac->chip);
1199 }
1200 
1201 
1202 static u64 zd_op_prepare_multicast(struct ieee80211_hw *hw,
1203 				   struct netdev_hw_addr_list *mc_list)
1204 {
1205 	struct zd_mac *mac = zd_hw_mac(hw);
1206 	struct zd_mc_hash hash;
1207 	struct netdev_hw_addr *ha;
1208 
1209 	zd_mc_clear(&hash);
1210 
1211 	netdev_hw_addr_list_for_each(ha, mc_list) {
1212 		dev_dbg_f(zd_mac_dev(mac), "mc addr %pM\n", ha->addr);
1213 		zd_mc_add_addr(&hash, ha->addr);
1214 	}
1215 
1216 	return hash.low | ((u64)hash.high << 32);
1217 }
1218 
1219 #define SUPPORTED_FIF_FLAGS \
1220 	(FIF_ALLMULTI | FIF_FCSFAIL | FIF_CONTROL | \
1221 	FIF_OTHER_BSS | FIF_BCN_PRBRESP_PROMISC)
1222 static void zd_op_configure_filter(struct ieee80211_hw *hw,
1223 			unsigned int changed_flags,
1224 			unsigned int *new_flags,
1225 			u64 multicast)
1226 {
1227 	struct zd_mc_hash hash = {
1228 		.low = multicast,
1229 		.high = multicast >> 32,
1230 	};
1231 	struct zd_mac *mac = zd_hw_mac(hw);
1232 	unsigned long flags;
1233 	int r;
1234 
1235 	/* Only deal with supported flags */
1236 	changed_flags &= SUPPORTED_FIF_FLAGS;
1237 	*new_flags &= SUPPORTED_FIF_FLAGS;
1238 
1239 	/*
1240 	 * If multicast parameter (as returned by zd_op_prepare_multicast)
1241 	 * has changed, no bit in changed_flags is set. To handle this
1242 	 * situation, we do not return if changed_flags is 0. If we do so,
1243 	 * we will have some issue with IPv6 which uses multicast for link
1244 	 * layer address resolution.
1245 	 */
1246 	if (*new_flags & FIF_ALLMULTI)
1247 		zd_mc_add_all(&hash);
1248 
1249 	spin_lock_irqsave(&mac->lock, flags);
1250 	mac->pass_failed_fcs = !!(*new_flags & FIF_FCSFAIL);
1251 	mac->pass_ctrl = !!(*new_flags & FIF_CONTROL);
1252 	mac->multicast_hash = hash;
1253 	spin_unlock_irqrestore(&mac->lock, flags);
1254 
1255 	zd_chip_set_multicast_hash(&mac->chip, &hash);
1256 
1257 	if (changed_flags & FIF_CONTROL) {
1258 		r = set_rx_filter(mac);
1259 		if (r)
1260 			dev_err(zd_mac_dev(mac), "set_rx_filter error %d\n", r);
1261 	}
1262 
1263 	/* no handling required for FIF_OTHER_BSS as we don't currently
1264 	 * do BSSID filtering */
1265 	/* FIXME: in future it would be nice to enable the probe response
1266 	 * filter (so that the driver doesn't see them) until
1267 	 * FIF_BCN_PRBRESP_PROMISC is set. however due to atomicity here, we'd
1268 	 * have to schedule work to enable prbresp reception, which might
1269 	 * happen too late. For now we'll just listen and forward them all the
1270 	 * time. */
1271 }
1272 
1273 static void set_rts_cts(struct zd_mac *mac, unsigned int short_preamble)
1274 {
1275 	mutex_lock(&mac->chip.mutex);
1276 	zd_chip_set_rts_cts_rate_locked(&mac->chip, short_preamble);
1277 	mutex_unlock(&mac->chip.mutex);
1278 }
1279 
1280 static void zd_op_bss_info_changed(struct ieee80211_hw *hw,
1281 				   struct ieee80211_vif *vif,
1282 				   struct ieee80211_bss_conf *bss_conf,
1283 				   u32 changes)
1284 {
1285 	struct zd_mac *mac = zd_hw_mac(hw);
1286 	int associated;
1287 
1288 	dev_dbg_f(zd_mac_dev(mac), "changes: %x\n", changes);
1289 
1290 	if (mac->type == NL80211_IFTYPE_MESH_POINT ||
1291 	    mac->type == NL80211_IFTYPE_ADHOC ||
1292 	    mac->type == NL80211_IFTYPE_AP) {
1293 		associated = true;
1294 		if (changes & BSS_CHANGED_BEACON) {
1295 			struct sk_buff *beacon = ieee80211_beacon_get(hw, vif);
1296 
1297 			if (beacon) {
1298 				zd_chip_disable_hwint(&mac->chip);
1299 				zd_mac_config_beacon(hw, beacon, false);
1300 				zd_chip_enable_hwint(&mac->chip);
1301 			}
1302 		}
1303 
1304 		if (changes & BSS_CHANGED_BEACON_ENABLED) {
1305 			u16 interval = 0;
1306 			u8 period = 0;
1307 
1308 			if (bss_conf->enable_beacon) {
1309 				period = bss_conf->dtim_period;
1310 				interval = bss_conf->beacon_int;
1311 			}
1312 
1313 			spin_lock_irq(&mac->lock);
1314 			mac->beacon.period = period;
1315 			mac->beacon.interval = interval;
1316 			mac->beacon.last_update = jiffies;
1317 			spin_unlock_irq(&mac->lock);
1318 
1319 			zd_set_beacon_interval(&mac->chip, interval, period,
1320 					       mac->type);
1321 		}
1322 	} else
1323 		associated = is_valid_ether_addr(bss_conf->bssid);
1324 
1325 	spin_lock_irq(&mac->lock);
1326 	mac->associated = associated;
1327 	spin_unlock_irq(&mac->lock);
1328 
1329 	/* TODO: do hardware bssid filtering */
1330 
1331 	if (changes & BSS_CHANGED_ERP_PREAMBLE) {
1332 		spin_lock_irq(&mac->lock);
1333 		mac->short_preamble = bss_conf->use_short_preamble;
1334 		spin_unlock_irq(&mac->lock);
1335 
1336 		set_rts_cts(mac, bss_conf->use_short_preamble);
1337 	}
1338 }
1339 
1340 static u64 zd_op_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
1341 {
1342 	struct zd_mac *mac = zd_hw_mac(hw);
1343 	return zd_chip_get_tsf(&mac->chip);
1344 }
1345 
1346 static const struct ieee80211_ops zd_ops = {
1347 	.tx			= zd_op_tx,
1348 	.start			= zd_op_start,
1349 	.stop			= zd_op_stop,
1350 	.add_interface		= zd_op_add_interface,
1351 	.remove_interface	= zd_op_remove_interface,
1352 	.config			= zd_op_config,
1353 	.prepare_multicast	= zd_op_prepare_multicast,
1354 	.configure_filter	= zd_op_configure_filter,
1355 	.bss_info_changed	= zd_op_bss_info_changed,
1356 	.get_tsf		= zd_op_get_tsf,
1357 };
1358 
1359 struct ieee80211_hw *zd_mac_alloc_hw(struct usb_interface *intf)
1360 {
1361 	struct zd_mac *mac;
1362 	struct ieee80211_hw *hw;
1363 
1364 	hw = ieee80211_alloc_hw(sizeof(struct zd_mac), &zd_ops);
1365 	if (!hw) {
1366 		dev_dbg_f(&intf->dev, "out of memory\n");
1367 		return NULL;
1368 	}
1369 
1370 	mac = zd_hw_mac(hw);
1371 
1372 	memset(mac, 0, sizeof(*mac));
1373 	spin_lock_init(&mac->lock);
1374 	mac->hw = hw;
1375 
1376 	mac->type = NL80211_IFTYPE_UNSPECIFIED;
1377 
1378 	memcpy(mac->channels, zd_channels, sizeof(zd_channels));
1379 	memcpy(mac->rates, zd_rates, sizeof(zd_rates));
1380 	mac->band.n_bitrates = ARRAY_SIZE(zd_rates);
1381 	mac->band.bitrates = mac->rates;
1382 	mac->band.n_channels = ARRAY_SIZE(zd_channels);
1383 	mac->band.channels = mac->channels;
1384 
1385 	hw->wiphy->bands[NL80211_BAND_2GHZ] = &mac->band;
1386 
1387 	ieee80211_hw_set(hw, MFP_CAPABLE);
1388 	ieee80211_hw_set(hw, HOST_BROADCAST_PS_BUFFERING);
1389 	ieee80211_hw_set(hw, RX_INCLUDES_FCS);
1390 	ieee80211_hw_set(hw, SIGNAL_UNSPEC);
1391 
1392 	hw->wiphy->interface_modes =
1393 		BIT(NL80211_IFTYPE_MESH_POINT) |
1394 		BIT(NL80211_IFTYPE_STATION) |
1395 		BIT(NL80211_IFTYPE_ADHOC) |
1396 		BIT(NL80211_IFTYPE_AP);
1397 
1398 	wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_CQM_RSSI_LIST);
1399 
1400 	hw->max_signal = 100;
1401 	hw->queues = 1;
1402 	hw->extra_tx_headroom = sizeof(struct zd_ctrlset);
1403 
1404 	/*
1405 	 * Tell mac80211 that we support multi rate retries
1406 	 */
1407 	hw->max_rates = IEEE80211_TX_MAX_RATES;
1408 	hw->max_rate_tries = 18;	/* 9 rates * 2 retries/rate */
1409 
1410 	skb_queue_head_init(&mac->ack_wait_queue);
1411 	mac->ack_pending = 0;
1412 
1413 	zd_chip_init(&mac->chip, hw, intf);
1414 	housekeeping_init(mac);
1415 	beacon_init(mac);
1416 	INIT_WORK(&mac->process_intr, zd_process_intr);
1417 
1418 	SET_IEEE80211_DEV(hw, &intf->dev);
1419 	return hw;
1420 }
1421 
1422 #define BEACON_WATCHDOG_DELAY round_jiffies_relative(HZ)
1423 
1424 static void beacon_watchdog_handler(struct work_struct *work)
1425 {
1426 	struct zd_mac *mac =
1427 		container_of(work, struct zd_mac, beacon.watchdog_work.work);
1428 	struct sk_buff *beacon;
1429 	unsigned long timeout;
1430 	int interval, period;
1431 
1432 	if (!test_bit(ZD_DEVICE_RUNNING, &mac->flags))
1433 		goto rearm;
1434 	if (mac->type != NL80211_IFTYPE_AP || !mac->vif)
1435 		goto rearm;
1436 
1437 	spin_lock_irq(&mac->lock);
1438 	interval = mac->beacon.interval;
1439 	period = mac->beacon.period;
1440 	timeout = mac->beacon.last_update +
1441 			msecs_to_jiffies(interval * 1024 / 1000) * 3;
1442 	spin_unlock_irq(&mac->lock);
1443 
1444 	if (interval > 0 && time_is_before_jiffies(timeout)) {
1445 		dev_dbg_f(zd_mac_dev(mac), "beacon interrupt stalled, "
1446 					   "restarting. "
1447 					   "(interval: %d, dtim: %d)\n",
1448 					   interval, period);
1449 
1450 		zd_chip_disable_hwint(&mac->chip);
1451 
1452 		beacon = ieee80211_beacon_get(mac->hw, mac->vif);
1453 		if (beacon) {
1454 			zd_mac_free_cur_beacon(mac);
1455 
1456 			zd_mac_config_beacon(mac->hw, beacon, false);
1457 		}
1458 
1459 		zd_set_beacon_interval(&mac->chip, interval, period, mac->type);
1460 
1461 		zd_chip_enable_hwint(&mac->chip);
1462 
1463 		spin_lock_irq(&mac->lock);
1464 		mac->beacon.last_update = jiffies;
1465 		spin_unlock_irq(&mac->lock);
1466 	}
1467 
1468 rearm:
1469 	queue_delayed_work(zd_workqueue, &mac->beacon.watchdog_work,
1470 			   BEACON_WATCHDOG_DELAY);
1471 }
1472 
1473 static void beacon_init(struct zd_mac *mac)
1474 {
1475 	INIT_DELAYED_WORK(&mac->beacon.watchdog_work, beacon_watchdog_handler);
1476 }
1477 
1478 static void beacon_enable(struct zd_mac *mac)
1479 {
1480 	dev_dbg_f(zd_mac_dev(mac), "\n");
1481 
1482 	mac->beacon.last_update = jiffies;
1483 	queue_delayed_work(zd_workqueue, &mac->beacon.watchdog_work,
1484 			   BEACON_WATCHDOG_DELAY);
1485 }
1486 
1487 static void beacon_disable(struct zd_mac *mac)
1488 {
1489 	dev_dbg_f(zd_mac_dev(mac), "\n");
1490 	cancel_delayed_work_sync(&mac->beacon.watchdog_work);
1491 
1492 	zd_mac_free_cur_beacon(mac);
1493 }
1494 
1495 #define LINK_LED_WORK_DELAY HZ
1496 
1497 static void link_led_handler(struct work_struct *work)
1498 {
1499 	struct zd_mac *mac =
1500 		container_of(work, struct zd_mac, housekeeping.link_led_work.work);
1501 	struct zd_chip *chip = &mac->chip;
1502 	int is_associated;
1503 	int r;
1504 
1505 	if (!test_bit(ZD_DEVICE_RUNNING, &mac->flags))
1506 		goto requeue;
1507 
1508 	spin_lock_irq(&mac->lock);
1509 	is_associated = mac->associated;
1510 	spin_unlock_irq(&mac->lock);
1511 
1512 	r = zd_chip_control_leds(chip,
1513 		                 is_associated ? ZD_LED_ASSOCIATED : ZD_LED_SCANNING);
1514 	if (r)
1515 		dev_dbg_f(zd_mac_dev(mac), "zd_chip_control_leds error %d\n", r);
1516 
1517 requeue:
1518 	queue_delayed_work(zd_workqueue, &mac->housekeeping.link_led_work,
1519 		           LINK_LED_WORK_DELAY);
1520 }
1521 
1522 static void housekeeping_init(struct zd_mac *mac)
1523 {
1524 	INIT_DELAYED_WORK(&mac->housekeeping.link_led_work, link_led_handler);
1525 }
1526 
1527 static void housekeeping_enable(struct zd_mac *mac)
1528 {
1529 	dev_dbg_f(zd_mac_dev(mac), "\n");
1530 	queue_delayed_work(zd_workqueue, &mac->housekeeping.link_led_work,
1531 			   0);
1532 }
1533 
1534 static void housekeeping_disable(struct zd_mac *mac)
1535 {
1536 	dev_dbg_f(zd_mac_dev(mac), "\n");
1537 	cancel_delayed_work_sync(&mac->housekeeping.link_led_work);
1538 	zd_chip_control_leds(&mac->chip, ZD_LED_OFF);
1539 }
1540