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