1 /* main.c - (formerly known as dldwd_cs.c, orinoco_cs.c and orinoco.c)
2  *
3  * A driver for Hermes or Prism 2 chipset based PCMCIA wireless
4  * adaptors, with Lucent/Agere, Intersil or Symbol firmware.
5  *
6  * Current maintainers (as of 29 September 2003) are:
7  *	Pavel Roskin <proski AT gnu.org>
8  * and	David Gibson <hermes AT gibson.dropbear.id.au>
9  *
10  * (C) Copyright David Gibson, IBM Corporation 2001-2003.
11  * Copyright (C) 2000 David Gibson, Linuxcare Australia.
12  *	With some help from :
13  * Copyright (C) 2001 Jean Tourrilhes, HP Labs
14  * Copyright (C) 2001 Benjamin Herrenschmidt
15  *
16  * Based on dummy_cs.c 1.27 2000/06/12 21:27:25
17  *
18  * Portions based on wvlan_cs.c 1.0.6, Copyright Andreas Neuhaus <andy
19  * AT fasta.fh-dortmund.de>
20  *      http://www.stud.fh-dortmund.de/~andy/wvlan/
21  *
22  * The contents of this file are subject to the Mozilla Public License
23  * Version 1.1 (the "License"); you may not use this file except in
24  * compliance with the License. You may obtain a copy of the License
25  * at http://www.mozilla.org/MPL/
26  *
27  * Software distributed under the License is distributed on an "AS IS"
28  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
29  * the License for the specific language governing rights and
30  * limitations under the License.
31  *
32  * The initial developer of the original code is David A. Hinds
33  * <dahinds AT users.sourceforge.net>.  Portions created by David
34  * A. Hinds are Copyright (C) 1999 David A. Hinds.  All Rights
35  * Reserved.
36  *
37  * Alternatively, the contents of this file may be used under the
38  * terms of the GNU General Public License version 2 (the "GPL"), in
39  * which case the provisions of the GPL are applicable instead of the
40  * above.  If you wish to allow the use of your version of this file
41  * only under the terms of the GPL and not to allow others to use your
42  * version of this file under the MPL, indicate your decision by
43  * deleting the provisions above and replace them with the notice and
44  * other provisions required by the GPL.  If you do not delete the
45  * provisions above, a recipient may use your version of this file
46  * under either the MPL or the GPL.  */
47 
48 /*
49  * TODO
50  *	o Handle de-encapsulation within network layer, provide 802.11
51  *	  headers (patch from Thomas 'Dent' Mirlacher)
52  *	o Fix possible races in SPY handling.
53  *	o Disconnect wireless extensions from fundamental configuration.
54  *	o (maybe) Software WEP support (patch from Stano Meduna).
55  *	o (maybe) Use multiple Tx buffers - driver handling queue
56  *	  rather than firmware.
57  */
58 
59 /* Locking and synchronization:
60  *
61  * The basic principle is that everything is serialized through a
62  * single spinlock, priv->lock.  The lock is used in user, bh and irq
63  * context, so when taken outside hardirq context it should always be
64  * taken with interrupts disabled.  The lock protects both the
65  * hardware and the struct orinoco_private.
66  *
67  * Another flag, priv->hw_unavailable indicates that the hardware is
68  * unavailable for an extended period of time (e.g. suspended, or in
69  * the middle of a hard reset).  This flag is protected by the
70  * spinlock.  All code which touches the hardware should check the
71  * flag after taking the lock, and if it is set, give up on whatever
72  * they are doing and drop the lock again.  The orinoco_lock()
73  * function handles this (it unlocks and returns -EBUSY if
74  * hw_unavailable is non-zero).
75  */
76 
77 #define DRIVER_NAME "orinoco"
78 
79 #include <linux/module.h>
80 #include <linux/kernel.h>
81 #include <linux/slab.h>
82 #include <linux/init.h>
83 #include <linux/delay.h>
84 #include <linux/device.h>
85 #include <linux/netdevice.h>
86 #include <linux/etherdevice.h>
87 #include <linux/suspend.h>
88 #include <linux/if_arp.h>
89 #include <linux/wireless.h>
90 #include <linux/ieee80211.h>
91 #include <net/iw_handler.h>
92 #include <net/cfg80211.h>
93 
94 #include "hermes_rid.h"
95 #include "hermes_dld.h"
96 #include "hw.h"
97 #include "scan.h"
98 #include "mic.h"
99 #include "fw.h"
100 #include "wext.h"
101 #include "cfg.h"
102 #include "main.h"
103 
104 #include "orinoco.h"
105 
106 /********************************************************************/
107 /* Module information                                               */
108 /********************************************************************/
109 
110 MODULE_AUTHOR("Pavel Roskin <proski@gnu.org> & "
111 	      "David Gibson <hermes@gibson.dropbear.id.au>");
112 MODULE_DESCRIPTION("Driver for Lucent Orinoco, Prism II based "
113 		   "and similar wireless cards");
114 MODULE_LICENSE("Dual MPL/GPL");
115 
116 /* Level of debugging. Used in the macros in orinoco.h */
117 #ifdef ORINOCO_DEBUG
118 int orinoco_debug = ORINOCO_DEBUG;
119 EXPORT_SYMBOL(orinoco_debug);
120 module_param(orinoco_debug, int, 0644);
121 MODULE_PARM_DESC(orinoco_debug, "Debug level");
122 #endif
123 
124 static bool suppress_linkstatus; /* = 0 */
125 module_param(suppress_linkstatus, bool, 0644);
126 MODULE_PARM_DESC(suppress_linkstatus, "Don't log link status changes");
127 
128 static int ignore_disconnect; /* = 0 */
129 module_param(ignore_disconnect, int, 0644);
130 MODULE_PARM_DESC(ignore_disconnect,
131 		 "Don't report lost link to the network layer");
132 
133 int force_monitor; /* = 0 */
134 module_param(force_monitor, int, 0644);
135 MODULE_PARM_DESC(force_monitor, "Allow monitor mode for all firmware versions");
136 
137 /********************************************************************/
138 /* Internal constants                                               */
139 /********************************************************************/
140 
141 /* 802.2 LLC/SNAP header used for Ethernet encapsulation over 802.11 */
142 static const u8 encaps_hdr[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
143 #define ENCAPS_OVERHEAD		(sizeof(encaps_hdr) + 2)
144 
145 #define ORINOCO_MIN_MTU		256
146 #define ORINOCO_MAX_MTU		(IEEE80211_MAX_DATA_LEN - ENCAPS_OVERHEAD)
147 
148 #define MAX_IRQLOOPS_PER_IRQ	10
149 #define MAX_IRQLOOPS_PER_JIFFY	(20000 / HZ)	/* Based on a guestimate of
150 						 * how many events the
151 						 * device could
152 						 * legitimately generate */
153 
154 #define DUMMY_FID		0xFFFF
155 
156 /*#define MAX_MULTICAST(priv)	(priv->firmware_type == FIRMWARE_TYPE_AGERE ? \
157   HERMES_MAX_MULTICAST : 0)*/
158 #define MAX_MULTICAST(priv)	(HERMES_MAX_MULTICAST)
159 
160 #define ORINOCO_INTEN		(HERMES_EV_RX | HERMES_EV_ALLOC \
161 				 | HERMES_EV_TX | HERMES_EV_TXEXC \
162 				 | HERMES_EV_WTERR | HERMES_EV_INFO \
163 				 | HERMES_EV_INFDROP)
164 
165 /********************************************************************/
166 /* Data types                                                       */
167 /********************************************************************/
168 
169 /* Beginning of the Tx descriptor, used in TxExc handling */
170 struct hermes_txexc_data {
171 	struct hermes_tx_descriptor desc;
172 	__le16 frame_ctl;
173 	__le16 duration_id;
174 	u8 addr1[ETH_ALEN];
175 } __packed;
176 
177 /* Rx frame header except compatibility 802.3 header */
178 struct hermes_rx_descriptor {
179 	/* Control */
180 	__le16 status;
181 	__le32 time;
182 	u8 silence;
183 	u8 signal;
184 	u8 rate;
185 	u8 rxflow;
186 	__le32 reserved;
187 
188 	/* 802.11 header */
189 	__le16 frame_ctl;
190 	__le16 duration_id;
191 	u8 addr1[ETH_ALEN];
192 	u8 addr2[ETH_ALEN];
193 	u8 addr3[ETH_ALEN];
194 	__le16 seq_ctl;
195 	u8 addr4[ETH_ALEN];
196 
197 	/* Data length */
198 	__le16 data_len;
199 } __packed;
200 
201 struct orinoco_rx_data {
202 	struct hermes_rx_descriptor *desc;
203 	struct sk_buff *skb;
204 	struct list_head list;
205 };
206 
207 struct orinoco_scan_data {
208 	void *buf;
209 	size_t len;
210 	int type;
211 	struct list_head list;
212 };
213 
214 /********************************************************************/
215 /* Function prototypes                                              */
216 /********************************************************************/
217 
218 static int __orinoco_set_multicast_list(struct net_device *dev);
219 static int __orinoco_up(struct orinoco_private *priv);
220 static int __orinoco_down(struct orinoco_private *priv);
221 static int __orinoco_commit(struct orinoco_private *priv);
222 
223 /********************************************************************/
224 /* Internal helper functions                                        */
225 /********************************************************************/
226 
227 void set_port_type(struct orinoco_private *priv)
228 {
229 	switch (priv->iw_mode) {
230 	case NL80211_IFTYPE_STATION:
231 		priv->port_type = 1;
232 		priv->createibss = 0;
233 		break;
234 	case NL80211_IFTYPE_ADHOC:
235 		if (priv->prefer_port3) {
236 			priv->port_type = 3;
237 			priv->createibss = 0;
238 		} else {
239 			priv->port_type = priv->ibss_port;
240 			priv->createibss = 1;
241 		}
242 		break;
243 	case NL80211_IFTYPE_MONITOR:
244 		priv->port_type = 3;
245 		priv->createibss = 0;
246 		break;
247 	default:
248 		printk(KERN_ERR "%s: Invalid priv->iw_mode in set_port_type()\n",
249 		       priv->ndev->name);
250 	}
251 }
252 
253 /********************************************************************/
254 /* Device methods                                                   */
255 /********************************************************************/
256 
257 int orinoco_open(struct net_device *dev)
258 {
259 	struct orinoco_private *priv = ndev_priv(dev);
260 	unsigned long flags;
261 	int err;
262 
263 	if (orinoco_lock(priv, &flags) != 0)
264 		return -EBUSY;
265 
266 	err = __orinoco_up(priv);
267 
268 	if (!err)
269 		priv->open = 1;
270 
271 	orinoco_unlock(priv, &flags);
272 
273 	return err;
274 }
275 EXPORT_SYMBOL(orinoco_open);
276 
277 int orinoco_stop(struct net_device *dev)
278 {
279 	struct orinoco_private *priv = ndev_priv(dev);
280 	int err = 0;
281 
282 	/* We mustn't use orinoco_lock() here, because we need to be
283 	   able to close the interface even if hw_unavailable is set
284 	   (e.g. as we're released after a PC Card removal) */
285 	orinoco_lock_irq(priv);
286 
287 	priv->open = 0;
288 
289 	err = __orinoco_down(priv);
290 
291 	orinoco_unlock_irq(priv);
292 
293 	return err;
294 }
295 EXPORT_SYMBOL(orinoco_stop);
296 
297 struct net_device_stats *orinoco_get_stats(struct net_device *dev)
298 {
299 	struct orinoco_private *priv = ndev_priv(dev);
300 
301 	return &priv->stats;
302 }
303 EXPORT_SYMBOL(orinoco_get_stats);
304 
305 void orinoco_set_multicast_list(struct net_device *dev)
306 {
307 	struct orinoco_private *priv = ndev_priv(dev);
308 	unsigned long flags;
309 
310 	if (orinoco_lock(priv, &flags) != 0) {
311 		printk(KERN_DEBUG "%s: orinoco_set_multicast_list() "
312 		       "called when hw_unavailable\n", dev->name);
313 		return;
314 	}
315 
316 	__orinoco_set_multicast_list(dev);
317 	orinoco_unlock(priv, &flags);
318 }
319 EXPORT_SYMBOL(orinoco_set_multicast_list);
320 
321 int orinoco_change_mtu(struct net_device *dev, int new_mtu)
322 {
323 	struct orinoco_private *priv = ndev_priv(dev);
324 
325 	/* MTU + encapsulation + header length */
326 	if ((new_mtu + ENCAPS_OVERHEAD + sizeof(struct ieee80211_hdr)) >
327 	     (priv->nicbuf_size - ETH_HLEN))
328 		return -EINVAL;
329 
330 	dev->mtu = new_mtu;
331 
332 	return 0;
333 }
334 EXPORT_SYMBOL(orinoco_change_mtu);
335 
336 /********************************************************************/
337 /* Tx path                                                          */
338 /********************************************************************/
339 
340 /* Add encapsulation and MIC to the existing SKB.
341  * The main xmit routine will then send the whole lot to the card.
342  * Need 8 bytes headroom
343  * Need 8 bytes tailroom
344  *
345  *                          With encapsulated ethernet II frame
346  *                          --------
347  *                          803.3 header (14 bytes)
348  *                           dst[6]
349  * --------                  src[6]
350  * 803.3 header (14 bytes)   len[2]
351  *  dst[6]                  803.2 header (8 bytes)
352  *  src[6]                   encaps[6]
353  *  len[2] <- leave alone -> len[2]
354  * --------                 -------- <-- 0
355  * Payload                  Payload
356  * ...                      ...
357  *
358  * --------                 --------
359  *                          MIC (8 bytes)
360  *                          --------
361  *
362  * returns 0 on success, -ENOMEM on error.
363  */
364 int orinoco_process_xmit_skb(struct sk_buff *skb,
365 			     struct net_device *dev,
366 			     struct orinoco_private *priv,
367 			     int *tx_control,
368 			     u8 *mic_buf)
369 {
370 	struct orinoco_tkip_key *key;
371 	struct ethhdr *eh;
372 	int do_mic;
373 
374 	key = (struct orinoco_tkip_key *) priv->keys[priv->tx_key].key;
375 
376 	do_mic = ((priv->encode_alg == ORINOCO_ALG_TKIP) &&
377 		  (key != NULL));
378 
379 	if (do_mic)
380 		*tx_control |= (priv->tx_key << HERMES_MIC_KEY_ID_SHIFT) |
381 			HERMES_TXCTRL_MIC;
382 
383 	eh = (struct ethhdr *)skb->data;
384 
385 	/* Encapsulate Ethernet-II frames */
386 	if (ntohs(eh->h_proto) > ETH_DATA_LEN) { /* Ethernet-II frame */
387 		struct header_struct {
388 			struct ethhdr eth;	/* 802.3 header */
389 			u8 encap[6];		/* 802.2 header */
390 		} __packed hdr;
391 		int len = skb->len + sizeof(encaps_hdr) - (2 * ETH_ALEN);
392 
393 		if (skb_headroom(skb) < ENCAPS_OVERHEAD) {
394 			if (net_ratelimit())
395 				printk(KERN_ERR
396 				       "%s: Not enough headroom for 802.2 headers %d\n",
397 				       dev->name, skb_headroom(skb));
398 			return -ENOMEM;
399 		}
400 
401 		/* Fill in new header */
402 		memcpy(&hdr.eth, eh, 2 * ETH_ALEN);
403 		hdr.eth.h_proto = htons(len);
404 		memcpy(hdr.encap, encaps_hdr, sizeof(encaps_hdr));
405 
406 		/* Make room for the new header, and copy it in */
407 		eh = (struct ethhdr *) skb_push(skb, ENCAPS_OVERHEAD);
408 		memcpy(eh, &hdr, sizeof(hdr));
409 	}
410 
411 	/* Calculate Michael MIC */
412 	if (do_mic) {
413 		size_t len = skb->len - ETH_HLEN;
414 		u8 *mic = &mic_buf[0];
415 
416 		/* Have to write to an even address, so copy the spare
417 		 * byte across */
418 		if (skb->len % 2) {
419 			*mic = skb->data[skb->len - 1];
420 			mic++;
421 		}
422 
423 		orinoco_mic(priv->tx_tfm_mic, key->tx_mic,
424 			    eh->h_dest, eh->h_source, 0 /* priority */,
425 			    skb->data + ETH_HLEN,
426 			    len, mic);
427 	}
428 
429 	return 0;
430 }
431 EXPORT_SYMBOL(orinoco_process_xmit_skb);
432 
433 static netdev_tx_t orinoco_xmit(struct sk_buff *skb, struct net_device *dev)
434 {
435 	struct orinoco_private *priv = ndev_priv(dev);
436 	struct net_device_stats *stats = &priv->stats;
437 	struct hermes *hw = &priv->hw;
438 	int err = 0;
439 	u16 txfid = priv->txfid;
440 	int tx_control;
441 	unsigned long flags;
442 	u8 mic_buf[MICHAEL_MIC_LEN + 1];
443 
444 	if (!netif_running(dev)) {
445 		printk(KERN_ERR "%s: Tx on stopped device!\n",
446 		       dev->name);
447 		return NETDEV_TX_BUSY;
448 	}
449 
450 	if (netif_queue_stopped(dev)) {
451 		printk(KERN_DEBUG "%s: Tx while transmitter busy!\n",
452 		       dev->name);
453 		return NETDEV_TX_BUSY;
454 	}
455 
456 	if (orinoco_lock(priv, &flags) != 0) {
457 		printk(KERN_ERR "%s: orinoco_xmit() called while hw_unavailable\n",
458 		       dev->name);
459 		return NETDEV_TX_BUSY;
460 	}
461 
462 	if (!netif_carrier_ok(dev) ||
463 	    (priv->iw_mode == NL80211_IFTYPE_MONITOR)) {
464 		/* Oops, the firmware hasn't established a connection,
465 		   silently drop the packet (this seems to be the
466 		   safest approach). */
467 		goto drop;
468 	}
469 
470 	/* Check packet length */
471 	if (skb->len < ETH_HLEN)
472 		goto drop;
473 
474 	tx_control = HERMES_TXCTRL_TX_OK | HERMES_TXCTRL_TX_EX;
475 
476 	err = orinoco_process_xmit_skb(skb, dev, priv, &tx_control,
477 				       &mic_buf[0]);
478 	if (err)
479 		goto drop;
480 
481 	if (priv->has_alt_txcntl) {
482 		/* WPA enabled firmwares have tx_cntl at the end of
483 		 * the 802.11 header.  So write zeroed descriptor and
484 		 * 802.11 header at the same time
485 		 */
486 		char desc[HERMES_802_3_OFFSET];
487 		__le16 *txcntl = (__le16 *) &desc[HERMES_TXCNTL2_OFFSET];
488 
489 		memset(&desc, 0, sizeof(desc));
490 
491 		*txcntl = cpu_to_le16(tx_control);
492 		err = hw->ops->bap_pwrite(hw, USER_BAP, &desc, sizeof(desc),
493 					  txfid, 0);
494 		if (err) {
495 			if (net_ratelimit())
496 				printk(KERN_ERR "%s: Error %d writing Tx "
497 				       "descriptor to BAP\n", dev->name, err);
498 			goto busy;
499 		}
500 	} else {
501 		struct hermes_tx_descriptor desc;
502 
503 		memset(&desc, 0, sizeof(desc));
504 
505 		desc.tx_control = cpu_to_le16(tx_control);
506 		err = hw->ops->bap_pwrite(hw, USER_BAP, &desc, sizeof(desc),
507 					  txfid, 0);
508 		if (err) {
509 			if (net_ratelimit())
510 				printk(KERN_ERR "%s: Error %d writing Tx "
511 				       "descriptor to BAP\n", dev->name, err);
512 			goto busy;
513 		}
514 
515 		/* Clear the 802.11 header and data length fields - some
516 		 * firmwares (e.g. Lucent/Agere 8.xx) appear to get confused
517 		 * if this isn't done. */
518 		hermes_clear_words(hw, HERMES_DATA0,
519 				   HERMES_802_3_OFFSET - HERMES_802_11_OFFSET);
520 	}
521 
522 	err = hw->ops->bap_pwrite(hw, USER_BAP, skb->data, skb->len,
523 				  txfid, HERMES_802_3_OFFSET);
524 	if (err) {
525 		printk(KERN_ERR "%s: Error %d writing packet to BAP\n",
526 		       dev->name, err);
527 		goto busy;
528 	}
529 
530 	if (tx_control & HERMES_TXCTRL_MIC) {
531 		size_t offset = HERMES_802_3_OFFSET + skb->len;
532 		size_t len = MICHAEL_MIC_LEN;
533 
534 		if (offset % 2) {
535 			offset--;
536 			len++;
537 		}
538 		err = hw->ops->bap_pwrite(hw, USER_BAP, &mic_buf[0], len,
539 					  txfid, offset);
540 		if (err) {
541 			printk(KERN_ERR "%s: Error %d writing MIC to BAP\n",
542 			       dev->name, err);
543 			goto busy;
544 		}
545 	}
546 
547 	/* Finally, we actually initiate the send */
548 	netif_stop_queue(dev);
549 
550 	err = hw->ops->cmd_wait(hw, HERMES_CMD_TX | HERMES_CMD_RECL,
551 				txfid, NULL);
552 	if (err) {
553 		netif_start_queue(dev);
554 		if (net_ratelimit())
555 			printk(KERN_ERR "%s: Error %d transmitting packet\n",
556 				dev->name, err);
557 		goto busy;
558 	}
559 
560 	stats->tx_bytes += HERMES_802_3_OFFSET + skb->len;
561 	goto ok;
562 
563  drop:
564 	stats->tx_errors++;
565 	stats->tx_dropped++;
566 
567  ok:
568 	orinoco_unlock(priv, &flags);
569 	dev_kfree_skb(skb);
570 	return NETDEV_TX_OK;
571 
572  busy:
573 	if (err == -EIO)
574 		schedule_work(&priv->reset_work);
575 	orinoco_unlock(priv, &flags);
576 	return NETDEV_TX_BUSY;
577 }
578 
579 static void __orinoco_ev_alloc(struct net_device *dev, struct hermes *hw)
580 {
581 	struct orinoco_private *priv = ndev_priv(dev);
582 	u16 fid = hermes_read_regn(hw, ALLOCFID);
583 
584 	if (fid != priv->txfid) {
585 		if (fid != DUMMY_FID)
586 			printk(KERN_WARNING "%s: Allocate event on unexpected fid (%04X)\n",
587 			       dev->name, fid);
588 		return;
589 	}
590 
591 	hermes_write_regn(hw, ALLOCFID, DUMMY_FID);
592 }
593 
594 static void __orinoco_ev_tx(struct net_device *dev, struct hermes *hw)
595 {
596 	struct orinoco_private *priv = ndev_priv(dev);
597 	struct net_device_stats *stats = &priv->stats;
598 
599 	stats->tx_packets++;
600 
601 	netif_wake_queue(dev);
602 
603 	hermes_write_regn(hw, TXCOMPLFID, DUMMY_FID);
604 }
605 
606 static void __orinoco_ev_txexc(struct net_device *dev, struct hermes *hw)
607 {
608 	struct orinoco_private *priv = ndev_priv(dev);
609 	struct net_device_stats *stats = &priv->stats;
610 	u16 fid = hermes_read_regn(hw, TXCOMPLFID);
611 	u16 status;
612 	struct hermes_txexc_data hdr;
613 	int err = 0;
614 
615 	if (fid == DUMMY_FID)
616 		return; /* Nothing's really happened */
617 
618 	/* Read part of the frame header - we need status and addr1 */
619 	err = hw->ops->bap_pread(hw, IRQ_BAP, &hdr,
620 				 sizeof(struct hermes_txexc_data),
621 				 fid, 0);
622 
623 	hermes_write_regn(hw, TXCOMPLFID, DUMMY_FID);
624 	stats->tx_errors++;
625 
626 	if (err) {
627 		printk(KERN_WARNING "%s: Unable to read descriptor on Tx error "
628 		       "(FID=%04X error %d)\n",
629 		       dev->name, fid, err);
630 		return;
631 	}
632 
633 	DEBUG(1, "%s: Tx error, err %d (FID=%04X)\n", dev->name,
634 	      err, fid);
635 
636 	/* We produce a TXDROP event only for retry or lifetime
637 	 * exceeded, because that's the only status that really mean
638 	 * that this particular node went away.
639 	 * Other errors means that *we* screwed up. - Jean II */
640 	status = le16_to_cpu(hdr.desc.status);
641 	if (status & (HERMES_TXSTAT_RETRYERR | HERMES_TXSTAT_AGEDERR)) {
642 		union iwreq_data	wrqu;
643 
644 		/* Copy 802.11 dest address.
645 		 * We use the 802.11 header because the frame may
646 		 * not be 802.3 or may be mangled...
647 		 * In Ad-Hoc mode, it will be the node address.
648 		 * In managed mode, it will be most likely the AP addr
649 		 * User space will figure out how to convert it to
650 		 * whatever it needs (IP address or else).
651 		 * - Jean II */
652 		memcpy(wrqu.addr.sa_data, hdr.addr1, ETH_ALEN);
653 		wrqu.addr.sa_family = ARPHRD_ETHER;
654 
655 		/* Send event to user space */
656 		wireless_send_event(dev, IWEVTXDROP, &wrqu, NULL);
657 	}
658 
659 	netif_wake_queue(dev);
660 }
661 
662 void orinoco_tx_timeout(struct net_device *dev)
663 {
664 	struct orinoco_private *priv = ndev_priv(dev);
665 	struct net_device_stats *stats = &priv->stats;
666 	struct hermes *hw = &priv->hw;
667 
668 	printk(KERN_WARNING "%s: Tx timeout! "
669 	       "ALLOCFID=%04x, TXCOMPLFID=%04x, EVSTAT=%04x\n",
670 	       dev->name, hermes_read_regn(hw, ALLOCFID),
671 	       hermes_read_regn(hw, TXCOMPLFID), hermes_read_regn(hw, EVSTAT));
672 
673 	stats->tx_errors++;
674 
675 	schedule_work(&priv->reset_work);
676 }
677 EXPORT_SYMBOL(orinoco_tx_timeout);
678 
679 /********************************************************************/
680 /* Rx path (data frames)                                            */
681 /********************************************************************/
682 
683 /* Does the frame have a SNAP header indicating it should be
684  * de-encapsulated to Ethernet-II? */
685 static inline int is_ethersnap(void *_hdr)
686 {
687 	u8 *hdr = _hdr;
688 
689 	/* We de-encapsulate all packets which, a) have SNAP headers
690 	 * (i.e. SSAP=DSAP=0xaa and CTRL=0x3 in the 802.2 LLC header
691 	 * and where b) the OUI of the SNAP header is 00:00:00 or
692 	 * 00:00:f8 - we need both because different APs appear to use
693 	 * different OUIs for some reason */
694 	return (memcmp(hdr, &encaps_hdr, 5) == 0)
695 		&& ((hdr[5] == 0x00) || (hdr[5] == 0xf8));
696 }
697 
698 static inline void orinoco_spy_gather(struct net_device *dev, u_char *mac,
699 				      int level, int noise)
700 {
701 	struct iw_quality wstats;
702 	wstats.level = level - 0x95;
703 	wstats.noise = noise - 0x95;
704 	wstats.qual = (level > noise) ? (level - noise) : 0;
705 	wstats.updated = IW_QUAL_ALL_UPDATED | IW_QUAL_DBM;
706 	/* Update spy records */
707 	wireless_spy_update(dev, mac, &wstats);
708 }
709 
710 static void orinoco_stat_gather(struct net_device *dev,
711 				struct sk_buff *skb,
712 				struct hermes_rx_descriptor *desc)
713 {
714 	struct orinoco_private *priv = ndev_priv(dev);
715 
716 	/* Using spy support with lots of Rx packets, like in an
717 	 * infrastructure (AP), will really slow down everything, because
718 	 * the MAC address must be compared to each entry of the spy list.
719 	 * If the user really asks for it (set some address in the
720 	 * spy list), we do it, but he will pay the price.
721 	 * Note that to get here, you need both WIRELESS_SPY
722 	 * compiled in AND some addresses in the list !!!
723 	 */
724 	/* Note : gcc will optimise the whole section away if
725 	 * WIRELESS_SPY is not defined... - Jean II */
726 	if (SPY_NUMBER(priv)) {
727 		orinoco_spy_gather(dev, skb_mac_header(skb) + ETH_ALEN,
728 				   desc->signal, desc->silence);
729 	}
730 }
731 
732 /*
733  * orinoco_rx_monitor - handle received monitor frames.
734  *
735  * Arguments:
736  *	dev		network device
737  *	rxfid		received FID
738  *	desc		rx descriptor of the frame
739  *
740  * Call context: interrupt
741  */
742 static void orinoco_rx_monitor(struct net_device *dev, u16 rxfid,
743 			       struct hermes_rx_descriptor *desc)
744 {
745 	u32 hdrlen = 30;	/* return full header by default */
746 	u32 datalen = 0;
747 	u16 fc;
748 	int err;
749 	int len;
750 	struct sk_buff *skb;
751 	struct orinoco_private *priv = ndev_priv(dev);
752 	struct net_device_stats *stats = &priv->stats;
753 	struct hermes *hw = &priv->hw;
754 
755 	len = le16_to_cpu(desc->data_len);
756 
757 	/* Determine the size of the header and the data */
758 	fc = le16_to_cpu(desc->frame_ctl);
759 	switch (fc & IEEE80211_FCTL_FTYPE) {
760 	case IEEE80211_FTYPE_DATA:
761 		if ((fc & IEEE80211_FCTL_TODS)
762 		    && (fc & IEEE80211_FCTL_FROMDS))
763 			hdrlen = 30;
764 		else
765 			hdrlen = 24;
766 		datalen = len;
767 		break;
768 	case IEEE80211_FTYPE_MGMT:
769 		hdrlen = 24;
770 		datalen = len;
771 		break;
772 	case IEEE80211_FTYPE_CTL:
773 		switch (fc & IEEE80211_FCTL_STYPE) {
774 		case IEEE80211_STYPE_PSPOLL:
775 		case IEEE80211_STYPE_RTS:
776 		case IEEE80211_STYPE_CFEND:
777 		case IEEE80211_STYPE_CFENDACK:
778 			hdrlen = 16;
779 			break;
780 		case IEEE80211_STYPE_CTS:
781 		case IEEE80211_STYPE_ACK:
782 			hdrlen = 10;
783 			break;
784 		}
785 		break;
786 	default:
787 		/* Unknown frame type */
788 		break;
789 	}
790 
791 	/* sanity check the length */
792 	if (datalen > IEEE80211_MAX_DATA_LEN + 12) {
793 		printk(KERN_DEBUG "%s: oversized monitor frame, "
794 		       "data length = %d\n", dev->name, datalen);
795 		stats->rx_length_errors++;
796 		goto update_stats;
797 	}
798 
799 	skb = dev_alloc_skb(hdrlen + datalen);
800 	if (!skb) {
801 		printk(KERN_WARNING "%s: Cannot allocate skb for monitor frame\n",
802 		       dev->name);
803 		goto update_stats;
804 	}
805 
806 	/* Copy the 802.11 header to the skb */
807 	memcpy(skb_put(skb, hdrlen), &(desc->frame_ctl), hdrlen);
808 	skb_reset_mac_header(skb);
809 
810 	/* If any, copy the data from the card to the skb */
811 	if (datalen > 0) {
812 		err = hw->ops->bap_pread(hw, IRQ_BAP, skb_put(skb, datalen),
813 					 ALIGN(datalen, 2), rxfid,
814 					 HERMES_802_2_OFFSET);
815 		if (err) {
816 			printk(KERN_ERR "%s: error %d reading monitor frame\n",
817 			       dev->name, err);
818 			goto drop;
819 		}
820 	}
821 
822 	skb->dev = dev;
823 	skb->ip_summed = CHECKSUM_NONE;
824 	skb->pkt_type = PACKET_OTHERHOST;
825 	skb->protocol = cpu_to_be16(ETH_P_802_2);
826 
827 	stats->rx_packets++;
828 	stats->rx_bytes += skb->len;
829 
830 	netif_rx(skb);
831 	return;
832 
833  drop:
834 	dev_kfree_skb_irq(skb);
835  update_stats:
836 	stats->rx_errors++;
837 	stats->rx_dropped++;
838 }
839 
840 void __orinoco_ev_rx(struct net_device *dev, struct hermes *hw)
841 {
842 	struct orinoco_private *priv = ndev_priv(dev);
843 	struct net_device_stats *stats = &priv->stats;
844 	struct iw_statistics *wstats = &priv->wstats;
845 	struct sk_buff *skb = NULL;
846 	u16 rxfid, status;
847 	int length;
848 	struct hermes_rx_descriptor *desc;
849 	struct orinoco_rx_data *rx_data;
850 	int err;
851 
852 	desc = kmalloc(sizeof(*desc), GFP_ATOMIC);
853 	if (!desc)
854 		goto update_stats;
855 
856 	rxfid = hermes_read_regn(hw, RXFID);
857 
858 	err = hw->ops->bap_pread(hw, IRQ_BAP, desc, sizeof(*desc),
859 				 rxfid, 0);
860 	if (err) {
861 		printk(KERN_ERR "%s: error %d reading Rx descriptor. "
862 		       "Frame dropped.\n", dev->name, err);
863 		goto update_stats;
864 	}
865 
866 	status = le16_to_cpu(desc->status);
867 
868 	if (status & HERMES_RXSTAT_BADCRC) {
869 		DEBUG(1, "%s: Bad CRC on Rx. Frame dropped.\n",
870 		      dev->name);
871 		stats->rx_crc_errors++;
872 		goto update_stats;
873 	}
874 
875 	/* Handle frames in monitor mode */
876 	if (priv->iw_mode == NL80211_IFTYPE_MONITOR) {
877 		orinoco_rx_monitor(dev, rxfid, desc);
878 		goto out;
879 	}
880 
881 	if (status & HERMES_RXSTAT_UNDECRYPTABLE) {
882 		DEBUG(1, "%s: Undecryptable frame on Rx. Frame dropped.\n",
883 		      dev->name);
884 		wstats->discard.code++;
885 		goto update_stats;
886 	}
887 
888 	length = le16_to_cpu(desc->data_len);
889 
890 	/* Sanity checks */
891 	if (length < 3) { /* No for even an 802.2 LLC header */
892 		/* At least on Symbol firmware with PCF we get quite a
893 		   lot of these legitimately - Poll frames with no
894 		   data. */
895 		goto out;
896 	}
897 	if (length > IEEE80211_MAX_DATA_LEN) {
898 		printk(KERN_WARNING "%s: Oversized frame received (%d bytes)\n",
899 		       dev->name, length);
900 		stats->rx_length_errors++;
901 		goto update_stats;
902 	}
903 
904 	/* Payload size does not include Michael MIC. Increase payload
905 	 * size to read it together with the data. */
906 	if (status & HERMES_RXSTAT_MIC)
907 		length += MICHAEL_MIC_LEN;
908 
909 	/* We need space for the packet data itself, plus an ethernet
910 	   header, plus 2 bytes so we can align the IP header on a
911 	   32bit boundary, plus 1 byte so we can read in odd length
912 	   packets from the card, which has an IO granularity of 16
913 	   bits */
914 	skb = dev_alloc_skb(length + ETH_HLEN + 2 + 1);
915 	if (!skb) {
916 		printk(KERN_WARNING "%s: Can't allocate skb for Rx\n",
917 		       dev->name);
918 		goto update_stats;
919 	}
920 
921 	/* We'll prepend the header, so reserve space for it.  The worst
922 	   case is no decapsulation, when 802.3 header is prepended and
923 	   nothing is removed.  2 is for aligning the IP header.  */
924 	skb_reserve(skb, ETH_HLEN + 2);
925 
926 	err = hw->ops->bap_pread(hw, IRQ_BAP, skb_put(skb, length),
927 				 ALIGN(length, 2), rxfid,
928 				 HERMES_802_2_OFFSET);
929 	if (err) {
930 		printk(KERN_ERR "%s: error %d reading frame. "
931 		       "Frame dropped.\n", dev->name, err);
932 		goto drop;
933 	}
934 
935 	/* Add desc and skb to rx queue */
936 	rx_data = kzalloc(sizeof(*rx_data), GFP_ATOMIC);
937 	if (!rx_data)
938 		goto drop;
939 
940 	rx_data->desc = desc;
941 	rx_data->skb = skb;
942 	list_add_tail(&rx_data->list, &priv->rx_list);
943 	tasklet_schedule(&priv->rx_tasklet);
944 
945 	return;
946 
947 drop:
948 	dev_kfree_skb_irq(skb);
949 update_stats:
950 	stats->rx_errors++;
951 	stats->rx_dropped++;
952 out:
953 	kfree(desc);
954 }
955 EXPORT_SYMBOL(__orinoco_ev_rx);
956 
957 static void orinoco_rx(struct net_device *dev,
958 		       struct hermes_rx_descriptor *desc,
959 		       struct sk_buff *skb)
960 {
961 	struct orinoco_private *priv = ndev_priv(dev);
962 	struct net_device_stats *stats = &priv->stats;
963 	u16 status, fc;
964 	int length;
965 	struct ethhdr *hdr;
966 
967 	status = le16_to_cpu(desc->status);
968 	length = le16_to_cpu(desc->data_len);
969 	fc = le16_to_cpu(desc->frame_ctl);
970 
971 	/* Calculate and check MIC */
972 	if (status & HERMES_RXSTAT_MIC) {
973 		struct orinoco_tkip_key *key;
974 		int key_id = ((status & HERMES_RXSTAT_MIC_KEY_ID) >>
975 			      HERMES_MIC_KEY_ID_SHIFT);
976 		u8 mic[MICHAEL_MIC_LEN];
977 		u8 *rxmic;
978 		u8 *src = (fc & IEEE80211_FCTL_FROMDS) ?
979 			desc->addr3 : desc->addr2;
980 
981 		/* Extract Michael MIC from payload */
982 		rxmic = skb->data + skb->len - MICHAEL_MIC_LEN;
983 
984 		skb_trim(skb, skb->len - MICHAEL_MIC_LEN);
985 		length -= MICHAEL_MIC_LEN;
986 
987 		key = (struct orinoco_tkip_key *) priv->keys[key_id].key;
988 
989 		if (!key) {
990 			printk(KERN_WARNING "%s: Received encrypted frame from "
991 			       "%pM using key %i, but key is not installed\n",
992 			       dev->name, src, key_id);
993 			goto drop;
994 		}
995 
996 		orinoco_mic(priv->rx_tfm_mic, key->rx_mic, desc->addr1, src,
997 			    0, /* priority or QoS? */
998 			    skb->data, skb->len, &mic[0]);
999 
1000 		if (memcmp(mic, rxmic,
1001 			   MICHAEL_MIC_LEN)) {
1002 			union iwreq_data wrqu;
1003 			struct iw_michaelmicfailure wxmic;
1004 
1005 			printk(KERN_WARNING "%s: "
1006 			       "Invalid Michael MIC in data frame from %pM, "
1007 			       "using key %i\n",
1008 			       dev->name, src, key_id);
1009 
1010 			/* TODO: update stats */
1011 
1012 			/* Notify userspace */
1013 			memset(&wxmic, 0, sizeof(wxmic));
1014 			wxmic.flags = key_id & IW_MICFAILURE_KEY_ID;
1015 			wxmic.flags |= (desc->addr1[0] & 1) ?
1016 				IW_MICFAILURE_GROUP : IW_MICFAILURE_PAIRWISE;
1017 			wxmic.src_addr.sa_family = ARPHRD_ETHER;
1018 			memcpy(wxmic.src_addr.sa_data, src, ETH_ALEN);
1019 
1020 			(void) orinoco_hw_get_tkip_iv(priv, key_id,
1021 						      &wxmic.tsc[0]);
1022 
1023 			memset(&wrqu, 0, sizeof(wrqu));
1024 			wrqu.data.length = sizeof(wxmic);
1025 			wireless_send_event(dev, IWEVMICHAELMICFAILURE, &wrqu,
1026 					    (char *) &wxmic);
1027 
1028 			goto drop;
1029 		}
1030 	}
1031 
1032 	/* Handle decapsulation
1033 	 * In most cases, the firmware tell us about SNAP frames.
1034 	 * For some reason, the SNAP frames sent by LinkSys APs
1035 	 * are not properly recognised by most firmwares.
1036 	 * So, check ourselves */
1037 	if (length >= ENCAPS_OVERHEAD &&
1038 	    (((status & HERMES_RXSTAT_MSGTYPE) == HERMES_RXSTAT_1042) ||
1039 	     ((status & HERMES_RXSTAT_MSGTYPE) == HERMES_RXSTAT_TUNNEL) ||
1040 	     is_ethersnap(skb->data))) {
1041 		/* These indicate a SNAP within 802.2 LLC within
1042 		   802.11 frame which we'll need to de-encapsulate to
1043 		   the original EthernetII frame. */
1044 		hdr = (struct ethhdr *)skb_push(skb,
1045 						ETH_HLEN - ENCAPS_OVERHEAD);
1046 	} else {
1047 		/* 802.3 frame - prepend 802.3 header as is */
1048 		hdr = (struct ethhdr *)skb_push(skb, ETH_HLEN);
1049 		hdr->h_proto = htons(length);
1050 	}
1051 	memcpy(hdr->h_dest, desc->addr1, ETH_ALEN);
1052 	if (fc & IEEE80211_FCTL_FROMDS)
1053 		memcpy(hdr->h_source, desc->addr3, ETH_ALEN);
1054 	else
1055 		memcpy(hdr->h_source, desc->addr2, ETH_ALEN);
1056 
1057 	skb->protocol = eth_type_trans(skb, dev);
1058 	skb->ip_summed = CHECKSUM_NONE;
1059 	if (fc & IEEE80211_FCTL_TODS)
1060 		skb->pkt_type = PACKET_OTHERHOST;
1061 
1062 	/* Process the wireless stats if needed */
1063 	orinoco_stat_gather(dev, skb, desc);
1064 
1065 	/* Pass the packet to the networking stack */
1066 	netif_rx(skb);
1067 	stats->rx_packets++;
1068 	stats->rx_bytes += length;
1069 
1070 	return;
1071 
1072  drop:
1073 	dev_kfree_skb(skb);
1074 	stats->rx_errors++;
1075 	stats->rx_dropped++;
1076 }
1077 
1078 static void orinoco_rx_isr_tasklet(unsigned long data)
1079 {
1080 	struct orinoco_private *priv = (struct orinoco_private *) data;
1081 	struct net_device *dev = priv->ndev;
1082 	struct orinoco_rx_data *rx_data, *temp;
1083 	struct hermes_rx_descriptor *desc;
1084 	struct sk_buff *skb;
1085 	unsigned long flags;
1086 
1087 	/* orinoco_rx requires the driver lock, and we also need to
1088 	 * protect priv->rx_list, so just hold the lock over the
1089 	 * lot.
1090 	 *
1091 	 * If orinoco_lock fails, we've unplugged the card. In this
1092 	 * case just abort. */
1093 	if (orinoco_lock(priv, &flags) != 0)
1094 		return;
1095 
1096 	/* extract desc and skb from queue */
1097 	list_for_each_entry_safe(rx_data, temp, &priv->rx_list, list) {
1098 		desc = rx_data->desc;
1099 		skb = rx_data->skb;
1100 		list_del(&rx_data->list);
1101 		kfree(rx_data);
1102 
1103 		orinoco_rx(dev, desc, skb);
1104 
1105 		kfree(desc);
1106 	}
1107 
1108 	orinoco_unlock(priv, &flags);
1109 }
1110 
1111 /********************************************************************/
1112 /* Rx path (info frames)                                            */
1113 /********************************************************************/
1114 
1115 static void print_linkstatus(struct net_device *dev, u16 status)
1116 {
1117 	char *s;
1118 
1119 	if (suppress_linkstatus)
1120 		return;
1121 
1122 	switch (status) {
1123 	case HERMES_LINKSTATUS_NOT_CONNECTED:
1124 		s = "Not Connected";
1125 		break;
1126 	case HERMES_LINKSTATUS_CONNECTED:
1127 		s = "Connected";
1128 		break;
1129 	case HERMES_LINKSTATUS_DISCONNECTED:
1130 		s = "Disconnected";
1131 		break;
1132 	case HERMES_LINKSTATUS_AP_CHANGE:
1133 		s = "AP Changed";
1134 		break;
1135 	case HERMES_LINKSTATUS_AP_OUT_OF_RANGE:
1136 		s = "AP Out of Range";
1137 		break;
1138 	case HERMES_LINKSTATUS_AP_IN_RANGE:
1139 		s = "AP In Range";
1140 		break;
1141 	case HERMES_LINKSTATUS_ASSOC_FAILED:
1142 		s = "Association Failed";
1143 		break;
1144 	default:
1145 		s = "UNKNOWN";
1146 	}
1147 
1148 	printk(KERN_DEBUG "%s: New link status: %s (%04x)\n",
1149 	       dev->name, s, status);
1150 }
1151 
1152 /* Search scan results for requested BSSID, join it if found */
1153 static void orinoco_join_ap(struct work_struct *work)
1154 {
1155 	struct orinoco_private *priv =
1156 		container_of(work, struct orinoco_private, join_work);
1157 	struct net_device *dev = priv->ndev;
1158 	struct hermes *hw = &priv->hw;
1159 	int err;
1160 	unsigned long flags;
1161 	struct join_req {
1162 		u8 bssid[ETH_ALEN];
1163 		__le16 channel;
1164 	} __packed req;
1165 	const int atom_len = offsetof(struct prism2_scan_apinfo, atim);
1166 	struct prism2_scan_apinfo *atom = NULL;
1167 	int offset = 4;
1168 	int found = 0;
1169 	u8 *buf;
1170 	u16 len;
1171 
1172 	/* Allocate buffer for scan results */
1173 	buf = kmalloc(MAX_SCAN_LEN, GFP_KERNEL);
1174 	if (!buf)
1175 		return;
1176 
1177 	if (orinoco_lock(priv, &flags) != 0)
1178 		goto fail_lock;
1179 
1180 	/* Sanity checks in case user changed something in the meantime */
1181 	if (!priv->bssid_fixed)
1182 		goto out;
1183 
1184 	if (strlen(priv->desired_essid) == 0)
1185 		goto out;
1186 
1187 	/* Read scan results from the firmware */
1188 	err = hw->ops->read_ltv(hw, USER_BAP,
1189 				HERMES_RID_SCANRESULTSTABLE,
1190 				MAX_SCAN_LEN, &len, buf);
1191 	if (err) {
1192 		printk(KERN_ERR "%s: Cannot read scan results\n",
1193 		       dev->name);
1194 		goto out;
1195 	}
1196 
1197 	len = HERMES_RECLEN_TO_BYTES(len);
1198 
1199 	/* Go through the scan results looking for the channel of the AP
1200 	 * we were requested to join */
1201 	for (; offset + atom_len <= len; offset += atom_len) {
1202 		atom = (struct prism2_scan_apinfo *) (buf + offset);
1203 		if (memcmp(&atom->bssid, priv->desired_bssid, ETH_ALEN) == 0) {
1204 			found = 1;
1205 			break;
1206 		}
1207 	}
1208 
1209 	if (!found) {
1210 		DEBUG(1, "%s: Requested AP not found in scan results\n",
1211 		      dev->name);
1212 		goto out;
1213 	}
1214 
1215 	memcpy(req.bssid, priv->desired_bssid, ETH_ALEN);
1216 	req.channel = atom->channel;	/* both are little-endian */
1217 	err = HERMES_WRITE_RECORD(hw, USER_BAP, HERMES_RID_CNFJOINREQUEST,
1218 				  &req);
1219 	if (err)
1220 		printk(KERN_ERR "%s: Error issuing join request\n", dev->name);
1221 
1222  out:
1223 	orinoco_unlock(priv, &flags);
1224 
1225  fail_lock:
1226 	kfree(buf);
1227 }
1228 
1229 /* Send new BSSID to userspace */
1230 static void orinoco_send_bssid_wevent(struct orinoco_private *priv)
1231 {
1232 	struct net_device *dev = priv->ndev;
1233 	struct hermes *hw = &priv->hw;
1234 	union iwreq_data wrqu;
1235 	int err;
1236 
1237 	err = hw->ops->read_ltv(hw, USER_BAP, HERMES_RID_CURRENTBSSID,
1238 				ETH_ALEN, NULL, wrqu.ap_addr.sa_data);
1239 	if (err != 0)
1240 		return;
1241 
1242 	wrqu.ap_addr.sa_family = ARPHRD_ETHER;
1243 
1244 	/* Send event to user space */
1245 	wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL);
1246 }
1247 
1248 static void orinoco_send_assocreqie_wevent(struct orinoco_private *priv)
1249 {
1250 	struct net_device *dev = priv->ndev;
1251 	struct hermes *hw = &priv->hw;
1252 	union iwreq_data wrqu;
1253 	int err;
1254 	u8 buf[88];
1255 	u8 *ie;
1256 
1257 	if (!priv->has_wpa)
1258 		return;
1259 
1260 	err = hw->ops->read_ltv(hw, USER_BAP, HERMES_RID_CURRENT_ASSOC_REQ_INFO,
1261 				sizeof(buf), NULL, &buf);
1262 	if (err != 0)
1263 		return;
1264 
1265 	ie = orinoco_get_wpa_ie(buf, sizeof(buf));
1266 	if (ie) {
1267 		int rem = sizeof(buf) - (ie - &buf[0]);
1268 		wrqu.data.length = ie[1] + 2;
1269 		if (wrqu.data.length > rem)
1270 			wrqu.data.length = rem;
1271 
1272 		if (wrqu.data.length)
1273 			/* Send event to user space */
1274 			wireless_send_event(dev, IWEVASSOCREQIE, &wrqu, ie);
1275 	}
1276 }
1277 
1278 static void orinoco_send_assocrespie_wevent(struct orinoco_private *priv)
1279 {
1280 	struct net_device *dev = priv->ndev;
1281 	struct hermes *hw = &priv->hw;
1282 	union iwreq_data wrqu;
1283 	int err;
1284 	u8 buf[88]; /* TODO: verify max size or IW_GENERIC_IE_MAX */
1285 	u8 *ie;
1286 
1287 	if (!priv->has_wpa)
1288 		return;
1289 
1290 	err = hw->ops->read_ltv(hw, USER_BAP,
1291 				HERMES_RID_CURRENT_ASSOC_RESP_INFO,
1292 				sizeof(buf), NULL, &buf);
1293 	if (err != 0)
1294 		return;
1295 
1296 	ie = orinoco_get_wpa_ie(buf, sizeof(buf));
1297 	if (ie) {
1298 		int rem = sizeof(buf) - (ie - &buf[0]);
1299 		wrqu.data.length = ie[1] + 2;
1300 		if (wrqu.data.length > rem)
1301 			wrqu.data.length = rem;
1302 
1303 		if (wrqu.data.length)
1304 			/* Send event to user space */
1305 			wireless_send_event(dev, IWEVASSOCRESPIE, &wrqu, ie);
1306 	}
1307 }
1308 
1309 static void orinoco_send_wevents(struct work_struct *work)
1310 {
1311 	struct orinoco_private *priv =
1312 		container_of(work, struct orinoco_private, wevent_work);
1313 	unsigned long flags;
1314 
1315 	if (orinoco_lock(priv, &flags) != 0)
1316 		return;
1317 
1318 	orinoco_send_assocreqie_wevent(priv);
1319 	orinoco_send_assocrespie_wevent(priv);
1320 	orinoco_send_bssid_wevent(priv);
1321 
1322 	orinoco_unlock(priv, &flags);
1323 }
1324 
1325 static void qbuf_scan(struct orinoco_private *priv, void *buf,
1326 		      int len, int type)
1327 {
1328 	struct orinoco_scan_data *sd;
1329 	unsigned long flags;
1330 
1331 	sd = kmalloc(sizeof(*sd), GFP_ATOMIC);
1332 	if (!sd)
1333 		return;
1334 
1335 	sd->buf = buf;
1336 	sd->len = len;
1337 	sd->type = type;
1338 
1339 	spin_lock_irqsave(&priv->scan_lock, flags);
1340 	list_add_tail(&sd->list, &priv->scan_list);
1341 	spin_unlock_irqrestore(&priv->scan_lock, flags);
1342 
1343 	schedule_work(&priv->process_scan);
1344 }
1345 
1346 static void qabort_scan(struct orinoco_private *priv)
1347 {
1348 	struct orinoco_scan_data *sd;
1349 	unsigned long flags;
1350 
1351 	sd = kmalloc(sizeof(*sd), GFP_ATOMIC);
1352 	if (!sd)
1353 		return;
1354 
1355 	sd->len = -1; /* Abort */
1356 
1357 	spin_lock_irqsave(&priv->scan_lock, flags);
1358 	list_add_tail(&sd->list, &priv->scan_list);
1359 	spin_unlock_irqrestore(&priv->scan_lock, flags);
1360 
1361 	schedule_work(&priv->process_scan);
1362 }
1363 
1364 static void orinoco_process_scan_results(struct work_struct *work)
1365 {
1366 	struct orinoco_private *priv =
1367 		container_of(work, struct orinoco_private, process_scan);
1368 	struct orinoco_scan_data *sd, *temp;
1369 	unsigned long flags;
1370 	void *buf;
1371 	int len;
1372 	int type;
1373 
1374 	spin_lock_irqsave(&priv->scan_lock, flags);
1375 	list_for_each_entry_safe(sd, temp, &priv->scan_list, list) {
1376 
1377 		buf = sd->buf;
1378 		len = sd->len;
1379 		type = sd->type;
1380 
1381 		list_del(&sd->list);
1382 		spin_unlock_irqrestore(&priv->scan_lock, flags);
1383 		kfree(sd);
1384 
1385 		if (len > 0) {
1386 			if (type == HERMES_INQ_CHANNELINFO)
1387 				orinoco_add_extscan_result(priv, buf, len);
1388 			else
1389 				orinoco_add_hostscan_results(priv, buf, len);
1390 
1391 			kfree(buf);
1392 		} else {
1393 			/* Either abort or complete the scan */
1394 			orinoco_scan_done(priv, (len < 0));
1395 		}
1396 
1397 		spin_lock_irqsave(&priv->scan_lock, flags);
1398 	}
1399 	spin_unlock_irqrestore(&priv->scan_lock, flags);
1400 }
1401 
1402 void __orinoco_ev_info(struct net_device *dev, struct hermes *hw)
1403 {
1404 	struct orinoco_private *priv = ndev_priv(dev);
1405 	u16 infofid;
1406 	struct {
1407 		__le16 len;
1408 		__le16 type;
1409 	} __packed info;
1410 	int len, type;
1411 	int err;
1412 
1413 	/* This is an answer to an INQUIRE command that we did earlier,
1414 	 * or an information "event" generated by the card
1415 	 * The controller return to us a pseudo frame containing
1416 	 * the information in question - Jean II */
1417 	infofid = hermes_read_regn(hw, INFOFID);
1418 
1419 	/* Read the info frame header - don't try too hard */
1420 	err = hw->ops->bap_pread(hw, IRQ_BAP, &info, sizeof(info),
1421 				 infofid, 0);
1422 	if (err) {
1423 		printk(KERN_ERR "%s: error %d reading info frame. "
1424 		       "Frame dropped.\n", dev->name, err);
1425 		return;
1426 	}
1427 
1428 	len = HERMES_RECLEN_TO_BYTES(le16_to_cpu(info.len));
1429 	type = le16_to_cpu(info.type);
1430 
1431 	switch (type) {
1432 	case HERMES_INQ_TALLIES: {
1433 		struct hermes_tallies_frame tallies;
1434 		struct iw_statistics *wstats = &priv->wstats;
1435 
1436 		if (len > sizeof(tallies)) {
1437 			printk(KERN_WARNING "%s: Tallies frame too long (%d bytes)\n",
1438 			       dev->name, len);
1439 			len = sizeof(tallies);
1440 		}
1441 
1442 		err = hw->ops->bap_pread(hw, IRQ_BAP, &tallies, len,
1443 					 infofid, sizeof(info));
1444 		if (err)
1445 			break;
1446 
1447 		/* Increment our various counters */
1448 		/* wstats->discard.nwid - no wrong BSSID stuff */
1449 		wstats->discard.code +=
1450 			le16_to_cpu(tallies.RxWEPUndecryptable);
1451 		if (len == sizeof(tallies))
1452 			wstats->discard.code +=
1453 				le16_to_cpu(tallies.RxDiscards_WEPICVError) +
1454 				le16_to_cpu(tallies.RxDiscards_WEPExcluded);
1455 		wstats->discard.misc +=
1456 			le16_to_cpu(tallies.TxDiscardsWrongSA);
1457 		wstats->discard.fragment +=
1458 			le16_to_cpu(tallies.RxMsgInBadMsgFragments);
1459 		wstats->discard.retries +=
1460 			le16_to_cpu(tallies.TxRetryLimitExceeded);
1461 		/* wstats->miss.beacon - no match */
1462 	}
1463 	break;
1464 	case HERMES_INQ_LINKSTATUS: {
1465 		struct hermes_linkstatus linkstatus;
1466 		u16 newstatus;
1467 		int connected;
1468 
1469 		if (priv->iw_mode == NL80211_IFTYPE_MONITOR)
1470 			break;
1471 
1472 		if (len != sizeof(linkstatus)) {
1473 			printk(KERN_WARNING "%s: Unexpected size for linkstatus frame (%d bytes)\n",
1474 			       dev->name, len);
1475 			break;
1476 		}
1477 
1478 		err = hw->ops->bap_pread(hw, IRQ_BAP, &linkstatus, len,
1479 					 infofid, sizeof(info));
1480 		if (err)
1481 			break;
1482 		newstatus = le16_to_cpu(linkstatus.linkstatus);
1483 
1484 		/* Symbol firmware uses "out of range" to signal that
1485 		 * the hostscan frame can be requested.  */
1486 		if (newstatus == HERMES_LINKSTATUS_AP_OUT_OF_RANGE &&
1487 		    priv->firmware_type == FIRMWARE_TYPE_SYMBOL &&
1488 		    priv->has_hostscan && priv->scan_request) {
1489 			hermes_inquire(hw, HERMES_INQ_HOSTSCAN_SYMBOL);
1490 			break;
1491 		}
1492 
1493 		connected = (newstatus == HERMES_LINKSTATUS_CONNECTED)
1494 			|| (newstatus == HERMES_LINKSTATUS_AP_CHANGE)
1495 			|| (newstatus == HERMES_LINKSTATUS_AP_IN_RANGE);
1496 
1497 		if (connected)
1498 			netif_carrier_on(dev);
1499 		else if (!ignore_disconnect)
1500 			netif_carrier_off(dev);
1501 
1502 		if (newstatus != priv->last_linkstatus) {
1503 			priv->last_linkstatus = newstatus;
1504 			print_linkstatus(dev, newstatus);
1505 			/* The info frame contains only one word which is the
1506 			 * status (see hermes.h). The status is pretty boring
1507 			 * in itself, that's why we export the new BSSID...
1508 			 * Jean II */
1509 			schedule_work(&priv->wevent_work);
1510 		}
1511 	}
1512 	break;
1513 	case HERMES_INQ_SCAN:
1514 		if (!priv->scan_request && priv->bssid_fixed &&
1515 		    priv->firmware_type == FIRMWARE_TYPE_INTERSIL) {
1516 			schedule_work(&priv->join_work);
1517 			break;
1518 		}
1519 		/* fall through */
1520 	case HERMES_INQ_HOSTSCAN:
1521 	case HERMES_INQ_HOSTSCAN_SYMBOL: {
1522 		/* Result of a scanning. Contains information about
1523 		 * cells in the vicinity - Jean II */
1524 		unsigned char *buf;
1525 
1526 		/* Sanity check */
1527 		if (len > 4096) {
1528 			printk(KERN_WARNING "%s: Scan results too large (%d bytes)\n",
1529 			       dev->name, len);
1530 			qabort_scan(priv);
1531 			break;
1532 		}
1533 
1534 		/* Allocate buffer for results */
1535 		buf = kmalloc(len, GFP_ATOMIC);
1536 		if (buf == NULL) {
1537 			/* No memory, so can't printk()... */
1538 			qabort_scan(priv);
1539 			break;
1540 		}
1541 
1542 		/* Read scan data */
1543 		err = hw->ops->bap_pread(hw, IRQ_BAP, (void *) buf, len,
1544 					 infofid, sizeof(info));
1545 		if (err) {
1546 			kfree(buf);
1547 			qabort_scan(priv);
1548 			break;
1549 		}
1550 
1551 #ifdef ORINOCO_DEBUG
1552 		{
1553 			int	i;
1554 			printk(KERN_DEBUG "Scan result [%02X", buf[0]);
1555 			for (i = 1; i < (len * 2); i++)
1556 				printk(":%02X", buf[i]);
1557 			printk("]\n");
1558 		}
1559 #endif	/* ORINOCO_DEBUG */
1560 
1561 		qbuf_scan(priv, buf, len, type);
1562 	}
1563 	break;
1564 	case HERMES_INQ_CHANNELINFO:
1565 	{
1566 		struct agere_ext_scan_info *bss;
1567 
1568 		if (!priv->scan_request) {
1569 			printk(KERN_DEBUG "%s: Got chaninfo without scan, "
1570 			       "len=%d\n", dev->name, len);
1571 			break;
1572 		}
1573 
1574 		/* An empty result indicates that the scan is complete */
1575 		if (len == 0) {
1576 			qbuf_scan(priv, NULL, len, type);
1577 			break;
1578 		}
1579 
1580 		/* Sanity check */
1581 		else if (len < (offsetof(struct agere_ext_scan_info,
1582 					   data) + 2)) {
1583 			/* Drop this result now so we don't have to
1584 			 * keep checking later */
1585 			printk(KERN_WARNING
1586 			       "%s: Ext scan results too short (%d bytes)\n",
1587 			       dev->name, len);
1588 			break;
1589 		}
1590 
1591 		bss = kmalloc(len, GFP_ATOMIC);
1592 		if (bss == NULL)
1593 			break;
1594 
1595 		/* Read scan data */
1596 		err = hw->ops->bap_pread(hw, IRQ_BAP, (void *) bss, len,
1597 					 infofid, sizeof(info));
1598 		if (err)
1599 			kfree(bss);
1600 		else
1601 			qbuf_scan(priv, bss, len, type);
1602 
1603 		break;
1604 	}
1605 	case HERMES_INQ_SEC_STAT_AGERE:
1606 		/* Security status (Agere specific) */
1607 		/* Ignore this frame for now */
1608 		if (priv->firmware_type == FIRMWARE_TYPE_AGERE)
1609 			break;
1610 		/* fall through */
1611 	default:
1612 		printk(KERN_DEBUG "%s: Unknown information frame received: "
1613 		       "type 0x%04x, length %d\n", dev->name, type, len);
1614 		/* We don't actually do anything about it */
1615 		break;
1616 	}
1617 }
1618 EXPORT_SYMBOL(__orinoco_ev_info);
1619 
1620 static void __orinoco_ev_infdrop(struct net_device *dev, struct hermes *hw)
1621 {
1622 	if (net_ratelimit())
1623 		printk(KERN_DEBUG "%s: Information frame lost.\n", dev->name);
1624 }
1625 
1626 /********************************************************************/
1627 /* Internal hardware control routines                               */
1628 /********************************************************************/
1629 
1630 static int __orinoco_up(struct orinoco_private *priv)
1631 {
1632 	struct net_device *dev = priv->ndev;
1633 	struct hermes *hw = &priv->hw;
1634 	int err;
1635 
1636 	netif_carrier_off(dev); /* just to make sure */
1637 
1638 	err = __orinoco_commit(priv);
1639 	if (err) {
1640 		printk(KERN_ERR "%s: Error %d configuring card\n",
1641 		       dev->name, err);
1642 		return err;
1643 	}
1644 
1645 	/* Fire things up again */
1646 	hermes_set_irqmask(hw, ORINOCO_INTEN);
1647 	err = hermes_enable_port(hw, 0);
1648 	if (err) {
1649 		printk(KERN_ERR "%s: Error %d enabling MAC port\n",
1650 		       dev->name, err);
1651 		return err;
1652 	}
1653 
1654 	netif_start_queue(dev);
1655 
1656 	return 0;
1657 }
1658 
1659 static int __orinoco_down(struct orinoco_private *priv)
1660 {
1661 	struct net_device *dev = priv->ndev;
1662 	struct hermes *hw = &priv->hw;
1663 	int err;
1664 
1665 	netif_stop_queue(dev);
1666 
1667 	if (!priv->hw_unavailable) {
1668 		if (!priv->broken_disableport) {
1669 			err = hermes_disable_port(hw, 0);
1670 			if (err) {
1671 				/* Some firmwares (e.g. Intersil 1.3.x) seem
1672 				 * to have problems disabling the port, oh
1673 				 * well, too bad. */
1674 				printk(KERN_WARNING "%s: Error %d disabling MAC port\n",
1675 				       dev->name, err);
1676 				priv->broken_disableport = 1;
1677 			}
1678 		}
1679 		hermes_set_irqmask(hw, 0);
1680 		hermes_write_regn(hw, EVACK, 0xffff);
1681 	}
1682 
1683 	orinoco_scan_done(priv, true);
1684 
1685 	/* firmware will have to reassociate */
1686 	netif_carrier_off(dev);
1687 	priv->last_linkstatus = 0xffff;
1688 
1689 	return 0;
1690 }
1691 
1692 static int orinoco_reinit_firmware(struct orinoco_private *priv)
1693 {
1694 	struct hermes *hw = &priv->hw;
1695 	int err;
1696 
1697 	err = hw->ops->init(hw);
1698 	if (priv->do_fw_download && !err) {
1699 		err = orinoco_download(priv);
1700 		if (err)
1701 			priv->do_fw_download = 0;
1702 	}
1703 	if (!err)
1704 		err = orinoco_hw_allocate_fid(priv);
1705 
1706 	return err;
1707 }
1708 
1709 static int
1710 __orinoco_set_multicast_list(struct net_device *dev)
1711 {
1712 	struct orinoco_private *priv = ndev_priv(dev);
1713 	int err = 0;
1714 	int promisc, mc_count;
1715 
1716 	/* The Hermes doesn't seem to have an allmulti mode, so we go
1717 	 * into promiscuous mode and let the upper levels deal. */
1718 	if ((dev->flags & IFF_PROMISC) || (dev->flags & IFF_ALLMULTI) ||
1719 	    (netdev_mc_count(dev) > MAX_MULTICAST(priv))) {
1720 		promisc = 1;
1721 		mc_count = 0;
1722 	} else {
1723 		promisc = 0;
1724 		mc_count = netdev_mc_count(dev);
1725 	}
1726 
1727 	err = __orinoco_hw_set_multicast_list(priv, dev, mc_count, promisc);
1728 
1729 	return err;
1730 }
1731 
1732 /* This must be called from user context, without locks held - use
1733  * schedule_work() */
1734 void orinoco_reset(struct work_struct *work)
1735 {
1736 	struct orinoco_private *priv =
1737 		container_of(work, struct orinoco_private, reset_work);
1738 	struct net_device *dev = priv->ndev;
1739 	struct hermes *hw = &priv->hw;
1740 	int err;
1741 	unsigned long flags;
1742 
1743 	if (orinoco_lock(priv, &flags) != 0)
1744 		/* When the hardware becomes available again, whatever
1745 		 * detects that is responsible for re-initializing
1746 		 * it. So no need for anything further */
1747 		return;
1748 
1749 	netif_stop_queue(dev);
1750 
1751 	/* Shut off interrupts.  Depending on what state the hardware
1752 	 * is in, this might not work, but we'll try anyway */
1753 	hermes_set_irqmask(hw, 0);
1754 	hermes_write_regn(hw, EVACK, 0xffff);
1755 
1756 	priv->hw_unavailable++;
1757 	priv->last_linkstatus = 0xffff; /* firmware will have to reassociate */
1758 	netif_carrier_off(dev);
1759 
1760 	orinoco_unlock(priv, &flags);
1761 
1762 	/* Scanning support: Notify scan cancellation */
1763 	orinoco_scan_done(priv, true);
1764 
1765 	if (priv->hard_reset) {
1766 		err = (*priv->hard_reset)(priv);
1767 		if (err) {
1768 			printk(KERN_ERR "%s: orinoco_reset: Error %d "
1769 			       "performing hard reset\n", dev->name, err);
1770 			goto disable;
1771 		}
1772 	}
1773 
1774 	err = orinoco_reinit_firmware(priv);
1775 	if (err) {
1776 		printk(KERN_ERR "%s: orinoco_reset: Error %d re-initializing firmware\n",
1777 		       dev->name, err);
1778 		goto disable;
1779 	}
1780 
1781 	/* This has to be called from user context */
1782 	orinoco_lock_irq(priv);
1783 
1784 	priv->hw_unavailable--;
1785 
1786 	/* priv->open or priv->hw_unavailable might have changed while
1787 	 * we dropped the lock */
1788 	if (priv->open && (!priv->hw_unavailable)) {
1789 		err = __orinoco_up(priv);
1790 		if (err) {
1791 			printk(KERN_ERR "%s: orinoco_reset: Error %d reenabling card\n",
1792 			       dev->name, err);
1793 		} else
1794 			netif_trans_update(dev);
1795 	}
1796 
1797 	orinoco_unlock_irq(priv);
1798 
1799 	return;
1800  disable:
1801 	hermes_set_irqmask(hw, 0);
1802 	netif_device_detach(dev);
1803 	printk(KERN_ERR "%s: Device has been disabled!\n", dev->name);
1804 }
1805 
1806 static int __orinoco_commit(struct orinoco_private *priv)
1807 {
1808 	struct net_device *dev = priv->ndev;
1809 	int err = 0;
1810 
1811 	/* If we've called commit, we are reconfiguring or bringing the
1812 	 * interface up. Maintaining countermeasures across this would
1813 	 * be confusing, so note that we've disabled them. The port will
1814 	 * be enabled later in orinoco_commit or __orinoco_up. */
1815 	priv->tkip_cm_active = 0;
1816 
1817 	err = orinoco_hw_program_rids(priv);
1818 
1819 	/* FIXME: what about netif_tx_lock */
1820 	(void) __orinoco_set_multicast_list(dev);
1821 
1822 	return err;
1823 }
1824 
1825 /* Ensures configuration changes are applied. May result in a reset.
1826  * The caller should hold priv->lock
1827  */
1828 int orinoco_commit(struct orinoco_private *priv)
1829 {
1830 	struct net_device *dev = priv->ndev;
1831 	struct hermes *hw = &priv->hw;
1832 	int err;
1833 
1834 	if (priv->broken_disableport) {
1835 		schedule_work(&priv->reset_work);
1836 		return 0;
1837 	}
1838 
1839 	err = hermes_disable_port(hw, 0);
1840 	if (err) {
1841 		printk(KERN_WARNING "%s: Unable to disable port "
1842 		       "while reconfiguring card\n", dev->name);
1843 		priv->broken_disableport = 1;
1844 		goto out;
1845 	}
1846 
1847 	err = __orinoco_commit(priv);
1848 	if (err) {
1849 		printk(KERN_WARNING "%s: Unable to reconfigure card\n",
1850 		       dev->name);
1851 		goto out;
1852 	}
1853 
1854 	err = hermes_enable_port(hw, 0);
1855 	if (err) {
1856 		printk(KERN_WARNING "%s: Unable to enable port while reconfiguring card\n",
1857 		       dev->name);
1858 		goto out;
1859 	}
1860 
1861  out:
1862 	if (err) {
1863 		printk(KERN_WARNING "%s: Resetting instead...\n", dev->name);
1864 		schedule_work(&priv->reset_work);
1865 		err = 0;
1866 	}
1867 	return err;
1868 }
1869 
1870 /********************************************************************/
1871 /* Interrupt handler                                                */
1872 /********************************************************************/
1873 
1874 static void __orinoco_ev_tick(struct net_device *dev, struct hermes *hw)
1875 {
1876 	printk(KERN_DEBUG "%s: TICK\n", dev->name);
1877 }
1878 
1879 static void __orinoco_ev_wterr(struct net_device *dev, struct hermes *hw)
1880 {
1881 	/* This seems to happen a fair bit under load, but ignoring it
1882 	   seems to work fine...*/
1883 	printk(KERN_DEBUG "%s: MAC controller error (WTERR). Ignoring.\n",
1884 	       dev->name);
1885 }
1886 
1887 irqreturn_t orinoco_interrupt(int irq, void *dev_id)
1888 {
1889 	struct orinoco_private *priv = dev_id;
1890 	struct net_device *dev = priv->ndev;
1891 	struct hermes *hw = &priv->hw;
1892 	int count = MAX_IRQLOOPS_PER_IRQ;
1893 	u16 evstat, events;
1894 	/* These are used to detect a runaway interrupt situation.
1895 	 *
1896 	 * If we get more than MAX_IRQLOOPS_PER_JIFFY iterations in a jiffy,
1897 	 * we panic and shut down the hardware
1898 	 */
1899 	/* jiffies value the last time we were called */
1900 	static int last_irq_jiffy; /* = 0 */
1901 	static int loops_this_jiffy; /* = 0 */
1902 	unsigned long flags;
1903 
1904 	if (orinoco_lock(priv, &flags) != 0) {
1905 		/* If hw is unavailable - we don't know if the irq was
1906 		 * for us or not */
1907 		return IRQ_HANDLED;
1908 	}
1909 
1910 	evstat = hermes_read_regn(hw, EVSTAT);
1911 	events = evstat & hw->inten;
1912 	if (!events) {
1913 		orinoco_unlock(priv, &flags);
1914 		return IRQ_NONE;
1915 	}
1916 
1917 	if (jiffies != last_irq_jiffy)
1918 		loops_this_jiffy = 0;
1919 	last_irq_jiffy = jiffies;
1920 
1921 	while (events && count--) {
1922 		if (++loops_this_jiffy > MAX_IRQLOOPS_PER_JIFFY) {
1923 			printk(KERN_WARNING "%s: IRQ handler is looping too "
1924 			       "much! Resetting.\n", dev->name);
1925 			/* Disable interrupts for now */
1926 			hermes_set_irqmask(hw, 0);
1927 			schedule_work(&priv->reset_work);
1928 			break;
1929 		}
1930 
1931 		/* Check the card hasn't been removed */
1932 		if (!hermes_present(hw)) {
1933 			DEBUG(0, "orinoco_interrupt(): card removed\n");
1934 			break;
1935 		}
1936 
1937 		if (events & HERMES_EV_TICK)
1938 			__orinoco_ev_tick(dev, hw);
1939 		if (events & HERMES_EV_WTERR)
1940 			__orinoco_ev_wterr(dev, hw);
1941 		if (events & HERMES_EV_INFDROP)
1942 			__orinoco_ev_infdrop(dev, hw);
1943 		if (events & HERMES_EV_INFO)
1944 			__orinoco_ev_info(dev, hw);
1945 		if (events & HERMES_EV_RX)
1946 			__orinoco_ev_rx(dev, hw);
1947 		if (events & HERMES_EV_TXEXC)
1948 			__orinoco_ev_txexc(dev, hw);
1949 		if (events & HERMES_EV_TX)
1950 			__orinoco_ev_tx(dev, hw);
1951 		if (events & HERMES_EV_ALLOC)
1952 			__orinoco_ev_alloc(dev, hw);
1953 
1954 		hermes_write_regn(hw, EVACK, evstat);
1955 
1956 		evstat = hermes_read_regn(hw, EVSTAT);
1957 		events = evstat & hw->inten;
1958 	}
1959 
1960 	orinoco_unlock(priv, &flags);
1961 	return IRQ_HANDLED;
1962 }
1963 EXPORT_SYMBOL(orinoco_interrupt);
1964 
1965 /********************************************************************/
1966 /* Power management                                                 */
1967 /********************************************************************/
1968 #if defined(CONFIG_PM_SLEEP) && !defined(CONFIG_HERMES_CACHE_FW_ON_INIT)
1969 static int orinoco_pm_notifier(struct notifier_block *notifier,
1970 			       unsigned long pm_event,
1971 			       void *unused)
1972 {
1973 	struct orinoco_private *priv = container_of(notifier,
1974 						    struct orinoco_private,
1975 						    pm_notifier);
1976 
1977 	/* All we need to do is cache the firmware before suspend, and
1978 	 * release it when we come out.
1979 	 *
1980 	 * Only need to do this if we're downloading firmware. */
1981 	if (!priv->do_fw_download)
1982 		return NOTIFY_DONE;
1983 
1984 	switch (pm_event) {
1985 	case PM_HIBERNATION_PREPARE:
1986 	case PM_SUSPEND_PREPARE:
1987 		orinoco_cache_fw(priv, 0);
1988 		break;
1989 
1990 	case PM_POST_RESTORE:
1991 		/* Restore from hibernation failed. We need to clean
1992 		 * up in exactly the same way, so fall through. */
1993 	case PM_POST_HIBERNATION:
1994 	case PM_POST_SUSPEND:
1995 		orinoco_uncache_fw(priv);
1996 		break;
1997 
1998 	case PM_RESTORE_PREPARE:
1999 	default:
2000 		break;
2001 	}
2002 
2003 	return NOTIFY_DONE;
2004 }
2005 
2006 static void orinoco_register_pm_notifier(struct orinoco_private *priv)
2007 {
2008 	priv->pm_notifier.notifier_call = orinoco_pm_notifier;
2009 	register_pm_notifier(&priv->pm_notifier);
2010 }
2011 
2012 static void orinoco_unregister_pm_notifier(struct orinoco_private *priv)
2013 {
2014 	unregister_pm_notifier(&priv->pm_notifier);
2015 }
2016 #else /* !PM_SLEEP || HERMES_CACHE_FW_ON_INIT */
2017 #define orinoco_register_pm_notifier(priv) do { } while (0)
2018 #define orinoco_unregister_pm_notifier(priv) do { } while (0)
2019 #endif
2020 
2021 /********************************************************************/
2022 /* Initialization                                                   */
2023 /********************************************************************/
2024 
2025 int orinoco_init(struct orinoco_private *priv)
2026 {
2027 	struct device *dev = priv->dev;
2028 	struct wiphy *wiphy = priv_to_wiphy(priv);
2029 	struct hermes *hw = &priv->hw;
2030 	int err = 0;
2031 
2032 	/* No need to lock, the hw_unavailable flag is already set in
2033 	 * alloc_orinocodev() */
2034 	priv->nicbuf_size = IEEE80211_MAX_FRAME_LEN + ETH_HLEN;
2035 
2036 	/* Initialize the firmware */
2037 	err = hw->ops->init(hw);
2038 	if (err != 0) {
2039 		dev_err(dev, "Failed to initialize firmware (err = %d)\n",
2040 			err);
2041 		goto out;
2042 	}
2043 
2044 	err = determine_fw_capabilities(priv, wiphy->fw_version,
2045 					sizeof(wiphy->fw_version),
2046 					&wiphy->hw_version);
2047 	if (err != 0) {
2048 		dev_err(dev, "Incompatible firmware, aborting\n");
2049 		goto out;
2050 	}
2051 
2052 	if (priv->do_fw_download) {
2053 #ifdef CONFIG_HERMES_CACHE_FW_ON_INIT
2054 		orinoco_cache_fw(priv, 0);
2055 #endif
2056 
2057 		err = orinoco_download(priv);
2058 		if (err)
2059 			priv->do_fw_download = 0;
2060 
2061 		/* Check firmware version again */
2062 		err = determine_fw_capabilities(priv, wiphy->fw_version,
2063 						sizeof(wiphy->fw_version),
2064 						&wiphy->hw_version);
2065 		if (err != 0) {
2066 			dev_err(dev, "Incompatible firmware, aborting\n");
2067 			goto out;
2068 		}
2069 	}
2070 
2071 	if (priv->has_port3)
2072 		dev_info(dev, "Ad-hoc demo mode supported\n");
2073 	if (priv->has_ibss)
2074 		dev_info(dev, "IEEE standard IBSS ad-hoc mode supported\n");
2075 	if (priv->has_wep)
2076 		dev_info(dev, "WEP supported, %s-bit key\n",
2077 			 priv->has_big_wep ? "104" : "40");
2078 	if (priv->has_wpa) {
2079 		dev_info(dev, "WPA-PSK supported\n");
2080 		if (orinoco_mic_init(priv)) {
2081 			dev_err(dev, "Failed to setup MIC crypto algorithm. "
2082 				"Disabling WPA support\n");
2083 			priv->has_wpa = 0;
2084 		}
2085 	}
2086 
2087 	err = orinoco_hw_read_card_settings(priv, wiphy->perm_addr);
2088 	if (err)
2089 		goto out;
2090 
2091 	err = orinoco_hw_allocate_fid(priv);
2092 	if (err) {
2093 		dev_err(dev, "Failed to allocate NIC buffer!\n");
2094 		goto out;
2095 	}
2096 
2097 	/* Set up the default configuration */
2098 	priv->iw_mode = NL80211_IFTYPE_STATION;
2099 	/* By default use IEEE/IBSS ad-hoc mode if we have it */
2100 	priv->prefer_port3 = priv->has_port3 && (!priv->has_ibss);
2101 	set_port_type(priv);
2102 	priv->channel = 0; /* use firmware default */
2103 
2104 	priv->promiscuous = 0;
2105 	priv->encode_alg = ORINOCO_ALG_NONE;
2106 	priv->tx_key = 0;
2107 	priv->wpa_enabled = 0;
2108 	priv->tkip_cm_active = 0;
2109 	priv->key_mgmt = 0;
2110 	priv->wpa_ie_len = 0;
2111 	priv->wpa_ie = NULL;
2112 
2113 	if (orinoco_wiphy_register(wiphy)) {
2114 		err = -ENODEV;
2115 		goto out;
2116 	}
2117 
2118 	/* Make the hardware available, as long as it hasn't been
2119 	 * removed elsewhere (e.g. by PCMCIA hot unplug) */
2120 	orinoco_lock_irq(priv);
2121 	priv->hw_unavailable--;
2122 	orinoco_unlock_irq(priv);
2123 
2124 	dev_dbg(dev, "Ready\n");
2125 
2126  out:
2127 	return err;
2128 }
2129 EXPORT_SYMBOL(orinoco_init);
2130 
2131 static const struct net_device_ops orinoco_netdev_ops = {
2132 	.ndo_open		= orinoco_open,
2133 	.ndo_stop		= orinoco_stop,
2134 	.ndo_start_xmit		= orinoco_xmit,
2135 	.ndo_set_rx_mode	= orinoco_set_multicast_list,
2136 	.ndo_change_mtu		= orinoco_change_mtu,
2137 	.ndo_set_mac_address	= eth_mac_addr,
2138 	.ndo_validate_addr	= eth_validate_addr,
2139 	.ndo_tx_timeout		= orinoco_tx_timeout,
2140 	.ndo_get_stats		= orinoco_get_stats,
2141 };
2142 
2143 /* Allocate private data.
2144  *
2145  * This driver has a number of structures associated with it
2146  *  netdev - Net device structure for each network interface
2147  *  wiphy - structure associated with wireless phy
2148  *  wireless_dev (wdev) - structure for each wireless interface
2149  *  hw - structure for hermes chip info
2150  *  card - card specific structure for use by the card driver
2151  *         (airport, orinoco_cs)
2152  *  priv - orinoco private data
2153  *  device - generic linux device structure
2154  *
2155  *  +---------+    +---------+
2156  *  |  wiphy  |    | netdev  |
2157  *  | +-------+    | +-------+
2158  *  | | priv  |    | | wdev  |
2159  *  | | +-----+    +-+-------+
2160  *  | | | hw  |
2161  *  | +-+-----+
2162  *  | | card  |
2163  *  +-+-------+
2164  *
2165  * priv has a link to netdev and device
2166  * wdev has a link to wiphy
2167  */
2168 struct orinoco_private
2169 *alloc_orinocodev(int sizeof_card,
2170 		  struct device *device,
2171 		  int (*hard_reset)(struct orinoco_private *),
2172 		  int (*stop_fw)(struct orinoco_private *, int))
2173 {
2174 	struct orinoco_private *priv;
2175 	struct wiphy *wiphy;
2176 
2177 	/* allocate wiphy
2178 	 * NOTE: We only support a single virtual interface
2179 	 *       but this may change when monitor mode is added
2180 	 */
2181 	wiphy = wiphy_new(&orinoco_cfg_ops,
2182 			  sizeof(struct orinoco_private) + sizeof_card);
2183 	if (!wiphy)
2184 		return NULL;
2185 
2186 	priv = wiphy_priv(wiphy);
2187 	priv->dev = device;
2188 
2189 	if (sizeof_card)
2190 		priv->card = (void *)((unsigned long)priv
2191 				      + sizeof(struct orinoco_private));
2192 	else
2193 		priv->card = NULL;
2194 
2195 	orinoco_wiphy_init(wiphy);
2196 
2197 #ifdef WIRELESS_SPY
2198 	priv->wireless_data.spy_data = &priv->spy_data;
2199 #endif
2200 
2201 	/* Set up default callbacks */
2202 	priv->hard_reset = hard_reset;
2203 	priv->stop_fw = stop_fw;
2204 
2205 	spin_lock_init(&priv->lock);
2206 	priv->open = 0;
2207 	priv->hw_unavailable = 1; /* orinoco_init() must clear this
2208 				   * before anything else touches the
2209 				   * hardware */
2210 	INIT_WORK(&priv->reset_work, orinoco_reset);
2211 	INIT_WORK(&priv->join_work, orinoco_join_ap);
2212 	INIT_WORK(&priv->wevent_work, orinoco_send_wevents);
2213 
2214 	INIT_LIST_HEAD(&priv->rx_list);
2215 	tasklet_init(&priv->rx_tasklet, orinoco_rx_isr_tasklet,
2216 		     (unsigned long) priv);
2217 
2218 	spin_lock_init(&priv->scan_lock);
2219 	INIT_LIST_HEAD(&priv->scan_list);
2220 	INIT_WORK(&priv->process_scan, orinoco_process_scan_results);
2221 
2222 	priv->last_linkstatus = 0xffff;
2223 
2224 #if defined(CONFIG_HERMES_CACHE_FW_ON_INIT) || defined(CONFIG_PM_SLEEP)
2225 	priv->cached_pri_fw = NULL;
2226 	priv->cached_fw = NULL;
2227 #endif
2228 
2229 	/* Register PM notifiers */
2230 	orinoco_register_pm_notifier(priv);
2231 
2232 	return priv;
2233 }
2234 EXPORT_SYMBOL(alloc_orinocodev);
2235 
2236 /* We can only support a single interface. We provide a separate
2237  * function to set it up to distinguish between hardware
2238  * initialisation and interface setup.
2239  *
2240  * The base_addr and irq parameters are passed on to netdev for use
2241  * with SIOCGIFMAP.
2242  */
2243 int orinoco_if_add(struct orinoco_private *priv,
2244 		   unsigned long base_addr,
2245 		   unsigned int irq,
2246 		   const struct net_device_ops *ops)
2247 {
2248 	struct wiphy *wiphy = priv_to_wiphy(priv);
2249 	struct wireless_dev *wdev;
2250 	struct net_device *dev;
2251 	int ret;
2252 
2253 	dev = alloc_etherdev(sizeof(struct wireless_dev));
2254 
2255 	if (!dev)
2256 		return -ENOMEM;
2257 
2258 	/* Initialise wireless_dev */
2259 	wdev = netdev_priv(dev);
2260 	wdev->wiphy = wiphy;
2261 	wdev->iftype = NL80211_IFTYPE_STATION;
2262 
2263 	/* Setup / override net_device fields */
2264 	dev->ieee80211_ptr = wdev;
2265 	dev->watchdog_timeo = HZ; /* 1 second timeout */
2266 	dev->wireless_handlers = &orinoco_handler_def;
2267 #ifdef WIRELESS_SPY
2268 	dev->wireless_data = &priv->wireless_data;
2269 #endif
2270 	/* Default to standard ops if not set */
2271 	if (ops)
2272 		dev->netdev_ops = ops;
2273 	else
2274 		dev->netdev_ops = &orinoco_netdev_ops;
2275 
2276 	/* we use the default eth_mac_addr for setting the MAC addr */
2277 
2278 	/* Reserve space in skb for the SNAP header */
2279 	dev->needed_headroom = ENCAPS_OVERHEAD;
2280 
2281 	netif_carrier_off(dev);
2282 
2283 	memcpy(dev->dev_addr, wiphy->perm_addr, ETH_ALEN);
2284 
2285 	dev->base_addr = base_addr;
2286 	dev->irq = irq;
2287 
2288 	dev->min_mtu = ORINOCO_MIN_MTU;
2289 	dev->max_mtu = ORINOCO_MAX_MTU;
2290 
2291 	SET_NETDEV_DEV(dev, priv->dev);
2292 	ret = register_netdev(dev);
2293 	if (ret)
2294 		goto fail;
2295 
2296 	priv->ndev = dev;
2297 
2298 	/* Report what we've done */
2299 	dev_dbg(priv->dev, "Registerred interface %s.\n", dev->name);
2300 
2301 	return 0;
2302 
2303  fail:
2304 	free_netdev(dev);
2305 	return ret;
2306 }
2307 EXPORT_SYMBOL(orinoco_if_add);
2308 
2309 void orinoco_if_del(struct orinoco_private *priv)
2310 {
2311 	struct net_device *dev = priv->ndev;
2312 
2313 	unregister_netdev(dev);
2314 	free_netdev(dev);
2315 }
2316 EXPORT_SYMBOL(orinoco_if_del);
2317 
2318 void free_orinocodev(struct orinoco_private *priv)
2319 {
2320 	struct wiphy *wiphy = priv_to_wiphy(priv);
2321 	struct orinoco_rx_data *rx_data, *temp;
2322 	struct orinoco_scan_data *sd, *sdtemp;
2323 
2324 	/* If the tasklet is scheduled when we call tasklet_kill it
2325 	 * will run one final time. However the tasklet will only
2326 	 * drain priv->rx_list if the hw is still available. */
2327 	tasklet_kill(&priv->rx_tasklet);
2328 
2329 	/* Explicitly drain priv->rx_list */
2330 	list_for_each_entry_safe(rx_data, temp, &priv->rx_list, list) {
2331 		list_del(&rx_data->list);
2332 
2333 		dev_kfree_skb(rx_data->skb);
2334 		kfree(rx_data->desc);
2335 		kfree(rx_data);
2336 	}
2337 
2338 	cancel_work_sync(&priv->process_scan);
2339 	/* Explicitly drain priv->scan_list */
2340 	list_for_each_entry_safe(sd, sdtemp, &priv->scan_list, list) {
2341 		list_del(&sd->list);
2342 
2343 		if (sd->len > 0)
2344 			kfree(sd->buf);
2345 		kfree(sd);
2346 	}
2347 
2348 	orinoco_unregister_pm_notifier(priv);
2349 	orinoco_uncache_fw(priv);
2350 
2351 	priv->wpa_ie_len = 0;
2352 	kfree(priv->wpa_ie);
2353 	orinoco_mic_free(priv);
2354 	wiphy_free(wiphy);
2355 }
2356 EXPORT_SYMBOL(free_orinocodev);
2357 
2358 int orinoco_up(struct orinoco_private *priv)
2359 {
2360 	struct net_device *dev = priv->ndev;
2361 	unsigned long flags;
2362 	int err;
2363 
2364 	priv->hw.ops->lock_irqsave(&priv->lock, &flags);
2365 
2366 	err = orinoco_reinit_firmware(priv);
2367 	if (err) {
2368 		printk(KERN_ERR "%s: Error %d re-initializing firmware\n",
2369 		       dev->name, err);
2370 		goto exit;
2371 	}
2372 
2373 	netif_device_attach(dev);
2374 	priv->hw_unavailable--;
2375 
2376 	if (priv->open && !priv->hw_unavailable) {
2377 		err = __orinoco_up(priv);
2378 		if (err)
2379 			printk(KERN_ERR "%s: Error %d restarting card\n",
2380 			       dev->name, err);
2381 	}
2382 
2383 exit:
2384 	priv->hw.ops->unlock_irqrestore(&priv->lock, &flags);
2385 
2386 	return 0;
2387 }
2388 EXPORT_SYMBOL(orinoco_up);
2389 
2390 void orinoco_down(struct orinoco_private *priv)
2391 {
2392 	struct net_device *dev = priv->ndev;
2393 	unsigned long flags;
2394 	int err;
2395 
2396 	priv->hw.ops->lock_irqsave(&priv->lock, &flags);
2397 	err = __orinoco_down(priv);
2398 	if (err)
2399 		printk(KERN_WARNING "%s: Error %d downing interface\n",
2400 		       dev->name, err);
2401 
2402 	netif_device_detach(dev);
2403 	priv->hw_unavailable++;
2404 	priv->hw.ops->unlock_irqrestore(&priv->lock, &flags);
2405 }
2406 EXPORT_SYMBOL(orinoco_down);
2407 
2408 /********************************************************************/
2409 /* Module initialization                                            */
2410 /********************************************************************/
2411 
2412 /* Can't be declared "const" or the whole __initdata section will
2413  * become const */
2414 static char version[] __initdata = DRIVER_NAME " " DRIVER_VERSION
2415 	" (David Gibson <hermes@gibson.dropbear.id.au>, "
2416 	"Pavel Roskin <proski@gnu.org>, et al)";
2417 
2418 static int __init init_orinoco(void)
2419 {
2420 	printk(KERN_DEBUG "%s\n", version);
2421 	return 0;
2422 }
2423 
2424 static void __exit exit_orinoco(void)
2425 {
2426 }
2427 
2428 module_init(init_orinoco);
2429 module_exit(exit_orinoco);
2430