• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/linux/linux-2.6/drivers/net/wireless/ipw2x00/
1/******************************************************************************
2
3  Copyright(c) 2003 - 2006 Intel Corporation. All rights reserved.
4
5  802.11 status code portion of this file from ethereal-0.10.6:
6    Copyright 2000, Axis Communications AB
7    Ethereal - Network traffic analyzer
8    By Gerald Combs <gerald@ethereal.com>
9    Copyright 1998 Gerald Combs
10
11  This program is free software; you can redistribute it and/or modify it
12  under the terms of version 2 of the GNU General Public License as
13  published by the Free Software Foundation.
14
15  This program is distributed in the hope that it will be useful, but WITHOUT
16  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
18  more details.
19
20  You should have received a copy of the GNU General Public License along with
21  this program; if not, write to the Free Software Foundation, Inc., 59
22  Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23
24  The full GNU General Public License is included in this distribution in the
25  file called LICENSE.
26
27  Contact Information:
28  Intel Linux Wireless <ilw@linux.intel.com>
29  Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
30
31******************************************************************************/
32
33#include <linux/sched.h>
34#include <linux/slab.h>
35#include "ipw2200.h"
36
37
38#ifndef KBUILD_EXTMOD
39#define VK "k"
40#else
41#define VK
42#endif
43
44#ifdef CONFIG_IPW2200_DEBUG
45#define VD "d"
46#else
47#define VD
48#endif
49
50#ifdef CONFIG_IPW2200_MONITOR
51#define VM "m"
52#else
53#define VM
54#endif
55
56#ifdef CONFIG_IPW2200_PROMISCUOUS
57#define VP "p"
58#else
59#define VP
60#endif
61
62#ifdef CONFIG_IPW2200_RADIOTAP
63#define VR "r"
64#else
65#define VR
66#endif
67
68#ifdef CONFIG_IPW2200_QOS
69#define VQ "q"
70#else
71#define VQ
72#endif
73
74#define IPW2200_VERSION "1.2.2" VK VD VM VP VR VQ
75#define DRV_DESCRIPTION	"Intel(R) PRO/Wireless 2200/2915 Network Driver"
76#define DRV_COPYRIGHT	"Copyright(c) 2003-2006 Intel Corporation"
77#define DRV_VERSION     IPW2200_VERSION
78
79#define ETH_P_80211_STATS (ETH_P_80211_RAW + 1)
80
81MODULE_DESCRIPTION(DRV_DESCRIPTION);
82MODULE_VERSION(DRV_VERSION);
83MODULE_AUTHOR(DRV_COPYRIGHT);
84MODULE_LICENSE("GPL");
85MODULE_FIRMWARE("ipw2200-ibss.fw");
86#ifdef CONFIG_IPW2200_MONITOR
87MODULE_FIRMWARE("ipw2200-sniffer.fw");
88#endif
89MODULE_FIRMWARE("ipw2200-bss.fw");
90
91static int cmdlog = 0;
92static int debug = 0;
93static int default_channel = 0;
94static int network_mode = 0;
95
96static u32 ipw_debug_level;
97static int associate;
98static int auto_create = 1;
99static int led_support = 1;
100static int disable = 0;
101static int bt_coexist = 0;
102static int hwcrypto = 0;
103static int roaming = 1;
104static const char ipw_modes[] = {
105	'a', 'b', 'g', '?'
106};
107static int antenna = CFG_SYS_ANTENNA_BOTH;
108
109#ifdef CONFIG_IPW2200_PROMISCUOUS
110static int rtap_iface = 0;     /* def: 0 -- do not create rtap interface */
111#endif
112
113static struct ieee80211_rate ipw2200_rates[] = {
114	{ .bitrate = 10 },
115	{ .bitrate = 20, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
116	{ .bitrate = 55, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
117	{ .bitrate = 110, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
118	{ .bitrate = 60 },
119	{ .bitrate = 90 },
120	{ .bitrate = 120 },
121	{ .bitrate = 180 },
122	{ .bitrate = 240 },
123	{ .bitrate = 360 },
124	{ .bitrate = 480 },
125	{ .bitrate = 540 }
126};
127
128#define ipw2200_a_rates		(ipw2200_rates + 4)
129#define ipw2200_num_a_rates	8
130#define ipw2200_bg_rates	(ipw2200_rates + 0)
131#define ipw2200_num_bg_rates	12
132
133#ifdef CONFIG_IPW2200_QOS
134static int qos_enable = 0;
135static int qos_burst_enable = 0;
136static int qos_no_ack_mask = 0;
137static int burst_duration_CCK = 0;
138static int burst_duration_OFDM = 0;
139
140static struct libipw_qos_parameters def_qos_parameters_OFDM = {
141	{QOS_TX0_CW_MIN_OFDM, QOS_TX1_CW_MIN_OFDM, QOS_TX2_CW_MIN_OFDM,
142	 QOS_TX3_CW_MIN_OFDM},
143	{QOS_TX0_CW_MAX_OFDM, QOS_TX1_CW_MAX_OFDM, QOS_TX2_CW_MAX_OFDM,
144	 QOS_TX3_CW_MAX_OFDM},
145	{QOS_TX0_AIFS, QOS_TX1_AIFS, QOS_TX2_AIFS, QOS_TX3_AIFS},
146	{QOS_TX0_ACM, QOS_TX1_ACM, QOS_TX2_ACM, QOS_TX3_ACM},
147	{QOS_TX0_TXOP_LIMIT_OFDM, QOS_TX1_TXOP_LIMIT_OFDM,
148	 QOS_TX2_TXOP_LIMIT_OFDM, QOS_TX3_TXOP_LIMIT_OFDM}
149};
150
151static struct libipw_qos_parameters def_qos_parameters_CCK = {
152	{QOS_TX0_CW_MIN_CCK, QOS_TX1_CW_MIN_CCK, QOS_TX2_CW_MIN_CCK,
153	 QOS_TX3_CW_MIN_CCK},
154	{QOS_TX0_CW_MAX_CCK, QOS_TX1_CW_MAX_CCK, QOS_TX2_CW_MAX_CCK,
155	 QOS_TX3_CW_MAX_CCK},
156	{QOS_TX0_AIFS, QOS_TX1_AIFS, QOS_TX2_AIFS, QOS_TX3_AIFS},
157	{QOS_TX0_ACM, QOS_TX1_ACM, QOS_TX2_ACM, QOS_TX3_ACM},
158	{QOS_TX0_TXOP_LIMIT_CCK, QOS_TX1_TXOP_LIMIT_CCK, QOS_TX2_TXOP_LIMIT_CCK,
159	 QOS_TX3_TXOP_LIMIT_CCK}
160};
161
162static struct libipw_qos_parameters def_parameters_OFDM = {
163	{DEF_TX0_CW_MIN_OFDM, DEF_TX1_CW_MIN_OFDM, DEF_TX2_CW_MIN_OFDM,
164	 DEF_TX3_CW_MIN_OFDM},
165	{DEF_TX0_CW_MAX_OFDM, DEF_TX1_CW_MAX_OFDM, DEF_TX2_CW_MAX_OFDM,
166	 DEF_TX3_CW_MAX_OFDM},
167	{DEF_TX0_AIFS, DEF_TX1_AIFS, DEF_TX2_AIFS, DEF_TX3_AIFS},
168	{DEF_TX0_ACM, DEF_TX1_ACM, DEF_TX2_ACM, DEF_TX3_ACM},
169	{DEF_TX0_TXOP_LIMIT_OFDM, DEF_TX1_TXOP_LIMIT_OFDM,
170	 DEF_TX2_TXOP_LIMIT_OFDM, DEF_TX3_TXOP_LIMIT_OFDM}
171};
172
173static struct libipw_qos_parameters def_parameters_CCK = {
174	{DEF_TX0_CW_MIN_CCK, DEF_TX1_CW_MIN_CCK, DEF_TX2_CW_MIN_CCK,
175	 DEF_TX3_CW_MIN_CCK},
176	{DEF_TX0_CW_MAX_CCK, DEF_TX1_CW_MAX_CCK, DEF_TX2_CW_MAX_CCK,
177	 DEF_TX3_CW_MAX_CCK},
178	{DEF_TX0_AIFS, DEF_TX1_AIFS, DEF_TX2_AIFS, DEF_TX3_AIFS},
179	{DEF_TX0_ACM, DEF_TX1_ACM, DEF_TX2_ACM, DEF_TX3_ACM},
180	{DEF_TX0_TXOP_LIMIT_CCK, DEF_TX1_TXOP_LIMIT_CCK, DEF_TX2_TXOP_LIMIT_CCK,
181	 DEF_TX3_TXOP_LIMIT_CCK}
182};
183
184static u8 qos_oui[QOS_OUI_LEN] = { 0x00, 0x50, 0xF2 };
185
186static int from_priority_to_tx_queue[] = {
187	IPW_TX_QUEUE_1, IPW_TX_QUEUE_2, IPW_TX_QUEUE_2, IPW_TX_QUEUE_1,
188	IPW_TX_QUEUE_3, IPW_TX_QUEUE_3, IPW_TX_QUEUE_4, IPW_TX_QUEUE_4
189};
190
191static u32 ipw_qos_get_burst_duration(struct ipw_priv *priv);
192
193static int ipw_send_qos_params_command(struct ipw_priv *priv, struct libipw_qos_parameters
194				       *qos_param);
195static int ipw_send_qos_info_command(struct ipw_priv *priv, struct libipw_qos_information_element
196				     *qos_param);
197#endif				/* CONFIG_IPW2200_QOS */
198
199static struct iw_statistics *ipw_get_wireless_stats(struct net_device *dev);
200static void ipw_remove_current_network(struct ipw_priv *priv);
201static void ipw_rx(struct ipw_priv *priv);
202static int ipw_queue_tx_reclaim(struct ipw_priv *priv,
203				struct clx2_tx_queue *txq, int qindex);
204static int ipw_queue_reset(struct ipw_priv *priv);
205
206static int ipw_queue_tx_hcmd(struct ipw_priv *priv, int hcmd, void *buf,
207			     int len, int sync);
208
209static void ipw_tx_queue_free(struct ipw_priv *);
210
211static struct ipw_rx_queue *ipw_rx_queue_alloc(struct ipw_priv *);
212static void ipw_rx_queue_free(struct ipw_priv *, struct ipw_rx_queue *);
213static void ipw_rx_queue_replenish(void *);
214static int ipw_up(struct ipw_priv *);
215static void ipw_bg_up(struct work_struct *work);
216static void ipw_down(struct ipw_priv *);
217static void ipw_bg_down(struct work_struct *work);
218static int ipw_config(struct ipw_priv *);
219static int init_supported_rates(struct ipw_priv *priv,
220				struct ipw_supported_rates *prates);
221static void ipw_set_hwcrypto_keys(struct ipw_priv *);
222static void ipw_send_wep_keys(struct ipw_priv *, int);
223
224static int snprint_line(char *buf, size_t count,
225			const u8 * data, u32 len, u32 ofs)
226{
227	int out, i, j, l;
228	char c;
229
230	out = snprintf(buf, count, "%08X", ofs);
231
232	for (l = 0, i = 0; i < 2; i++) {
233		out += snprintf(buf + out, count - out, " ");
234		for (j = 0; j < 8 && l < len; j++, l++)
235			out += snprintf(buf + out, count - out, "%02X ",
236					data[(i * 8 + j)]);
237		for (; j < 8; j++)
238			out += snprintf(buf + out, count - out, "   ");
239	}
240
241	out += snprintf(buf + out, count - out, " ");
242	for (l = 0, i = 0; i < 2; i++) {
243		out += snprintf(buf + out, count - out, " ");
244		for (j = 0; j < 8 && l < len; j++, l++) {
245			c = data[(i * 8 + j)];
246			if (!isascii(c) || !isprint(c))
247				c = '.';
248
249			out += snprintf(buf + out, count - out, "%c", c);
250		}
251
252		for (; j < 8; j++)
253			out += snprintf(buf + out, count - out, " ");
254	}
255
256	return out;
257}
258
259static void printk_buf(int level, const u8 * data, u32 len)
260{
261	char line[81];
262	u32 ofs = 0;
263	if (!(ipw_debug_level & level))
264		return;
265
266	while (len) {
267		snprint_line(line, sizeof(line), &data[ofs],
268			     min(len, 16U), ofs);
269		printk(KERN_DEBUG "%s\n", line);
270		ofs += 16;
271		len -= min(len, 16U);
272	}
273}
274
275static int snprintk_buf(u8 * output, size_t size, const u8 * data, size_t len)
276{
277	size_t out = size;
278	u32 ofs = 0;
279	int total = 0;
280
281	while (size && len) {
282		out = snprint_line(output, size, &data[ofs],
283				   min_t(size_t, len, 16U), ofs);
284
285		ofs += 16;
286		output += out;
287		size -= out;
288		len -= min_t(size_t, len, 16U);
289		total += out;
290	}
291	return total;
292}
293
294/* alias for 32-bit indirect read (for SRAM/reg above 4K), with debug wrapper */
295static u32 _ipw_read_reg32(struct ipw_priv *priv, u32 reg);
296#define ipw_read_reg32(a, b) _ipw_read_reg32(a, b)
297
298/* alias for 8-bit indirect read (for SRAM/reg above 4K), with debug wrapper */
299static u8 _ipw_read_reg8(struct ipw_priv *ipw, u32 reg);
300#define ipw_read_reg8(a, b) _ipw_read_reg8(a, b)
301
302/* 8-bit indirect write (for SRAM/reg above 4K), with debug wrapper */
303static void _ipw_write_reg8(struct ipw_priv *priv, u32 reg, u8 value);
304static inline void ipw_write_reg8(struct ipw_priv *a, u32 b, u8 c)
305{
306	IPW_DEBUG_IO("%s %d: write_indirect8(0x%08X, 0x%08X)\n", __FILE__,
307		     __LINE__, (u32) (b), (u32) (c));
308	_ipw_write_reg8(a, b, c);
309}
310
311/* 16-bit indirect write (for SRAM/reg above 4K), with debug wrapper */
312static void _ipw_write_reg16(struct ipw_priv *priv, u32 reg, u16 value);
313static inline void ipw_write_reg16(struct ipw_priv *a, u32 b, u16 c)
314{
315	IPW_DEBUG_IO("%s %d: write_indirect16(0x%08X, 0x%08X)\n", __FILE__,
316		     __LINE__, (u32) (b), (u32) (c));
317	_ipw_write_reg16(a, b, c);
318}
319
320/* 32-bit indirect write (for SRAM/reg above 4K), with debug wrapper */
321static void _ipw_write_reg32(struct ipw_priv *priv, u32 reg, u32 value);
322static inline void ipw_write_reg32(struct ipw_priv *a, u32 b, u32 c)
323{
324	IPW_DEBUG_IO("%s %d: write_indirect32(0x%08X, 0x%08X)\n", __FILE__,
325		     __LINE__, (u32) (b), (u32) (c));
326	_ipw_write_reg32(a, b, c);
327}
328
329/* 8-bit direct write (low 4K) */
330static inline void _ipw_write8(struct ipw_priv *ipw, unsigned long ofs,
331		u8 val)
332{
333	writeb(val, ipw->hw_base + ofs);
334}
335
336/* 8-bit direct write (for low 4K of SRAM/regs), with debug wrapper */
337#define ipw_write8(ipw, ofs, val) do { \
338	IPW_DEBUG_IO("%s %d: write_direct8(0x%08X, 0x%08X)\n", __FILE__, \
339			__LINE__, (u32)(ofs), (u32)(val)); \
340	_ipw_write8(ipw, ofs, val); \
341} while (0)
342
343/* 16-bit direct write (low 4K) */
344static inline void _ipw_write16(struct ipw_priv *ipw, unsigned long ofs,
345		u16 val)
346{
347	writew(val, ipw->hw_base + ofs);
348}
349
350/* 16-bit direct write (for low 4K of SRAM/regs), with debug wrapper */
351#define ipw_write16(ipw, ofs, val) do { \
352	IPW_DEBUG_IO("%s %d: write_direct16(0x%08X, 0x%08X)\n", __FILE__, \
353			__LINE__, (u32)(ofs), (u32)(val)); \
354	_ipw_write16(ipw, ofs, val); \
355} while (0)
356
357/* 32-bit direct write (low 4K) */
358static inline void _ipw_write32(struct ipw_priv *ipw, unsigned long ofs,
359		u32 val)
360{
361	writel(val, ipw->hw_base + ofs);
362}
363
364/* 32-bit direct write (for low 4K of SRAM/regs), with debug wrapper */
365#define ipw_write32(ipw, ofs, val) do { \
366	IPW_DEBUG_IO("%s %d: write_direct32(0x%08X, 0x%08X)\n", __FILE__, \
367			__LINE__, (u32)(ofs), (u32)(val)); \
368	_ipw_write32(ipw, ofs, val); \
369} while (0)
370
371/* 8-bit direct read (low 4K) */
372static inline u8 _ipw_read8(struct ipw_priv *ipw, unsigned long ofs)
373{
374	return readb(ipw->hw_base + ofs);
375}
376
377/* alias to 8-bit direct read (low 4K of SRAM/regs), with debug wrapper */
378#define ipw_read8(ipw, ofs) ({ \
379	IPW_DEBUG_IO("%s %d: read_direct8(0x%08X)\n", __FILE__, __LINE__, \
380			(u32)(ofs)); \
381	_ipw_read8(ipw, ofs); \
382})
383
384/* 16-bit direct read (low 4K) */
385static inline u16 _ipw_read16(struct ipw_priv *ipw, unsigned long ofs)
386{
387	return readw(ipw->hw_base + ofs);
388}
389
390/* alias to 16-bit direct read (low 4K of SRAM/regs), with debug wrapper */
391#define ipw_read16(ipw, ofs) ({ \
392	IPW_DEBUG_IO("%s %d: read_direct16(0x%08X)\n", __FILE__, __LINE__, \
393			(u32)(ofs)); \
394	_ipw_read16(ipw, ofs); \
395})
396
397/* 32-bit direct read (low 4K) */
398static inline u32 _ipw_read32(struct ipw_priv *ipw, unsigned long ofs)
399{
400	return readl(ipw->hw_base + ofs);
401}
402
403/* alias to 32-bit direct read (low 4K of SRAM/regs), with debug wrapper */
404#define ipw_read32(ipw, ofs) ({ \
405	IPW_DEBUG_IO("%s %d: read_direct32(0x%08X)\n", __FILE__, __LINE__, \
406			(u32)(ofs)); \
407	_ipw_read32(ipw, ofs); \
408})
409
410static void _ipw_read_indirect(struct ipw_priv *, u32, u8 *, int);
411/* alias to multi-byte read (SRAM/regs above 4K), with debug wrapper */
412#define ipw_read_indirect(a, b, c, d) ({ \
413	IPW_DEBUG_IO("%s %d: read_indirect(0x%08X) %u bytes\n", __FILE__, \
414			__LINE__, (u32)(b), (u32)(d)); \
415	_ipw_read_indirect(a, b, c, d); \
416})
417
418/* alias to multi-byte read (SRAM/regs above 4K), with debug wrapper */
419static void _ipw_write_indirect(struct ipw_priv *priv, u32 addr, u8 * data,
420				int num);
421#define ipw_write_indirect(a, b, c, d) do { \
422	IPW_DEBUG_IO("%s %d: write_indirect(0x%08X) %u bytes\n", __FILE__, \
423			__LINE__, (u32)(b), (u32)(d)); \
424	_ipw_write_indirect(a, b, c, d); \
425} while (0)
426
427/* 32-bit indirect write (above 4K) */
428static void _ipw_write_reg32(struct ipw_priv *priv, u32 reg, u32 value)
429{
430	IPW_DEBUG_IO(" %p : reg = 0x%8X : value = 0x%8X\n", priv, reg, value);
431	_ipw_write32(priv, IPW_INDIRECT_ADDR, reg);
432	_ipw_write32(priv, IPW_INDIRECT_DATA, value);
433}
434
435/* 8-bit indirect write (above 4K) */
436static void _ipw_write_reg8(struct ipw_priv *priv, u32 reg, u8 value)
437{
438	u32 aligned_addr = reg & IPW_INDIRECT_ADDR_MASK;	/* dword align */
439	u32 dif_len = reg - aligned_addr;
440
441	IPW_DEBUG_IO(" reg = 0x%8X : value = 0x%8X\n", reg, value);
442	_ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
443	_ipw_write8(priv, IPW_INDIRECT_DATA + dif_len, value);
444}
445
446/* 16-bit indirect write (above 4K) */
447static void _ipw_write_reg16(struct ipw_priv *priv, u32 reg, u16 value)
448{
449	u32 aligned_addr = reg & IPW_INDIRECT_ADDR_MASK;	/* dword align */
450	u32 dif_len = (reg - aligned_addr) & (~0x1ul);
451
452	IPW_DEBUG_IO(" reg = 0x%8X : value = 0x%8X\n", reg, value);
453	_ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
454	_ipw_write16(priv, IPW_INDIRECT_DATA + dif_len, value);
455}
456
457/* 8-bit indirect read (above 4K) */
458static u8 _ipw_read_reg8(struct ipw_priv *priv, u32 reg)
459{
460	u32 word;
461	_ipw_write32(priv, IPW_INDIRECT_ADDR, reg & IPW_INDIRECT_ADDR_MASK);
462	IPW_DEBUG_IO(" reg = 0x%8X :\n", reg);
463	word = _ipw_read32(priv, IPW_INDIRECT_DATA);
464	return (word >> ((reg & 0x3) * 8)) & 0xff;
465}
466
467/* 32-bit indirect read (above 4K) */
468static u32 _ipw_read_reg32(struct ipw_priv *priv, u32 reg)
469{
470	u32 value;
471
472	IPW_DEBUG_IO("%p : reg = 0x%08x\n", priv, reg);
473
474	_ipw_write32(priv, IPW_INDIRECT_ADDR, reg);
475	value = _ipw_read32(priv, IPW_INDIRECT_DATA);
476	IPW_DEBUG_IO(" reg = 0x%4X : value = 0x%4x\n", reg, value);
477	return value;
478}
479
480/* General purpose, no alignment requirement, iterative (multi-byte) read, */
481/*    for area above 1st 4K of SRAM/reg space */
482static void _ipw_read_indirect(struct ipw_priv *priv, u32 addr, u8 * buf,
483			       int num)
484{
485	u32 aligned_addr = addr & IPW_INDIRECT_ADDR_MASK;	/* dword align */
486	u32 dif_len = addr - aligned_addr;
487	u32 i;
488
489	IPW_DEBUG_IO("addr = %i, buf = %p, num = %i\n", addr, buf, num);
490
491	if (num <= 0) {
492		return;
493	}
494
495	/* Read the first dword (or portion) byte by byte */
496	if (unlikely(dif_len)) {
497		_ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
498		/* Start reading at aligned_addr + dif_len */
499		for (i = dif_len; ((i < 4) && (num > 0)); i++, num--)
500			*buf++ = _ipw_read8(priv, IPW_INDIRECT_DATA + i);
501		aligned_addr += 4;
502	}
503
504	/* Read all of the middle dwords as dwords, with auto-increment */
505	_ipw_write32(priv, IPW_AUTOINC_ADDR, aligned_addr);
506	for (; num >= 4; buf += 4, aligned_addr += 4, num -= 4)
507		*(u32 *) buf = _ipw_read32(priv, IPW_AUTOINC_DATA);
508
509	/* Read the last dword (or portion) byte by byte */
510	if (unlikely(num)) {
511		_ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
512		for (i = 0; num > 0; i++, num--)
513			*buf++ = ipw_read8(priv, IPW_INDIRECT_DATA + i);
514	}
515}
516
517/* General purpose, no alignment requirement, iterative (multi-byte) write, */
518/*    for area above 1st 4K of SRAM/reg space */
519static void _ipw_write_indirect(struct ipw_priv *priv, u32 addr, u8 * buf,
520				int num)
521{
522	u32 aligned_addr = addr & IPW_INDIRECT_ADDR_MASK;	/* dword align */
523	u32 dif_len = addr - aligned_addr;
524	u32 i;
525
526	IPW_DEBUG_IO("addr = %i, buf = %p, num = %i\n", addr, buf, num);
527
528	if (num <= 0) {
529		return;
530	}
531
532	/* Write the first dword (or portion) byte by byte */
533	if (unlikely(dif_len)) {
534		_ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
535		/* Start writing at aligned_addr + dif_len */
536		for (i = dif_len; ((i < 4) && (num > 0)); i++, num--, buf++)
537			_ipw_write8(priv, IPW_INDIRECT_DATA + i, *buf);
538		aligned_addr += 4;
539	}
540
541	/* Write all of the middle dwords as dwords, with auto-increment */
542	_ipw_write32(priv, IPW_AUTOINC_ADDR, aligned_addr);
543	for (; num >= 4; buf += 4, aligned_addr += 4, num -= 4)
544		_ipw_write32(priv, IPW_AUTOINC_DATA, *(u32 *) buf);
545
546	/* Write the last dword (or portion) byte by byte */
547	if (unlikely(num)) {
548		_ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
549		for (i = 0; num > 0; i++, num--, buf++)
550			_ipw_write8(priv, IPW_INDIRECT_DATA + i, *buf);
551	}
552}
553
554/* General purpose, no alignment requirement, iterative (multi-byte) write, */
555/*    for 1st 4K of SRAM/regs space */
556static void ipw_write_direct(struct ipw_priv *priv, u32 addr, void *buf,
557			     int num)
558{
559	memcpy_toio((priv->hw_base + addr), buf, num);
560}
561
562/* Set bit(s) in low 4K of SRAM/regs */
563static inline void ipw_set_bit(struct ipw_priv *priv, u32 reg, u32 mask)
564{
565	ipw_write32(priv, reg, ipw_read32(priv, reg) | mask);
566}
567
568/* Clear bit(s) in low 4K of SRAM/regs */
569static inline void ipw_clear_bit(struct ipw_priv *priv, u32 reg, u32 mask)
570{
571	ipw_write32(priv, reg, ipw_read32(priv, reg) & ~mask);
572}
573
574static inline void __ipw_enable_interrupts(struct ipw_priv *priv)
575{
576	if (priv->status & STATUS_INT_ENABLED)
577		return;
578	priv->status |= STATUS_INT_ENABLED;
579	ipw_write32(priv, IPW_INTA_MASK_R, IPW_INTA_MASK_ALL);
580}
581
582static inline void __ipw_disable_interrupts(struct ipw_priv *priv)
583{
584	if (!(priv->status & STATUS_INT_ENABLED))
585		return;
586	priv->status &= ~STATUS_INT_ENABLED;
587	ipw_write32(priv, IPW_INTA_MASK_R, ~IPW_INTA_MASK_ALL);
588}
589
590static inline void ipw_enable_interrupts(struct ipw_priv *priv)
591{
592	unsigned long flags;
593
594	spin_lock_irqsave(&priv->irq_lock, flags);
595	__ipw_enable_interrupts(priv);
596	spin_unlock_irqrestore(&priv->irq_lock, flags);
597}
598
599static inline void ipw_disable_interrupts(struct ipw_priv *priv)
600{
601	unsigned long flags;
602
603	spin_lock_irqsave(&priv->irq_lock, flags);
604	__ipw_disable_interrupts(priv);
605	spin_unlock_irqrestore(&priv->irq_lock, flags);
606}
607
608static char *ipw_error_desc(u32 val)
609{
610	switch (val) {
611	case IPW_FW_ERROR_OK:
612		return "ERROR_OK";
613	case IPW_FW_ERROR_FAIL:
614		return "ERROR_FAIL";
615	case IPW_FW_ERROR_MEMORY_UNDERFLOW:
616		return "MEMORY_UNDERFLOW";
617	case IPW_FW_ERROR_MEMORY_OVERFLOW:
618		return "MEMORY_OVERFLOW";
619	case IPW_FW_ERROR_BAD_PARAM:
620		return "BAD_PARAM";
621	case IPW_FW_ERROR_BAD_CHECKSUM:
622		return "BAD_CHECKSUM";
623	case IPW_FW_ERROR_NMI_INTERRUPT:
624		return "NMI_INTERRUPT";
625	case IPW_FW_ERROR_BAD_DATABASE:
626		return "BAD_DATABASE";
627	case IPW_FW_ERROR_ALLOC_FAIL:
628		return "ALLOC_FAIL";
629	case IPW_FW_ERROR_DMA_UNDERRUN:
630		return "DMA_UNDERRUN";
631	case IPW_FW_ERROR_DMA_STATUS:
632		return "DMA_STATUS";
633	case IPW_FW_ERROR_DINO_ERROR:
634		return "DINO_ERROR";
635	case IPW_FW_ERROR_EEPROM_ERROR:
636		return "EEPROM_ERROR";
637	case IPW_FW_ERROR_SYSASSERT:
638		return "SYSASSERT";
639	case IPW_FW_ERROR_FATAL_ERROR:
640		return "FATAL_ERROR";
641	default:
642		return "UNKNOWN_ERROR";
643	}
644}
645
646static void ipw_dump_error_log(struct ipw_priv *priv,
647			       struct ipw_fw_error *error)
648{
649	u32 i;
650
651	if (!error) {
652		IPW_ERROR("Error allocating and capturing error log.  "
653			  "Nothing to dump.\n");
654		return;
655	}
656
657	IPW_ERROR("Start IPW Error Log Dump:\n");
658	IPW_ERROR("Status: 0x%08X, Config: %08X\n",
659		  error->status, error->config);
660
661	for (i = 0; i < error->elem_len; i++)
662		IPW_ERROR("%s %i 0x%08x  0x%08x  0x%08x  0x%08x  0x%08x\n",
663			  ipw_error_desc(error->elem[i].desc),
664			  error->elem[i].time,
665			  error->elem[i].blink1,
666			  error->elem[i].blink2,
667			  error->elem[i].link1,
668			  error->elem[i].link2, error->elem[i].data);
669	for (i = 0; i < error->log_len; i++)
670		IPW_ERROR("%i\t0x%08x\t%i\n",
671			  error->log[i].time,
672			  error->log[i].data, error->log[i].event);
673}
674
675static inline int ipw_is_init(struct ipw_priv *priv)
676{
677	return (priv->status & STATUS_INIT) ? 1 : 0;
678}
679
680static int ipw_get_ordinal(struct ipw_priv *priv, u32 ord, void *val, u32 * len)
681{
682	u32 addr, field_info, field_len, field_count, total_len;
683
684	IPW_DEBUG_ORD("ordinal = %i\n", ord);
685
686	if (!priv || !val || !len) {
687		IPW_DEBUG_ORD("Invalid argument\n");
688		return -EINVAL;
689	}
690
691	/* verify device ordinal tables have been initialized */
692	if (!priv->table0_addr || !priv->table1_addr || !priv->table2_addr) {
693		IPW_DEBUG_ORD("Access ordinals before initialization\n");
694		return -EINVAL;
695	}
696
697	switch (IPW_ORD_TABLE_ID_MASK & ord) {
698	case IPW_ORD_TABLE_0_MASK:
699		/*
700		 * TABLE 0: Direct access to a table of 32 bit values
701		 *
702		 * This is a very simple table with the data directly
703		 * read from the table
704		 */
705
706		/* remove the table id from the ordinal */
707		ord &= IPW_ORD_TABLE_VALUE_MASK;
708
709		/* boundary check */
710		if (ord > priv->table0_len) {
711			IPW_DEBUG_ORD("ordinal value (%i) longer then "
712				      "max (%i)\n", ord, priv->table0_len);
713			return -EINVAL;
714		}
715
716		/* verify we have enough room to store the value */
717		if (*len < sizeof(u32)) {
718			IPW_DEBUG_ORD("ordinal buffer length too small, "
719				      "need %zd\n", sizeof(u32));
720			return -EINVAL;
721		}
722
723		IPW_DEBUG_ORD("Reading TABLE0[%i] from offset 0x%08x\n",
724			      ord, priv->table0_addr + (ord << 2));
725
726		*len = sizeof(u32);
727		ord <<= 2;
728		*((u32 *) val) = ipw_read32(priv, priv->table0_addr + ord);
729		break;
730
731	case IPW_ORD_TABLE_1_MASK:
732		/*
733		 * TABLE 1: Indirect access to a table of 32 bit values
734		 *
735		 * This is a fairly large table of u32 values each
736		 * representing starting addr for the data (which is
737		 * also a u32)
738		 */
739
740		/* remove the table id from the ordinal */
741		ord &= IPW_ORD_TABLE_VALUE_MASK;
742
743		/* boundary check */
744		if (ord > priv->table1_len) {
745			IPW_DEBUG_ORD("ordinal value too long\n");
746			return -EINVAL;
747		}
748
749		/* verify we have enough room to store the value */
750		if (*len < sizeof(u32)) {
751			IPW_DEBUG_ORD("ordinal buffer length too small, "
752				      "need %zd\n", sizeof(u32));
753			return -EINVAL;
754		}
755
756		*((u32 *) val) =
757		    ipw_read_reg32(priv, (priv->table1_addr + (ord << 2)));
758		*len = sizeof(u32);
759		break;
760
761	case IPW_ORD_TABLE_2_MASK:
762		/*
763		 * TABLE 2: Indirect access to a table of variable sized values
764		 *
765		 * This table consist of six values, each containing
766		 *     - dword containing the starting offset of the data
767		 *     - dword containing the lengh in the first 16bits
768		 *       and the count in the second 16bits
769		 */
770
771		/* remove the table id from the ordinal */
772		ord &= IPW_ORD_TABLE_VALUE_MASK;
773
774		/* boundary check */
775		if (ord > priv->table2_len) {
776			IPW_DEBUG_ORD("ordinal value too long\n");
777			return -EINVAL;
778		}
779
780		/* get the address of statistic */
781		addr = ipw_read_reg32(priv, priv->table2_addr + (ord << 3));
782
783		/* get the second DW of statistics ;
784		 * two 16-bit words - first is length, second is count */
785		field_info =
786		    ipw_read_reg32(priv,
787				   priv->table2_addr + (ord << 3) +
788				   sizeof(u32));
789
790		/* get each entry length */
791		field_len = *((u16 *) & field_info);
792
793		/* get number of entries */
794		field_count = *(((u16 *) & field_info) + 1);
795
796		/* abort if not enough memory */
797		total_len = field_len * field_count;
798		if (total_len > *len) {
799			*len = total_len;
800			return -EINVAL;
801		}
802
803		*len = total_len;
804		if (!total_len)
805			return 0;
806
807		IPW_DEBUG_ORD("addr = 0x%08x, total_len = %i, "
808			      "field_info = 0x%08x\n",
809			      addr, total_len, field_info);
810		ipw_read_indirect(priv, addr, val, total_len);
811		break;
812
813	default:
814		IPW_DEBUG_ORD("Invalid ordinal!\n");
815		return -EINVAL;
816
817	}
818
819	return 0;
820}
821
822static void ipw_init_ordinals(struct ipw_priv *priv)
823{
824	priv->table0_addr = IPW_ORDINALS_TABLE_LOWER;
825	priv->table0_len = ipw_read32(priv, priv->table0_addr);
826
827	IPW_DEBUG_ORD("table 0 offset at 0x%08x, len = %i\n",
828		      priv->table0_addr, priv->table0_len);
829
830	priv->table1_addr = ipw_read32(priv, IPW_ORDINALS_TABLE_1);
831	priv->table1_len = ipw_read_reg32(priv, priv->table1_addr);
832
833	IPW_DEBUG_ORD("table 1 offset at 0x%08x, len = %i\n",
834		      priv->table1_addr, priv->table1_len);
835
836	priv->table2_addr = ipw_read32(priv, IPW_ORDINALS_TABLE_2);
837	priv->table2_len = ipw_read_reg32(priv, priv->table2_addr);
838	priv->table2_len &= 0x0000ffff;	/* use first two bytes */
839
840	IPW_DEBUG_ORD("table 2 offset at 0x%08x, len = %i\n",
841		      priv->table2_addr, priv->table2_len);
842
843}
844
845static u32 ipw_register_toggle(u32 reg)
846{
847	reg &= ~IPW_START_STANDBY;
848	if (reg & IPW_GATE_ODMA)
849		reg &= ~IPW_GATE_ODMA;
850	if (reg & IPW_GATE_IDMA)
851		reg &= ~IPW_GATE_IDMA;
852	if (reg & IPW_GATE_ADMA)
853		reg &= ~IPW_GATE_ADMA;
854	return reg;
855}
856
857/*
858 * LED behavior:
859 * - On radio ON, turn on any LEDs that require to be on during start
860 * - On initialization, start unassociated blink
861 * - On association, disable unassociated blink
862 * - On disassociation, start unassociated blink
863 * - On radio OFF, turn off any LEDs started during radio on
864 *
865 */
866#define LD_TIME_LINK_ON msecs_to_jiffies(300)
867#define LD_TIME_LINK_OFF msecs_to_jiffies(2700)
868#define LD_TIME_ACT_ON msecs_to_jiffies(250)
869
870static void ipw_led_link_on(struct ipw_priv *priv)
871{
872	unsigned long flags;
873	u32 led;
874
875	/* If configured to not use LEDs, or nic_type is 1,
876	 * then we don't toggle a LINK led */
877	if (priv->config & CFG_NO_LED || priv->nic_type == EEPROM_NIC_TYPE_1)
878		return;
879
880	spin_lock_irqsave(&priv->lock, flags);
881
882	if (!(priv->status & STATUS_RF_KILL_MASK) &&
883	    !(priv->status & STATUS_LED_LINK_ON)) {
884		IPW_DEBUG_LED("Link LED On\n");
885		led = ipw_read_reg32(priv, IPW_EVENT_REG);
886		led |= priv->led_association_on;
887
888		led = ipw_register_toggle(led);
889
890		IPW_DEBUG_LED("Reg: 0x%08X\n", led);
891		ipw_write_reg32(priv, IPW_EVENT_REG, led);
892
893		priv->status |= STATUS_LED_LINK_ON;
894
895		/* If we aren't associated, schedule turning the LED off */
896		if (!(priv->status & STATUS_ASSOCIATED))
897			queue_delayed_work(priv->workqueue,
898					   &priv->led_link_off,
899					   LD_TIME_LINK_ON);
900	}
901
902	spin_unlock_irqrestore(&priv->lock, flags);
903}
904
905static void ipw_bg_led_link_on(struct work_struct *work)
906{
907	struct ipw_priv *priv =
908		container_of(work, struct ipw_priv, led_link_on.work);
909	mutex_lock(&priv->mutex);
910	ipw_led_link_on(priv);
911	mutex_unlock(&priv->mutex);
912}
913
914static void ipw_led_link_off(struct ipw_priv *priv)
915{
916	unsigned long flags;
917	u32 led;
918
919	/* If configured not to use LEDs, or nic type is 1,
920	 * then we don't goggle the LINK led. */
921	if (priv->config & CFG_NO_LED || priv->nic_type == EEPROM_NIC_TYPE_1)
922		return;
923
924	spin_lock_irqsave(&priv->lock, flags);
925
926	if (priv->status & STATUS_LED_LINK_ON) {
927		led = ipw_read_reg32(priv, IPW_EVENT_REG);
928		led &= priv->led_association_off;
929		led = ipw_register_toggle(led);
930
931		IPW_DEBUG_LED("Reg: 0x%08X\n", led);
932		ipw_write_reg32(priv, IPW_EVENT_REG, led);
933
934		IPW_DEBUG_LED("Link LED Off\n");
935
936		priv->status &= ~STATUS_LED_LINK_ON;
937
938		/* If we aren't associated and the radio is on, schedule
939		 * turning the LED on (blink while unassociated) */
940		if (!(priv->status & STATUS_RF_KILL_MASK) &&
941		    !(priv->status & STATUS_ASSOCIATED))
942			queue_delayed_work(priv->workqueue, &priv->led_link_on,
943					   LD_TIME_LINK_OFF);
944
945	}
946
947	spin_unlock_irqrestore(&priv->lock, flags);
948}
949
950static void ipw_bg_led_link_off(struct work_struct *work)
951{
952	struct ipw_priv *priv =
953		container_of(work, struct ipw_priv, led_link_off.work);
954	mutex_lock(&priv->mutex);
955	ipw_led_link_off(priv);
956	mutex_unlock(&priv->mutex);
957}
958
959static void __ipw_led_activity_on(struct ipw_priv *priv)
960{
961	u32 led;
962
963	if (priv->config & CFG_NO_LED)
964		return;
965
966	if (priv->status & STATUS_RF_KILL_MASK)
967		return;
968
969	if (!(priv->status & STATUS_LED_ACT_ON)) {
970		led = ipw_read_reg32(priv, IPW_EVENT_REG);
971		led |= priv->led_activity_on;
972
973		led = ipw_register_toggle(led);
974
975		IPW_DEBUG_LED("Reg: 0x%08X\n", led);
976		ipw_write_reg32(priv, IPW_EVENT_REG, led);
977
978		IPW_DEBUG_LED("Activity LED On\n");
979
980		priv->status |= STATUS_LED_ACT_ON;
981
982		cancel_delayed_work(&priv->led_act_off);
983		queue_delayed_work(priv->workqueue, &priv->led_act_off,
984				   LD_TIME_ACT_ON);
985	} else {
986		/* Reschedule LED off for full time period */
987		cancel_delayed_work(&priv->led_act_off);
988		queue_delayed_work(priv->workqueue, &priv->led_act_off,
989				   LD_TIME_ACT_ON);
990	}
991}
992
993
994static void ipw_led_activity_off(struct ipw_priv *priv)
995{
996	unsigned long flags;
997	u32 led;
998
999	if (priv->config & CFG_NO_LED)
1000		return;
1001
1002	spin_lock_irqsave(&priv->lock, flags);
1003
1004	if (priv->status & STATUS_LED_ACT_ON) {
1005		led = ipw_read_reg32(priv, IPW_EVENT_REG);
1006		led &= priv->led_activity_off;
1007
1008		led = ipw_register_toggle(led);
1009
1010		IPW_DEBUG_LED("Reg: 0x%08X\n", led);
1011		ipw_write_reg32(priv, IPW_EVENT_REG, led);
1012
1013		IPW_DEBUG_LED("Activity LED Off\n");
1014
1015		priv->status &= ~STATUS_LED_ACT_ON;
1016	}
1017
1018	spin_unlock_irqrestore(&priv->lock, flags);
1019}
1020
1021static void ipw_bg_led_activity_off(struct work_struct *work)
1022{
1023	struct ipw_priv *priv =
1024		container_of(work, struct ipw_priv, led_act_off.work);
1025	mutex_lock(&priv->mutex);
1026	ipw_led_activity_off(priv);
1027	mutex_unlock(&priv->mutex);
1028}
1029
1030static void ipw_led_band_on(struct ipw_priv *priv)
1031{
1032	unsigned long flags;
1033	u32 led;
1034
1035	/* Only nic type 1 supports mode LEDs */
1036	if (priv->config & CFG_NO_LED ||
1037	    priv->nic_type != EEPROM_NIC_TYPE_1 || !priv->assoc_network)
1038		return;
1039
1040	spin_lock_irqsave(&priv->lock, flags);
1041
1042	led = ipw_read_reg32(priv, IPW_EVENT_REG);
1043	if (priv->assoc_network->mode == IEEE_A) {
1044		led |= priv->led_ofdm_on;
1045		led &= priv->led_association_off;
1046		IPW_DEBUG_LED("Mode LED On: 802.11a\n");
1047	} else if (priv->assoc_network->mode == IEEE_G) {
1048		led |= priv->led_ofdm_on;
1049		led |= priv->led_association_on;
1050		IPW_DEBUG_LED("Mode LED On: 802.11g\n");
1051	} else {
1052		led &= priv->led_ofdm_off;
1053		led |= priv->led_association_on;
1054		IPW_DEBUG_LED("Mode LED On: 802.11b\n");
1055	}
1056
1057	led = ipw_register_toggle(led);
1058
1059	IPW_DEBUG_LED("Reg: 0x%08X\n", led);
1060	ipw_write_reg32(priv, IPW_EVENT_REG, led);
1061
1062	spin_unlock_irqrestore(&priv->lock, flags);
1063}
1064
1065static void ipw_led_band_off(struct ipw_priv *priv)
1066{
1067	unsigned long flags;
1068	u32 led;
1069
1070	/* Only nic type 1 supports mode LEDs */
1071	if (priv->config & CFG_NO_LED || priv->nic_type != EEPROM_NIC_TYPE_1)
1072		return;
1073
1074	spin_lock_irqsave(&priv->lock, flags);
1075
1076	led = ipw_read_reg32(priv, IPW_EVENT_REG);
1077	led &= priv->led_ofdm_off;
1078	led &= priv->led_association_off;
1079
1080	led = ipw_register_toggle(led);
1081
1082	IPW_DEBUG_LED("Reg: 0x%08X\n", led);
1083	ipw_write_reg32(priv, IPW_EVENT_REG, led);
1084
1085	spin_unlock_irqrestore(&priv->lock, flags);
1086}
1087
1088static void ipw_led_radio_on(struct ipw_priv *priv)
1089{
1090	ipw_led_link_on(priv);
1091}
1092
1093static void ipw_led_radio_off(struct ipw_priv *priv)
1094{
1095	ipw_led_activity_off(priv);
1096	ipw_led_link_off(priv);
1097}
1098
1099static void ipw_led_link_up(struct ipw_priv *priv)
1100{
1101	/* Set the Link Led on for all nic types */
1102	ipw_led_link_on(priv);
1103}
1104
1105static void ipw_led_link_down(struct ipw_priv *priv)
1106{
1107	ipw_led_activity_off(priv);
1108	ipw_led_link_off(priv);
1109
1110	if (priv->status & STATUS_RF_KILL_MASK)
1111		ipw_led_radio_off(priv);
1112}
1113
1114static void ipw_led_init(struct ipw_priv *priv)
1115{
1116	priv->nic_type = priv->eeprom[EEPROM_NIC_TYPE];
1117
1118	/* Set the default PINs for the link and activity leds */
1119	priv->led_activity_on = IPW_ACTIVITY_LED;
1120	priv->led_activity_off = ~(IPW_ACTIVITY_LED);
1121
1122	priv->led_association_on = IPW_ASSOCIATED_LED;
1123	priv->led_association_off = ~(IPW_ASSOCIATED_LED);
1124
1125	/* Set the default PINs for the OFDM leds */
1126	priv->led_ofdm_on = IPW_OFDM_LED;
1127	priv->led_ofdm_off = ~(IPW_OFDM_LED);
1128
1129	switch (priv->nic_type) {
1130	case EEPROM_NIC_TYPE_1:
1131		/* In this NIC type, the LEDs are reversed.... */
1132		priv->led_activity_on = IPW_ASSOCIATED_LED;
1133		priv->led_activity_off = ~(IPW_ASSOCIATED_LED);
1134		priv->led_association_on = IPW_ACTIVITY_LED;
1135		priv->led_association_off = ~(IPW_ACTIVITY_LED);
1136
1137		if (!(priv->config & CFG_NO_LED))
1138			ipw_led_band_on(priv);
1139
1140		/* And we don't blink link LEDs for this nic, so
1141		 * just return here */
1142		return;
1143
1144	case EEPROM_NIC_TYPE_3:
1145	case EEPROM_NIC_TYPE_2:
1146	case EEPROM_NIC_TYPE_4:
1147	case EEPROM_NIC_TYPE_0:
1148		break;
1149
1150	default:
1151		IPW_DEBUG_INFO("Unknown NIC type from EEPROM: %d\n",
1152			       priv->nic_type);
1153		priv->nic_type = EEPROM_NIC_TYPE_0;
1154		break;
1155	}
1156
1157	if (!(priv->config & CFG_NO_LED)) {
1158		if (priv->status & STATUS_ASSOCIATED)
1159			ipw_led_link_on(priv);
1160		else
1161			ipw_led_link_off(priv);
1162	}
1163}
1164
1165static void ipw_led_shutdown(struct ipw_priv *priv)
1166{
1167	ipw_led_activity_off(priv);
1168	ipw_led_link_off(priv);
1169	ipw_led_band_off(priv);
1170	cancel_delayed_work(&priv->led_link_on);
1171	cancel_delayed_work(&priv->led_link_off);
1172	cancel_delayed_work(&priv->led_act_off);
1173}
1174
1175/*
1176 * The following adds a new attribute to the sysfs representation
1177 * of this device driver (i.e. a new file in /sys/bus/pci/drivers/ipw/)
1178 * used for controling the debug level.
1179 *
1180 * See the level definitions in ipw for details.
1181 */
1182static ssize_t show_debug_level(struct device_driver *d, char *buf)
1183{
1184	return sprintf(buf, "0x%08X\n", ipw_debug_level);
1185}
1186
1187static ssize_t store_debug_level(struct device_driver *d, const char *buf,
1188				 size_t count)
1189{
1190	char *p = (char *)buf;
1191	u32 val;
1192
1193	if (p[1] == 'x' || p[1] == 'X' || p[0] == 'x' || p[0] == 'X') {
1194		p++;
1195		if (p[0] == 'x' || p[0] == 'X')
1196			p++;
1197		val = simple_strtoul(p, &p, 16);
1198	} else
1199		val = simple_strtoul(p, &p, 10);
1200	if (p == buf)
1201		printk(KERN_INFO DRV_NAME
1202		       ": %s is not in hex or decimal form.\n", buf);
1203	else
1204		ipw_debug_level = val;
1205
1206	return strnlen(buf, count);
1207}
1208
1209static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
1210		   show_debug_level, store_debug_level);
1211
1212static inline u32 ipw_get_event_log_len(struct ipw_priv *priv)
1213{
1214	/* length = 1st dword in log */
1215	return ipw_read_reg32(priv, ipw_read32(priv, IPW_EVENT_LOG));
1216}
1217
1218static void ipw_capture_event_log(struct ipw_priv *priv,
1219				  u32 log_len, struct ipw_event *log)
1220{
1221	u32 base;
1222
1223	if (log_len) {
1224		base = ipw_read32(priv, IPW_EVENT_LOG);
1225		ipw_read_indirect(priv, base + sizeof(base) + sizeof(u32),
1226				  (u8 *) log, sizeof(*log) * log_len);
1227	}
1228}
1229
1230static struct ipw_fw_error *ipw_alloc_error_log(struct ipw_priv *priv)
1231{
1232	struct ipw_fw_error *error;
1233	u32 log_len = ipw_get_event_log_len(priv);
1234	u32 base = ipw_read32(priv, IPW_ERROR_LOG);
1235	u32 elem_len = ipw_read_reg32(priv, base);
1236
1237	error = kmalloc(sizeof(*error) +
1238			sizeof(*error->elem) * elem_len +
1239			sizeof(*error->log) * log_len, GFP_ATOMIC);
1240	if (!error) {
1241		IPW_ERROR("Memory allocation for firmware error log "
1242			  "failed.\n");
1243		return NULL;
1244	}
1245	error->jiffies = jiffies;
1246	error->status = priv->status;
1247	error->config = priv->config;
1248	error->elem_len = elem_len;
1249	error->log_len = log_len;
1250	error->elem = (struct ipw_error_elem *)error->payload;
1251	error->log = (struct ipw_event *)(error->elem + elem_len);
1252
1253	ipw_capture_event_log(priv, log_len, error->log);
1254
1255	if (elem_len)
1256		ipw_read_indirect(priv, base + sizeof(base), (u8 *) error->elem,
1257				  sizeof(*error->elem) * elem_len);
1258
1259	return error;
1260}
1261
1262static ssize_t show_event_log(struct device *d,
1263			      struct device_attribute *attr, char *buf)
1264{
1265	struct ipw_priv *priv = dev_get_drvdata(d);
1266	u32 log_len = ipw_get_event_log_len(priv);
1267	u32 log_size;
1268	struct ipw_event *log;
1269	u32 len = 0, i;
1270
1271	/* not using min() because of its strict type checking */
1272	log_size = PAGE_SIZE / sizeof(*log) > log_len ?
1273			sizeof(*log) * log_len : PAGE_SIZE;
1274	log = kzalloc(log_size, GFP_KERNEL);
1275	if (!log) {
1276		IPW_ERROR("Unable to allocate memory for log\n");
1277		return 0;
1278	}
1279	log_len = log_size / sizeof(*log);
1280	ipw_capture_event_log(priv, log_len, log);
1281
1282	len += snprintf(buf + len, PAGE_SIZE - len, "%08X", log_len);
1283	for (i = 0; i < log_len; i++)
1284		len += snprintf(buf + len, PAGE_SIZE - len,
1285				"\n%08X%08X%08X",
1286				log[i].time, log[i].event, log[i].data);
1287	len += snprintf(buf + len, PAGE_SIZE - len, "\n");
1288	kfree(log);
1289	return len;
1290}
1291
1292static DEVICE_ATTR(event_log, S_IRUGO, show_event_log, NULL);
1293
1294static ssize_t show_error(struct device *d,
1295			  struct device_attribute *attr, char *buf)
1296{
1297	struct ipw_priv *priv = dev_get_drvdata(d);
1298	u32 len = 0, i;
1299	if (!priv->error)
1300		return 0;
1301	len += snprintf(buf + len, PAGE_SIZE - len,
1302			"%08lX%08X%08X%08X",
1303			priv->error->jiffies,
1304			priv->error->status,
1305			priv->error->config, priv->error->elem_len);
1306	for (i = 0; i < priv->error->elem_len; i++)
1307		len += snprintf(buf + len, PAGE_SIZE - len,
1308				"\n%08X%08X%08X%08X%08X%08X%08X",
1309				priv->error->elem[i].time,
1310				priv->error->elem[i].desc,
1311				priv->error->elem[i].blink1,
1312				priv->error->elem[i].blink2,
1313				priv->error->elem[i].link1,
1314				priv->error->elem[i].link2,
1315				priv->error->elem[i].data);
1316
1317	len += snprintf(buf + len, PAGE_SIZE - len,
1318			"\n%08X", priv->error->log_len);
1319	for (i = 0; i < priv->error->log_len; i++)
1320		len += snprintf(buf + len, PAGE_SIZE - len,
1321				"\n%08X%08X%08X",
1322				priv->error->log[i].time,
1323				priv->error->log[i].event,
1324				priv->error->log[i].data);
1325	len += snprintf(buf + len, PAGE_SIZE - len, "\n");
1326	return len;
1327}
1328
1329static ssize_t clear_error(struct device *d,
1330			   struct device_attribute *attr,
1331			   const char *buf, size_t count)
1332{
1333	struct ipw_priv *priv = dev_get_drvdata(d);
1334
1335	kfree(priv->error);
1336	priv->error = NULL;
1337	return count;
1338}
1339
1340static DEVICE_ATTR(error, S_IRUGO | S_IWUSR, show_error, clear_error);
1341
1342static ssize_t show_cmd_log(struct device *d,
1343			    struct device_attribute *attr, char *buf)
1344{
1345	struct ipw_priv *priv = dev_get_drvdata(d);
1346	u32 len = 0, i;
1347	if (!priv->cmdlog)
1348		return 0;
1349	for (i = (priv->cmdlog_pos + 1) % priv->cmdlog_len;
1350	     (i != priv->cmdlog_pos) && (PAGE_SIZE - len);
1351	     i = (i + 1) % priv->cmdlog_len) {
1352		len +=
1353		    snprintf(buf + len, PAGE_SIZE - len,
1354			     "\n%08lX%08X%08X%08X\n", priv->cmdlog[i].jiffies,
1355			     priv->cmdlog[i].retcode, priv->cmdlog[i].cmd.cmd,
1356			     priv->cmdlog[i].cmd.len);
1357		len +=
1358		    snprintk_buf(buf + len, PAGE_SIZE - len,
1359				 (u8 *) priv->cmdlog[i].cmd.param,
1360				 priv->cmdlog[i].cmd.len);
1361		len += snprintf(buf + len, PAGE_SIZE - len, "\n");
1362	}
1363	len += snprintf(buf + len, PAGE_SIZE - len, "\n");
1364	return len;
1365}
1366
1367static DEVICE_ATTR(cmd_log, S_IRUGO, show_cmd_log, NULL);
1368
1369#ifdef CONFIG_IPW2200_PROMISCUOUS
1370static void ipw_prom_free(struct ipw_priv *priv);
1371static int ipw_prom_alloc(struct ipw_priv *priv);
1372static ssize_t store_rtap_iface(struct device *d,
1373			 struct device_attribute *attr,
1374			 const char *buf, size_t count)
1375{
1376	struct ipw_priv *priv = dev_get_drvdata(d);
1377	int rc = 0;
1378
1379	if (count < 1)
1380		return -EINVAL;
1381
1382	switch (buf[0]) {
1383	case '0':
1384		if (!rtap_iface)
1385			return count;
1386
1387		if (netif_running(priv->prom_net_dev)) {
1388			IPW_WARNING("Interface is up.  Cannot unregister.\n");
1389			return count;
1390		}
1391
1392		ipw_prom_free(priv);
1393		rtap_iface = 0;
1394		break;
1395
1396	case '1':
1397		if (rtap_iface)
1398			return count;
1399
1400		rc = ipw_prom_alloc(priv);
1401		if (!rc)
1402			rtap_iface = 1;
1403		break;
1404
1405	default:
1406		return -EINVAL;
1407	}
1408
1409	if (rc) {
1410		IPW_ERROR("Failed to register promiscuous network "
1411			  "device (error %d).\n", rc);
1412	}
1413
1414	return count;
1415}
1416
1417static ssize_t show_rtap_iface(struct device *d,
1418			struct device_attribute *attr,
1419			char *buf)
1420{
1421	struct ipw_priv *priv = dev_get_drvdata(d);
1422	if (rtap_iface)
1423		return sprintf(buf, "%s", priv->prom_net_dev->name);
1424	else {
1425		buf[0] = '-';
1426		buf[1] = '1';
1427		buf[2] = '\0';
1428		return 3;
1429	}
1430}
1431
1432static DEVICE_ATTR(rtap_iface, S_IWUSR | S_IRUSR, show_rtap_iface,
1433		   store_rtap_iface);
1434
1435static ssize_t store_rtap_filter(struct device *d,
1436			 struct device_attribute *attr,
1437			 const char *buf, size_t count)
1438{
1439	struct ipw_priv *priv = dev_get_drvdata(d);
1440
1441	if (!priv->prom_priv) {
1442		IPW_ERROR("Attempting to set filter without "
1443			  "rtap_iface enabled.\n");
1444		return -EPERM;
1445	}
1446
1447	priv->prom_priv->filter = simple_strtol(buf, NULL, 0);
1448
1449	IPW_DEBUG_INFO("Setting rtap filter to " BIT_FMT16 "\n",
1450		       BIT_ARG16(priv->prom_priv->filter));
1451
1452	return count;
1453}
1454
1455static ssize_t show_rtap_filter(struct device *d,
1456			struct device_attribute *attr,
1457			char *buf)
1458{
1459	struct ipw_priv *priv = dev_get_drvdata(d);
1460	return sprintf(buf, "0x%04X",
1461		       priv->prom_priv ? priv->prom_priv->filter : 0);
1462}
1463
1464static DEVICE_ATTR(rtap_filter, S_IWUSR | S_IRUSR, show_rtap_filter,
1465		   store_rtap_filter);
1466#endif
1467
1468static ssize_t show_scan_age(struct device *d, struct device_attribute *attr,
1469			     char *buf)
1470{
1471	struct ipw_priv *priv = dev_get_drvdata(d);
1472	return sprintf(buf, "%d\n", priv->ieee->scan_age);
1473}
1474
1475static ssize_t store_scan_age(struct device *d, struct device_attribute *attr,
1476			      const char *buf, size_t count)
1477{
1478	struct ipw_priv *priv = dev_get_drvdata(d);
1479	struct net_device *dev = priv->net_dev;
1480	char buffer[] = "00000000";
1481	unsigned long len =
1482	    (sizeof(buffer) - 1) > count ? count : sizeof(buffer) - 1;
1483	unsigned long val;
1484	char *p = buffer;
1485
1486	IPW_DEBUG_INFO("enter\n");
1487
1488	strncpy(buffer, buf, len);
1489	buffer[len] = 0;
1490
1491	if (p[1] == 'x' || p[1] == 'X' || p[0] == 'x' || p[0] == 'X') {
1492		p++;
1493		if (p[0] == 'x' || p[0] == 'X')
1494			p++;
1495		val = simple_strtoul(p, &p, 16);
1496	} else
1497		val = simple_strtoul(p, &p, 10);
1498	if (p == buffer) {
1499		IPW_DEBUG_INFO("%s: user supplied invalid value.\n", dev->name);
1500	} else {
1501		priv->ieee->scan_age = val;
1502		IPW_DEBUG_INFO("set scan_age = %u\n", priv->ieee->scan_age);
1503	}
1504
1505	IPW_DEBUG_INFO("exit\n");
1506	return len;
1507}
1508
1509static DEVICE_ATTR(scan_age, S_IWUSR | S_IRUGO, show_scan_age, store_scan_age);
1510
1511static ssize_t show_led(struct device *d, struct device_attribute *attr,
1512			char *buf)
1513{
1514	struct ipw_priv *priv = dev_get_drvdata(d);
1515	return sprintf(buf, "%d\n", (priv->config & CFG_NO_LED) ? 0 : 1);
1516}
1517
1518static ssize_t store_led(struct device *d, struct device_attribute *attr,
1519			 const char *buf, size_t count)
1520{
1521	struct ipw_priv *priv = dev_get_drvdata(d);
1522
1523	IPW_DEBUG_INFO("enter\n");
1524
1525	if (count == 0)
1526		return 0;
1527
1528	if (*buf == 0) {
1529		IPW_DEBUG_LED("Disabling LED control.\n");
1530		priv->config |= CFG_NO_LED;
1531		ipw_led_shutdown(priv);
1532	} else {
1533		IPW_DEBUG_LED("Enabling LED control.\n");
1534		priv->config &= ~CFG_NO_LED;
1535		ipw_led_init(priv);
1536	}
1537
1538	IPW_DEBUG_INFO("exit\n");
1539	return count;
1540}
1541
1542static DEVICE_ATTR(led, S_IWUSR | S_IRUGO, show_led, store_led);
1543
1544static ssize_t show_status(struct device *d,
1545			   struct device_attribute *attr, char *buf)
1546{
1547	struct ipw_priv *p = dev_get_drvdata(d);
1548	return sprintf(buf, "0x%08x\n", (int)p->status);
1549}
1550
1551static DEVICE_ATTR(status, S_IRUGO, show_status, NULL);
1552
1553static ssize_t show_cfg(struct device *d, struct device_attribute *attr,
1554			char *buf)
1555{
1556	struct ipw_priv *p = dev_get_drvdata(d);
1557	return sprintf(buf, "0x%08x\n", (int)p->config);
1558}
1559
1560static DEVICE_ATTR(cfg, S_IRUGO, show_cfg, NULL);
1561
1562static ssize_t show_nic_type(struct device *d,
1563			     struct device_attribute *attr, char *buf)
1564{
1565	struct ipw_priv *priv = dev_get_drvdata(d);
1566	return sprintf(buf, "TYPE: %d\n", priv->nic_type);
1567}
1568
1569static DEVICE_ATTR(nic_type, S_IRUGO, show_nic_type, NULL);
1570
1571static ssize_t show_ucode_version(struct device *d,
1572				  struct device_attribute *attr, char *buf)
1573{
1574	u32 len = sizeof(u32), tmp = 0;
1575	struct ipw_priv *p = dev_get_drvdata(d);
1576
1577	if (ipw_get_ordinal(p, IPW_ORD_STAT_UCODE_VERSION, &tmp, &len))
1578		return 0;
1579
1580	return sprintf(buf, "0x%08x\n", tmp);
1581}
1582
1583static DEVICE_ATTR(ucode_version, S_IWUSR | S_IRUGO, show_ucode_version, NULL);
1584
1585static ssize_t show_rtc(struct device *d, struct device_attribute *attr,
1586			char *buf)
1587{
1588	u32 len = sizeof(u32), tmp = 0;
1589	struct ipw_priv *p = dev_get_drvdata(d);
1590
1591	if (ipw_get_ordinal(p, IPW_ORD_STAT_RTC, &tmp, &len))
1592		return 0;
1593
1594	return sprintf(buf, "0x%08x\n", tmp);
1595}
1596
1597static DEVICE_ATTR(rtc, S_IWUSR | S_IRUGO, show_rtc, NULL);
1598
1599/*
1600 * Add a device attribute to view/control the delay between eeprom
1601 * operations.
1602 */
1603static ssize_t show_eeprom_delay(struct device *d,
1604				 struct device_attribute *attr, char *buf)
1605{
1606	struct ipw_priv *p = dev_get_drvdata(d);
1607	int n = p->eeprom_delay;
1608	return sprintf(buf, "%i\n", n);
1609}
1610static ssize_t store_eeprom_delay(struct device *d,
1611				  struct device_attribute *attr,
1612				  const char *buf, size_t count)
1613{
1614	struct ipw_priv *p = dev_get_drvdata(d);
1615	sscanf(buf, "%i", &p->eeprom_delay);
1616	return strnlen(buf, count);
1617}
1618
1619static DEVICE_ATTR(eeprom_delay, S_IWUSR | S_IRUGO,
1620		   show_eeprom_delay, store_eeprom_delay);
1621
1622static ssize_t show_command_event_reg(struct device *d,
1623				      struct device_attribute *attr, char *buf)
1624{
1625	u32 reg = 0;
1626	struct ipw_priv *p = dev_get_drvdata(d);
1627
1628	reg = ipw_read_reg32(p, IPW_INTERNAL_CMD_EVENT);
1629	return sprintf(buf, "0x%08x\n", reg);
1630}
1631static ssize_t store_command_event_reg(struct device *d,
1632				       struct device_attribute *attr,
1633				       const char *buf, size_t count)
1634{
1635	u32 reg;
1636	struct ipw_priv *p = dev_get_drvdata(d);
1637
1638	sscanf(buf, "%x", &reg);
1639	ipw_write_reg32(p, IPW_INTERNAL_CMD_EVENT, reg);
1640	return strnlen(buf, count);
1641}
1642
1643static DEVICE_ATTR(command_event_reg, S_IWUSR | S_IRUGO,
1644		   show_command_event_reg, store_command_event_reg);
1645
1646static ssize_t show_mem_gpio_reg(struct device *d,
1647				 struct device_attribute *attr, char *buf)
1648{
1649	u32 reg = 0;
1650	struct ipw_priv *p = dev_get_drvdata(d);
1651
1652	reg = ipw_read_reg32(p, 0x301100);
1653	return sprintf(buf, "0x%08x\n", reg);
1654}
1655static ssize_t store_mem_gpio_reg(struct device *d,
1656				  struct device_attribute *attr,
1657				  const char *buf, size_t count)
1658{
1659	u32 reg;
1660	struct ipw_priv *p = dev_get_drvdata(d);
1661
1662	sscanf(buf, "%x", &reg);
1663	ipw_write_reg32(p, 0x301100, reg);
1664	return strnlen(buf, count);
1665}
1666
1667static DEVICE_ATTR(mem_gpio_reg, S_IWUSR | S_IRUGO,
1668		   show_mem_gpio_reg, store_mem_gpio_reg);
1669
1670static ssize_t show_indirect_dword(struct device *d,
1671				   struct device_attribute *attr, char *buf)
1672{
1673	u32 reg = 0;
1674	struct ipw_priv *priv = dev_get_drvdata(d);
1675
1676	if (priv->status & STATUS_INDIRECT_DWORD)
1677		reg = ipw_read_reg32(priv, priv->indirect_dword);
1678	else
1679		reg = 0;
1680
1681	return sprintf(buf, "0x%08x\n", reg);
1682}
1683static ssize_t store_indirect_dword(struct device *d,
1684				    struct device_attribute *attr,
1685				    const char *buf, size_t count)
1686{
1687	struct ipw_priv *priv = dev_get_drvdata(d);
1688
1689	sscanf(buf, "%x", &priv->indirect_dword);
1690	priv->status |= STATUS_INDIRECT_DWORD;
1691	return strnlen(buf, count);
1692}
1693
1694static DEVICE_ATTR(indirect_dword, S_IWUSR | S_IRUGO,
1695		   show_indirect_dword, store_indirect_dword);
1696
1697static ssize_t show_indirect_byte(struct device *d,
1698				  struct device_attribute *attr, char *buf)
1699{
1700	u8 reg = 0;
1701	struct ipw_priv *priv = dev_get_drvdata(d);
1702
1703	if (priv->status & STATUS_INDIRECT_BYTE)
1704		reg = ipw_read_reg8(priv, priv->indirect_byte);
1705	else
1706		reg = 0;
1707
1708	return sprintf(buf, "0x%02x\n", reg);
1709}
1710static ssize_t store_indirect_byte(struct device *d,
1711				   struct device_attribute *attr,
1712				   const char *buf, size_t count)
1713{
1714	struct ipw_priv *priv = dev_get_drvdata(d);
1715
1716	sscanf(buf, "%x", &priv->indirect_byte);
1717	priv->status |= STATUS_INDIRECT_BYTE;
1718	return strnlen(buf, count);
1719}
1720
1721static DEVICE_ATTR(indirect_byte, S_IWUSR | S_IRUGO,
1722		   show_indirect_byte, store_indirect_byte);
1723
1724static ssize_t show_direct_dword(struct device *d,
1725				 struct device_attribute *attr, char *buf)
1726{
1727	u32 reg = 0;
1728	struct ipw_priv *priv = dev_get_drvdata(d);
1729
1730	if (priv->status & STATUS_DIRECT_DWORD)
1731		reg = ipw_read32(priv, priv->direct_dword);
1732	else
1733		reg = 0;
1734
1735	return sprintf(buf, "0x%08x\n", reg);
1736}
1737static ssize_t store_direct_dword(struct device *d,
1738				  struct device_attribute *attr,
1739				  const char *buf, size_t count)
1740{
1741	struct ipw_priv *priv = dev_get_drvdata(d);
1742
1743	sscanf(buf, "%x", &priv->direct_dword);
1744	priv->status |= STATUS_DIRECT_DWORD;
1745	return strnlen(buf, count);
1746}
1747
1748static DEVICE_ATTR(direct_dword, S_IWUSR | S_IRUGO,
1749		   show_direct_dword, store_direct_dword);
1750
1751static int rf_kill_active(struct ipw_priv *priv)
1752{
1753	if (0 == (ipw_read32(priv, 0x30) & 0x10000)) {
1754		priv->status |= STATUS_RF_KILL_HW;
1755		wiphy_rfkill_set_hw_state(priv->ieee->wdev.wiphy, true);
1756	} else {
1757		priv->status &= ~STATUS_RF_KILL_HW;
1758		wiphy_rfkill_set_hw_state(priv->ieee->wdev.wiphy, false);
1759	}
1760
1761	return (priv->status & STATUS_RF_KILL_HW) ? 1 : 0;
1762}
1763
1764static ssize_t show_rf_kill(struct device *d, struct device_attribute *attr,
1765			    char *buf)
1766{
1767	/* 0 - RF kill not enabled
1768	   1 - SW based RF kill active (sysfs)
1769	   2 - HW based RF kill active
1770	   3 - Both HW and SW baed RF kill active */
1771	struct ipw_priv *priv = dev_get_drvdata(d);
1772	int val = ((priv->status & STATUS_RF_KILL_SW) ? 0x1 : 0x0) |
1773	    (rf_kill_active(priv) ? 0x2 : 0x0);
1774	return sprintf(buf, "%i\n", val);
1775}
1776
1777static int ipw_radio_kill_sw(struct ipw_priv *priv, int disable_radio)
1778{
1779	if ((disable_radio ? 1 : 0) ==
1780	    ((priv->status & STATUS_RF_KILL_SW) ? 1 : 0))
1781		return 0;
1782
1783	IPW_DEBUG_RF_KILL("Manual SW RF Kill set to: RADIO  %s\n",
1784			  disable_radio ? "OFF" : "ON");
1785
1786	if (disable_radio) {
1787		priv->status |= STATUS_RF_KILL_SW;
1788
1789		if (priv->workqueue) {
1790			cancel_delayed_work(&priv->request_scan);
1791			cancel_delayed_work(&priv->request_direct_scan);
1792			cancel_delayed_work(&priv->request_passive_scan);
1793			cancel_delayed_work(&priv->scan_event);
1794		}
1795		queue_work(priv->workqueue, &priv->down);
1796	} else {
1797		priv->status &= ~STATUS_RF_KILL_SW;
1798		if (rf_kill_active(priv)) {
1799			IPW_DEBUG_RF_KILL("Can not turn radio back on - "
1800					  "disabled by HW switch\n");
1801			/* Make sure the RF_KILL check timer is running */
1802			cancel_delayed_work(&priv->rf_kill);
1803			queue_delayed_work(priv->workqueue, &priv->rf_kill,
1804					   round_jiffies_relative(2 * HZ));
1805		} else
1806			queue_work(priv->workqueue, &priv->up);
1807	}
1808
1809	return 1;
1810}
1811
1812static ssize_t store_rf_kill(struct device *d, struct device_attribute *attr,
1813			     const char *buf, size_t count)
1814{
1815	struct ipw_priv *priv = dev_get_drvdata(d);
1816
1817	ipw_radio_kill_sw(priv, buf[0] == '1');
1818
1819	return count;
1820}
1821
1822static DEVICE_ATTR(rf_kill, S_IWUSR | S_IRUGO, show_rf_kill, store_rf_kill);
1823
1824static ssize_t show_speed_scan(struct device *d, struct device_attribute *attr,
1825			       char *buf)
1826{
1827	struct ipw_priv *priv = dev_get_drvdata(d);
1828	int pos = 0, len = 0;
1829	if (priv->config & CFG_SPEED_SCAN) {
1830		while (priv->speed_scan[pos] != 0)
1831			len += sprintf(&buf[len], "%d ",
1832				       priv->speed_scan[pos++]);
1833		return len + sprintf(&buf[len], "\n");
1834	}
1835
1836	return sprintf(buf, "0\n");
1837}
1838
1839static ssize_t store_speed_scan(struct device *d, struct device_attribute *attr,
1840				const char *buf, size_t count)
1841{
1842	struct ipw_priv *priv = dev_get_drvdata(d);
1843	int channel, pos = 0;
1844	const char *p = buf;
1845
1846	/* list of space separated channels to scan, optionally ending with 0 */
1847	while ((channel = simple_strtol(p, NULL, 0))) {
1848		if (pos == MAX_SPEED_SCAN - 1) {
1849			priv->speed_scan[pos] = 0;
1850			break;
1851		}
1852
1853		if (libipw_is_valid_channel(priv->ieee, channel))
1854			priv->speed_scan[pos++] = channel;
1855		else
1856			IPW_WARNING("Skipping invalid channel request: %d\n",
1857				    channel);
1858		p = strchr(p, ' ');
1859		if (!p)
1860			break;
1861		while (*p == ' ' || *p == '\t')
1862			p++;
1863	}
1864
1865	if (pos == 0)
1866		priv->config &= ~CFG_SPEED_SCAN;
1867	else {
1868		priv->speed_scan_pos = 0;
1869		priv->config |= CFG_SPEED_SCAN;
1870	}
1871
1872	return count;
1873}
1874
1875static DEVICE_ATTR(speed_scan, S_IWUSR | S_IRUGO, show_speed_scan,
1876		   store_speed_scan);
1877
1878static ssize_t show_net_stats(struct device *d, struct device_attribute *attr,
1879			      char *buf)
1880{
1881	struct ipw_priv *priv = dev_get_drvdata(d);
1882	return sprintf(buf, "%c\n", (priv->config & CFG_NET_STATS) ? '1' : '0');
1883}
1884
1885static ssize_t store_net_stats(struct device *d, struct device_attribute *attr,
1886			       const char *buf, size_t count)
1887{
1888	struct ipw_priv *priv = dev_get_drvdata(d);
1889	if (buf[0] == '1')
1890		priv->config |= CFG_NET_STATS;
1891	else
1892		priv->config &= ~CFG_NET_STATS;
1893
1894	return count;
1895}
1896
1897static DEVICE_ATTR(net_stats, S_IWUSR | S_IRUGO,
1898		   show_net_stats, store_net_stats);
1899
1900static ssize_t show_channels(struct device *d,
1901			     struct device_attribute *attr,
1902			     char *buf)
1903{
1904	struct ipw_priv *priv = dev_get_drvdata(d);
1905	const struct libipw_geo *geo = libipw_get_geo(priv->ieee);
1906	int len = 0, i;
1907
1908	len = sprintf(&buf[len],
1909		      "Displaying %d channels in 2.4Ghz band "
1910		      "(802.11bg):\n", geo->bg_channels);
1911
1912	for (i = 0; i < geo->bg_channels; i++) {
1913		len += sprintf(&buf[len], "%d: BSS%s%s, %s, Band %s.\n",
1914			       geo->bg[i].channel,
1915			       geo->bg[i].flags & LIBIPW_CH_RADAR_DETECT ?
1916			       " (radar spectrum)" : "",
1917			       ((geo->bg[i].flags & LIBIPW_CH_NO_IBSS) ||
1918				(geo->bg[i].flags & LIBIPW_CH_RADAR_DETECT))
1919			       ? "" : ", IBSS",
1920			       geo->bg[i].flags & LIBIPW_CH_PASSIVE_ONLY ?
1921			       "passive only" : "active/passive",
1922			       geo->bg[i].flags & LIBIPW_CH_B_ONLY ?
1923			       "B" : "B/G");
1924	}
1925
1926	len += sprintf(&buf[len],
1927		       "Displaying %d channels in 5.2Ghz band "
1928		       "(802.11a):\n", geo->a_channels);
1929	for (i = 0; i < geo->a_channels; i++) {
1930		len += sprintf(&buf[len], "%d: BSS%s%s, %s.\n",
1931			       geo->a[i].channel,
1932			       geo->a[i].flags & LIBIPW_CH_RADAR_DETECT ?
1933			       " (radar spectrum)" : "",
1934			       ((geo->a[i].flags & LIBIPW_CH_NO_IBSS) ||
1935				(geo->a[i].flags & LIBIPW_CH_RADAR_DETECT))
1936			       ? "" : ", IBSS",
1937			       geo->a[i].flags & LIBIPW_CH_PASSIVE_ONLY ?
1938			       "passive only" : "active/passive");
1939	}
1940
1941	return len;
1942}
1943
1944static DEVICE_ATTR(channels, S_IRUSR, show_channels, NULL);
1945
1946static void notify_wx_assoc_event(struct ipw_priv *priv)
1947{
1948	union iwreq_data wrqu;
1949	wrqu.ap_addr.sa_family = ARPHRD_ETHER;
1950	if (priv->status & STATUS_ASSOCIATED)
1951		memcpy(wrqu.ap_addr.sa_data, priv->bssid, ETH_ALEN);
1952	else
1953		memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
1954	wireless_send_event(priv->net_dev, SIOCGIWAP, &wrqu, NULL);
1955}
1956
1957static void ipw_irq_tasklet(struct ipw_priv *priv)
1958{
1959	u32 inta, inta_mask, handled = 0;
1960	unsigned long flags;
1961	int rc = 0;
1962
1963	spin_lock_irqsave(&priv->irq_lock, flags);
1964
1965	inta = ipw_read32(priv, IPW_INTA_RW);
1966	inta_mask = ipw_read32(priv, IPW_INTA_MASK_R);
1967	inta &= (IPW_INTA_MASK_ALL & inta_mask);
1968
1969	/* Add any cached INTA values that need to be handled */
1970	inta |= priv->isr_inta;
1971
1972	spin_unlock_irqrestore(&priv->irq_lock, flags);
1973
1974	spin_lock_irqsave(&priv->lock, flags);
1975
1976	/* handle all the justifications for the interrupt */
1977	if (inta & IPW_INTA_BIT_RX_TRANSFER) {
1978		ipw_rx(priv);
1979		handled |= IPW_INTA_BIT_RX_TRANSFER;
1980	}
1981
1982	if (inta & IPW_INTA_BIT_TX_CMD_QUEUE) {
1983		IPW_DEBUG_HC("Command completed.\n");
1984		rc = ipw_queue_tx_reclaim(priv, &priv->txq_cmd, -1);
1985		priv->status &= ~STATUS_HCMD_ACTIVE;
1986		wake_up_interruptible(&priv->wait_command_queue);
1987		handled |= IPW_INTA_BIT_TX_CMD_QUEUE;
1988	}
1989
1990	if (inta & IPW_INTA_BIT_TX_QUEUE_1) {
1991		IPW_DEBUG_TX("TX_QUEUE_1\n");
1992		rc = ipw_queue_tx_reclaim(priv, &priv->txq[0], 0);
1993		handled |= IPW_INTA_BIT_TX_QUEUE_1;
1994	}
1995
1996	if (inta & IPW_INTA_BIT_TX_QUEUE_2) {
1997		IPW_DEBUG_TX("TX_QUEUE_2\n");
1998		rc = ipw_queue_tx_reclaim(priv, &priv->txq[1], 1);
1999		handled |= IPW_INTA_BIT_TX_QUEUE_2;
2000	}
2001
2002	if (inta & IPW_INTA_BIT_TX_QUEUE_3) {
2003		IPW_DEBUG_TX("TX_QUEUE_3\n");
2004		rc = ipw_queue_tx_reclaim(priv, &priv->txq[2], 2);
2005		handled |= IPW_INTA_BIT_TX_QUEUE_3;
2006	}
2007
2008	if (inta & IPW_INTA_BIT_TX_QUEUE_4) {
2009		IPW_DEBUG_TX("TX_QUEUE_4\n");
2010		rc = ipw_queue_tx_reclaim(priv, &priv->txq[3], 3);
2011		handled |= IPW_INTA_BIT_TX_QUEUE_4;
2012	}
2013
2014	if (inta & IPW_INTA_BIT_STATUS_CHANGE) {
2015		IPW_WARNING("STATUS_CHANGE\n");
2016		handled |= IPW_INTA_BIT_STATUS_CHANGE;
2017	}
2018
2019	if (inta & IPW_INTA_BIT_BEACON_PERIOD_EXPIRED) {
2020		IPW_WARNING("TX_PERIOD_EXPIRED\n");
2021		handled |= IPW_INTA_BIT_BEACON_PERIOD_EXPIRED;
2022	}
2023
2024	if (inta & IPW_INTA_BIT_SLAVE_MODE_HOST_CMD_DONE) {
2025		IPW_WARNING("HOST_CMD_DONE\n");
2026		handled |= IPW_INTA_BIT_SLAVE_MODE_HOST_CMD_DONE;
2027	}
2028
2029	if (inta & IPW_INTA_BIT_FW_INITIALIZATION_DONE) {
2030		IPW_WARNING("FW_INITIALIZATION_DONE\n");
2031		handled |= IPW_INTA_BIT_FW_INITIALIZATION_DONE;
2032	}
2033
2034	if (inta & IPW_INTA_BIT_FW_CARD_DISABLE_PHY_OFF_DONE) {
2035		IPW_WARNING("PHY_OFF_DONE\n");
2036		handled |= IPW_INTA_BIT_FW_CARD_DISABLE_PHY_OFF_DONE;
2037	}
2038
2039	if (inta & IPW_INTA_BIT_RF_KILL_DONE) {
2040		IPW_DEBUG_RF_KILL("RF_KILL_DONE\n");
2041		priv->status |= STATUS_RF_KILL_HW;
2042		wiphy_rfkill_set_hw_state(priv->ieee->wdev.wiphy, true);
2043		wake_up_interruptible(&priv->wait_command_queue);
2044		priv->status &= ~(STATUS_ASSOCIATED | STATUS_ASSOCIATING);
2045		cancel_delayed_work(&priv->request_scan);
2046		cancel_delayed_work(&priv->request_direct_scan);
2047		cancel_delayed_work(&priv->request_passive_scan);
2048		cancel_delayed_work(&priv->scan_event);
2049		schedule_work(&priv->link_down);
2050		queue_delayed_work(priv->workqueue, &priv->rf_kill, 2 * HZ);
2051		handled |= IPW_INTA_BIT_RF_KILL_DONE;
2052	}
2053
2054	if (inta & IPW_INTA_BIT_FATAL_ERROR) {
2055		IPW_WARNING("Firmware error detected.  Restarting.\n");
2056		if (priv->error) {
2057			IPW_DEBUG_FW("Sysfs 'error' log already exists.\n");
2058			if (ipw_debug_level & IPW_DL_FW_ERRORS) {
2059				struct ipw_fw_error *error =
2060				    ipw_alloc_error_log(priv);
2061				ipw_dump_error_log(priv, error);
2062				kfree(error);
2063			}
2064		} else {
2065			priv->error = ipw_alloc_error_log(priv);
2066			if (priv->error)
2067				IPW_DEBUG_FW("Sysfs 'error' log captured.\n");
2068			else
2069				IPW_DEBUG_FW("Error allocating sysfs 'error' "
2070					     "log.\n");
2071			if (ipw_debug_level & IPW_DL_FW_ERRORS)
2072				ipw_dump_error_log(priv, priv->error);
2073		}
2074
2075		if (priv->ieee->sec.encrypt) {
2076			priv->status &= ~STATUS_ASSOCIATED;
2077			notify_wx_assoc_event(priv);
2078		}
2079
2080		/* Keep the restart process from trying to send host
2081		 * commands by clearing the INIT status bit */
2082		priv->status &= ~STATUS_INIT;
2083
2084		/* Cancel currently queued command. */
2085		priv->status &= ~STATUS_HCMD_ACTIVE;
2086		wake_up_interruptible(&priv->wait_command_queue);
2087
2088		queue_work(priv->workqueue, &priv->adapter_restart);
2089		handled |= IPW_INTA_BIT_FATAL_ERROR;
2090	}
2091
2092	if (inta & IPW_INTA_BIT_PARITY_ERROR) {
2093		IPW_ERROR("Parity error\n");
2094		handled |= IPW_INTA_BIT_PARITY_ERROR;
2095	}
2096
2097	if (handled != inta) {
2098		IPW_ERROR("Unhandled INTA bits 0x%08x\n", inta & ~handled);
2099	}
2100
2101	spin_unlock_irqrestore(&priv->lock, flags);
2102
2103	/* enable all interrupts */
2104	ipw_enable_interrupts(priv);
2105}
2106
2107#define IPW_CMD(x) case IPW_CMD_ ## x : return #x
2108static char *get_cmd_string(u8 cmd)
2109{
2110	switch (cmd) {
2111		IPW_CMD(HOST_COMPLETE);
2112		IPW_CMD(POWER_DOWN);
2113		IPW_CMD(SYSTEM_CONFIG);
2114		IPW_CMD(MULTICAST_ADDRESS);
2115		IPW_CMD(SSID);
2116		IPW_CMD(ADAPTER_ADDRESS);
2117		IPW_CMD(PORT_TYPE);
2118		IPW_CMD(RTS_THRESHOLD);
2119		IPW_CMD(FRAG_THRESHOLD);
2120		IPW_CMD(POWER_MODE);
2121		IPW_CMD(WEP_KEY);
2122		IPW_CMD(TGI_TX_KEY);
2123		IPW_CMD(SCAN_REQUEST);
2124		IPW_CMD(SCAN_REQUEST_EXT);
2125		IPW_CMD(ASSOCIATE);
2126		IPW_CMD(SUPPORTED_RATES);
2127		IPW_CMD(SCAN_ABORT);
2128		IPW_CMD(TX_FLUSH);
2129		IPW_CMD(QOS_PARAMETERS);
2130		IPW_CMD(DINO_CONFIG);
2131		IPW_CMD(RSN_CAPABILITIES);
2132		IPW_CMD(RX_KEY);
2133		IPW_CMD(CARD_DISABLE);
2134		IPW_CMD(SEED_NUMBER);
2135		IPW_CMD(TX_POWER);
2136		IPW_CMD(COUNTRY_INFO);
2137		IPW_CMD(AIRONET_INFO);
2138		IPW_CMD(AP_TX_POWER);
2139		IPW_CMD(CCKM_INFO);
2140		IPW_CMD(CCX_VER_INFO);
2141		IPW_CMD(SET_CALIBRATION);
2142		IPW_CMD(SENSITIVITY_CALIB);
2143		IPW_CMD(RETRY_LIMIT);
2144		IPW_CMD(IPW_PRE_POWER_DOWN);
2145		IPW_CMD(VAP_BEACON_TEMPLATE);
2146		IPW_CMD(VAP_DTIM_PERIOD);
2147		IPW_CMD(EXT_SUPPORTED_RATES);
2148		IPW_CMD(VAP_LOCAL_TX_PWR_CONSTRAINT);
2149		IPW_CMD(VAP_QUIET_INTERVALS);
2150		IPW_CMD(VAP_CHANNEL_SWITCH);
2151		IPW_CMD(VAP_MANDATORY_CHANNELS);
2152		IPW_CMD(VAP_CELL_PWR_LIMIT);
2153		IPW_CMD(VAP_CF_PARAM_SET);
2154		IPW_CMD(VAP_SET_BEACONING_STATE);
2155		IPW_CMD(MEASUREMENT);
2156		IPW_CMD(POWER_CAPABILITY);
2157		IPW_CMD(SUPPORTED_CHANNELS);
2158		IPW_CMD(TPC_REPORT);
2159		IPW_CMD(WME_INFO);
2160		IPW_CMD(PRODUCTION_COMMAND);
2161	default:
2162		return "UNKNOWN";
2163	}
2164}
2165
2166#define HOST_COMPLETE_TIMEOUT HZ
2167
2168static int __ipw_send_cmd(struct ipw_priv *priv, struct host_cmd *cmd)
2169{
2170	int rc = 0;
2171	unsigned long flags;
2172
2173	spin_lock_irqsave(&priv->lock, flags);
2174	if (priv->status & STATUS_HCMD_ACTIVE) {
2175		IPW_ERROR("Failed to send %s: Already sending a command.\n",
2176			  get_cmd_string(cmd->cmd));
2177		spin_unlock_irqrestore(&priv->lock, flags);
2178		return -EAGAIN;
2179	}
2180
2181	priv->status |= STATUS_HCMD_ACTIVE;
2182
2183	if (priv->cmdlog) {
2184		priv->cmdlog[priv->cmdlog_pos].jiffies = jiffies;
2185		priv->cmdlog[priv->cmdlog_pos].cmd.cmd = cmd->cmd;
2186		priv->cmdlog[priv->cmdlog_pos].cmd.len = cmd->len;
2187		memcpy(priv->cmdlog[priv->cmdlog_pos].cmd.param, cmd->param,
2188		       cmd->len);
2189		priv->cmdlog[priv->cmdlog_pos].retcode = -1;
2190	}
2191
2192	IPW_DEBUG_HC("%s command (#%d) %d bytes: 0x%08X\n",
2193		     get_cmd_string(cmd->cmd), cmd->cmd, cmd->len,
2194		     priv->status);
2195
2196#ifndef DEBUG_CMD_WEP_KEY
2197	if (cmd->cmd == IPW_CMD_WEP_KEY)
2198		IPW_DEBUG_HC("WEP_KEY command masked out for secure.\n");
2199	else
2200#endif
2201		printk_buf(IPW_DL_HOST_COMMAND, (u8 *) cmd->param, cmd->len);
2202
2203	rc = ipw_queue_tx_hcmd(priv, cmd->cmd, cmd->param, cmd->len, 0);
2204	if (rc) {
2205		priv->status &= ~STATUS_HCMD_ACTIVE;
2206		IPW_ERROR("Failed to send %s: Reason %d\n",
2207			  get_cmd_string(cmd->cmd), rc);
2208		spin_unlock_irqrestore(&priv->lock, flags);
2209		goto exit;
2210	}
2211	spin_unlock_irqrestore(&priv->lock, flags);
2212
2213	rc = wait_event_interruptible_timeout(priv->wait_command_queue,
2214					      !(priv->
2215						status & STATUS_HCMD_ACTIVE),
2216					      HOST_COMPLETE_TIMEOUT);
2217	if (rc == 0) {
2218		spin_lock_irqsave(&priv->lock, flags);
2219		if (priv->status & STATUS_HCMD_ACTIVE) {
2220			IPW_ERROR("Failed to send %s: Command timed out.\n",
2221				  get_cmd_string(cmd->cmd));
2222			priv->status &= ~STATUS_HCMD_ACTIVE;
2223			spin_unlock_irqrestore(&priv->lock, flags);
2224			rc = -EIO;
2225			goto exit;
2226		}
2227		spin_unlock_irqrestore(&priv->lock, flags);
2228	} else
2229		rc = 0;
2230
2231	if (priv->status & STATUS_RF_KILL_HW) {
2232		IPW_ERROR("Failed to send %s: Aborted due to RF kill switch.\n",
2233			  get_cmd_string(cmd->cmd));
2234		rc = -EIO;
2235		goto exit;
2236	}
2237
2238      exit:
2239	if (priv->cmdlog) {
2240		priv->cmdlog[priv->cmdlog_pos++].retcode = rc;
2241		priv->cmdlog_pos %= priv->cmdlog_len;
2242	}
2243	return rc;
2244}
2245
2246static int ipw_send_cmd_simple(struct ipw_priv *priv, u8 command)
2247{
2248	struct host_cmd cmd = {
2249		.cmd = command,
2250	};
2251
2252	return __ipw_send_cmd(priv, &cmd);
2253}
2254
2255static int ipw_send_cmd_pdu(struct ipw_priv *priv, u8 command, u8 len,
2256			    void *data)
2257{
2258	struct host_cmd cmd = {
2259		.cmd = command,
2260		.len = len,
2261		.param = data,
2262	};
2263
2264	return __ipw_send_cmd(priv, &cmd);
2265}
2266
2267static int ipw_send_host_complete(struct ipw_priv *priv)
2268{
2269	if (!priv) {
2270		IPW_ERROR("Invalid args\n");
2271		return -1;
2272	}
2273
2274	return ipw_send_cmd_simple(priv, IPW_CMD_HOST_COMPLETE);
2275}
2276
2277static int ipw_send_system_config(struct ipw_priv *priv)
2278{
2279	return ipw_send_cmd_pdu(priv, IPW_CMD_SYSTEM_CONFIG,
2280				sizeof(priv->sys_config),
2281				&priv->sys_config);
2282}
2283
2284static int ipw_send_ssid(struct ipw_priv *priv, u8 * ssid, int len)
2285{
2286	if (!priv || !ssid) {
2287		IPW_ERROR("Invalid args\n");
2288		return -1;
2289	}
2290
2291	return ipw_send_cmd_pdu(priv, IPW_CMD_SSID, min(len, IW_ESSID_MAX_SIZE),
2292				ssid);
2293}
2294
2295static int ipw_send_adapter_address(struct ipw_priv *priv, u8 * mac)
2296{
2297	if (!priv || !mac) {
2298		IPW_ERROR("Invalid args\n");
2299		return -1;
2300	}
2301
2302	IPW_DEBUG_INFO("%s: Setting MAC to %pM\n",
2303		       priv->net_dev->name, mac);
2304
2305	return ipw_send_cmd_pdu(priv, IPW_CMD_ADAPTER_ADDRESS, ETH_ALEN, mac);
2306}
2307
2308/*
2309 * NOTE: This must be executed from our workqueue as it results in udelay
2310 * being called which may corrupt the keyboard if executed on default
2311 * workqueue
2312 */
2313static void ipw_adapter_restart(void *adapter)
2314{
2315	struct ipw_priv *priv = adapter;
2316
2317	if (priv->status & STATUS_RF_KILL_MASK)
2318		return;
2319
2320	ipw_down(priv);
2321
2322	if (priv->assoc_network &&
2323	    (priv->assoc_network->capability & WLAN_CAPABILITY_IBSS))
2324		ipw_remove_current_network(priv);
2325
2326	if (ipw_up(priv)) {
2327		IPW_ERROR("Failed to up device\n");
2328		return;
2329	}
2330}
2331
2332static void ipw_bg_adapter_restart(struct work_struct *work)
2333{
2334	struct ipw_priv *priv =
2335		container_of(work, struct ipw_priv, adapter_restart);
2336	mutex_lock(&priv->mutex);
2337	ipw_adapter_restart(priv);
2338	mutex_unlock(&priv->mutex);
2339}
2340
2341static void ipw_abort_scan(struct ipw_priv *priv);
2342
2343#define IPW_SCAN_CHECK_WATCHDOG	(5 * HZ)
2344
2345static void ipw_scan_check(void *data)
2346{
2347	struct ipw_priv *priv = data;
2348
2349	if (priv->status & STATUS_SCAN_ABORTING) {
2350		IPW_DEBUG_SCAN("Scan completion watchdog resetting "
2351			       "adapter after (%dms).\n",
2352			       jiffies_to_msecs(IPW_SCAN_CHECK_WATCHDOG));
2353		queue_work(priv->workqueue, &priv->adapter_restart);
2354	} else if (priv->status & STATUS_SCANNING) {
2355		IPW_DEBUG_SCAN("Scan completion watchdog aborting scan "
2356			       "after (%dms).\n",
2357			       jiffies_to_msecs(IPW_SCAN_CHECK_WATCHDOG));
2358		ipw_abort_scan(priv);
2359		queue_delayed_work(priv->workqueue, &priv->scan_check, HZ);
2360	}
2361}
2362
2363static void ipw_bg_scan_check(struct work_struct *work)
2364{
2365	struct ipw_priv *priv =
2366		container_of(work, struct ipw_priv, scan_check.work);
2367	mutex_lock(&priv->mutex);
2368	ipw_scan_check(priv);
2369	mutex_unlock(&priv->mutex);
2370}
2371
2372static int ipw_send_scan_request_ext(struct ipw_priv *priv,
2373				     struct ipw_scan_request_ext *request)
2374{
2375	return ipw_send_cmd_pdu(priv, IPW_CMD_SCAN_REQUEST_EXT,
2376				sizeof(*request), request);
2377}
2378
2379static int ipw_send_scan_abort(struct ipw_priv *priv)
2380{
2381	if (!priv) {
2382		IPW_ERROR("Invalid args\n");
2383		return -1;
2384	}
2385
2386	return ipw_send_cmd_simple(priv, IPW_CMD_SCAN_ABORT);
2387}
2388
2389static int ipw_set_sensitivity(struct ipw_priv *priv, u16 sens)
2390{
2391	struct ipw_sensitivity_calib calib = {
2392		.beacon_rssi_raw = cpu_to_le16(sens),
2393	};
2394
2395	return ipw_send_cmd_pdu(priv, IPW_CMD_SENSITIVITY_CALIB, sizeof(calib),
2396				&calib);
2397}
2398
2399static int ipw_send_associate(struct ipw_priv *priv,
2400			      struct ipw_associate *associate)
2401{
2402	if (!priv || !associate) {
2403		IPW_ERROR("Invalid args\n");
2404		return -1;
2405	}
2406
2407	return ipw_send_cmd_pdu(priv, IPW_CMD_ASSOCIATE, sizeof(*associate),
2408				associate);
2409}
2410
2411static int ipw_send_supported_rates(struct ipw_priv *priv,
2412				    struct ipw_supported_rates *rates)
2413{
2414	if (!priv || !rates) {
2415		IPW_ERROR("Invalid args\n");
2416		return -1;
2417	}
2418
2419	return ipw_send_cmd_pdu(priv, IPW_CMD_SUPPORTED_RATES, sizeof(*rates),
2420				rates);
2421}
2422
2423static int ipw_set_random_seed(struct ipw_priv *priv)
2424{
2425	u32 val;
2426
2427	if (!priv) {
2428		IPW_ERROR("Invalid args\n");
2429		return -1;
2430	}
2431
2432	get_random_bytes(&val, sizeof(val));
2433
2434	return ipw_send_cmd_pdu(priv, IPW_CMD_SEED_NUMBER, sizeof(val), &val);
2435}
2436
2437static int ipw_send_card_disable(struct ipw_priv *priv, u32 phy_off)
2438{
2439	__le32 v = cpu_to_le32(phy_off);
2440	if (!priv) {
2441		IPW_ERROR("Invalid args\n");
2442		return -1;
2443	}
2444
2445	return ipw_send_cmd_pdu(priv, IPW_CMD_CARD_DISABLE, sizeof(v), &v);
2446}
2447
2448static int ipw_send_tx_power(struct ipw_priv *priv, struct ipw_tx_power *power)
2449{
2450	if (!priv || !power) {
2451		IPW_ERROR("Invalid args\n");
2452		return -1;
2453	}
2454
2455	return ipw_send_cmd_pdu(priv, IPW_CMD_TX_POWER, sizeof(*power), power);
2456}
2457
2458static int ipw_set_tx_power(struct ipw_priv *priv)
2459{
2460	const struct libipw_geo *geo = libipw_get_geo(priv->ieee);
2461	struct ipw_tx_power tx_power;
2462	s8 max_power;
2463	int i;
2464
2465	memset(&tx_power, 0, sizeof(tx_power));
2466
2467	/* configure device for 'G' band */
2468	tx_power.ieee_mode = IPW_G_MODE;
2469	tx_power.num_channels = geo->bg_channels;
2470	for (i = 0; i < geo->bg_channels; i++) {
2471		max_power = geo->bg[i].max_power;
2472		tx_power.channels_tx_power[i].channel_number =
2473		    geo->bg[i].channel;
2474		tx_power.channels_tx_power[i].tx_power = max_power ?
2475		    min(max_power, priv->tx_power) : priv->tx_power;
2476	}
2477	if (ipw_send_tx_power(priv, &tx_power))
2478		return -EIO;
2479
2480	/* configure device to also handle 'B' band */
2481	tx_power.ieee_mode = IPW_B_MODE;
2482	if (ipw_send_tx_power(priv, &tx_power))
2483		return -EIO;
2484
2485	/* configure device to also handle 'A' band */
2486	if (priv->ieee->abg_true) {
2487		tx_power.ieee_mode = IPW_A_MODE;
2488		tx_power.num_channels = geo->a_channels;
2489		for (i = 0; i < tx_power.num_channels; i++) {
2490			max_power = geo->a[i].max_power;
2491			tx_power.channels_tx_power[i].channel_number =
2492			    geo->a[i].channel;
2493			tx_power.channels_tx_power[i].tx_power = max_power ?
2494			    min(max_power, priv->tx_power) : priv->tx_power;
2495		}
2496		if (ipw_send_tx_power(priv, &tx_power))
2497			return -EIO;
2498	}
2499	return 0;
2500}
2501
2502static int ipw_send_rts_threshold(struct ipw_priv *priv, u16 rts)
2503{
2504	struct ipw_rts_threshold rts_threshold = {
2505		.rts_threshold = cpu_to_le16(rts),
2506	};
2507
2508	if (!priv) {
2509		IPW_ERROR("Invalid args\n");
2510		return -1;
2511	}
2512
2513	return ipw_send_cmd_pdu(priv, IPW_CMD_RTS_THRESHOLD,
2514				sizeof(rts_threshold), &rts_threshold);
2515}
2516
2517static int ipw_send_frag_threshold(struct ipw_priv *priv, u16 frag)
2518{
2519	struct ipw_frag_threshold frag_threshold = {
2520		.frag_threshold = cpu_to_le16(frag),
2521	};
2522
2523	if (!priv) {
2524		IPW_ERROR("Invalid args\n");
2525		return -1;
2526	}
2527
2528	return ipw_send_cmd_pdu(priv, IPW_CMD_FRAG_THRESHOLD,
2529				sizeof(frag_threshold), &frag_threshold);
2530}
2531
2532static int ipw_send_power_mode(struct ipw_priv *priv, u32 mode)
2533{
2534	__le32 param;
2535
2536	if (!priv) {
2537		IPW_ERROR("Invalid args\n");
2538		return -1;
2539	}
2540
2541	/* If on battery, set to 3, if AC set to CAM, else user
2542	 * level */
2543	switch (mode) {
2544	case IPW_POWER_BATTERY:
2545		param = cpu_to_le32(IPW_POWER_INDEX_3);
2546		break;
2547	case IPW_POWER_AC:
2548		param = cpu_to_le32(IPW_POWER_MODE_CAM);
2549		break;
2550	default:
2551		param = cpu_to_le32(mode);
2552		break;
2553	}
2554
2555	return ipw_send_cmd_pdu(priv, IPW_CMD_POWER_MODE, sizeof(param),
2556				&param);
2557}
2558
2559static int ipw_send_retry_limit(struct ipw_priv *priv, u8 slimit, u8 llimit)
2560{
2561	struct ipw_retry_limit retry_limit = {
2562		.short_retry_limit = slimit,
2563		.long_retry_limit = llimit
2564	};
2565
2566	if (!priv) {
2567		IPW_ERROR("Invalid args\n");
2568		return -1;
2569	}
2570
2571	return ipw_send_cmd_pdu(priv, IPW_CMD_RETRY_LIMIT, sizeof(retry_limit),
2572				&retry_limit);
2573}
2574
2575/*
2576 * The IPW device contains a Microwire compatible EEPROM that stores
2577 * various data like the MAC address.  Usually the firmware has exclusive
2578 * access to the eeprom, but during device initialization (before the
2579 * device driver has sent the HostComplete command to the firmware) the
2580 * device driver has read access to the EEPROM by way of indirect addressing
2581 * through a couple of memory mapped registers.
2582 *
2583 * The following is a simplified implementation for pulling data out of the
2584 * the eeprom, along with some helper functions to find information in
2585 * the per device private data's copy of the eeprom.
2586 *
2587 * NOTE: To better understand how these functions work (i.e what is a chip
2588 *       select and why do have to keep driving the eeprom clock?), read
2589 *       just about any data sheet for a Microwire compatible EEPROM.
2590 */
2591
2592/* write a 32 bit value into the indirect accessor register */
2593static inline void eeprom_write_reg(struct ipw_priv *p, u32 data)
2594{
2595	ipw_write_reg32(p, FW_MEM_REG_EEPROM_ACCESS, data);
2596
2597	/* the eeprom requires some time to complete the operation */
2598	udelay(p->eeprom_delay);
2599}
2600
2601/* perform a chip select operation */
2602static void eeprom_cs(struct ipw_priv *priv)
2603{
2604	eeprom_write_reg(priv, 0);
2605	eeprom_write_reg(priv, EEPROM_BIT_CS);
2606	eeprom_write_reg(priv, EEPROM_BIT_CS | EEPROM_BIT_SK);
2607	eeprom_write_reg(priv, EEPROM_BIT_CS);
2608}
2609
2610/* perform a chip select operation */
2611static void eeprom_disable_cs(struct ipw_priv *priv)
2612{
2613	eeprom_write_reg(priv, EEPROM_BIT_CS);
2614	eeprom_write_reg(priv, 0);
2615	eeprom_write_reg(priv, EEPROM_BIT_SK);
2616}
2617
2618/* push a single bit down to the eeprom */
2619static inline void eeprom_write_bit(struct ipw_priv *p, u8 bit)
2620{
2621	int d = (bit ? EEPROM_BIT_DI : 0);
2622	eeprom_write_reg(p, EEPROM_BIT_CS | d);
2623	eeprom_write_reg(p, EEPROM_BIT_CS | d | EEPROM_BIT_SK);
2624}
2625
2626/* push an opcode followed by an address down to the eeprom */
2627static void eeprom_op(struct ipw_priv *priv, u8 op, u8 addr)
2628{
2629	int i;
2630
2631	eeprom_cs(priv);
2632	eeprom_write_bit(priv, 1);
2633	eeprom_write_bit(priv, op & 2);
2634	eeprom_write_bit(priv, op & 1);
2635	for (i = 7; i >= 0; i--) {
2636		eeprom_write_bit(priv, addr & (1 << i));
2637	}
2638}
2639
2640/* pull 16 bits off the eeprom, one bit at a time */
2641static u16 eeprom_read_u16(struct ipw_priv *priv, u8 addr)
2642{
2643	int i;
2644	u16 r = 0;
2645
2646	/* Send READ Opcode */
2647	eeprom_op(priv, EEPROM_CMD_READ, addr);
2648
2649	/* Send dummy bit */
2650	eeprom_write_reg(priv, EEPROM_BIT_CS);
2651
2652	/* Read the byte off the eeprom one bit at a time */
2653	for (i = 0; i < 16; i++) {
2654		u32 data = 0;
2655		eeprom_write_reg(priv, EEPROM_BIT_CS | EEPROM_BIT_SK);
2656		eeprom_write_reg(priv, EEPROM_BIT_CS);
2657		data = ipw_read_reg32(priv, FW_MEM_REG_EEPROM_ACCESS);
2658		r = (r << 1) | ((data & EEPROM_BIT_DO) ? 1 : 0);
2659	}
2660
2661	/* Send another dummy bit */
2662	eeprom_write_reg(priv, 0);
2663	eeprom_disable_cs(priv);
2664
2665	return r;
2666}
2667
2668/* helper function for pulling the mac address out of the private */
2669/* data's copy of the eeprom data                                 */
2670static void eeprom_parse_mac(struct ipw_priv *priv, u8 * mac)
2671{
2672	memcpy(mac, &priv->eeprom[EEPROM_MAC_ADDRESS], 6);
2673}
2674
2675/*
2676 * Either the device driver (i.e. the host) or the firmware can
2677 * load eeprom data into the designated region in SRAM.  If neither
2678 * happens then the FW will shutdown with a fatal error.
2679 *
2680 * In order to signal the FW to load the EEPROM, the EEPROM_LOAD_DISABLE
2681 * bit needs region of shared SRAM needs to be non-zero.
2682 */
2683static void ipw_eeprom_init_sram(struct ipw_priv *priv)
2684{
2685	int i;
2686	__le16 *eeprom = (__le16 *) priv->eeprom;
2687
2688	IPW_DEBUG_TRACE(">>\n");
2689
2690	/* read entire contents of eeprom into private buffer */
2691	for (i = 0; i < 128; i++)
2692		eeprom[i] = cpu_to_le16(eeprom_read_u16(priv, (u8) i));
2693
2694	/*
2695	   If the data looks correct, then copy it to our private
2696	   copy.  Otherwise let the firmware know to perform the operation
2697	   on its own.
2698	 */
2699	if (priv->eeprom[EEPROM_VERSION] != 0) {
2700		IPW_DEBUG_INFO("Writing EEPROM data into SRAM\n");
2701
2702		/* write the eeprom data to sram */
2703		for (i = 0; i < IPW_EEPROM_IMAGE_SIZE; i++)
2704			ipw_write8(priv, IPW_EEPROM_DATA + i, priv->eeprom[i]);
2705
2706		/* Do not load eeprom data on fatal error or suspend */
2707		ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 0);
2708	} else {
2709		IPW_DEBUG_INFO("Enabling FW initializationg of SRAM\n");
2710
2711		/* Load eeprom data on fatal error or suspend */
2712		ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 1);
2713	}
2714
2715	IPW_DEBUG_TRACE("<<\n");
2716}
2717
2718static void ipw_zero_memory(struct ipw_priv *priv, u32 start, u32 count)
2719{
2720	count >>= 2;
2721	if (!count)
2722		return;
2723	_ipw_write32(priv, IPW_AUTOINC_ADDR, start);
2724	while (count--)
2725		_ipw_write32(priv, IPW_AUTOINC_DATA, 0);
2726}
2727
2728static inline void ipw_fw_dma_reset_command_blocks(struct ipw_priv *priv)
2729{
2730	ipw_zero_memory(priv, IPW_SHARED_SRAM_DMA_CONTROL,
2731			CB_NUMBER_OF_ELEMENTS_SMALL *
2732			sizeof(struct command_block));
2733}
2734
2735static int ipw_fw_dma_enable(struct ipw_priv *priv)
2736{				/* start dma engine but no transfers yet */
2737
2738	IPW_DEBUG_FW(">> :\n");
2739
2740	/* Start the dma */
2741	ipw_fw_dma_reset_command_blocks(priv);
2742
2743	/* Write CB base address */
2744	ipw_write_reg32(priv, IPW_DMA_I_CB_BASE, IPW_SHARED_SRAM_DMA_CONTROL);
2745
2746	IPW_DEBUG_FW("<< :\n");
2747	return 0;
2748}
2749
2750static void ipw_fw_dma_abort(struct ipw_priv *priv)
2751{
2752	u32 control = 0;
2753
2754	IPW_DEBUG_FW(">> :\n");
2755
2756	/* set the Stop and Abort bit */
2757	control = DMA_CONTROL_SMALL_CB_CONST_VALUE | DMA_CB_STOP_AND_ABORT;
2758	ipw_write_reg32(priv, IPW_DMA_I_DMA_CONTROL, control);
2759	priv->sram_desc.last_cb_index = 0;
2760
2761	IPW_DEBUG_FW("<<\n");
2762}
2763
2764static int ipw_fw_dma_write_command_block(struct ipw_priv *priv, int index,
2765					  struct command_block *cb)
2766{
2767	u32 address =
2768	    IPW_SHARED_SRAM_DMA_CONTROL +
2769	    (sizeof(struct command_block) * index);
2770	IPW_DEBUG_FW(">> :\n");
2771
2772	ipw_write_indirect(priv, address, (u8 *) cb,
2773			   (int)sizeof(struct command_block));
2774
2775	IPW_DEBUG_FW("<< :\n");
2776	return 0;
2777
2778}
2779
2780static int ipw_fw_dma_kick(struct ipw_priv *priv)
2781{
2782	u32 control = 0;
2783	u32 index = 0;
2784
2785	IPW_DEBUG_FW(">> :\n");
2786
2787	for (index = 0; index < priv->sram_desc.last_cb_index; index++)
2788		ipw_fw_dma_write_command_block(priv, index,
2789					       &priv->sram_desc.cb_list[index]);
2790
2791	/* Enable the DMA in the CSR register */
2792	ipw_clear_bit(priv, IPW_RESET_REG,
2793		      IPW_RESET_REG_MASTER_DISABLED |
2794		      IPW_RESET_REG_STOP_MASTER);
2795
2796	/* Set the Start bit. */
2797	control = DMA_CONTROL_SMALL_CB_CONST_VALUE | DMA_CB_START;
2798	ipw_write_reg32(priv, IPW_DMA_I_DMA_CONTROL, control);
2799
2800	IPW_DEBUG_FW("<< :\n");
2801	return 0;
2802}
2803
2804static void ipw_fw_dma_dump_command_block(struct ipw_priv *priv)
2805{
2806	u32 address;
2807	u32 register_value = 0;
2808	u32 cb_fields_address = 0;
2809
2810	IPW_DEBUG_FW(">> :\n");
2811	address = ipw_read_reg32(priv, IPW_DMA_I_CURRENT_CB);
2812	IPW_DEBUG_FW_INFO("Current CB is 0x%x\n", address);
2813
2814	/* Read the DMA Controlor register */
2815	register_value = ipw_read_reg32(priv, IPW_DMA_I_DMA_CONTROL);
2816	IPW_DEBUG_FW_INFO("IPW_DMA_I_DMA_CONTROL is 0x%x\n", register_value);
2817
2818	/* Print the CB values */
2819	cb_fields_address = address;
2820	register_value = ipw_read_reg32(priv, cb_fields_address);
2821	IPW_DEBUG_FW_INFO("Current CB Control Field is 0x%x\n", register_value);
2822
2823	cb_fields_address += sizeof(u32);
2824	register_value = ipw_read_reg32(priv, cb_fields_address);
2825	IPW_DEBUG_FW_INFO("Current CB Source Field is 0x%x\n", register_value);
2826
2827	cb_fields_address += sizeof(u32);
2828	register_value = ipw_read_reg32(priv, cb_fields_address);
2829	IPW_DEBUG_FW_INFO("Current CB Destination Field is 0x%x\n",
2830			  register_value);
2831
2832	cb_fields_address += sizeof(u32);
2833	register_value = ipw_read_reg32(priv, cb_fields_address);
2834	IPW_DEBUG_FW_INFO("Current CB Status Field is 0x%x\n", register_value);
2835
2836	IPW_DEBUG_FW(">> :\n");
2837}
2838
2839static int ipw_fw_dma_command_block_index(struct ipw_priv *priv)
2840{
2841	u32 current_cb_address = 0;
2842	u32 current_cb_index = 0;
2843
2844	IPW_DEBUG_FW("<< :\n");
2845	current_cb_address = ipw_read_reg32(priv, IPW_DMA_I_CURRENT_CB);
2846
2847	current_cb_index = (current_cb_address - IPW_SHARED_SRAM_DMA_CONTROL) /
2848	    sizeof(struct command_block);
2849
2850	IPW_DEBUG_FW_INFO("Current CB index 0x%x address = 0x%X\n",
2851			  current_cb_index, current_cb_address);
2852
2853	IPW_DEBUG_FW(">> :\n");
2854	return current_cb_index;
2855
2856}
2857
2858static int ipw_fw_dma_add_command_block(struct ipw_priv *priv,
2859					u32 src_address,
2860					u32 dest_address,
2861					u32 length,
2862					int interrupt_enabled, int is_last)
2863{
2864
2865	u32 control = CB_VALID | CB_SRC_LE | CB_DEST_LE | CB_SRC_AUTOINC |
2866	    CB_SRC_IO_GATED | CB_DEST_AUTOINC | CB_SRC_SIZE_LONG |
2867	    CB_DEST_SIZE_LONG;
2868	struct command_block *cb;
2869	u32 last_cb_element = 0;
2870
2871	IPW_DEBUG_FW_INFO("src_address=0x%x dest_address=0x%x length=0x%x\n",
2872			  src_address, dest_address, length);
2873
2874	if (priv->sram_desc.last_cb_index >= CB_NUMBER_OF_ELEMENTS_SMALL)
2875		return -1;
2876
2877	last_cb_element = priv->sram_desc.last_cb_index;
2878	cb = &priv->sram_desc.cb_list[last_cb_element];
2879	priv->sram_desc.last_cb_index++;
2880
2881	/* Calculate the new CB control word */
2882	if (interrupt_enabled)
2883		control |= CB_INT_ENABLED;
2884
2885	if (is_last)
2886		control |= CB_LAST_VALID;
2887
2888	control |= length;
2889
2890	/* Calculate the CB Element's checksum value */
2891	cb->status = control ^ src_address ^ dest_address;
2892
2893	/* Copy the Source and Destination addresses */
2894	cb->dest_addr = dest_address;
2895	cb->source_addr = src_address;
2896
2897	/* Copy the Control Word last */
2898	cb->control = control;
2899
2900	return 0;
2901}
2902
2903static int ipw_fw_dma_add_buffer(struct ipw_priv *priv, dma_addr_t *src_address,
2904				 int nr, u32 dest_address, u32 len)
2905{
2906	int ret, i;
2907	u32 size;
2908
2909	IPW_DEBUG_FW(">>\n");
2910	IPW_DEBUG_FW_INFO("nr=%d dest_address=0x%x len=0x%x\n",
2911			  nr, dest_address, len);
2912
2913	for (i = 0; i < nr; i++) {
2914		size = min_t(u32, len - i * CB_MAX_LENGTH, CB_MAX_LENGTH);
2915		ret = ipw_fw_dma_add_command_block(priv, src_address[i],
2916						   dest_address +
2917						   i * CB_MAX_LENGTH, size,
2918						   0, 0);
2919		if (ret) {
2920			IPW_DEBUG_FW_INFO(": Failed\n");
2921			return -1;
2922		} else
2923			IPW_DEBUG_FW_INFO(": Added new cb\n");
2924	}
2925
2926	IPW_DEBUG_FW("<<\n");
2927	return 0;
2928}
2929
2930static int ipw_fw_dma_wait(struct ipw_priv *priv)
2931{
2932	u32 current_index = 0, previous_index;
2933	u32 watchdog = 0;
2934
2935	IPW_DEBUG_FW(">> :\n");
2936
2937	current_index = ipw_fw_dma_command_block_index(priv);
2938	IPW_DEBUG_FW_INFO("sram_desc.last_cb_index:0x%08X\n",
2939			  (int)priv->sram_desc.last_cb_index);
2940
2941	while (current_index < priv->sram_desc.last_cb_index) {
2942		udelay(50);
2943		previous_index = current_index;
2944		current_index = ipw_fw_dma_command_block_index(priv);
2945
2946		if (previous_index < current_index) {
2947			watchdog = 0;
2948			continue;
2949		}
2950		if (++watchdog > 400) {
2951			IPW_DEBUG_FW_INFO("Timeout\n");
2952			ipw_fw_dma_dump_command_block(priv);
2953			ipw_fw_dma_abort(priv);
2954			return -1;
2955		}
2956	}
2957
2958	ipw_fw_dma_abort(priv);
2959
2960	/*Disable the DMA in the CSR register */
2961	ipw_set_bit(priv, IPW_RESET_REG,
2962		    IPW_RESET_REG_MASTER_DISABLED | IPW_RESET_REG_STOP_MASTER);
2963
2964	IPW_DEBUG_FW("<< dmaWaitSync\n");
2965	return 0;
2966}
2967
2968static void ipw_remove_current_network(struct ipw_priv *priv)
2969{
2970	struct list_head *element, *safe;
2971	struct libipw_network *network = NULL;
2972	unsigned long flags;
2973
2974	spin_lock_irqsave(&priv->ieee->lock, flags);
2975	list_for_each_safe(element, safe, &priv->ieee->network_list) {
2976		network = list_entry(element, struct libipw_network, list);
2977		if (!memcmp(network->bssid, priv->bssid, ETH_ALEN)) {
2978			list_del(element);
2979			list_add_tail(&network->list,
2980				      &priv->ieee->network_free_list);
2981		}
2982	}
2983	spin_unlock_irqrestore(&priv->ieee->lock, flags);
2984}
2985
2986/**
2987 * Check that card is still alive.
2988 * Reads debug register from domain0.
2989 * If card is present, pre-defined value should
2990 * be found there.
2991 *
2992 * @param priv
2993 * @return 1 if card is present, 0 otherwise
2994 */
2995static inline int ipw_alive(struct ipw_priv *priv)
2996{
2997	return ipw_read32(priv, 0x90) == 0xd55555d5;
2998}
2999
3000/* timeout in msec, attempted in 10-msec quanta */
3001static int ipw_poll_bit(struct ipw_priv *priv, u32 addr, u32 mask,
3002			       int timeout)
3003{
3004	int i = 0;
3005
3006	do {
3007		if ((ipw_read32(priv, addr) & mask) == mask)
3008			return i;
3009		mdelay(10);
3010		i += 10;
3011	} while (i < timeout);
3012
3013	return -ETIME;
3014}
3015
3016/* These functions load the firmware and micro code for the operation of
3017 * the ipw hardware.  It assumes the buffer has all the bits for the
3018 * image and the caller is handling the memory allocation and clean up.
3019 */
3020
3021static int ipw_stop_master(struct ipw_priv *priv)
3022{
3023	int rc;
3024
3025	IPW_DEBUG_TRACE(">>\n");
3026	/* stop master. typical delay - 0 */
3027	ipw_set_bit(priv, IPW_RESET_REG, IPW_RESET_REG_STOP_MASTER);
3028
3029	/* timeout is in msec, polled in 10-msec quanta */
3030	rc = ipw_poll_bit(priv, IPW_RESET_REG,
3031			  IPW_RESET_REG_MASTER_DISABLED, 100);
3032	if (rc < 0) {
3033		IPW_ERROR("wait for stop master failed after 100ms\n");
3034		return -1;
3035	}
3036
3037	IPW_DEBUG_INFO("stop master %dms\n", rc);
3038
3039	return rc;
3040}
3041
3042static void ipw_arc_release(struct ipw_priv *priv)
3043{
3044	IPW_DEBUG_TRACE(">>\n");
3045	mdelay(5);
3046
3047	ipw_clear_bit(priv, IPW_RESET_REG, CBD_RESET_REG_PRINCETON_RESET);
3048
3049	/* no one knows timing, for safety add some delay */
3050	mdelay(5);
3051}
3052
3053struct fw_chunk {
3054	__le32 address;
3055	__le32 length;
3056};
3057
3058static int ipw_load_ucode(struct ipw_priv *priv, u8 * data, size_t len)
3059{
3060	int rc = 0, i, addr;
3061	u8 cr = 0;
3062	__le16 *image;
3063
3064	image = (__le16 *) data;
3065
3066	IPW_DEBUG_TRACE(">>\n");
3067
3068	rc = ipw_stop_master(priv);
3069
3070	if (rc < 0)
3071		return rc;
3072
3073	for (addr = IPW_SHARED_LOWER_BOUND;
3074	     addr < IPW_REGISTER_DOMAIN1_END; addr += 4) {
3075		ipw_write32(priv, addr, 0);
3076	}
3077
3078	/* no ucode (yet) */
3079	memset(&priv->dino_alive, 0, sizeof(priv->dino_alive));
3080	/* destroy DMA queues */
3081	/* reset sequence */
3082
3083	ipw_write_reg32(priv, IPW_MEM_HALT_AND_RESET, IPW_BIT_HALT_RESET_ON);
3084	ipw_arc_release(priv);
3085	ipw_write_reg32(priv, IPW_MEM_HALT_AND_RESET, IPW_BIT_HALT_RESET_OFF);
3086	mdelay(1);
3087
3088	/* reset PHY */
3089	ipw_write_reg32(priv, IPW_INTERNAL_CMD_EVENT, IPW_BASEBAND_POWER_DOWN);
3090	mdelay(1);
3091
3092	ipw_write_reg32(priv, IPW_INTERNAL_CMD_EVENT, 0);
3093	mdelay(1);
3094
3095	/* enable ucode store */
3096	ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, 0x0);
3097	ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, DINO_ENABLE_CS);
3098	mdelay(1);
3099
3100	/* write ucode */
3101	/**
3102	 * @bug
3103	 * Do NOT set indirect address register once and then
3104	 * store data to indirect data register in the loop.
3105	 * It seems very reasonable, but in this case DINO do not
3106	 * accept ucode. It is essential to set address each time.
3107	 */
3108	/* load new ipw uCode */
3109	for (i = 0; i < len / 2; i++)
3110		ipw_write_reg16(priv, IPW_BASEBAND_CONTROL_STORE,
3111				le16_to_cpu(image[i]));
3112
3113	/* enable DINO */
3114	ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, 0);
3115	ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, DINO_ENABLE_SYSTEM);
3116
3117	/* this is where the igx / win driver deveates from the VAP driver. */
3118
3119	/* wait for alive response */
3120	for (i = 0; i < 100; i++) {
3121		/* poll for incoming data */
3122		cr = ipw_read_reg8(priv, IPW_BASEBAND_CONTROL_STATUS);
3123		if (cr & DINO_RXFIFO_DATA)
3124			break;
3125		mdelay(1);
3126	}
3127
3128	if (cr & DINO_RXFIFO_DATA) {
3129		/* alive_command_responce size is NOT multiple of 4 */
3130		__le32 response_buffer[(sizeof(priv->dino_alive) + 3) / 4];
3131
3132		for (i = 0; i < ARRAY_SIZE(response_buffer); i++)
3133			response_buffer[i] =
3134			    cpu_to_le32(ipw_read_reg32(priv,
3135						       IPW_BASEBAND_RX_FIFO_READ));
3136		memcpy(&priv->dino_alive, response_buffer,
3137		       sizeof(priv->dino_alive));
3138		if (priv->dino_alive.alive_command == 1
3139		    && priv->dino_alive.ucode_valid == 1) {
3140			rc = 0;
3141			IPW_DEBUG_INFO
3142			    ("Microcode OK, rev. %d (0x%x) dev. %d (0x%x) "
3143			     "of %02d/%02d/%02d %02d:%02d\n",
3144			     priv->dino_alive.software_revision,
3145			     priv->dino_alive.software_revision,
3146			     priv->dino_alive.device_identifier,
3147			     priv->dino_alive.device_identifier,
3148			     priv->dino_alive.time_stamp[0],
3149			     priv->dino_alive.time_stamp[1],
3150			     priv->dino_alive.time_stamp[2],
3151			     priv->dino_alive.time_stamp[3],
3152			     priv->dino_alive.time_stamp[4]);
3153		} else {
3154			IPW_DEBUG_INFO("Microcode is not alive\n");
3155			rc = -EINVAL;
3156		}
3157	} else {
3158		IPW_DEBUG_INFO("No alive response from DINO\n");
3159		rc = -ETIME;
3160	}
3161
3162	/* disable DINO, otherwise for some reason
3163	   firmware have problem getting alive resp. */
3164	ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, 0);
3165
3166	return rc;
3167}
3168
3169static int ipw_load_firmware(struct ipw_priv *priv, u8 * data, size_t len)
3170{
3171	int ret = -1;
3172	int offset = 0;
3173	struct fw_chunk *chunk;
3174	int total_nr = 0;
3175	int i;
3176	struct pci_pool *pool;
3177	void **virts;
3178	dma_addr_t *phys;
3179
3180	IPW_DEBUG_TRACE("<< :\n");
3181
3182	virts = kmalloc(sizeof(void *) * CB_NUMBER_OF_ELEMENTS_SMALL,
3183			GFP_KERNEL);
3184	if (!virts)
3185		return -ENOMEM;
3186
3187	phys = kmalloc(sizeof(dma_addr_t) * CB_NUMBER_OF_ELEMENTS_SMALL,
3188			GFP_KERNEL);
3189	if (!phys) {
3190		kfree(virts);
3191		return -ENOMEM;
3192	}
3193	pool = pci_pool_create("ipw2200", priv->pci_dev, CB_MAX_LENGTH, 0, 0);
3194	if (!pool) {
3195		IPW_ERROR("pci_pool_create failed\n");
3196		kfree(phys);
3197		kfree(virts);
3198		return -ENOMEM;
3199	}
3200
3201	/* Start the Dma */
3202	ret = ipw_fw_dma_enable(priv);
3203
3204	/* the DMA is already ready this would be a bug. */
3205	BUG_ON(priv->sram_desc.last_cb_index > 0);
3206
3207	do {
3208		u32 chunk_len;
3209		u8 *start;
3210		int size;
3211		int nr = 0;
3212
3213		chunk = (struct fw_chunk *)(data + offset);
3214		offset += sizeof(struct fw_chunk);
3215		chunk_len = le32_to_cpu(chunk->length);
3216		start = data + offset;
3217
3218		nr = (chunk_len + CB_MAX_LENGTH - 1) / CB_MAX_LENGTH;
3219		for (i = 0; i < nr; i++) {
3220			virts[total_nr] = pci_pool_alloc(pool, GFP_KERNEL,
3221							 &phys[total_nr]);
3222			if (!virts[total_nr]) {
3223				ret = -ENOMEM;
3224				goto out;
3225			}
3226			size = min_t(u32, chunk_len - i * CB_MAX_LENGTH,
3227				     CB_MAX_LENGTH);
3228			memcpy(virts[total_nr], start, size);
3229			start += size;
3230			total_nr++;
3231			/* We don't support fw chunk larger than 64*8K */
3232			BUG_ON(total_nr > CB_NUMBER_OF_ELEMENTS_SMALL);
3233		}
3234
3235		/* build DMA packet and queue up for sending */
3236		/* dma to chunk->address, the chunk->length bytes from data +
3237		 * offeset*/
3238		/* Dma loading */
3239		ret = ipw_fw_dma_add_buffer(priv, &phys[total_nr - nr],
3240					    nr, le32_to_cpu(chunk->address),
3241					    chunk_len);
3242		if (ret) {
3243			IPW_DEBUG_INFO("dmaAddBuffer Failed\n");
3244			goto out;
3245		}
3246
3247		offset += chunk_len;
3248	} while (offset < len);
3249
3250	/* Run the DMA and wait for the answer */
3251	ret = ipw_fw_dma_kick(priv);
3252	if (ret) {
3253		IPW_ERROR("dmaKick Failed\n");
3254		goto out;
3255	}
3256
3257	ret = ipw_fw_dma_wait(priv);
3258	if (ret) {
3259		IPW_ERROR("dmaWaitSync Failed\n");
3260		goto out;
3261	}
3262 out:
3263	for (i = 0; i < total_nr; i++)
3264		pci_pool_free(pool, virts[i], phys[i]);
3265
3266	pci_pool_destroy(pool);
3267	kfree(phys);
3268	kfree(virts);
3269
3270	return ret;
3271}
3272
3273/* stop nic */
3274static int ipw_stop_nic(struct ipw_priv *priv)
3275{
3276	int rc = 0;
3277
3278	/* stop */
3279	ipw_write32(priv, IPW_RESET_REG, IPW_RESET_REG_STOP_MASTER);
3280
3281	rc = ipw_poll_bit(priv, IPW_RESET_REG,
3282			  IPW_RESET_REG_MASTER_DISABLED, 500);
3283	if (rc < 0) {
3284		IPW_ERROR("wait for reg master disabled failed after 500ms\n");
3285		return rc;
3286	}
3287
3288	ipw_set_bit(priv, IPW_RESET_REG, CBD_RESET_REG_PRINCETON_RESET);
3289
3290	return rc;
3291}
3292
3293static void ipw_start_nic(struct ipw_priv *priv)
3294{
3295	IPW_DEBUG_TRACE(">>\n");
3296
3297	/* prvHwStartNic  release ARC */
3298	ipw_clear_bit(priv, IPW_RESET_REG,
3299		      IPW_RESET_REG_MASTER_DISABLED |
3300		      IPW_RESET_REG_STOP_MASTER |
3301		      CBD_RESET_REG_PRINCETON_RESET);
3302
3303	/* enable power management */
3304	ipw_set_bit(priv, IPW_GP_CNTRL_RW,
3305		    IPW_GP_CNTRL_BIT_HOST_ALLOWS_STANDBY);
3306
3307	IPW_DEBUG_TRACE("<<\n");
3308}
3309
3310static int ipw_init_nic(struct ipw_priv *priv)
3311{
3312	int rc;
3313
3314	IPW_DEBUG_TRACE(">>\n");
3315	/* reset */
3316	/*prvHwInitNic */
3317	/* set "initialization complete" bit to move adapter to D0 state */
3318	ipw_set_bit(priv, IPW_GP_CNTRL_RW, IPW_GP_CNTRL_BIT_INIT_DONE);
3319
3320	/* low-level PLL activation */
3321	ipw_write32(priv, IPW_READ_INT_REGISTER,
3322		    IPW_BIT_INT_HOST_SRAM_READ_INT_REGISTER);
3323
3324	/* wait for clock stabilization */
3325	rc = ipw_poll_bit(priv, IPW_GP_CNTRL_RW,
3326			  IPW_GP_CNTRL_BIT_CLOCK_READY, 250);
3327	if (rc < 0)
3328		IPW_DEBUG_INFO("FAILED wait for clock stablization\n");
3329
3330	/* assert SW reset */
3331	ipw_set_bit(priv, IPW_RESET_REG, IPW_RESET_REG_SW_RESET);
3332
3333	udelay(10);
3334
3335	/* set "initialization complete" bit to move adapter to D0 state */
3336	ipw_set_bit(priv, IPW_GP_CNTRL_RW, IPW_GP_CNTRL_BIT_INIT_DONE);
3337
3338	IPW_DEBUG_TRACE(">>\n");
3339	return 0;
3340}
3341
3342/* Call this function from process context, it will sleep in request_firmware.
3343 * Probe is an ok place to call this from.
3344 */
3345static int ipw_reset_nic(struct ipw_priv *priv)
3346{
3347	int rc = 0;
3348	unsigned long flags;
3349
3350	IPW_DEBUG_TRACE(">>\n");
3351
3352	rc = ipw_init_nic(priv);
3353
3354	spin_lock_irqsave(&priv->lock, flags);
3355	/* Clear the 'host command active' bit... */
3356	priv->status &= ~STATUS_HCMD_ACTIVE;
3357	wake_up_interruptible(&priv->wait_command_queue);
3358	priv->status &= ~(STATUS_SCANNING | STATUS_SCAN_ABORTING);
3359	wake_up_interruptible(&priv->wait_state);
3360	spin_unlock_irqrestore(&priv->lock, flags);
3361
3362	IPW_DEBUG_TRACE("<<\n");
3363	return rc;
3364}
3365
3366
3367struct ipw_fw {
3368	__le32 ver;
3369	__le32 boot_size;
3370	__le32 ucode_size;
3371	__le32 fw_size;
3372	u8 data[0];
3373};
3374
3375static int ipw_get_fw(struct ipw_priv *priv,
3376		      const struct firmware **raw, const char *name)
3377{
3378	struct ipw_fw *fw;
3379	int rc;
3380
3381	/* ask firmware_class module to get the boot firmware off disk */
3382	rc = request_firmware(raw, name, &priv->pci_dev->dev);
3383	if (rc < 0) {
3384		IPW_ERROR("%s request_firmware failed: Reason %d\n", name, rc);
3385		return rc;
3386	}
3387
3388	if ((*raw)->size < sizeof(*fw)) {
3389		IPW_ERROR("%s is too small (%zd)\n", name, (*raw)->size);
3390		return -EINVAL;
3391	}
3392
3393	fw = (void *)(*raw)->data;
3394
3395	if ((*raw)->size < sizeof(*fw) + le32_to_cpu(fw->boot_size) +
3396	    le32_to_cpu(fw->ucode_size) + le32_to_cpu(fw->fw_size)) {
3397		IPW_ERROR("%s is too small or corrupt (%zd)\n",
3398			  name, (*raw)->size);
3399		return -EINVAL;
3400	}
3401
3402	IPW_DEBUG_INFO("Read firmware '%s' image v%d.%d (%zd bytes)\n",
3403		       name,
3404		       le32_to_cpu(fw->ver) >> 16,
3405		       le32_to_cpu(fw->ver) & 0xff,
3406		       (*raw)->size - sizeof(*fw));
3407	return 0;
3408}
3409
3410#define IPW_RX_BUF_SIZE (3000)
3411
3412static void ipw_rx_queue_reset(struct ipw_priv *priv,
3413				      struct ipw_rx_queue *rxq)
3414{
3415	unsigned long flags;
3416	int i;
3417
3418	spin_lock_irqsave(&rxq->lock, flags);
3419
3420	INIT_LIST_HEAD(&rxq->rx_free);
3421	INIT_LIST_HEAD(&rxq->rx_used);
3422
3423	/* Fill the rx_used queue with _all_ of the Rx buffers */
3424	for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
3425		/* In the reset function, these buffers may have been allocated
3426		 * to an SKB, so we need to unmap and free potential storage */
3427		if (rxq->pool[i].skb != NULL) {
3428			pci_unmap_single(priv->pci_dev, rxq->pool[i].dma_addr,
3429					 IPW_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3430			dev_kfree_skb(rxq->pool[i].skb);
3431			rxq->pool[i].skb = NULL;
3432		}
3433		list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
3434	}
3435
3436	/* Set us so that we have processed and used all buffers, but have
3437	 * not restocked the Rx queue with fresh buffers */
3438	rxq->read = rxq->write = 0;
3439	rxq->free_count = 0;
3440	spin_unlock_irqrestore(&rxq->lock, flags);
3441}
3442
3443#ifdef CONFIG_PM
3444static int fw_loaded = 0;
3445static const struct firmware *raw = NULL;
3446
3447static void free_firmware(void)
3448{
3449	if (fw_loaded) {
3450		release_firmware(raw);
3451		raw = NULL;
3452		fw_loaded = 0;
3453	}
3454}
3455#else
3456#define free_firmware() do {} while (0)
3457#endif
3458
3459static int ipw_load(struct ipw_priv *priv)
3460{
3461#ifndef CONFIG_PM
3462	const struct firmware *raw = NULL;
3463#endif
3464	struct ipw_fw *fw;
3465	u8 *boot_img, *ucode_img, *fw_img;
3466	u8 *name = NULL;
3467	int rc = 0, retries = 3;
3468
3469	switch (priv->ieee->iw_mode) {
3470	case IW_MODE_ADHOC:
3471		name = "ipw2200-ibss.fw";
3472		break;
3473#ifdef CONFIG_IPW2200_MONITOR
3474	case IW_MODE_MONITOR:
3475		name = "ipw2200-sniffer.fw";
3476		break;
3477#endif
3478	case IW_MODE_INFRA:
3479		name = "ipw2200-bss.fw";
3480		break;
3481	}
3482
3483	if (!name) {
3484		rc = -EINVAL;
3485		goto error;
3486	}
3487
3488#ifdef CONFIG_PM
3489	if (!fw_loaded) {
3490#endif
3491		rc = ipw_get_fw(priv, &raw, name);
3492		if (rc < 0)
3493			goto error;
3494#ifdef CONFIG_PM
3495	}
3496#endif
3497
3498	fw = (void *)raw->data;
3499	boot_img = &fw->data[0];
3500	ucode_img = &fw->data[le32_to_cpu(fw->boot_size)];
3501	fw_img = &fw->data[le32_to_cpu(fw->boot_size) +
3502			   le32_to_cpu(fw->ucode_size)];
3503
3504	if (rc < 0)
3505		goto error;
3506
3507	if (!priv->rxq)
3508		priv->rxq = ipw_rx_queue_alloc(priv);
3509	else
3510		ipw_rx_queue_reset(priv, priv->rxq);
3511	if (!priv->rxq) {
3512		IPW_ERROR("Unable to initialize Rx queue\n");
3513		goto error;
3514	}
3515
3516      retry:
3517	/* Ensure interrupts are disabled */
3518	ipw_write32(priv, IPW_INTA_MASK_R, ~IPW_INTA_MASK_ALL);
3519	priv->status &= ~STATUS_INT_ENABLED;
3520
3521	/* ack pending interrupts */
3522	ipw_write32(priv, IPW_INTA_RW, IPW_INTA_MASK_ALL);
3523
3524	ipw_stop_nic(priv);
3525
3526	rc = ipw_reset_nic(priv);
3527	if (rc < 0) {
3528		IPW_ERROR("Unable to reset NIC\n");
3529		goto error;
3530	}
3531
3532	ipw_zero_memory(priv, IPW_NIC_SRAM_LOWER_BOUND,
3533			IPW_NIC_SRAM_UPPER_BOUND - IPW_NIC_SRAM_LOWER_BOUND);
3534
3535	/* DMA the initial boot firmware into the device */
3536	rc = ipw_load_firmware(priv, boot_img, le32_to_cpu(fw->boot_size));
3537	if (rc < 0) {
3538		IPW_ERROR("Unable to load boot firmware: %d\n", rc);
3539		goto error;
3540	}
3541
3542	/* kick start the device */
3543	ipw_start_nic(priv);
3544
3545	/* wait for the device to finish its initial startup sequence */
3546	rc = ipw_poll_bit(priv, IPW_INTA_RW,
3547			  IPW_INTA_BIT_FW_INITIALIZATION_DONE, 500);
3548	if (rc < 0) {
3549		IPW_ERROR("device failed to boot initial fw image\n");
3550		goto error;
3551	}
3552	IPW_DEBUG_INFO("initial device response after %dms\n", rc);
3553
3554	/* ack fw init done interrupt */
3555	ipw_write32(priv, IPW_INTA_RW, IPW_INTA_BIT_FW_INITIALIZATION_DONE);
3556
3557	/* DMA the ucode into the device */
3558	rc = ipw_load_ucode(priv, ucode_img, le32_to_cpu(fw->ucode_size));
3559	if (rc < 0) {
3560		IPW_ERROR("Unable to load ucode: %d\n", rc);
3561		goto error;
3562	}
3563
3564	/* stop nic */
3565	ipw_stop_nic(priv);
3566
3567	/* DMA bss firmware into the device */
3568	rc = ipw_load_firmware(priv, fw_img, le32_to_cpu(fw->fw_size));
3569	if (rc < 0) {
3570		IPW_ERROR("Unable to load firmware: %d\n", rc);
3571		goto error;
3572	}
3573#ifdef CONFIG_PM
3574	fw_loaded = 1;
3575#endif
3576
3577	ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 0);
3578
3579	rc = ipw_queue_reset(priv);
3580	if (rc < 0) {
3581		IPW_ERROR("Unable to initialize queues\n");
3582		goto error;
3583	}
3584
3585	/* Ensure interrupts are disabled */
3586	ipw_write32(priv, IPW_INTA_MASK_R, ~IPW_INTA_MASK_ALL);
3587	/* ack pending interrupts */
3588	ipw_write32(priv, IPW_INTA_RW, IPW_INTA_MASK_ALL);
3589
3590	/* kick start the device */
3591	ipw_start_nic(priv);
3592
3593	if (ipw_read32(priv, IPW_INTA_RW) & IPW_INTA_BIT_PARITY_ERROR) {
3594		if (retries > 0) {
3595			IPW_WARNING("Parity error.  Retrying init.\n");
3596			retries--;
3597			goto retry;
3598		}
3599
3600		IPW_ERROR("TODO: Handle parity error -- schedule restart?\n");
3601		rc = -EIO;
3602		goto error;
3603	}
3604
3605	/* wait for the device */
3606	rc = ipw_poll_bit(priv, IPW_INTA_RW,
3607			  IPW_INTA_BIT_FW_INITIALIZATION_DONE, 500);
3608	if (rc < 0) {
3609		IPW_ERROR("device failed to start within 500ms\n");
3610		goto error;
3611	}
3612	IPW_DEBUG_INFO("device response after %dms\n", rc);
3613
3614	/* ack fw init done interrupt */
3615	ipw_write32(priv, IPW_INTA_RW, IPW_INTA_BIT_FW_INITIALIZATION_DONE);
3616
3617	/* read eeprom data and initialize the eeprom region of sram */
3618	priv->eeprom_delay = 1;
3619	ipw_eeprom_init_sram(priv);
3620
3621	/* enable interrupts */
3622	ipw_enable_interrupts(priv);
3623
3624	/* Ensure our queue has valid packets */
3625	ipw_rx_queue_replenish(priv);
3626
3627	ipw_write32(priv, IPW_RX_READ_INDEX, priv->rxq->read);
3628
3629	/* ack pending interrupts */
3630	ipw_write32(priv, IPW_INTA_RW, IPW_INTA_MASK_ALL);
3631
3632#ifndef CONFIG_PM
3633	release_firmware(raw);
3634#endif
3635	return 0;
3636
3637      error:
3638	if (priv->rxq) {
3639		ipw_rx_queue_free(priv, priv->rxq);
3640		priv->rxq = NULL;
3641	}
3642	ipw_tx_queue_free(priv);
3643	if (raw)
3644		release_firmware(raw);
3645#ifdef CONFIG_PM
3646	fw_loaded = 0;
3647	raw = NULL;
3648#endif
3649
3650	return rc;
3651}
3652
3653/**
3654 * DMA services
3655 *
3656 * Theory of operation
3657 *
3658 * A queue is a circular buffers with 'Read' and 'Write' pointers.
3659 * 2 empty entries always kept in the buffer to protect from overflow.
3660 *
3661 * For Tx queue, there are low mark and high mark limits. If, after queuing
3662 * the packet for Tx, free space become < low mark, Tx queue stopped. When
3663 * reclaiming packets (on 'tx done IRQ), if free space become > high mark,
3664 * Tx queue resumed.
3665 *
3666 * The IPW operates with six queues, one receive queue in the device's
3667 * sram, one transmit queue for sending commands to the device firmware,
3668 * and four transmit queues for data.
3669 *
3670 * The four transmit queues allow for performing quality of service (qos)
3671 * transmissions as per the 802.11 protocol.  Currently Linux does not
3672 * provide a mechanism to the user for utilizing prioritized queues, so
3673 * we only utilize the first data transmit queue (queue1).
3674 */
3675
3676/**
3677 * Driver allocates buffers of this size for Rx
3678 */
3679
3680/**
3681 * ipw_rx_queue_space - Return number of free slots available in queue.
3682 */
3683static int ipw_rx_queue_space(const struct ipw_rx_queue *q)
3684{
3685	int s = q->read - q->write;
3686	if (s <= 0)
3687		s += RX_QUEUE_SIZE;
3688	/* keep some buffer to not confuse full and empty queue */
3689	s -= 2;
3690	if (s < 0)
3691		s = 0;
3692	return s;
3693}
3694
3695static inline int ipw_tx_queue_space(const struct clx2_queue *q)
3696{
3697	int s = q->last_used - q->first_empty;
3698	if (s <= 0)
3699		s += q->n_bd;
3700	s -= 2;			/* keep some reserve to not confuse empty and full situations */
3701	if (s < 0)
3702		s = 0;
3703	return s;
3704}
3705
3706static inline int ipw_queue_inc_wrap(int index, int n_bd)
3707{
3708	return (++index == n_bd) ? 0 : index;
3709}
3710
3711/**
3712 * Initialize common DMA queue structure
3713 *
3714 * @param q                queue to init
3715 * @param count            Number of BD's to allocate. Should be power of 2
3716 * @param read_register    Address for 'read' register
3717 *                         (not offset within BAR, full address)
3718 * @param write_register   Address for 'write' register
3719 *                         (not offset within BAR, full address)
3720 * @param base_register    Address for 'base' register
3721 *                         (not offset within BAR, full address)
3722 * @param size             Address for 'size' register
3723 *                         (not offset within BAR, full address)
3724 */
3725static void ipw_queue_init(struct ipw_priv *priv, struct clx2_queue *q,
3726			   int count, u32 read, u32 write, u32 base, u32 size)
3727{
3728	q->n_bd = count;
3729
3730	q->low_mark = q->n_bd / 4;
3731	if (q->low_mark < 4)
3732		q->low_mark = 4;
3733
3734	q->high_mark = q->n_bd / 8;
3735	if (q->high_mark < 2)
3736		q->high_mark = 2;
3737
3738	q->first_empty = q->last_used = 0;
3739	q->reg_r = read;
3740	q->reg_w = write;
3741
3742	ipw_write32(priv, base, q->dma_addr);
3743	ipw_write32(priv, size, count);
3744	ipw_write32(priv, read, 0);
3745	ipw_write32(priv, write, 0);
3746
3747	_ipw_read32(priv, 0x90);
3748}
3749
3750static int ipw_queue_tx_init(struct ipw_priv *priv,
3751			     struct clx2_tx_queue *q,
3752			     int count, u32 read, u32 write, u32 base, u32 size)
3753{
3754	struct pci_dev *dev = priv->pci_dev;
3755
3756	q->txb = kmalloc(sizeof(q->txb[0]) * count, GFP_KERNEL);
3757	if (!q->txb) {
3758		IPW_ERROR("vmalloc for auxilary BD structures failed\n");
3759		return -ENOMEM;
3760	}
3761
3762	q->bd =
3763	    pci_alloc_consistent(dev, sizeof(q->bd[0]) * count, &q->q.dma_addr);
3764	if (!q->bd) {
3765		IPW_ERROR("pci_alloc_consistent(%zd) failed\n",
3766			  sizeof(q->bd[0]) * count);
3767		kfree(q->txb);
3768		q->txb = NULL;
3769		return -ENOMEM;
3770	}
3771
3772	ipw_queue_init(priv, &q->q, count, read, write, base, size);
3773	return 0;
3774}
3775
3776/**
3777 * Free one TFD, those at index [txq->q.last_used].
3778 * Do NOT advance any indexes
3779 *
3780 * @param dev
3781 * @param txq
3782 */
3783static void ipw_queue_tx_free_tfd(struct ipw_priv *priv,
3784				  struct clx2_tx_queue *txq)
3785{
3786	struct tfd_frame *bd = &txq->bd[txq->q.last_used];
3787	struct pci_dev *dev = priv->pci_dev;
3788	int i;
3789
3790	/* classify bd */
3791	if (bd->control_flags.message_type == TX_HOST_COMMAND_TYPE)
3792		/* nothing to cleanup after for host commands */
3793		return;
3794
3795	/* sanity check */
3796	if (le32_to_cpu(bd->u.data.num_chunks) > NUM_TFD_CHUNKS) {
3797		IPW_ERROR("Too many chunks: %i\n",
3798			  le32_to_cpu(bd->u.data.num_chunks));
3799		/** @todo issue fatal error, it is quite serious situation */
3800		return;
3801	}
3802
3803	/* unmap chunks if any */
3804	for (i = 0; i < le32_to_cpu(bd->u.data.num_chunks); i++) {
3805		pci_unmap_single(dev, le32_to_cpu(bd->u.data.chunk_ptr[i]),
3806				 le16_to_cpu(bd->u.data.chunk_len[i]),
3807				 PCI_DMA_TODEVICE);
3808		if (txq->txb[txq->q.last_used]) {
3809			libipw_txb_free(txq->txb[txq->q.last_used]);
3810			txq->txb[txq->q.last_used] = NULL;
3811		}
3812	}
3813}
3814
3815/**
3816 * Deallocate DMA queue.
3817 *
3818 * Empty queue by removing and destroying all BD's.
3819 * Free all buffers.
3820 *
3821 * @param dev
3822 * @param q
3823 */
3824static void ipw_queue_tx_free(struct ipw_priv *priv, struct clx2_tx_queue *txq)
3825{
3826	struct clx2_queue *q = &txq->q;
3827	struct pci_dev *dev = priv->pci_dev;
3828
3829	if (q->n_bd == 0)
3830		return;
3831
3832	/* first, empty all BD's */
3833	for (; q->first_empty != q->last_used;
3834	     q->last_used = ipw_queue_inc_wrap(q->last_used, q->n_bd)) {
3835		ipw_queue_tx_free_tfd(priv, txq);
3836	}
3837
3838	/* free buffers belonging to queue itself */
3839	pci_free_consistent(dev, sizeof(txq->bd[0]) * q->n_bd, txq->bd,
3840			    q->dma_addr);
3841	kfree(txq->txb);
3842
3843	/* 0 fill whole structure */
3844	memset(txq, 0, sizeof(*txq));
3845}
3846
3847/**
3848 * Destroy all DMA queues and structures
3849 *
3850 * @param priv
3851 */
3852static void ipw_tx_queue_free(struct ipw_priv *priv)
3853{
3854	/* Tx CMD queue */
3855	ipw_queue_tx_free(priv, &priv->txq_cmd);
3856
3857	/* Tx queues */
3858	ipw_queue_tx_free(priv, &priv->txq[0]);
3859	ipw_queue_tx_free(priv, &priv->txq[1]);
3860	ipw_queue_tx_free(priv, &priv->txq[2]);
3861	ipw_queue_tx_free(priv, &priv->txq[3]);
3862}
3863
3864static void ipw_create_bssid(struct ipw_priv *priv, u8 * bssid)
3865{
3866	/* First 3 bytes are manufacturer */
3867	bssid[0] = priv->mac_addr[0];
3868	bssid[1] = priv->mac_addr[1];
3869	bssid[2] = priv->mac_addr[2];
3870
3871	/* Last bytes are random */
3872	get_random_bytes(&bssid[3], ETH_ALEN - 3);
3873
3874	bssid[0] &= 0xfe;	/* clear multicast bit */
3875	bssid[0] |= 0x02;	/* set local assignment bit (IEEE802) */
3876}
3877
3878static u8 ipw_add_station(struct ipw_priv *priv, u8 * bssid)
3879{
3880	struct ipw_station_entry entry;
3881	int i;
3882
3883	for (i = 0; i < priv->num_stations; i++) {
3884		if (!memcmp(priv->stations[i], bssid, ETH_ALEN)) {
3885			/* Another node is active in network */
3886			priv->missed_adhoc_beacons = 0;
3887			if (!(priv->config & CFG_STATIC_CHANNEL))
3888				/* when other nodes drop out, we drop out */
3889				priv->config &= ~CFG_ADHOC_PERSIST;
3890
3891			return i;
3892		}
3893	}
3894
3895	if (i == MAX_STATIONS)
3896		return IPW_INVALID_STATION;
3897
3898	IPW_DEBUG_SCAN("Adding AdHoc station: %pM\n", bssid);
3899
3900	entry.reserved = 0;
3901	entry.support_mode = 0;
3902	memcpy(entry.mac_addr, bssid, ETH_ALEN);
3903	memcpy(priv->stations[i], bssid, ETH_ALEN);
3904	ipw_write_direct(priv, IPW_STATION_TABLE_LOWER + i * sizeof(entry),
3905			 &entry, sizeof(entry));
3906	priv->num_stations++;
3907
3908	return i;
3909}
3910
3911static u8 ipw_find_station(struct ipw_priv *priv, u8 * bssid)
3912{
3913	int i;
3914
3915	for (i = 0; i < priv->num_stations; i++)
3916		if (!memcmp(priv->stations[i], bssid, ETH_ALEN))
3917			return i;
3918
3919	return IPW_INVALID_STATION;
3920}
3921
3922static void ipw_send_disassociate(struct ipw_priv *priv, int quiet)
3923{
3924	int err;
3925
3926	if (priv->status & STATUS_ASSOCIATING) {
3927		IPW_DEBUG_ASSOC("Disassociating while associating.\n");
3928		queue_work(priv->workqueue, &priv->disassociate);
3929		return;
3930	}
3931
3932	if (!(priv->status & STATUS_ASSOCIATED)) {
3933		IPW_DEBUG_ASSOC("Disassociating while not associated.\n");
3934		return;
3935	}
3936
3937	IPW_DEBUG_ASSOC("Disassocation attempt from %pM "
3938			"on channel %d.\n",
3939			priv->assoc_request.bssid,
3940			priv->assoc_request.channel);
3941
3942	priv->status &= ~(STATUS_ASSOCIATING | STATUS_ASSOCIATED);
3943	priv->status |= STATUS_DISASSOCIATING;
3944
3945	if (quiet)
3946		priv->assoc_request.assoc_type = HC_DISASSOC_QUIET;
3947	else
3948		priv->assoc_request.assoc_type = HC_DISASSOCIATE;
3949
3950	err = ipw_send_associate(priv, &priv->assoc_request);
3951	if (err) {
3952		IPW_DEBUG_HC("Attempt to send [dis]associate command "
3953			     "failed.\n");
3954		return;
3955	}
3956
3957}
3958
3959static int ipw_disassociate(void *data)
3960{
3961	struct ipw_priv *priv = data;
3962	if (!(priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)))
3963		return 0;
3964	ipw_send_disassociate(data, 0);
3965	netif_carrier_off(priv->net_dev);
3966	return 1;
3967}
3968
3969static void ipw_bg_disassociate(struct work_struct *work)
3970{
3971	struct ipw_priv *priv =
3972		container_of(work, struct ipw_priv, disassociate);
3973	mutex_lock(&priv->mutex);
3974	ipw_disassociate(priv);
3975	mutex_unlock(&priv->mutex);
3976}
3977
3978static void ipw_system_config(struct work_struct *work)
3979{
3980	struct ipw_priv *priv =
3981		container_of(work, struct ipw_priv, system_config);
3982
3983#ifdef CONFIG_IPW2200_PROMISCUOUS
3984	if (priv->prom_net_dev && netif_running(priv->prom_net_dev)) {
3985		priv->sys_config.accept_all_data_frames = 1;
3986		priv->sys_config.accept_non_directed_frames = 1;
3987		priv->sys_config.accept_all_mgmt_bcpr = 1;
3988		priv->sys_config.accept_all_mgmt_frames = 1;
3989	}
3990#endif
3991
3992	ipw_send_system_config(priv);
3993}
3994
3995struct ipw_status_code {
3996	u16 status;
3997	const char *reason;
3998};
3999
4000static const struct ipw_status_code ipw_status_codes[] = {
4001	{0x00, "Successful"},
4002	{0x01, "Unspecified failure"},
4003	{0x0A, "Cannot support all requested capabilities in the "
4004	 "Capability information field"},
4005	{0x0B, "Reassociation denied due to inability to confirm that "
4006	 "association exists"},
4007	{0x0C, "Association denied due to reason outside the scope of this "
4008	 "standard"},
4009	{0x0D,
4010	 "Responding station does not support the specified authentication "
4011	 "algorithm"},
4012	{0x0E,
4013	 "Received an Authentication frame with authentication sequence "
4014	 "transaction sequence number out of expected sequence"},
4015	{0x0F, "Authentication rejected because of challenge failure"},
4016	{0x10, "Authentication rejected due to timeout waiting for next "
4017	 "frame in sequence"},
4018	{0x11, "Association denied because AP is unable to handle additional "
4019	 "associated stations"},
4020	{0x12,
4021	 "Association denied due to requesting station not supporting all "
4022	 "of the datarates in the BSSBasicServiceSet Parameter"},
4023	{0x13,
4024	 "Association denied due to requesting station not supporting "
4025	 "short preamble operation"},
4026	{0x14,
4027	 "Association denied due to requesting station not supporting "
4028	 "PBCC encoding"},
4029	{0x15,
4030	 "Association denied due to requesting station not supporting "
4031	 "channel agility"},
4032	{0x19,
4033	 "Association denied due to requesting station not supporting "
4034	 "short slot operation"},
4035	{0x1A,
4036	 "Association denied due to requesting station not supporting "
4037	 "DSSS-OFDM operation"},
4038	{0x28, "Invalid Information Element"},
4039	{0x29, "Group Cipher is not valid"},
4040	{0x2A, "Pairwise Cipher is not valid"},
4041	{0x2B, "AKMP is not valid"},
4042	{0x2C, "Unsupported RSN IE version"},
4043	{0x2D, "Invalid RSN IE Capabilities"},
4044	{0x2E, "Cipher suite is rejected per security policy"},
4045};
4046
4047static const char *ipw_get_status_code(u16 status)
4048{
4049	int i;
4050	for (i = 0; i < ARRAY_SIZE(ipw_status_codes); i++)
4051		if (ipw_status_codes[i].status == (status & 0xff))
4052			return ipw_status_codes[i].reason;
4053	return "Unknown status value.";
4054}
4055
4056static void inline average_init(struct average *avg)
4057{
4058	memset(avg, 0, sizeof(*avg));
4059}
4060
4061#define DEPTH_RSSI 8
4062#define DEPTH_NOISE 16
4063static s16 exponential_average(s16 prev_avg, s16 val, u8 depth)
4064{
4065	return ((depth-1)*prev_avg +  val)/depth;
4066}
4067
4068static void average_add(struct average *avg, s16 val)
4069{
4070	avg->sum -= avg->entries[avg->pos];
4071	avg->sum += val;
4072	avg->entries[avg->pos++] = val;
4073	if (unlikely(avg->pos == AVG_ENTRIES)) {
4074		avg->init = 1;
4075		avg->pos = 0;
4076	}
4077}
4078
4079static s16 average_value(struct average *avg)
4080{
4081	if (!unlikely(avg->init)) {
4082		if (avg->pos)
4083			return avg->sum / avg->pos;
4084		return 0;
4085	}
4086
4087	return avg->sum / AVG_ENTRIES;
4088}
4089
4090static void ipw_reset_stats(struct ipw_priv *priv)
4091{
4092	u32 len = sizeof(u32);
4093
4094	priv->quality = 0;
4095
4096	average_init(&priv->average_missed_beacons);
4097	priv->exp_avg_rssi = -60;
4098	priv->exp_avg_noise = -85 + 0x100;
4099
4100	priv->last_rate = 0;
4101	priv->last_missed_beacons = 0;
4102	priv->last_rx_packets = 0;
4103	priv->last_tx_packets = 0;
4104	priv->last_tx_failures = 0;
4105
4106	/* Firmware managed, reset only when NIC is restarted, so we have to
4107	 * normalize on the current value */
4108	ipw_get_ordinal(priv, IPW_ORD_STAT_RX_ERR_CRC,
4109			&priv->last_rx_err, &len);
4110	ipw_get_ordinal(priv, IPW_ORD_STAT_TX_FAILURE,
4111			&priv->last_tx_failures, &len);
4112
4113	/* Driver managed, reset with each association */
4114	priv->missed_adhoc_beacons = 0;
4115	priv->missed_beacons = 0;
4116	priv->tx_packets = 0;
4117	priv->rx_packets = 0;
4118
4119}
4120
4121static u32 ipw_get_max_rate(struct ipw_priv *priv)
4122{
4123	u32 i = 0x80000000;
4124	u32 mask = priv->rates_mask;
4125	/* If currently associated in B mode, restrict the maximum
4126	 * rate match to B rates */
4127	if (priv->assoc_request.ieee_mode == IPW_B_MODE)
4128		mask &= LIBIPW_CCK_RATES_MASK;
4129
4130	/* TODO: Verify that the rate is supported by the current rates
4131	 * list. */
4132
4133	while (i && !(mask & i))
4134		i >>= 1;
4135	switch (i) {
4136	case LIBIPW_CCK_RATE_1MB_MASK:
4137		return 1000000;
4138	case LIBIPW_CCK_RATE_2MB_MASK:
4139		return 2000000;
4140	case LIBIPW_CCK_RATE_5MB_MASK:
4141		return 5500000;
4142	case LIBIPW_OFDM_RATE_6MB_MASK:
4143		return 6000000;
4144	case LIBIPW_OFDM_RATE_9MB_MASK:
4145		return 9000000;
4146	case LIBIPW_CCK_RATE_11MB_MASK:
4147		return 11000000;
4148	case LIBIPW_OFDM_RATE_12MB_MASK:
4149		return 12000000;
4150	case LIBIPW_OFDM_RATE_18MB_MASK:
4151		return 18000000;
4152	case LIBIPW_OFDM_RATE_24MB_MASK:
4153		return 24000000;
4154	case LIBIPW_OFDM_RATE_36MB_MASK:
4155		return 36000000;
4156	case LIBIPW_OFDM_RATE_48MB_MASK:
4157		return 48000000;
4158	case LIBIPW_OFDM_RATE_54MB_MASK:
4159		return 54000000;
4160	}
4161
4162	if (priv->ieee->mode == IEEE_B)
4163		return 11000000;
4164	else
4165		return 54000000;
4166}
4167
4168static u32 ipw_get_current_rate(struct ipw_priv *priv)
4169{
4170	u32 rate, len = sizeof(rate);
4171	int err;
4172
4173	if (!(priv->status & STATUS_ASSOCIATED))
4174		return 0;
4175
4176	if (priv->tx_packets > IPW_REAL_RATE_RX_PACKET_THRESHOLD) {
4177		err = ipw_get_ordinal(priv, IPW_ORD_STAT_TX_CURR_RATE, &rate,
4178				      &len);
4179		if (err) {
4180			IPW_DEBUG_INFO("failed querying ordinals.\n");
4181			return 0;
4182		}
4183	} else
4184		return ipw_get_max_rate(priv);
4185
4186	switch (rate) {
4187	case IPW_TX_RATE_1MB:
4188		return 1000000;
4189	case IPW_TX_RATE_2MB:
4190		return 2000000;
4191	case IPW_TX_RATE_5MB:
4192		return 5500000;
4193	case IPW_TX_RATE_6MB:
4194		return 6000000;
4195	case IPW_TX_RATE_9MB:
4196		return 9000000;
4197	case IPW_TX_RATE_11MB:
4198		return 11000000;
4199	case IPW_TX_RATE_12MB:
4200		return 12000000;
4201	case IPW_TX_RATE_18MB:
4202		return 18000000;
4203	case IPW_TX_RATE_24MB:
4204		return 24000000;
4205	case IPW_TX_RATE_36MB:
4206		return 36000000;
4207	case IPW_TX_RATE_48MB:
4208		return 48000000;
4209	case IPW_TX_RATE_54MB:
4210		return 54000000;
4211	}
4212
4213	return 0;
4214}
4215
4216#define IPW_STATS_INTERVAL (2 * HZ)
4217static void ipw_gather_stats(struct ipw_priv *priv)
4218{
4219	u32 rx_err, rx_err_delta, rx_packets_delta;
4220	u32 tx_failures, tx_failures_delta, tx_packets_delta;
4221	u32 missed_beacons_percent, missed_beacons_delta;
4222	u32 quality = 0;
4223	u32 len = sizeof(u32);
4224	s16 rssi;
4225	u32 beacon_quality, signal_quality, tx_quality, rx_quality,
4226	    rate_quality;
4227	u32 max_rate;
4228
4229	if (!(priv->status & STATUS_ASSOCIATED)) {
4230		priv->quality = 0;
4231		return;
4232	}
4233
4234	/* Update the statistics */
4235	ipw_get_ordinal(priv, IPW_ORD_STAT_MISSED_BEACONS,
4236			&priv->missed_beacons, &len);
4237	missed_beacons_delta = priv->missed_beacons - priv->last_missed_beacons;
4238	priv->last_missed_beacons = priv->missed_beacons;
4239	if (priv->assoc_request.beacon_interval) {
4240		missed_beacons_percent = missed_beacons_delta *
4241		    (HZ * le16_to_cpu(priv->assoc_request.beacon_interval)) /
4242		    (IPW_STATS_INTERVAL * 10);
4243	} else {
4244		missed_beacons_percent = 0;
4245	}
4246	average_add(&priv->average_missed_beacons, missed_beacons_percent);
4247
4248	ipw_get_ordinal(priv, IPW_ORD_STAT_RX_ERR_CRC, &rx_err, &len);
4249	rx_err_delta = rx_err - priv->last_rx_err;
4250	priv->last_rx_err = rx_err;
4251
4252	ipw_get_ordinal(priv, IPW_ORD_STAT_TX_FAILURE, &tx_failures, &len);
4253	tx_failures_delta = tx_failures - priv->last_tx_failures;
4254	priv->last_tx_failures = tx_failures;
4255
4256	rx_packets_delta = priv->rx_packets - priv->last_rx_packets;
4257	priv->last_rx_packets = priv->rx_packets;
4258
4259	tx_packets_delta = priv->tx_packets - priv->last_tx_packets;
4260	priv->last_tx_packets = priv->tx_packets;
4261
4262	/* Calculate quality based on the following:
4263	 *
4264	 * Missed beacon: 100% = 0, 0% = 70% missed
4265	 * Rate: 60% = 1Mbs, 100% = Max
4266	 * Rx and Tx errors represent a straight % of total Rx/Tx
4267	 * RSSI: 100% = > -50,  0% = < -80
4268	 * Rx errors: 100% = 0, 0% = 50% missed
4269	 *
4270	 * The lowest computed quality is used.
4271	 *
4272	 */
4273#define BEACON_THRESHOLD 5
4274	beacon_quality = 100 - missed_beacons_percent;
4275	if (beacon_quality < BEACON_THRESHOLD)
4276		beacon_quality = 0;
4277	else
4278		beacon_quality = (beacon_quality - BEACON_THRESHOLD) * 100 /
4279		    (100 - BEACON_THRESHOLD);
4280	IPW_DEBUG_STATS("Missed beacon: %3d%% (%d%%)\n",
4281			beacon_quality, missed_beacons_percent);
4282
4283	priv->last_rate = ipw_get_current_rate(priv);
4284	max_rate = ipw_get_max_rate(priv);
4285	rate_quality = priv->last_rate * 40 / max_rate + 60;
4286	IPW_DEBUG_STATS("Rate quality : %3d%% (%dMbs)\n",
4287			rate_quality, priv->last_rate / 1000000);
4288
4289	if (rx_packets_delta > 100 && rx_packets_delta + rx_err_delta)
4290		rx_quality = 100 - (rx_err_delta * 100) /
4291		    (rx_packets_delta + rx_err_delta);
4292	else
4293		rx_quality = 100;
4294	IPW_DEBUG_STATS("Rx quality   : %3d%% (%u errors, %u packets)\n",
4295			rx_quality, rx_err_delta, rx_packets_delta);
4296
4297	if (tx_packets_delta > 100 && tx_packets_delta + tx_failures_delta)
4298		tx_quality = 100 - (tx_failures_delta * 100) /
4299		    (tx_packets_delta + tx_failures_delta);
4300	else
4301		tx_quality = 100;
4302	IPW_DEBUG_STATS("Tx quality   : %3d%% (%u errors, %u packets)\n",
4303			tx_quality, tx_failures_delta, tx_packets_delta);
4304
4305	rssi = priv->exp_avg_rssi;
4306	signal_quality =
4307	    (100 *
4308	     (priv->ieee->perfect_rssi - priv->ieee->worst_rssi) *
4309	     (priv->ieee->perfect_rssi - priv->ieee->worst_rssi) -
4310	     (priv->ieee->perfect_rssi - rssi) *
4311	     (15 * (priv->ieee->perfect_rssi - priv->ieee->worst_rssi) +
4312	      62 * (priv->ieee->perfect_rssi - rssi))) /
4313	    ((priv->ieee->perfect_rssi - priv->ieee->worst_rssi) *
4314	     (priv->ieee->perfect_rssi - priv->ieee->worst_rssi));
4315	if (signal_quality > 100)
4316		signal_quality = 100;
4317	else if (signal_quality < 1)
4318		signal_quality = 0;
4319
4320	IPW_DEBUG_STATS("Signal level : %3d%% (%d dBm)\n",
4321			signal_quality, rssi);
4322
4323	quality = min(rx_quality, signal_quality);
4324	quality = min(tx_quality, quality);
4325	quality = min(rate_quality, quality);
4326	quality = min(beacon_quality, quality);
4327	if (quality == beacon_quality)
4328		IPW_DEBUG_STATS("Quality (%d%%): Clamped to missed beacons.\n",
4329				quality);
4330	if (quality == rate_quality)
4331		IPW_DEBUG_STATS("Quality (%d%%): Clamped to rate quality.\n",
4332				quality);
4333	if (quality == tx_quality)
4334		IPW_DEBUG_STATS("Quality (%d%%): Clamped to Tx quality.\n",
4335				quality);
4336	if (quality == rx_quality)
4337		IPW_DEBUG_STATS("Quality (%d%%): Clamped to Rx quality.\n",
4338				quality);
4339	if (quality == signal_quality)
4340		IPW_DEBUG_STATS("Quality (%d%%): Clamped to signal quality.\n",
4341				quality);
4342
4343	priv->quality = quality;
4344
4345	queue_delayed_work(priv->workqueue, &priv->gather_stats,
4346			   IPW_STATS_INTERVAL);
4347}
4348
4349static void ipw_bg_gather_stats(struct work_struct *work)
4350{
4351	struct ipw_priv *priv =
4352		container_of(work, struct ipw_priv, gather_stats.work);
4353	mutex_lock(&priv->mutex);
4354	ipw_gather_stats(priv);
4355	mutex_unlock(&priv->mutex);
4356}
4357
4358/* Missed beacon behavior:
4359 * 1st missed -> roaming_threshold, just wait, don't do any scan/roam.
4360 * roaming_threshold -> disassociate_threshold, scan and roam for better signal.
4361 * Above disassociate threshold, give up and stop scanning.
4362 * Roaming is disabled if disassociate_threshold <= roaming_threshold  */
4363static void ipw_handle_missed_beacon(struct ipw_priv *priv,
4364					    int missed_count)
4365{
4366	priv->notif_missed_beacons = missed_count;
4367
4368	if (missed_count > priv->disassociate_threshold &&
4369	    priv->status & STATUS_ASSOCIATED) {
4370		/* If associated and we've hit the missed
4371		 * beacon threshold, disassociate, turn
4372		 * off roaming, and abort any active scans */
4373		IPW_DEBUG(IPW_DL_INFO | IPW_DL_NOTIF |
4374			  IPW_DL_STATE | IPW_DL_ASSOC,
4375			  "Missed beacon: %d - disassociate\n", missed_count);
4376		priv->status &= ~STATUS_ROAMING;
4377		if (priv->status & STATUS_SCANNING) {
4378			IPW_DEBUG(IPW_DL_INFO | IPW_DL_NOTIF |
4379				  IPW_DL_STATE,
4380				  "Aborting scan with missed beacon.\n");
4381			queue_work(priv->workqueue, &priv->abort_scan);
4382		}
4383
4384		queue_work(priv->workqueue, &priv->disassociate);
4385		return;
4386	}
4387
4388	if (priv->status & STATUS_ROAMING) {
4389		/* If we are currently roaming, then just
4390		 * print a debug statement... */
4391		IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
4392			  "Missed beacon: %d - roam in progress\n",
4393			  missed_count);
4394		return;
4395	}
4396
4397	if (roaming &&
4398	    (missed_count > priv->roaming_threshold &&
4399	     missed_count <= priv->disassociate_threshold)) {
4400		/* If we are not already roaming, set the ROAM
4401		 * bit in the status and kick off a scan.
4402		 * This can happen several times before we reach
4403		 * disassociate_threshold. */
4404		IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
4405			  "Missed beacon: %d - initiate "
4406			  "roaming\n", missed_count);
4407		if (!(priv->status & STATUS_ROAMING)) {
4408			priv->status |= STATUS_ROAMING;
4409			if (!(priv->status & STATUS_SCANNING))
4410				queue_delayed_work(priv->workqueue,
4411						   &priv->request_scan, 0);
4412		}
4413		return;
4414	}
4415
4416	if (priv->status & STATUS_SCANNING &&
4417	    missed_count > IPW_MB_SCAN_CANCEL_THRESHOLD) {
4418		/* Stop scan to keep fw from getting
4419		 * stuck (only if we aren't roaming --
4420		 * otherwise we'll never scan more than 2 or 3
4421		 * channels..) */
4422		IPW_DEBUG(IPW_DL_INFO | IPW_DL_NOTIF | IPW_DL_STATE,
4423			  "Aborting scan with missed beacon.\n");
4424		queue_work(priv->workqueue, &priv->abort_scan);
4425	}
4426
4427	IPW_DEBUG_NOTIF("Missed beacon: %d\n", missed_count);
4428}
4429
4430static void ipw_scan_event(struct work_struct *work)
4431{
4432	union iwreq_data wrqu;
4433
4434	struct ipw_priv *priv =
4435		container_of(work, struct ipw_priv, scan_event.work);
4436
4437	wrqu.data.length = 0;
4438	wrqu.data.flags = 0;
4439	wireless_send_event(priv->net_dev, SIOCGIWSCAN, &wrqu, NULL);
4440}
4441
4442static void handle_scan_event(struct ipw_priv *priv)
4443{
4444	/* Only userspace-requested scan completion events go out immediately */
4445	if (!priv->user_requested_scan) {
4446		if (!delayed_work_pending(&priv->scan_event))
4447			queue_delayed_work(priv->workqueue, &priv->scan_event,
4448					 round_jiffies_relative(msecs_to_jiffies(4000)));
4449	} else {
4450		union iwreq_data wrqu;
4451
4452		priv->user_requested_scan = 0;
4453		cancel_delayed_work(&priv->scan_event);
4454
4455		wrqu.data.length = 0;
4456		wrqu.data.flags = 0;
4457		wireless_send_event(priv->net_dev, SIOCGIWSCAN, &wrqu, NULL);
4458	}
4459}
4460
4461/**
4462 * Handle host notification packet.
4463 * Called from interrupt routine
4464 */
4465static void ipw_rx_notification(struct ipw_priv *priv,
4466				       struct ipw_rx_notification *notif)
4467{
4468	DECLARE_SSID_BUF(ssid);
4469	u16 size = le16_to_cpu(notif->size);
4470
4471	IPW_DEBUG_NOTIF("type = %i (%d bytes)\n", notif->subtype, size);
4472
4473	switch (notif->subtype) {
4474	case HOST_NOTIFICATION_STATUS_ASSOCIATED:{
4475			struct notif_association *assoc = &notif->u.assoc;
4476
4477			switch (assoc->state) {
4478			case CMAS_ASSOCIATED:{
4479					IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4480						  IPW_DL_ASSOC,
4481						  "associated: '%s' %pM\n",
4482						  print_ssid(ssid, priv->essid,
4483							     priv->essid_len),
4484						  priv->bssid);
4485
4486					switch (priv->ieee->iw_mode) {
4487					case IW_MODE_INFRA:
4488						memcpy(priv->ieee->bssid,
4489						       priv->bssid, ETH_ALEN);
4490						break;
4491
4492					case IW_MODE_ADHOC:
4493						memcpy(priv->ieee->bssid,
4494						       priv->bssid, ETH_ALEN);
4495
4496						/* clear out the station table */
4497						priv->num_stations = 0;
4498
4499						IPW_DEBUG_ASSOC
4500						    ("queueing adhoc check\n");
4501						queue_delayed_work(priv->
4502								   workqueue,
4503								   &priv->
4504								   adhoc_check,
4505								   le16_to_cpu(priv->
4506								   assoc_request.
4507								   beacon_interval));
4508						break;
4509					}
4510
4511					priv->status &= ~STATUS_ASSOCIATING;
4512					priv->status |= STATUS_ASSOCIATED;
4513					queue_work(priv->workqueue,
4514						   &priv->system_config);
4515
4516#ifdef CONFIG_IPW2200_QOS
4517#define IPW_GET_PACKET_STYPE(x) WLAN_FC_GET_STYPE( \
4518			 le16_to_cpu(((struct ieee80211_hdr *)(x))->frame_control))
4519					if ((priv->status & STATUS_AUTH) &&
4520					    (IPW_GET_PACKET_STYPE(&notif->u.raw)
4521					     == IEEE80211_STYPE_ASSOC_RESP)) {
4522						if ((sizeof
4523						     (struct
4524						      libipw_assoc_response)
4525						     <= size)
4526						    && (size <= 2314)) {
4527							struct
4528							libipw_rx_stats
4529							    stats = {
4530								.len = size - 1,
4531							};
4532
4533							IPW_DEBUG_QOS
4534							    ("QoS Associate "
4535							     "size %d\n", size);
4536							libipw_rx_mgt(priv->
4537									 ieee,
4538									 (struct
4539									  libipw_hdr_4addr
4540									  *)
4541									 &notif->u.raw, &stats);
4542						}
4543					}
4544#endif
4545
4546					schedule_work(&priv->link_up);
4547
4548					break;
4549				}
4550
4551			case CMAS_AUTHENTICATED:{
4552					if (priv->
4553					    status & (STATUS_ASSOCIATED |
4554						      STATUS_AUTH)) {
4555						struct notif_authenticate *auth
4556						    = &notif->u.auth;
4557						IPW_DEBUG(IPW_DL_NOTIF |
4558							  IPW_DL_STATE |
4559							  IPW_DL_ASSOC,
4560							  "deauthenticated: '%s' "
4561							  "%pM"
4562							  ": (0x%04X) - %s\n",
4563							  print_ssid(ssid,
4564								     priv->
4565								     essid,
4566								     priv->
4567								     essid_len),
4568							  priv->bssid,
4569							  le16_to_cpu(auth->status),
4570							  ipw_get_status_code
4571							  (le16_to_cpu
4572							   (auth->status)));
4573
4574						priv->status &=
4575						    ~(STATUS_ASSOCIATING |
4576						      STATUS_AUTH |
4577						      STATUS_ASSOCIATED);
4578
4579						schedule_work(&priv->link_down);
4580						break;
4581					}
4582
4583					IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4584						  IPW_DL_ASSOC,
4585						  "authenticated: '%s' %pM\n",
4586						  print_ssid(ssid, priv->essid,
4587							     priv->essid_len),
4588						  priv->bssid);
4589					break;
4590				}
4591
4592			case CMAS_INIT:{
4593					if (priv->status & STATUS_AUTH) {
4594						struct
4595						    libipw_assoc_response
4596						*resp;
4597						resp =
4598						    (struct
4599						     libipw_assoc_response
4600						     *)&notif->u.raw;
4601						IPW_DEBUG(IPW_DL_NOTIF |
4602							  IPW_DL_STATE |
4603							  IPW_DL_ASSOC,
4604							  "association failed (0x%04X): %s\n",
4605							  le16_to_cpu(resp->status),
4606							  ipw_get_status_code
4607							  (le16_to_cpu
4608							   (resp->status)));
4609					}
4610
4611					IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4612						  IPW_DL_ASSOC,
4613						  "disassociated: '%s' %pM\n",
4614						  print_ssid(ssid, priv->essid,
4615							     priv->essid_len),
4616						  priv->bssid);
4617
4618					priv->status &=
4619					    ~(STATUS_DISASSOCIATING |
4620					      STATUS_ASSOCIATING |
4621					      STATUS_ASSOCIATED | STATUS_AUTH);
4622					if (priv->assoc_network
4623					    && (priv->assoc_network->
4624						capability &
4625						WLAN_CAPABILITY_IBSS))
4626						ipw_remove_current_network
4627						    (priv);
4628
4629					schedule_work(&priv->link_down);
4630
4631					break;
4632				}
4633
4634			case CMAS_RX_ASSOC_RESP:
4635				break;
4636
4637			default:
4638				IPW_ERROR("assoc: unknown (%d)\n",
4639					  assoc->state);
4640				break;
4641			}
4642
4643			break;
4644		}
4645
4646	case HOST_NOTIFICATION_STATUS_AUTHENTICATE:{
4647			struct notif_authenticate *auth = &notif->u.auth;
4648			switch (auth->state) {
4649			case CMAS_AUTHENTICATED:
4650				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
4651					  "authenticated: '%s' %pM\n",
4652					  print_ssid(ssid, priv->essid,
4653						     priv->essid_len),
4654					  priv->bssid);
4655				priv->status |= STATUS_AUTH;
4656				break;
4657
4658			case CMAS_INIT:
4659				if (priv->status & STATUS_AUTH) {
4660					IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4661						  IPW_DL_ASSOC,
4662						  "authentication failed (0x%04X): %s\n",
4663						  le16_to_cpu(auth->status),
4664						  ipw_get_status_code(le16_to_cpu
4665								      (auth->
4666								       status)));
4667				}
4668				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4669					  IPW_DL_ASSOC,
4670					  "deauthenticated: '%s' %pM\n",
4671					  print_ssid(ssid, priv->essid,
4672						     priv->essid_len),
4673					  priv->bssid);
4674
4675				priv->status &= ~(STATUS_ASSOCIATING |
4676						  STATUS_AUTH |
4677						  STATUS_ASSOCIATED);
4678
4679				schedule_work(&priv->link_down);
4680				break;
4681
4682			case CMAS_TX_AUTH_SEQ_1:
4683				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4684					  IPW_DL_ASSOC, "AUTH_SEQ_1\n");
4685				break;
4686			case CMAS_RX_AUTH_SEQ_2:
4687				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4688					  IPW_DL_ASSOC, "AUTH_SEQ_2\n");
4689				break;
4690			case CMAS_AUTH_SEQ_1_PASS:
4691				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4692					  IPW_DL_ASSOC, "AUTH_SEQ_1_PASS\n");
4693				break;
4694			case CMAS_AUTH_SEQ_1_FAIL:
4695				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4696					  IPW_DL_ASSOC, "AUTH_SEQ_1_FAIL\n");
4697				break;
4698			case CMAS_TX_AUTH_SEQ_3:
4699				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4700					  IPW_DL_ASSOC, "AUTH_SEQ_3\n");
4701				break;
4702			case CMAS_RX_AUTH_SEQ_4:
4703				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4704					  IPW_DL_ASSOC, "RX_AUTH_SEQ_4\n");
4705				break;
4706			case CMAS_AUTH_SEQ_2_PASS:
4707				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4708					  IPW_DL_ASSOC, "AUTH_SEQ_2_PASS\n");
4709				break;
4710			case CMAS_AUTH_SEQ_2_FAIL:
4711				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4712					  IPW_DL_ASSOC, "AUT_SEQ_2_FAIL\n");
4713				break;
4714			case CMAS_TX_ASSOC:
4715				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4716					  IPW_DL_ASSOC, "TX_ASSOC\n");
4717				break;
4718			case CMAS_RX_ASSOC_RESP:
4719				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4720					  IPW_DL_ASSOC, "RX_ASSOC_RESP\n");
4721
4722				break;
4723			case CMAS_ASSOCIATED:
4724				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4725					  IPW_DL_ASSOC, "ASSOCIATED\n");
4726				break;
4727			default:
4728				IPW_DEBUG_NOTIF("auth: failure - %d\n",
4729						auth->state);
4730				break;
4731			}
4732			break;
4733		}
4734
4735	case HOST_NOTIFICATION_STATUS_SCAN_CHANNEL_RESULT:{
4736			struct notif_channel_result *x =
4737			    &notif->u.channel_result;
4738
4739			if (size == sizeof(*x)) {
4740				IPW_DEBUG_SCAN("Scan result for channel %d\n",
4741					       x->channel_num);
4742			} else {
4743				IPW_DEBUG_SCAN("Scan result of wrong size %d "
4744					       "(should be %zd)\n",
4745					       size, sizeof(*x));
4746			}
4747			break;
4748		}
4749
4750	case HOST_NOTIFICATION_STATUS_SCAN_COMPLETED:{
4751			struct notif_scan_complete *x = &notif->u.scan_complete;
4752			if (size == sizeof(*x)) {
4753				IPW_DEBUG_SCAN
4754				    ("Scan completed: type %d, %d channels, "
4755				     "%d status\n", x->scan_type,
4756				     x->num_channels, x->status);
4757			} else {
4758				IPW_ERROR("Scan completed of wrong size %d "
4759					  "(should be %zd)\n",
4760					  size, sizeof(*x));
4761			}
4762
4763			priv->status &=
4764			    ~(STATUS_SCANNING | STATUS_SCAN_ABORTING);
4765
4766			wake_up_interruptible(&priv->wait_state);
4767			cancel_delayed_work(&priv->scan_check);
4768
4769			if (priv->status & STATUS_EXIT_PENDING)
4770				break;
4771
4772			priv->ieee->scans++;
4773
4774#ifdef CONFIG_IPW2200_MONITOR
4775			if (priv->ieee->iw_mode == IW_MODE_MONITOR) {
4776				priv->status |= STATUS_SCAN_FORCED;
4777				queue_delayed_work(priv->workqueue,
4778						   &priv->request_scan, 0);
4779				break;
4780			}
4781			priv->status &= ~STATUS_SCAN_FORCED;
4782#endif				/* CONFIG_IPW2200_MONITOR */
4783
4784			/* Do queued direct scans first */
4785			if (priv->status & STATUS_DIRECT_SCAN_PENDING) {
4786				queue_delayed_work(priv->workqueue,
4787						   &priv->request_direct_scan, 0);
4788			}
4789
4790			if (!(priv->status & (STATUS_ASSOCIATED |
4791					      STATUS_ASSOCIATING |
4792					      STATUS_ROAMING |
4793					      STATUS_DISASSOCIATING)))
4794				queue_work(priv->workqueue, &priv->associate);
4795			else if (priv->status & STATUS_ROAMING) {
4796				if (x->status == SCAN_COMPLETED_STATUS_COMPLETE)
4797					/* If a scan completed and we are in roam mode, then
4798					 * the scan that completed was the one requested as a
4799					 * result of entering roam... so, schedule the
4800					 * roam work */
4801					queue_work(priv->workqueue,
4802						   &priv->roam);
4803				else
4804					/* Don't schedule if we aborted the scan */
4805					priv->status &= ~STATUS_ROAMING;
4806			} else if (priv->status & STATUS_SCAN_PENDING)
4807				queue_delayed_work(priv->workqueue,
4808						   &priv->request_scan, 0);
4809			else if (priv->config & CFG_BACKGROUND_SCAN
4810				 && priv->status & STATUS_ASSOCIATED)
4811				queue_delayed_work(priv->workqueue,
4812						   &priv->request_scan,
4813						   round_jiffies_relative(HZ));
4814
4815			/* Send an empty event to user space.
4816			 * We don't send the received data on the event because
4817			 * it would require us to do complex transcoding, and
4818			 * we want to minimise the work done in the irq handler
4819			 * Use a request to extract the data.
4820			 * Also, we generate this even for any scan, regardless
4821			 * on how the scan was initiated. User space can just
4822			 * sync on periodic scan to get fresh data...
4823			 * Jean II */
4824			if (x->status == SCAN_COMPLETED_STATUS_COMPLETE)
4825				handle_scan_event(priv);
4826			break;
4827		}
4828
4829	case HOST_NOTIFICATION_STATUS_FRAG_LENGTH:{
4830			struct notif_frag_length *x = &notif->u.frag_len;
4831
4832			if (size == sizeof(*x))
4833				IPW_ERROR("Frag length: %d\n",
4834					  le16_to_cpu(x->frag_length));
4835			else
4836				IPW_ERROR("Frag length of wrong size %d "
4837					  "(should be %zd)\n",
4838					  size, sizeof(*x));
4839			break;
4840		}
4841
4842	case HOST_NOTIFICATION_STATUS_LINK_DETERIORATION:{
4843			struct notif_link_deterioration *x =
4844			    &notif->u.link_deterioration;
4845
4846			if (size == sizeof(*x)) {
4847				IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
4848					"link deterioration: type %d, cnt %d\n",
4849					x->silence_notification_type,
4850					x->silence_count);
4851				memcpy(&priv->last_link_deterioration, x,
4852				       sizeof(*x));
4853			} else {
4854				IPW_ERROR("Link Deterioration of wrong size %d "
4855					  "(should be %zd)\n",
4856					  size, sizeof(*x));
4857			}
4858			break;
4859		}
4860
4861	case HOST_NOTIFICATION_DINO_CONFIG_RESPONSE:{
4862			IPW_ERROR("Dino config\n");
4863			if (priv->hcmd
4864			    && priv->hcmd->cmd != HOST_CMD_DINO_CONFIG)
4865				IPW_ERROR("Unexpected DINO_CONFIG_RESPONSE\n");
4866
4867			break;
4868		}
4869
4870	case HOST_NOTIFICATION_STATUS_BEACON_STATE:{
4871			struct notif_beacon_state *x = &notif->u.beacon_state;
4872			if (size != sizeof(*x)) {
4873				IPW_ERROR
4874				    ("Beacon state of wrong size %d (should "
4875				     "be %zd)\n", size, sizeof(*x));
4876				break;
4877			}
4878
4879			if (le32_to_cpu(x->state) ==
4880			    HOST_NOTIFICATION_STATUS_BEACON_MISSING)
4881				ipw_handle_missed_beacon(priv,
4882							 le32_to_cpu(x->
4883								     number));
4884
4885			break;
4886		}
4887
4888	case HOST_NOTIFICATION_STATUS_TGI_TX_KEY:{
4889			struct notif_tgi_tx_key *x = &notif->u.tgi_tx_key;
4890			if (size == sizeof(*x)) {
4891				IPW_ERROR("TGi Tx Key: state 0x%02x sec type "
4892					  "0x%02x station %d\n",
4893					  x->key_state, x->security_type,
4894					  x->station_index);
4895				break;
4896			}
4897
4898			IPW_ERROR
4899			    ("TGi Tx Key of wrong size %d (should be %zd)\n",
4900			     size, sizeof(*x));
4901			break;
4902		}
4903
4904	case HOST_NOTIFICATION_CALIB_KEEP_RESULTS:{
4905			struct notif_calibration *x = &notif->u.calibration;
4906
4907			if (size == sizeof(*x)) {
4908				memcpy(&priv->calib, x, sizeof(*x));
4909				IPW_DEBUG_INFO("TODO: Calibration\n");
4910				break;
4911			}
4912
4913			IPW_ERROR
4914			    ("Calibration of wrong size %d (should be %zd)\n",
4915			     size, sizeof(*x));
4916			break;
4917		}
4918
4919	case HOST_NOTIFICATION_NOISE_STATS:{
4920			if (size == sizeof(u32)) {
4921				priv->exp_avg_noise =
4922				    exponential_average(priv->exp_avg_noise,
4923				    (u8) (le32_to_cpu(notif->u.noise.value) & 0xff),
4924				    DEPTH_NOISE);
4925				break;
4926			}
4927
4928			IPW_ERROR
4929			    ("Noise stat is wrong size %d (should be %zd)\n",
4930			     size, sizeof(u32));
4931			break;
4932		}
4933
4934	default:
4935		IPW_DEBUG_NOTIF("Unknown notification: "
4936				"subtype=%d,flags=0x%2x,size=%d\n",
4937				notif->subtype, notif->flags, size);
4938	}
4939}
4940
4941/**
4942 * Destroys all DMA structures and initialise them again
4943 *
4944 * @param priv
4945 * @return error code
4946 */
4947static int ipw_queue_reset(struct ipw_priv *priv)
4948{
4949	int rc = 0;
4950	/** @todo customize queue sizes */
4951	int nTx = 64, nTxCmd = 8;
4952	ipw_tx_queue_free(priv);
4953	/* Tx CMD queue */
4954	rc = ipw_queue_tx_init(priv, &priv->txq_cmd, nTxCmd,
4955			       IPW_TX_CMD_QUEUE_READ_INDEX,
4956			       IPW_TX_CMD_QUEUE_WRITE_INDEX,
4957			       IPW_TX_CMD_QUEUE_BD_BASE,
4958			       IPW_TX_CMD_QUEUE_BD_SIZE);
4959	if (rc) {
4960		IPW_ERROR("Tx Cmd queue init failed\n");
4961		goto error;
4962	}
4963	/* Tx queue(s) */
4964	rc = ipw_queue_tx_init(priv, &priv->txq[0], nTx,
4965			       IPW_TX_QUEUE_0_READ_INDEX,
4966			       IPW_TX_QUEUE_0_WRITE_INDEX,
4967			       IPW_TX_QUEUE_0_BD_BASE, IPW_TX_QUEUE_0_BD_SIZE);
4968	if (rc) {
4969		IPW_ERROR("Tx 0 queue init failed\n");
4970		goto error;
4971	}
4972	rc = ipw_queue_tx_init(priv, &priv->txq[1], nTx,
4973			       IPW_TX_QUEUE_1_READ_INDEX,
4974			       IPW_TX_QUEUE_1_WRITE_INDEX,
4975			       IPW_TX_QUEUE_1_BD_BASE, IPW_TX_QUEUE_1_BD_SIZE);
4976	if (rc) {
4977		IPW_ERROR("Tx 1 queue init failed\n");
4978		goto error;
4979	}
4980	rc = ipw_queue_tx_init(priv, &priv->txq[2], nTx,
4981			       IPW_TX_QUEUE_2_READ_INDEX,
4982			       IPW_TX_QUEUE_2_WRITE_INDEX,
4983			       IPW_TX_QUEUE_2_BD_BASE, IPW_TX_QUEUE_2_BD_SIZE);
4984	if (rc) {
4985		IPW_ERROR("Tx 2 queue init failed\n");
4986		goto error;
4987	}
4988	rc = ipw_queue_tx_init(priv, &priv->txq[3], nTx,
4989			       IPW_TX_QUEUE_3_READ_INDEX,
4990			       IPW_TX_QUEUE_3_WRITE_INDEX,
4991			       IPW_TX_QUEUE_3_BD_BASE, IPW_TX_QUEUE_3_BD_SIZE);
4992	if (rc) {
4993		IPW_ERROR("Tx 3 queue init failed\n");
4994		goto error;
4995	}
4996	/* statistics */
4997	priv->rx_bufs_min = 0;
4998	priv->rx_pend_max = 0;
4999	return rc;
5000
5001      error:
5002	ipw_tx_queue_free(priv);
5003	return rc;
5004}
5005
5006/**
5007 * Reclaim Tx queue entries no more used by NIC.
5008 *
5009 * When FW advances 'R' index, all entries between old and
5010 * new 'R' index need to be reclaimed. As result, some free space
5011 * forms. If there is enough free space (> low mark), wake Tx queue.
5012 *
5013 * @note Need to protect against garbage in 'R' index
5014 * @param priv
5015 * @param txq
5016 * @param qindex
5017 * @return Number of used entries remains in the queue
5018 */
5019static int ipw_queue_tx_reclaim(struct ipw_priv *priv,
5020				struct clx2_tx_queue *txq, int qindex)
5021{
5022	u32 hw_tail;
5023	int used;
5024	struct clx2_queue *q = &txq->q;
5025
5026	hw_tail = ipw_read32(priv, q->reg_r);
5027	if (hw_tail >= q->n_bd) {
5028		IPW_ERROR
5029		    ("Read index for DMA queue (%d) is out of range [0-%d)\n",
5030		     hw_tail, q->n_bd);
5031		goto done;
5032	}
5033	for (; q->last_used != hw_tail;
5034	     q->last_used = ipw_queue_inc_wrap(q->last_used, q->n_bd)) {
5035		ipw_queue_tx_free_tfd(priv, txq);
5036		priv->tx_packets++;
5037	}
5038      done:
5039	if ((ipw_tx_queue_space(q) > q->low_mark) &&
5040	    (qindex >= 0))
5041		netif_wake_queue(priv->net_dev);
5042	used = q->first_empty - q->last_used;
5043	if (used < 0)
5044		used += q->n_bd;
5045
5046	return used;
5047}
5048
5049static int ipw_queue_tx_hcmd(struct ipw_priv *priv, int hcmd, void *buf,
5050			     int len, int sync)
5051{
5052	struct clx2_tx_queue *txq = &priv->txq_cmd;
5053	struct clx2_queue *q = &txq->q;
5054	struct tfd_frame *tfd;
5055
5056	if (ipw_tx_queue_space(q) < (sync ? 1 : 2)) {
5057		IPW_ERROR("No space for Tx\n");
5058		return -EBUSY;
5059	}
5060
5061	tfd = &txq->bd[q->first_empty];
5062	txq->txb[q->first_empty] = NULL;
5063
5064	memset(tfd, 0, sizeof(*tfd));
5065	tfd->control_flags.message_type = TX_HOST_COMMAND_TYPE;
5066	tfd->control_flags.control_bits = TFD_NEED_IRQ_MASK;
5067	priv->hcmd_seq++;
5068	tfd->u.cmd.index = hcmd;
5069	tfd->u.cmd.length = len;
5070	memcpy(tfd->u.cmd.payload, buf, len);
5071	q->first_empty = ipw_queue_inc_wrap(q->first_empty, q->n_bd);
5072	ipw_write32(priv, q->reg_w, q->first_empty);
5073	_ipw_read32(priv, 0x90);
5074
5075	return 0;
5076}
5077
5078/*
5079 * Rx theory of operation
5080 *
5081 * The host allocates 32 DMA target addresses and passes the host address
5082 * to the firmware at register IPW_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
5083 * 0 to 31
5084 *
5085 * Rx Queue Indexes
5086 * The host/firmware share two index registers for managing the Rx buffers.
5087 *
5088 * The READ index maps to the first position that the firmware may be writing
5089 * to -- the driver can read up to (but not including) this position and get
5090 * good data.
5091 * The READ index is managed by the firmware once the card is enabled.
5092 *
5093 * The WRITE index maps to the last position the driver has read from -- the
5094 * position preceding WRITE is the last slot the firmware can place a packet.
5095 *
5096 * The queue is empty (no good data) if WRITE = READ - 1, and is full if
5097 * WRITE = READ.
5098 *
5099 * During initialization the host sets up the READ queue position to the first
5100 * INDEX position, and WRITE to the last (READ - 1 wrapped)
5101 *
5102 * When the firmware places a packet in a buffer it will advance the READ index
5103 * and fire the RX interrupt.  The driver can then query the READ index and
5104 * process as many packets as possible, moving the WRITE index forward as it
5105 * resets the Rx queue buffers with new memory.
5106 *
5107 * The management in the driver is as follows:
5108 * + A list of pre-allocated SKBs is stored in ipw->rxq->rx_free.  When
5109 *   ipw->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
5110 *   to replensish the ipw->rxq->rx_free.
5111 * + In ipw_rx_queue_replenish (scheduled) if 'processed' != 'read' then the
5112 *   ipw->rxq is replenished and the READ INDEX is updated (updating the
5113 *   'processed' and 'read' driver indexes as well)
5114 * + A received packet is processed and handed to the kernel network stack,
5115 *   detached from the ipw->rxq.  The driver 'processed' index is updated.
5116 * + The Host/Firmware ipw->rxq is replenished at tasklet time from the rx_free
5117 *   list. If there are no allocated buffers in ipw->rxq->rx_free, the READ
5118 *   INDEX is not incremented and ipw->status(RX_STALLED) is set.  If there
5119 *   were enough free buffers and RX_STALLED is set it is cleared.
5120 *
5121 *
5122 * Driver sequence:
5123 *
5124 * ipw_rx_queue_alloc()       Allocates rx_free
5125 * ipw_rx_queue_replenish()   Replenishes rx_free list from rx_used, and calls
5126 *                            ipw_rx_queue_restock
5127 * ipw_rx_queue_restock()     Moves available buffers from rx_free into Rx
5128 *                            queue, updates firmware pointers, and updates
5129 *                            the WRITE index.  If insufficient rx_free buffers
5130 *                            are available, schedules ipw_rx_queue_replenish
5131 *
5132 * -- enable interrupts --
5133 * ISR - ipw_rx()             Detach ipw_rx_mem_buffers from pool up to the
5134 *                            READ INDEX, detaching the SKB from the pool.
5135 *                            Moves the packet buffer from queue to rx_used.
5136 *                            Calls ipw_rx_queue_restock to refill any empty
5137 *                            slots.
5138 * ...
5139 *
5140 */
5141
5142/*
5143 * If there are slots in the RX queue that  need to be restocked,
5144 * and we have free pre-allocated buffers, fill the ranks as much
5145 * as we can pulling from rx_free.
5146 *
5147 * This moves the 'write' index forward to catch up with 'processed', and
5148 * also updates the memory address in the firmware to reference the new
5149 * target buffer.
5150 */
5151static void ipw_rx_queue_restock(struct ipw_priv *priv)
5152{
5153	struct ipw_rx_queue *rxq = priv->rxq;
5154	struct list_head *element;
5155	struct ipw_rx_mem_buffer *rxb;
5156	unsigned long flags;
5157	int write;
5158
5159	spin_lock_irqsave(&rxq->lock, flags);
5160	write = rxq->write;
5161	while ((ipw_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
5162		element = rxq->rx_free.next;
5163		rxb = list_entry(element, struct ipw_rx_mem_buffer, list);
5164		list_del(element);
5165
5166		ipw_write32(priv, IPW_RFDS_TABLE_LOWER + rxq->write * RFD_SIZE,
5167			    rxb->dma_addr);
5168		rxq->queue[rxq->write] = rxb;
5169		rxq->write = (rxq->write + 1) % RX_QUEUE_SIZE;
5170		rxq->free_count--;
5171	}
5172	spin_unlock_irqrestore(&rxq->lock, flags);
5173
5174	/* If the pre-allocated buffer pool is dropping low, schedule to
5175	 * refill it */
5176	if (rxq->free_count <= RX_LOW_WATERMARK)
5177		queue_work(priv->workqueue, &priv->rx_replenish);
5178
5179	/* If we've added more space for the firmware to place data, tell it */
5180	if (write != rxq->write)
5181		ipw_write32(priv, IPW_RX_WRITE_INDEX, rxq->write);
5182}
5183
5184/*
5185 * Move all used packet from rx_used to rx_free, allocating a new SKB for each.
5186 * Also restock the Rx queue via ipw_rx_queue_restock.
5187 *
5188 * This is called as a scheduled work item (except for during intialization)
5189 */
5190static void ipw_rx_queue_replenish(void *data)
5191{
5192	struct ipw_priv *priv = data;
5193	struct ipw_rx_queue *rxq = priv->rxq;
5194	struct list_head *element;
5195	struct ipw_rx_mem_buffer *rxb;
5196	unsigned long flags;
5197
5198	spin_lock_irqsave(&rxq->lock, flags);
5199	while (!list_empty(&rxq->rx_used)) {
5200		element = rxq->rx_used.next;
5201		rxb = list_entry(element, struct ipw_rx_mem_buffer, list);
5202		rxb->skb = alloc_skb(IPW_RX_BUF_SIZE, GFP_ATOMIC);
5203		if (!rxb->skb) {
5204			printk(KERN_CRIT "%s: Can not allocate SKB buffers.\n",
5205			       priv->net_dev->name);
5206			/* We don't reschedule replenish work here -- we will
5207			 * call the restock method and if it still needs
5208			 * more buffers it will schedule replenish */
5209			break;
5210		}
5211		list_del(element);
5212
5213		rxb->dma_addr =
5214		    pci_map_single(priv->pci_dev, rxb->skb->data,
5215				   IPW_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
5216
5217		list_add_tail(&rxb->list, &rxq->rx_free);
5218		rxq->free_count++;
5219	}
5220	spin_unlock_irqrestore(&rxq->lock, flags);
5221
5222	ipw_rx_queue_restock(priv);
5223}
5224
5225static void ipw_bg_rx_queue_replenish(struct work_struct *work)
5226{
5227	struct ipw_priv *priv =
5228		container_of(work, struct ipw_priv, rx_replenish);
5229	mutex_lock(&priv->mutex);
5230	ipw_rx_queue_replenish(priv);
5231	mutex_unlock(&priv->mutex);
5232}
5233
5234/* Assumes that the skb field of the buffers in 'pool' is kept accurate.
5235 * If an SKB has been detached, the POOL needs to have its SKB set to NULL
5236 * This free routine walks the list of POOL entries and if SKB is set to
5237 * non NULL it is unmapped and freed
5238 */
5239static void ipw_rx_queue_free(struct ipw_priv *priv, struct ipw_rx_queue *rxq)
5240{
5241	int i;
5242
5243	if (!rxq)
5244		return;
5245
5246	for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
5247		if (rxq->pool[i].skb != NULL) {
5248			pci_unmap_single(priv->pci_dev, rxq->pool[i].dma_addr,
5249					 IPW_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
5250			dev_kfree_skb(rxq->pool[i].skb);
5251		}
5252	}
5253
5254	kfree(rxq);
5255}
5256
5257static struct ipw_rx_queue *ipw_rx_queue_alloc(struct ipw_priv *priv)
5258{
5259	struct ipw_rx_queue *rxq;
5260	int i;
5261
5262	rxq = kzalloc(sizeof(*rxq), GFP_KERNEL);
5263	if (unlikely(!rxq)) {
5264		IPW_ERROR("memory allocation failed\n");
5265		return NULL;
5266	}
5267	spin_lock_init(&rxq->lock);
5268	INIT_LIST_HEAD(&rxq->rx_free);
5269	INIT_LIST_HEAD(&rxq->rx_used);
5270
5271	/* Fill the rx_used queue with _all_ of the Rx buffers */
5272	for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++)
5273		list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
5274
5275	/* Set us so that we have processed and used all buffers, but have
5276	 * not restocked the Rx queue with fresh buffers */
5277	rxq->read = rxq->write = 0;
5278	rxq->free_count = 0;
5279
5280	return rxq;
5281}
5282
5283static int ipw_is_rate_in_mask(struct ipw_priv *priv, int ieee_mode, u8 rate)
5284{
5285	rate &= ~LIBIPW_BASIC_RATE_MASK;
5286	if (ieee_mode == IEEE_A) {
5287		switch (rate) {
5288		case LIBIPW_OFDM_RATE_6MB:
5289			return priv->rates_mask & LIBIPW_OFDM_RATE_6MB_MASK ?
5290			    1 : 0;
5291		case LIBIPW_OFDM_RATE_9MB:
5292			return priv->rates_mask & LIBIPW_OFDM_RATE_9MB_MASK ?
5293			    1 : 0;
5294		case LIBIPW_OFDM_RATE_12MB:
5295			return priv->
5296			    rates_mask & LIBIPW_OFDM_RATE_12MB_MASK ? 1 : 0;
5297		case LIBIPW_OFDM_RATE_18MB:
5298			return priv->
5299			    rates_mask & LIBIPW_OFDM_RATE_18MB_MASK ? 1 : 0;
5300		case LIBIPW_OFDM_RATE_24MB:
5301			return priv->
5302			    rates_mask & LIBIPW_OFDM_RATE_24MB_MASK ? 1 : 0;
5303		case LIBIPW_OFDM_RATE_36MB:
5304			return priv->
5305			    rates_mask & LIBIPW_OFDM_RATE_36MB_MASK ? 1 : 0;
5306		case LIBIPW_OFDM_RATE_48MB:
5307			return priv->
5308			    rates_mask & LIBIPW_OFDM_RATE_48MB_MASK ? 1 : 0;
5309		case LIBIPW_OFDM_RATE_54MB:
5310			return priv->
5311			    rates_mask & LIBIPW_OFDM_RATE_54MB_MASK ? 1 : 0;
5312		default:
5313			return 0;
5314		}
5315	}
5316
5317	/* B and G mixed */
5318	switch (rate) {
5319	case LIBIPW_CCK_RATE_1MB:
5320		return priv->rates_mask & LIBIPW_CCK_RATE_1MB_MASK ? 1 : 0;
5321	case LIBIPW_CCK_RATE_2MB:
5322		return priv->rates_mask & LIBIPW_CCK_RATE_2MB_MASK ? 1 : 0;
5323	case LIBIPW_CCK_RATE_5MB:
5324		return priv->rates_mask & LIBIPW_CCK_RATE_5MB_MASK ? 1 : 0;
5325	case LIBIPW_CCK_RATE_11MB:
5326		return priv->rates_mask & LIBIPW_CCK_RATE_11MB_MASK ? 1 : 0;
5327	}
5328
5329	/* If we are limited to B modulations, bail at this point */
5330	if (ieee_mode == IEEE_B)
5331		return 0;
5332
5333	/* G */
5334	switch (rate) {
5335	case LIBIPW_OFDM_RATE_6MB:
5336		return priv->rates_mask & LIBIPW_OFDM_RATE_6MB_MASK ? 1 : 0;
5337	case LIBIPW_OFDM_RATE_9MB:
5338		return priv->rates_mask & LIBIPW_OFDM_RATE_9MB_MASK ? 1 : 0;
5339	case LIBIPW_OFDM_RATE_12MB:
5340		return priv->rates_mask & LIBIPW_OFDM_RATE_12MB_MASK ? 1 : 0;
5341	case LIBIPW_OFDM_RATE_18MB:
5342		return priv->rates_mask & LIBIPW_OFDM_RATE_18MB_MASK ? 1 : 0;
5343	case LIBIPW_OFDM_RATE_24MB:
5344		return priv->rates_mask & LIBIPW_OFDM_RATE_24MB_MASK ? 1 : 0;
5345	case LIBIPW_OFDM_RATE_36MB:
5346		return priv->rates_mask & LIBIPW_OFDM_RATE_36MB_MASK ? 1 : 0;
5347	case LIBIPW_OFDM_RATE_48MB:
5348		return priv->rates_mask & LIBIPW_OFDM_RATE_48MB_MASK ? 1 : 0;
5349	case LIBIPW_OFDM_RATE_54MB:
5350		return priv->rates_mask & LIBIPW_OFDM_RATE_54MB_MASK ? 1 : 0;
5351	}
5352
5353	return 0;
5354}
5355
5356static int ipw_compatible_rates(struct ipw_priv *priv,
5357				const struct libipw_network *network,
5358				struct ipw_supported_rates *rates)
5359{
5360	int num_rates, i;
5361
5362	memset(rates, 0, sizeof(*rates));
5363	num_rates = min(network->rates_len, (u8) IPW_MAX_RATES);
5364	rates->num_rates = 0;
5365	for (i = 0; i < num_rates; i++) {
5366		if (!ipw_is_rate_in_mask(priv, network->mode,
5367					 network->rates[i])) {
5368
5369			if (network->rates[i] & LIBIPW_BASIC_RATE_MASK) {
5370				IPW_DEBUG_SCAN("Adding masked mandatory "
5371					       "rate %02X\n",
5372					       network->rates[i]);
5373				rates->supported_rates[rates->num_rates++] =
5374				    network->rates[i];
5375				continue;
5376			}
5377
5378			IPW_DEBUG_SCAN("Rate %02X masked : 0x%08X\n",
5379				       network->rates[i], priv->rates_mask);
5380			continue;
5381		}
5382
5383		rates->supported_rates[rates->num_rates++] = network->rates[i];
5384	}
5385
5386	num_rates = min(network->rates_ex_len,
5387			(u8) (IPW_MAX_RATES - num_rates));
5388	for (i = 0; i < num_rates; i++) {
5389		if (!ipw_is_rate_in_mask(priv, network->mode,
5390					 network->rates_ex[i])) {
5391			if (network->rates_ex[i] & LIBIPW_BASIC_RATE_MASK) {
5392				IPW_DEBUG_SCAN("Adding masked mandatory "
5393					       "rate %02X\n",
5394					       network->rates_ex[i]);
5395				rates->supported_rates[rates->num_rates++] =
5396				    network->rates[i];
5397				continue;
5398			}
5399
5400			IPW_DEBUG_SCAN("Rate %02X masked : 0x%08X\n",
5401				       network->rates_ex[i], priv->rates_mask);
5402			continue;
5403		}
5404
5405		rates->supported_rates[rates->num_rates++] =
5406		    network->rates_ex[i];
5407	}
5408
5409	return 1;
5410}
5411
5412static void ipw_copy_rates(struct ipw_supported_rates *dest,
5413				  const struct ipw_supported_rates *src)
5414{
5415	u8 i;
5416	for (i = 0; i < src->num_rates; i++)
5417		dest->supported_rates[i] = src->supported_rates[i];
5418	dest->num_rates = src->num_rates;
5419}
5420
5421/* TODO: Look at sniffed packets in the air to determine if the basic rate
5422 * mask should ever be used -- right now all callers to add the scan rates are
5423 * set with the modulation = CCK, so BASIC_RATE_MASK is never set... */
5424static void ipw_add_cck_scan_rates(struct ipw_supported_rates *rates,
5425				   u8 modulation, u32 rate_mask)
5426{
5427	u8 basic_mask = (LIBIPW_OFDM_MODULATION == modulation) ?
5428	    LIBIPW_BASIC_RATE_MASK : 0;
5429
5430	if (rate_mask & LIBIPW_CCK_RATE_1MB_MASK)
5431		rates->supported_rates[rates->num_rates++] =
5432		    LIBIPW_BASIC_RATE_MASK | LIBIPW_CCK_RATE_1MB;
5433
5434	if (rate_mask & LIBIPW_CCK_RATE_2MB_MASK)
5435		rates->supported_rates[rates->num_rates++] =
5436		    LIBIPW_BASIC_RATE_MASK | LIBIPW_CCK_RATE_2MB;
5437
5438	if (rate_mask & LIBIPW_CCK_RATE_5MB_MASK)
5439		rates->supported_rates[rates->num_rates++] = basic_mask |
5440		    LIBIPW_CCK_RATE_5MB;
5441
5442	if (rate_mask & LIBIPW_CCK_RATE_11MB_MASK)
5443		rates->supported_rates[rates->num_rates++] = basic_mask |
5444		    LIBIPW_CCK_RATE_11MB;
5445}
5446
5447static void ipw_add_ofdm_scan_rates(struct ipw_supported_rates *rates,
5448				    u8 modulation, u32 rate_mask)
5449{
5450	u8 basic_mask = (LIBIPW_OFDM_MODULATION == modulation) ?
5451	    LIBIPW_BASIC_RATE_MASK : 0;
5452
5453	if (rate_mask & LIBIPW_OFDM_RATE_6MB_MASK)
5454		rates->supported_rates[rates->num_rates++] = basic_mask |
5455		    LIBIPW_OFDM_RATE_6MB;
5456
5457	if (rate_mask & LIBIPW_OFDM_RATE_9MB_MASK)
5458		rates->supported_rates[rates->num_rates++] =
5459		    LIBIPW_OFDM_RATE_9MB;
5460
5461	if (rate_mask & LIBIPW_OFDM_RATE_12MB_MASK)
5462		rates->supported_rates[rates->num_rates++] = basic_mask |
5463		    LIBIPW_OFDM_RATE_12MB;
5464
5465	if (rate_mask & LIBIPW_OFDM_RATE_18MB_MASK)
5466		rates->supported_rates[rates->num_rates++] =
5467		    LIBIPW_OFDM_RATE_18MB;
5468
5469	if (rate_mask & LIBIPW_OFDM_RATE_24MB_MASK)
5470		rates->supported_rates[rates->num_rates++] = basic_mask |
5471		    LIBIPW_OFDM_RATE_24MB;
5472
5473	if (rate_mask & LIBIPW_OFDM_RATE_36MB_MASK)
5474		rates->supported_rates[rates->num_rates++] =
5475		    LIBIPW_OFDM_RATE_36MB;
5476
5477	if (rate_mask & LIBIPW_OFDM_RATE_48MB_MASK)
5478		rates->supported_rates[rates->num_rates++] =
5479		    LIBIPW_OFDM_RATE_48MB;
5480
5481	if (rate_mask & LIBIPW_OFDM_RATE_54MB_MASK)
5482		rates->supported_rates[rates->num_rates++] =
5483		    LIBIPW_OFDM_RATE_54MB;
5484}
5485
5486struct ipw_network_match {
5487	struct libipw_network *network;
5488	struct ipw_supported_rates rates;
5489};
5490
5491static int ipw_find_adhoc_network(struct ipw_priv *priv,
5492				  struct ipw_network_match *match,
5493				  struct libipw_network *network,
5494				  int roaming)
5495{
5496	struct ipw_supported_rates rates;
5497	DECLARE_SSID_BUF(ssid);
5498
5499	/* Verify that this network's capability is compatible with the
5500	 * current mode (AdHoc or Infrastructure) */
5501	if ((priv->ieee->iw_mode == IW_MODE_ADHOC &&
5502	     !(network->capability & WLAN_CAPABILITY_IBSS))) {
5503		IPW_DEBUG_MERGE("Network '%s (%pM)' excluded due to "
5504				"capability mismatch.\n",
5505				print_ssid(ssid, network->ssid,
5506					   network->ssid_len),
5507				network->bssid);
5508		return 0;
5509	}
5510
5511	if (unlikely(roaming)) {
5512		/* If we are roaming, then ensure check if this is a valid
5513		 * network to try and roam to */
5514		if ((network->ssid_len != match->network->ssid_len) ||
5515		    memcmp(network->ssid, match->network->ssid,
5516			   network->ssid_len)) {
5517			IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5518					"because of non-network ESSID.\n",
5519					print_ssid(ssid, network->ssid,
5520						   network->ssid_len),
5521					network->bssid);
5522			return 0;
5523		}
5524	} else {
5525		/* If an ESSID has been configured then compare the broadcast
5526		 * ESSID to ours */
5527		if ((priv->config & CFG_STATIC_ESSID) &&
5528		    ((network->ssid_len != priv->essid_len) ||
5529		     memcmp(network->ssid, priv->essid,
5530			    min(network->ssid_len, priv->essid_len)))) {
5531			char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
5532
5533			strncpy(escaped,
5534				print_ssid(ssid, network->ssid,
5535					   network->ssid_len),
5536				sizeof(escaped));
5537			IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5538					"because of ESSID mismatch: '%s'.\n",
5539					escaped, network->bssid,
5540					print_ssid(ssid, priv->essid,
5541						   priv->essid_len));
5542			return 0;
5543		}
5544	}
5545
5546	/* If the old network rate is better than this one, don't bother
5547	 * testing everything else. */
5548
5549	if (network->time_stamp[0] < match->network->time_stamp[0]) {
5550		IPW_DEBUG_MERGE("Network '%s excluded because newer than "
5551				"current network.\n",
5552				print_ssid(ssid, match->network->ssid,
5553					   match->network->ssid_len));
5554		return 0;
5555	} else if (network->time_stamp[1] < match->network->time_stamp[1]) {
5556		IPW_DEBUG_MERGE("Network '%s excluded because newer than "
5557				"current network.\n",
5558				print_ssid(ssid, match->network->ssid,
5559					   match->network->ssid_len));
5560		return 0;
5561	}
5562
5563	/* Now go through and see if the requested network is valid... */
5564	if (priv->ieee->scan_age != 0 &&
5565	    time_after(jiffies, network->last_scanned + priv->ieee->scan_age)) {
5566		IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5567				"because of age: %ums.\n",
5568				print_ssid(ssid, network->ssid,
5569					   network->ssid_len),
5570				network->bssid,
5571				jiffies_to_msecs(jiffies -
5572						 network->last_scanned));
5573		return 0;
5574	}
5575
5576	if ((priv->config & CFG_STATIC_CHANNEL) &&
5577	    (network->channel != priv->channel)) {
5578		IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5579				"because of channel mismatch: %d != %d.\n",
5580				print_ssid(ssid, network->ssid,
5581					   network->ssid_len),
5582				network->bssid,
5583				network->channel, priv->channel);
5584		return 0;
5585	}
5586
5587	/* Verify privacy compatability */
5588	if (((priv->capability & CAP_PRIVACY_ON) ? 1 : 0) !=
5589	    ((network->capability & WLAN_CAPABILITY_PRIVACY) ? 1 : 0)) {
5590		IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5591				"because of privacy mismatch: %s != %s.\n",
5592				print_ssid(ssid, network->ssid,
5593					   network->ssid_len),
5594				network->bssid,
5595				priv->
5596				capability & CAP_PRIVACY_ON ? "on" : "off",
5597				network->
5598				capability & WLAN_CAPABILITY_PRIVACY ? "on" :
5599				"off");
5600		return 0;
5601	}
5602
5603	if (!memcmp(network->bssid, priv->bssid, ETH_ALEN)) {
5604		IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5605				"because of the same BSSID match: %pM"
5606				".\n", print_ssid(ssid, network->ssid,
5607						  network->ssid_len),
5608				network->bssid,
5609				priv->bssid);
5610		return 0;
5611	}
5612
5613	/* Filter out any incompatible freq / mode combinations */
5614	if (!libipw_is_valid_mode(priv->ieee, network->mode)) {
5615		IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5616				"because of invalid frequency/mode "
5617				"combination.\n",
5618				print_ssid(ssid, network->ssid,
5619					   network->ssid_len),
5620				network->bssid);
5621		return 0;
5622	}
5623
5624	/* Ensure that the rates supported by the driver are compatible with
5625	 * this AP, including verification of basic rates (mandatory) */
5626	if (!ipw_compatible_rates(priv, network, &rates)) {
5627		IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5628				"because configured rate mask excludes "
5629				"AP mandatory rate.\n",
5630				print_ssid(ssid, network->ssid,
5631					   network->ssid_len),
5632				network->bssid);
5633		return 0;
5634	}
5635
5636	if (rates.num_rates == 0) {
5637		IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5638				"because of no compatible rates.\n",
5639				print_ssid(ssid, network->ssid,
5640					   network->ssid_len),
5641				network->bssid);
5642		return 0;
5643	}
5644
5645	/* TODO: Perform any further minimal comparititive tests.  We do not
5646	 * want to put too much policy logic here; intelligent scan selection
5647	 * should occur within a generic IEEE 802.11 user space tool.  */
5648
5649	/* Set up 'new' AP to this network */
5650	ipw_copy_rates(&match->rates, &rates);
5651	match->network = network;
5652	IPW_DEBUG_MERGE("Network '%s (%pM)' is a viable match.\n",
5653			print_ssid(ssid, network->ssid, network->ssid_len),
5654			network->bssid);
5655
5656	return 1;
5657}
5658
5659static void ipw_merge_adhoc_network(struct work_struct *work)
5660{
5661	DECLARE_SSID_BUF(ssid);
5662	struct ipw_priv *priv =
5663		container_of(work, struct ipw_priv, merge_networks);
5664	struct libipw_network *network = NULL;
5665	struct ipw_network_match match = {
5666		.network = priv->assoc_network
5667	};
5668
5669	if ((priv->status & STATUS_ASSOCIATED) &&
5670	    (priv->ieee->iw_mode == IW_MODE_ADHOC)) {
5671		/* First pass through ROAM process -- look for a better
5672		 * network */
5673		unsigned long flags;
5674
5675		spin_lock_irqsave(&priv->ieee->lock, flags);
5676		list_for_each_entry(network, &priv->ieee->network_list, list) {
5677			if (network != priv->assoc_network)
5678				ipw_find_adhoc_network(priv, &match, network,
5679						       1);
5680		}
5681		spin_unlock_irqrestore(&priv->ieee->lock, flags);
5682
5683		if (match.network == priv->assoc_network) {
5684			IPW_DEBUG_MERGE("No better ADHOC in this network to "
5685					"merge to.\n");
5686			return;
5687		}
5688
5689		mutex_lock(&priv->mutex);
5690		if ((priv->ieee->iw_mode == IW_MODE_ADHOC)) {
5691			IPW_DEBUG_MERGE("remove network %s\n",
5692					print_ssid(ssid, priv->essid,
5693						   priv->essid_len));
5694			ipw_remove_current_network(priv);
5695		}
5696
5697		ipw_disassociate(priv);
5698		priv->assoc_network = match.network;
5699		mutex_unlock(&priv->mutex);
5700		return;
5701	}
5702}
5703
5704static int ipw_best_network(struct ipw_priv *priv,
5705			    struct ipw_network_match *match,
5706			    struct libipw_network *network, int roaming)
5707{
5708	struct ipw_supported_rates rates;
5709	DECLARE_SSID_BUF(ssid);
5710
5711	/* Verify that this network's capability is compatible with the
5712	 * current mode (AdHoc or Infrastructure) */
5713	if ((priv->ieee->iw_mode == IW_MODE_INFRA &&
5714	     !(network->capability & WLAN_CAPABILITY_ESS)) ||
5715	    (priv->ieee->iw_mode == IW_MODE_ADHOC &&
5716	     !(network->capability & WLAN_CAPABILITY_IBSS))) {
5717		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded due to "
5718				"capability mismatch.\n",
5719				print_ssid(ssid, network->ssid,
5720					   network->ssid_len),
5721				network->bssid);
5722		return 0;
5723	}
5724
5725	if (unlikely(roaming)) {
5726		/* If we are roaming, then ensure check if this is a valid
5727		 * network to try and roam to */
5728		if ((network->ssid_len != match->network->ssid_len) ||
5729		    memcmp(network->ssid, match->network->ssid,
5730			   network->ssid_len)) {
5731			IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5732					"because of non-network ESSID.\n",
5733					print_ssid(ssid, network->ssid,
5734						   network->ssid_len),
5735					network->bssid);
5736			return 0;
5737		}
5738	} else {
5739		/* If an ESSID has been configured then compare the broadcast
5740		 * ESSID to ours */
5741		if ((priv->config & CFG_STATIC_ESSID) &&
5742		    ((network->ssid_len != priv->essid_len) ||
5743		     memcmp(network->ssid, priv->essid,
5744			    min(network->ssid_len, priv->essid_len)))) {
5745			char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
5746			strncpy(escaped,
5747				print_ssid(ssid, network->ssid,
5748					   network->ssid_len),
5749				sizeof(escaped));
5750			IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5751					"because of ESSID mismatch: '%s'.\n",
5752					escaped, network->bssid,
5753					print_ssid(ssid, priv->essid,
5754						   priv->essid_len));
5755			return 0;
5756		}
5757	}
5758
5759	/* If the old network rate is better than this one, don't bother
5760	 * testing everything else. */
5761	if (match->network && match->network->stats.rssi > network->stats.rssi) {
5762		char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
5763		strncpy(escaped,
5764			print_ssid(ssid, network->ssid, network->ssid_len),
5765			sizeof(escaped));
5766		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded because "
5767				"'%s (%pM)' has a stronger signal.\n",
5768				escaped, network->bssid,
5769				print_ssid(ssid, match->network->ssid,
5770					   match->network->ssid_len),
5771				match->network->bssid);
5772		return 0;
5773	}
5774
5775	/* If this network has already had an association attempt within the
5776	 * last 3 seconds, do not try and associate again... */
5777	if (network->last_associate &&
5778	    time_after(network->last_associate + (HZ * 3UL), jiffies)) {
5779		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5780				"because of storming (%ums since last "
5781				"assoc attempt).\n",
5782				print_ssid(ssid, network->ssid,
5783					   network->ssid_len),
5784				network->bssid,
5785				jiffies_to_msecs(jiffies -
5786						 network->last_associate));
5787		return 0;
5788	}
5789
5790	/* Now go through and see if the requested network is valid... */
5791	if (priv->ieee->scan_age != 0 &&
5792	    time_after(jiffies, network->last_scanned + priv->ieee->scan_age)) {
5793		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5794				"because of age: %ums.\n",
5795				print_ssid(ssid, network->ssid,
5796					   network->ssid_len),
5797				network->bssid,
5798				jiffies_to_msecs(jiffies -
5799						 network->last_scanned));
5800		return 0;
5801	}
5802
5803	if ((priv->config & CFG_STATIC_CHANNEL) &&
5804	    (network->channel != priv->channel)) {
5805		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5806				"because of channel mismatch: %d != %d.\n",
5807				print_ssid(ssid, network->ssid,
5808					   network->ssid_len),
5809				network->bssid,
5810				network->channel, priv->channel);
5811		return 0;
5812	}
5813
5814	/* Verify privacy compatability */
5815	if (((priv->capability & CAP_PRIVACY_ON) ? 1 : 0) !=
5816	    ((network->capability & WLAN_CAPABILITY_PRIVACY) ? 1 : 0)) {
5817		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5818				"because of privacy mismatch: %s != %s.\n",
5819				print_ssid(ssid, network->ssid,
5820					   network->ssid_len),
5821				network->bssid,
5822				priv->capability & CAP_PRIVACY_ON ? "on" :
5823				"off",
5824				network->capability &
5825				WLAN_CAPABILITY_PRIVACY ? "on" : "off");
5826		return 0;
5827	}
5828
5829	if ((priv->config & CFG_STATIC_BSSID) &&
5830	    memcmp(network->bssid, priv->bssid, ETH_ALEN)) {
5831		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5832				"because of BSSID mismatch: %pM.\n",
5833				print_ssid(ssid, network->ssid,
5834					   network->ssid_len),
5835				network->bssid, priv->bssid);
5836		return 0;
5837	}
5838
5839	/* Filter out any incompatible freq / mode combinations */
5840	if (!libipw_is_valid_mode(priv->ieee, network->mode)) {
5841		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5842				"because of invalid frequency/mode "
5843				"combination.\n",
5844				print_ssid(ssid, network->ssid,
5845					   network->ssid_len),
5846				network->bssid);
5847		return 0;
5848	}
5849
5850	/* Filter out invalid channel in current GEO */
5851	if (!libipw_is_valid_channel(priv->ieee, network->channel)) {
5852		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5853				"because of invalid channel in current GEO\n",
5854				print_ssid(ssid, network->ssid,
5855					   network->ssid_len),
5856				network->bssid);
5857		return 0;
5858	}
5859
5860	/* Ensure that the rates supported by the driver are compatible with
5861	 * this AP, including verification of basic rates (mandatory) */
5862	if (!ipw_compatible_rates(priv, network, &rates)) {
5863		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5864				"because configured rate mask excludes "
5865				"AP mandatory rate.\n",
5866				print_ssid(ssid, network->ssid,
5867					   network->ssid_len),
5868				network->bssid);
5869		return 0;
5870	}
5871
5872	if (rates.num_rates == 0) {
5873		IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5874				"because of no compatible rates.\n",
5875				print_ssid(ssid, network->ssid,
5876					   network->ssid_len),
5877				network->bssid);
5878		return 0;
5879	}
5880
5881	/* TODO: Perform any further minimal comparititive tests.  We do not
5882	 * want to put too much policy logic here; intelligent scan selection
5883	 * should occur within a generic IEEE 802.11 user space tool.  */
5884
5885	/* Set up 'new' AP to this network */
5886	ipw_copy_rates(&match->rates, &rates);
5887	match->network = network;
5888
5889	IPW_DEBUG_ASSOC("Network '%s (%pM)' is a viable match.\n",
5890			print_ssid(ssid, network->ssid, network->ssid_len),
5891			network->bssid);
5892
5893	return 1;
5894}
5895
5896static void ipw_adhoc_create(struct ipw_priv *priv,
5897			     struct libipw_network *network)
5898{
5899	const struct libipw_geo *geo = libipw_get_geo(priv->ieee);
5900	int i;
5901
5902	/*
5903	 * For the purposes of scanning, we can set our wireless mode
5904	 * to trigger scans across combinations of bands, but when it
5905	 * comes to creating a new ad-hoc network, we have tell the FW
5906	 * exactly which band to use.
5907	 *
5908	 * We also have the possibility of an invalid channel for the
5909	 * chossen band.  Attempting to create a new ad-hoc network
5910	 * with an invalid channel for wireless mode will trigger a
5911	 * FW fatal error.
5912	 *
5913	 */
5914	switch (libipw_is_valid_channel(priv->ieee, priv->channel)) {
5915	case LIBIPW_52GHZ_BAND:
5916		network->mode = IEEE_A;
5917		i = libipw_channel_to_index(priv->ieee, priv->channel);
5918		BUG_ON(i == -1);
5919		if (geo->a[i].flags & LIBIPW_CH_PASSIVE_ONLY) {
5920			IPW_WARNING("Overriding invalid channel\n");
5921			priv->channel = geo->a[0].channel;
5922		}
5923		break;
5924
5925	case LIBIPW_24GHZ_BAND:
5926		if (priv->ieee->mode & IEEE_G)
5927			network->mode = IEEE_G;
5928		else
5929			network->mode = IEEE_B;
5930		i = libipw_channel_to_index(priv->ieee, priv->channel);
5931		BUG_ON(i == -1);
5932		if (geo->bg[i].flags & LIBIPW_CH_PASSIVE_ONLY) {
5933			IPW_WARNING("Overriding invalid channel\n");
5934			priv->channel = geo->bg[0].channel;
5935		}
5936		break;
5937
5938	default:
5939		IPW_WARNING("Overriding invalid channel\n");
5940		if (priv->ieee->mode & IEEE_A) {
5941			network->mode = IEEE_A;
5942			priv->channel = geo->a[0].channel;
5943		} else if (priv->ieee->mode & IEEE_G) {
5944			network->mode = IEEE_G;
5945			priv->channel = geo->bg[0].channel;
5946		} else {
5947			network->mode = IEEE_B;
5948			priv->channel = geo->bg[0].channel;
5949		}
5950		break;
5951	}
5952
5953	network->channel = priv->channel;
5954	priv->config |= CFG_ADHOC_PERSIST;
5955	ipw_create_bssid(priv, network->bssid);
5956	network->ssid_len = priv->essid_len;
5957	memcpy(network->ssid, priv->essid, priv->essid_len);
5958	memset(&network->stats, 0, sizeof(network->stats));
5959	network->capability = WLAN_CAPABILITY_IBSS;
5960	if (!(priv->config & CFG_PREAMBLE_LONG))
5961		network->capability |= WLAN_CAPABILITY_SHORT_PREAMBLE;
5962	if (priv->capability & CAP_PRIVACY_ON)
5963		network->capability |= WLAN_CAPABILITY_PRIVACY;
5964	network->rates_len = min(priv->rates.num_rates, MAX_RATES_LENGTH);
5965	memcpy(network->rates, priv->rates.supported_rates, network->rates_len);
5966	network->rates_ex_len = priv->rates.num_rates - network->rates_len;
5967	memcpy(network->rates_ex,
5968	       &priv->rates.supported_rates[network->rates_len],
5969	       network->rates_ex_len);
5970	network->last_scanned = 0;
5971	network->flags = 0;
5972	network->last_associate = 0;
5973	network->time_stamp[0] = 0;
5974	network->time_stamp[1] = 0;
5975	network->beacon_interval = 100;	/* Default */
5976	network->listen_interval = 10;	/* Default */
5977	network->atim_window = 0;	/* Default */
5978	network->wpa_ie_len = 0;
5979	network->rsn_ie_len = 0;
5980}
5981
5982static void ipw_send_tgi_tx_key(struct ipw_priv *priv, int type, int index)
5983{
5984	struct ipw_tgi_tx_key key;
5985
5986	if (!(priv->ieee->sec.flags & (1 << index)))
5987		return;
5988
5989	key.key_id = index;
5990	memcpy(key.key, priv->ieee->sec.keys[index], SCM_TEMPORAL_KEY_LENGTH);
5991	key.security_type = type;
5992	key.station_index = 0;	/* always 0 for BSS */
5993	key.flags = 0;
5994	/* 0 for new key; previous value of counter (after fatal error) */
5995	key.tx_counter[0] = cpu_to_le32(0);
5996	key.tx_counter[1] = cpu_to_le32(0);
5997
5998	ipw_send_cmd_pdu(priv, IPW_CMD_TGI_TX_KEY, sizeof(key), &key);
5999}
6000
6001static void ipw_send_wep_keys(struct ipw_priv *priv, int type)
6002{
6003	struct ipw_wep_key key;
6004	int i;
6005
6006	key.cmd_id = DINO_CMD_WEP_KEY;
6007	key.seq_num = 0;
6008
6009	/* Note: AES keys cannot be set for multiple times.
6010	 * Only set it at the first time. */
6011	for (i = 0; i < 4; i++) {
6012		key.key_index = i | type;
6013		if (!(priv->ieee->sec.flags & (1 << i))) {
6014			key.key_size = 0;
6015			continue;
6016		}
6017
6018		key.key_size = priv->ieee->sec.key_sizes[i];
6019		memcpy(key.key, priv->ieee->sec.keys[i], key.key_size);
6020
6021		ipw_send_cmd_pdu(priv, IPW_CMD_WEP_KEY, sizeof(key), &key);
6022	}
6023}
6024
6025static void ipw_set_hw_decrypt_unicast(struct ipw_priv *priv, int level)
6026{
6027	if (priv->ieee->host_encrypt)
6028		return;
6029
6030	switch (level) {
6031	case SEC_LEVEL_3:
6032		priv->sys_config.disable_unicast_decryption = 0;
6033		priv->ieee->host_decrypt = 0;
6034		break;
6035	case SEC_LEVEL_2:
6036		priv->sys_config.disable_unicast_decryption = 1;
6037		priv->ieee->host_decrypt = 1;
6038		break;
6039	case SEC_LEVEL_1:
6040		priv->sys_config.disable_unicast_decryption = 0;
6041		priv->ieee->host_decrypt = 0;
6042		break;
6043	case SEC_LEVEL_0:
6044		priv->sys_config.disable_unicast_decryption = 1;
6045		break;
6046	default:
6047		break;
6048	}
6049}
6050
6051static void ipw_set_hw_decrypt_multicast(struct ipw_priv *priv, int level)
6052{
6053	if (priv->ieee->host_encrypt)
6054		return;
6055
6056	switch (level) {
6057	case SEC_LEVEL_3:
6058		priv->sys_config.disable_multicast_decryption = 0;
6059		break;
6060	case SEC_LEVEL_2:
6061		priv->sys_config.disable_multicast_decryption = 1;
6062		break;
6063	case SEC_LEVEL_1:
6064		priv->sys_config.disable_multicast_decryption = 0;
6065		break;
6066	case SEC_LEVEL_0:
6067		priv->sys_config.disable_multicast_decryption = 1;
6068		break;
6069	default:
6070		break;
6071	}
6072}
6073
6074static void ipw_set_hwcrypto_keys(struct ipw_priv *priv)
6075{
6076	switch (priv->ieee->sec.level) {
6077	case SEC_LEVEL_3:
6078		if (priv->ieee->sec.flags & SEC_ACTIVE_KEY)
6079			ipw_send_tgi_tx_key(priv,
6080					    DCT_FLAG_EXT_SECURITY_CCM,
6081					    priv->ieee->sec.active_key);
6082
6083		if (!priv->ieee->host_mc_decrypt)
6084			ipw_send_wep_keys(priv, DCW_WEP_KEY_SEC_TYPE_CCM);
6085		break;
6086	case SEC_LEVEL_2:
6087		if (priv->ieee->sec.flags & SEC_ACTIVE_KEY)
6088			ipw_send_tgi_tx_key(priv,
6089					    DCT_FLAG_EXT_SECURITY_TKIP,
6090					    priv->ieee->sec.active_key);
6091		break;
6092	case SEC_LEVEL_1:
6093		ipw_send_wep_keys(priv, DCW_WEP_KEY_SEC_TYPE_WEP);
6094		ipw_set_hw_decrypt_unicast(priv, priv->ieee->sec.level);
6095		ipw_set_hw_decrypt_multicast(priv, priv->ieee->sec.level);
6096		break;
6097	case SEC_LEVEL_0:
6098	default:
6099		break;
6100	}
6101}
6102
6103static void ipw_adhoc_check(void *data)
6104{
6105	struct ipw_priv *priv = data;
6106
6107	if (priv->missed_adhoc_beacons++ > priv->disassociate_threshold &&
6108	    !(priv->config & CFG_ADHOC_PERSIST)) {
6109		IPW_DEBUG(IPW_DL_INFO | IPW_DL_NOTIF |
6110			  IPW_DL_STATE | IPW_DL_ASSOC,
6111			  "Missed beacon: %d - disassociate\n",
6112			  priv->missed_adhoc_beacons);
6113		ipw_remove_current_network(priv);
6114		ipw_disassociate(priv);
6115		return;
6116	}
6117
6118	queue_delayed_work(priv->workqueue, &priv->adhoc_check,
6119			   le16_to_cpu(priv->assoc_request.beacon_interval));
6120}
6121
6122static void ipw_bg_adhoc_check(struct work_struct *work)
6123{
6124	struct ipw_priv *priv =
6125		container_of(work, struct ipw_priv, adhoc_check.work);
6126	mutex_lock(&priv->mutex);
6127	ipw_adhoc_check(priv);
6128	mutex_unlock(&priv->mutex);
6129}
6130
6131static void ipw_debug_config(struct ipw_priv *priv)
6132{
6133	DECLARE_SSID_BUF(ssid);
6134	IPW_DEBUG_INFO("Scan completed, no valid APs matched "
6135		       "[CFG 0x%08X]\n", priv->config);
6136	if (priv->config & CFG_STATIC_CHANNEL)
6137		IPW_DEBUG_INFO("Channel locked to %d\n", priv->channel);
6138	else
6139		IPW_DEBUG_INFO("Channel unlocked.\n");
6140	if (priv->config & CFG_STATIC_ESSID)
6141		IPW_DEBUG_INFO("ESSID locked to '%s'\n",
6142			       print_ssid(ssid, priv->essid, priv->essid_len));
6143	else
6144		IPW_DEBUG_INFO("ESSID unlocked.\n");
6145	if (priv->config & CFG_STATIC_BSSID)
6146		IPW_DEBUG_INFO("BSSID locked to %pM\n", priv->bssid);
6147	else
6148		IPW_DEBUG_INFO("BSSID unlocked.\n");
6149	if (priv->capability & CAP_PRIVACY_ON)
6150		IPW_DEBUG_INFO("PRIVACY on\n");
6151	else
6152		IPW_DEBUG_INFO("PRIVACY off\n");
6153	IPW_DEBUG_INFO("RATE MASK: 0x%08X\n", priv->rates_mask);
6154}
6155
6156static void ipw_set_fixed_rate(struct ipw_priv *priv, int mode)
6157{
6158	/* TODO: Verify that this works... */
6159	struct ipw_fixed_rate fr;
6160	u32 reg;
6161	u16 mask = 0;
6162	u16 new_tx_rates = priv->rates_mask;
6163
6164	/* Identify 'current FW band' and match it with the fixed
6165	 * Tx rates */
6166
6167	switch (priv->ieee->freq_band) {
6168	case LIBIPW_52GHZ_BAND:	/* A only */
6169		/* IEEE_A */
6170		if (priv->rates_mask & ~LIBIPW_OFDM_RATES_MASK) {
6171			/* Invalid fixed rate mask */
6172			IPW_DEBUG_WX
6173			    ("invalid fixed rate mask in ipw_set_fixed_rate\n");
6174			new_tx_rates = 0;
6175			break;
6176		}
6177
6178		new_tx_rates >>= LIBIPW_OFDM_SHIFT_MASK_A;
6179		break;
6180
6181	default:		/* 2.4Ghz or Mixed */
6182		/* IEEE_B */
6183		if (mode == IEEE_B) {
6184			if (new_tx_rates & ~LIBIPW_CCK_RATES_MASK) {
6185				/* Invalid fixed rate mask */
6186				IPW_DEBUG_WX
6187				    ("invalid fixed rate mask in ipw_set_fixed_rate\n");
6188				new_tx_rates = 0;
6189			}
6190			break;
6191		}
6192
6193		/* IEEE_G */
6194		if (new_tx_rates & ~(LIBIPW_CCK_RATES_MASK |
6195				    LIBIPW_OFDM_RATES_MASK)) {
6196			/* Invalid fixed rate mask */
6197			IPW_DEBUG_WX
6198			    ("invalid fixed rate mask in ipw_set_fixed_rate\n");
6199			new_tx_rates = 0;
6200			break;
6201		}
6202
6203		if (LIBIPW_OFDM_RATE_6MB_MASK & new_tx_rates) {
6204			mask |= (LIBIPW_OFDM_RATE_6MB_MASK >> 1);
6205			new_tx_rates &= ~LIBIPW_OFDM_RATE_6MB_MASK;
6206		}
6207
6208		if (LIBIPW_OFDM_RATE_9MB_MASK & new_tx_rates) {
6209			mask |= (LIBIPW_OFDM_RATE_9MB_MASK >> 1);
6210			new_tx_rates &= ~LIBIPW_OFDM_RATE_9MB_MASK;
6211		}
6212
6213		if (LIBIPW_OFDM_RATE_12MB_MASK & new_tx_rates) {
6214			mask |= (LIBIPW_OFDM_RATE_12MB_MASK >> 1);
6215			new_tx_rates &= ~LIBIPW_OFDM_RATE_12MB_MASK;
6216		}
6217
6218		new_tx_rates |= mask;
6219		break;
6220	}
6221
6222	fr.tx_rates = cpu_to_le16(new_tx_rates);
6223
6224	reg = ipw_read32(priv, IPW_MEM_FIXED_OVERRIDE);
6225	ipw_write_reg32(priv, reg, *(u32 *) & fr);
6226}
6227
6228static void ipw_abort_scan(struct ipw_priv *priv)
6229{
6230	int err;
6231
6232	if (priv->status & STATUS_SCAN_ABORTING) {
6233		IPW_DEBUG_HC("Ignoring concurrent scan abort request.\n");
6234		return;
6235	}
6236	priv->status |= STATUS_SCAN_ABORTING;
6237
6238	err = ipw_send_scan_abort(priv);
6239	if (err)
6240		IPW_DEBUG_HC("Request to abort scan failed.\n");
6241}
6242
6243static void ipw_add_scan_channels(struct ipw_priv *priv,
6244				  struct ipw_scan_request_ext *scan,
6245				  int scan_type)
6246{
6247	int channel_index = 0;
6248	const struct libipw_geo *geo;
6249	int i;
6250
6251	geo = libipw_get_geo(priv->ieee);
6252
6253	if (priv->ieee->freq_band & LIBIPW_52GHZ_BAND) {
6254		int start = channel_index;
6255		for (i = 0; i < geo->a_channels; i++) {
6256			if ((priv->status & STATUS_ASSOCIATED) &&
6257			    geo->a[i].channel == priv->channel)
6258				continue;
6259			channel_index++;
6260			scan->channels_list[channel_index] = geo->a[i].channel;
6261			ipw_set_scan_type(scan, channel_index,
6262					  geo->a[i].
6263					  flags & LIBIPW_CH_PASSIVE_ONLY ?
6264					  IPW_SCAN_PASSIVE_FULL_DWELL_SCAN :
6265					  scan_type);
6266		}
6267
6268		if (start != channel_index) {
6269			scan->channels_list[start] = (u8) (IPW_A_MODE << 6) |
6270			    (channel_index - start);
6271			channel_index++;
6272		}
6273	}
6274
6275	if (priv->ieee->freq_band & LIBIPW_24GHZ_BAND) {
6276		int start = channel_index;
6277		if (priv->config & CFG_SPEED_SCAN) {
6278			int index;
6279			u8 channels[LIBIPW_24GHZ_CHANNELS] = {
6280				/* nop out the list */
6281				[0] = 0
6282			};
6283
6284			u8 channel;
6285			while (channel_index < IPW_SCAN_CHANNELS - 1) {
6286				channel =
6287				    priv->speed_scan[priv->speed_scan_pos];
6288				if (channel == 0) {
6289					priv->speed_scan_pos = 0;
6290					channel = priv->speed_scan[0];
6291				}
6292				if ((priv->status & STATUS_ASSOCIATED) &&
6293				    channel == priv->channel) {
6294					priv->speed_scan_pos++;
6295					continue;
6296				}
6297
6298				/* If this channel has already been
6299				 * added in scan, break from loop
6300				 * and this will be the first channel
6301				 * in the next scan.
6302				 */
6303				if (channels[channel - 1] != 0)
6304					break;
6305
6306				channels[channel - 1] = 1;
6307				priv->speed_scan_pos++;
6308				channel_index++;
6309				scan->channels_list[channel_index] = channel;
6310				index =
6311				    libipw_channel_to_index(priv->ieee, channel);
6312				ipw_set_scan_type(scan, channel_index,
6313						  geo->bg[index].
6314						  flags &
6315						  LIBIPW_CH_PASSIVE_ONLY ?
6316						  IPW_SCAN_PASSIVE_FULL_DWELL_SCAN
6317						  : scan_type);
6318			}
6319		} else {
6320			for (i = 0; i < geo->bg_channels; i++) {
6321				if ((priv->status & STATUS_ASSOCIATED) &&
6322				    geo->bg[i].channel == priv->channel)
6323					continue;
6324				channel_index++;
6325				scan->channels_list[channel_index] =
6326				    geo->bg[i].channel;
6327				ipw_set_scan_type(scan, channel_index,
6328						  geo->bg[i].
6329						  flags &
6330						  LIBIPW_CH_PASSIVE_ONLY ?
6331						  IPW_SCAN_PASSIVE_FULL_DWELL_SCAN
6332						  : scan_type);
6333			}
6334		}
6335
6336		if (start != channel_index) {
6337			scan->channels_list[start] = (u8) (IPW_B_MODE << 6) |
6338			    (channel_index - start);
6339		}
6340	}
6341}
6342
6343static int ipw_passive_dwell_time(struct ipw_priv *priv)
6344{
6345	/* staying on passive channels longer than the DTIM interval during a
6346	 * scan, while associated, causes the firmware to cancel the scan
6347	 * without notification. Hence, don't stay on passive channels longer
6348	 * than the beacon interval.
6349	 */
6350	if (priv->status & STATUS_ASSOCIATED
6351	    && priv->assoc_network->beacon_interval > 10)
6352		return priv->assoc_network->beacon_interval - 10;
6353	else
6354		return 120;
6355}
6356
6357static int ipw_request_scan_helper(struct ipw_priv *priv, int type, int direct)
6358{
6359	struct ipw_scan_request_ext scan;
6360	int err = 0, scan_type;
6361
6362	if (!(priv->status & STATUS_INIT) ||
6363	    (priv->status & STATUS_EXIT_PENDING))
6364		return 0;
6365
6366	mutex_lock(&priv->mutex);
6367
6368	if (direct && (priv->direct_scan_ssid_len == 0)) {
6369		IPW_DEBUG_HC("Direct scan requested but no SSID to scan for\n");
6370		priv->status &= ~STATUS_DIRECT_SCAN_PENDING;
6371		goto done;
6372	}
6373
6374	if (priv->status & STATUS_SCANNING) {
6375		IPW_DEBUG_HC("Concurrent scan requested.  Queuing.\n");
6376		priv->status |= direct ? STATUS_DIRECT_SCAN_PENDING :
6377					STATUS_SCAN_PENDING;
6378		goto done;
6379	}
6380
6381	if (!(priv->status & STATUS_SCAN_FORCED) &&
6382	    priv->status & STATUS_SCAN_ABORTING) {
6383		IPW_DEBUG_HC("Scan request while abort pending.  Queuing.\n");
6384		priv->status |= direct ? STATUS_DIRECT_SCAN_PENDING :
6385					STATUS_SCAN_PENDING;
6386		goto done;
6387	}
6388
6389	if (priv->status & STATUS_RF_KILL_MASK) {
6390		IPW_DEBUG_HC("Queuing scan due to RF Kill activation\n");
6391		priv->status |= direct ? STATUS_DIRECT_SCAN_PENDING :
6392					STATUS_SCAN_PENDING;
6393		goto done;
6394	}
6395
6396	memset(&scan, 0, sizeof(scan));
6397	scan.full_scan_index = cpu_to_le32(libipw_get_scans(priv->ieee));
6398
6399	if (type == IW_SCAN_TYPE_PASSIVE) {
6400		IPW_DEBUG_WX("use passive scanning\n");
6401		scan_type = IPW_SCAN_PASSIVE_FULL_DWELL_SCAN;
6402		scan.dwell_time[IPW_SCAN_PASSIVE_FULL_DWELL_SCAN] =
6403			cpu_to_le16(ipw_passive_dwell_time(priv));
6404		ipw_add_scan_channels(priv, &scan, scan_type);
6405		goto send_request;
6406	}
6407
6408	/* Use active scan by default. */
6409	if (priv->config & CFG_SPEED_SCAN)
6410		scan.dwell_time[IPW_SCAN_ACTIVE_BROADCAST_SCAN] =
6411			cpu_to_le16(30);
6412	else
6413		scan.dwell_time[IPW_SCAN_ACTIVE_BROADCAST_SCAN] =
6414			cpu_to_le16(20);
6415
6416	scan.dwell_time[IPW_SCAN_ACTIVE_BROADCAST_AND_DIRECT_SCAN] =
6417		cpu_to_le16(20);
6418
6419	scan.dwell_time[IPW_SCAN_PASSIVE_FULL_DWELL_SCAN] =
6420		cpu_to_le16(ipw_passive_dwell_time(priv));
6421	scan.dwell_time[IPW_SCAN_ACTIVE_DIRECT_SCAN] = cpu_to_le16(20);
6422
6423#ifdef CONFIG_IPW2200_MONITOR
6424	if (priv->ieee->iw_mode == IW_MODE_MONITOR) {
6425		u8 channel;
6426		u8 band = 0;
6427
6428		switch (libipw_is_valid_channel(priv->ieee, priv->channel)) {
6429		case LIBIPW_52GHZ_BAND:
6430			band = (u8) (IPW_A_MODE << 6) | 1;
6431			channel = priv->channel;
6432			break;
6433
6434		case LIBIPW_24GHZ_BAND:
6435			band = (u8) (IPW_B_MODE << 6) | 1;
6436			channel = priv->channel;
6437			break;
6438
6439		default:
6440			band = (u8) (IPW_B_MODE << 6) | 1;
6441			channel = 9;
6442			break;
6443		}
6444
6445		scan.channels_list[0] = band;
6446		scan.channels_list[1] = channel;
6447		ipw_set_scan_type(&scan, 1, IPW_SCAN_PASSIVE_FULL_DWELL_SCAN);
6448
6449		/* NOTE:  The card will sit on this channel for this time
6450		 * period.  Scan aborts are timing sensitive and frequently
6451		 * result in firmware restarts.  As such, it is best to
6452		 * set a small dwell_time here and just keep re-issuing
6453		 * scans.  Otherwise fast channel hopping will not actually
6454		 * hop channels.
6455		 *
6456		 * TODO: Move SPEED SCAN support to all modes and bands */
6457		scan.dwell_time[IPW_SCAN_PASSIVE_FULL_DWELL_SCAN] =
6458			cpu_to_le16(2000);
6459	} else {
6460#endif				/* CONFIG_IPW2200_MONITOR */
6461		/* Honor direct scans first, otherwise if we are roaming make
6462		 * this a direct scan for the current network.  Finally,
6463		 * ensure that every other scan is a fast channel hop scan */
6464		if (direct) {
6465			err = ipw_send_ssid(priv, priv->direct_scan_ssid,
6466			                    priv->direct_scan_ssid_len);
6467			if (err) {
6468				IPW_DEBUG_HC("Attempt to send SSID command  "
6469					     "failed\n");
6470				goto done;
6471			}
6472
6473			scan_type = IPW_SCAN_ACTIVE_BROADCAST_AND_DIRECT_SCAN;
6474		} else if ((priv->status & STATUS_ROAMING)
6475			   || (!(priv->status & STATUS_ASSOCIATED)
6476			       && (priv->config & CFG_STATIC_ESSID)
6477			       && (le32_to_cpu(scan.full_scan_index) % 2))) {
6478			err = ipw_send_ssid(priv, priv->essid, priv->essid_len);
6479			if (err) {
6480				IPW_DEBUG_HC("Attempt to send SSID command "
6481					     "failed.\n");
6482				goto done;
6483			}
6484
6485			scan_type = IPW_SCAN_ACTIVE_BROADCAST_AND_DIRECT_SCAN;
6486		} else
6487			scan_type = IPW_SCAN_ACTIVE_BROADCAST_SCAN;
6488
6489		ipw_add_scan_channels(priv, &scan, scan_type);
6490#ifdef CONFIG_IPW2200_MONITOR
6491	}
6492#endif
6493
6494send_request:
6495	err = ipw_send_scan_request_ext(priv, &scan);
6496	if (err) {
6497		IPW_DEBUG_HC("Sending scan command failed: %08X\n", err);
6498		goto done;
6499	}
6500
6501	priv->status |= STATUS_SCANNING;
6502	if (direct) {
6503		priv->status &= ~STATUS_DIRECT_SCAN_PENDING;
6504		priv->direct_scan_ssid_len = 0;
6505	} else
6506		priv->status &= ~STATUS_SCAN_PENDING;
6507
6508	queue_delayed_work(priv->workqueue, &priv->scan_check,
6509			   IPW_SCAN_CHECK_WATCHDOG);
6510done:
6511	mutex_unlock(&priv->mutex);
6512	return err;
6513}
6514
6515static void ipw_request_passive_scan(struct work_struct *work)
6516{
6517	struct ipw_priv *priv =
6518		container_of(work, struct ipw_priv, request_passive_scan.work);
6519	ipw_request_scan_helper(priv, IW_SCAN_TYPE_PASSIVE, 0);
6520}
6521
6522static void ipw_request_scan(struct work_struct *work)
6523{
6524	struct ipw_priv *priv =
6525		container_of(work, struct ipw_priv, request_scan.work);
6526	ipw_request_scan_helper(priv, IW_SCAN_TYPE_ACTIVE, 0);
6527}
6528
6529static void ipw_request_direct_scan(struct work_struct *work)
6530{
6531	struct ipw_priv *priv =
6532		container_of(work, struct ipw_priv, request_direct_scan.work);
6533	ipw_request_scan_helper(priv, IW_SCAN_TYPE_ACTIVE, 1);
6534}
6535
6536static void ipw_bg_abort_scan(struct work_struct *work)
6537{
6538	struct ipw_priv *priv =
6539		container_of(work, struct ipw_priv, abort_scan);
6540	mutex_lock(&priv->mutex);
6541	ipw_abort_scan(priv);
6542	mutex_unlock(&priv->mutex);
6543}
6544
6545static int ipw_wpa_enable(struct ipw_priv *priv, int value)
6546{
6547	/* This is called when wpa_supplicant loads and closes the driver
6548	 * interface. */
6549	priv->ieee->wpa_enabled = value;
6550	return 0;
6551}
6552
6553static int ipw_wpa_set_auth_algs(struct ipw_priv *priv, int value)
6554{
6555	struct libipw_device *ieee = priv->ieee;
6556	struct libipw_security sec = {
6557		.flags = SEC_AUTH_MODE,
6558	};
6559	int ret = 0;
6560
6561	if (value & IW_AUTH_ALG_SHARED_KEY) {
6562		sec.auth_mode = WLAN_AUTH_SHARED_KEY;
6563		ieee->open_wep = 0;
6564	} else if (value & IW_AUTH_ALG_OPEN_SYSTEM) {
6565		sec.auth_mode = WLAN_AUTH_OPEN;
6566		ieee->open_wep = 1;
6567	} else if (value & IW_AUTH_ALG_LEAP) {
6568		sec.auth_mode = WLAN_AUTH_LEAP;
6569		ieee->open_wep = 1;
6570	} else
6571		return -EINVAL;
6572
6573	if (ieee->set_security)
6574		ieee->set_security(ieee->dev, &sec);
6575	else
6576		ret = -EOPNOTSUPP;
6577
6578	return ret;
6579}
6580
6581static void ipw_wpa_assoc_frame(struct ipw_priv *priv, char *wpa_ie,
6582				int wpa_ie_len)
6583{
6584	/* make sure WPA is enabled */
6585	ipw_wpa_enable(priv, 1);
6586}
6587
6588static int ipw_set_rsn_capa(struct ipw_priv *priv,
6589			    char *capabilities, int length)
6590{
6591	IPW_DEBUG_HC("HOST_CMD_RSN_CAPABILITIES\n");
6592
6593	return ipw_send_cmd_pdu(priv, IPW_CMD_RSN_CAPABILITIES, length,
6594				capabilities);
6595}
6596
6597/*
6598 * WE-18 support
6599 */
6600
6601/* SIOCSIWGENIE */
6602static int ipw_wx_set_genie(struct net_device *dev,
6603			    struct iw_request_info *info,
6604			    union iwreq_data *wrqu, char *extra)
6605{
6606	struct ipw_priv *priv = libipw_priv(dev);
6607	struct libipw_device *ieee = priv->ieee;
6608	u8 *buf;
6609	int err = 0;
6610
6611	if (wrqu->data.length > MAX_WPA_IE_LEN ||
6612	    (wrqu->data.length && extra == NULL))
6613		return -EINVAL;
6614
6615	if (wrqu->data.length) {
6616		buf = kmemdup(extra, wrqu->data.length, GFP_KERNEL);
6617		if (buf == NULL) {
6618			err = -ENOMEM;
6619			goto out;
6620		}
6621
6622		kfree(ieee->wpa_ie);
6623		ieee->wpa_ie = buf;
6624		ieee->wpa_ie_len = wrqu->data.length;
6625	} else {
6626		kfree(ieee->wpa_ie);
6627		ieee->wpa_ie = NULL;
6628		ieee->wpa_ie_len = 0;
6629	}
6630
6631	ipw_wpa_assoc_frame(priv, ieee->wpa_ie, ieee->wpa_ie_len);
6632      out:
6633	return err;
6634}
6635
6636/* SIOCGIWGENIE */
6637static int ipw_wx_get_genie(struct net_device *dev,
6638			    struct iw_request_info *info,
6639			    union iwreq_data *wrqu, char *extra)
6640{
6641	struct ipw_priv *priv = libipw_priv(dev);
6642	struct libipw_device *ieee = priv->ieee;
6643	int err = 0;
6644
6645	if (ieee->wpa_ie_len == 0 || ieee->wpa_ie == NULL) {
6646		wrqu->data.length = 0;
6647		goto out;
6648	}
6649
6650	if (wrqu->data.length < ieee->wpa_ie_len) {
6651		err = -E2BIG;
6652		goto out;
6653	}
6654
6655	wrqu->data.length = ieee->wpa_ie_len;
6656	memcpy(extra, ieee->wpa_ie, ieee->wpa_ie_len);
6657
6658      out:
6659	return err;
6660}
6661
6662static int wext_cipher2level(int cipher)
6663{
6664	switch (cipher) {
6665	case IW_AUTH_CIPHER_NONE:
6666		return SEC_LEVEL_0;
6667	case IW_AUTH_CIPHER_WEP40:
6668	case IW_AUTH_CIPHER_WEP104:
6669		return SEC_LEVEL_1;
6670	case IW_AUTH_CIPHER_TKIP:
6671		return SEC_LEVEL_2;
6672	case IW_AUTH_CIPHER_CCMP:
6673		return SEC_LEVEL_3;
6674	default:
6675		return -1;
6676	}
6677}
6678
6679/* SIOCSIWAUTH */
6680static int ipw_wx_set_auth(struct net_device *dev,
6681			   struct iw_request_info *info,
6682			   union iwreq_data *wrqu, char *extra)
6683{
6684	struct ipw_priv *priv = libipw_priv(dev);
6685	struct libipw_device *ieee = priv->ieee;
6686	struct iw_param *param = &wrqu->param;
6687	struct lib80211_crypt_data *crypt;
6688	unsigned long flags;
6689	int ret = 0;
6690
6691	switch (param->flags & IW_AUTH_INDEX) {
6692	case IW_AUTH_WPA_VERSION:
6693		break;
6694	case IW_AUTH_CIPHER_PAIRWISE:
6695		ipw_set_hw_decrypt_unicast(priv,
6696					   wext_cipher2level(param->value));
6697		break;
6698	case IW_AUTH_CIPHER_GROUP:
6699		ipw_set_hw_decrypt_multicast(priv,
6700					     wext_cipher2level(param->value));
6701		break;
6702	case IW_AUTH_KEY_MGMT:
6703		/*
6704		 * ipw2200 does not use these parameters
6705		 */
6706		break;
6707
6708	case IW_AUTH_TKIP_COUNTERMEASURES:
6709		crypt = priv->ieee->crypt_info.crypt[priv->ieee->crypt_info.tx_keyidx];
6710		if (!crypt || !crypt->ops->set_flags || !crypt->ops->get_flags)
6711			break;
6712
6713		flags = crypt->ops->get_flags(crypt->priv);
6714
6715		if (param->value)
6716			flags |= IEEE80211_CRYPTO_TKIP_COUNTERMEASURES;
6717		else
6718			flags &= ~IEEE80211_CRYPTO_TKIP_COUNTERMEASURES;
6719
6720		crypt->ops->set_flags(flags, crypt->priv);
6721
6722		break;
6723
6724	case IW_AUTH_DROP_UNENCRYPTED:{
6725			/* HACK:
6726			 *
6727			 * wpa_supplicant calls set_wpa_enabled when the driver
6728			 * is loaded and unloaded, regardless of if WPA is being
6729			 * used.  No other calls are made which can be used to
6730			 * determine if encryption will be used or not prior to
6731			 * association being expected.  If encryption is not being
6732			 * used, drop_unencrypted is set to false, else true -- we
6733			 * can use this to determine if the CAP_PRIVACY_ON bit should
6734			 * be set.
6735			 */
6736			struct libipw_security sec = {
6737				.flags = SEC_ENABLED,
6738				.enabled = param->value,
6739			};
6740			priv->ieee->drop_unencrypted = param->value;
6741			/* We only change SEC_LEVEL for open mode. Others
6742			 * are set by ipw_wpa_set_encryption.
6743			 */
6744			if (!param->value) {
6745				sec.flags |= SEC_LEVEL;
6746				sec.level = SEC_LEVEL_0;
6747			} else {
6748				sec.flags |= SEC_LEVEL;
6749				sec.level = SEC_LEVEL_1;
6750			}
6751			if (priv->ieee->set_security)
6752				priv->ieee->set_security(priv->ieee->dev, &sec);
6753			break;
6754		}
6755
6756	case IW_AUTH_80211_AUTH_ALG:
6757		ret = ipw_wpa_set_auth_algs(priv, param->value);
6758		break;
6759
6760	case IW_AUTH_WPA_ENABLED:
6761		ret = ipw_wpa_enable(priv, param->value);
6762		ipw_disassociate(priv);
6763		break;
6764
6765	case IW_AUTH_RX_UNENCRYPTED_EAPOL:
6766		ieee->ieee802_1x = param->value;
6767		break;
6768
6769	case IW_AUTH_PRIVACY_INVOKED:
6770		ieee->privacy_invoked = param->value;
6771		break;
6772
6773	default:
6774		return -EOPNOTSUPP;
6775	}
6776	return ret;
6777}
6778
6779/* SIOCGIWAUTH */
6780static int ipw_wx_get_auth(struct net_device *dev,
6781			   struct iw_request_info *info,
6782			   union iwreq_data *wrqu, char *extra)
6783{
6784	struct ipw_priv *priv = libipw_priv(dev);
6785	struct libipw_device *ieee = priv->ieee;
6786	struct lib80211_crypt_data *crypt;
6787	struct iw_param *param = &wrqu->param;
6788	int ret = 0;
6789
6790	switch (param->flags & IW_AUTH_INDEX) {
6791	case IW_AUTH_WPA_VERSION:
6792	case IW_AUTH_CIPHER_PAIRWISE:
6793	case IW_AUTH_CIPHER_GROUP:
6794	case IW_AUTH_KEY_MGMT:
6795		/*
6796		 * wpa_supplicant will control these internally
6797		 */
6798		ret = -EOPNOTSUPP;
6799		break;
6800
6801	case IW_AUTH_TKIP_COUNTERMEASURES:
6802		crypt = priv->ieee->crypt_info.crypt[priv->ieee->crypt_info.tx_keyidx];
6803		if (!crypt || !crypt->ops->get_flags)
6804			break;
6805
6806		param->value = (crypt->ops->get_flags(crypt->priv) &
6807				IEEE80211_CRYPTO_TKIP_COUNTERMEASURES) ? 1 : 0;
6808
6809		break;
6810
6811	case IW_AUTH_DROP_UNENCRYPTED:
6812		param->value = ieee->drop_unencrypted;
6813		break;
6814
6815	case IW_AUTH_80211_AUTH_ALG:
6816		param->value = ieee->sec.auth_mode;
6817		break;
6818
6819	case IW_AUTH_WPA_ENABLED:
6820		param->value = ieee->wpa_enabled;
6821		break;
6822
6823	case IW_AUTH_RX_UNENCRYPTED_EAPOL:
6824		param->value = ieee->ieee802_1x;
6825		break;
6826
6827	case IW_AUTH_ROAMING_CONTROL:
6828	case IW_AUTH_PRIVACY_INVOKED:
6829		param->value = ieee->privacy_invoked;
6830		break;
6831
6832	default:
6833		return -EOPNOTSUPP;
6834	}
6835	return 0;
6836}
6837
6838/* SIOCSIWENCODEEXT */
6839static int ipw_wx_set_encodeext(struct net_device *dev,
6840				struct iw_request_info *info,
6841				union iwreq_data *wrqu, char *extra)
6842{
6843	struct ipw_priv *priv = libipw_priv(dev);
6844	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
6845
6846	if (hwcrypto) {
6847		if (ext->alg == IW_ENCODE_ALG_TKIP) {
6848			/* IPW HW can't build TKIP MIC,
6849			   host decryption still needed */
6850			if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
6851				priv->ieee->host_mc_decrypt = 1;
6852			else {
6853				priv->ieee->host_encrypt = 0;
6854				priv->ieee->host_encrypt_msdu = 1;
6855				priv->ieee->host_decrypt = 1;
6856			}
6857		} else {
6858			priv->ieee->host_encrypt = 0;
6859			priv->ieee->host_encrypt_msdu = 0;
6860			priv->ieee->host_decrypt = 0;
6861			priv->ieee->host_mc_decrypt = 0;
6862		}
6863	}
6864
6865	return libipw_wx_set_encodeext(priv->ieee, info, wrqu, extra);
6866}
6867
6868/* SIOCGIWENCODEEXT */
6869static int ipw_wx_get_encodeext(struct net_device *dev,
6870				struct iw_request_info *info,
6871				union iwreq_data *wrqu, char *extra)
6872{
6873	struct ipw_priv *priv = libipw_priv(dev);
6874	return libipw_wx_get_encodeext(priv->ieee, info, wrqu, extra);
6875}
6876
6877/* SIOCSIWMLME */
6878static int ipw_wx_set_mlme(struct net_device *dev,
6879			   struct iw_request_info *info,
6880			   union iwreq_data *wrqu, char *extra)
6881{
6882	struct ipw_priv *priv = libipw_priv(dev);
6883	struct iw_mlme *mlme = (struct iw_mlme *)extra;
6884	__le16 reason;
6885
6886	reason = cpu_to_le16(mlme->reason_code);
6887
6888	switch (mlme->cmd) {
6889	case IW_MLME_DEAUTH:
6890		/* silently ignore */
6891		break;
6892
6893	case IW_MLME_DISASSOC:
6894		ipw_disassociate(priv);
6895		break;
6896
6897	default:
6898		return -EOPNOTSUPP;
6899	}
6900	return 0;
6901}
6902
6903#ifdef CONFIG_IPW2200_QOS
6904
6905/* QoS */
6906/*
6907* get the modulation type of the current network or
6908* the card current mode
6909*/
6910static u8 ipw_qos_current_mode(struct ipw_priv * priv)
6911{
6912	u8 mode = 0;
6913
6914	if (priv->status & STATUS_ASSOCIATED) {
6915		unsigned long flags;
6916
6917		spin_lock_irqsave(&priv->ieee->lock, flags);
6918		mode = priv->assoc_network->mode;
6919		spin_unlock_irqrestore(&priv->ieee->lock, flags);
6920	} else {
6921		mode = priv->ieee->mode;
6922	}
6923	IPW_DEBUG_QOS("QoS network/card mode %d\n", mode);
6924	return mode;
6925}
6926
6927/*
6928* Handle management frame beacon and probe response
6929*/
6930static int ipw_qos_handle_probe_response(struct ipw_priv *priv,
6931					 int active_network,
6932					 struct libipw_network *network)
6933{
6934	u32 size = sizeof(struct libipw_qos_parameters);
6935
6936	if (network->capability & WLAN_CAPABILITY_IBSS)
6937		network->qos_data.active = network->qos_data.supported;
6938
6939	if (network->flags & NETWORK_HAS_QOS_MASK) {
6940		if (active_network &&
6941		    (network->flags & NETWORK_HAS_QOS_PARAMETERS))
6942			network->qos_data.active = network->qos_data.supported;
6943
6944		if ((network->qos_data.active == 1) && (active_network == 1) &&
6945		    (network->flags & NETWORK_HAS_QOS_PARAMETERS) &&
6946		    (network->qos_data.old_param_count !=
6947		     network->qos_data.param_count)) {
6948			network->qos_data.old_param_count =
6949			    network->qos_data.param_count;
6950			schedule_work(&priv->qos_activate);
6951			IPW_DEBUG_QOS("QoS parameters change call "
6952				      "qos_activate\n");
6953		}
6954	} else {
6955		if ((priv->ieee->mode == IEEE_B) || (network->mode == IEEE_B))
6956			memcpy(&network->qos_data.parameters,
6957			       &def_parameters_CCK, size);
6958		else
6959			memcpy(&network->qos_data.parameters,
6960			       &def_parameters_OFDM, size);
6961
6962		if ((network->qos_data.active == 1) && (active_network == 1)) {
6963			IPW_DEBUG_QOS("QoS was disabled call qos_activate\n");
6964			schedule_work(&priv->qos_activate);
6965		}
6966
6967		network->qos_data.active = 0;
6968		network->qos_data.supported = 0;
6969	}
6970	if ((priv->status & STATUS_ASSOCIATED) &&
6971	    (priv->ieee->iw_mode == IW_MODE_ADHOC) && (active_network == 0)) {
6972		if (memcmp(network->bssid, priv->bssid, ETH_ALEN))
6973			if (network->capability & WLAN_CAPABILITY_IBSS)
6974				if ((network->ssid_len ==
6975				     priv->assoc_network->ssid_len) &&
6976				    !memcmp(network->ssid,
6977					    priv->assoc_network->ssid,
6978					    network->ssid_len)) {
6979					queue_work(priv->workqueue,
6980						   &priv->merge_networks);
6981				}
6982	}
6983
6984	return 0;
6985}
6986
6987/*
6988* This function set up the firmware to support QoS. It sends
6989* IPW_CMD_QOS_PARAMETERS and IPW_CMD_WME_INFO
6990*/
6991static int ipw_qos_activate(struct ipw_priv *priv,
6992			    struct libipw_qos_data *qos_network_data)
6993{
6994	int err;
6995	struct libipw_qos_parameters qos_parameters[QOS_QOS_SETS];
6996	struct libipw_qos_parameters *active_one = NULL;
6997	u32 size = sizeof(struct libipw_qos_parameters);
6998	u32 burst_duration;
6999	int i;
7000	u8 type;
7001
7002	type = ipw_qos_current_mode(priv);
7003
7004	active_one = &(qos_parameters[QOS_PARAM_SET_DEF_CCK]);
7005	memcpy(active_one, priv->qos_data.def_qos_parm_CCK, size);
7006	active_one = &(qos_parameters[QOS_PARAM_SET_DEF_OFDM]);
7007	memcpy(active_one, priv->qos_data.def_qos_parm_OFDM, size);
7008
7009	if (qos_network_data == NULL) {
7010		if (type == IEEE_B) {
7011			IPW_DEBUG_QOS("QoS activate network mode %d\n", type);
7012			active_one = &def_parameters_CCK;
7013		} else
7014			active_one = &def_parameters_OFDM;
7015
7016		memcpy(&qos_parameters[QOS_PARAM_SET_ACTIVE], active_one, size);
7017		burst_duration = ipw_qos_get_burst_duration(priv);
7018		for (i = 0; i < QOS_QUEUE_NUM; i++)
7019			qos_parameters[QOS_PARAM_SET_ACTIVE].tx_op_limit[i] =
7020			    cpu_to_le16(burst_duration);
7021	} else if (priv->ieee->iw_mode == IW_MODE_ADHOC) {
7022		if (type == IEEE_B) {
7023			IPW_DEBUG_QOS("QoS activate IBSS nework mode %d\n",
7024				      type);
7025			if (priv->qos_data.qos_enable == 0)
7026				active_one = &def_parameters_CCK;
7027			else
7028				active_one = priv->qos_data.def_qos_parm_CCK;
7029		} else {
7030			if (priv->qos_data.qos_enable == 0)
7031				active_one = &def_parameters_OFDM;
7032			else
7033				active_one = priv->qos_data.def_qos_parm_OFDM;
7034		}
7035		memcpy(&qos_parameters[QOS_PARAM_SET_ACTIVE], active_one, size);
7036	} else {
7037		unsigned long flags;
7038		int active;
7039
7040		spin_lock_irqsave(&priv->ieee->lock, flags);
7041		active_one = &(qos_network_data->parameters);
7042		qos_network_data->old_param_count =
7043		    qos_network_data->param_count;
7044		memcpy(&qos_parameters[QOS_PARAM_SET_ACTIVE], active_one, size);
7045		active = qos_network_data->supported;
7046		spin_unlock_irqrestore(&priv->ieee->lock, flags);
7047
7048		if (active == 0) {
7049			burst_duration = ipw_qos_get_burst_duration(priv);
7050			for (i = 0; i < QOS_QUEUE_NUM; i++)
7051				qos_parameters[QOS_PARAM_SET_ACTIVE].
7052				    tx_op_limit[i] = cpu_to_le16(burst_duration);
7053		}
7054	}
7055
7056	IPW_DEBUG_QOS("QoS sending IPW_CMD_QOS_PARAMETERS\n");
7057	err = ipw_send_qos_params_command(priv,
7058					  (struct libipw_qos_parameters *)
7059					  &(qos_parameters[0]));
7060	if (err)
7061		IPW_DEBUG_QOS("QoS IPW_CMD_QOS_PARAMETERS failed\n");
7062
7063	return err;
7064}
7065
7066/*
7067* send IPW_CMD_WME_INFO to the firmware
7068*/
7069static int ipw_qos_set_info_element(struct ipw_priv *priv)
7070{
7071	int ret = 0;
7072	struct libipw_qos_information_element qos_info;
7073
7074	if (priv == NULL)
7075		return -1;
7076
7077	qos_info.elementID = QOS_ELEMENT_ID;
7078	qos_info.length = sizeof(struct libipw_qos_information_element) - 2;
7079
7080	qos_info.version = QOS_VERSION_1;
7081	qos_info.ac_info = 0;
7082
7083	memcpy(qos_info.qui, qos_oui, QOS_OUI_LEN);
7084	qos_info.qui_type = QOS_OUI_TYPE;
7085	qos_info.qui_subtype = QOS_OUI_INFO_SUB_TYPE;
7086
7087	ret = ipw_send_qos_info_command(priv, &qos_info);
7088	if (ret != 0) {
7089		IPW_DEBUG_QOS("QoS error calling ipw_send_qos_info_command\n");
7090	}
7091	return ret;
7092}
7093
7094/*
7095* Set the QoS parameter with the association request structure
7096*/
7097static int ipw_qos_association(struct ipw_priv *priv,
7098			       struct libipw_network *network)
7099{
7100	int err = 0;
7101	struct libipw_qos_data *qos_data = NULL;
7102	struct libipw_qos_data ibss_data = {
7103		.supported = 1,
7104		.active = 1,
7105	};
7106
7107	switch (priv->ieee->iw_mode) {
7108	case IW_MODE_ADHOC:
7109		BUG_ON(!(network->capability & WLAN_CAPABILITY_IBSS));
7110
7111		qos_data = &ibss_data;
7112		break;
7113
7114	case IW_MODE_INFRA:
7115		qos_data = &network->qos_data;
7116		break;
7117
7118	default:
7119		BUG();
7120		break;
7121	}
7122
7123	err = ipw_qos_activate(priv, qos_data);
7124	if (err) {
7125		priv->assoc_request.policy_support &= ~HC_QOS_SUPPORT_ASSOC;
7126		return err;
7127	}
7128
7129	if (priv->qos_data.qos_enable && qos_data->supported) {
7130		IPW_DEBUG_QOS("QoS will be enabled for this association\n");
7131		priv->assoc_request.policy_support |= HC_QOS_SUPPORT_ASSOC;
7132		return ipw_qos_set_info_element(priv);
7133	}
7134
7135	return 0;
7136}
7137
7138/*
7139* handling the beaconing responses. if we get different QoS setting
7140* off the network from the associated setting, adjust the QoS
7141* setting
7142*/
7143static int ipw_qos_association_resp(struct ipw_priv *priv,
7144				    struct libipw_network *network)
7145{
7146	int ret = 0;
7147	unsigned long flags;
7148	u32 size = sizeof(struct libipw_qos_parameters);
7149	int set_qos_param = 0;
7150
7151	if ((priv == NULL) || (network == NULL) ||
7152	    (priv->assoc_network == NULL))
7153		return ret;
7154
7155	if (!(priv->status & STATUS_ASSOCIATED))
7156		return ret;
7157
7158	if ((priv->ieee->iw_mode != IW_MODE_INFRA))
7159		return ret;
7160
7161	spin_lock_irqsave(&priv->ieee->lock, flags);
7162	if (network->flags & NETWORK_HAS_QOS_PARAMETERS) {
7163		memcpy(&priv->assoc_network->qos_data, &network->qos_data,
7164		       sizeof(struct libipw_qos_data));
7165		priv->assoc_network->qos_data.active = 1;
7166		if ((network->qos_data.old_param_count !=
7167		     network->qos_data.param_count)) {
7168			set_qos_param = 1;
7169			network->qos_data.old_param_count =
7170			    network->qos_data.param_count;
7171		}
7172
7173	} else {
7174		if ((network->mode == IEEE_B) || (priv->ieee->mode == IEEE_B))
7175			memcpy(&priv->assoc_network->qos_data.parameters,
7176			       &def_parameters_CCK, size);
7177		else
7178			memcpy(&priv->assoc_network->qos_data.parameters,
7179			       &def_parameters_OFDM, size);
7180		priv->assoc_network->qos_data.active = 0;
7181		priv->assoc_network->qos_data.supported = 0;
7182		set_qos_param = 1;
7183	}
7184
7185	spin_unlock_irqrestore(&priv->ieee->lock, flags);
7186
7187	if (set_qos_param == 1)
7188		schedule_work(&priv->qos_activate);
7189
7190	return ret;
7191}
7192
7193static u32 ipw_qos_get_burst_duration(struct ipw_priv *priv)
7194{
7195	u32 ret = 0;
7196
7197	if ((priv == NULL))
7198		return 0;
7199
7200	if (!(priv->ieee->modulation & LIBIPW_OFDM_MODULATION))
7201		ret = priv->qos_data.burst_duration_CCK;
7202	else
7203		ret = priv->qos_data.burst_duration_OFDM;
7204
7205	return ret;
7206}
7207
7208/*
7209* Initialize the setting of QoS global
7210*/
7211static void ipw_qos_init(struct ipw_priv *priv, int enable,
7212			 int burst_enable, u32 burst_duration_CCK,
7213			 u32 burst_duration_OFDM)
7214{
7215	priv->qos_data.qos_enable = enable;
7216
7217	if (priv->qos_data.qos_enable) {
7218		priv->qos_data.def_qos_parm_CCK = &def_qos_parameters_CCK;
7219		priv->qos_data.def_qos_parm_OFDM = &def_qos_parameters_OFDM;
7220		IPW_DEBUG_QOS("QoS is enabled\n");
7221	} else {
7222		priv->qos_data.def_qos_parm_CCK = &def_parameters_CCK;
7223		priv->qos_data.def_qos_parm_OFDM = &def_parameters_OFDM;
7224		IPW_DEBUG_QOS("QoS is not enabled\n");
7225	}
7226
7227	priv->qos_data.burst_enable = burst_enable;
7228
7229	if (burst_enable) {
7230		priv->qos_data.burst_duration_CCK = burst_duration_CCK;
7231		priv->qos_data.burst_duration_OFDM = burst_duration_OFDM;
7232	} else {
7233		priv->qos_data.burst_duration_CCK = 0;
7234		priv->qos_data.burst_duration_OFDM = 0;
7235	}
7236}
7237
7238/*
7239* map the packet priority to the right TX Queue
7240*/
7241static int ipw_get_tx_queue_number(struct ipw_priv *priv, u16 priority)
7242{
7243	if (priority > 7 || !priv->qos_data.qos_enable)
7244		priority = 0;
7245
7246	return from_priority_to_tx_queue[priority] - 1;
7247}
7248
7249static int ipw_is_qos_active(struct net_device *dev,
7250			     struct sk_buff *skb)
7251{
7252	struct ipw_priv *priv = libipw_priv(dev);
7253	struct libipw_qos_data *qos_data = NULL;
7254	int active, supported;
7255	u8 *daddr = skb->data + ETH_ALEN;
7256	int unicast = !is_multicast_ether_addr(daddr);
7257
7258	if (!(priv->status & STATUS_ASSOCIATED))
7259		return 0;
7260
7261	qos_data = &priv->assoc_network->qos_data;
7262
7263	if (priv->ieee->iw_mode == IW_MODE_ADHOC) {
7264		if (unicast == 0)
7265			qos_data->active = 0;
7266		else
7267			qos_data->active = qos_data->supported;
7268	}
7269	active = qos_data->active;
7270	supported = qos_data->supported;
7271	IPW_DEBUG_QOS("QoS  %d network is QoS active %d  supported %d  "
7272		      "unicast %d\n",
7273		      priv->qos_data.qos_enable, active, supported, unicast);
7274	if (active && priv->qos_data.qos_enable)
7275		return 1;
7276
7277	return 0;
7278
7279}
7280/*
7281* add QoS parameter to the TX command
7282*/
7283static int ipw_qos_set_tx_queue_command(struct ipw_priv *priv,
7284					u16 priority,
7285					struct tfd_data *tfd)
7286{
7287	int tx_queue_id = 0;
7288
7289
7290	tx_queue_id = from_priority_to_tx_queue[priority] - 1;
7291	tfd->tx_flags_ext |= DCT_FLAG_EXT_QOS_ENABLED;
7292
7293	if (priv->qos_data.qos_no_ack_mask & (1UL << tx_queue_id)) {
7294		tfd->tx_flags &= ~DCT_FLAG_ACK_REQD;
7295		tfd->tfd.tfd_26.mchdr.qos_ctrl |= cpu_to_le16(CTRL_QOS_NO_ACK);
7296	}
7297	return 0;
7298}
7299
7300/*
7301* background support to run QoS activate functionality
7302*/
7303static void ipw_bg_qos_activate(struct work_struct *work)
7304{
7305	struct ipw_priv *priv =
7306		container_of(work, struct ipw_priv, qos_activate);
7307
7308	mutex_lock(&priv->mutex);
7309
7310	if (priv->status & STATUS_ASSOCIATED)
7311		ipw_qos_activate(priv, &(priv->assoc_network->qos_data));
7312
7313	mutex_unlock(&priv->mutex);
7314}
7315
7316static int ipw_handle_probe_response(struct net_device *dev,
7317				     struct libipw_probe_response *resp,
7318				     struct libipw_network *network)
7319{
7320	struct ipw_priv *priv = libipw_priv(dev);
7321	int active_network = ((priv->status & STATUS_ASSOCIATED) &&
7322			      (network == priv->assoc_network));
7323
7324	ipw_qos_handle_probe_response(priv, active_network, network);
7325
7326	return 0;
7327}
7328
7329static int ipw_handle_beacon(struct net_device *dev,
7330			     struct libipw_beacon *resp,
7331			     struct libipw_network *network)
7332{
7333	struct ipw_priv *priv = libipw_priv(dev);
7334	int active_network = ((priv->status & STATUS_ASSOCIATED) &&
7335			      (network == priv->assoc_network));
7336
7337	ipw_qos_handle_probe_response(priv, active_network, network);
7338
7339	return 0;
7340}
7341
7342static int ipw_handle_assoc_response(struct net_device *dev,
7343				     struct libipw_assoc_response *resp,
7344				     struct libipw_network *network)
7345{
7346	struct ipw_priv *priv = libipw_priv(dev);
7347	ipw_qos_association_resp(priv, network);
7348	return 0;
7349}
7350
7351static int ipw_send_qos_params_command(struct ipw_priv *priv, struct libipw_qos_parameters
7352				       *qos_param)
7353{
7354	return ipw_send_cmd_pdu(priv, IPW_CMD_QOS_PARAMETERS,
7355				sizeof(*qos_param) * 3, qos_param);
7356}
7357
7358static int ipw_send_qos_info_command(struct ipw_priv *priv, struct libipw_qos_information_element
7359				     *qos_param)
7360{
7361	return ipw_send_cmd_pdu(priv, IPW_CMD_WME_INFO, sizeof(*qos_param),
7362				qos_param);
7363}
7364
7365#endif				/* CONFIG_IPW2200_QOS */
7366
7367static int ipw_associate_network(struct ipw_priv *priv,
7368				 struct libipw_network *network,
7369				 struct ipw_supported_rates *rates, int roaming)
7370{
7371	int err;
7372	DECLARE_SSID_BUF(ssid);
7373
7374	if (priv->config & CFG_FIXED_RATE)
7375		ipw_set_fixed_rate(priv, network->mode);
7376
7377	if (!(priv->config & CFG_STATIC_ESSID)) {
7378		priv->essid_len = min(network->ssid_len,
7379				      (u8) IW_ESSID_MAX_SIZE);
7380		memcpy(priv->essid, network->ssid, priv->essid_len);
7381	}
7382
7383	network->last_associate = jiffies;
7384
7385	memset(&priv->assoc_request, 0, sizeof(priv->assoc_request));
7386	priv->assoc_request.channel = network->channel;
7387	priv->assoc_request.auth_key = 0;
7388
7389	if ((priv->capability & CAP_PRIVACY_ON) &&
7390	    (priv->ieee->sec.auth_mode == WLAN_AUTH_SHARED_KEY)) {
7391		priv->assoc_request.auth_type = AUTH_SHARED_KEY;
7392		priv->assoc_request.auth_key = priv->ieee->sec.active_key;
7393
7394		if (priv->ieee->sec.level == SEC_LEVEL_1)
7395			ipw_send_wep_keys(priv, DCW_WEP_KEY_SEC_TYPE_WEP);
7396
7397	} else if ((priv->capability & CAP_PRIVACY_ON) &&
7398		   (priv->ieee->sec.auth_mode == WLAN_AUTH_LEAP))
7399		priv->assoc_request.auth_type = AUTH_LEAP;
7400	else
7401		priv->assoc_request.auth_type = AUTH_OPEN;
7402
7403	if (priv->ieee->wpa_ie_len) {
7404		priv->assoc_request.policy_support = cpu_to_le16(0x02);	/* RSN active */
7405		ipw_set_rsn_capa(priv, priv->ieee->wpa_ie,
7406				 priv->ieee->wpa_ie_len);
7407	}
7408
7409	/*
7410	 * It is valid for our ieee device to support multiple modes, but
7411	 * when it comes to associating to a given network we have to choose
7412	 * just one mode.
7413	 */
7414	if (network->mode & priv->ieee->mode & IEEE_A)
7415		priv->assoc_request.ieee_mode = IPW_A_MODE;
7416	else if (network->mode & priv->ieee->mode & IEEE_G)
7417		priv->assoc_request.ieee_mode = IPW_G_MODE;
7418	else if (network->mode & priv->ieee->mode & IEEE_B)
7419		priv->assoc_request.ieee_mode = IPW_B_MODE;
7420
7421	priv->assoc_request.capability = cpu_to_le16(network->capability);
7422	if ((network->capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
7423	    && !(priv->config & CFG_PREAMBLE_LONG)) {
7424		priv->assoc_request.preamble_length = DCT_FLAG_SHORT_PREAMBLE;
7425	} else {
7426		priv->assoc_request.preamble_length = DCT_FLAG_LONG_PREAMBLE;
7427
7428		/* Clear the short preamble if we won't be supporting it */
7429		priv->assoc_request.capability &=
7430		    ~cpu_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE);
7431	}
7432
7433	/* Clear capability bits that aren't used in Ad Hoc */
7434	if (priv->ieee->iw_mode == IW_MODE_ADHOC)
7435		priv->assoc_request.capability &=
7436		    ~cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT_TIME);
7437
7438	IPW_DEBUG_ASSOC("%sssocation attempt: '%s', channel %d, "
7439			"802.11%c [%d], %s[:%s], enc=%s%s%s%c%c\n",
7440			roaming ? "Rea" : "A",
7441			print_ssid(ssid, priv->essid, priv->essid_len),
7442			network->channel,
7443			ipw_modes[priv->assoc_request.ieee_mode],
7444			rates->num_rates,
7445			(priv->assoc_request.preamble_length ==
7446			 DCT_FLAG_LONG_PREAMBLE) ? "long" : "short",
7447			network->capability &
7448			WLAN_CAPABILITY_SHORT_PREAMBLE ? "short" : "long",
7449			priv->capability & CAP_PRIVACY_ON ? "on " : "off",
7450			priv->capability & CAP_PRIVACY_ON ?
7451			(priv->capability & CAP_SHARED_KEY ? "(shared)" :
7452			 "(open)") : "",
7453			priv->capability & CAP_PRIVACY_ON ? " key=" : "",
7454			priv->capability & CAP_PRIVACY_ON ?
7455			'1' + priv->ieee->sec.active_key : '.',
7456			priv->capability & CAP_PRIVACY_ON ? '.' : ' ');
7457
7458	priv->assoc_request.beacon_interval = cpu_to_le16(network->beacon_interval);
7459	if ((priv->ieee->iw_mode == IW_MODE_ADHOC) &&
7460	    (network->time_stamp[0] == 0) && (network->time_stamp[1] == 0)) {
7461		priv->assoc_request.assoc_type = HC_IBSS_START;
7462		priv->assoc_request.assoc_tsf_msw = 0;
7463		priv->assoc_request.assoc_tsf_lsw = 0;
7464	} else {
7465		if (unlikely(roaming))
7466			priv->assoc_request.assoc_type = HC_REASSOCIATE;
7467		else
7468			priv->assoc_request.assoc_type = HC_ASSOCIATE;
7469		priv->assoc_request.assoc_tsf_msw = cpu_to_le32(network->time_stamp[1]);
7470		priv->assoc_request.assoc_tsf_lsw = cpu_to_le32(network->time_stamp[0]);
7471	}
7472
7473	memcpy(priv->assoc_request.bssid, network->bssid, ETH_ALEN);
7474
7475	if (priv->ieee->iw_mode == IW_MODE_ADHOC) {
7476		memset(&priv->assoc_request.dest, 0xFF, ETH_ALEN);
7477		priv->assoc_request.atim_window = cpu_to_le16(network->atim_window);
7478	} else {
7479		memcpy(priv->assoc_request.dest, network->bssid, ETH_ALEN);
7480		priv->assoc_request.atim_window = 0;
7481	}
7482
7483	priv->assoc_request.listen_interval = cpu_to_le16(network->listen_interval);
7484
7485	err = ipw_send_ssid(priv, priv->essid, priv->essid_len);
7486	if (err) {
7487		IPW_DEBUG_HC("Attempt to send SSID command failed.\n");
7488		return err;
7489	}
7490
7491	rates->ieee_mode = priv->assoc_request.ieee_mode;
7492	rates->purpose = IPW_RATE_CONNECT;
7493	ipw_send_supported_rates(priv, rates);
7494
7495	if (priv->assoc_request.ieee_mode == IPW_G_MODE)
7496		priv->sys_config.dot11g_auto_detection = 1;
7497	else
7498		priv->sys_config.dot11g_auto_detection = 0;
7499
7500	if (priv->ieee->iw_mode == IW_MODE_ADHOC)
7501		priv->sys_config.answer_broadcast_ssid_probe = 1;
7502	else
7503		priv->sys_config.answer_broadcast_ssid_probe = 0;
7504
7505	err = ipw_send_system_config(priv);
7506	if (err) {
7507		IPW_DEBUG_HC("Attempt to send sys config command failed.\n");
7508		return err;
7509	}
7510
7511	IPW_DEBUG_ASSOC("Association sensitivity: %d\n", network->stats.rssi);
7512	err = ipw_set_sensitivity(priv, network->stats.rssi + IPW_RSSI_TO_DBM);
7513	if (err) {
7514		IPW_DEBUG_HC("Attempt to send associate command failed.\n");
7515		return err;
7516	}
7517
7518	/*
7519	 * If preemption is enabled, it is possible for the association
7520	 * to complete before we return from ipw_send_associate.  Therefore
7521	 * we have to be sure and update our priviate data first.
7522	 */
7523	priv->channel = network->channel;
7524	memcpy(priv->bssid, network->bssid, ETH_ALEN);
7525	priv->status |= STATUS_ASSOCIATING;
7526	priv->status &= ~STATUS_SECURITY_UPDATED;
7527
7528	priv->assoc_network = network;
7529
7530#ifdef CONFIG_IPW2200_QOS
7531	ipw_qos_association(priv, network);
7532#endif
7533
7534	err = ipw_send_associate(priv, &priv->assoc_request);
7535	if (err) {
7536		IPW_DEBUG_HC("Attempt to send associate command failed.\n");
7537		return err;
7538	}
7539
7540	IPW_DEBUG(IPW_DL_STATE, "associating: '%s' %pM\n",
7541		  print_ssid(ssid, priv->essid, priv->essid_len),
7542		  priv->bssid);
7543
7544	return 0;
7545}
7546
7547static void ipw_roam(void *data)
7548{
7549	struct ipw_priv *priv = data;
7550	struct libipw_network *network = NULL;
7551	struct ipw_network_match match = {
7552		.network = priv->assoc_network
7553	};
7554
7555	/* The roaming process is as follows:
7556	 *
7557	 * 1.  Missed beacon threshold triggers the roaming process by
7558	 *     setting the status ROAM bit and requesting a scan.
7559	 * 2.  When the scan completes, it schedules the ROAM work
7560	 * 3.  The ROAM work looks at all of the known networks for one that
7561	 *     is a better network than the currently associated.  If none
7562	 *     found, the ROAM process is over (ROAM bit cleared)
7563	 * 4.  If a better network is found, a disassociation request is
7564	 *     sent.
7565	 * 5.  When the disassociation completes, the roam work is again
7566	 *     scheduled.  The second time through, the driver is no longer
7567	 *     associated, and the newly selected network is sent an
7568	 *     association request.
7569	 * 6.  At this point ,the roaming process is complete and the ROAM
7570	 *     status bit is cleared.
7571	 */
7572
7573	/* If we are no longer associated, and the roaming bit is no longer
7574	 * set, then we are not actively roaming, so just return */
7575	if (!(priv->status & (STATUS_ASSOCIATED | STATUS_ROAMING)))
7576		return;
7577
7578	if (priv->status & STATUS_ASSOCIATED) {
7579		/* First pass through ROAM process -- look for a better
7580		 * network */
7581		unsigned long flags;
7582		u8 rssi = priv->assoc_network->stats.rssi;
7583		priv->assoc_network->stats.rssi = -128;
7584		spin_lock_irqsave(&priv->ieee->lock, flags);
7585		list_for_each_entry(network, &priv->ieee->network_list, list) {
7586			if (network != priv->assoc_network)
7587				ipw_best_network(priv, &match, network, 1);
7588		}
7589		spin_unlock_irqrestore(&priv->ieee->lock, flags);
7590		priv->assoc_network->stats.rssi = rssi;
7591
7592		if (match.network == priv->assoc_network) {
7593			IPW_DEBUG_ASSOC("No better APs in this network to "
7594					"roam to.\n");
7595			priv->status &= ~STATUS_ROAMING;
7596			ipw_debug_config(priv);
7597			return;
7598		}
7599
7600		ipw_send_disassociate(priv, 1);
7601		priv->assoc_network = match.network;
7602
7603		return;
7604	}
7605
7606	/* Second pass through ROAM process -- request association */
7607	ipw_compatible_rates(priv, priv->assoc_network, &match.rates);
7608	ipw_associate_network(priv, priv->assoc_network, &match.rates, 1);
7609	priv->status &= ~STATUS_ROAMING;
7610}
7611
7612static void ipw_bg_roam(struct work_struct *work)
7613{
7614	struct ipw_priv *priv =
7615		container_of(work, struct ipw_priv, roam);
7616	mutex_lock(&priv->mutex);
7617	ipw_roam(priv);
7618	mutex_unlock(&priv->mutex);
7619}
7620
7621static int ipw_associate(void *data)
7622{
7623	struct ipw_priv *priv = data;
7624
7625	struct libipw_network *network = NULL;
7626	struct ipw_network_match match = {
7627		.network = NULL
7628	};
7629	struct ipw_supported_rates *rates;
7630	struct list_head *element;
7631	unsigned long flags;
7632	DECLARE_SSID_BUF(ssid);
7633
7634	if (priv->ieee->iw_mode == IW_MODE_MONITOR) {
7635		IPW_DEBUG_ASSOC("Not attempting association (monitor mode)\n");
7636		return 0;
7637	}
7638
7639	if (priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
7640		IPW_DEBUG_ASSOC("Not attempting association (already in "
7641				"progress)\n");
7642		return 0;
7643	}
7644
7645	if (priv->status & STATUS_DISASSOCIATING) {
7646		IPW_DEBUG_ASSOC("Not attempting association (in "
7647				"disassociating)\n ");
7648		queue_work(priv->workqueue, &priv->associate);
7649		return 0;
7650	}
7651
7652	if (!ipw_is_init(priv) || (priv->status & STATUS_SCANNING)) {
7653		IPW_DEBUG_ASSOC("Not attempting association (scanning or not "
7654				"initialized)\n");
7655		return 0;
7656	}
7657
7658	if (!(priv->config & CFG_ASSOCIATE) &&
7659	    !(priv->config & (CFG_STATIC_ESSID | CFG_STATIC_BSSID))) {
7660		IPW_DEBUG_ASSOC("Not attempting association (associate=0)\n");
7661		return 0;
7662	}
7663
7664	/* Protect our use of the network_list */
7665	spin_lock_irqsave(&priv->ieee->lock, flags);
7666	list_for_each_entry(network, &priv->ieee->network_list, list)
7667	    ipw_best_network(priv, &match, network, 0);
7668
7669	network = match.network;
7670	rates = &match.rates;
7671
7672	if (network == NULL &&
7673	    priv->ieee->iw_mode == IW_MODE_ADHOC &&
7674	    priv->config & CFG_ADHOC_CREATE &&
7675	    priv->config & CFG_STATIC_ESSID &&
7676	    priv->config & CFG_STATIC_CHANNEL) {
7677		/* Use oldest network if the free list is empty */
7678		if (list_empty(&priv->ieee->network_free_list)) {
7679			struct libipw_network *oldest = NULL;
7680			struct libipw_network *target;
7681
7682			list_for_each_entry(target, &priv->ieee->network_list, list) {
7683				if ((oldest == NULL) ||
7684				    (target->last_scanned < oldest->last_scanned))
7685					oldest = target;
7686			}
7687
7688			/* If there are no more slots, expire the oldest */
7689			list_del(&oldest->list);
7690			target = oldest;
7691			IPW_DEBUG_ASSOC("Expired '%s' (%pM) from "
7692					"network list.\n",
7693					print_ssid(ssid, target->ssid,
7694						   target->ssid_len),
7695					target->bssid);
7696			list_add_tail(&target->list,
7697				      &priv->ieee->network_free_list);
7698		}
7699
7700		element = priv->ieee->network_free_list.next;
7701		network = list_entry(element, struct libipw_network, list);
7702		ipw_adhoc_create(priv, network);
7703		rates = &priv->rates;
7704		list_del(element);
7705		list_add_tail(&network->list, &priv->ieee->network_list);
7706	}
7707	spin_unlock_irqrestore(&priv->ieee->lock, flags);
7708
7709	/* If we reached the end of the list, then we don't have any valid
7710	 * matching APs */
7711	if (!network) {
7712		ipw_debug_config(priv);
7713
7714		if (!(priv->status & STATUS_SCANNING)) {
7715			if (!(priv->config & CFG_SPEED_SCAN))
7716				queue_delayed_work(priv->workqueue,
7717						   &priv->request_scan,
7718						   SCAN_INTERVAL);
7719			else
7720				queue_delayed_work(priv->workqueue,
7721						   &priv->request_scan, 0);
7722		}
7723
7724		return 0;
7725	}
7726
7727	ipw_associate_network(priv, network, rates, 0);
7728
7729	return 1;
7730}
7731
7732static void ipw_bg_associate(struct work_struct *work)
7733{
7734	struct ipw_priv *priv =
7735		container_of(work, struct ipw_priv, associate);
7736	mutex_lock(&priv->mutex);
7737	ipw_associate(priv);
7738	mutex_unlock(&priv->mutex);
7739}
7740
7741static void ipw_rebuild_decrypted_skb(struct ipw_priv *priv,
7742				      struct sk_buff *skb)
7743{
7744	struct ieee80211_hdr *hdr;
7745	u16 fc;
7746
7747	hdr = (struct ieee80211_hdr *)skb->data;
7748	fc = le16_to_cpu(hdr->frame_control);
7749	if (!(fc & IEEE80211_FCTL_PROTECTED))
7750		return;
7751
7752	fc &= ~IEEE80211_FCTL_PROTECTED;
7753	hdr->frame_control = cpu_to_le16(fc);
7754	switch (priv->ieee->sec.level) {
7755	case SEC_LEVEL_3:
7756		/* Remove CCMP HDR */
7757		memmove(skb->data + LIBIPW_3ADDR_LEN,
7758			skb->data + LIBIPW_3ADDR_LEN + 8,
7759			skb->len - LIBIPW_3ADDR_LEN - 8);
7760		skb_trim(skb, skb->len - 16);	/* CCMP_HDR_LEN + CCMP_MIC_LEN */
7761		break;
7762	case SEC_LEVEL_2:
7763		break;
7764	case SEC_LEVEL_1:
7765		/* Remove IV */
7766		memmove(skb->data + LIBIPW_3ADDR_LEN,
7767			skb->data + LIBIPW_3ADDR_LEN + 4,
7768			skb->len - LIBIPW_3ADDR_LEN - 4);
7769		skb_trim(skb, skb->len - 8);	/* IV + ICV */
7770		break;
7771	case SEC_LEVEL_0:
7772		break;
7773	default:
7774		printk(KERN_ERR "Unknown security level %d\n",
7775		       priv->ieee->sec.level);
7776		break;
7777	}
7778}
7779
7780static void ipw_handle_data_packet(struct ipw_priv *priv,
7781				   struct ipw_rx_mem_buffer *rxb,
7782				   struct libipw_rx_stats *stats)
7783{
7784	struct net_device *dev = priv->net_dev;
7785	struct libipw_hdr_4addr *hdr;
7786	struct ipw_rx_packet *pkt = (struct ipw_rx_packet *)rxb->skb->data;
7787
7788	/* We received data from the HW, so stop the watchdog */
7789	dev->trans_start = jiffies;
7790
7791	/* We only process data packets if the
7792	 * interface is open */
7793	if (unlikely((le16_to_cpu(pkt->u.frame.length) + IPW_RX_FRAME_SIZE) >
7794		     skb_tailroom(rxb->skb))) {
7795		dev->stats.rx_errors++;
7796		priv->wstats.discard.misc++;
7797		IPW_DEBUG_DROP("Corruption detected! Oh no!\n");
7798		return;
7799	} else if (unlikely(!netif_running(priv->net_dev))) {
7800		dev->stats.rx_dropped++;
7801		priv->wstats.discard.misc++;
7802		IPW_DEBUG_DROP("Dropping packet while interface is not up.\n");
7803		return;
7804	}
7805
7806	/* Advance skb->data to the start of the actual payload */
7807	skb_reserve(rxb->skb, offsetof(struct ipw_rx_packet, u.frame.data));
7808
7809	/* Set the size of the skb to the size of the frame */
7810	skb_put(rxb->skb, le16_to_cpu(pkt->u.frame.length));
7811
7812	IPW_DEBUG_RX("Rx packet of %d bytes.\n", rxb->skb->len);
7813
7814	/* HW decrypt will not clear the WEP bit, MIC, PN, etc. */
7815	hdr = (struct libipw_hdr_4addr *)rxb->skb->data;
7816	if (priv->ieee->iw_mode != IW_MODE_MONITOR &&
7817	    (is_multicast_ether_addr(hdr->addr1) ?
7818	     !priv->ieee->host_mc_decrypt : !priv->ieee->host_decrypt))
7819		ipw_rebuild_decrypted_skb(priv, rxb->skb);
7820
7821	if (!libipw_rx(priv->ieee, rxb->skb, stats))
7822		dev->stats.rx_errors++;
7823	else {			/* libipw_rx succeeded, so it now owns the SKB */
7824		rxb->skb = NULL;
7825		__ipw_led_activity_on(priv);
7826	}
7827}
7828
7829#ifdef CONFIG_IPW2200_RADIOTAP
7830static void ipw_handle_data_packet_monitor(struct ipw_priv *priv,
7831					   struct ipw_rx_mem_buffer *rxb,
7832					   struct libipw_rx_stats *stats)
7833{
7834	struct net_device *dev = priv->net_dev;
7835	struct ipw_rx_packet *pkt = (struct ipw_rx_packet *)rxb->skb->data;
7836	struct ipw_rx_frame *frame = &pkt->u.frame;
7837
7838	/* initial pull of some data */
7839	u16 received_channel = frame->received_channel;
7840	u8 antennaAndPhy = frame->antennaAndPhy;
7841	s8 antsignal = frame->rssi_dbm - IPW_RSSI_TO_DBM;	/* call it signed anyhow */
7842	u16 pktrate = frame->rate;
7843
7844	/* Magic struct that slots into the radiotap header -- no reason
7845	 * to build this manually element by element, we can write it much
7846	 * more efficiently than we can parse it. ORDER MATTERS HERE */
7847	struct ipw_rt_hdr *ipw_rt;
7848
7849	short len = le16_to_cpu(pkt->u.frame.length);
7850
7851	/* We received data from the HW, so stop the watchdog */
7852	dev->trans_start = jiffies;
7853
7854	/* We only process data packets if the
7855	 * interface is open */
7856	if (unlikely((le16_to_cpu(pkt->u.frame.length) + IPW_RX_FRAME_SIZE) >
7857		     skb_tailroom(rxb->skb))) {
7858		dev->stats.rx_errors++;
7859		priv->wstats.discard.misc++;
7860		IPW_DEBUG_DROP("Corruption detected! Oh no!\n");
7861		return;
7862	} else if (unlikely(!netif_running(priv->net_dev))) {
7863		dev->stats.rx_dropped++;
7864		priv->wstats.discard.misc++;
7865		IPW_DEBUG_DROP("Dropping packet while interface is not up.\n");
7866		return;
7867	}
7868
7869	/* Libpcap 0.9.3+ can handle variable length radiotap, so we'll use
7870	 * that now */
7871	if (len > IPW_RX_BUF_SIZE - sizeof(struct ipw_rt_hdr)) {
7872		dev->stats.rx_dropped++;
7873		priv->wstats.discard.misc++;
7874		IPW_DEBUG_DROP("Dropping too large packet in monitor\n");
7875		return;
7876	}
7877
7878	/* copy the frame itself */
7879	memmove(rxb->skb->data + sizeof(struct ipw_rt_hdr),
7880		rxb->skb->data + IPW_RX_FRAME_SIZE, len);
7881
7882	ipw_rt = (struct ipw_rt_hdr *)rxb->skb->data;
7883
7884	ipw_rt->rt_hdr.it_version = PKTHDR_RADIOTAP_VERSION;
7885	ipw_rt->rt_hdr.it_pad = 0;	/* always good to zero */
7886	ipw_rt->rt_hdr.it_len = cpu_to_le16(sizeof(struct ipw_rt_hdr));	/* total header+data */
7887
7888	/* Big bitfield of all the fields we provide in radiotap */
7889	ipw_rt->rt_hdr.it_present = cpu_to_le32(
7890	     (1 << IEEE80211_RADIOTAP_TSFT) |
7891	     (1 << IEEE80211_RADIOTAP_FLAGS) |
7892	     (1 << IEEE80211_RADIOTAP_RATE) |
7893	     (1 << IEEE80211_RADIOTAP_CHANNEL) |
7894	     (1 << IEEE80211_RADIOTAP_DBM_ANTSIGNAL) |
7895	     (1 << IEEE80211_RADIOTAP_DBM_ANTNOISE) |
7896	     (1 << IEEE80211_RADIOTAP_ANTENNA));
7897
7898	/* Zero the flags, we'll add to them as we go */
7899	ipw_rt->rt_flags = 0;
7900	ipw_rt->rt_tsf = (u64)(frame->parent_tsf[3] << 24 |
7901			       frame->parent_tsf[2] << 16 |
7902			       frame->parent_tsf[1] << 8  |
7903			       frame->parent_tsf[0]);
7904
7905	/* Convert signal to DBM */
7906	ipw_rt->rt_dbmsignal = antsignal;
7907	ipw_rt->rt_dbmnoise = (s8) le16_to_cpu(frame->noise);
7908
7909	/* Convert the channel data and set the flags */
7910	ipw_rt->rt_channel = cpu_to_le16(ieee80211chan2mhz(received_channel));
7911	if (received_channel > 14) {	/* 802.11a */
7912		ipw_rt->rt_chbitmask =
7913		    cpu_to_le16((IEEE80211_CHAN_OFDM | IEEE80211_CHAN_5GHZ));
7914	} else if (antennaAndPhy & 32) {	/* 802.11b */
7915		ipw_rt->rt_chbitmask =
7916		    cpu_to_le16((IEEE80211_CHAN_CCK | IEEE80211_CHAN_2GHZ));
7917	} else {		/* 802.11g */
7918		ipw_rt->rt_chbitmask =
7919		    cpu_to_le16(IEEE80211_CHAN_OFDM | IEEE80211_CHAN_2GHZ);
7920	}
7921
7922	/* set the rate in multiples of 500k/s */
7923	switch (pktrate) {
7924	case IPW_TX_RATE_1MB:
7925		ipw_rt->rt_rate = 2;
7926		break;
7927	case IPW_TX_RATE_2MB:
7928		ipw_rt->rt_rate = 4;
7929		break;
7930	case IPW_TX_RATE_5MB:
7931		ipw_rt->rt_rate = 10;
7932		break;
7933	case IPW_TX_RATE_6MB:
7934		ipw_rt->rt_rate = 12;
7935		break;
7936	case IPW_TX_RATE_9MB:
7937		ipw_rt->rt_rate = 18;
7938		break;
7939	case IPW_TX_RATE_11MB:
7940		ipw_rt->rt_rate = 22;
7941		break;
7942	case IPW_TX_RATE_12MB:
7943		ipw_rt->rt_rate = 24;
7944		break;
7945	case IPW_TX_RATE_18MB:
7946		ipw_rt->rt_rate = 36;
7947		break;
7948	case IPW_TX_RATE_24MB:
7949		ipw_rt->rt_rate = 48;
7950		break;
7951	case IPW_TX_RATE_36MB:
7952		ipw_rt->rt_rate = 72;
7953		break;
7954	case IPW_TX_RATE_48MB:
7955		ipw_rt->rt_rate = 96;
7956		break;
7957	case IPW_TX_RATE_54MB:
7958		ipw_rt->rt_rate = 108;
7959		break;
7960	default:
7961		ipw_rt->rt_rate = 0;
7962		break;
7963	}
7964
7965	/* antenna number */
7966	ipw_rt->rt_antenna = (antennaAndPhy & 3);	/* Is this right? */
7967
7968	/* set the preamble flag if we have it */
7969	if ((antennaAndPhy & 64))
7970		ipw_rt->rt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
7971
7972	/* Set the size of the skb to the size of the frame */
7973	skb_put(rxb->skb, len + sizeof(struct ipw_rt_hdr));
7974
7975	IPW_DEBUG_RX("Rx packet of %d bytes.\n", rxb->skb->len);
7976
7977	if (!libipw_rx(priv->ieee, rxb->skb, stats))
7978		dev->stats.rx_errors++;
7979	else {			/* libipw_rx succeeded, so it now owns the SKB */
7980		rxb->skb = NULL;
7981		/* no LED during capture */
7982	}
7983}
7984#endif
7985
7986#ifdef CONFIG_IPW2200_PROMISCUOUS
7987#define libipw_is_probe_response(fc) \
7988   ((fc & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_MGMT && \
7989    (fc & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_PROBE_RESP )
7990
7991#define libipw_is_management(fc) \
7992   ((fc & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_MGMT)
7993
7994#define libipw_is_control(fc) \
7995   ((fc & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_CTL)
7996
7997#define libipw_is_data(fc) \
7998   ((fc & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_DATA)
7999
8000#define libipw_is_assoc_request(fc) \
8001   ((fc & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_ASSOC_REQ)
8002
8003#define libipw_is_reassoc_request(fc) \
8004   ((fc & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_REASSOC_REQ)
8005
8006static void ipw_handle_promiscuous_rx(struct ipw_priv *priv,
8007				      struct ipw_rx_mem_buffer *rxb,
8008				      struct libipw_rx_stats *stats)
8009{
8010	struct net_device *dev = priv->prom_net_dev;
8011	struct ipw_rx_packet *pkt = (struct ipw_rx_packet *)rxb->skb->data;
8012	struct ipw_rx_frame *frame = &pkt->u.frame;
8013	struct ipw_rt_hdr *ipw_rt;
8014
8015	/* First cache any information we need before we overwrite
8016	 * the information provided in the skb from the hardware */
8017	struct ieee80211_hdr *hdr;
8018	u16 channel = frame->received_channel;
8019	u8 phy_flags = frame->antennaAndPhy;
8020	s8 signal = frame->rssi_dbm - IPW_RSSI_TO_DBM;
8021	s8 noise = (s8) le16_to_cpu(frame->noise);
8022	u8 rate = frame->rate;
8023	short len = le16_to_cpu(pkt->u.frame.length);
8024	struct sk_buff *skb;
8025	int hdr_only = 0;
8026	u16 filter = priv->prom_priv->filter;
8027
8028	/* If the filter is set to not include Rx frames then return */
8029	if (filter & IPW_PROM_NO_RX)
8030		return;
8031
8032	/* We received data from the HW, so stop the watchdog */
8033	dev->trans_start = jiffies;
8034
8035	if (unlikely((len + IPW_RX_FRAME_SIZE) > skb_tailroom(rxb->skb))) {
8036		dev->stats.rx_errors++;
8037		IPW_DEBUG_DROP("Corruption detected! Oh no!\n");
8038		return;
8039	}
8040
8041	/* We only process data packets if the interface is open */
8042	if (unlikely(!netif_running(dev))) {
8043		dev->stats.rx_dropped++;
8044		IPW_DEBUG_DROP("Dropping packet while interface is not up.\n");
8045		return;
8046	}
8047
8048	/* Libpcap 0.9.3+ can handle variable length radiotap, so we'll use
8049	 * that now */
8050	if (len > IPW_RX_BUF_SIZE - sizeof(struct ipw_rt_hdr)) {
8051		dev->stats.rx_dropped++;
8052		IPW_DEBUG_DROP("Dropping too large packet in monitor\n");
8053		return;
8054	}
8055
8056	hdr = (void *)rxb->skb->data + IPW_RX_FRAME_SIZE;
8057	if (libipw_is_management(le16_to_cpu(hdr->frame_control))) {
8058		if (filter & IPW_PROM_NO_MGMT)
8059			return;
8060		if (filter & IPW_PROM_MGMT_HEADER_ONLY)
8061			hdr_only = 1;
8062	} else if (libipw_is_control(le16_to_cpu(hdr->frame_control))) {
8063		if (filter & IPW_PROM_NO_CTL)
8064			return;
8065		if (filter & IPW_PROM_CTL_HEADER_ONLY)
8066			hdr_only = 1;
8067	} else if (libipw_is_data(le16_to_cpu(hdr->frame_control))) {
8068		if (filter & IPW_PROM_NO_DATA)
8069			return;
8070		if (filter & IPW_PROM_DATA_HEADER_ONLY)
8071			hdr_only = 1;
8072	}
8073
8074	/* Copy the SKB since this is for the promiscuous side */
8075	skb = skb_copy(rxb->skb, GFP_ATOMIC);
8076	if (skb == NULL) {
8077		IPW_ERROR("skb_clone failed for promiscuous copy.\n");
8078		return;
8079	}
8080
8081	/* copy the frame data to write after where the radiotap header goes */
8082	ipw_rt = (void *)skb->data;
8083
8084	if (hdr_only)
8085		len = libipw_get_hdrlen(le16_to_cpu(hdr->frame_control));
8086
8087	memcpy(ipw_rt->payload, hdr, len);
8088
8089	ipw_rt->rt_hdr.it_version = PKTHDR_RADIOTAP_VERSION;
8090	ipw_rt->rt_hdr.it_pad = 0;	/* always good to zero */
8091	ipw_rt->rt_hdr.it_len = cpu_to_le16(sizeof(*ipw_rt));	/* total header+data */
8092
8093	/* Set the size of the skb to the size of the frame */
8094	skb_put(skb, sizeof(*ipw_rt) + len);
8095
8096	/* Big bitfield of all the fields we provide in radiotap */
8097	ipw_rt->rt_hdr.it_present = cpu_to_le32(
8098	     (1 << IEEE80211_RADIOTAP_TSFT) |
8099	     (1 << IEEE80211_RADIOTAP_FLAGS) |
8100	     (1 << IEEE80211_RADIOTAP_RATE) |
8101	     (1 << IEEE80211_RADIOTAP_CHANNEL) |
8102	     (1 << IEEE80211_RADIOTAP_DBM_ANTSIGNAL) |
8103	     (1 << IEEE80211_RADIOTAP_DBM_ANTNOISE) |
8104	     (1 << IEEE80211_RADIOTAP_ANTENNA));
8105
8106	/* Zero the flags, we'll add to them as we go */
8107	ipw_rt->rt_flags = 0;
8108	ipw_rt->rt_tsf = (u64)(frame->parent_tsf[3] << 24 |
8109			       frame->parent_tsf[2] << 16 |
8110			       frame->parent_tsf[1] << 8  |
8111			       frame->parent_tsf[0]);
8112
8113	/* Convert to DBM */
8114	ipw_rt->rt_dbmsignal = signal;
8115	ipw_rt->rt_dbmnoise = noise;
8116
8117	/* Convert the channel data and set the flags */
8118	ipw_rt->rt_channel = cpu_to_le16(ieee80211chan2mhz(channel));
8119	if (channel > 14) {	/* 802.11a */
8120		ipw_rt->rt_chbitmask =
8121		    cpu_to_le16((IEEE80211_CHAN_OFDM | IEEE80211_CHAN_5GHZ));
8122	} else if (phy_flags & (1 << 5)) {	/* 802.11b */
8123		ipw_rt->rt_chbitmask =
8124		    cpu_to_le16((IEEE80211_CHAN_CCK | IEEE80211_CHAN_2GHZ));
8125	} else {		/* 802.11g */
8126		ipw_rt->rt_chbitmask =
8127		    cpu_to_le16(IEEE80211_CHAN_OFDM | IEEE80211_CHAN_2GHZ);
8128	}
8129
8130	/* set the rate in multiples of 500k/s */
8131	switch (rate) {
8132	case IPW_TX_RATE_1MB:
8133		ipw_rt->rt_rate = 2;
8134		break;
8135	case IPW_TX_RATE_2MB:
8136		ipw_rt->rt_rate = 4;
8137		break;
8138	case IPW_TX_RATE_5MB:
8139		ipw_rt->rt_rate = 10;
8140		break;
8141	case IPW_TX_RATE_6MB:
8142		ipw_rt->rt_rate = 12;
8143		break;
8144	case IPW_TX_RATE_9MB:
8145		ipw_rt->rt_rate = 18;
8146		break;
8147	case IPW_TX_RATE_11MB:
8148		ipw_rt->rt_rate = 22;
8149		break;
8150	case IPW_TX_RATE_12MB:
8151		ipw_rt->rt_rate = 24;
8152		break;
8153	case IPW_TX_RATE_18MB:
8154		ipw_rt->rt_rate = 36;
8155		break;
8156	case IPW_TX_RATE_24MB:
8157		ipw_rt->rt_rate = 48;
8158		break;
8159	case IPW_TX_RATE_36MB:
8160		ipw_rt->rt_rate = 72;
8161		break;
8162	case IPW_TX_RATE_48MB:
8163		ipw_rt->rt_rate = 96;
8164		break;
8165	case IPW_TX_RATE_54MB:
8166		ipw_rt->rt_rate = 108;
8167		break;
8168	default:
8169		ipw_rt->rt_rate = 0;
8170		break;
8171	}
8172
8173	/* antenna number */
8174	ipw_rt->rt_antenna = (phy_flags & 3);
8175
8176	/* set the preamble flag if we have it */
8177	if (phy_flags & (1 << 6))
8178		ipw_rt->rt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
8179
8180	IPW_DEBUG_RX("Rx packet of %d bytes.\n", skb->len);
8181
8182	if (!libipw_rx(priv->prom_priv->ieee, skb, stats)) {
8183		dev->stats.rx_errors++;
8184		dev_kfree_skb_any(skb);
8185	}
8186}
8187#endif
8188
8189static int is_network_packet(struct ipw_priv *priv,
8190				    struct libipw_hdr_4addr *header)
8191{
8192	/* Filter incoming packets to determine if they are targetted toward
8193	 * this network, discarding packets coming from ourselves */
8194	switch (priv->ieee->iw_mode) {
8195	case IW_MODE_ADHOC:	/* Header: Dest. | Source    | BSSID */
8196		/* packets from our adapter are dropped (echo) */
8197		if (!memcmp(header->addr2, priv->net_dev->dev_addr, ETH_ALEN))
8198			return 0;
8199
8200		/* {broad,multi}cast packets to our BSSID go through */
8201		if (is_multicast_ether_addr(header->addr1))
8202			return !memcmp(header->addr3, priv->bssid, ETH_ALEN);
8203
8204		/* packets to our adapter go through */
8205		return !memcmp(header->addr1, priv->net_dev->dev_addr,
8206			       ETH_ALEN);
8207
8208	case IW_MODE_INFRA:	/* Header: Dest. | BSSID | Source */
8209		/* packets from our adapter are dropped (echo) */
8210		if (!memcmp(header->addr3, priv->net_dev->dev_addr, ETH_ALEN))
8211			return 0;
8212
8213		/* {broad,multi}cast packets to our BSS go through */
8214		if (is_multicast_ether_addr(header->addr1))
8215			return !memcmp(header->addr2, priv->bssid, ETH_ALEN);
8216
8217		/* packets to our adapter go through */
8218		return !memcmp(header->addr1, priv->net_dev->dev_addr,
8219			       ETH_ALEN);
8220	}
8221
8222	return 1;
8223}
8224
8225#define IPW_PACKET_RETRY_TIME HZ
8226
8227static  int is_duplicate_packet(struct ipw_priv *priv,
8228				      struct libipw_hdr_4addr *header)
8229{
8230	u16 sc = le16_to_cpu(header->seq_ctl);
8231	u16 seq = WLAN_GET_SEQ_SEQ(sc);
8232	u16 frag = WLAN_GET_SEQ_FRAG(sc);
8233	u16 *last_seq, *last_frag;
8234	unsigned long *last_time;
8235
8236	switch (priv->ieee->iw_mode) {
8237	case IW_MODE_ADHOC:
8238		{
8239			struct list_head *p;
8240			struct ipw_ibss_seq *entry = NULL;
8241			u8 *mac = header->addr2;
8242			int index = mac[5] % IPW_IBSS_MAC_HASH_SIZE;
8243
8244			__list_for_each(p, &priv->ibss_mac_hash[index]) {
8245				entry =
8246				    list_entry(p, struct ipw_ibss_seq, list);
8247				if (!memcmp(entry->mac, mac, ETH_ALEN))
8248					break;
8249			}
8250			if (p == &priv->ibss_mac_hash[index]) {
8251				entry = kmalloc(sizeof(*entry), GFP_ATOMIC);
8252				if (!entry) {
8253					IPW_ERROR
8254					    ("Cannot malloc new mac entry\n");
8255					return 0;
8256				}
8257				memcpy(entry->mac, mac, ETH_ALEN);
8258				entry->seq_num = seq;
8259				entry->frag_num = frag;
8260				entry->packet_time = jiffies;
8261				list_add(&entry->list,
8262					 &priv->ibss_mac_hash[index]);
8263				return 0;
8264			}
8265			last_seq = &entry->seq_num;
8266			last_frag = &entry->frag_num;
8267			last_time = &entry->packet_time;
8268			break;
8269		}
8270	case IW_MODE_INFRA:
8271		last_seq = &priv->last_seq_num;
8272		last_frag = &priv->last_frag_num;
8273		last_time = &priv->last_packet_time;
8274		break;
8275	default:
8276		return 0;
8277	}
8278	if ((*last_seq == seq) &&
8279	    time_after(*last_time + IPW_PACKET_RETRY_TIME, jiffies)) {
8280		if (*last_frag == frag)
8281			goto drop;
8282		if (*last_frag + 1 != frag)
8283			/* out-of-order fragment */
8284			goto drop;
8285	} else
8286		*last_seq = seq;
8287
8288	*last_frag = frag;
8289	*last_time = jiffies;
8290	return 0;
8291
8292      drop:
8293	/* Comment this line now since we observed the card receives
8294	 * duplicate packets but the FCTL_RETRY bit is not set in the
8295	 * IBSS mode with fragmentation enabled.
8296	 BUG_ON(!(le16_to_cpu(header->frame_control) & IEEE80211_FCTL_RETRY)); */
8297	return 1;
8298}
8299
8300static void ipw_handle_mgmt_packet(struct ipw_priv *priv,
8301				   struct ipw_rx_mem_buffer *rxb,
8302				   struct libipw_rx_stats *stats)
8303{
8304	struct sk_buff *skb = rxb->skb;
8305	struct ipw_rx_packet *pkt = (struct ipw_rx_packet *)skb->data;
8306	struct libipw_hdr_4addr *header = (struct libipw_hdr_4addr *)
8307	    (skb->data + IPW_RX_FRAME_SIZE);
8308
8309	libipw_rx_mgt(priv->ieee, header, stats);
8310
8311	if (priv->ieee->iw_mode == IW_MODE_ADHOC &&
8312	    ((WLAN_FC_GET_STYPE(le16_to_cpu(header->frame_ctl)) ==
8313	      IEEE80211_STYPE_PROBE_RESP) ||
8314	     (WLAN_FC_GET_STYPE(le16_to_cpu(header->frame_ctl)) ==
8315	      IEEE80211_STYPE_BEACON))) {
8316		if (!memcmp(header->addr3, priv->bssid, ETH_ALEN))
8317			ipw_add_station(priv, header->addr2);
8318	}
8319
8320	if (priv->config & CFG_NET_STATS) {
8321		IPW_DEBUG_HC("sending stat packet\n");
8322
8323		/* Set the size of the skb to the size of the full
8324		 * ipw header and 802.11 frame */
8325		skb_put(skb, le16_to_cpu(pkt->u.frame.length) +
8326			IPW_RX_FRAME_SIZE);
8327
8328		/* Advance past the ipw packet header to the 802.11 frame */
8329		skb_pull(skb, IPW_RX_FRAME_SIZE);
8330
8331		/* Push the libipw_rx_stats before the 802.11 frame */
8332		memcpy(skb_push(skb, sizeof(*stats)), stats, sizeof(*stats));
8333
8334		skb->dev = priv->ieee->dev;
8335
8336		/* Point raw at the libipw_stats */
8337		skb_reset_mac_header(skb);
8338
8339		skb->pkt_type = PACKET_OTHERHOST;
8340		skb->protocol = cpu_to_be16(ETH_P_80211_STATS);
8341		memset(skb->cb, 0, sizeof(rxb->skb->cb));
8342		netif_rx(skb);
8343		rxb->skb = NULL;
8344	}
8345}
8346
8347/*
8348 * Main entry function for recieving a packet with 80211 headers.  This
8349 * should be called when ever the FW has notified us that there is a new
8350 * skb in the recieve queue.
8351 */
8352static void ipw_rx(struct ipw_priv *priv)
8353{
8354	struct ipw_rx_mem_buffer *rxb;
8355	struct ipw_rx_packet *pkt;
8356	struct libipw_hdr_4addr *header;
8357	u32 r, w, i;
8358	u8 network_packet;
8359	u8 fill_rx = 0;
8360
8361	r = ipw_read32(priv, IPW_RX_READ_INDEX);
8362	w = ipw_read32(priv, IPW_RX_WRITE_INDEX);
8363	i = priv->rxq->read;
8364
8365	if (ipw_rx_queue_space (priv->rxq) > (RX_QUEUE_SIZE / 2))
8366		fill_rx = 1;
8367
8368	while (i != r) {
8369		rxb = priv->rxq->queue[i];
8370		if (unlikely(rxb == NULL)) {
8371			printk(KERN_CRIT "Queue not allocated!\n");
8372			break;
8373		}
8374		priv->rxq->queue[i] = NULL;
8375
8376		pci_dma_sync_single_for_cpu(priv->pci_dev, rxb->dma_addr,
8377					    IPW_RX_BUF_SIZE,
8378					    PCI_DMA_FROMDEVICE);
8379
8380		pkt = (struct ipw_rx_packet *)rxb->skb->data;
8381		IPW_DEBUG_RX("Packet: type=%02X seq=%02X bits=%02X\n",
8382			     pkt->header.message_type,
8383			     pkt->header.rx_seq_num, pkt->header.control_bits);
8384
8385		switch (pkt->header.message_type) {
8386		case RX_FRAME_TYPE:	/* 802.11 frame */  {
8387				struct libipw_rx_stats stats = {
8388					.rssi = pkt->u.frame.rssi_dbm -
8389					    IPW_RSSI_TO_DBM,
8390					.signal =
8391					    pkt->u.frame.rssi_dbm -
8392					    IPW_RSSI_TO_DBM + 0x100,
8393					.noise =
8394					    le16_to_cpu(pkt->u.frame.noise),
8395					.rate = pkt->u.frame.rate,
8396					.mac_time = jiffies,
8397					.received_channel =
8398					    pkt->u.frame.received_channel,
8399					.freq =
8400					    (pkt->u.frame.
8401					     control & (1 << 0)) ?
8402					    LIBIPW_24GHZ_BAND :
8403					    LIBIPW_52GHZ_BAND,
8404					.len = le16_to_cpu(pkt->u.frame.length),
8405				};
8406
8407				if (stats.rssi != 0)
8408					stats.mask |= LIBIPW_STATMASK_RSSI;
8409				if (stats.signal != 0)
8410					stats.mask |= LIBIPW_STATMASK_SIGNAL;
8411				if (stats.noise != 0)
8412					stats.mask |= LIBIPW_STATMASK_NOISE;
8413				if (stats.rate != 0)
8414					stats.mask |= LIBIPW_STATMASK_RATE;
8415
8416				priv->rx_packets++;
8417
8418#ifdef CONFIG_IPW2200_PROMISCUOUS
8419	if (priv->prom_net_dev && netif_running(priv->prom_net_dev))
8420		ipw_handle_promiscuous_rx(priv, rxb, &stats);
8421#endif
8422
8423#ifdef CONFIG_IPW2200_MONITOR
8424				if (priv->ieee->iw_mode == IW_MODE_MONITOR) {
8425#ifdef CONFIG_IPW2200_RADIOTAP
8426
8427                ipw_handle_data_packet_monitor(priv,
8428					       rxb,
8429					       &stats);
8430#else
8431		ipw_handle_data_packet(priv, rxb,
8432				       &stats);
8433#endif
8434					break;
8435				}
8436#endif
8437
8438				header =
8439				    (struct libipw_hdr_4addr *)(rxb->skb->
8440								   data +
8441								   IPW_RX_FRAME_SIZE);
8442				/* TODO: Check Ad-Hoc dest/source and make sure
8443				 * that we are actually parsing these packets
8444				 * correctly -- we should probably use the
8445				 * frame control of the packet and disregard
8446				 * the current iw_mode */
8447
8448				network_packet =
8449				    is_network_packet(priv, header);
8450				if (network_packet && priv->assoc_network) {
8451					priv->assoc_network->stats.rssi =
8452					    stats.rssi;
8453					priv->exp_avg_rssi =
8454					    exponential_average(priv->exp_avg_rssi,
8455					    stats.rssi, DEPTH_RSSI);
8456				}
8457
8458				IPW_DEBUG_RX("Frame: len=%u\n",
8459					     le16_to_cpu(pkt->u.frame.length));
8460
8461				if (le16_to_cpu(pkt->u.frame.length) <
8462				    libipw_get_hdrlen(le16_to_cpu(
8463						    header->frame_ctl))) {
8464					IPW_DEBUG_DROP
8465					    ("Received packet is too small. "
8466					     "Dropping.\n");
8467					priv->net_dev->stats.rx_errors++;
8468					priv->wstats.discard.misc++;
8469					break;
8470				}
8471
8472				switch (WLAN_FC_GET_TYPE
8473					(le16_to_cpu(header->frame_ctl))) {
8474
8475				case IEEE80211_FTYPE_MGMT:
8476					ipw_handle_mgmt_packet(priv, rxb,
8477							       &stats);
8478					break;
8479
8480				case IEEE80211_FTYPE_CTL:
8481					break;
8482
8483				case IEEE80211_FTYPE_DATA:
8484					if (unlikely(!network_packet ||
8485						     is_duplicate_packet(priv,
8486									 header)))
8487					{
8488						IPW_DEBUG_DROP("Dropping: "
8489							       "%pM, "
8490							       "%pM, "
8491							       "%pM\n",
8492							       header->addr1,
8493							       header->addr2,
8494							       header->addr3);
8495						break;
8496					}
8497
8498					ipw_handle_data_packet(priv, rxb,
8499							       &stats);
8500
8501					break;
8502				}
8503				break;
8504			}
8505
8506		case RX_HOST_NOTIFICATION_TYPE:{
8507				IPW_DEBUG_RX
8508				    ("Notification: subtype=%02X flags=%02X size=%d\n",
8509				     pkt->u.notification.subtype,
8510				     pkt->u.notification.flags,
8511				     le16_to_cpu(pkt->u.notification.size));
8512				ipw_rx_notification(priv, &pkt->u.notification);
8513				break;
8514			}
8515
8516		default:
8517			IPW_DEBUG_RX("Bad Rx packet of type %d\n",
8518				     pkt->header.message_type);
8519			break;
8520		}
8521
8522		/* For now we just don't re-use anything.  We can tweak this
8523		 * later to try and re-use notification packets and SKBs that
8524		 * fail to Rx correctly */
8525		if (rxb->skb != NULL) {
8526			dev_kfree_skb_any(rxb->skb);
8527			rxb->skb = NULL;
8528		}
8529
8530		pci_unmap_single(priv->pci_dev, rxb->dma_addr,
8531				 IPW_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
8532		list_add_tail(&rxb->list, &priv->rxq->rx_used);
8533
8534		i = (i + 1) % RX_QUEUE_SIZE;
8535
8536		/* If there are a lot of unsued frames, restock the Rx queue
8537		 * so the ucode won't assert */
8538		if (fill_rx) {
8539			priv->rxq->read = i;
8540			ipw_rx_queue_replenish(priv);
8541		}
8542	}
8543
8544	/* Backtrack one entry */
8545	priv->rxq->read = i;
8546	ipw_rx_queue_restock(priv);
8547}
8548
8549#define DEFAULT_RTS_THRESHOLD     2304U
8550#define MIN_RTS_THRESHOLD         1U
8551#define MAX_RTS_THRESHOLD         2304U
8552#define DEFAULT_BEACON_INTERVAL   100U
8553#define	DEFAULT_SHORT_RETRY_LIMIT 7U
8554#define	DEFAULT_LONG_RETRY_LIMIT  4U
8555
8556/**
8557 * ipw_sw_reset
8558 * @option: options to control different reset behaviour
8559 * 	    0 = reset everything except the 'disable' module_param
8560 * 	    1 = reset everything and print out driver info (for probe only)
8561 * 	    2 = reset everything
8562 */
8563static int ipw_sw_reset(struct ipw_priv *priv, int option)
8564{
8565	int band, modulation;
8566	int old_mode = priv->ieee->iw_mode;
8567
8568	/* Initialize module parameter values here */
8569	priv->config = 0;
8570
8571	/* We default to disabling the LED code as right now it causes
8572	 * too many systems to lock up... */
8573	if (!led_support)
8574		priv->config |= CFG_NO_LED;
8575
8576	if (associate)
8577		priv->config |= CFG_ASSOCIATE;
8578	else
8579		IPW_DEBUG_INFO("Auto associate disabled.\n");
8580
8581	if (auto_create)
8582		priv->config |= CFG_ADHOC_CREATE;
8583	else
8584		IPW_DEBUG_INFO("Auto adhoc creation disabled.\n");
8585
8586	priv->config &= ~CFG_STATIC_ESSID;
8587	priv->essid_len = 0;
8588	memset(priv->essid, 0, IW_ESSID_MAX_SIZE);
8589
8590	if (disable && option) {
8591		priv->status |= STATUS_RF_KILL_SW;
8592		IPW_DEBUG_INFO("Radio disabled.\n");
8593	}
8594
8595	if (default_channel != 0) {
8596		priv->config |= CFG_STATIC_CHANNEL;
8597		priv->channel = default_channel;
8598		IPW_DEBUG_INFO("Bind to static channel %d\n", default_channel);
8599		/* TODO: Validate that provided channel is in range */
8600	}
8601#ifdef CONFIG_IPW2200_QOS
8602	ipw_qos_init(priv, qos_enable, qos_burst_enable,
8603		     burst_duration_CCK, burst_duration_OFDM);
8604#endif				/* CONFIG_IPW2200_QOS */
8605
8606	switch (network_mode) {
8607	case 1:
8608		priv->ieee->iw_mode = IW_MODE_ADHOC;
8609		priv->net_dev->type = ARPHRD_ETHER;
8610
8611		break;
8612#ifdef CONFIG_IPW2200_MONITOR
8613	case 2:
8614		priv->ieee->iw_mode = IW_MODE_MONITOR;
8615#ifdef CONFIG_IPW2200_RADIOTAP
8616		priv->net_dev->type = ARPHRD_IEEE80211_RADIOTAP;
8617#else
8618		priv->net_dev->type = ARPHRD_IEEE80211;
8619#endif
8620		break;
8621#endif
8622	default:
8623	case 0:
8624		priv->net_dev->type = ARPHRD_ETHER;
8625		priv->ieee->iw_mode = IW_MODE_INFRA;
8626		break;
8627	}
8628
8629	if (hwcrypto) {
8630		priv->ieee->host_encrypt = 0;
8631		priv->ieee->host_encrypt_msdu = 0;
8632		priv->ieee->host_decrypt = 0;
8633		priv->ieee->host_mc_decrypt = 0;
8634	}
8635	IPW_DEBUG_INFO("Hardware crypto [%s]\n", hwcrypto ? "on" : "off");
8636
8637	/* IPW2200/2915 is abled to do hardware fragmentation. */
8638	priv->ieee->host_open_frag = 0;
8639
8640	if ((priv->pci_dev->device == 0x4223) ||
8641	    (priv->pci_dev->device == 0x4224)) {
8642		if (option == 1)
8643			printk(KERN_INFO DRV_NAME
8644			       ": Detected Intel PRO/Wireless 2915ABG Network "
8645			       "Connection\n");
8646		priv->ieee->abg_true = 1;
8647		band = LIBIPW_52GHZ_BAND | LIBIPW_24GHZ_BAND;
8648		modulation = LIBIPW_OFDM_MODULATION |
8649		    LIBIPW_CCK_MODULATION;
8650		priv->adapter = IPW_2915ABG;
8651		priv->ieee->mode = IEEE_A | IEEE_G | IEEE_B;
8652	} else {
8653		if (option == 1)
8654			printk(KERN_INFO DRV_NAME
8655			       ": Detected Intel PRO/Wireless 2200BG Network "
8656			       "Connection\n");
8657
8658		priv->ieee->abg_true = 0;
8659		band = LIBIPW_24GHZ_BAND;
8660		modulation = LIBIPW_OFDM_MODULATION |
8661		    LIBIPW_CCK_MODULATION;
8662		priv->adapter = IPW_2200BG;
8663		priv->ieee->mode = IEEE_G | IEEE_B;
8664	}
8665
8666	priv->ieee->freq_band = band;
8667	priv->ieee->modulation = modulation;
8668
8669	priv->rates_mask = LIBIPW_DEFAULT_RATES_MASK;
8670
8671	priv->disassociate_threshold = IPW_MB_DISASSOCIATE_THRESHOLD_DEFAULT;
8672	priv->roaming_threshold = IPW_MB_ROAMING_THRESHOLD_DEFAULT;
8673
8674	priv->rts_threshold = DEFAULT_RTS_THRESHOLD;
8675	priv->short_retry_limit = DEFAULT_SHORT_RETRY_LIMIT;
8676	priv->long_retry_limit = DEFAULT_LONG_RETRY_LIMIT;
8677
8678	/* If power management is turned on, default to AC mode */
8679	priv->power_mode = IPW_POWER_AC;
8680	priv->tx_power = IPW_TX_POWER_DEFAULT;
8681
8682	return old_mode == priv->ieee->iw_mode;
8683}
8684
8685/*
8686 * This file defines the Wireless Extension handlers.  It does not
8687 * define any methods of hardware manipulation and relies on the
8688 * functions defined in ipw_main to provide the HW interaction.
8689 *
8690 * The exception to this is the use of the ipw_get_ordinal()
8691 * function used to poll the hardware vs. making unecessary calls.
8692 *
8693 */
8694
8695static int ipw_set_channel(struct ipw_priv *priv, u8 channel)
8696{
8697	if (channel == 0) {
8698		IPW_DEBUG_INFO("Setting channel to ANY (0)\n");
8699		priv->config &= ~CFG_STATIC_CHANNEL;
8700		IPW_DEBUG_ASSOC("Attempting to associate with new "
8701				"parameters.\n");
8702		ipw_associate(priv);
8703		return 0;
8704	}
8705
8706	priv->config |= CFG_STATIC_CHANNEL;
8707
8708	if (priv->channel == channel) {
8709		IPW_DEBUG_INFO("Request to set channel to current value (%d)\n",
8710			       channel);
8711		return 0;
8712	}
8713
8714	IPW_DEBUG_INFO("Setting channel to %i\n", (int)channel);
8715	priv->channel = channel;
8716
8717#ifdef CONFIG_IPW2200_MONITOR
8718	if (priv->ieee->iw_mode == IW_MODE_MONITOR) {
8719		int i;
8720		if (priv->status & STATUS_SCANNING) {
8721			IPW_DEBUG_SCAN("Scan abort triggered due to "
8722				       "channel change.\n");
8723			ipw_abort_scan(priv);
8724		}
8725
8726		for (i = 1000; i && (priv->status & STATUS_SCANNING); i--)
8727			udelay(10);
8728
8729		if (priv->status & STATUS_SCANNING)
8730			IPW_DEBUG_SCAN("Still scanning...\n");
8731		else
8732			IPW_DEBUG_SCAN("Took %dms to abort current scan\n",
8733				       1000 - i);
8734
8735		return 0;
8736	}
8737#endif				/* CONFIG_IPW2200_MONITOR */
8738
8739	/* Network configuration changed -- force [re]association */
8740	IPW_DEBUG_ASSOC("[re]association triggered due to channel change.\n");
8741	if (!ipw_disassociate(priv))
8742		ipw_associate(priv);
8743
8744	return 0;
8745}
8746
8747static int ipw_wx_set_freq(struct net_device *dev,
8748			   struct iw_request_info *info,
8749			   union iwreq_data *wrqu, char *extra)
8750{
8751	struct ipw_priv *priv = libipw_priv(dev);
8752	const struct libipw_geo *geo = libipw_get_geo(priv->ieee);
8753	struct iw_freq *fwrq = &wrqu->freq;
8754	int ret = 0, i;
8755	u8 channel, flags;
8756	int band;
8757
8758	if (fwrq->m == 0) {
8759		IPW_DEBUG_WX("SET Freq/Channel -> any\n");
8760		mutex_lock(&priv->mutex);
8761		ret = ipw_set_channel(priv, 0);
8762		mutex_unlock(&priv->mutex);
8763		return ret;
8764	}
8765	/* if setting by freq convert to channel */
8766	if (fwrq->e == 1) {
8767		channel = libipw_freq_to_channel(priv->ieee, fwrq->m);
8768		if (channel == 0)
8769			return -EINVAL;
8770	} else
8771		channel = fwrq->m;
8772
8773	if (!(band = libipw_is_valid_channel(priv->ieee, channel)))
8774		return -EINVAL;
8775
8776	if (priv->ieee->iw_mode == IW_MODE_ADHOC) {
8777		i = libipw_channel_to_index(priv->ieee, channel);
8778		if (i == -1)
8779			return -EINVAL;
8780
8781		flags = (band == LIBIPW_24GHZ_BAND) ?
8782		    geo->bg[i].flags : geo->a[i].flags;
8783		if (flags & LIBIPW_CH_PASSIVE_ONLY) {
8784			IPW_DEBUG_WX("Invalid Ad-Hoc channel for 802.11a\n");
8785			return -EINVAL;
8786		}
8787	}
8788
8789	IPW_DEBUG_WX("SET Freq/Channel -> %d\n", fwrq->m);
8790	mutex_lock(&priv->mutex);
8791	ret = ipw_set_channel(priv, channel);
8792	mutex_unlock(&priv->mutex);
8793	return ret;
8794}
8795
8796static int ipw_wx_get_freq(struct net_device *dev,
8797			   struct iw_request_info *info,
8798			   union iwreq_data *wrqu, char *extra)
8799{
8800	struct ipw_priv *priv = libipw_priv(dev);
8801
8802	wrqu->freq.e = 0;
8803
8804	/* If we are associated, trying to associate, or have a statically
8805	 * configured CHANNEL then return that; otherwise return ANY */
8806	mutex_lock(&priv->mutex);
8807	if (priv->config & CFG_STATIC_CHANNEL ||
8808	    priv->status & (STATUS_ASSOCIATING | STATUS_ASSOCIATED)) {
8809		int i;
8810
8811		i = libipw_channel_to_index(priv->ieee, priv->channel);
8812		BUG_ON(i == -1);
8813		wrqu->freq.e = 1;
8814
8815		switch (libipw_is_valid_channel(priv->ieee, priv->channel)) {
8816		case LIBIPW_52GHZ_BAND:
8817			wrqu->freq.m = priv->ieee->geo.a[i].freq * 100000;
8818			break;
8819
8820		case LIBIPW_24GHZ_BAND:
8821			wrqu->freq.m = priv->ieee->geo.bg[i].freq * 100000;
8822			break;
8823
8824		default:
8825			BUG();
8826		}
8827	} else
8828		wrqu->freq.m = 0;
8829
8830	mutex_unlock(&priv->mutex);
8831	IPW_DEBUG_WX("GET Freq/Channel -> %d\n", priv->channel);
8832	return 0;
8833}
8834
8835static int ipw_wx_set_mode(struct net_device *dev,
8836			   struct iw_request_info *info,
8837			   union iwreq_data *wrqu, char *extra)
8838{
8839	struct ipw_priv *priv = libipw_priv(dev);
8840	int err = 0;
8841
8842	IPW_DEBUG_WX("Set MODE: %d\n", wrqu->mode);
8843
8844	switch (wrqu->mode) {
8845#ifdef CONFIG_IPW2200_MONITOR
8846	case IW_MODE_MONITOR:
8847#endif
8848	case IW_MODE_ADHOC:
8849	case IW_MODE_INFRA:
8850		break;
8851	case IW_MODE_AUTO:
8852		wrqu->mode = IW_MODE_INFRA;
8853		break;
8854	default:
8855		return -EINVAL;
8856	}
8857	if (wrqu->mode == priv->ieee->iw_mode)
8858		return 0;
8859
8860	mutex_lock(&priv->mutex);
8861
8862	ipw_sw_reset(priv, 0);
8863
8864#ifdef CONFIG_IPW2200_MONITOR
8865	if (priv->ieee->iw_mode == IW_MODE_MONITOR)
8866		priv->net_dev->type = ARPHRD_ETHER;
8867
8868	if (wrqu->mode == IW_MODE_MONITOR)
8869#ifdef CONFIG_IPW2200_RADIOTAP
8870		priv->net_dev->type = ARPHRD_IEEE80211_RADIOTAP;
8871#else
8872		priv->net_dev->type = ARPHRD_IEEE80211;
8873#endif
8874#endif				/* CONFIG_IPW2200_MONITOR */
8875
8876	/* Free the existing firmware and reset the fw_loaded
8877	 * flag so ipw_load() will bring in the new firmware */
8878	free_firmware();
8879
8880	priv->ieee->iw_mode = wrqu->mode;
8881
8882	queue_work(priv->workqueue, &priv->adapter_restart);
8883	mutex_unlock(&priv->mutex);
8884	return err;
8885}
8886
8887static int ipw_wx_get_mode(struct net_device *dev,
8888			   struct iw_request_info *info,
8889			   union iwreq_data *wrqu, char *extra)
8890{
8891	struct ipw_priv *priv = libipw_priv(dev);
8892	mutex_lock(&priv->mutex);
8893	wrqu->mode = priv->ieee->iw_mode;
8894	IPW_DEBUG_WX("Get MODE -> %d\n", wrqu->mode);
8895	mutex_unlock(&priv->mutex);
8896	return 0;
8897}
8898
8899/* Values are in microsecond */
8900static const s32 timeout_duration[] = {
8901	350000,
8902	250000,
8903	75000,
8904	37000,
8905	25000,
8906};
8907
8908static const s32 period_duration[] = {
8909	400000,
8910	700000,
8911	1000000,
8912	1000000,
8913	1000000
8914};
8915
8916static int ipw_wx_get_range(struct net_device *dev,
8917			    struct iw_request_info *info,
8918			    union iwreq_data *wrqu, char *extra)
8919{
8920	struct ipw_priv *priv = libipw_priv(dev);
8921	struct iw_range *range = (struct iw_range *)extra;
8922	const struct libipw_geo *geo = libipw_get_geo(priv->ieee);
8923	int i = 0, j;
8924
8925	wrqu->data.length = sizeof(*range);
8926	memset(range, 0, sizeof(*range));
8927
8928	/* 54Mbs == ~27 Mb/s real (802.11g) */
8929	range->throughput = 27 * 1000 * 1000;
8930
8931	range->max_qual.qual = 100;
8932	/* TODO: Find real max RSSI and stick here */
8933	range->max_qual.level = 0;
8934	range->max_qual.noise = 0;
8935	range->max_qual.updated = 7;	/* Updated all three */
8936
8937	range->avg_qual.qual = 70;
8938	/* TODO: Find real 'good' to 'bad' threshold value for RSSI */
8939	range->avg_qual.level = 0;
8940	range->avg_qual.noise = 0;
8941	range->avg_qual.updated = 7;	/* Updated all three */
8942	mutex_lock(&priv->mutex);
8943	range->num_bitrates = min(priv->rates.num_rates, (u8) IW_MAX_BITRATES);
8944
8945	for (i = 0; i < range->num_bitrates; i++)
8946		range->bitrate[i] = (priv->rates.supported_rates[i] & 0x7F) *
8947		    500000;
8948
8949	range->max_rts = DEFAULT_RTS_THRESHOLD;
8950	range->min_frag = MIN_FRAG_THRESHOLD;
8951	range->max_frag = MAX_FRAG_THRESHOLD;
8952
8953	range->encoding_size[0] = 5;
8954	range->encoding_size[1] = 13;
8955	range->num_encoding_sizes = 2;
8956	range->max_encoding_tokens = WEP_KEYS;
8957
8958	/* Set the Wireless Extension versions */
8959	range->we_version_compiled = WIRELESS_EXT;
8960	range->we_version_source = 18;
8961
8962	i = 0;
8963	if (priv->ieee->mode & (IEEE_B | IEEE_G)) {
8964		for (j = 0; j < geo->bg_channels && i < IW_MAX_FREQUENCIES; j++) {
8965			if ((priv->ieee->iw_mode == IW_MODE_ADHOC) &&
8966			    (geo->bg[j].flags & LIBIPW_CH_PASSIVE_ONLY))
8967				continue;
8968
8969			range->freq[i].i = geo->bg[j].channel;
8970			range->freq[i].m = geo->bg[j].freq * 100000;
8971			range->freq[i].e = 1;
8972			i++;
8973		}
8974	}
8975
8976	if (priv->ieee->mode & IEEE_A) {
8977		for (j = 0; j < geo->a_channels && i < IW_MAX_FREQUENCIES; j++) {
8978			if ((priv->ieee->iw_mode == IW_MODE_ADHOC) &&
8979			    (geo->a[j].flags & LIBIPW_CH_PASSIVE_ONLY))
8980				continue;
8981
8982			range->freq[i].i = geo->a[j].channel;
8983			range->freq[i].m = geo->a[j].freq * 100000;
8984			range->freq[i].e = 1;
8985			i++;
8986		}
8987	}
8988
8989	range->num_channels = i;
8990	range->num_frequency = i;
8991
8992	mutex_unlock(&priv->mutex);
8993
8994	/* Event capability (kernel + driver) */
8995	range->event_capa[0] = (IW_EVENT_CAPA_K_0 |
8996				IW_EVENT_CAPA_MASK(SIOCGIWTHRSPY) |
8997				IW_EVENT_CAPA_MASK(SIOCGIWAP) |
8998				IW_EVENT_CAPA_MASK(SIOCGIWSCAN));
8999	range->event_capa[1] = IW_EVENT_CAPA_K_1;
9000
9001	range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_WPA2 |
9002		IW_ENC_CAPA_CIPHER_TKIP | IW_ENC_CAPA_CIPHER_CCMP;
9003
9004	range->scan_capa = IW_SCAN_CAPA_ESSID | IW_SCAN_CAPA_TYPE;
9005
9006	IPW_DEBUG_WX("GET Range\n");
9007	return 0;
9008}
9009
9010static int ipw_wx_set_wap(struct net_device *dev,
9011			  struct iw_request_info *info,
9012			  union iwreq_data *wrqu, char *extra)
9013{
9014	struct ipw_priv *priv = libipw_priv(dev);
9015
9016	static const unsigned char any[] = {
9017		0xff, 0xff, 0xff, 0xff, 0xff, 0xff
9018	};
9019	static const unsigned char off[] = {
9020		0x00, 0x00, 0x00, 0x00, 0x00, 0x00
9021	};
9022
9023	if (wrqu->ap_addr.sa_family != ARPHRD_ETHER)
9024		return -EINVAL;
9025	mutex_lock(&priv->mutex);
9026	if (!memcmp(any, wrqu->ap_addr.sa_data, ETH_ALEN) ||
9027	    !memcmp(off, wrqu->ap_addr.sa_data, ETH_ALEN)) {
9028		/* we disable mandatory BSSID association */
9029		IPW_DEBUG_WX("Setting AP BSSID to ANY\n");
9030		priv->config &= ~CFG_STATIC_BSSID;
9031		IPW_DEBUG_ASSOC("Attempting to associate with new "
9032				"parameters.\n");
9033		ipw_associate(priv);
9034		mutex_unlock(&priv->mutex);
9035		return 0;
9036	}
9037
9038	priv->config |= CFG_STATIC_BSSID;
9039	if (!memcmp(priv->bssid, wrqu->ap_addr.sa_data, ETH_ALEN)) {
9040		IPW_DEBUG_WX("BSSID set to current BSSID.\n");
9041		mutex_unlock(&priv->mutex);
9042		return 0;
9043	}
9044
9045	IPW_DEBUG_WX("Setting mandatory BSSID to %pM\n",
9046		     wrqu->ap_addr.sa_data);
9047
9048	memcpy(priv->bssid, wrqu->ap_addr.sa_data, ETH_ALEN);
9049
9050	/* Network configuration changed -- force [re]association */
9051	IPW_DEBUG_ASSOC("[re]association triggered due to BSSID change.\n");
9052	if (!ipw_disassociate(priv))
9053		ipw_associate(priv);
9054
9055	mutex_unlock(&priv->mutex);
9056	return 0;
9057}
9058
9059static int ipw_wx_get_wap(struct net_device *dev,
9060			  struct iw_request_info *info,
9061			  union iwreq_data *wrqu, char *extra)
9062{
9063	struct ipw_priv *priv = libipw_priv(dev);
9064
9065	/* If we are associated, trying to associate, or have a statically
9066	 * configured BSSID then return that; otherwise return ANY */
9067	mutex_lock(&priv->mutex);
9068	if (priv->config & CFG_STATIC_BSSID ||
9069	    priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
9070		wrqu->ap_addr.sa_family = ARPHRD_ETHER;
9071		memcpy(wrqu->ap_addr.sa_data, priv->bssid, ETH_ALEN);
9072	} else
9073		memset(wrqu->ap_addr.sa_data, 0, ETH_ALEN);
9074
9075	IPW_DEBUG_WX("Getting WAP BSSID: %pM\n",
9076		     wrqu->ap_addr.sa_data);
9077	mutex_unlock(&priv->mutex);
9078	return 0;
9079}
9080
9081static int ipw_wx_set_essid(struct net_device *dev,
9082			    struct iw_request_info *info,
9083			    union iwreq_data *wrqu, char *extra)
9084{
9085	struct ipw_priv *priv = libipw_priv(dev);
9086        int length;
9087	DECLARE_SSID_BUF(ssid);
9088
9089        mutex_lock(&priv->mutex);
9090
9091        if (!wrqu->essid.flags)
9092        {
9093                IPW_DEBUG_WX("Setting ESSID to ANY\n");
9094                ipw_disassociate(priv);
9095                priv->config &= ~CFG_STATIC_ESSID;
9096                ipw_associate(priv);
9097                mutex_unlock(&priv->mutex);
9098                return 0;
9099        }
9100
9101	length = min((int)wrqu->essid.length, IW_ESSID_MAX_SIZE);
9102
9103	priv->config |= CFG_STATIC_ESSID;
9104
9105	if (priv->essid_len == length && !memcmp(priv->essid, extra, length)
9106	    && (priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING))) {
9107		IPW_DEBUG_WX("ESSID set to current ESSID.\n");
9108		mutex_unlock(&priv->mutex);
9109		return 0;
9110	}
9111
9112	IPW_DEBUG_WX("Setting ESSID: '%s' (%d)\n",
9113		     print_ssid(ssid, extra, length), length);
9114
9115	priv->essid_len = length;
9116	memcpy(priv->essid, extra, priv->essid_len);
9117
9118	/* Network configuration changed -- force [re]association */
9119	IPW_DEBUG_ASSOC("[re]association triggered due to ESSID change.\n");
9120	if (!ipw_disassociate(priv))
9121		ipw_associate(priv);
9122
9123	mutex_unlock(&priv->mutex);
9124	return 0;
9125}
9126
9127static int ipw_wx_get_essid(struct net_device *dev,
9128			    struct iw_request_info *info,
9129			    union iwreq_data *wrqu, char *extra)
9130{
9131	struct ipw_priv *priv = libipw_priv(dev);
9132	DECLARE_SSID_BUF(ssid);
9133
9134	/* If we are associated, trying to associate, or have a statically
9135	 * configured ESSID then return that; otherwise return ANY */
9136	mutex_lock(&priv->mutex);
9137	if (priv->config & CFG_STATIC_ESSID ||
9138	    priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)) {
9139		IPW_DEBUG_WX("Getting essid: '%s'\n",
9140			     print_ssid(ssid, priv->essid, priv->essid_len));
9141		memcpy(extra, priv->essid, priv->essid_len);
9142		wrqu->essid.length = priv->essid_len;
9143		wrqu->essid.flags = 1;	/* active */
9144	} else {
9145		IPW_DEBUG_WX("Getting essid: ANY\n");
9146		wrqu->essid.length = 0;
9147		wrqu->essid.flags = 0;	/* active */
9148	}
9149	mutex_unlock(&priv->mutex);
9150	return 0;
9151}
9152
9153static int ipw_wx_set_nick(struct net_device *dev,
9154			   struct iw_request_info *info,
9155			   union iwreq_data *wrqu, char *extra)
9156{
9157	struct ipw_priv *priv = libipw_priv(dev);
9158
9159	IPW_DEBUG_WX("Setting nick to '%s'\n", extra);
9160	if (wrqu->data.length > IW_ESSID_MAX_SIZE)
9161		return -E2BIG;
9162	mutex_lock(&priv->mutex);
9163	wrqu->data.length = min((size_t) wrqu->data.length, sizeof(priv->nick));
9164	memset(priv->nick, 0, sizeof(priv->nick));
9165	memcpy(priv->nick, extra, wrqu->data.length);
9166	IPW_DEBUG_TRACE("<<\n");
9167	mutex_unlock(&priv->mutex);
9168	return 0;
9169
9170}
9171
9172static int ipw_wx_get_nick(struct net_device *dev,
9173			   struct iw_request_info *info,
9174			   union iwreq_data *wrqu, char *extra)
9175{
9176	struct ipw_priv *priv = libipw_priv(dev);
9177	IPW_DEBUG_WX("Getting nick\n");
9178	mutex_lock(&priv->mutex);
9179	wrqu->data.length = strlen(priv->nick);
9180	memcpy(extra, priv->nick, wrqu->data.length);
9181	wrqu->data.flags = 1;	/* active */
9182	mutex_unlock(&priv->mutex);
9183	return 0;
9184}
9185
9186static int ipw_wx_set_sens(struct net_device *dev,
9187			    struct iw_request_info *info,
9188			    union iwreq_data *wrqu, char *extra)
9189{
9190	struct ipw_priv *priv = libipw_priv(dev);
9191	int err = 0;
9192
9193	IPW_DEBUG_WX("Setting roaming threshold to %d\n", wrqu->sens.value);
9194	IPW_DEBUG_WX("Setting disassociate threshold to %d\n", 3*wrqu->sens.value);
9195	mutex_lock(&priv->mutex);
9196
9197	if (wrqu->sens.fixed == 0)
9198	{
9199		priv->roaming_threshold = IPW_MB_ROAMING_THRESHOLD_DEFAULT;
9200		priv->disassociate_threshold = IPW_MB_DISASSOCIATE_THRESHOLD_DEFAULT;
9201		goto out;
9202	}
9203	if ((wrqu->sens.value > IPW_MB_ROAMING_THRESHOLD_MAX) ||
9204	    (wrqu->sens.value < IPW_MB_ROAMING_THRESHOLD_MIN)) {
9205		err = -EINVAL;
9206		goto out;
9207	}
9208
9209	priv->roaming_threshold = wrqu->sens.value;
9210	priv->disassociate_threshold = 3*wrqu->sens.value;
9211      out:
9212	mutex_unlock(&priv->mutex);
9213	return err;
9214}
9215
9216static int ipw_wx_get_sens(struct net_device *dev,
9217			    struct iw_request_info *info,
9218			    union iwreq_data *wrqu, char *extra)
9219{
9220	struct ipw_priv *priv = libipw_priv(dev);
9221	mutex_lock(&priv->mutex);
9222	wrqu->sens.fixed = 1;
9223	wrqu->sens.value = priv->roaming_threshold;
9224	mutex_unlock(&priv->mutex);
9225
9226	IPW_DEBUG_WX("GET roaming threshold -> %s %d\n",
9227		     wrqu->power.disabled ? "OFF" : "ON", wrqu->power.value);
9228
9229	return 0;
9230}
9231
9232static int ipw_wx_set_rate(struct net_device *dev,
9233			   struct iw_request_info *info,
9234			   union iwreq_data *wrqu, char *extra)
9235{
9236	/* TODO: We should use semaphores or locks for access to priv */
9237	struct ipw_priv *priv = libipw_priv(dev);
9238	u32 target_rate = wrqu->bitrate.value;
9239	u32 fixed, mask;
9240
9241	/* value = -1, fixed = 0 means auto only, so we should use all rates offered by AP */
9242	/* value = X, fixed = 1 means only rate X */
9243	/* value = X, fixed = 0 means all rates lower equal X */
9244
9245	if (target_rate == -1) {
9246		fixed = 0;
9247		mask = LIBIPW_DEFAULT_RATES_MASK;
9248		/* Now we should reassociate */
9249		goto apply;
9250	}
9251
9252	mask = 0;
9253	fixed = wrqu->bitrate.fixed;
9254
9255	if (target_rate == 1000000 || !fixed)
9256		mask |= LIBIPW_CCK_RATE_1MB_MASK;
9257	if (target_rate == 1000000)
9258		goto apply;
9259
9260	if (target_rate == 2000000 || !fixed)
9261		mask |= LIBIPW_CCK_RATE_2MB_MASK;
9262	if (target_rate == 2000000)
9263		goto apply;
9264
9265	if (target_rate == 5500000 || !fixed)
9266		mask |= LIBIPW_CCK_RATE_5MB_MASK;
9267	if (target_rate == 5500000)
9268		goto apply;
9269
9270	if (target_rate == 6000000 || !fixed)
9271		mask |= LIBIPW_OFDM_RATE_6MB_MASK;
9272	if (target_rate == 6000000)
9273		goto apply;
9274
9275	if (target_rate == 9000000 || !fixed)
9276		mask |= LIBIPW_OFDM_RATE_9MB_MASK;
9277	if (target_rate == 9000000)
9278		goto apply;
9279
9280	if (target_rate == 11000000 || !fixed)
9281		mask |= LIBIPW_CCK_RATE_11MB_MASK;
9282	if (target_rate == 11000000)
9283		goto apply;
9284
9285	if (target_rate == 12000000 || !fixed)
9286		mask |= LIBIPW_OFDM_RATE_12MB_MASK;
9287	if (target_rate == 12000000)
9288		goto apply;
9289
9290	if (target_rate == 18000000 || !fixed)
9291		mask |= LIBIPW_OFDM_RATE_18MB_MASK;
9292	if (target_rate == 18000000)
9293		goto apply;
9294
9295	if (target_rate == 24000000 || !fixed)
9296		mask |= LIBIPW_OFDM_RATE_24MB_MASK;
9297	if (target_rate == 24000000)
9298		goto apply;
9299
9300	if (target_rate == 36000000 || !fixed)
9301		mask |= LIBIPW_OFDM_RATE_36MB_MASK;
9302	if (target_rate == 36000000)
9303		goto apply;
9304
9305	if (target_rate == 48000000 || !fixed)
9306		mask |= LIBIPW_OFDM_RATE_48MB_MASK;
9307	if (target_rate == 48000000)
9308		goto apply;
9309
9310	if (target_rate == 54000000 || !fixed)
9311		mask |= LIBIPW_OFDM_RATE_54MB_MASK;
9312	if (target_rate == 54000000)
9313		goto apply;
9314
9315	IPW_DEBUG_WX("invalid rate specified, returning error\n");
9316	return -EINVAL;
9317
9318      apply:
9319	IPW_DEBUG_WX("Setting rate mask to 0x%08X [%s]\n",
9320		     mask, fixed ? "fixed" : "sub-rates");
9321	mutex_lock(&priv->mutex);
9322	if (mask == LIBIPW_DEFAULT_RATES_MASK) {
9323		priv->config &= ~CFG_FIXED_RATE;
9324		ipw_set_fixed_rate(priv, priv->ieee->mode);
9325	} else
9326		priv->config |= CFG_FIXED_RATE;
9327
9328	if (priv->rates_mask == mask) {
9329		IPW_DEBUG_WX("Mask set to current mask.\n");
9330		mutex_unlock(&priv->mutex);
9331		return 0;
9332	}
9333
9334	priv->rates_mask = mask;
9335
9336	/* Network configuration changed -- force [re]association */
9337	IPW_DEBUG_ASSOC("[re]association triggered due to rates change.\n");
9338	if (!ipw_disassociate(priv))
9339		ipw_associate(priv);
9340
9341	mutex_unlock(&priv->mutex);
9342	return 0;
9343}
9344
9345static int ipw_wx_get_rate(struct net_device *dev,
9346			   struct iw_request_info *info,
9347			   union iwreq_data *wrqu, char *extra)
9348{
9349	struct ipw_priv *priv = libipw_priv(dev);
9350	mutex_lock(&priv->mutex);
9351	wrqu->bitrate.value = priv->last_rate;
9352	wrqu->bitrate.fixed = (priv->config & CFG_FIXED_RATE) ? 1 : 0;
9353	mutex_unlock(&priv->mutex);
9354	IPW_DEBUG_WX("GET Rate -> %d\n", wrqu->bitrate.value);
9355	return 0;
9356}
9357
9358static int ipw_wx_set_rts(struct net_device *dev,
9359			  struct iw_request_info *info,
9360			  union iwreq_data *wrqu, char *extra)
9361{
9362	struct ipw_priv *priv = libipw_priv(dev);
9363	mutex_lock(&priv->mutex);
9364	if (wrqu->rts.disabled || !wrqu->rts.fixed)
9365		priv->rts_threshold = DEFAULT_RTS_THRESHOLD;
9366	else {
9367		if (wrqu->rts.value < MIN_RTS_THRESHOLD ||
9368		    wrqu->rts.value > MAX_RTS_THRESHOLD) {
9369			mutex_unlock(&priv->mutex);
9370			return -EINVAL;
9371		}
9372		priv->rts_threshold = wrqu->rts.value;
9373	}
9374
9375	ipw_send_rts_threshold(priv, priv->rts_threshold);
9376	mutex_unlock(&priv->mutex);
9377	IPW_DEBUG_WX("SET RTS Threshold -> %d\n", priv->rts_threshold);
9378	return 0;
9379}
9380
9381static int ipw_wx_get_rts(struct net_device *dev,
9382			  struct iw_request_info *info,
9383			  union iwreq_data *wrqu, char *extra)
9384{
9385	struct ipw_priv *priv = libipw_priv(dev);
9386	mutex_lock(&priv->mutex);
9387	wrqu->rts.value = priv->rts_threshold;
9388	wrqu->rts.fixed = 0;	/* no auto select */
9389	wrqu->rts.disabled = (wrqu->rts.value == DEFAULT_RTS_THRESHOLD);
9390	mutex_unlock(&priv->mutex);
9391	IPW_DEBUG_WX("GET RTS Threshold -> %d\n", wrqu->rts.value);
9392	return 0;
9393}
9394
9395static int ipw_wx_set_txpow(struct net_device *dev,
9396			    struct iw_request_info *info,
9397			    union iwreq_data *wrqu, char *extra)
9398{
9399	struct ipw_priv *priv = libipw_priv(dev);
9400	int err = 0;
9401
9402	mutex_lock(&priv->mutex);
9403	if (ipw_radio_kill_sw(priv, wrqu->power.disabled)) {
9404		err = -EINPROGRESS;
9405		goto out;
9406	}
9407
9408	if (!wrqu->power.fixed)
9409		wrqu->power.value = IPW_TX_POWER_DEFAULT;
9410
9411	if (wrqu->power.flags != IW_TXPOW_DBM) {
9412		err = -EINVAL;
9413		goto out;
9414	}
9415
9416	if ((wrqu->power.value > IPW_TX_POWER_MAX) ||
9417	    (wrqu->power.value < IPW_TX_POWER_MIN)) {
9418		err = -EINVAL;
9419		goto out;
9420	}
9421
9422	priv->tx_power = wrqu->power.value;
9423	err = ipw_set_tx_power(priv);
9424      out:
9425	mutex_unlock(&priv->mutex);
9426	return err;
9427}
9428
9429static int ipw_wx_get_txpow(struct net_device *dev,
9430			    struct iw_request_info *info,
9431			    union iwreq_data *wrqu, char *extra)
9432{
9433	struct ipw_priv *priv = libipw_priv(dev);
9434	mutex_lock(&priv->mutex);
9435	wrqu->power.value = priv->tx_power;
9436	wrqu->power.fixed = 1;
9437	wrqu->power.flags = IW_TXPOW_DBM;
9438	wrqu->power.disabled = (priv->status & STATUS_RF_KILL_MASK) ? 1 : 0;
9439	mutex_unlock(&priv->mutex);
9440
9441	IPW_DEBUG_WX("GET TX Power -> %s %d\n",
9442		     wrqu->power.disabled ? "OFF" : "ON", wrqu->power.value);
9443
9444	return 0;
9445}
9446
9447static int ipw_wx_set_frag(struct net_device *dev,
9448			   struct iw_request_info *info,
9449			   union iwreq_data *wrqu, char *extra)
9450{
9451	struct ipw_priv *priv = libipw_priv(dev);
9452	mutex_lock(&priv->mutex);
9453	if (wrqu->frag.disabled || !wrqu->frag.fixed)
9454		priv->ieee->fts = DEFAULT_FTS;
9455	else {
9456		if (wrqu->frag.value < MIN_FRAG_THRESHOLD ||
9457		    wrqu->frag.value > MAX_FRAG_THRESHOLD) {
9458			mutex_unlock(&priv->mutex);
9459			return -EINVAL;
9460		}
9461
9462		priv->ieee->fts = wrqu->frag.value & ~0x1;
9463	}
9464
9465	ipw_send_frag_threshold(priv, wrqu->frag.value);
9466	mutex_unlock(&priv->mutex);
9467	IPW_DEBUG_WX("SET Frag Threshold -> %d\n", wrqu->frag.value);
9468	return 0;
9469}
9470
9471static int ipw_wx_get_frag(struct net_device *dev,
9472			   struct iw_request_info *info,
9473			   union iwreq_data *wrqu, char *extra)
9474{
9475	struct ipw_priv *priv = libipw_priv(dev);
9476	mutex_lock(&priv->mutex);
9477	wrqu->frag.value = priv->ieee->fts;
9478	wrqu->frag.fixed = 0;	/* no auto select */
9479	wrqu->frag.disabled = (wrqu->frag.value == DEFAULT_FTS);
9480	mutex_unlock(&priv->mutex);
9481	IPW_DEBUG_WX("GET Frag Threshold -> %d\n", wrqu->frag.value);
9482
9483	return 0;
9484}
9485
9486static int ipw_wx_set_retry(struct net_device *dev,
9487			    struct iw_request_info *info,
9488			    union iwreq_data *wrqu, char *extra)
9489{
9490	struct ipw_priv *priv = libipw_priv(dev);
9491
9492	if (wrqu->retry.flags & IW_RETRY_LIFETIME || wrqu->retry.disabled)
9493		return -EINVAL;
9494
9495	if (!(wrqu->retry.flags & IW_RETRY_LIMIT))
9496		return 0;
9497
9498	if (wrqu->retry.value < 0 || wrqu->retry.value >= 255)
9499		return -EINVAL;
9500
9501	mutex_lock(&priv->mutex);
9502	if (wrqu->retry.flags & IW_RETRY_SHORT)
9503		priv->short_retry_limit = (u8) wrqu->retry.value;
9504	else if (wrqu->retry.flags & IW_RETRY_LONG)
9505		priv->long_retry_limit = (u8) wrqu->retry.value;
9506	else {
9507		priv->short_retry_limit = (u8) wrqu->retry.value;
9508		priv->long_retry_limit = (u8) wrqu->retry.value;
9509	}
9510
9511	ipw_send_retry_limit(priv, priv->short_retry_limit,
9512			     priv->long_retry_limit);
9513	mutex_unlock(&priv->mutex);
9514	IPW_DEBUG_WX("SET retry limit -> short:%d long:%d\n",
9515		     priv->short_retry_limit, priv->long_retry_limit);
9516	return 0;
9517}
9518
9519static int ipw_wx_get_retry(struct net_device *dev,
9520			    struct iw_request_info *info,
9521			    union iwreq_data *wrqu, char *extra)
9522{
9523	struct ipw_priv *priv = libipw_priv(dev);
9524
9525	mutex_lock(&priv->mutex);
9526	wrqu->retry.disabled = 0;
9527
9528	if ((wrqu->retry.flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME) {
9529		mutex_unlock(&priv->mutex);
9530		return -EINVAL;
9531	}
9532
9533	if (wrqu->retry.flags & IW_RETRY_LONG) {
9534		wrqu->retry.flags = IW_RETRY_LIMIT | IW_RETRY_LONG;
9535		wrqu->retry.value = priv->long_retry_limit;
9536	} else if (wrqu->retry.flags & IW_RETRY_SHORT) {
9537		wrqu->retry.flags = IW_RETRY_LIMIT | IW_RETRY_SHORT;
9538		wrqu->retry.value = priv->short_retry_limit;
9539	} else {
9540		wrqu->retry.flags = IW_RETRY_LIMIT;
9541		wrqu->retry.value = priv->short_retry_limit;
9542	}
9543	mutex_unlock(&priv->mutex);
9544
9545	IPW_DEBUG_WX("GET retry -> %d\n", wrqu->retry.value);
9546
9547	return 0;
9548}
9549
9550static int ipw_wx_set_scan(struct net_device *dev,
9551			   struct iw_request_info *info,
9552			   union iwreq_data *wrqu, char *extra)
9553{
9554	struct ipw_priv *priv = libipw_priv(dev);
9555	struct iw_scan_req *req = (struct iw_scan_req *)extra;
9556	struct delayed_work *work = NULL;
9557
9558	mutex_lock(&priv->mutex);
9559
9560	priv->user_requested_scan = 1;
9561
9562	if (wrqu->data.length == sizeof(struct iw_scan_req)) {
9563		if (wrqu->data.flags & IW_SCAN_THIS_ESSID) {
9564			int len = min((int)req->essid_len,
9565			              (int)sizeof(priv->direct_scan_ssid));
9566			memcpy(priv->direct_scan_ssid, req->essid, len);
9567			priv->direct_scan_ssid_len = len;
9568			work = &priv->request_direct_scan;
9569		} else if (req->scan_type == IW_SCAN_TYPE_PASSIVE) {
9570			work = &priv->request_passive_scan;
9571		}
9572	} else {
9573		/* Normal active broadcast scan */
9574		work = &priv->request_scan;
9575	}
9576
9577	mutex_unlock(&priv->mutex);
9578
9579	IPW_DEBUG_WX("Start scan\n");
9580
9581	queue_delayed_work(priv->workqueue, work, 0);
9582
9583	return 0;
9584}
9585
9586static int ipw_wx_get_scan(struct net_device *dev,
9587			   struct iw_request_info *info,
9588			   union iwreq_data *wrqu, char *extra)
9589{
9590	struct ipw_priv *priv = libipw_priv(dev);
9591	return libipw_wx_get_scan(priv->ieee, info, wrqu, extra);
9592}
9593
9594static int ipw_wx_set_encode(struct net_device *dev,
9595			     struct iw_request_info *info,
9596			     union iwreq_data *wrqu, char *key)
9597{
9598	struct ipw_priv *priv = libipw_priv(dev);
9599	int ret;
9600	u32 cap = priv->capability;
9601
9602	mutex_lock(&priv->mutex);
9603	ret = libipw_wx_set_encode(priv->ieee, info, wrqu, key);
9604
9605	/* In IBSS mode, we need to notify the firmware to update
9606	 * the beacon info after we changed the capability. */
9607	if (cap != priv->capability &&
9608	    priv->ieee->iw_mode == IW_MODE_ADHOC &&
9609	    priv->status & STATUS_ASSOCIATED)
9610		ipw_disassociate(priv);
9611
9612	mutex_unlock(&priv->mutex);
9613	return ret;
9614}
9615
9616static int ipw_wx_get_encode(struct net_device *dev,
9617			     struct iw_request_info *info,
9618			     union iwreq_data *wrqu, char *key)
9619{
9620	struct ipw_priv *priv = libipw_priv(dev);
9621	return libipw_wx_get_encode(priv->ieee, info, wrqu, key);
9622}
9623
9624static int ipw_wx_set_power(struct net_device *dev,
9625			    struct iw_request_info *info,
9626			    union iwreq_data *wrqu, char *extra)
9627{
9628	struct ipw_priv *priv = libipw_priv(dev);
9629	int err;
9630	mutex_lock(&priv->mutex);
9631	if (wrqu->power.disabled) {
9632		priv->power_mode = IPW_POWER_LEVEL(priv->power_mode);
9633		err = ipw_send_power_mode(priv, IPW_POWER_MODE_CAM);
9634		if (err) {
9635			IPW_DEBUG_WX("failed setting power mode.\n");
9636			mutex_unlock(&priv->mutex);
9637			return err;
9638		}
9639		IPW_DEBUG_WX("SET Power Management Mode -> off\n");
9640		mutex_unlock(&priv->mutex);
9641		return 0;
9642	}
9643
9644	switch (wrqu->power.flags & IW_POWER_MODE) {
9645	case IW_POWER_ON:	/* If not specified */
9646	case IW_POWER_MODE:	/* If set all mask */
9647	case IW_POWER_ALL_R:	/* If explicitly state all */
9648		break;
9649	default:		/* Otherwise we don't support it */
9650		IPW_DEBUG_WX("SET PM Mode: %X not supported.\n",
9651			     wrqu->power.flags);
9652		mutex_unlock(&priv->mutex);
9653		return -EOPNOTSUPP;
9654	}
9655
9656	/* If the user hasn't specified a power management mode yet, default
9657	 * to BATTERY */
9658	if (IPW_POWER_LEVEL(priv->power_mode) == IPW_POWER_AC)
9659		priv->power_mode = IPW_POWER_ENABLED | IPW_POWER_BATTERY;
9660	else
9661		priv->power_mode = IPW_POWER_ENABLED | priv->power_mode;
9662
9663	err = ipw_send_power_mode(priv, IPW_POWER_LEVEL(priv->power_mode));
9664	if (err) {
9665		IPW_DEBUG_WX("failed setting power mode.\n");
9666		mutex_unlock(&priv->mutex);
9667		return err;
9668	}
9669
9670	IPW_DEBUG_WX("SET Power Management Mode -> 0x%02X\n", priv->power_mode);
9671	mutex_unlock(&priv->mutex);
9672	return 0;
9673}
9674
9675static int ipw_wx_get_power(struct net_device *dev,
9676			    struct iw_request_info *info,
9677			    union iwreq_data *wrqu, char *extra)
9678{
9679	struct ipw_priv *priv = libipw_priv(dev);
9680	mutex_lock(&priv->mutex);
9681	if (!(priv->power_mode & IPW_POWER_ENABLED))
9682		wrqu->power.disabled = 1;
9683	else
9684		wrqu->power.disabled = 0;
9685
9686	mutex_unlock(&priv->mutex);
9687	IPW_DEBUG_WX("GET Power Management Mode -> %02X\n", priv->power_mode);
9688
9689	return 0;
9690}
9691
9692static int ipw_wx_set_powermode(struct net_device *dev,
9693				struct iw_request_info *info,
9694				union iwreq_data *wrqu, char *extra)
9695{
9696	struct ipw_priv *priv = libipw_priv(dev);
9697	int mode = *(int *)extra;
9698	int err;
9699
9700	mutex_lock(&priv->mutex);
9701	if ((mode < 1) || (mode > IPW_POWER_LIMIT))
9702		mode = IPW_POWER_AC;
9703
9704	if (IPW_POWER_LEVEL(priv->power_mode) != mode) {
9705		err = ipw_send_power_mode(priv, mode);
9706		if (err) {
9707			IPW_DEBUG_WX("failed setting power mode.\n");
9708			mutex_unlock(&priv->mutex);
9709			return err;
9710		}
9711		priv->power_mode = IPW_POWER_ENABLED | mode;
9712	}
9713	mutex_unlock(&priv->mutex);
9714	return 0;
9715}
9716
9717#define MAX_WX_STRING 80
9718static int ipw_wx_get_powermode(struct net_device *dev,
9719				struct iw_request_info *info,
9720				union iwreq_data *wrqu, char *extra)
9721{
9722	struct ipw_priv *priv = libipw_priv(dev);
9723	int level = IPW_POWER_LEVEL(priv->power_mode);
9724	char *p = extra;
9725
9726	p += snprintf(p, MAX_WX_STRING, "Power save level: %d ", level);
9727
9728	switch (level) {
9729	case IPW_POWER_AC:
9730		p += snprintf(p, MAX_WX_STRING - (p - extra), "(AC)");
9731		break;
9732	case IPW_POWER_BATTERY:
9733		p += snprintf(p, MAX_WX_STRING - (p - extra), "(BATTERY)");
9734		break;
9735	default:
9736		p += snprintf(p, MAX_WX_STRING - (p - extra),
9737			      "(Timeout %dms, Period %dms)",
9738			      timeout_duration[level - 1] / 1000,
9739			      period_duration[level - 1] / 1000);
9740	}
9741
9742	if (!(priv->power_mode & IPW_POWER_ENABLED))
9743		p += snprintf(p, MAX_WX_STRING - (p - extra), " OFF");
9744
9745	wrqu->data.length = p - extra + 1;
9746
9747	return 0;
9748}
9749
9750static int ipw_wx_set_wireless_mode(struct net_device *dev,
9751				    struct iw_request_info *info,
9752				    union iwreq_data *wrqu, char *extra)
9753{
9754	struct ipw_priv *priv = libipw_priv(dev);
9755	int mode = *(int *)extra;
9756	u8 band = 0, modulation = 0;
9757
9758	if (mode == 0 || mode & ~IEEE_MODE_MASK) {
9759		IPW_WARNING("Attempt to set invalid wireless mode: %d\n", mode);
9760		return -EINVAL;
9761	}
9762	mutex_lock(&priv->mutex);
9763	if (priv->adapter == IPW_2915ABG) {
9764		priv->ieee->abg_true = 1;
9765		if (mode & IEEE_A) {
9766			band |= LIBIPW_52GHZ_BAND;
9767			modulation |= LIBIPW_OFDM_MODULATION;
9768		} else
9769			priv->ieee->abg_true = 0;
9770	} else {
9771		if (mode & IEEE_A) {
9772			IPW_WARNING("Attempt to set 2200BG into "
9773				    "802.11a mode\n");
9774			mutex_unlock(&priv->mutex);
9775			return -EINVAL;
9776		}
9777
9778		priv->ieee->abg_true = 0;
9779	}
9780
9781	if (mode & IEEE_B) {
9782		band |= LIBIPW_24GHZ_BAND;
9783		modulation |= LIBIPW_CCK_MODULATION;
9784	} else
9785		priv->ieee->abg_true = 0;
9786
9787	if (mode & IEEE_G) {
9788		band |= LIBIPW_24GHZ_BAND;
9789		modulation |= LIBIPW_OFDM_MODULATION;
9790	} else
9791		priv->ieee->abg_true = 0;
9792
9793	priv->ieee->mode = mode;
9794	priv->ieee->freq_band = band;
9795	priv->ieee->modulation = modulation;
9796	init_supported_rates(priv, &priv->rates);
9797
9798	/* Network configuration changed -- force [re]association */
9799	IPW_DEBUG_ASSOC("[re]association triggered due to mode change.\n");
9800	if (!ipw_disassociate(priv)) {
9801		ipw_send_supported_rates(priv, &priv->rates);
9802		ipw_associate(priv);
9803	}
9804
9805	/* Update the band LEDs */
9806	ipw_led_band_on(priv);
9807
9808	IPW_DEBUG_WX("PRIV SET MODE: %c%c%c\n",
9809		     mode & IEEE_A ? 'a' : '.',
9810		     mode & IEEE_B ? 'b' : '.', mode & IEEE_G ? 'g' : '.');
9811	mutex_unlock(&priv->mutex);
9812	return 0;
9813}
9814
9815static int ipw_wx_get_wireless_mode(struct net_device *dev,
9816				    struct iw_request_info *info,
9817				    union iwreq_data *wrqu, char *extra)
9818{
9819	struct ipw_priv *priv = libipw_priv(dev);
9820	mutex_lock(&priv->mutex);
9821	switch (priv->ieee->mode) {
9822	case IEEE_A:
9823		strncpy(extra, "802.11a (1)", MAX_WX_STRING);
9824		break;
9825	case IEEE_B:
9826		strncpy(extra, "802.11b (2)", MAX_WX_STRING);
9827		break;
9828	case IEEE_A | IEEE_B:
9829		strncpy(extra, "802.11ab (3)", MAX_WX_STRING);
9830		break;
9831	case IEEE_G:
9832		strncpy(extra, "802.11g (4)", MAX_WX_STRING);
9833		break;
9834	case IEEE_A | IEEE_G:
9835		strncpy(extra, "802.11ag (5)", MAX_WX_STRING);
9836		break;
9837	case IEEE_B | IEEE_G:
9838		strncpy(extra, "802.11bg (6)", MAX_WX_STRING);
9839		break;
9840	case IEEE_A | IEEE_B | IEEE_G:
9841		strncpy(extra, "802.11abg (7)", MAX_WX_STRING);
9842		break;
9843	default:
9844		strncpy(extra, "unknown", MAX_WX_STRING);
9845		break;
9846	}
9847
9848	IPW_DEBUG_WX("PRIV GET MODE: %s\n", extra);
9849
9850	wrqu->data.length = strlen(extra) + 1;
9851	mutex_unlock(&priv->mutex);
9852
9853	return 0;
9854}
9855
9856static int ipw_wx_set_preamble(struct net_device *dev,
9857			       struct iw_request_info *info,
9858			       union iwreq_data *wrqu, char *extra)
9859{
9860	struct ipw_priv *priv = libipw_priv(dev);
9861	int mode = *(int *)extra;
9862	mutex_lock(&priv->mutex);
9863	/* Switching from SHORT -> LONG requires a disassociation */
9864	if (mode == 1) {
9865		if (!(priv->config & CFG_PREAMBLE_LONG)) {
9866			priv->config |= CFG_PREAMBLE_LONG;
9867
9868			/* Network configuration changed -- force [re]association */
9869			IPW_DEBUG_ASSOC
9870			    ("[re]association triggered due to preamble change.\n");
9871			if (!ipw_disassociate(priv))
9872				ipw_associate(priv);
9873		}
9874		goto done;
9875	}
9876
9877	if (mode == 0) {
9878		priv->config &= ~CFG_PREAMBLE_LONG;
9879		goto done;
9880	}
9881	mutex_unlock(&priv->mutex);
9882	return -EINVAL;
9883
9884      done:
9885	mutex_unlock(&priv->mutex);
9886	return 0;
9887}
9888
9889static int ipw_wx_get_preamble(struct net_device *dev,
9890			       struct iw_request_info *info,
9891			       union iwreq_data *wrqu, char *extra)
9892{
9893	struct ipw_priv *priv = libipw_priv(dev);
9894	mutex_lock(&priv->mutex);
9895	if (priv->config & CFG_PREAMBLE_LONG)
9896		snprintf(wrqu->name, IFNAMSIZ, "long (1)");
9897	else
9898		snprintf(wrqu->name, IFNAMSIZ, "auto (0)");
9899	mutex_unlock(&priv->mutex);
9900	return 0;
9901}
9902
9903#ifdef CONFIG_IPW2200_MONITOR
9904static int ipw_wx_set_monitor(struct net_device *dev,
9905			      struct iw_request_info *info,
9906			      union iwreq_data *wrqu, char *extra)
9907{
9908	struct ipw_priv *priv = libipw_priv(dev);
9909	int *parms = (int *)extra;
9910	int enable = (parms[0] > 0);
9911	mutex_lock(&priv->mutex);
9912	IPW_DEBUG_WX("SET MONITOR: %d %d\n", enable, parms[1]);
9913	if (enable) {
9914		if (priv->ieee->iw_mode != IW_MODE_MONITOR) {
9915#ifdef CONFIG_IPW2200_RADIOTAP
9916			priv->net_dev->type = ARPHRD_IEEE80211_RADIOTAP;
9917#else
9918			priv->net_dev->type = ARPHRD_IEEE80211;
9919#endif
9920			queue_work(priv->workqueue, &priv->adapter_restart);
9921		}
9922
9923		ipw_set_channel(priv, parms[1]);
9924	} else {
9925		if (priv->ieee->iw_mode != IW_MODE_MONITOR) {
9926			mutex_unlock(&priv->mutex);
9927			return 0;
9928		}
9929		priv->net_dev->type = ARPHRD_ETHER;
9930		queue_work(priv->workqueue, &priv->adapter_restart);
9931	}
9932	mutex_unlock(&priv->mutex);
9933	return 0;
9934}
9935
9936#endif				/* CONFIG_IPW2200_MONITOR */
9937
9938static int ipw_wx_reset(struct net_device *dev,
9939			struct iw_request_info *info,
9940			union iwreq_data *wrqu, char *extra)
9941{
9942	struct ipw_priv *priv = libipw_priv(dev);
9943	IPW_DEBUG_WX("RESET\n");
9944	queue_work(priv->workqueue, &priv->adapter_restart);
9945	return 0;
9946}
9947
9948static int ipw_wx_sw_reset(struct net_device *dev,
9949			   struct iw_request_info *info,
9950			   union iwreq_data *wrqu, char *extra)
9951{
9952	struct ipw_priv *priv = libipw_priv(dev);
9953	union iwreq_data wrqu_sec = {
9954		.encoding = {
9955			     .flags = IW_ENCODE_DISABLED,
9956			     },
9957	};
9958	int ret;
9959
9960	IPW_DEBUG_WX("SW_RESET\n");
9961
9962	mutex_lock(&priv->mutex);
9963
9964	ret = ipw_sw_reset(priv, 2);
9965	if (!ret) {
9966		free_firmware();
9967		ipw_adapter_restart(priv);
9968	}
9969
9970	/* The SW reset bit might have been toggled on by the 'disable'
9971	 * module parameter, so take appropriate action */
9972	ipw_radio_kill_sw(priv, priv->status & STATUS_RF_KILL_SW);
9973
9974	mutex_unlock(&priv->mutex);
9975	libipw_wx_set_encode(priv->ieee, info, &wrqu_sec, NULL);
9976	mutex_lock(&priv->mutex);
9977
9978	if (!(priv->status & STATUS_RF_KILL_MASK)) {
9979		/* Configuration likely changed -- force [re]association */
9980		IPW_DEBUG_ASSOC("[re]association triggered due to sw "
9981				"reset.\n");
9982		if (!ipw_disassociate(priv))
9983			ipw_associate(priv);
9984	}
9985
9986	mutex_unlock(&priv->mutex);
9987
9988	return 0;
9989}
9990
9991/* Rebase the WE IOCTLs to zero for the handler array */
9992static iw_handler ipw_wx_handlers[] = {
9993	IW_HANDLER(SIOCGIWNAME, (iw_handler)cfg80211_wext_giwname),
9994	IW_HANDLER(SIOCSIWFREQ, ipw_wx_set_freq),
9995	IW_HANDLER(SIOCGIWFREQ, ipw_wx_get_freq),
9996	IW_HANDLER(SIOCSIWMODE, ipw_wx_set_mode),
9997	IW_HANDLER(SIOCGIWMODE, ipw_wx_get_mode),
9998	IW_HANDLER(SIOCSIWSENS, ipw_wx_set_sens),
9999	IW_HANDLER(SIOCGIWSENS, ipw_wx_get_sens),
10000	IW_HANDLER(SIOCGIWRANGE, ipw_wx_get_range),
10001	IW_HANDLER(SIOCSIWAP, ipw_wx_set_wap),
10002	IW_HANDLER(SIOCGIWAP, ipw_wx_get_wap),
10003	IW_HANDLER(SIOCSIWSCAN, ipw_wx_set_scan),
10004	IW_HANDLER(SIOCGIWSCAN, ipw_wx_get_scan),
10005	IW_HANDLER(SIOCSIWESSID, ipw_wx_set_essid),
10006	IW_HANDLER(SIOCGIWESSID, ipw_wx_get_essid),
10007	IW_HANDLER(SIOCSIWNICKN, ipw_wx_set_nick),
10008	IW_HANDLER(SIOCGIWNICKN, ipw_wx_get_nick),
10009	IW_HANDLER(SIOCSIWRATE, ipw_wx_set_rate),
10010	IW_HANDLER(SIOCGIWRATE, ipw_wx_get_rate),
10011	IW_HANDLER(SIOCSIWRTS, ipw_wx_set_rts),
10012	IW_HANDLER(SIOCGIWRTS, ipw_wx_get_rts),
10013	IW_HANDLER(SIOCSIWFRAG, ipw_wx_set_frag),
10014	IW_HANDLER(SIOCGIWFRAG, ipw_wx_get_frag),
10015	IW_HANDLER(SIOCSIWTXPOW, ipw_wx_set_txpow),
10016	IW_HANDLER(SIOCGIWTXPOW, ipw_wx_get_txpow),
10017	IW_HANDLER(SIOCSIWRETRY, ipw_wx_set_retry),
10018	IW_HANDLER(SIOCGIWRETRY, ipw_wx_get_retry),
10019	IW_HANDLER(SIOCSIWENCODE, ipw_wx_set_encode),
10020	IW_HANDLER(SIOCGIWENCODE, ipw_wx_get_encode),
10021	IW_HANDLER(SIOCSIWPOWER, ipw_wx_set_power),
10022	IW_HANDLER(SIOCGIWPOWER, ipw_wx_get_power),
10023	IW_HANDLER(SIOCSIWSPY, iw_handler_set_spy),
10024	IW_HANDLER(SIOCGIWSPY, iw_handler_get_spy),
10025	IW_HANDLER(SIOCSIWTHRSPY, iw_handler_set_thrspy),
10026	IW_HANDLER(SIOCGIWTHRSPY, iw_handler_get_thrspy),
10027	IW_HANDLER(SIOCSIWGENIE, ipw_wx_set_genie),
10028	IW_HANDLER(SIOCGIWGENIE, ipw_wx_get_genie),
10029	IW_HANDLER(SIOCSIWMLME, ipw_wx_set_mlme),
10030	IW_HANDLER(SIOCSIWAUTH, ipw_wx_set_auth),
10031	IW_HANDLER(SIOCGIWAUTH, ipw_wx_get_auth),
10032	IW_HANDLER(SIOCSIWENCODEEXT, ipw_wx_set_encodeext),
10033	IW_HANDLER(SIOCGIWENCODEEXT, ipw_wx_get_encodeext),
10034};
10035
10036enum {
10037	IPW_PRIV_SET_POWER = SIOCIWFIRSTPRIV,
10038	IPW_PRIV_GET_POWER,
10039	IPW_PRIV_SET_MODE,
10040	IPW_PRIV_GET_MODE,
10041	IPW_PRIV_SET_PREAMBLE,
10042	IPW_PRIV_GET_PREAMBLE,
10043	IPW_PRIV_RESET,
10044	IPW_PRIV_SW_RESET,
10045#ifdef CONFIG_IPW2200_MONITOR
10046	IPW_PRIV_SET_MONITOR,
10047#endif
10048};
10049
10050static struct iw_priv_args ipw_priv_args[] = {
10051	{
10052	 .cmd = IPW_PRIV_SET_POWER,
10053	 .set_args = IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
10054	 .name = "set_power"},
10055	{
10056	 .cmd = IPW_PRIV_GET_POWER,
10057	 .get_args = IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING,
10058	 .name = "get_power"},
10059	{
10060	 .cmd = IPW_PRIV_SET_MODE,
10061	 .set_args = IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
10062	 .name = "set_mode"},
10063	{
10064	 .cmd = IPW_PRIV_GET_MODE,
10065	 .get_args = IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING,
10066	 .name = "get_mode"},
10067	{
10068	 .cmd = IPW_PRIV_SET_PREAMBLE,
10069	 .set_args = IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1,
10070	 .name = "set_preamble"},
10071	{
10072	 .cmd = IPW_PRIV_GET_PREAMBLE,
10073	 .get_args = IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | IFNAMSIZ,
10074	 .name = "get_preamble"},
10075	{
10076	 IPW_PRIV_RESET,
10077	 IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 0, 0, "reset"},
10078	{
10079	 IPW_PRIV_SW_RESET,
10080	 IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 0, 0, "sw_reset"},
10081#ifdef CONFIG_IPW2200_MONITOR
10082	{
10083	 IPW_PRIV_SET_MONITOR,
10084	 IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 2, 0, "monitor"},
10085#endif				/* CONFIG_IPW2200_MONITOR */
10086};
10087
10088static iw_handler ipw_priv_handler[] = {
10089	ipw_wx_set_powermode,
10090	ipw_wx_get_powermode,
10091	ipw_wx_set_wireless_mode,
10092	ipw_wx_get_wireless_mode,
10093	ipw_wx_set_preamble,
10094	ipw_wx_get_preamble,
10095	ipw_wx_reset,
10096	ipw_wx_sw_reset,
10097#ifdef CONFIG_IPW2200_MONITOR
10098	ipw_wx_set_monitor,
10099#endif
10100};
10101
10102static struct iw_handler_def ipw_wx_handler_def = {
10103	.standard = ipw_wx_handlers,
10104	.num_standard = ARRAY_SIZE(ipw_wx_handlers),
10105	.num_private = ARRAY_SIZE(ipw_priv_handler),
10106	.num_private_args = ARRAY_SIZE(ipw_priv_args),
10107	.private = ipw_priv_handler,
10108	.private_args = ipw_priv_args,
10109	.get_wireless_stats = ipw_get_wireless_stats,
10110};
10111
10112/*
10113 * Get wireless statistics.
10114 * Called by /proc/net/wireless
10115 * Also called by SIOCGIWSTATS
10116 */
10117static struct iw_statistics *ipw_get_wireless_stats(struct net_device *dev)
10118{
10119	struct ipw_priv *priv = libipw_priv(dev);
10120	struct iw_statistics *wstats;
10121
10122	wstats = &priv->wstats;
10123
10124	/* if hw is disabled, then ipw_get_ordinal() can't be called.
10125	 * netdev->get_wireless_stats seems to be called before fw is
10126	 * initialized.  STATUS_ASSOCIATED will only be set if the hw is up
10127	 * and associated; if not associcated, the values are all meaningless
10128	 * anyway, so set them all to NULL and INVALID */
10129	if (!(priv->status & STATUS_ASSOCIATED)) {
10130		wstats->miss.beacon = 0;
10131		wstats->discard.retries = 0;
10132		wstats->qual.qual = 0;
10133		wstats->qual.level = 0;
10134		wstats->qual.noise = 0;
10135		wstats->qual.updated = 7;
10136		wstats->qual.updated |= IW_QUAL_NOISE_INVALID |
10137		    IW_QUAL_QUAL_INVALID | IW_QUAL_LEVEL_INVALID;
10138		return wstats;
10139	}
10140
10141	wstats->qual.qual = priv->quality;
10142	wstats->qual.level = priv->exp_avg_rssi;
10143	wstats->qual.noise = priv->exp_avg_noise;
10144	wstats->qual.updated = IW_QUAL_QUAL_UPDATED | IW_QUAL_LEVEL_UPDATED |
10145	    IW_QUAL_NOISE_UPDATED | IW_QUAL_DBM;
10146
10147	wstats->miss.beacon = average_value(&priv->average_missed_beacons);
10148	wstats->discard.retries = priv->last_tx_failures;
10149	wstats->discard.code = priv->ieee->ieee_stats.rx_discards_undecryptable;
10150
10151/*	if (ipw_get_ordinal(priv, IPW_ORD_STAT_TX_RETRY, &tx_retry, &len))
10152	goto fail_get_ordinal;
10153	wstats->discard.retries += tx_retry; */
10154
10155	return wstats;
10156}
10157
10158/* net device stuff */
10159
10160static  void init_sys_config(struct ipw_sys_config *sys_config)
10161{
10162	memset(sys_config, 0, sizeof(struct ipw_sys_config));
10163	sys_config->bt_coexistence = 0;
10164	sys_config->answer_broadcast_ssid_probe = 0;
10165	sys_config->accept_all_data_frames = 0;
10166	sys_config->accept_non_directed_frames = 1;
10167	sys_config->exclude_unicast_unencrypted = 0;
10168	sys_config->disable_unicast_decryption = 1;
10169	sys_config->exclude_multicast_unencrypted = 0;
10170	sys_config->disable_multicast_decryption = 1;
10171	if (antenna < CFG_SYS_ANTENNA_BOTH || antenna > CFG_SYS_ANTENNA_B)
10172		antenna = CFG_SYS_ANTENNA_BOTH;
10173	sys_config->antenna_diversity = antenna;
10174	sys_config->pass_crc_to_host = 0;	/* TODO: See if 1 gives us FCS */
10175	sys_config->dot11g_auto_detection = 0;
10176	sys_config->enable_cts_to_self = 0;
10177	sys_config->bt_coexist_collision_thr = 0;
10178	sys_config->pass_noise_stats_to_host = 1;	/* 1 -- fix for 256 */
10179	sys_config->silence_threshold = 0x1e;
10180}
10181
10182static int ipw_net_open(struct net_device *dev)
10183{
10184	IPW_DEBUG_INFO("dev->open\n");
10185	netif_start_queue(dev);
10186	return 0;
10187}
10188
10189static int ipw_net_stop(struct net_device *dev)
10190{
10191	IPW_DEBUG_INFO("dev->close\n");
10192	netif_stop_queue(dev);
10193	return 0;
10194}
10195
10196/*
10197todo:
10198
10199modify to send one tfd per fragment instead of using chunking.  otherwise
10200we need to heavily modify the libipw_skb_to_txb.
10201*/
10202
10203static int ipw_tx_skb(struct ipw_priv *priv, struct libipw_txb *txb,
10204			     int pri)
10205{
10206	struct libipw_hdr_3addrqos *hdr = (struct libipw_hdr_3addrqos *)
10207	    txb->fragments[0]->data;
10208	int i = 0;
10209	struct tfd_frame *tfd;
10210#ifdef CONFIG_IPW2200_QOS
10211	int tx_id = ipw_get_tx_queue_number(priv, pri);
10212	struct clx2_tx_queue *txq = &priv->txq[tx_id];
10213#else
10214	struct clx2_tx_queue *txq = &priv->txq[0];
10215#endif
10216	struct clx2_queue *q = &txq->q;
10217	u8 id, hdr_len, unicast;
10218	int fc;
10219
10220	if (!(priv->status & STATUS_ASSOCIATED))
10221		goto drop;
10222
10223	hdr_len = libipw_get_hdrlen(le16_to_cpu(hdr->frame_ctl));
10224	switch (priv->ieee->iw_mode) {
10225	case IW_MODE_ADHOC:
10226		unicast = !is_multicast_ether_addr(hdr->addr1);
10227		id = ipw_find_station(priv, hdr->addr1);
10228		if (id == IPW_INVALID_STATION) {
10229			id = ipw_add_station(priv, hdr->addr1);
10230			if (id == IPW_INVALID_STATION) {
10231				IPW_WARNING("Attempt to send data to "
10232					    "invalid cell: %pM\n",
10233					    hdr->addr1);
10234				goto drop;
10235			}
10236		}
10237		break;
10238
10239	case IW_MODE_INFRA:
10240	default:
10241		unicast = !is_multicast_ether_addr(hdr->addr3);
10242		id = 0;
10243		break;
10244	}
10245
10246	tfd = &txq->bd[q->first_empty];
10247	txq->txb[q->first_empty] = txb;
10248	memset(tfd, 0, sizeof(*tfd));
10249	tfd->u.data.station_number = id;
10250
10251	tfd->control_flags.message_type = TX_FRAME_TYPE;
10252	tfd->control_flags.control_bits = TFD_NEED_IRQ_MASK;
10253
10254	tfd->u.data.cmd_id = DINO_CMD_TX;
10255	tfd->u.data.len = cpu_to_le16(txb->payload_size);
10256
10257	if (priv->assoc_request.ieee_mode == IPW_B_MODE)
10258		tfd->u.data.tx_flags_ext |= DCT_FLAG_EXT_MODE_CCK;
10259	else
10260		tfd->u.data.tx_flags_ext |= DCT_FLAG_EXT_MODE_OFDM;
10261
10262	if (priv->assoc_request.preamble_length == DCT_FLAG_SHORT_PREAMBLE)
10263		tfd->u.data.tx_flags |= DCT_FLAG_SHORT_PREAMBLE;
10264
10265	fc = le16_to_cpu(hdr->frame_ctl);
10266	hdr->frame_ctl = cpu_to_le16(fc & ~IEEE80211_FCTL_MOREFRAGS);
10267
10268	memcpy(&tfd->u.data.tfd.tfd_24.mchdr, hdr, hdr_len);
10269
10270	if (likely(unicast))
10271		tfd->u.data.tx_flags |= DCT_FLAG_ACK_REQD;
10272
10273	if (txb->encrypted && !priv->ieee->host_encrypt) {
10274		switch (priv->ieee->sec.level) {
10275		case SEC_LEVEL_3:
10276			tfd->u.data.tfd.tfd_24.mchdr.frame_ctl |=
10277			    cpu_to_le16(IEEE80211_FCTL_PROTECTED);
10278			if (!unicast)
10279				tfd->u.data.tx_flags |= DCT_FLAG_ACK_REQD;
10280
10281			tfd->u.data.tx_flags &= ~DCT_FLAG_NO_WEP;
10282			tfd->u.data.tx_flags_ext |= DCT_FLAG_EXT_SECURITY_CCM;
10283			tfd->u.data.key_index = 0;
10284			tfd->u.data.key_index |= DCT_WEP_INDEX_USE_IMMEDIATE;
10285			break;
10286		case SEC_LEVEL_2:
10287			tfd->u.data.tfd.tfd_24.mchdr.frame_ctl |=
10288			    cpu_to_le16(IEEE80211_FCTL_PROTECTED);
10289			tfd->u.data.tx_flags &= ~DCT_FLAG_NO_WEP;
10290			tfd->u.data.tx_flags_ext |= DCT_FLAG_EXT_SECURITY_TKIP;
10291			tfd->u.data.key_index = DCT_WEP_INDEX_USE_IMMEDIATE;
10292			break;
10293		case SEC_LEVEL_1:
10294			tfd->u.data.tfd.tfd_24.mchdr.frame_ctl |=
10295			    cpu_to_le16(IEEE80211_FCTL_PROTECTED);
10296			tfd->u.data.key_index = priv->ieee->crypt_info.tx_keyidx;
10297			if (priv->ieee->sec.key_sizes[priv->ieee->crypt_info.tx_keyidx] <=
10298			    40)
10299				tfd->u.data.key_index |= DCT_WEP_KEY_64Bit;
10300			else
10301				tfd->u.data.key_index |= DCT_WEP_KEY_128Bit;
10302			break;
10303		case SEC_LEVEL_0:
10304			break;
10305		default:
10306			printk(KERN_ERR "Unknown security level %d\n",
10307			       priv->ieee->sec.level);
10308			break;
10309		}
10310	} else
10311		/* No hardware encryption */
10312		tfd->u.data.tx_flags |= DCT_FLAG_NO_WEP;
10313
10314#ifdef CONFIG_IPW2200_QOS
10315	if (fc & IEEE80211_STYPE_QOS_DATA)
10316		ipw_qos_set_tx_queue_command(priv, pri, &(tfd->u.data));
10317#endif				/* CONFIG_IPW2200_QOS */
10318
10319	/* payload */
10320	tfd->u.data.num_chunks = cpu_to_le32(min((u8) (NUM_TFD_CHUNKS - 2),
10321						 txb->nr_frags));
10322	IPW_DEBUG_FRAG("%i fragments being sent as %i chunks.\n",
10323		       txb->nr_frags, le32_to_cpu(tfd->u.data.num_chunks));
10324	for (i = 0; i < le32_to_cpu(tfd->u.data.num_chunks); i++) {
10325		IPW_DEBUG_FRAG("Adding fragment %i of %i (%d bytes).\n",
10326			       i, le32_to_cpu(tfd->u.data.num_chunks),
10327			       txb->fragments[i]->len - hdr_len);
10328		IPW_DEBUG_TX("Dumping TX packet frag %i of %i (%d bytes):\n",
10329			     i, tfd->u.data.num_chunks,
10330			     txb->fragments[i]->len - hdr_len);
10331		printk_buf(IPW_DL_TX, txb->fragments[i]->data + hdr_len,
10332			   txb->fragments[i]->len - hdr_len);
10333
10334		tfd->u.data.chunk_ptr[i] =
10335		    cpu_to_le32(pci_map_single
10336				(priv->pci_dev,
10337				 txb->fragments[i]->data + hdr_len,
10338				 txb->fragments[i]->len - hdr_len,
10339				 PCI_DMA_TODEVICE));
10340		tfd->u.data.chunk_len[i] =
10341		    cpu_to_le16(txb->fragments[i]->len - hdr_len);
10342	}
10343
10344	if (i != txb->nr_frags) {
10345		struct sk_buff *skb;
10346		u16 remaining_bytes = 0;
10347		int j;
10348
10349		for (j = i; j < txb->nr_frags; j++)
10350			remaining_bytes += txb->fragments[j]->len - hdr_len;
10351
10352		printk(KERN_INFO "Trying to reallocate for %d bytes\n",
10353		       remaining_bytes);
10354		skb = alloc_skb(remaining_bytes, GFP_ATOMIC);
10355		if (skb != NULL) {
10356			tfd->u.data.chunk_len[i] = cpu_to_le16(remaining_bytes);
10357			for (j = i; j < txb->nr_frags; j++) {
10358				int size = txb->fragments[j]->len - hdr_len;
10359
10360				printk(KERN_INFO "Adding frag %d %d...\n",
10361				       j, size);
10362				memcpy(skb_put(skb, size),
10363				       txb->fragments[j]->data + hdr_len, size);
10364			}
10365			dev_kfree_skb_any(txb->fragments[i]);
10366			txb->fragments[i] = skb;
10367			tfd->u.data.chunk_ptr[i] =
10368			    cpu_to_le32(pci_map_single
10369					(priv->pci_dev, skb->data,
10370					 remaining_bytes,
10371					 PCI_DMA_TODEVICE));
10372
10373			le32_add_cpu(&tfd->u.data.num_chunks, 1);
10374		}
10375	}
10376
10377	/* kick DMA */
10378	q->first_empty = ipw_queue_inc_wrap(q->first_empty, q->n_bd);
10379	ipw_write32(priv, q->reg_w, q->first_empty);
10380
10381	if (ipw_tx_queue_space(q) < q->high_mark)
10382		netif_stop_queue(priv->net_dev);
10383
10384	return NETDEV_TX_OK;
10385
10386      drop:
10387	IPW_DEBUG_DROP("Silently dropping Tx packet.\n");
10388	libipw_txb_free(txb);
10389	return NETDEV_TX_OK;
10390}
10391
10392static int ipw_net_is_queue_full(struct net_device *dev, int pri)
10393{
10394	struct ipw_priv *priv = libipw_priv(dev);
10395#ifdef CONFIG_IPW2200_QOS
10396	int tx_id = ipw_get_tx_queue_number(priv, pri);
10397	struct clx2_tx_queue *txq = &priv->txq[tx_id];
10398#else
10399	struct clx2_tx_queue *txq = &priv->txq[0];
10400#endif				/* CONFIG_IPW2200_QOS */
10401
10402	if (ipw_tx_queue_space(&txq->q) < txq->q.high_mark)
10403		return 1;
10404
10405	return 0;
10406}
10407
10408#ifdef CONFIG_IPW2200_PROMISCUOUS
10409static void ipw_handle_promiscuous_tx(struct ipw_priv *priv,
10410				      struct libipw_txb *txb)
10411{
10412	struct libipw_rx_stats dummystats;
10413	struct ieee80211_hdr *hdr;
10414	u8 n;
10415	u16 filter = priv->prom_priv->filter;
10416	int hdr_only = 0;
10417
10418	if (filter & IPW_PROM_NO_TX)
10419		return;
10420
10421	memset(&dummystats, 0, sizeof(dummystats));
10422
10423	/* Filtering of fragment chains is done agains the first fragment */
10424	hdr = (void *)txb->fragments[0]->data;
10425	if (libipw_is_management(le16_to_cpu(hdr->frame_control))) {
10426		if (filter & IPW_PROM_NO_MGMT)
10427			return;
10428		if (filter & IPW_PROM_MGMT_HEADER_ONLY)
10429			hdr_only = 1;
10430	} else if (libipw_is_control(le16_to_cpu(hdr->frame_control))) {
10431		if (filter & IPW_PROM_NO_CTL)
10432			return;
10433		if (filter & IPW_PROM_CTL_HEADER_ONLY)
10434			hdr_only = 1;
10435	} else if (libipw_is_data(le16_to_cpu(hdr->frame_control))) {
10436		if (filter & IPW_PROM_NO_DATA)
10437			return;
10438		if (filter & IPW_PROM_DATA_HEADER_ONLY)
10439			hdr_only = 1;
10440	}
10441
10442	for(n=0; n<txb->nr_frags; ++n) {
10443		struct sk_buff *src = txb->fragments[n];
10444		struct sk_buff *dst;
10445		struct ieee80211_radiotap_header *rt_hdr;
10446		int len;
10447
10448		if (hdr_only) {
10449			hdr = (void *)src->data;
10450			len = libipw_get_hdrlen(le16_to_cpu(hdr->frame_control));
10451		} else
10452			len = src->len;
10453
10454		dst = alloc_skb(len + sizeof(*rt_hdr), GFP_ATOMIC);
10455		if (!dst)
10456			continue;
10457
10458		rt_hdr = (void *)skb_put(dst, sizeof(*rt_hdr));
10459
10460		rt_hdr->it_version = PKTHDR_RADIOTAP_VERSION;
10461		rt_hdr->it_pad = 0;
10462		rt_hdr->it_present = 0; /* after all, it's just an idea */
10463		rt_hdr->it_present |=  cpu_to_le32(1 << IEEE80211_RADIOTAP_CHANNEL);
10464
10465		*(__le16*)skb_put(dst, sizeof(u16)) = cpu_to_le16(
10466			ieee80211chan2mhz(priv->channel));
10467		if (priv->channel > 14) 	/* 802.11a */
10468			*(__le16*)skb_put(dst, sizeof(u16)) =
10469				cpu_to_le16(IEEE80211_CHAN_OFDM |
10470					     IEEE80211_CHAN_5GHZ);
10471		else if (priv->ieee->mode == IEEE_B) /* 802.11b */
10472			*(__le16*)skb_put(dst, sizeof(u16)) =
10473				cpu_to_le16(IEEE80211_CHAN_CCK |
10474					     IEEE80211_CHAN_2GHZ);
10475		else 		/* 802.11g */
10476			*(__le16*)skb_put(dst, sizeof(u16)) =
10477				cpu_to_le16(IEEE80211_CHAN_OFDM |
10478				 IEEE80211_CHAN_2GHZ);
10479
10480		rt_hdr->it_len = cpu_to_le16(dst->len);
10481
10482		skb_copy_from_linear_data(src, skb_put(dst, len), len);
10483
10484		if (!libipw_rx(priv->prom_priv->ieee, dst, &dummystats))
10485			dev_kfree_skb_any(dst);
10486	}
10487}
10488#endif
10489
10490static netdev_tx_t ipw_net_hard_start_xmit(struct libipw_txb *txb,
10491					   struct net_device *dev, int pri)
10492{
10493	struct ipw_priv *priv = libipw_priv(dev);
10494	unsigned long flags;
10495	netdev_tx_t ret;
10496
10497	IPW_DEBUG_TX("dev->xmit(%d bytes)\n", txb->payload_size);
10498	spin_lock_irqsave(&priv->lock, flags);
10499
10500#ifdef CONFIG_IPW2200_PROMISCUOUS
10501	if (rtap_iface && netif_running(priv->prom_net_dev))
10502		ipw_handle_promiscuous_tx(priv, txb);
10503#endif
10504
10505	ret = ipw_tx_skb(priv, txb, pri);
10506	if (ret == NETDEV_TX_OK)
10507		__ipw_led_activity_on(priv);
10508	spin_unlock_irqrestore(&priv->lock, flags);
10509
10510	return ret;
10511}
10512
10513static void ipw_net_set_multicast_list(struct net_device *dev)
10514{
10515
10516}
10517
10518static int ipw_net_set_mac_address(struct net_device *dev, void *p)
10519{
10520	struct ipw_priv *priv = libipw_priv(dev);
10521	struct sockaddr *addr = p;
10522
10523	if (!is_valid_ether_addr(addr->sa_data))
10524		return -EADDRNOTAVAIL;
10525	mutex_lock(&priv->mutex);
10526	priv->config |= CFG_CUSTOM_MAC;
10527	memcpy(priv->mac_addr, addr->sa_data, ETH_ALEN);
10528	printk(KERN_INFO "%s: Setting MAC to %pM\n",
10529	       priv->net_dev->name, priv->mac_addr);
10530	queue_work(priv->workqueue, &priv->adapter_restart);
10531	mutex_unlock(&priv->mutex);
10532	return 0;
10533}
10534
10535static void ipw_ethtool_get_drvinfo(struct net_device *dev,
10536				    struct ethtool_drvinfo *info)
10537{
10538	struct ipw_priv *p = libipw_priv(dev);
10539	char vers[64];
10540	char date[32];
10541	u32 len;
10542
10543	strcpy(info->driver, DRV_NAME);
10544	strcpy(info->version, DRV_VERSION);
10545
10546	len = sizeof(vers);
10547	ipw_get_ordinal(p, IPW_ORD_STAT_FW_VERSION, vers, &len);
10548	len = sizeof(date);
10549	ipw_get_ordinal(p, IPW_ORD_STAT_FW_DATE, date, &len);
10550
10551	snprintf(info->fw_version, sizeof(info->fw_version), "%s (%s)",
10552		 vers, date);
10553	strcpy(info->bus_info, pci_name(p->pci_dev));
10554	info->eedump_len = IPW_EEPROM_IMAGE_SIZE;
10555}
10556
10557static u32 ipw_ethtool_get_link(struct net_device *dev)
10558{
10559	struct ipw_priv *priv = libipw_priv(dev);
10560	return (priv->status & STATUS_ASSOCIATED) != 0;
10561}
10562
10563static int ipw_ethtool_get_eeprom_len(struct net_device *dev)
10564{
10565	return IPW_EEPROM_IMAGE_SIZE;
10566}
10567
10568static int ipw_ethtool_get_eeprom(struct net_device *dev,
10569				  struct ethtool_eeprom *eeprom, u8 * bytes)
10570{
10571	struct ipw_priv *p = libipw_priv(dev);
10572
10573	if (eeprom->offset + eeprom->len > IPW_EEPROM_IMAGE_SIZE)
10574		return -EINVAL;
10575	mutex_lock(&p->mutex);
10576	memcpy(bytes, &p->eeprom[eeprom->offset], eeprom->len);
10577	mutex_unlock(&p->mutex);
10578	return 0;
10579}
10580
10581static int ipw_ethtool_set_eeprom(struct net_device *dev,
10582				  struct ethtool_eeprom *eeprom, u8 * bytes)
10583{
10584	struct ipw_priv *p = libipw_priv(dev);
10585	int i;
10586
10587	if (eeprom->offset + eeprom->len > IPW_EEPROM_IMAGE_SIZE)
10588		return -EINVAL;
10589	mutex_lock(&p->mutex);
10590	memcpy(&p->eeprom[eeprom->offset], bytes, eeprom->len);
10591	for (i = 0; i < IPW_EEPROM_IMAGE_SIZE; i++)
10592		ipw_write8(p, i + IPW_EEPROM_DATA, p->eeprom[i]);
10593	mutex_unlock(&p->mutex);
10594	return 0;
10595}
10596
10597static const struct ethtool_ops ipw_ethtool_ops = {
10598	.get_link = ipw_ethtool_get_link,
10599	.get_drvinfo = ipw_ethtool_get_drvinfo,
10600	.get_eeprom_len = ipw_ethtool_get_eeprom_len,
10601	.get_eeprom = ipw_ethtool_get_eeprom,
10602	.set_eeprom = ipw_ethtool_set_eeprom,
10603};
10604
10605static irqreturn_t ipw_isr(int irq, void *data)
10606{
10607	struct ipw_priv *priv = data;
10608	u32 inta, inta_mask;
10609
10610	if (!priv)
10611		return IRQ_NONE;
10612
10613	spin_lock(&priv->irq_lock);
10614
10615	if (!(priv->status & STATUS_INT_ENABLED)) {
10616		/* IRQ is disabled */
10617		goto none;
10618	}
10619
10620	inta = ipw_read32(priv, IPW_INTA_RW);
10621	inta_mask = ipw_read32(priv, IPW_INTA_MASK_R);
10622
10623	if (inta == 0xFFFFFFFF) {
10624		/* Hardware disappeared */
10625		IPW_WARNING("IRQ INTA == 0xFFFFFFFF\n");
10626		goto none;
10627	}
10628
10629	if (!(inta & (IPW_INTA_MASK_ALL & inta_mask))) {
10630		/* Shared interrupt */
10631		goto none;
10632	}
10633
10634	/* tell the device to stop sending interrupts */
10635	__ipw_disable_interrupts(priv);
10636
10637	/* ack current interrupts */
10638	inta &= (IPW_INTA_MASK_ALL & inta_mask);
10639	ipw_write32(priv, IPW_INTA_RW, inta);
10640
10641	/* Cache INTA value for our tasklet */
10642	priv->isr_inta = inta;
10643
10644	tasklet_schedule(&priv->irq_tasklet);
10645
10646	spin_unlock(&priv->irq_lock);
10647
10648	return IRQ_HANDLED;
10649      none:
10650	spin_unlock(&priv->irq_lock);
10651	return IRQ_NONE;
10652}
10653
10654static void ipw_rf_kill(void *adapter)
10655{
10656	struct ipw_priv *priv = adapter;
10657	unsigned long flags;
10658
10659	spin_lock_irqsave(&priv->lock, flags);
10660
10661	if (rf_kill_active(priv)) {
10662		IPW_DEBUG_RF_KILL("RF Kill active, rescheduling GPIO check\n");
10663		if (priv->workqueue)
10664			queue_delayed_work(priv->workqueue,
10665					   &priv->rf_kill, 2 * HZ);
10666		goto exit_unlock;
10667	}
10668
10669	/* RF Kill is now disabled, so bring the device back up */
10670
10671	if (!(priv->status & STATUS_RF_KILL_MASK)) {
10672		IPW_DEBUG_RF_KILL("HW RF Kill no longer active, restarting "
10673				  "device\n");
10674
10675		/* we can not do an adapter restart while inside an irq lock */
10676		queue_work(priv->workqueue, &priv->adapter_restart);
10677	} else
10678		IPW_DEBUG_RF_KILL("HW RF Kill deactivated.  SW RF Kill still "
10679				  "enabled\n");
10680
10681      exit_unlock:
10682	spin_unlock_irqrestore(&priv->lock, flags);
10683}
10684
10685static void ipw_bg_rf_kill(struct work_struct *work)
10686{
10687	struct ipw_priv *priv =
10688		container_of(work, struct ipw_priv, rf_kill.work);
10689	mutex_lock(&priv->mutex);
10690	ipw_rf_kill(priv);
10691	mutex_unlock(&priv->mutex);
10692}
10693
10694static void ipw_link_up(struct ipw_priv *priv)
10695{
10696	priv->last_seq_num = -1;
10697	priv->last_frag_num = -1;
10698	priv->last_packet_time = 0;
10699
10700	netif_carrier_on(priv->net_dev);
10701
10702	cancel_delayed_work(&priv->request_scan);
10703	cancel_delayed_work(&priv->request_direct_scan);
10704	cancel_delayed_work(&priv->request_passive_scan);
10705	cancel_delayed_work(&priv->scan_event);
10706	ipw_reset_stats(priv);
10707	/* Ensure the rate is updated immediately */
10708	priv->last_rate = ipw_get_current_rate(priv);
10709	ipw_gather_stats(priv);
10710	ipw_led_link_up(priv);
10711	notify_wx_assoc_event(priv);
10712
10713	if (priv->config & CFG_BACKGROUND_SCAN)
10714		queue_delayed_work(priv->workqueue, &priv->request_scan, HZ);
10715}
10716
10717static void ipw_bg_link_up(struct work_struct *work)
10718{
10719	struct ipw_priv *priv =
10720		container_of(work, struct ipw_priv, link_up);
10721	mutex_lock(&priv->mutex);
10722	ipw_link_up(priv);
10723	mutex_unlock(&priv->mutex);
10724}
10725
10726static void ipw_link_down(struct ipw_priv *priv)
10727{
10728	ipw_led_link_down(priv);
10729	netif_carrier_off(priv->net_dev);
10730	notify_wx_assoc_event(priv);
10731
10732	/* Cancel any queued work ... */
10733	cancel_delayed_work(&priv->request_scan);
10734	cancel_delayed_work(&priv->request_direct_scan);
10735	cancel_delayed_work(&priv->request_passive_scan);
10736	cancel_delayed_work(&priv->adhoc_check);
10737	cancel_delayed_work(&priv->gather_stats);
10738
10739	ipw_reset_stats(priv);
10740
10741	if (!(priv->status & STATUS_EXIT_PENDING)) {
10742		/* Queue up another scan... */
10743		queue_delayed_work(priv->workqueue, &priv->request_scan, 0);
10744	} else
10745		cancel_delayed_work(&priv->scan_event);
10746}
10747
10748static void ipw_bg_link_down(struct work_struct *work)
10749{
10750	struct ipw_priv *priv =
10751		container_of(work, struct ipw_priv, link_down);
10752	mutex_lock(&priv->mutex);
10753	ipw_link_down(priv);
10754	mutex_unlock(&priv->mutex);
10755}
10756
10757static int __devinit ipw_setup_deferred_work(struct ipw_priv *priv)
10758{
10759	int ret = 0;
10760
10761	priv->workqueue = create_workqueue(DRV_NAME);
10762	init_waitqueue_head(&priv->wait_command_queue);
10763	init_waitqueue_head(&priv->wait_state);
10764
10765	INIT_DELAYED_WORK(&priv->adhoc_check, ipw_bg_adhoc_check);
10766	INIT_WORK(&priv->associate, ipw_bg_associate);
10767	INIT_WORK(&priv->disassociate, ipw_bg_disassociate);
10768	INIT_WORK(&priv->system_config, ipw_system_config);
10769	INIT_WORK(&priv->rx_replenish, ipw_bg_rx_queue_replenish);
10770	INIT_WORK(&priv->adapter_restart, ipw_bg_adapter_restart);
10771	INIT_DELAYED_WORK(&priv->rf_kill, ipw_bg_rf_kill);
10772	INIT_WORK(&priv->up, ipw_bg_up);
10773	INIT_WORK(&priv->down, ipw_bg_down);
10774	INIT_DELAYED_WORK(&priv->request_scan, ipw_request_scan);
10775	INIT_DELAYED_WORK(&priv->request_direct_scan, ipw_request_direct_scan);
10776	INIT_DELAYED_WORK(&priv->request_passive_scan, ipw_request_passive_scan);
10777	INIT_DELAYED_WORK(&priv->scan_event, ipw_scan_event);
10778	INIT_DELAYED_WORK(&priv->gather_stats, ipw_bg_gather_stats);
10779	INIT_WORK(&priv->abort_scan, ipw_bg_abort_scan);
10780	INIT_WORK(&priv->roam, ipw_bg_roam);
10781	INIT_DELAYED_WORK(&priv->scan_check, ipw_bg_scan_check);
10782	INIT_WORK(&priv->link_up, ipw_bg_link_up);
10783	INIT_WORK(&priv->link_down, ipw_bg_link_down);
10784	INIT_DELAYED_WORK(&priv->led_link_on, ipw_bg_led_link_on);
10785	INIT_DELAYED_WORK(&priv->led_link_off, ipw_bg_led_link_off);
10786	INIT_DELAYED_WORK(&priv->led_act_off, ipw_bg_led_activity_off);
10787	INIT_WORK(&priv->merge_networks, ipw_merge_adhoc_network);
10788
10789#ifdef CONFIG_IPW2200_QOS
10790	INIT_WORK(&priv->qos_activate, ipw_bg_qos_activate);
10791#endif				/* CONFIG_IPW2200_QOS */
10792
10793	tasklet_init(&priv->irq_tasklet, (void (*)(unsigned long))
10794		     ipw_irq_tasklet, (unsigned long)priv);
10795
10796	return ret;
10797}
10798
10799static void shim__set_security(struct net_device *dev,
10800			       struct libipw_security *sec)
10801{
10802	struct ipw_priv *priv = libipw_priv(dev);
10803	int i;
10804	for (i = 0; i < 4; i++) {
10805		if (sec->flags & (1 << i)) {
10806			priv->ieee->sec.encode_alg[i] = sec->encode_alg[i];
10807			priv->ieee->sec.key_sizes[i] = sec->key_sizes[i];
10808			if (sec->key_sizes[i] == 0)
10809				priv->ieee->sec.flags &= ~(1 << i);
10810			else {
10811				memcpy(priv->ieee->sec.keys[i], sec->keys[i],
10812				       sec->key_sizes[i]);
10813				priv->ieee->sec.flags |= (1 << i);
10814			}
10815			priv->status |= STATUS_SECURITY_UPDATED;
10816		} else if (sec->level != SEC_LEVEL_1)
10817			priv->ieee->sec.flags &= ~(1 << i);
10818	}
10819
10820	if (sec->flags & SEC_ACTIVE_KEY) {
10821		if (sec->active_key <= 3) {
10822			priv->ieee->sec.active_key = sec->active_key;
10823			priv->ieee->sec.flags |= SEC_ACTIVE_KEY;
10824		} else
10825			priv->ieee->sec.flags &= ~SEC_ACTIVE_KEY;
10826		priv->status |= STATUS_SECURITY_UPDATED;
10827	} else
10828		priv->ieee->sec.flags &= ~SEC_ACTIVE_KEY;
10829
10830	if ((sec->flags & SEC_AUTH_MODE) &&
10831	    (priv->ieee->sec.auth_mode != sec->auth_mode)) {
10832		priv->ieee->sec.auth_mode = sec->auth_mode;
10833		priv->ieee->sec.flags |= SEC_AUTH_MODE;
10834		if (sec->auth_mode == WLAN_AUTH_SHARED_KEY)
10835			priv->capability |= CAP_SHARED_KEY;
10836		else
10837			priv->capability &= ~CAP_SHARED_KEY;
10838		priv->status |= STATUS_SECURITY_UPDATED;
10839	}
10840
10841	if (sec->flags & SEC_ENABLED && priv->ieee->sec.enabled != sec->enabled) {
10842		priv->ieee->sec.flags |= SEC_ENABLED;
10843		priv->ieee->sec.enabled = sec->enabled;
10844		priv->status |= STATUS_SECURITY_UPDATED;
10845		if (sec->enabled)
10846			priv->capability |= CAP_PRIVACY_ON;
10847		else
10848			priv->capability &= ~CAP_PRIVACY_ON;
10849	}
10850
10851	if (sec->flags & SEC_ENCRYPT)
10852		priv->ieee->sec.encrypt = sec->encrypt;
10853
10854	if (sec->flags & SEC_LEVEL && priv->ieee->sec.level != sec->level) {
10855		priv->ieee->sec.level = sec->level;
10856		priv->ieee->sec.flags |= SEC_LEVEL;
10857		priv->status |= STATUS_SECURITY_UPDATED;
10858	}
10859
10860	if (!priv->ieee->host_encrypt && (sec->flags & SEC_ENCRYPT))
10861		ipw_set_hwcrypto_keys(priv);
10862
10863	/* To match current functionality of ipw2100 (which works well w/
10864	 * various supplicants, we don't force a disassociate if the
10865	 * privacy capability changes ... */
10866}
10867
10868static int init_supported_rates(struct ipw_priv *priv,
10869				struct ipw_supported_rates *rates)
10870{
10871	/* TODO: Mask out rates based on priv->rates_mask */
10872
10873	memset(rates, 0, sizeof(*rates));
10874	/* configure supported rates */
10875	switch (priv->ieee->freq_band) {
10876	case LIBIPW_52GHZ_BAND:
10877		rates->ieee_mode = IPW_A_MODE;
10878		rates->purpose = IPW_RATE_CAPABILITIES;
10879		ipw_add_ofdm_scan_rates(rates, LIBIPW_CCK_MODULATION,
10880					LIBIPW_OFDM_DEFAULT_RATES_MASK);
10881		break;
10882
10883	default:		/* Mixed or 2.4Ghz */
10884		rates->ieee_mode = IPW_G_MODE;
10885		rates->purpose = IPW_RATE_CAPABILITIES;
10886		ipw_add_cck_scan_rates(rates, LIBIPW_CCK_MODULATION,
10887				       LIBIPW_CCK_DEFAULT_RATES_MASK);
10888		if (priv->ieee->modulation & LIBIPW_OFDM_MODULATION) {
10889			ipw_add_ofdm_scan_rates(rates, LIBIPW_CCK_MODULATION,
10890						LIBIPW_OFDM_DEFAULT_RATES_MASK);
10891		}
10892		break;
10893	}
10894
10895	return 0;
10896}
10897
10898static int ipw_config(struct ipw_priv *priv)
10899{
10900	/* This is only called from ipw_up, which resets/reloads the firmware
10901	   so, we don't need to first disable the card before we configure
10902	   it */
10903	if (ipw_set_tx_power(priv))
10904		goto error;
10905
10906	/* initialize adapter address */
10907	if (ipw_send_adapter_address(priv, priv->net_dev->dev_addr))
10908		goto error;
10909
10910	/* set basic system config settings */
10911	init_sys_config(&priv->sys_config);
10912
10913	/* Support Bluetooth if we have BT h/w on board, and user wants to.
10914	 * Does not support BT priority yet (don't abort or defer our Tx) */
10915	if (bt_coexist) {
10916		unsigned char bt_caps = priv->eeprom[EEPROM_SKU_CAPABILITY];
10917
10918		if (bt_caps & EEPROM_SKU_CAP_BT_CHANNEL_SIG)
10919			priv->sys_config.bt_coexistence
10920			    |= CFG_BT_COEXISTENCE_SIGNAL_CHNL;
10921		if (bt_caps & EEPROM_SKU_CAP_BT_OOB)
10922			priv->sys_config.bt_coexistence
10923			    |= CFG_BT_COEXISTENCE_OOB;
10924	}
10925
10926#ifdef CONFIG_IPW2200_PROMISCUOUS
10927	if (priv->prom_net_dev && netif_running(priv->prom_net_dev)) {
10928		priv->sys_config.accept_all_data_frames = 1;
10929		priv->sys_config.accept_non_directed_frames = 1;
10930		priv->sys_config.accept_all_mgmt_bcpr = 1;
10931		priv->sys_config.accept_all_mgmt_frames = 1;
10932	}
10933#endif
10934
10935	if (priv->ieee->iw_mode == IW_MODE_ADHOC)
10936		priv->sys_config.answer_broadcast_ssid_probe = 1;
10937	else
10938		priv->sys_config.answer_broadcast_ssid_probe = 0;
10939
10940	if (ipw_send_system_config(priv))
10941		goto error;
10942
10943	init_supported_rates(priv, &priv->rates);
10944	if (ipw_send_supported_rates(priv, &priv->rates))
10945		goto error;
10946
10947	/* Set request-to-send threshold */
10948	if (priv->rts_threshold) {
10949		if (ipw_send_rts_threshold(priv, priv->rts_threshold))
10950			goto error;
10951	}
10952#ifdef CONFIG_IPW2200_QOS
10953	IPW_DEBUG_QOS("QoS: call ipw_qos_activate\n");
10954	ipw_qos_activate(priv, NULL);
10955#endif				/* CONFIG_IPW2200_QOS */
10956
10957	if (ipw_set_random_seed(priv))
10958		goto error;
10959
10960	/* final state transition to the RUN state */
10961	if (ipw_send_host_complete(priv))
10962		goto error;
10963
10964	priv->status |= STATUS_INIT;
10965
10966	ipw_led_init(priv);
10967	ipw_led_radio_on(priv);
10968	priv->notif_missed_beacons = 0;
10969
10970	/* Set hardware WEP key if it is configured. */
10971	if ((priv->capability & CAP_PRIVACY_ON) &&
10972	    (priv->ieee->sec.level == SEC_LEVEL_1) &&
10973	    !(priv->ieee->host_encrypt || priv->ieee->host_decrypt))
10974		ipw_set_hwcrypto_keys(priv);
10975
10976	return 0;
10977
10978      error:
10979	return -EIO;
10980}
10981
10982/*
10983 * NOTE:
10984 *
10985 * These tables have been tested in conjunction with the
10986 * Intel PRO/Wireless 2200BG and 2915ABG Network Connection Adapters.
10987 *
10988 * Altering this values, using it on other hardware, or in geographies
10989 * not intended for resale of the above mentioned Intel adapters has
10990 * not been tested.
10991 *
10992 * Remember to update the table in README.ipw2200 when changing this
10993 * table.
10994 *
10995 */
10996static const struct libipw_geo ipw_geos[] = {
10997	{			/* Restricted */
10998	 "---",
10999	 .bg_channels = 11,
11000	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11001		{2427, 4}, {2432, 5}, {2437, 6},
11002		{2442, 7}, {2447, 8}, {2452, 9},
11003		{2457, 10}, {2462, 11}},
11004	 },
11005
11006	{			/* Custom US/Canada */
11007	 "ZZF",
11008	 .bg_channels = 11,
11009	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11010		{2427, 4}, {2432, 5}, {2437, 6},
11011		{2442, 7}, {2447, 8}, {2452, 9},
11012		{2457, 10}, {2462, 11}},
11013	 .a_channels = 8,
11014	 .a = {{5180, 36},
11015	       {5200, 40},
11016	       {5220, 44},
11017	       {5240, 48},
11018	       {5260, 52, LIBIPW_CH_PASSIVE_ONLY},
11019	       {5280, 56, LIBIPW_CH_PASSIVE_ONLY},
11020	       {5300, 60, LIBIPW_CH_PASSIVE_ONLY},
11021	       {5320, 64, LIBIPW_CH_PASSIVE_ONLY}},
11022	 },
11023
11024	{			/* Rest of World */
11025	 "ZZD",
11026	 .bg_channels = 13,
11027	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11028		{2427, 4}, {2432, 5}, {2437, 6},
11029		{2442, 7}, {2447, 8}, {2452, 9},
11030		{2457, 10}, {2462, 11}, {2467, 12},
11031		{2472, 13}},
11032	 },
11033
11034	{			/* Custom USA & Europe & High */
11035	 "ZZA",
11036	 .bg_channels = 11,
11037	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11038		{2427, 4}, {2432, 5}, {2437, 6},
11039		{2442, 7}, {2447, 8}, {2452, 9},
11040		{2457, 10}, {2462, 11}},
11041	 .a_channels = 13,
11042	 .a = {{5180, 36},
11043	       {5200, 40},
11044	       {5220, 44},
11045	       {5240, 48},
11046	       {5260, 52, LIBIPW_CH_PASSIVE_ONLY},
11047	       {5280, 56, LIBIPW_CH_PASSIVE_ONLY},
11048	       {5300, 60, LIBIPW_CH_PASSIVE_ONLY},
11049	       {5320, 64, LIBIPW_CH_PASSIVE_ONLY},
11050	       {5745, 149},
11051	       {5765, 153},
11052	       {5785, 157},
11053	       {5805, 161},
11054	       {5825, 165}},
11055	 },
11056
11057	{			/* Custom NA & Europe */
11058	 "ZZB",
11059	 .bg_channels = 11,
11060	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11061		{2427, 4}, {2432, 5}, {2437, 6},
11062		{2442, 7}, {2447, 8}, {2452, 9},
11063		{2457, 10}, {2462, 11}},
11064	 .a_channels = 13,
11065	 .a = {{5180, 36},
11066	       {5200, 40},
11067	       {5220, 44},
11068	       {5240, 48},
11069	       {5260, 52, LIBIPW_CH_PASSIVE_ONLY},
11070	       {5280, 56, LIBIPW_CH_PASSIVE_ONLY},
11071	       {5300, 60, LIBIPW_CH_PASSIVE_ONLY},
11072	       {5320, 64, LIBIPW_CH_PASSIVE_ONLY},
11073	       {5745, 149, LIBIPW_CH_PASSIVE_ONLY},
11074	       {5765, 153, LIBIPW_CH_PASSIVE_ONLY},
11075	       {5785, 157, LIBIPW_CH_PASSIVE_ONLY},
11076	       {5805, 161, LIBIPW_CH_PASSIVE_ONLY},
11077	       {5825, 165, LIBIPW_CH_PASSIVE_ONLY}},
11078	 },
11079
11080	{			/* Custom Japan */
11081	 "ZZC",
11082	 .bg_channels = 11,
11083	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11084		{2427, 4}, {2432, 5}, {2437, 6},
11085		{2442, 7}, {2447, 8}, {2452, 9},
11086		{2457, 10}, {2462, 11}},
11087	 .a_channels = 4,
11088	 .a = {{5170, 34}, {5190, 38},
11089	       {5210, 42}, {5230, 46}},
11090	 },
11091
11092	{			/* Custom */
11093	 "ZZM",
11094	 .bg_channels = 11,
11095	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11096		{2427, 4}, {2432, 5}, {2437, 6},
11097		{2442, 7}, {2447, 8}, {2452, 9},
11098		{2457, 10}, {2462, 11}},
11099	 },
11100
11101	{			/* Europe */
11102	 "ZZE",
11103	 .bg_channels = 13,
11104	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11105		{2427, 4}, {2432, 5}, {2437, 6},
11106		{2442, 7}, {2447, 8}, {2452, 9},
11107		{2457, 10}, {2462, 11}, {2467, 12},
11108		{2472, 13}},
11109	 .a_channels = 19,
11110	 .a = {{5180, 36},
11111	       {5200, 40},
11112	       {5220, 44},
11113	       {5240, 48},
11114	       {5260, 52, LIBIPW_CH_PASSIVE_ONLY},
11115	       {5280, 56, LIBIPW_CH_PASSIVE_ONLY},
11116	       {5300, 60, LIBIPW_CH_PASSIVE_ONLY},
11117	       {5320, 64, LIBIPW_CH_PASSIVE_ONLY},
11118	       {5500, 100, LIBIPW_CH_PASSIVE_ONLY},
11119	       {5520, 104, LIBIPW_CH_PASSIVE_ONLY},
11120	       {5540, 108, LIBIPW_CH_PASSIVE_ONLY},
11121	       {5560, 112, LIBIPW_CH_PASSIVE_ONLY},
11122	       {5580, 116, LIBIPW_CH_PASSIVE_ONLY},
11123	       {5600, 120, LIBIPW_CH_PASSIVE_ONLY},
11124	       {5620, 124, LIBIPW_CH_PASSIVE_ONLY},
11125	       {5640, 128, LIBIPW_CH_PASSIVE_ONLY},
11126	       {5660, 132, LIBIPW_CH_PASSIVE_ONLY},
11127	       {5680, 136, LIBIPW_CH_PASSIVE_ONLY},
11128	       {5700, 140, LIBIPW_CH_PASSIVE_ONLY}},
11129	 },
11130
11131	{			/* Custom Japan */
11132	 "ZZJ",
11133	 .bg_channels = 14,
11134	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11135		{2427, 4}, {2432, 5}, {2437, 6},
11136		{2442, 7}, {2447, 8}, {2452, 9},
11137		{2457, 10}, {2462, 11}, {2467, 12},
11138		{2472, 13}, {2484, 14, LIBIPW_CH_B_ONLY}},
11139	 .a_channels = 4,
11140	 .a = {{5170, 34}, {5190, 38},
11141	       {5210, 42}, {5230, 46}},
11142	 },
11143
11144	{			/* Rest of World */
11145	 "ZZR",
11146	 .bg_channels = 14,
11147	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11148		{2427, 4}, {2432, 5}, {2437, 6},
11149		{2442, 7}, {2447, 8}, {2452, 9},
11150		{2457, 10}, {2462, 11}, {2467, 12},
11151		{2472, 13}, {2484, 14, LIBIPW_CH_B_ONLY |
11152			     LIBIPW_CH_PASSIVE_ONLY}},
11153	 },
11154
11155	{			/* High Band */
11156	 "ZZH",
11157	 .bg_channels = 13,
11158	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11159		{2427, 4}, {2432, 5}, {2437, 6},
11160		{2442, 7}, {2447, 8}, {2452, 9},
11161		{2457, 10}, {2462, 11},
11162		{2467, 12, LIBIPW_CH_PASSIVE_ONLY},
11163		{2472, 13, LIBIPW_CH_PASSIVE_ONLY}},
11164	 .a_channels = 4,
11165	 .a = {{5745, 149}, {5765, 153},
11166	       {5785, 157}, {5805, 161}},
11167	 },
11168
11169	{			/* Custom Europe */
11170	 "ZZG",
11171	 .bg_channels = 13,
11172	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11173		{2427, 4}, {2432, 5}, {2437, 6},
11174		{2442, 7}, {2447, 8}, {2452, 9},
11175		{2457, 10}, {2462, 11},
11176		{2467, 12}, {2472, 13}},
11177	 .a_channels = 4,
11178	 .a = {{5180, 36}, {5200, 40},
11179	       {5220, 44}, {5240, 48}},
11180	 },
11181
11182	{			/* Europe */
11183	 "ZZK",
11184	 .bg_channels = 13,
11185	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11186		{2427, 4}, {2432, 5}, {2437, 6},
11187		{2442, 7}, {2447, 8}, {2452, 9},
11188		{2457, 10}, {2462, 11},
11189		{2467, 12, LIBIPW_CH_PASSIVE_ONLY},
11190		{2472, 13, LIBIPW_CH_PASSIVE_ONLY}},
11191	 .a_channels = 24,
11192	 .a = {{5180, 36, LIBIPW_CH_PASSIVE_ONLY},
11193	       {5200, 40, LIBIPW_CH_PASSIVE_ONLY},
11194	       {5220, 44, LIBIPW_CH_PASSIVE_ONLY},
11195	       {5240, 48, LIBIPW_CH_PASSIVE_ONLY},
11196	       {5260, 52, LIBIPW_CH_PASSIVE_ONLY},
11197	       {5280, 56, LIBIPW_CH_PASSIVE_ONLY},
11198	       {5300, 60, LIBIPW_CH_PASSIVE_ONLY},
11199	       {5320, 64, LIBIPW_CH_PASSIVE_ONLY},
11200	       {5500, 100, LIBIPW_CH_PASSIVE_ONLY},
11201	       {5520, 104, LIBIPW_CH_PASSIVE_ONLY},
11202	       {5540, 108, LIBIPW_CH_PASSIVE_ONLY},
11203	       {5560, 112, LIBIPW_CH_PASSIVE_ONLY},
11204	       {5580, 116, LIBIPW_CH_PASSIVE_ONLY},
11205	       {5600, 120, LIBIPW_CH_PASSIVE_ONLY},
11206	       {5620, 124, LIBIPW_CH_PASSIVE_ONLY},
11207	       {5640, 128, LIBIPW_CH_PASSIVE_ONLY},
11208	       {5660, 132, LIBIPW_CH_PASSIVE_ONLY},
11209	       {5680, 136, LIBIPW_CH_PASSIVE_ONLY},
11210	       {5700, 140, LIBIPW_CH_PASSIVE_ONLY},
11211	       {5745, 149, LIBIPW_CH_PASSIVE_ONLY},
11212	       {5765, 153, LIBIPW_CH_PASSIVE_ONLY},
11213	       {5785, 157, LIBIPW_CH_PASSIVE_ONLY},
11214	       {5805, 161, LIBIPW_CH_PASSIVE_ONLY},
11215	       {5825, 165, LIBIPW_CH_PASSIVE_ONLY}},
11216	 },
11217
11218	{			/* Europe */
11219	 "ZZL",
11220	 .bg_channels = 11,
11221	 .bg = {{2412, 1}, {2417, 2}, {2422, 3},
11222		{2427, 4}, {2432, 5}, {2437, 6},
11223		{2442, 7}, {2447, 8}, {2452, 9},
11224		{2457, 10}, {2462, 11}},
11225	 .a_channels = 13,
11226	 .a = {{5180, 36, LIBIPW_CH_PASSIVE_ONLY},
11227	       {5200, 40, LIBIPW_CH_PASSIVE_ONLY},
11228	       {5220, 44, LIBIPW_CH_PASSIVE_ONLY},
11229	       {5240, 48, LIBIPW_CH_PASSIVE_ONLY},
11230	       {5260, 52, LIBIPW_CH_PASSIVE_ONLY},
11231	       {5280, 56, LIBIPW_CH_PASSIVE_ONLY},
11232	       {5300, 60, LIBIPW_CH_PASSIVE_ONLY},
11233	       {5320, 64, LIBIPW_CH_PASSIVE_ONLY},
11234	       {5745, 149, LIBIPW_CH_PASSIVE_ONLY},
11235	       {5765, 153, LIBIPW_CH_PASSIVE_ONLY},
11236	       {5785, 157, LIBIPW_CH_PASSIVE_ONLY},
11237	       {5805, 161, LIBIPW_CH_PASSIVE_ONLY},
11238	       {5825, 165, LIBIPW_CH_PASSIVE_ONLY}},
11239	 }
11240};
11241
11242#define MAX_HW_RESTARTS 5
11243static int ipw_up(struct ipw_priv *priv)
11244{
11245	int rc, i, j;
11246
11247	/* Age scan list entries found before suspend */
11248	if (priv->suspend_time) {
11249		libipw_networks_age(priv->ieee, priv->suspend_time);
11250		priv->suspend_time = 0;
11251	}
11252
11253	if (priv->status & STATUS_EXIT_PENDING)
11254		return -EIO;
11255
11256	if (cmdlog && !priv->cmdlog) {
11257		priv->cmdlog = kcalloc(cmdlog, sizeof(*priv->cmdlog),
11258				       GFP_KERNEL);
11259		if (priv->cmdlog == NULL) {
11260			IPW_ERROR("Error allocating %d command log entries.\n",
11261				  cmdlog);
11262			return -ENOMEM;
11263		} else {
11264			priv->cmdlog_len = cmdlog;
11265		}
11266	}
11267
11268	for (i = 0; i < MAX_HW_RESTARTS; i++) {
11269		/* Load the microcode, firmware, and eeprom.
11270		 * Also start the clocks. */
11271		rc = ipw_load(priv);
11272		if (rc) {
11273			IPW_ERROR("Unable to load firmware: %d\n", rc);
11274			return rc;
11275		}
11276
11277		ipw_init_ordinals(priv);
11278		if (!(priv->config & CFG_CUSTOM_MAC))
11279			eeprom_parse_mac(priv, priv->mac_addr);
11280		memcpy(priv->net_dev->dev_addr, priv->mac_addr, ETH_ALEN);
11281		memcpy(priv->net_dev->perm_addr, priv->mac_addr, ETH_ALEN);
11282
11283		for (j = 0; j < ARRAY_SIZE(ipw_geos); j++) {
11284			if (!memcmp(&priv->eeprom[EEPROM_COUNTRY_CODE],
11285				    ipw_geos[j].name, 3))
11286				break;
11287		}
11288		if (j == ARRAY_SIZE(ipw_geos)) {
11289			IPW_WARNING("SKU [%c%c%c] not recognized.\n",
11290				    priv->eeprom[EEPROM_COUNTRY_CODE + 0],
11291				    priv->eeprom[EEPROM_COUNTRY_CODE + 1],
11292				    priv->eeprom[EEPROM_COUNTRY_CODE + 2]);
11293			j = 0;
11294		}
11295		if (libipw_set_geo(priv->ieee, &ipw_geos[j])) {
11296			IPW_WARNING("Could not set geography.");
11297			return 0;
11298		}
11299
11300		if (priv->status & STATUS_RF_KILL_SW) {
11301			IPW_WARNING("Radio disabled by module parameter.\n");
11302			return 0;
11303		} else if (rf_kill_active(priv)) {
11304			IPW_WARNING("Radio Frequency Kill Switch is On:\n"
11305				    "Kill switch must be turned off for "
11306				    "wireless networking to work.\n");
11307			queue_delayed_work(priv->workqueue, &priv->rf_kill,
11308					   2 * HZ);
11309			return 0;
11310		}
11311
11312		rc = ipw_config(priv);
11313		if (!rc) {
11314			IPW_DEBUG_INFO("Configured device on count %i\n", i);
11315
11316			/* If configure to try and auto-associate, kick
11317			 * off a scan. */
11318			queue_delayed_work(priv->workqueue,
11319					   &priv->request_scan, 0);
11320
11321			return 0;
11322		}
11323
11324		IPW_DEBUG_INFO("Device configuration failed: 0x%08X\n", rc);
11325		IPW_DEBUG_INFO("Failed to config device on retry %d of %d\n",
11326			       i, MAX_HW_RESTARTS);
11327
11328		/* We had an error bringing up the hardware, so take it
11329		 * all the way back down so we can try again */
11330		ipw_down(priv);
11331	}
11332
11333	/* tried to restart and config the device for as long as our
11334	 * patience could withstand */
11335	IPW_ERROR("Unable to initialize device after %d attempts.\n", i);
11336
11337	return -EIO;
11338}
11339
11340static void ipw_bg_up(struct work_struct *work)
11341{
11342	struct ipw_priv *priv =
11343		container_of(work, struct ipw_priv, up);
11344	mutex_lock(&priv->mutex);
11345	ipw_up(priv);
11346	mutex_unlock(&priv->mutex);
11347}
11348
11349static void ipw_deinit(struct ipw_priv *priv)
11350{
11351	int i;
11352
11353	if (priv->status & STATUS_SCANNING) {
11354		IPW_DEBUG_INFO("Aborting scan during shutdown.\n");
11355		ipw_abort_scan(priv);
11356	}
11357
11358	if (priv->status & STATUS_ASSOCIATED) {
11359		IPW_DEBUG_INFO("Disassociating during shutdown.\n");
11360		ipw_disassociate(priv);
11361	}
11362
11363	ipw_led_shutdown(priv);
11364
11365	/* Wait up to 1s for status to change to not scanning and not
11366	 * associated (disassociation can take a while for a ful 802.11
11367	 * exchange */
11368	for (i = 1000; i && (priv->status &
11369			     (STATUS_DISASSOCIATING |
11370			      STATUS_ASSOCIATED | STATUS_SCANNING)); i--)
11371		udelay(10);
11372
11373	if (priv->status & (STATUS_DISASSOCIATING |
11374			    STATUS_ASSOCIATED | STATUS_SCANNING))
11375		IPW_DEBUG_INFO("Still associated or scanning...\n");
11376	else
11377		IPW_DEBUG_INFO("Took %dms to de-init\n", 1000 - i);
11378
11379	/* Attempt to disable the card */
11380	ipw_send_card_disable(priv, 0);
11381
11382	priv->status &= ~STATUS_INIT;
11383}
11384
11385static void ipw_down(struct ipw_priv *priv)
11386{
11387	int exit_pending = priv->status & STATUS_EXIT_PENDING;
11388
11389	priv->status |= STATUS_EXIT_PENDING;
11390
11391	if (ipw_is_init(priv))
11392		ipw_deinit(priv);
11393
11394	/* Wipe out the EXIT_PENDING status bit if we are not actually
11395	 * exiting the module */
11396	if (!exit_pending)
11397		priv->status &= ~STATUS_EXIT_PENDING;
11398
11399	/* tell the device to stop sending interrupts */
11400	ipw_disable_interrupts(priv);
11401
11402	/* Clear all bits but the RF Kill */
11403	priv->status &= STATUS_RF_KILL_MASK | STATUS_EXIT_PENDING;
11404	netif_carrier_off(priv->net_dev);
11405
11406	ipw_stop_nic(priv);
11407
11408	ipw_led_radio_off(priv);
11409}
11410
11411static void ipw_bg_down(struct work_struct *work)
11412{
11413	struct ipw_priv *priv =
11414		container_of(work, struct ipw_priv, down);
11415	mutex_lock(&priv->mutex);
11416	ipw_down(priv);
11417	mutex_unlock(&priv->mutex);
11418}
11419
11420/* Called by register_netdev() */
11421static int ipw_net_init(struct net_device *dev)
11422{
11423	int i, rc = 0;
11424	struct ipw_priv *priv = libipw_priv(dev);
11425	const struct libipw_geo *geo = libipw_get_geo(priv->ieee);
11426	struct wireless_dev *wdev = &priv->ieee->wdev;
11427	mutex_lock(&priv->mutex);
11428
11429	if (ipw_up(priv)) {
11430		rc = -EIO;
11431		goto out;
11432	}
11433
11434	memcpy(wdev->wiphy->perm_addr, priv->mac_addr, ETH_ALEN);
11435
11436	/* fill-out priv->ieee->bg_band */
11437	if (geo->bg_channels) {
11438		struct ieee80211_supported_band *bg_band = &priv->ieee->bg_band;
11439
11440		bg_band->band = IEEE80211_BAND_2GHZ;
11441		bg_band->n_channels = geo->bg_channels;
11442		bg_band->channels =
11443			kzalloc(geo->bg_channels *
11444				sizeof(struct ieee80211_channel), GFP_KERNEL);
11445		/* translate geo->bg to bg_band.channels */
11446		for (i = 0; i < geo->bg_channels; i++) {
11447			bg_band->channels[i].band = IEEE80211_BAND_2GHZ;
11448			bg_band->channels[i].center_freq = geo->bg[i].freq;
11449			bg_band->channels[i].hw_value = geo->bg[i].channel;
11450			bg_band->channels[i].max_power = geo->bg[i].max_power;
11451			if (geo->bg[i].flags & LIBIPW_CH_PASSIVE_ONLY)
11452				bg_band->channels[i].flags |=
11453					IEEE80211_CHAN_PASSIVE_SCAN;
11454			if (geo->bg[i].flags & LIBIPW_CH_NO_IBSS)
11455				bg_band->channels[i].flags |=
11456					IEEE80211_CHAN_NO_IBSS;
11457			if (geo->bg[i].flags & LIBIPW_CH_RADAR_DETECT)
11458				bg_band->channels[i].flags |=
11459					IEEE80211_CHAN_RADAR;
11460			/* No equivalent for LIBIPW_CH_80211H_RULES,
11461			   LIBIPW_CH_UNIFORM_SPREADING, or
11462			   LIBIPW_CH_B_ONLY... */
11463		}
11464		/* point at bitrate info */
11465		bg_band->bitrates = ipw2200_bg_rates;
11466		bg_band->n_bitrates = ipw2200_num_bg_rates;
11467
11468		wdev->wiphy->bands[IEEE80211_BAND_2GHZ] = bg_band;
11469	}
11470
11471	/* fill-out priv->ieee->a_band */
11472	if (geo->a_channels) {
11473		struct ieee80211_supported_band *a_band = &priv->ieee->a_band;
11474
11475		a_band->band = IEEE80211_BAND_5GHZ;
11476		a_band->n_channels = geo->a_channels;
11477		a_band->channels =
11478			kzalloc(geo->a_channels *
11479				sizeof(struct ieee80211_channel), GFP_KERNEL);
11480		/* translate geo->bg to a_band.channels */
11481		for (i = 0; i < geo->a_channels; i++) {
11482			a_band->channels[i].band = IEEE80211_BAND_2GHZ;
11483			a_band->channels[i].center_freq = geo->a[i].freq;
11484			a_band->channels[i].hw_value = geo->a[i].channel;
11485			a_band->channels[i].max_power = geo->a[i].max_power;
11486			if (geo->a[i].flags & LIBIPW_CH_PASSIVE_ONLY)
11487				a_band->channels[i].flags |=
11488					IEEE80211_CHAN_PASSIVE_SCAN;
11489			if (geo->a[i].flags & LIBIPW_CH_NO_IBSS)
11490				a_band->channels[i].flags |=
11491					IEEE80211_CHAN_NO_IBSS;
11492			if (geo->a[i].flags & LIBIPW_CH_RADAR_DETECT)
11493				a_band->channels[i].flags |=
11494					IEEE80211_CHAN_RADAR;
11495			/* No equivalent for LIBIPW_CH_80211H_RULES,
11496			   LIBIPW_CH_UNIFORM_SPREADING, or
11497			   LIBIPW_CH_B_ONLY... */
11498		}
11499		/* point at bitrate info */
11500		a_band->bitrates = ipw2200_a_rates;
11501		a_band->n_bitrates = ipw2200_num_a_rates;
11502
11503		wdev->wiphy->bands[IEEE80211_BAND_5GHZ] = a_band;
11504	}
11505
11506	set_wiphy_dev(wdev->wiphy, &priv->pci_dev->dev);
11507
11508	/* With that information in place, we can now register the wiphy... */
11509	if (wiphy_register(wdev->wiphy)) {
11510		rc = -EIO;
11511		goto out;
11512	}
11513
11514out:
11515	mutex_unlock(&priv->mutex);
11516	return rc;
11517}
11518
11519/* PCI driver stuff */
11520static DEFINE_PCI_DEVICE_TABLE(card_ids) = {
11521	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2701, 0, 0, 0},
11522	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2702, 0, 0, 0},
11523	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2711, 0, 0, 0},
11524	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2712, 0, 0, 0},
11525	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2721, 0, 0, 0},
11526	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2722, 0, 0, 0},
11527	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2731, 0, 0, 0},
11528	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2732, 0, 0, 0},
11529	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2741, 0, 0, 0},
11530	{PCI_VENDOR_ID_INTEL, 0x1043, 0x103c, 0x2741, 0, 0, 0},
11531	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2742, 0, 0, 0},
11532	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2751, 0, 0, 0},
11533	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2752, 0, 0, 0},
11534	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2753, 0, 0, 0},
11535	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2754, 0, 0, 0},
11536	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2761, 0, 0, 0},
11537	{PCI_VENDOR_ID_INTEL, 0x1043, 0x8086, 0x2762, 0, 0, 0},
11538	{PCI_VDEVICE(INTEL, 0x104f), 0},
11539	{PCI_VDEVICE(INTEL, 0x4220), 0},	/* BG */
11540	{PCI_VDEVICE(INTEL, 0x4221), 0},	/* BG */
11541	{PCI_VDEVICE(INTEL, 0x4223), 0},	/* ABG */
11542	{PCI_VDEVICE(INTEL, 0x4224), 0},	/* ABG */
11543
11544	/* required last entry */
11545	{0,}
11546};
11547
11548MODULE_DEVICE_TABLE(pci, card_ids);
11549
11550static struct attribute *ipw_sysfs_entries[] = {
11551	&dev_attr_rf_kill.attr,
11552	&dev_attr_direct_dword.attr,
11553	&dev_attr_indirect_byte.attr,
11554	&dev_attr_indirect_dword.attr,
11555	&dev_attr_mem_gpio_reg.attr,
11556	&dev_attr_command_event_reg.attr,
11557	&dev_attr_nic_type.attr,
11558	&dev_attr_status.attr,
11559	&dev_attr_cfg.attr,
11560	&dev_attr_error.attr,
11561	&dev_attr_event_log.attr,
11562	&dev_attr_cmd_log.attr,
11563	&dev_attr_eeprom_delay.attr,
11564	&dev_attr_ucode_version.attr,
11565	&dev_attr_rtc.attr,
11566	&dev_attr_scan_age.attr,
11567	&dev_attr_led.attr,
11568	&dev_attr_speed_scan.attr,
11569	&dev_attr_net_stats.attr,
11570	&dev_attr_channels.attr,
11571#ifdef CONFIG_IPW2200_PROMISCUOUS
11572	&dev_attr_rtap_iface.attr,
11573	&dev_attr_rtap_filter.attr,
11574#endif
11575	NULL
11576};
11577
11578static struct attribute_group ipw_attribute_group = {
11579	.name = NULL,		/* put in device directory */
11580	.attrs = ipw_sysfs_entries,
11581};
11582
11583#ifdef CONFIG_IPW2200_PROMISCUOUS
11584static int ipw_prom_open(struct net_device *dev)
11585{
11586	struct ipw_prom_priv *prom_priv = libipw_priv(dev);
11587	struct ipw_priv *priv = prom_priv->priv;
11588
11589	IPW_DEBUG_INFO("prom dev->open\n");
11590	netif_carrier_off(dev);
11591
11592	if (priv->ieee->iw_mode != IW_MODE_MONITOR) {
11593		priv->sys_config.accept_all_data_frames = 1;
11594		priv->sys_config.accept_non_directed_frames = 1;
11595		priv->sys_config.accept_all_mgmt_bcpr = 1;
11596		priv->sys_config.accept_all_mgmt_frames = 1;
11597
11598		ipw_send_system_config(priv);
11599	}
11600
11601	return 0;
11602}
11603
11604static int ipw_prom_stop(struct net_device *dev)
11605{
11606	struct ipw_prom_priv *prom_priv = libipw_priv(dev);
11607	struct ipw_priv *priv = prom_priv->priv;
11608
11609	IPW_DEBUG_INFO("prom dev->stop\n");
11610
11611	if (priv->ieee->iw_mode != IW_MODE_MONITOR) {
11612		priv->sys_config.accept_all_data_frames = 0;
11613		priv->sys_config.accept_non_directed_frames = 0;
11614		priv->sys_config.accept_all_mgmt_bcpr = 0;
11615		priv->sys_config.accept_all_mgmt_frames = 0;
11616
11617		ipw_send_system_config(priv);
11618	}
11619
11620	return 0;
11621}
11622
11623static netdev_tx_t ipw_prom_hard_start_xmit(struct sk_buff *skb,
11624					    struct net_device *dev)
11625{
11626	IPW_DEBUG_INFO("prom dev->xmit\n");
11627	dev_kfree_skb(skb);
11628	return NETDEV_TX_OK;
11629}
11630
11631static const struct net_device_ops ipw_prom_netdev_ops = {
11632	.ndo_open 		= ipw_prom_open,
11633	.ndo_stop		= ipw_prom_stop,
11634	.ndo_start_xmit		= ipw_prom_hard_start_xmit,
11635	.ndo_change_mtu		= libipw_change_mtu,
11636	.ndo_set_mac_address 	= eth_mac_addr,
11637	.ndo_validate_addr	= eth_validate_addr,
11638};
11639
11640static int ipw_prom_alloc(struct ipw_priv *priv)
11641{
11642	int rc = 0;
11643
11644	if (priv->prom_net_dev)
11645		return -EPERM;
11646
11647	priv->prom_net_dev = alloc_libipw(sizeof(struct ipw_prom_priv), 1);
11648	if (priv->prom_net_dev == NULL)
11649		return -ENOMEM;
11650
11651	priv->prom_priv = libipw_priv(priv->prom_net_dev);
11652	priv->prom_priv->ieee = netdev_priv(priv->prom_net_dev);
11653	priv->prom_priv->priv = priv;
11654
11655	strcpy(priv->prom_net_dev->name, "rtap%d");
11656	memcpy(priv->prom_net_dev->dev_addr, priv->mac_addr, ETH_ALEN);
11657
11658	priv->prom_net_dev->type = ARPHRD_IEEE80211_RADIOTAP;
11659	priv->prom_net_dev->netdev_ops = &ipw_prom_netdev_ops;
11660
11661	priv->prom_priv->ieee->iw_mode = IW_MODE_MONITOR;
11662	SET_NETDEV_DEV(priv->prom_net_dev, &priv->pci_dev->dev);
11663
11664	rc = register_netdev(priv->prom_net_dev);
11665	if (rc) {
11666		free_libipw(priv->prom_net_dev, 1);
11667		priv->prom_net_dev = NULL;
11668		return rc;
11669	}
11670
11671	return 0;
11672}
11673
11674static void ipw_prom_free(struct ipw_priv *priv)
11675{
11676	if (!priv->prom_net_dev)
11677		return;
11678
11679	unregister_netdev(priv->prom_net_dev);
11680	free_libipw(priv->prom_net_dev, 1);
11681
11682	priv->prom_net_dev = NULL;
11683}
11684
11685#endif
11686
11687static const struct net_device_ops ipw_netdev_ops = {
11688	.ndo_init		= ipw_net_init,
11689	.ndo_open		= ipw_net_open,
11690	.ndo_stop		= ipw_net_stop,
11691	.ndo_set_multicast_list	= ipw_net_set_multicast_list,
11692	.ndo_set_mac_address	= ipw_net_set_mac_address,
11693	.ndo_start_xmit		= libipw_xmit,
11694	.ndo_change_mtu		= libipw_change_mtu,
11695	.ndo_validate_addr	= eth_validate_addr,
11696};
11697
11698static int __devinit ipw_pci_probe(struct pci_dev *pdev,
11699				   const struct pci_device_id *ent)
11700{
11701	int err = 0;
11702	struct net_device *net_dev;
11703	void __iomem *base;
11704	u32 length, val;
11705	struct ipw_priv *priv;
11706	int i;
11707
11708	net_dev = alloc_libipw(sizeof(struct ipw_priv), 0);
11709	if (net_dev == NULL) {
11710		err = -ENOMEM;
11711		goto out;
11712	}
11713
11714	priv = libipw_priv(net_dev);
11715	priv->ieee = netdev_priv(net_dev);
11716
11717	priv->net_dev = net_dev;
11718	priv->pci_dev = pdev;
11719	ipw_debug_level = debug;
11720	spin_lock_init(&priv->irq_lock);
11721	spin_lock_init(&priv->lock);
11722	for (i = 0; i < IPW_IBSS_MAC_HASH_SIZE; i++)
11723		INIT_LIST_HEAD(&priv->ibss_mac_hash[i]);
11724
11725	mutex_init(&priv->mutex);
11726	if (pci_enable_device(pdev)) {
11727		err = -ENODEV;
11728		goto out_free_libipw;
11729	}
11730
11731	pci_set_master(pdev);
11732
11733	err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
11734	if (!err)
11735		err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
11736	if (err) {
11737		printk(KERN_WARNING DRV_NAME ": No suitable DMA available.\n");
11738		goto out_pci_disable_device;
11739	}
11740
11741	pci_set_drvdata(pdev, priv);
11742
11743	err = pci_request_regions(pdev, DRV_NAME);
11744	if (err)
11745		goto out_pci_disable_device;
11746
11747	/* We disable the RETRY_TIMEOUT register (0x41) to keep
11748	 * PCI Tx retries from interfering with C3 CPU state */
11749	pci_read_config_dword(pdev, 0x40, &val);
11750	if ((val & 0x0000ff00) != 0)
11751		pci_write_config_dword(pdev, 0x40, val & 0xffff00ff);
11752
11753	length = pci_resource_len(pdev, 0);
11754	priv->hw_len = length;
11755
11756	base = pci_ioremap_bar(pdev, 0);
11757	if (!base) {
11758		err = -ENODEV;
11759		goto out_pci_release_regions;
11760	}
11761
11762	priv->hw_base = base;
11763	IPW_DEBUG_INFO("pci_resource_len = 0x%08x\n", length);
11764	IPW_DEBUG_INFO("pci_resource_base = %p\n", base);
11765
11766	err = ipw_setup_deferred_work(priv);
11767	if (err) {
11768		IPW_ERROR("Unable to setup deferred work\n");
11769		goto out_iounmap;
11770	}
11771
11772	ipw_sw_reset(priv, 1);
11773
11774	err = request_irq(pdev->irq, ipw_isr, IRQF_SHARED, DRV_NAME, priv);
11775	if (err) {
11776		IPW_ERROR("Error allocating IRQ %d\n", pdev->irq);
11777		goto out_destroy_workqueue;
11778	}
11779
11780	SET_NETDEV_DEV(net_dev, &pdev->dev);
11781
11782	mutex_lock(&priv->mutex);
11783
11784	priv->ieee->hard_start_xmit = ipw_net_hard_start_xmit;
11785	priv->ieee->set_security = shim__set_security;
11786	priv->ieee->is_queue_full = ipw_net_is_queue_full;
11787
11788#ifdef CONFIG_IPW2200_QOS
11789	priv->ieee->is_qos_active = ipw_is_qos_active;
11790	priv->ieee->handle_probe_response = ipw_handle_beacon;
11791	priv->ieee->handle_beacon = ipw_handle_probe_response;
11792	priv->ieee->handle_assoc_response = ipw_handle_assoc_response;
11793#endif				/* CONFIG_IPW2200_QOS */
11794
11795	priv->ieee->perfect_rssi = -20;
11796	priv->ieee->worst_rssi = -85;
11797
11798	net_dev->netdev_ops = &ipw_netdev_ops;
11799	priv->wireless_data.spy_data = &priv->ieee->spy_data;
11800	net_dev->wireless_data = &priv->wireless_data;
11801	net_dev->wireless_handlers = &ipw_wx_handler_def;
11802	net_dev->ethtool_ops = &ipw_ethtool_ops;
11803	net_dev->irq = pdev->irq;
11804	net_dev->base_addr = (unsigned long)priv->hw_base;
11805	net_dev->mem_start = pci_resource_start(pdev, 0);
11806	net_dev->mem_end = net_dev->mem_start + pci_resource_len(pdev, 0) - 1;
11807
11808	err = sysfs_create_group(&pdev->dev.kobj, &ipw_attribute_group);
11809	if (err) {
11810		IPW_ERROR("failed to create sysfs device attributes\n");
11811		mutex_unlock(&priv->mutex);
11812		goto out_release_irq;
11813	}
11814
11815	mutex_unlock(&priv->mutex);
11816	err = register_netdev(net_dev);
11817	if (err) {
11818		IPW_ERROR("failed to register network device\n");
11819		goto out_remove_sysfs;
11820	}
11821
11822#ifdef CONFIG_IPW2200_PROMISCUOUS
11823	if (rtap_iface) {
11824	        err = ipw_prom_alloc(priv);
11825		if (err) {
11826			IPW_ERROR("Failed to register promiscuous network "
11827				  "device (error %d).\n", err);
11828			unregister_netdev(priv->net_dev);
11829			goto out_remove_sysfs;
11830		}
11831	}
11832#endif
11833
11834	printk(KERN_INFO DRV_NAME ": Detected geography %s (%d 802.11bg "
11835	       "channels, %d 802.11a channels)\n",
11836	       priv->ieee->geo.name, priv->ieee->geo.bg_channels,
11837	       priv->ieee->geo.a_channels);
11838
11839	return 0;
11840
11841      out_remove_sysfs:
11842	sysfs_remove_group(&pdev->dev.kobj, &ipw_attribute_group);
11843      out_release_irq:
11844	free_irq(pdev->irq, priv);
11845      out_destroy_workqueue:
11846	destroy_workqueue(priv->workqueue);
11847	priv->workqueue = NULL;
11848      out_iounmap:
11849	iounmap(priv->hw_base);
11850      out_pci_release_regions:
11851	pci_release_regions(pdev);
11852      out_pci_disable_device:
11853	pci_disable_device(pdev);
11854	pci_set_drvdata(pdev, NULL);
11855      out_free_libipw:
11856	free_libipw(priv->net_dev, 0);
11857      out:
11858	return err;
11859}
11860
11861static void __devexit ipw_pci_remove(struct pci_dev *pdev)
11862{
11863	struct ipw_priv *priv = pci_get_drvdata(pdev);
11864	struct list_head *p, *q;
11865	int i;
11866
11867	if (!priv)
11868		return;
11869
11870	mutex_lock(&priv->mutex);
11871
11872	priv->status |= STATUS_EXIT_PENDING;
11873	ipw_down(priv);
11874	sysfs_remove_group(&pdev->dev.kobj, &ipw_attribute_group);
11875
11876	mutex_unlock(&priv->mutex);
11877
11878	unregister_netdev(priv->net_dev);
11879
11880	if (priv->rxq) {
11881		ipw_rx_queue_free(priv, priv->rxq);
11882		priv->rxq = NULL;
11883	}
11884	ipw_tx_queue_free(priv);
11885
11886	if (priv->cmdlog) {
11887		kfree(priv->cmdlog);
11888		priv->cmdlog = NULL;
11889	}
11890	/* ipw_down will ensure that there is no more pending work
11891	 * in the workqueue's, so we can safely remove them now. */
11892	cancel_delayed_work(&priv->adhoc_check);
11893	cancel_delayed_work(&priv->gather_stats);
11894	cancel_delayed_work(&priv->request_scan);
11895	cancel_delayed_work(&priv->request_direct_scan);
11896	cancel_delayed_work(&priv->request_passive_scan);
11897	cancel_delayed_work(&priv->scan_event);
11898	cancel_delayed_work(&priv->rf_kill);
11899	cancel_delayed_work(&priv->scan_check);
11900	destroy_workqueue(priv->workqueue);
11901	priv->workqueue = NULL;
11902
11903	/* Free MAC hash list for ADHOC */
11904	for (i = 0; i < IPW_IBSS_MAC_HASH_SIZE; i++) {
11905		list_for_each_safe(p, q, &priv->ibss_mac_hash[i]) {
11906			list_del(p);
11907			kfree(list_entry(p, struct ipw_ibss_seq, list));
11908		}
11909	}
11910
11911	kfree(priv->error);
11912	priv->error = NULL;
11913
11914#ifdef CONFIG_IPW2200_PROMISCUOUS
11915	ipw_prom_free(priv);
11916#endif
11917
11918	free_irq(pdev->irq, priv);
11919	iounmap(priv->hw_base);
11920	pci_release_regions(pdev);
11921	pci_disable_device(pdev);
11922	pci_set_drvdata(pdev, NULL);
11923	/* wiphy_unregister needs to be here, before free_libipw */
11924	wiphy_unregister(priv->ieee->wdev.wiphy);
11925	kfree(priv->ieee->a_band.channels);
11926	kfree(priv->ieee->bg_band.channels);
11927	free_libipw(priv->net_dev, 0);
11928	free_firmware();
11929}
11930
11931#ifdef CONFIG_PM
11932static int ipw_pci_suspend(struct pci_dev *pdev, pm_message_t state)
11933{
11934	struct ipw_priv *priv = pci_get_drvdata(pdev);
11935	struct net_device *dev = priv->net_dev;
11936
11937	printk(KERN_INFO "%s: Going into suspend...\n", dev->name);
11938
11939	/* Take down the device; powers it off, etc. */
11940	ipw_down(priv);
11941
11942	/* Remove the PRESENT state of the device */
11943	netif_device_detach(dev);
11944
11945	pci_save_state(pdev);
11946	pci_disable_device(pdev);
11947	pci_set_power_state(pdev, pci_choose_state(pdev, state));
11948
11949	priv->suspend_at = get_seconds();
11950
11951	return 0;
11952}
11953
11954static int ipw_pci_resume(struct pci_dev *pdev)
11955{
11956	struct ipw_priv *priv = pci_get_drvdata(pdev);
11957	struct net_device *dev = priv->net_dev;
11958	int err;
11959	u32 val;
11960
11961	printk(KERN_INFO "%s: Coming out of suspend...\n", dev->name);
11962
11963	pci_set_power_state(pdev, PCI_D0);
11964	err = pci_enable_device(pdev);
11965	if (err) {
11966		printk(KERN_ERR "%s: pci_enable_device failed on resume\n",
11967		       dev->name);
11968		return err;
11969	}
11970	pci_restore_state(pdev);
11971
11972	/*
11973	 * Suspend/Resume resets the PCI configuration space, so we have to
11974	 * re-disable the RETRY_TIMEOUT register (0x41) to keep PCI Tx retries
11975	 * from interfering with C3 CPU state. pci_restore_state won't help
11976	 * here since it only restores the first 64 bytes pci config header.
11977	 */
11978	pci_read_config_dword(pdev, 0x40, &val);
11979	if ((val & 0x0000ff00) != 0)
11980		pci_write_config_dword(pdev, 0x40, val & 0xffff00ff);
11981
11982	/* Set the device back into the PRESENT state; this will also wake
11983	 * the queue of needed */
11984	netif_device_attach(dev);
11985
11986	priv->suspend_time = get_seconds() - priv->suspend_at;
11987
11988	/* Bring the device back up */
11989	queue_work(priv->workqueue, &priv->up);
11990
11991	return 0;
11992}
11993#endif
11994
11995static void ipw_pci_shutdown(struct pci_dev *pdev)
11996{
11997	struct ipw_priv *priv = pci_get_drvdata(pdev);
11998
11999	/* Take down the device; powers it off, etc. */
12000	ipw_down(priv);
12001
12002	pci_disable_device(pdev);
12003}
12004
12005/* driver initialization stuff */
12006static struct pci_driver ipw_driver = {
12007	.name = DRV_NAME,
12008	.id_table = card_ids,
12009	.probe = ipw_pci_probe,
12010	.remove = __devexit_p(ipw_pci_remove),
12011#ifdef CONFIG_PM
12012	.suspend = ipw_pci_suspend,
12013	.resume = ipw_pci_resume,
12014#endif
12015	.shutdown = ipw_pci_shutdown,
12016};
12017
12018static int __init ipw_init(void)
12019{
12020	int ret;
12021
12022	printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION ", " DRV_VERSION "\n");
12023	printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
12024
12025	ret = pci_register_driver(&ipw_driver);
12026	if (ret) {
12027		IPW_ERROR("Unable to initialize PCI module\n");
12028		return ret;
12029	}
12030
12031	ret = driver_create_file(&ipw_driver.driver, &driver_attr_debug_level);
12032	if (ret) {
12033		IPW_ERROR("Unable to create driver sysfs file\n");
12034		pci_unregister_driver(&ipw_driver);
12035		return ret;
12036	}
12037
12038	return ret;
12039}
12040
12041static void __exit ipw_exit(void)
12042{
12043	driver_remove_file(&ipw_driver.driver, &driver_attr_debug_level);
12044	pci_unregister_driver(&ipw_driver);
12045}
12046
12047module_param(disable, int, 0444);
12048MODULE_PARM_DESC(disable, "manually disable the radio (default 0 [radio on])");
12049
12050module_param(associate, int, 0444);
12051MODULE_PARM_DESC(associate, "auto associate when scanning (default off)");
12052
12053module_param(auto_create, int, 0444);
12054MODULE_PARM_DESC(auto_create, "auto create adhoc network (default on)");
12055
12056module_param_named(led, led_support, int, 0444);
12057MODULE_PARM_DESC(led, "enable led control on some systems (default 1 on)");
12058
12059module_param(debug, int, 0444);
12060MODULE_PARM_DESC(debug, "debug output mask");
12061
12062module_param_named(channel, default_channel, int, 0444);
12063MODULE_PARM_DESC(channel, "channel to limit associate to (default 0 [ANY])");
12064
12065#ifdef CONFIG_IPW2200_PROMISCUOUS
12066module_param(rtap_iface, int, 0444);
12067MODULE_PARM_DESC(rtap_iface, "create the rtap interface (1 - create, default 0)");
12068#endif
12069
12070#ifdef CONFIG_IPW2200_QOS
12071module_param(qos_enable, int, 0444);
12072MODULE_PARM_DESC(qos_enable, "enable all QoS functionalitis");
12073
12074module_param(qos_burst_enable, int, 0444);
12075MODULE_PARM_DESC(qos_burst_enable, "enable QoS burst mode");
12076
12077module_param(qos_no_ack_mask, int, 0444);
12078MODULE_PARM_DESC(qos_no_ack_mask, "mask Tx_Queue to no ack");
12079
12080module_param(burst_duration_CCK, int, 0444);
12081MODULE_PARM_DESC(burst_duration_CCK, "set CCK burst value");
12082
12083module_param(burst_duration_OFDM, int, 0444);
12084MODULE_PARM_DESC(burst_duration_OFDM, "set OFDM burst value");
12085#endif				/* CONFIG_IPW2200_QOS */
12086
12087#ifdef CONFIG_IPW2200_MONITOR
12088module_param_named(mode, network_mode, int, 0444);
12089MODULE_PARM_DESC(mode, "network mode (0=BSS,1=IBSS,2=Monitor)");
12090#else
12091module_param_named(mode, network_mode, int, 0444);
12092MODULE_PARM_DESC(mode, "network mode (0=BSS,1=IBSS)");
12093#endif
12094
12095module_param(bt_coexist, int, 0444);
12096MODULE_PARM_DESC(bt_coexist, "enable bluetooth coexistence (default off)");
12097
12098module_param(hwcrypto, int, 0444);
12099MODULE_PARM_DESC(hwcrypto, "enable hardware crypto (default off)");
12100
12101module_param(cmdlog, int, 0444);
12102MODULE_PARM_DESC(cmdlog,
12103		 "allocate a ring buffer for logging firmware commands");
12104
12105module_param(roaming, int, 0444);
12106MODULE_PARM_DESC(roaming, "enable roaming support (default on)");
12107
12108module_param(antenna, int, 0444);
12109MODULE_PARM_DESC(antenna, "select antenna 1=Main, 3=Aux, default 0 [both], 2=slow_diversity (choose the one with lower background noise)");
12110
12111module_exit(ipw_exit);
12112module_init(ipw_init);
12113