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