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