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