Merge branch 'master' of master.kernel.org:/pub/scm/linux/kernel/git/davem/net-2.6
[linux-2.6.git] / drivers / net / wireless / ipw2x00 / ipw2200.c
1 /******************************************************************************
2
3   Copyright(c) 2003 - 2006 Intel Corporation. All rights reserved.
4
5   802.11 status code portion of this file from ethereal-0.10.6:
6     Copyright 2000, Axis Communications AB
7     Ethereal - Network traffic analyzer
8     By Gerald Combs <gerald@ethereal.com>
9     Copyright 1998 Gerald Combs
10
11   This program is free software; you can redistribute it and/or modify it
12   under the terms of version 2 of the GNU General Public License as
13   published by the Free Software Foundation.
14
15   This program is distributed in the hope that it will be useful, but WITHOUT
16   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
18   more details.
19
20   You should have received a copy of the GNU General Public License along with
21   this program; if not, write to the Free Software Foundation, Inc., 59
22   Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23
24   The full GNU General Public License is included in this distribution in the
25   file called LICENSE.
26
27   Contact Information:
28   Intel Linux Wireless <ilw@linux.intel.com>
29   Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
30
31 ******************************************************************************/
32
33 #include "ipw2200.h"
34
35
36 #ifndef KBUILD_EXTMOD
37 #define VK "k"
38 #else
39 #define VK
40 #endif
41
42 #ifdef CONFIG_IPW2200_DEBUG
43 #define VD "d"
44 #else
45 #define VD
46 #endif
47
48 #ifdef CONFIG_IPW2200_MONITOR
49 #define VM "m"
50 #else
51 #define VM
52 #endif
53
54 #ifdef CONFIG_IPW2200_PROMISCUOUS
55 #define VP "p"
56 #else
57 #define VP
58 #endif
59
60 #ifdef CONFIG_IPW2200_RADIOTAP
61 #define VR "r"
62 #else
63 #define VR
64 #endif
65
66 #ifdef CONFIG_IPW2200_QOS
67 #define VQ "q"
68 #else
69 #define VQ
70 #endif
71
72 #define IPW2200_VERSION "1.2.2" VK VD VM VP VR VQ
73 #define DRV_DESCRIPTION "Intel(R) PRO/Wireless 2200/2915 Network Driver"
74 #define DRV_COPYRIGHT   "Copyright(c) 2003-2006 Intel Corporation"
75 #define DRV_VERSION     IPW2200_VERSION
76
77 #define ETH_P_80211_STATS (ETH_P_80211_RAW + 1)
78
79 MODULE_DESCRIPTION(DRV_DESCRIPTION);
80 MODULE_VERSION(DRV_VERSION);
81 MODULE_AUTHOR(DRV_COPYRIGHT);
82 MODULE_LICENSE("GPL");
83
84 static int cmdlog = 0;
85 static int debug = 0;
86 static int default_channel = 0;
87 static int network_mode = 0;
88
89 static u32 ipw_debug_level;
90 static int associate;
91 static int auto_create = 1;
92 static int led_support = 0;
93 static int disable = 0;
94 static int bt_coexist = 0;
95 static int hwcrypto = 0;
96 static int roaming = 1;
97 static const char ipw_modes[] = {
98         'a', 'b', 'g', '?'
99 };
100 static int antenna = CFG_SYS_ANTENNA_BOTH;
101
102 #ifdef CONFIG_IPW2200_PROMISCUOUS
103 static int rtap_iface = 0;     /* def: 0 -- do not create rtap interface */
104 #endif
105
106
107 #ifdef CONFIG_IPW2200_QOS
108 static int qos_enable = 0;
109 static int qos_burst_enable = 0;
110 static int qos_no_ack_mask = 0;
111 static int burst_duration_CCK = 0;
112 static int burst_duration_OFDM = 0;
113
114 static struct libipw_qos_parameters def_qos_parameters_OFDM = {
115         {QOS_TX0_CW_MIN_OFDM, QOS_TX1_CW_MIN_OFDM, QOS_TX2_CW_MIN_OFDM,
116          QOS_TX3_CW_MIN_OFDM},
117         {QOS_TX0_CW_MAX_OFDM, QOS_TX1_CW_MAX_OFDM, QOS_TX2_CW_MAX_OFDM,
118          QOS_TX3_CW_MAX_OFDM},
119         {QOS_TX0_AIFS, QOS_TX1_AIFS, QOS_TX2_AIFS, QOS_TX3_AIFS},
120         {QOS_TX0_ACM, QOS_TX1_ACM, QOS_TX2_ACM, QOS_TX3_ACM},
121         {QOS_TX0_TXOP_LIMIT_OFDM, QOS_TX1_TXOP_LIMIT_OFDM,
122          QOS_TX2_TXOP_LIMIT_OFDM, QOS_TX3_TXOP_LIMIT_OFDM}
123 };
124
125 static struct libipw_qos_parameters def_qos_parameters_CCK = {
126         {QOS_TX0_CW_MIN_CCK, QOS_TX1_CW_MIN_CCK, QOS_TX2_CW_MIN_CCK,
127          QOS_TX3_CW_MIN_CCK},
128         {QOS_TX0_CW_MAX_CCK, QOS_TX1_CW_MAX_CCK, QOS_TX2_CW_MAX_CCK,
129          QOS_TX3_CW_MAX_CCK},
130         {QOS_TX0_AIFS, QOS_TX1_AIFS, QOS_TX2_AIFS, QOS_TX3_AIFS},
131         {QOS_TX0_ACM, QOS_TX1_ACM, QOS_TX2_ACM, QOS_TX3_ACM},
132         {QOS_TX0_TXOP_LIMIT_CCK, QOS_TX1_TXOP_LIMIT_CCK, QOS_TX2_TXOP_LIMIT_CCK,
133          QOS_TX3_TXOP_LIMIT_CCK}
134 };
135
136 static struct libipw_qos_parameters def_parameters_OFDM = {
137         {DEF_TX0_CW_MIN_OFDM, DEF_TX1_CW_MIN_OFDM, DEF_TX2_CW_MIN_OFDM,
138          DEF_TX3_CW_MIN_OFDM},
139         {DEF_TX0_CW_MAX_OFDM, DEF_TX1_CW_MAX_OFDM, DEF_TX2_CW_MAX_OFDM,
140          DEF_TX3_CW_MAX_OFDM},
141         {DEF_TX0_AIFS, DEF_TX1_AIFS, DEF_TX2_AIFS, DEF_TX3_AIFS},
142         {DEF_TX0_ACM, DEF_TX1_ACM, DEF_TX2_ACM, DEF_TX3_ACM},
143         {DEF_TX0_TXOP_LIMIT_OFDM, DEF_TX1_TXOP_LIMIT_OFDM,
144          DEF_TX2_TXOP_LIMIT_OFDM, DEF_TX3_TXOP_LIMIT_OFDM}
145 };
146
147 static struct libipw_qos_parameters def_parameters_CCK = {
148         {DEF_TX0_CW_MIN_CCK, DEF_TX1_CW_MIN_CCK, DEF_TX2_CW_MIN_CCK,
149          DEF_TX3_CW_MIN_CCK},
150         {DEF_TX0_CW_MAX_CCK, DEF_TX1_CW_MAX_CCK, DEF_TX2_CW_MAX_CCK,
151          DEF_TX3_CW_MAX_CCK},
152         {DEF_TX0_AIFS, DEF_TX1_AIFS, DEF_TX2_AIFS, DEF_TX3_AIFS},
153         {DEF_TX0_ACM, DEF_TX1_ACM, DEF_TX2_ACM, DEF_TX3_ACM},
154         {DEF_TX0_TXOP_LIMIT_CCK, DEF_TX1_TXOP_LIMIT_CCK, DEF_TX2_TXOP_LIMIT_CCK,
155          DEF_TX3_TXOP_LIMIT_CCK}
156 };
157
158 static u8 qos_oui[QOS_OUI_LEN] = { 0x00, 0x50, 0xF2 };
159
160 static int from_priority_to_tx_queue[] = {
161         IPW_TX_QUEUE_1, IPW_TX_QUEUE_2, IPW_TX_QUEUE_2, IPW_TX_QUEUE_1,
162         IPW_TX_QUEUE_3, IPW_TX_QUEUE_3, IPW_TX_QUEUE_4, IPW_TX_QUEUE_4
163 };
164
165 static u32 ipw_qos_get_burst_duration(struct ipw_priv *priv);
166
167 static int ipw_send_qos_params_command(struct ipw_priv *priv, struct libipw_qos_parameters
168                                        *qos_param);
169 static int ipw_send_qos_info_command(struct ipw_priv *priv, struct libipw_qos_information_element
170                                      *qos_param);
171 #endif                          /* CONFIG_IPW2200_QOS */
172
173 static struct iw_statistics *ipw_get_wireless_stats(struct net_device *dev);
174 static void ipw_remove_current_network(struct ipw_priv *priv);
175 static void ipw_rx(struct ipw_priv *priv);
176 static int ipw_queue_tx_reclaim(struct ipw_priv *priv,
177                                 struct clx2_tx_queue *txq, int qindex);
178 static int ipw_queue_reset(struct ipw_priv *priv);
179
180 static int ipw_queue_tx_hcmd(struct ipw_priv *priv, int hcmd, void *buf,
181                              int len, int sync);
182
183 static void ipw_tx_queue_free(struct ipw_priv *);
184
185 static struct ipw_rx_queue *ipw_rx_queue_alloc(struct ipw_priv *);
186 static void ipw_rx_queue_free(struct ipw_priv *, struct ipw_rx_queue *);
187 static void ipw_rx_queue_replenish(void *);
188 static int ipw_up(struct ipw_priv *);
189 static void ipw_bg_up(struct work_struct *work);
190 static void ipw_down(struct ipw_priv *);
191 static void ipw_bg_down(struct work_struct *work);
192 static int ipw_config(struct ipw_priv *);
193 static int init_supported_rates(struct ipw_priv *priv,
194                                 struct ipw_supported_rates *prates);
195 static void ipw_set_hwcrypto_keys(struct ipw_priv *);
196 static void ipw_send_wep_keys(struct ipw_priv *, int);
197
198 static int snprint_line(char *buf, size_t count,
199                         const u8 * data, u32 len, u32 ofs)
200 {
201         int out, i, j, l;
202         char c;
203
204         out = snprintf(buf, count, "%08X", ofs);
205
206         for (l = 0, i = 0; i < 2; i++) {
207                 out += snprintf(buf + out, count - out, " ");
208                 for (j = 0; j < 8 && l < len; j++, l++)
209                         out += snprintf(buf + out, count - out, "%02X ",
210                                         data[(i * 8 + j)]);
211                 for (; j < 8; j++)
212                         out += snprintf(buf + out, count - out, "   ");
213         }
214
215         out += snprintf(buf + out, count - out, " ");
216         for (l = 0, i = 0; i < 2; i++) {
217                 out += snprintf(buf + out, count - out, " ");
218                 for (j = 0; j < 8 && l < len; j++, l++) {
219                         c = data[(i * 8 + j)];
220                         if (!isascii(c) || !isprint(c))
221                                 c = '.';
222
223                         out += snprintf(buf + out, count - out, "%c", c);
224                 }
225
226                 for (; j < 8; j++)
227                         out += snprintf(buf + out, count - out, " ");
228         }
229
230         return out;
231 }
232
233 static void printk_buf(int level, const u8 * data, u32 len)
234 {
235         char line[81];
236         u32 ofs = 0;
237         if (!(ipw_debug_level & level))
238                 return;
239
240         while (len) {
241                 snprint_line(line, sizeof(line), &data[ofs],
242                              min(len, 16U), ofs);
243                 printk(KERN_DEBUG "%s\n", line);
244                 ofs += 16;
245                 len -= min(len, 16U);
246         }
247 }
248
249 static int snprintk_buf(u8 * output, size_t size, const u8 * data, size_t len)
250 {
251         size_t out = size;
252         u32 ofs = 0;
253         int total = 0;
254
255         while (size && len) {
256                 out = snprint_line(output, size, &data[ofs],
257                                    min_t(size_t, len, 16U), ofs);
258
259                 ofs += 16;
260                 output += out;
261                 size -= out;
262                 len -= min_t(size_t, len, 16U);
263                 total += out;
264         }
265         return total;
266 }
267
268 /* alias for 32-bit indirect read (for SRAM/reg above 4K), with debug wrapper */
269 static u32 _ipw_read_reg32(struct ipw_priv *priv, u32 reg);
270 #define ipw_read_reg32(a, b) _ipw_read_reg32(a, b)
271
272 /* alias for 8-bit indirect read (for SRAM/reg above 4K), with debug wrapper */
273 static u8 _ipw_read_reg8(struct ipw_priv *ipw, u32 reg);
274 #define ipw_read_reg8(a, b) _ipw_read_reg8(a, b)
275
276 /* 8-bit indirect write (for SRAM/reg above 4K), with debug wrapper */
277 static void _ipw_write_reg8(struct ipw_priv *priv, u32 reg, u8 value);
278 static inline void ipw_write_reg8(struct ipw_priv *a, u32 b, u8 c)
279 {
280         IPW_DEBUG_IO("%s %d: write_indirect8(0x%08X, 0x%08X)\n", __FILE__,
281                      __LINE__, (u32) (b), (u32) (c));
282         _ipw_write_reg8(a, b, c);
283 }
284
285 /* 16-bit indirect write (for SRAM/reg above 4K), with debug wrapper */
286 static void _ipw_write_reg16(struct ipw_priv *priv, u32 reg, u16 value);
287 static inline void ipw_write_reg16(struct ipw_priv *a, u32 b, u16 c)
288 {
289         IPW_DEBUG_IO("%s %d: write_indirect16(0x%08X, 0x%08X)\n", __FILE__,
290                      __LINE__, (u32) (b), (u32) (c));
291         _ipw_write_reg16(a, b, c);
292 }
293
294 /* 32-bit indirect write (for SRAM/reg above 4K), with debug wrapper */
295 static void _ipw_write_reg32(struct ipw_priv *priv, u32 reg, u32 value);
296 static inline void ipw_write_reg32(struct ipw_priv *a, u32 b, u32 c)
297 {
298         IPW_DEBUG_IO("%s %d: write_indirect32(0x%08X, 0x%08X)\n", __FILE__,
299                      __LINE__, (u32) (b), (u32) (c));
300         _ipw_write_reg32(a, b, c);
301 }
302
303 /* 8-bit direct write (low 4K) */
304 static inline void _ipw_write8(struct ipw_priv *ipw, unsigned long ofs,
305                 u8 val)
306 {
307         writeb(val, ipw->hw_base + ofs);
308 }
309
310 /* 8-bit direct write (for low 4K of SRAM/regs), with debug wrapper */
311 #define ipw_write8(ipw, ofs, val) do { \
312         IPW_DEBUG_IO("%s %d: write_direct8(0x%08X, 0x%08X)\n", __FILE__, \
313                         __LINE__, (u32)(ofs), (u32)(val)); \
314         _ipw_write8(ipw, ofs, val); \
315 } while (0)
316
317 /* 16-bit direct write (low 4K) */
318 static inline void _ipw_write16(struct ipw_priv *ipw, unsigned long ofs,
319                 u16 val)
320 {
321         writew(val, ipw->hw_base + ofs);
322 }
323
324 /* 16-bit direct write (for low 4K of SRAM/regs), with debug wrapper */
325 #define ipw_write16(ipw, ofs, val) do { \
326         IPW_DEBUG_IO("%s %d: write_direct16(0x%08X, 0x%08X)\n", __FILE__, \
327                         __LINE__, (u32)(ofs), (u32)(val)); \
328         _ipw_write16(ipw, ofs, val); \
329 } while (0)
330
331 /* 32-bit direct write (low 4K) */
332 static inline void _ipw_write32(struct ipw_priv *ipw, unsigned long ofs,
333                 u32 val)
334 {
335         writel(val, ipw->hw_base + ofs);
336 }
337
338 /* 32-bit direct write (for low 4K of SRAM/regs), with debug wrapper */
339 #define ipw_write32(ipw, ofs, val) do { \
340         IPW_DEBUG_IO("%s %d: write_direct32(0x%08X, 0x%08X)\n", __FILE__, \
341                         __LINE__, (u32)(ofs), (u32)(val)); \
342         _ipw_write32(ipw, ofs, val); \
343 } while (0)
344
345 /* 8-bit direct read (low 4K) */
346 static inline u8 _ipw_read8(struct ipw_priv *ipw, unsigned long ofs)
347 {
348         return readb(ipw->hw_base + ofs);
349 }
350
351 /* alias to 8-bit direct read (low 4K of SRAM/regs), with debug wrapper */
352 #define ipw_read8(ipw, ofs) ({ \
353         IPW_DEBUG_IO("%s %d: read_direct8(0x%08X)\n", __FILE__, __LINE__, \
354                         (u32)(ofs)); \
355         _ipw_read8(ipw, ofs); \
356 })
357
358 /* 16-bit direct read (low 4K) */
359 static inline u16 _ipw_read16(struct ipw_priv *ipw, unsigned long ofs)
360 {
361         return readw(ipw->hw_base + ofs);
362 }
363
364 /* alias to 16-bit direct read (low 4K of SRAM/regs), with debug wrapper */
365 #define ipw_read16(ipw, ofs) ({ \
366         IPW_DEBUG_IO("%s %d: read_direct16(0x%08X)\n", __FILE__, __LINE__, \
367                         (u32)(ofs)); \
368         _ipw_read16(ipw, ofs); \
369 })
370
371 /* 32-bit direct read (low 4K) */
372 static inline u32 _ipw_read32(struct ipw_priv *ipw, unsigned long ofs)
373 {
374         return readl(ipw->hw_base + ofs);
375 }
376
377 /* alias to 32-bit direct read (low 4K of SRAM/regs), with debug wrapper */
378 #define ipw_read32(ipw, ofs) ({ \
379         IPW_DEBUG_IO("%s %d: read_direct32(0x%08X)\n", __FILE__, __LINE__, \
380                         (u32)(ofs)); \
381         _ipw_read32(ipw, ofs); \
382 })
383
384 static void _ipw_read_indirect(struct ipw_priv *, u32, u8 *, int);
385 /* alias to multi-byte read (SRAM/regs above 4K), with debug wrapper */
386 #define ipw_read_indirect(a, b, c, d) ({ \
387         IPW_DEBUG_IO("%s %d: read_indirect(0x%08X) %u bytes\n", __FILE__, \
388                         __LINE__, (u32)(b), (u32)(d)); \
389         _ipw_read_indirect(a, b, c, d); \
390 })
391
392 /* alias to multi-byte read (SRAM/regs above 4K), with debug wrapper */
393 static void _ipw_write_indirect(struct ipw_priv *priv, u32 addr, u8 * data,
394                                 int num);
395 #define ipw_write_indirect(a, b, c, d) do { \
396         IPW_DEBUG_IO("%s %d: write_indirect(0x%08X) %u bytes\n", __FILE__, \
397                         __LINE__, (u32)(b), (u32)(d)); \
398         _ipw_write_indirect(a, b, c, d); \
399 } while (0)
400
401 /* 32-bit indirect write (above 4K) */
402 static void _ipw_write_reg32(struct ipw_priv *priv, u32 reg, u32 value)
403 {
404         IPW_DEBUG_IO(" %p : reg = 0x%8X : value = 0x%8X\n", priv, reg, value);
405         _ipw_write32(priv, IPW_INDIRECT_ADDR, reg);
406         _ipw_write32(priv, IPW_INDIRECT_DATA, value);
407 }
408
409 /* 8-bit indirect write (above 4K) */
410 static void _ipw_write_reg8(struct ipw_priv *priv, u32 reg, u8 value)
411 {
412         u32 aligned_addr = reg & IPW_INDIRECT_ADDR_MASK;        /* dword align */
413         u32 dif_len = reg - aligned_addr;
414
415         IPW_DEBUG_IO(" reg = 0x%8X : value = 0x%8X\n", reg, value);
416         _ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
417         _ipw_write8(priv, IPW_INDIRECT_DATA + dif_len, value);
418 }
419
420 /* 16-bit indirect write (above 4K) */
421 static void _ipw_write_reg16(struct ipw_priv *priv, u32 reg, u16 value)
422 {
423         u32 aligned_addr = reg & IPW_INDIRECT_ADDR_MASK;        /* dword align */
424         u32 dif_len = (reg - aligned_addr) & (~0x1ul);
425
426         IPW_DEBUG_IO(" reg = 0x%8X : value = 0x%8X\n", reg, value);
427         _ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
428         _ipw_write16(priv, IPW_INDIRECT_DATA + dif_len, value);
429 }
430
431 /* 8-bit indirect read (above 4K) */
432 static u8 _ipw_read_reg8(struct ipw_priv *priv, u32 reg)
433 {
434         u32 word;
435         _ipw_write32(priv, IPW_INDIRECT_ADDR, reg & IPW_INDIRECT_ADDR_MASK);
436         IPW_DEBUG_IO(" reg = 0x%8X : \n", reg);
437         word = _ipw_read32(priv, IPW_INDIRECT_DATA);
438         return (word >> ((reg & 0x3) * 8)) & 0xff;
439 }
440
441 /* 32-bit indirect read (above 4K) */
442 static u32 _ipw_read_reg32(struct ipw_priv *priv, u32 reg)
443 {
444         u32 value;
445
446         IPW_DEBUG_IO("%p : reg = 0x%08x\n", priv, reg);
447
448         _ipw_write32(priv, IPW_INDIRECT_ADDR, reg);
449         value = _ipw_read32(priv, IPW_INDIRECT_DATA);
450         IPW_DEBUG_IO(" reg = 0x%4X : value = 0x%4x \n", reg, value);
451         return value;
452 }
453
454 /* General purpose, no alignment requirement, iterative (multi-byte) read, */
455 /*    for area above 1st 4K of SRAM/reg space */
456 static void _ipw_read_indirect(struct ipw_priv *priv, u32 addr, u8 * buf,
457                                int num)
458 {
459         u32 aligned_addr = addr & IPW_INDIRECT_ADDR_MASK;       /* dword align */
460         u32 dif_len = addr - aligned_addr;
461         u32 i;
462
463         IPW_DEBUG_IO("addr = %i, buf = %p, num = %i\n", addr, buf, num);
464
465         if (num <= 0) {
466                 return;
467         }
468
469         /* Read the first dword (or portion) byte by byte */
470         if (unlikely(dif_len)) {
471                 _ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
472                 /* Start reading at aligned_addr + dif_len */
473                 for (i = dif_len; ((i < 4) && (num > 0)); i++, num--)
474                         *buf++ = _ipw_read8(priv, IPW_INDIRECT_DATA + i);
475                 aligned_addr += 4;
476         }
477
478         /* Read all of the middle dwords as dwords, with auto-increment */
479         _ipw_write32(priv, IPW_AUTOINC_ADDR, aligned_addr);
480         for (; num >= 4; buf += 4, aligned_addr += 4, num -= 4)
481                 *(u32 *) buf = _ipw_read32(priv, IPW_AUTOINC_DATA);
482
483         /* Read the last dword (or portion) byte by byte */
484         if (unlikely(num)) {
485                 _ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
486                 for (i = 0; num > 0; i++, num--)
487                         *buf++ = ipw_read8(priv, IPW_INDIRECT_DATA + i);
488         }
489 }
490
491 /* General purpose, no alignment requirement, iterative (multi-byte) write, */
492 /*    for area above 1st 4K of SRAM/reg space */
493 static void _ipw_write_indirect(struct ipw_priv *priv, u32 addr, u8 * buf,
494                                 int num)
495 {
496         u32 aligned_addr = addr & IPW_INDIRECT_ADDR_MASK;       /* dword align */
497         u32 dif_len = addr - aligned_addr;
498         u32 i;
499
500         IPW_DEBUG_IO("addr = %i, buf = %p, num = %i\n", addr, buf, num);
501
502         if (num <= 0) {
503                 return;
504         }
505
506         /* Write the first dword (or portion) byte by byte */
507         if (unlikely(dif_len)) {
508                 _ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
509                 /* Start writing at aligned_addr + dif_len */
510                 for (i = dif_len; ((i < 4) && (num > 0)); i++, num--, buf++)
511                         _ipw_write8(priv, IPW_INDIRECT_DATA + i, *buf);
512                 aligned_addr += 4;
513         }
514
515         /* Write all of the middle dwords as dwords, with auto-increment */
516         _ipw_write32(priv, IPW_AUTOINC_ADDR, aligned_addr);
517         for (; num >= 4; buf += 4, aligned_addr += 4, num -= 4)
518                 _ipw_write32(priv, IPW_AUTOINC_DATA, *(u32 *) buf);
519
520         /* Write the last dword (or portion) byte by byte */
521         if (unlikely(num)) {
522                 _ipw_write32(priv, IPW_INDIRECT_ADDR, aligned_addr);
523                 for (i = 0; num > 0; i++, num--, buf++)
524                         _ipw_write8(priv, IPW_INDIRECT_DATA + i, *buf);
525         }
526 }
527
528 /* General purpose, no alignment requirement, iterative (multi-byte) write, */
529 /*    for 1st 4K of SRAM/regs space */
530 static void ipw_write_direct(struct ipw_priv *priv, u32 addr, void *buf,
531                              int num)
532 {
533         memcpy_toio((priv->hw_base + addr), buf, num);
534 }
535
536 /* Set bit(s) in low 4K of SRAM/regs */
537 static inline void ipw_set_bit(struct ipw_priv *priv, u32 reg, u32 mask)
538 {
539         ipw_write32(priv, reg, ipw_read32(priv, reg) | mask);
540 }
541
542 /* Clear bit(s) in low 4K of SRAM/regs */
543 static inline void ipw_clear_bit(struct ipw_priv *priv, u32 reg, u32 mask)
544 {
545         ipw_write32(priv, reg, ipw_read32(priv, reg) & ~mask);
546 }
547
548 static inline void __ipw_enable_interrupts(struct ipw_priv *priv)
549 {
550         if (priv->status & STATUS_INT_ENABLED)
551                 return;
552         priv->status |= STATUS_INT_ENABLED;
553         ipw_write32(priv, IPW_INTA_MASK_R, IPW_INTA_MASK_ALL);
554 }
555
556 static inline void __ipw_disable_interrupts(struct ipw_priv *priv)
557 {
558         if (!(priv->status & STATUS_INT_ENABLED))
559                 return;
560         priv->status &= ~STATUS_INT_ENABLED;
561         ipw_write32(priv, IPW_INTA_MASK_R, ~IPW_INTA_MASK_ALL);
562 }
563
564 static inline void ipw_enable_interrupts(struct ipw_priv *priv)
565 {
566         unsigned long flags;
567
568         spin_lock_irqsave(&priv->irq_lock, flags);
569         __ipw_enable_interrupts(priv);
570         spin_unlock_irqrestore(&priv->irq_lock, flags);
571 }
572
573 static inline void ipw_disable_interrupts(struct ipw_priv *priv)
574 {
575         unsigned long flags;
576
577         spin_lock_irqsave(&priv->irq_lock, flags);
578         __ipw_disable_interrupts(priv);
579         spin_unlock_irqrestore(&priv->irq_lock, flags);
580 }
581
582 static char *ipw_error_desc(u32 val)
583 {
584         switch (val) {
585         case IPW_FW_ERROR_OK:
586                 return "ERROR_OK";
587         case IPW_FW_ERROR_FAIL:
588                 return "ERROR_FAIL";
589         case IPW_FW_ERROR_MEMORY_UNDERFLOW:
590                 return "MEMORY_UNDERFLOW";
591         case IPW_FW_ERROR_MEMORY_OVERFLOW:
592                 return "MEMORY_OVERFLOW";
593         case IPW_FW_ERROR_BAD_PARAM:
594                 return "BAD_PARAM";
595         case IPW_FW_ERROR_BAD_CHECKSUM:
596                 return "BAD_CHECKSUM";
597         case IPW_FW_ERROR_NMI_INTERRUPT:
598                 return "NMI_INTERRUPT";
599         case IPW_FW_ERROR_BAD_DATABASE:
600                 return "BAD_DATABASE";
601         case IPW_FW_ERROR_ALLOC_FAIL:
602                 return "ALLOC_FAIL";
603         case IPW_FW_ERROR_DMA_UNDERRUN:
604                 return "DMA_UNDERRUN";
605         case IPW_FW_ERROR_DMA_STATUS:
606                 return "DMA_STATUS";
607         case IPW_FW_ERROR_DINO_ERROR:
608                 return "DINO_ERROR";
609         case IPW_FW_ERROR_EEPROM_ERROR:
610                 return "EEPROM_ERROR";
611         case IPW_FW_ERROR_SYSASSERT:
612                 return "SYSASSERT";
613         case IPW_FW_ERROR_FATAL_ERROR:
614                 return "FATAL_ERROR";
615         default:
616                 return "UNKNOWN_ERROR";
617         }
618 }
619
620 static void ipw_dump_error_log(struct ipw_priv *priv,
621                                struct ipw_fw_error *error)
622 {
623         u32 i;
624
625         if (!error) {
626                 IPW_ERROR("Error allocating and capturing error log.  "
627                           "Nothing to dump.\n");
628                 return;
629         }
630
631         IPW_ERROR("Start IPW Error Log Dump:\n");
632         IPW_ERROR("Status: 0x%08X, Config: %08X\n",
633                   error->status, error->config);
634
635         for (i = 0; i < error->elem_len; i++)
636                 IPW_ERROR("%s %i 0x%08x  0x%08x  0x%08x  0x%08x  0x%08x\n",
637                           ipw_error_desc(error->elem[i].desc),
638                           error->elem[i].time,
639                           error->elem[i].blink1,
640                           error->elem[i].blink2,
641                           error->elem[i].link1,
642                           error->elem[i].link2, error->elem[i].data);
643         for (i = 0; i < error->log_len; i++)
644                 IPW_ERROR("%i\t0x%08x\t%i\n",
645                           error->log[i].time,
646                           error->log[i].data, error->log[i].event);
647 }
648
649 static inline int ipw_is_init(struct ipw_priv *priv)
650 {
651         return (priv->status & STATUS_INIT) ? 1 : 0;
652 }
653
654 static int ipw_get_ordinal(struct ipw_priv *priv, u32 ord, void *val, u32 * len)
655 {
656         u32 addr, field_info, field_len, field_count, total_len;
657
658         IPW_DEBUG_ORD("ordinal = %i\n", ord);
659
660         if (!priv || !val || !len) {
661                 IPW_DEBUG_ORD("Invalid argument\n");
662                 return -EINVAL;
663         }
664
665         /* verify device ordinal tables have been initialized */
666         if (!priv->table0_addr || !priv->table1_addr || !priv->table2_addr) {
667                 IPW_DEBUG_ORD("Access ordinals before initialization\n");
668                 return -EINVAL;
669         }
670
671         switch (IPW_ORD_TABLE_ID_MASK & ord) {
672         case IPW_ORD_TABLE_0_MASK:
673                 /*
674                  * TABLE 0: Direct access to a table of 32 bit values
675                  *
676                  * This is a very simple table with the data directly
677                  * read from the table
678                  */
679
680                 /* remove the table id from the ordinal */
681                 ord &= IPW_ORD_TABLE_VALUE_MASK;
682
683                 /* boundary check */
684                 if (ord > priv->table0_len) {
685                         IPW_DEBUG_ORD("ordinal value (%i) longer then "
686                                       "max (%i)\n", ord, priv->table0_len);
687                         return -EINVAL;
688                 }
689
690                 /* verify we have enough room to store the value */
691                 if (*len < sizeof(u32)) {
692                         IPW_DEBUG_ORD("ordinal buffer length too small, "
693                                       "need %zd\n", sizeof(u32));
694                         return -EINVAL;
695                 }
696
697                 IPW_DEBUG_ORD("Reading TABLE0[%i] from offset 0x%08x\n",
698                               ord, priv->table0_addr + (ord << 2));
699
700                 *len = sizeof(u32);
701                 ord <<= 2;
702                 *((u32 *) val) = ipw_read32(priv, priv->table0_addr + ord);
703                 break;
704
705         case IPW_ORD_TABLE_1_MASK:
706                 /*
707                  * TABLE 1: Indirect access to a table of 32 bit values
708                  *
709                  * This is a fairly large table of u32 values each
710                  * representing starting addr for the data (which is
711                  * also a u32)
712                  */
713
714                 /* remove the table id from the ordinal */
715                 ord &= IPW_ORD_TABLE_VALUE_MASK;
716
717                 /* boundary check */
718                 if (ord > priv->table1_len) {
719                         IPW_DEBUG_ORD("ordinal value too long\n");
720                         return -EINVAL;
721                 }
722
723                 /* verify we have enough room to store the value */
724                 if (*len < sizeof(u32)) {
725                         IPW_DEBUG_ORD("ordinal buffer length too small, "
726                                       "need %zd\n", sizeof(u32));
727                         return -EINVAL;
728                 }
729
730                 *((u32 *) val) =
731                     ipw_read_reg32(priv, (priv->table1_addr + (ord << 2)));
732                 *len = sizeof(u32);
733                 break;
734
735         case IPW_ORD_TABLE_2_MASK:
736                 /*
737                  * TABLE 2: Indirect access to a table of variable sized values
738                  *
739                  * This table consist of six values, each containing
740                  *     - dword containing the starting offset of the data
741                  *     - dword containing the lengh in the first 16bits
742                  *       and the count in the second 16bits
743                  */
744
745                 /* remove the table id from the ordinal */
746                 ord &= IPW_ORD_TABLE_VALUE_MASK;
747
748                 /* boundary check */
749                 if (ord > priv->table2_len) {
750                         IPW_DEBUG_ORD("ordinal value too long\n");
751                         return -EINVAL;
752                 }
753
754                 /* get the address of statistic */
755                 addr = ipw_read_reg32(priv, priv->table2_addr + (ord << 3));
756
757                 /* get the second DW of statistics ;
758                  * two 16-bit words - first is length, second is count */
759                 field_info =
760                     ipw_read_reg32(priv,
761                                    priv->table2_addr + (ord << 3) +
762                                    sizeof(u32));
763
764                 /* get each entry length */
765                 field_len = *((u16 *) & field_info);
766
767                 /* get number of entries */
768                 field_count = *(((u16 *) & field_info) + 1);
769
770                 /* abort if not enought memory */
771                 total_len = field_len * field_count;
772                 if (total_len > *len) {
773                         *len = total_len;
774                         return -EINVAL;
775                 }
776
777                 *len = total_len;
778                 if (!total_len)
779                         return 0;
780
781                 IPW_DEBUG_ORD("addr = 0x%08x, total_len = %i, "
782                               "field_info = 0x%08x\n",
783                               addr, total_len, field_info);
784                 ipw_read_indirect(priv, addr, val, total_len);
785                 break;
786
787         default:
788                 IPW_DEBUG_ORD("Invalid ordinal!\n");
789                 return -EINVAL;
790
791         }
792
793         return 0;
794 }
795
796 static void ipw_init_ordinals(struct ipw_priv *priv)
797 {
798         priv->table0_addr = IPW_ORDINALS_TABLE_LOWER;
799         priv->table0_len = ipw_read32(priv, priv->table0_addr);
800
801         IPW_DEBUG_ORD("table 0 offset at 0x%08x, len = %i\n",
802                       priv->table0_addr, priv->table0_len);
803
804         priv->table1_addr = ipw_read32(priv, IPW_ORDINALS_TABLE_1);
805         priv->table1_len = ipw_read_reg32(priv, priv->table1_addr);
806
807         IPW_DEBUG_ORD("table 1 offset at 0x%08x, len = %i\n",
808                       priv->table1_addr, priv->table1_len);
809
810         priv->table2_addr = ipw_read32(priv, IPW_ORDINALS_TABLE_2);
811         priv->table2_len = ipw_read_reg32(priv, priv->table2_addr);
812         priv->table2_len &= 0x0000ffff; /* use first two bytes */
813
814         IPW_DEBUG_ORD("table 2 offset at 0x%08x, len = %i\n",
815                       priv->table2_addr, priv->table2_len);
816
817 }
818
819 static u32 ipw_register_toggle(u32 reg)
820 {
821         reg &= ~IPW_START_STANDBY;
822         if (reg & IPW_GATE_ODMA)
823                 reg &= ~IPW_GATE_ODMA;
824         if (reg & IPW_GATE_IDMA)
825                 reg &= ~IPW_GATE_IDMA;
826         if (reg & IPW_GATE_ADMA)
827                 reg &= ~IPW_GATE_ADMA;
828         return reg;
829 }
830
831 /*
832  * LED behavior:
833  * - On radio ON, turn on any LEDs that require to be on during start
834  * - On initialization, start unassociated blink
835  * - On association, disable unassociated blink
836  * - On disassociation, start unassociated blink
837  * - On radio OFF, turn off any LEDs started during radio on
838  *
839  */
840 #define LD_TIME_LINK_ON msecs_to_jiffies(300)
841 #define LD_TIME_LINK_OFF msecs_to_jiffies(2700)
842 #define LD_TIME_ACT_ON msecs_to_jiffies(250)
843
844 static void ipw_led_link_on(struct ipw_priv *priv)
845 {
846         unsigned long flags;
847         u32 led;
848
849         /* If configured to not use LEDs, or nic_type is 1,
850          * then we don't toggle a LINK led */
851         if (priv->config & CFG_NO_LED || priv->nic_type == EEPROM_NIC_TYPE_1)
852                 return;
853
854         spin_lock_irqsave(&priv->lock, flags);
855
856         if (!(priv->status & STATUS_RF_KILL_MASK) &&
857             !(priv->status & STATUS_LED_LINK_ON)) {
858                 IPW_DEBUG_LED("Link LED On\n");
859                 led = ipw_read_reg32(priv, IPW_EVENT_REG);
860                 led |= priv->led_association_on;
861
862                 led = ipw_register_toggle(led);
863
864                 IPW_DEBUG_LED("Reg: 0x%08X\n", led);
865                 ipw_write_reg32(priv, IPW_EVENT_REG, led);
866
867                 priv->status |= STATUS_LED_LINK_ON;
868
869                 /* If we aren't associated, schedule turning the LED off */
870                 if (!(priv->status & STATUS_ASSOCIATED))
871                         queue_delayed_work(priv->workqueue,
872                                            &priv->led_link_off,
873                                            LD_TIME_LINK_ON);
874         }
875
876         spin_unlock_irqrestore(&priv->lock, flags);
877 }
878
879 static void ipw_bg_led_link_on(struct work_struct *work)
880 {
881         struct ipw_priv *priv =
882                 container_of(work, struct ipw_priv, led_link_on.work);
883         mutex_lock(&priv->mutex);
884         ipw_led_link_on(priv);
885         mutex_unlock(&priv->mutex);
886 }
887
888 static void ipw_led_link_off(struct ipw_priv *priv)
889 {
890         unsigned long flags;
891         u32 led;
892
893         /* If configured not to use LEDs, or nic type is 1,
894          * then we don't goggle the LINK led. */
895         if (priv->config & CFG_NO_LED || priv->nic_type == EEPROM_NIC_TYPE_1)
896                 return;
897
898         spin_lock_irqsave(&priv->lock, flags);
899
900         if (priv->status & STATUS_LED_LINK_ON) {
901                 led = ipw_read_reg32(priv, IPW_EVENT_REG);
902                 led &= priv->led_association_off;
903                 led = ipw_register_toggle(led);
904
905                 IPW_DEBUG_LED("Reg: 0x%08X\n", led);
906                 ipw_write_reg32(priv, IPW_EVENT_REG, led);
907
908                 IPW_DEBUG_LED("Link LED Off\n");
909
910                 priv->status &= ~STATUS_LED_LINK_ON;
911
912                 /* If we aren't associated and the radio is on, schedule
913                  * turning the LED on (blink while unassociated) */
914                 if (!(priv->status & STATUS_RF_KILL_MASK) &&
915                     !(priv->status & STATUS_ASSOCIATED))
916                         queue_delayed_work(priv->workqueue, &priv->led_link_on,
917                                            LD_TIME_LINK_OFF);
918
919         }
920
921         spin_unlock_irqrestore(&priv->lock, flags);
922 }
923
924 static void ipw_bg_led_link_off(struct work_struct *work)
925 {
926         struct ipw_priv *priv =
927                 container_of(work, struct ipw_priv, led_link_off.work);
928         mutex_lock(&priv->mutex);
929         ipw_led_link_off(priv);
930         mutex_unlock(&priv->mutex);
931 }
932
933 static void __ipw_led_activity_on(struct ipw_priv *priv)
934 {
935         u32 led;
936
937         if (priv->config & CFG_NO_LED)
938                 return;
939
940         if (priv->status & STATUS_RF_KILL_MASK)
941                 return;
942
943         if (!(priv->status & STATUS_LED_ACT_ON)) {
944                 led = ipw_read_reg32(priv, IPW_EVENT_REG);
945                 led |= priv->led_activity_on;
946
947                 led = ipw_register_toggle(led);
948
949                 IPW_DEBUG_LED("Reg: 0x%08X\n", led);
950                 ipw_write_reg32(priv, IPW_EVENT_REG, led);
951
952                 IPW_DEBUG_LED("Activity LED On\n");
953
954                 priv->status |= STATUS_LED_ACT_ON;
955
956                 cancel_delayed_work(&priv->led_act_off);
957                 queue_delayed_work(priv->workqueue, &priv->led_act_off,
958                                    LD_TIME_ACT_ON);
959         } else {
960                 /* Reschedule LED off for full time period */
961                 cancel_delayed_work(&priv->led_act_off);
962                 queue_delayed_work(priv->workqueue, &priv->led_act_off,
963                                    LD_TIME_ACT_ON);
964         }
965 }
966
967 #if 0
968 void ipw_led_activity_on(struct ipw_priv *priv)
969 {
970         unsigned long flags;
971         spin_lock_irqsave(&priv->lock, flags);
972         __ipw_led_activity_on(priv);
973         spin_unlock_irqrestore(&priv->lock, flags);
974 }
975 #endif  /*  0  */
976
977 static void ipw_led_activity_off(struct ipw_priv *priv)
978 {
979         unsigned long flags;
980         u32 led;
981
982         if (priv->config & CFG_NO_LED)
983                 return;
984
985         spin_lock_irqsave(&priv->lock, flags);
986
987         if (priv->status & STATUS_LED_ACT_ON) {
988                 led = ipw_read_reg32(priv, IPW_EVENT_REG);
989                 led &= priv->led_activity_off;
990
991                 led = ipw_register_toggle(led);
992
993                 IPW_DEBUG_LED("Reg: 0x%08X\n", led);
994                 ipw_write_reg32(priv, IPW_EVENT_REG, led);
995
996                 IPW_DEBUG_LED("Activity LED Off\n");
997
998                 priv->status &= ~STATUS_LED_ACT_ON;
999         }
1000
1001         spin_unlock_irqrestore(&priv->lock, flags);
1002 }
1003
1004 static void ipw_bg_led_activity_off(struct work_struct *work)
1005 {
1006         struct ipw_priv *priv =
1007                 container_of(work, struct ipw_priv, led_act_off.work);
1008         mutex_lock(&priv->mutex);
1009         ipw_led_activity_off(priv);
1010         mutex_unlock(&priv->mutex);
1011 }
1012
1013 static void ipw_led_band_on(struct ipw_priv *priv)
1014 {
1015         unsigned long flags;
1016         u32 led;
1017
1018         /* Only nic type 1 supports mode LEDs */
1019         if (priv->config & CFG_NO_LED ||
1020             priv->nic_type != EEPROM_NIC_TYPE_1 || !priv->assoc_network)
1021                 return;
1022
1023         spin_lock_irqsave(&priv->lock, flags);
1024
1025         led = ipw_read_reg32(priv, IPW_EVENT_REG);
1026         if (priv->assoc_network->mode == IEEE_A) {
1027                 led |= priv->led_ofdm_on;
1028                 led &= priv->led_association_off;
1029                 IPW_DEBUG_LED("Mode LED On: 802.11a\n");
1030         } else if (priv->assoc_network->mode == IEEE_G) {
1031                 led |= priv->led_ofdm_on;
1032                 led |= priv->led_association_on;
1033                 IPW_DEBUG_LED("Mode LED On: 802.11g\n");
1034         } else {
1035                 led &= priv->led_ofdm_off;
1036                 led |= priv->led_association_on;
1037                 IPW_DEBUG_LED("Mode LED On: 802.11b\n");
1038         }
1039
1040         led = ipw_register_toggle(led);
1041
1042         IPW_DEBUG_LED("Reg: 0x%08X\n", led);
1043         ipw_write_reg32(priv, IPW_EVENT_REG, led);
1044
1045         spin_unlock_irqrestore(&priv->lock, flags);
1046 }
1047
1048 static void ipw_led_band_off(struct ipw_priv *priv)
1049 {
1050         unsigned long flags;
1051         u32 led;
1052
1053         /* Only nic type 1 supports mode LEDs */
1054         if (priv->config & CFG_NO_LED || priv->nic_type != EEPROM_NIC_TYPE_1)
1055                 return;
1056
1057         spin_lock_irqsave(&priv->lock, flags);
1058
1059         led = ipw_read_reg32(priv, IPW_EVENT_REG);
1060         led &= priv->led_ofdm_off;
1061         led &= priv->led_association_off;
1062
1063         led = ipw_register_toggle(led);
1064
1065         IPW_DEBUG_LED("Reg: 0x%08X\n", led);
1066         ipw_write_reg32(priv, IPW_EVENT_REG, led);
1067
1068         spin_unlock_irqrestore(&priv->lock, flags);
1069 }
1070
1071 static void ipw_led_radio_on(struct ipw_priv *priv)
1072 {
1073         ipw_led_link_on(priv);
1074 }
1075
1076 static void ipw_led_radio_off(struct ipw_priv *priv)
1077 {
1078         ipw_led_activity_off(priv);
1079         ipw_led_link_off(priv);
1080 }
1081
1082 static void ipw_led_link_up(struct ipw_priv *priv)
1083 {
1084         /* Set the Link Led on for all nic types */
1085         ipw_led_link_on(priv);
1086 }
1087
1088 static void ipw_led_link_down(struct ipw_priv *priv)
1089 {
1090         ipw_led_activity_off(priv);
1091         ipw_led_link_off(priv);
1092
1093         if (priv->status & STATUS_RF_KILL_MASK)
1094                 ipw_led_radio_off(priv);
1095 }
1096
1097 static void ipw_led_init(struct ipw_priv *priv)
1098 {
1099         priv->nic_type = priv->eeprom[EEPROM_NIC_TYPE];
1100
1101         /* Set the default PINs for the link and activity leds */
1102         priv->led_activity_on = IPW_ACTIVITY_LED;
1103         priv->led_activity_off = ~(IPW_ACTIVITY_LED);
1104
1105         priv->led_association_on = IPW_ASSOCIATED_LED;
1106         priv->led_association_off = ~(IPW_ASSOCIATED_LED);
1107
1108         /* Set the default PINs for the OFDM leds */
1109         priv->led_ofdm_on = IPW_OFDM_LED;
1110         priv->led_ofdm_off = ~(IPW_OFDM_LED);
1111
1112         switch (priv->nic_type) {
1113         case EEPROM_NIC_TYPE_1:
1114                 /* In this NIC type, the LEDs are reversed.... */
1115                 priv->led_activity_on = IPW_ASSOCIATED_LED;
1116                 priv->led_activity_off = ~(IPW_ASSOCIATED_LED);
1117                 priv->led_association_on = IPW_ACTIVITY_LED;
1118                 priv->led_association_off = ~(IPW_ACTIVITY_LED);
1119
1120                 if (!(priv->config & CFG_NO_LED))
1121                         ipw_led_band_on(priv);
1122
1123                 /* And we don't blink link LEDs for this nic, so
1124                  * just return here */
1125                 return;
1126
1127         case EEPROM_NIC_TYPE_3:
1128         case EEPROM_NIC_TYPE_2:
1129         case EEPROM_NIC_TYPE_4:
1130         case EEPROM_NIC_TYPE_0:
1131                 break;
1132
1133         default:
1134                 IPW_DEBUG_INFO("Unknown NIC type from EEPROM: %d\n",
1135                                priv->nic_type);
1136                 priv->nic_type = EEPROM_NIC_TYPE_0;
1137                 break;
1138         }
1139
1140         if (!(priv->config & CFG_NO_LED)) {
1141                 if (priv->status & STATUS_ASSOCIATED)
1142                         ipw_led_link_on(priv);
1143                 else
1144                         ipw_led_link_off(priv);
1145         }
1146 }
1147
1148 static void ipw_led_shutdown(struct ipw_priv *priv)
1149 {
1150         ipw_led_activity_off(priv);
1151         ipw_led_link_off(priv);
1152         ipw_led_band_off(priv);
1153         cancel_delayed_work(&priv->led_link_on);
1154         cancel_delayed_work(&priv->led_link_off);
1155         cancel_delayed_work(&priv->led_act_off);
1156 }
1157
1158 /*
1159  * The following adds a new attribute to the sysfs representation
1160  * of this device driver (i.e. a new file in /sys/bus/pci/drivers/ipw/)
1161  * used for controling the debug level.
1162  *
1163  * See the level definitions in ipw for details.
1164  */
1165 static ssize_t show_debug_level(struct device_driver *d, char *buf)
1166 {
1167         return sprintf(buf, "0x%08X\n", ipw_debug_level);
1168 }
1169
1170 static ssize_t store_debug_level(struct device_driver *d, const char *buf,
1171                                  size_t count)
1172 {
1173         char *p = (char *)buf;
1174         u32 val;
1175
1176         if (p[1] == 'x' || p[1] == 'X' || p[0] == 'x' || p[0] == 'X') {
1177                 p++;
1178                 if (p[0] == 'x' || p[0] == 'X')
1179                         p++;
1180                 val = simple_strtoul(p, &p, 16);
1181         } else
1182                 val = simple_strtoul(p, &p, 10);
1183         if (p == buf)
1184                 printk(KERN_INFO DRV_NAME
1185                        ": %s is not in hex or decimal form.\n", buf);
1186         else
1187                 ipw_debug_level = val;
1188
1189         return strnlen(buf, count);
1190 }
1191
1192 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
1193                    show_debug_level, store_debug_level);
1194
1195 static inline u32 ipw_get_event_log_len(struct ipw_priv *priv)
1196 {
1197         /* length = 1st dword in log */
1198         return ipw_read_reg32(priv, ipw_read32(priv, IPW_EVENT_LOG));
1199 }
1200
1201 static void ipw_capture_event_log(struct ipw_priv *priv,
1202                                   u32 log_len, struct ipw_event *log)
1203 {
1204         u32 base;
1205
1206         if (log_len) {
1207                 base = ipw_read32(priv, IPW_EVENT_LOG);
1208                 ipw_read_indirect(priv, base + sizeof(base) + sizeof(u32),
1209                                   (u8 *) log, sizeof(*log) * log_len);
1210         }
1211 }
1212
1213 static struct ipw_fw_error *ipw_alloc_error_log(struct ipw_priv *priv)
1214 {
1215         struct ipw_fw_error *error;
1216         u32 log_len = ipw_get_event_log_len(priv);
1217         u32 base = ipw_read32(priv, IPW_ERROR_LOG);
1218         u32 elem_len = ipw_read_reg32(priv, base);
1219
1220         error = kmalloc(sizeof(*error) +
1221                         sizeof(*error->elem) * elem_len +
1222                         sizeof(*error->log) * log_len, GFP_ATOMIC);
1223         if (!error) {
1224                 IPW_ERROR("Memory allocation for firmware error log "
1225                           "failed.\n");
1226                 return NULL;
1227         }
1228         error->jiffies = jiffies;
1229         error->status = priv->status;
1230         error->config = priv->config;
1231         error->elem_len = elem_len;
1232         error->log_len = log_len;
1233         error->elem = (struct ipw_error_elem *)error->payload;
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 show_event_log(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 += snprintf(buf + len, PAGE_SIZE - len, "%08X", log_len);
1266         for (i = 0; i < log_len; i++)
1267                 len += snprintf(buf + len, PAGE_SIZE - len,
1268                                 "\n%08X%08X%08X",
1269                                 log[i].time, log[i].event, log[i].data);
1270         len += snprintf(buf + len, PAGE_SIZE - len, "\n");
1271         kfree(log);
1272         return len;
1273 }
1274
1275 static DEVICE_ATTR(event_log, S_IRUGO, show_event_log, NULL);
1276
1277 static ssize_t show_error(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 += snprintf(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 += snprintf(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 += snprintf(buf + len, PAGE_SIZE - len,
1301                         "\n%08X", priv->error->log_len);
1302         for (i = 0; i < priv->error->log_len; i++)
1303                 len += snprintf(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 += snprintf(buf + len, PAGE_SIZE - len, "\n");
1309         return len;
1310 }
1311
1312 static ssize_t clear_error(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(error, S_IRUGO | S_IWUSR, show_error, clear_error);
1324
1325 static ssize_t show_cmd_log(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) && (PAGE_SIZE - len);
1334              i = (i + 1) % priv->cmdlog_len) {
1335                 len +=
1336                     snprintf(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 += snprintf(buf + len, PAGE_SIZE - len, "\n");
1345         }
1346         len += snprintf(buf + len, PAGE_SIZE - len, "\n");
1347         return len;
1348 }
1349
1350 static DEVICE_ATTR(cmd_log, S_IRUGO, show_cmd_log, NULL);
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 store_rtap_iface(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 show_rtap_iface(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(rtap_iface, S_IWUSR | S_IRUSR, show_rtap_iface,
1416                    store_rtap_iface);
1417
1418 static ssize_t store_rtap_filter(struct device *d,
1419                          struct device_attribute *attr,
1420                          const char *buf, size_t count)
1421 {
1422         struct ipw_priv *priv = dev_get_drvdata(d);
1423
1424         if (!priv->prom_priv) {
1425                 IPW_ERROR("Attempting to set filter without "
1426                           "rtap_iface enabled.\n");
1427                 return -EPERM;
1428         }
1429
1430         priv->prom_priv->filter = simple_strtol(buf, NULL, 0);
1431
1432         IPW_DEBUG_INFO("Setting rtap filter to " BIT_FMT16 "\n",
1433                        BIT_ARG16(priv->prom_priv->filter));
1434
1435         return count;
1436 }
1437
1438 static ssize_t show_rtap_filter(struct device *d,
1439                         struct device_attribute *attr,
1440                         char *buf)
1441 {
1442         struct ipw_priv *priv = dev_get_drvdata(d);
1443         return sprintf(buf, "0x%04X",
1444                        priv->prom_priv ? priv->prom_priv->filter : 0);
1445 }
1446
1447 static DEVICE_ATTR(rtap_filter, S_IWUSR | S_IRUSR, show_rtap_filter,
1448                    store_rtap_filter);
1449 #endif
1450
1451 static ssize_t show_scan_age(struct device *d, struct device_attribute *attr,
1452                              char *buf)
1453 {
1454         struct ipw_priv *priv = dev_get_drvdata(d);
1455         return sprintf(buf, "%d\n", priv->ieee->scan_age);
1456 }
1457
1458 static ssize_t store_scan_age(struct device *d, struct device_attribute *attr,
1459                               const char *buf, size_t count)
1460 {
1461         struct ipw_priv *priv = dev_get_drvdata(d);
1462         struct net_device *dev = priv->net_dev;
1463         char buffer[] = "00000000";
1464         unsigned long len =
1465             (sizeof(buffer) - 1) > count ? count : sizeof(buffer) - 1;
1466         unsigned long val;
1467         char *p = buffer;
1468
1469         IPW_DEBUG_INFO("enter\n");
1470
1471         strncpy(buffer, buf, len);
1472         buffer[len] = 0;
1473
1474         if (p[1] == 'x' || p[1] == 'X' || p[0] == 'x' || p[0] == 'X') {
1475                 p++;
1476                 if (p[0] == 'x' || p[0] == 'X')
1477                         p++;
1478                 val = simple_strtoul(p, &p, 16);
1479         } else
1480                 val = simple_strtoul(p, &p, 10);
1481         if (p == buffer) {
1482                 IPW_DEBUG_INFO("%s: user supplied invalid value.\n", dev->name);
1483         } else {
1484                 priv->ieee->scan_age = val;
1485                 IPW_DEBUG_INFO("set scan_age = %u\n", priv->ieee->scan_age);
1486         }
1487
1488         IPW_DEBUG_INFO("exit\n");
1489         return len;
1490 }
1491
1492 static DEVICE_ATTR(scan_age, S_IWUSR | S_IRUGO, show_scan_age, store_scan_age);
1493
1494 static ssize_t show_led(struct device *d, struct device_attribute *attr,
1495                         char *buf)
1496 {
1497         struct ipw_priv *priv = dev_get_drvdata(d);
1498         return sprintf(buf, "%d\n", (priv->config & CFG_NO_LED) ? 0 : 1);
1499 }
1500
1501 static ssize_t store_led(struct device *d, struct device_attribute *attr,
1502                          const char *buf, size_t count)
1503 {
1504         struct ipw_priv *priv = dev_get_drvdata(d);
1505
1506         IPW_DEBUG_INFO("enter\n");
1507
1508         if (count == 0)
1509                 return 0;
1510
1511         if (*buf == 0) {
1512                 IPW_DEBUG_LED("Disabling LED control.\n");
1513                 priv->config |= CFG_NO_LED;
1514                 ipw_led_shutdown(priv);
1515         } else {
1516                 IPW_DEBUG_LED("Enabling LED control.\n");
1517                 priv->config &= ~CFG_NO_LED;
1518                 ipw_led_init(priv);
1519         }
1520
1521         IPW_DEBUG_INFO("exit\n");
1522         return count;
1523 }
1524
1525 static DEVICE_ATTR(led, S_IWUSR | S_IRUGO, show_led, store_led);
1526
1527 static ssize_t show_status(struct device *d,
1528                            struct device_attribute *attr, char *buf)
1529 {
1530         struct ipw_priv *p = dev_get_drvdata(d);
1531         return sprintf(buf, "0x%08x\n", (int)p->status);
1532 }
1533
1534 static DEVICE_ATTR(status, S_IRUGO, show_status, NULL);
1535
1536 static ssize_t show_cfg(struct device *d, struct device_attribute *attr,
1537                         char *buf)
1538 {
1539         struct ipw_priv *p = dev_get_drvdata(d);
1540         return sprintf(buf, "0x%08x\n", (int)p->config);
1541 }
1542
1543 static DEVICE_ATTR(cfg, S_IRUGO, show_cfg, NULL);
1544
1545 static ssize_t show_nic_type(struct device *d,
1546                              struct device_attribute *attr, char *buf)
1547 {
1548         struct ipw_priv *priv = dev_get_drvdata(d);
1549         return sprintf(buf, "TYPE: %d\n", priv->nic_type);
1550 }
1551
1552 static DEVICE_ATTR(nic_type, S_IRUGO, show_nic_type, NULL);
1553
1554 static ssize_t show_ucode_version(struct device *d,
1555                                   struct device_attribute *attr, 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_UCODE_VERSION, &tmp, &len))
1561                 return 0;
1562
1563         return sprintf(buf, "0x%08x\n", tmp);
1564 }
1565
1566 static DEVICE_ATTR(ucode_version, S_IWUSR | S_IRUGO, show_ucode_version, NULL);
1567
1568 static ssize_t show_rtc(struct device *d, struct device_attribute *attr,
1569                         char *buf)
1570 {
1571         u32 len = sizeof(u32), tmp = 0;
1572         struct ipw_priv *p = dev_get_drvdata(d);
1573
1574         if (ipw_get_ordinal(p, IPW_ORD_STAT_RTC, &tmp, &len))
1575                 return 0;
1576
1577         return sprintf(buf, "0x%08x\n", tmp);
1578 }
1579
1580 static DEVICE_ATTR(rtc, S_IWUSR | S_IRUGO, show_rtc, NULL);
1581
1582 /*
1583  * Add a device attribute to view/control the delay between eeprom
1584  * operations.
1585  */
1586 static ssize_t show_eeprom_delay(struct device *d,
1587                                  struct device_attribute *attr, char *buf)
1588 {
1589         struct ipw_priv *p = dev_get_drvdata(d);
1590         int n = p->eeprom_delay;
1591         return sprintf(buf, "%i\n", n);
1592 }
1593 static ssize_t store_eeprom_delay(struct device *d,
1594                                   struct device_attribute *attr,
1595                                   const char *buf, size_t count)
1596 {
1597         struct ipw_priv *p = dev_get_drvdata(d);
1598         sscanf(buf, "%i", &p->eeprom_delay);
1599         return strnlen(buf, count);
1600 }
1601
1602 static DEVICE_ATTR(eeprom_delay, S_IWUSR | S_IRUGO,
1603                    show_eeprom_delay, store_eeprom_delay);
1604
1605 static ssize_t show_command_event_reg(struct device *d,
1606                                       struct device_attribute *attr, char *buf)
1607 {
1608         u32 reg = 0;
1609         struct ipw_priv *p = dev_get_drvdata(d);
1610
1611         reg = ipw_read_reg32(p, IPW_INTERNAL_CMD_EVENT);
1612         return sprintf(buf, "0x%08x\n", reg);
1613 }
1614 static ssize_t store_command_event_reg(struct device *d,
1615                                        struct device_attribute *attr,
1616                                        const char *buf, size_t count)
1617 {
1618         u32 reg;
1619         struct ipw_priv *p = dev_get_drvdata(d);
1620
1621         sscanf(buf, "%x", &reg);
1622         ipw_write_reg32(p, IPW_INTERNAL_CMD_EVENT, reg);
1623         return strnlen(buf, count);
1624 }
1625
1626 static DEVICE_ATTR(command_event_reg, S_IWUSR | S_IRUGO,
1627                    show_command_event_reg, store_command_event_reg);
1628
1629 static ssize_t show_mem_gpio_reg(struct device *d,
1630                                  struct device_attribute *attr, char *buf)
1631 {
1632         u32 reg = 0;
1633         struct ipw_priv *p = dev_get_drvdata(d);
1634
1635         reg = ipw_read_reg32(p, 0x301100);
1636         return sprintf(buf, "0x%08x\n", reg);
1637 }
1638 static ssize_t store_mem_gpio_reg(struct device *d,
1639                                   struct device_attribute *attr,
1640                                   const char *buf, size_t count)
1641 {
1642         u32 reg;
1643         struct ipw_priv *p = dev_get_drvdata(d);
1644
1645         sscanf(buf, "%x", &reg);
1646         ipw_write_reg32(p, 0x301100, reg);
1647         return strnlen(buf, count);
1648 }
1649
1650 static DEVICE_ATTR(mem_gpio_reg, S_IWUSR | S_IRUGO,
1651                    show_mem_gpio_reg, store_mem_gpio_reg);
1652
1653 static ssize_t show_indirect_dword(struct device *d,
1654                                    struct device_attribute *attr, char *buf)
1655 {
1656         u32 reg = 0;
1657         struct ipw_priv *priv = dev_get_drvdata(d);
1658
1659         if (priv->status & STATUS_INDIRECT_DWORD)
1660                 reg = ipw_read_reg32(priv, priv->indirect_dword);
1661         else
1662                 reg = 0;
1663
1664         return sprintf(buf, "0x%08x\n", reg);
1665 }
1666 static ssize_t store_indirect_dword(struct device *d,
1667                                     struct device_attribute *attr,
1668                                     const char *buf, size_t count)
1669 {
1670         struct ipw_priv *priv = dev_get_drvdata(d);
1671
1672         sscanf(buf, "%x", &priv->indirect_dword);
1673         priv->status |= STATUS_INDIRECT_DWORD;
1674         return strnlen(buf, count);
1675 }
1676
1677 static DEVICE_ATTR(indirect_dword, S_IWUSR | S_IRUGO,
1678                    show_indirect_dword, store_indirect_dword);
1679
1680 static ssize_t show_indirect_byte(struct device *d,
1681                                   struct device_attribute *attr, char *buf)
1682 {
1683         u8 reg = 0;
1684         struct ipw_priv *priv = dev_get_drvdata(d);
1685
1686         if (priv->status & STATUS_INDIRECT_BYTE)
1687                 reg = ipw_read_reg8(priv, priv->indirect_byte);
1688         else
1689                 reg = 0;
1690
1691         return sprintf(buf, "0x%02x\n", reg);
1692 }
1693 static ssize_t store_indirect_byte(struct device *d,
1694                                    struct device_attribute *attr,
1695                                    const char *buf, size_t count)
1696 {
1697         struct ipw_priv *priv = dev_get_drvdata(d);
1698
1699         sscanf(buf, "%x", &priv->indirect_byte);
1700         priv->status |= STATUS_INDIRECT_BYTE;
1701         return strnlen(buf, count);
1702 }
1703
1704 static DEVICE_ATTR(indirect_byte, S_IWUSR | S_IRUGO,
1705                    show_indirect_byte, store_indirect_byte);
1706
1707 static ssize_t show_direct_dword(struct device *d,
1708                                  struct device_attribute *attr, char *buf)
1709 {
1710         u32 reg = 0;
1711         struct ipw_priv *priv = dev_get_drvdata(d);
1712
1713         if (priv->status & STATUS_DIRECT_DWORD)
1714                 reg = ipw_read32(priv, priv->direct_dword);
1715         else
1716                 reg = 0;
1717
1718         return sprintf(buf, "0x%08x\n", reg);
1719 }
1720 static ssize_t store_direct_dword(struct device *d,
1721                                   struct device_attribute *attr,
1722                                   const char *buf, size_t count)
1723 {
1724         struct ipw_priv *priv = dev_get_drvdata(d);
1725
1726         sscanf(buf, "%x", &priv->direct_dword);
1727         priv->status |= STATUS_DIRECT_DWORD;
1728         return strnlen(buf, count);
1729 }
1730
1731 static DEVICE_ATTR(direct_dword, S_IWUSR | S_IRUGO,
1732                    show_direct_dword, store_direct_dword);
1733
1734 static int rf_kill_active(struct ipw_priv *priv)
1735 {
1736         if (0 == (ipw_read32(priv, 0x30) & 0x10000))
1737                 priv->status |= STATUS_RF_KILL_HW;
1738         else
1739                 priv->status &= ~STATUS_RF_KILL_HW;
1740
1741         return (priv->status & STATUS_RF_KILL_HW) ? 1 : 0;
1742 }
1743
1744 static ssize_t show_rf_kill(struct device *d, struct device_attribute *attr,
1745                             char *buf)
1746 {
1747         /* 0 - RF kill not enabled
1748            1 - SW based RF kill active (sysfs)
1749            2 - HW based RF kill active
1750            3 - Both HW and SW baed RF kill active */
1751         struct ipw_priv *priv = dev_get_drvdata(d);
1752         int val = ((priv->status & STATUS_RF_KILL_SW) ? 0x1 : 0x0) |
1753             (rf_kill_active(priv) ? 0x2 : 0x0);
1754         return sprintf(buf, "%i\n", val);
1755 }
1756
1757 static int ipw_radio_kill_sw(struct ipw_priv *priv, int disable_radio)
1758 {
1759         if ((disable_radio ? 1 : 0) ==
1760             ((priv->status & STATUS_RF_KILL_SW) ? 1 : 0))
1761                 return 0;
1762
1763         IPW_DEBUG_RF_KILL("Manual SW RF Kill set to: RADIO  %s\n",
1764                           disable_radio ? "OFF" : "ON");
1765
1766         if (disable_radio) {
1767                 priv->status |= STATUS_RF_KILL_SW;
1768
1769                 if (priv->workqueue) {
1770                         cancel_delayed_work(&priv->request_scan);
1771                         cancel_delayed_work(&priv->request_direct_scan);
1772                         cancel_delayed_work(&priv->request_passive_scan);
1773                         cancel_delayed_work(&priv->scan_event);
1774                 }
1775                 queue_work(priv->workqueue, &priv->down);
1776         } else {
1777                 priv->status &= ~STATUS_RF_KILL_SW;
1778                 if (rf_kill_active(priv)) {
1779                         IPW_DEBUG_RF_KILL("Can not turn radio back on - "
1780                                           "disabled by HW switch\n");
1781                         /* Make sure the RF_KILL check timer is running */
1782                         cancel_delayed_work(&priv->rf_kill);
1783                         queue_delayed_work(priv->workqueue, &priv->rf_kill,
1784                                            round_jiffies_relative(2 * HZ));
1785                 } else
1786                         queue_work(priv->workqueue, &priv->up);
1787         }
1788
1789         return 1;
1790 }
1791
1792 static ssize_t store_rf_kill(struct device *d, struct device_attribute *attr,
1793                              const char *buf, size_t count)
1794 {
1795         struct ipw_priv *priv = dev_get_drvdata(d);
1796
1797         ipw_radio_kill_sw(priv, buf[0] == '1');
1798
1799         return count;
1800 }
1801
1802 static DEVICE_ATTR(rf_kill, S_IWUSR | S_IRUGO, show_rf_kill, store_rf_kill);
1803
1804 static ssize_t show_speed_scan(struct device *d, struct device_attribute *attr,
1805                                char *buf)
1806 {
1807         struct ipw_priv *priv = dev_get_drvdata(d);
1808         int pos = 0, len = 0;
1809         if (priv->config & CFG_SPEED_SCAN) {
1810                 while (priv->speed_scan[pos] != 0)
1811                         len += sprintf(&buf[len], "%d ",
1812                                        priv->speed_scan[pos++]);
1813                 return len + sprintf(&buf[len], "\n");
1814         }
1815
1816         return sprintf(buf, "0\n");
1817 }
1818
1819 static ssize_t store_speed_scan(struct device *d, struct device_attribute *attr,
1820                                 const char *buf, size_t count)
1821 {
1822         struct ipw_priv *priv = dev_get_drvdata(d);
1823         int channel, pos = 0;
1824         const char *p = buf;
1825
1826         /* list of space separated channels to scan, optionally ending with 0 */
1827         while ((channel = simple_strtol(p, NULL, 0))) {
1828                 if (pos == MAX_SPEED_SCAN - 1) {
1829                         priv->speed_scan[pos] = 0;
1830                         break;
1831                 }
1832
1833                 if (libipw_is_valid_channel(priv->ieee, channel))
1834                         priv->speed_scan[pos++] = channel;
1835                 else
1836                         IPW_WARNING("Skipping invalid channel request: %d\n",
1837                                     channel);
1838                 p = strchr(p, ' ');
1839                 if (!p)
1840                         break;
1841                 while (*p == ' ' || *p == '\t')
1842                         p++;
1843         }
1844
1845         if (pos == 0)
1846                 priv->config &= ~CFG_SPEED_SCAN;
1847         else {
1848                 priv->speed_scan_pos = 0;
1849                 priv->config |= CFG_SPEED_SCAN;
1850         }
1851
1852         return count;
1853 }
1854
1855 static DEVICE_ATTR(speed_scan, S_IWUSR | S_IRUGO, show_speed_scan,
1856                    store_speed_scan);
1857
1858 static ssize_t show_net_stats(struct device *d, struct device_attribute *attr,
1859                               char *buf)
1860 {
1861         struct ipw_priv *priv = dev_get_drvdata(d);
1862         return sprintf(buf, "%c\n", (priv->config & CFG_NET_STATS) ? '1' : '0');
1863 }
1864
1865 static ssize_t store_net_stats(struct device *d, struct device_attribute *attr,
1866                                const char *buf, size_t count)
1867 {
1868         struct ipw_priv *priv = dev_get_drvdata(d);
1869         if (buf[0] == '1')
1870                 priv->config |= CFG_NET_STATS;
1871         else
1872                 priv->config &= ~CFG_NET_STATS;
1873
1874         return count;
1875 }
1876
1877 static DEVICE_ATTR(net_stats, S_IWUSR | S_IRUGO,
1878                    show_net_stats, store_net_stats);
1879
1880 static ssize_t show_channels(struct device *d,
1881                              struct device_attribute *attr,
1882                              char *buf)
1883 {
1884         struct ipw_priv *priv = dev_get_drvdata(d);
1885         const struct libipw_geo *geo = libipw_get_geo(priv->ieee);
1886         int len = 0, i;
1887
1888         len = sprintf(&buf[len],
1889                       "Displaying %d channels in 2.4Ghz band "
1890                       "(802.11bg):\n", geo->bg_channels);
1891
1892         for (i = 0; i < geo->bg_channels; i++) {
1893                 len += sprintf(&buf[len], "%d: BSS%s%s, %s, Band %s.\n",
1894                                geo->bg[i].channel,
1895                                geo->bg[i].flags & LIBIPW_CH_RADAR_DETECT ?
1896                                " (radar spectrum)" : "",
1897                                ((geo->bg[i].flags & LIBIPW_CH_NO_IBSS) ||
1898                                 (geo->bg[i].flags & LIBIPW_CH_RADAR_DETECT))
1899                                ? "" : ", IBSS",
1900                                geo->bg[i].flags & LIBIPW_CH_PASSIVE_ONLY ?
1901                                "passive only" : "active/passive",
1902                                geo->bg[i].flags & LIBIPW_CH_B_ONLY ?
1903                                "B" : "B/G");
1904         }
1905
1906         len += sprintf(&buf[len],
1907                        "Displaying %d channels in 5.2Ghz band "
1908                        "(802.11a):\n", geo->a_channels);
1909         for (i = 0; i < geo->a_channels; i++) {
1910                 len += sprintf(&buf[len], "%d: BSS%s%s, %s.\n",
1911                                geo->a[i].channel,
1912                                geo->a[i].flags & LIBIPW_CH_RADAR_DETECT ?
1913                                " (radar spectrum)" : "",
1914                                ((geo->a[i].flags & LIBIPW_CH_NO_IBSS) ||
1915                                 (geo->a[i].flags & LIBIPW_CH_RADAR_DETECT))
1916                                ? "" : ", IBSS",
1917                                geo->a[i].flags & LIBIPW_CH_PASSIVE_ONLY ?
1918                                "passive only" : "active/passive");
1919         }
1920
1921         return len;
1922 }
1923
1924 static DEVICE_ATTR(channels, S_IRUSR, show_channels, NULL);
1925
1926 static void notify_wx_assoc_event(struct ipw_priv *priv)
1927 {
1928         union iwreq_data wrqu;
1929         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
1930         if (priv->status & STATUS_ASSOCIATED)
1931                 memcpy(wrqu.ap_addr.sa_data, priv->bssid, ETH_ALEN);
1932         else
1933                 memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
1934         wireless_send_event(priv->net_dev, SIOCGIWAP, &wrqu, NULL);
1935 }
1936
1937 static void ipw_irq_tasklet(struct ipw_priv *priv)
1938 {
1939         u32 inta, inta_mask, handled = 0;
1940         unsigned long flags;
1941         int rc = 0;
1942
1943         spin_lock_irqsave(&priv->irq_lock, flags);
1944
1945         inta = ipw_read32(priv, IPW_INTA_RW);
1946         inta_mask = ipw_read32(priv, IPW_INTA_MASK_R);
1947         inta &= (IPW_INTA_MASK_ALL & inta_mask);
1948
1949         /* Add any cached INTA values that need to be handled */
1950         inta |= priv->isr_inta;
1951
1952         spin_unlock_irqrestore(&priv->irq_lock, flags);
1953
1954         spin_lock_irqsave(&priv->lock, flags);
1955
1956         /* handle all the justifications for the interrupt */
1957         if (inta & IPW_INTA_BIT_RX_TRANSFER) {
1958                 ipw_rx(priv);
1959                 handled |= IPW_INTA_BIT_RX_TRANSFER;
1960         }
1961
1962         if (inta & IPW_INTA_BIT_TX_CMD_QUEUE) {
1963                 IPW_DEBUG_HC("Command completed.\n");
1964                 rc = ipw_queue_tx_reclaim(priv, &priv->txq_cmd, -1);
1965                 priv->status &= ~STATUS_HCMD_ACTIVE;
1966                 wake_up_interruptible(&priv->wait_command_queue);
1967                 handled |= IPW_INTA_BIT_TX_CMD_QUEUE;
1968         }
1969
1970         if (inta & IPW_INTA_BIT_TX_QUEUE_1) {
1971                 IPW_DEBUG_TX("TX_QUEUE_1\n");
1972                 rc = ipw_queue_tx_reclaim(priv, &priv->txq[0], 0);
1973                 handled |= IPW_INTA_BIT_TX_QUEUE_1;
1974         }
1975
1976         if (inta & IPW_INTA_BIT_TX_QUEUE_2) {
1977                 IPW_DEBUG_TX("TX_QUEUE_2\n");
1978                 rc = ipw_queue_tx_reclaim(priv, &priv->txq[1], 1);
1979                 handled |= IPW_INTA_BIT_TX_QUEUE_2;
1980         }
1981
1982         if (inta & IPW_INTA_BIT_TX_QUEUE_3) {
1983                 IPW_DEBUG_TX("TX_QUEUE_3\n");
1984                 rc = ipw_queue_tx_reclaim(priv, &priv->txq[2], 2);
1985                 handled |= IPW_INTA_BIT_TX_QUEUE_3;
1986         }
1987
1988         if (inta & IPW_INTA_BIT_TX_QUEUE_4) {
1989                 IPW_DEBUG_TX("TX_QUEUE_4\n");
1990                 rc = ipw_queue_tx_reclaim(priv, &priv->txq[3], 3);
1991                 handled |= IPW_INTA_BIT_TX_QUEUE_4;
1992         }
1993
1994         if (inta & IPW_INTA_BIT_STATUS_CHANGE) {
1995                 IPW_WARNING("STATUS_CHANGE\n");
1996                 handled |= IPW_INTA_BIT_STATUS_CHANGE;
1997         }
1998
1999         if (inta & IPW_INTA_BIT_BEACON_PERIOD_EXPIRED) {
2000                 IPW_WARNING("TX_PERIOD_EXPIRED\n");
2001                 handled |= IPW_INTA_BIT_BEACON_PERIOD_EXPIRED;
2002         }
2003
2004         if (inta & IPW_INTA_BIT_SLAVE_MODE_HOST_CMD_DONE) {
2005                 IPW_WARNING("HOST_CMD_DONE\n");
2006                 handled |= IPW_INTA_BIT_SLAVE_MODE_HOST_CMD_DONE;
2007         }
2008
2009         if (inta & IPW_INTA_BIT_FW_INITIALIZATION_DONE) {
2010                 IPW_WARNING("FW_INITIALIZATION_DONE\n");
2011                 handled |= IPW_INTA_BIT_FW_INITIALIZATION_DONE;
2012         }
2013
2014         if (inta & IPW_INTA_BIT_FW_CARD_DISABLE_PHY_OFF_DONE) {
2015                 IPW_WARNING("PHY_OFF_DONE\n");
2016                 handled |= IPW_INTA_BIT_FW_CARD_DISABLE_PHY_OFF_DONE;
2017         }
2018
2019         if (inta & IPW_INTA_BIT_RF_KILL_DONE) {
2020                 IPW_DEBUG_RF_KILL("RF_KILL_DONE\n");
2021                 priv->status |= STATUS_RF_KILL_HW;
2022                 wake_up_interruptible(&priv->wait_command_queue);
2023                 priv->status &= ~(STATUS_ASSOCIATED | STATUS_ASSOCIATING);
2024                 cancel_delayed_work(&priv->request_scan);
2025                 cancel_delayed_work(&priv->request_direct_scan);
2026                 cancel_delayed_work(&priv->request_passive_scan);
2027                 cancel_delayed_work(&priv->scan_event);
2028                 schedule_work(&priv->link_down);
2029                 queue_delayed_work(priv->workqueue, &priv->rf_kill, 2 * HZ);
2030                 handled |= IPW_INTA_BIT_RF_KILL_DONE;
2031         }
2032
2033         if (inta & IPW_INTA_BIT_FATAL_ERROR) {
2034                 IPW_WARNING("Firmware error detected.  Restarting.\n");
2035                 if (priv->error) {
2036                         IPW_DEBUG_FW("Sysfs 'error' log already exists.\n");
2037                         if (ipw_debug_level & IPW_DL_FW_ERRORS) {
2038                                 struct ipw_fw_error *error =
2039                                     ipw_alloc_error_log(priv);
2040                                 ipw_dump_error_log(priv, error);
2041                                 kfree(error);
2042                         }
2043                 } else {
2044                         priv->error = ipw_alloc_error_log(priv);
2045                         if (priv->error)
2046                                 IPW_DEBUG_FW("Sysfs 'error' log captured.\n");
2047                         else
2048                                 IPW_DEBUG_FW("Error allocating sysfs 'error' "
2049                                              "log.\n");
2050                         if (ipw_debug_level & IPW_DL_FW_ERRORS)
2051                                 ipw_dump_error_log(priv, priv->error);
2052                 }
2053
2054                 /* XXX: If hardware encryption is for WPA/WPA2,
2055                  * we have to notify the supplicant. */
2056                 if (priv->ieee->sec.encrypt) {
2057                         priv->status &= ~STATUS_ASSOCIATED;
2058                         notify_wx_assoc_event(priv);
2059                 }
2060
2061                 /* Keep the restart process from trying to send host
2062                  * commands by clearing the INIT status bit */
2063                 priv->status &= ~STATUS_INIT;
2064
2065                 /* Cancel currently queued command. */
2066                 priv->status &= ~STATUS_HCMD_ACTIVE;
2067                 wake_up_interruptible(&priv->wait_command_queue);
2068
2069                 queue_work(priv->workqueue, &priv->adapter_restart);
2070                 handled |= IPW_INTA_BIT_FATAL_ERROR;
2071         }
2072
2073         if (inta & IPW_INTA_BIT_PARITY_ERROR) {
2074                 IPW_ERROR("Parity error\n");
2075                 handled |= IPW_INTA_BIT_PARITY_ERROR;
2076         }
2077
2078         if (handled != inta) {
2079                 IPW_ERROR("Unhandled INTA bits 0x%08x\n", inta & ~handled);
2080         }
2081
2082         spin_unlock_irqrestore(&priv->lock, flags);
2083
2084         /* enable all interrupts */
2085         ipw_enable_interrupts(priv);
2086 }
2087
2088 #define IPW_CMD(x) case IPW_CMD_ ## x : return #x
2089 static char *get_cmd_string(u8 cmd)
2090 {
2091         switch (cmd) {
2092                 IPW_CMD(HOST_COMPLETE);
2093                 IPW_CMD(POWER_DOWN);
2094                 IPW_CMD(SYSTEM_CONFIG);
2095                 IPW_CMD(MULTICAST_ADDRESS);
2096                 IPW_CMD(SSID);
2097                 IPW_CMD(ADAPTER_ADDRESS);
2098                 IPW_CMD(PORT_TYPE);
2099                 IPW_CMD(RTS_THRESHOLD);
2100                 IPW_CMD(FRAG_THRESHOLD);
2101                 IPW_CMD(POWER_MODE);
2102                 IPW_CMD(WEP_KEY);
2103                 IPW_CMD(TGI_TX_KEY);
2104                 IPW_CMD(SCAN_REQUEST);
2105                 IPW_CMD(SCAN_REQUEST_EXT);
2106                 IPW_CMD(ASSOCIATE);
2107                 IPW_CMD(SUPPORTED_RATES);
2108                 IPW_CMD(SCAN_ABORT);
2109                 IPW_CMD(TX_FLUSH);
2110                 IPW_CMD(QOS_PARAMETERS);
2111                 IPW_CMD(DINO_CONFIG);
2112                 IPW_CMD(RSN_CAPABILITIES);
2113                 IPW_CMD(RX_KEY);
2114                 IPW_CMD(CARD_DISABLE);
2115                 IPW_CMD(SEED_NUMBER);
2116                 IPW_CMD(TX_POWER);
2117                 IPW_CMD(COUNTRY_INFO);
2118                 IPW_CMD(AIRONET_INFO);
2119                 IPW_CMD(AP_TX_POWER);
2120                 IPW_CMD(CCKM_INFO);
2121                 IPW_CMD(CCX_VER_INFO);
2122                 IPW_CMD(SET_CALIBRATION);
2123                 IPW_CMD(SENSITIVITY_CALIB);
2124                 IPW_CMD(RETRY_LIMIT);
2125                 IPW_CMD(IPW_PRE_POWER_DOWN);
2126                 IPW_CMD(VAP_BEACON_TEMPLATE);
2127                 IPW_CMD(VAP_DTIM_PERIOD);
2128                 IPW_CMD(EXT_SUPPORTED_RATES);
2129                 IPW_CMD(VAP_LOCAL_TX_PWR_CONSTRAINT);
2130                 IPW_CMD(VAP_QUIET_INTERVALS);
2131                 IPW_CMD(VAP_CHANNEL_SWITCH);
2132                 IPW_CMD(VAP_MANDATORY_CHANNELS);
2133                 IPW_CMD(VAP_CELL_PWR_LIMIT);
2134                 IPW_CMD(VAP_CF_PARAM_SET);
2135                 IPW_CMD(VAP_SET_BEACONING_STATE);
2136                 IPW_CMD(MEASUREMENT);
2137                 IPW_CMD(POWER_CAPABILITY);
2138                 IPW_CMD(SUPPORTED_CHANNELS);
2139                 IPW_CMD(TPC_REPORT);
2140                 IPW_CMD(WME_INFO);
2141                 IPW_CMD(PRODUCTION_COMMAND);
2142         default:
2143                 return "UNKNOWN";
2144         }
2145 }
2146
2147 #define HOST_COMPLETE_TIMEOUT HZ
2148
2149 static int __ipw_send_cmd(struct ipw_priv *priv, struct host_cmd *cmd)
2150 {
2151         int rc = 0;
2152         unsigned long flags;
2153
2154         spin_lock_irqsave(&priv->lock, flags);
2155         if (priv->status & STATUS_HCMD_ACTIVE) {
2156                 IPW_ERROR("Failed to send %s: Already sending a command.\n",
2157                           get_cmd_string(cmd->cmd));
2158                 spin_unlock_irqrestore(&priv->lock, flags);
2159                 return -EAGAIN;
2160         }
2161
2162         priv->status |= STATUS_HCMD_ACTIVE;
2163
2164         if (priv->cmdlog) {
2165                 priv->cmdlog[priv->cmdlog_pos].jiffies = jiffies;
2166                 priv->cmdlog[priv->cmdlog_pos].cmd.cmd = cmd->cmd;
2167                 priv->cmdlog[priv->cmdlog_pos].cmd.len = cmd->len;
2168                 memcpy(priv->cmdlog[priv->cmdlog_pos].cmd.param, cmd->param,
2169                        cmd->len);
2170                 priv->cmdlog[priv->cmdlog_pos].retcode = -1;
2171         }
2172
2173         IPW_DEBUG_HC("%s command (#%d) %d bytes: 0x%08X\n",
2174                      get_cmd_string(cmd->cmd), cmd->cmd, cmd->len,
2175                      priv->status);
2176
2177 #ifndef DEBUG_CMD_WEP_KEY
2178         if (cmd->cmd == IPW_CMD_WEP_KEY)
2179                 IPW_DEBUG_HC("WEP_KEY command masked out for secure.\n");
2180         else
2181 #endif
2182                 printk_buf(IPW_DL_HOST_COMMAND, (u8 *) cmd->param, cmd->len);
2183
2184         rc = ipw_queue_tx_hcmd(priv, cmd->cmd, cmd->param, cmd->len, 0);
2185         if (rc) {
2186                 priv->status &= ~STATUS_HCMD_ACTIVE;
2187                 IPW_ERROR("Failed to send %s: Reason %d\n",
2188                           get_cmd_string(cmd->cmd), rc);
2189                 spin_unlock_irqrestore(&priv->lock, flags);
2190                 goto exit;
2191         }
2192         spin_unlock_irqrestore(&priv->lock, flags);
2193
2194         rc = wait_event_interruptible_timeout(priv->wait_command_queue,
2195                                               !(priv->
2196                                                 status & STATUS_HCMD_ACTIVE),
2197                                               HOST_COMPLETE_TIMEOUT);
2198         if (rc == 0) {
2199                 spin_lock_irqsave(&priv->lock, flags);
2200                 if (priv->status & STATUS_HCMD_ACTIVE) {
2201                         IPW_ERROR("Failed to send %s: Command timed out.\n",
2202                                   get_cmd_string(cmd->cmd));
2203                         priv->status &= ~STATUS_HCMD_ACTIVE;
2204                         spin_unlock_irqrestore(&priv->lock, flags);
2205                         rc = -EIO;
2206                         goto exit;
2207                 }
2208                 spin_unlock_irqrestore(&priv->lock, flags);
2209         } else
2210                 rc = 0;
2211
2212         if (priv->status & STATUS_RF_KILL_HW) {
2213                 IPW_ERROR("Failed to send %s: Aborted due to RF kill switch.\n",
2214                           get_cmd_string(cmd->cmd));
2215                 rc = -EIO;
2216                 goto exit;
2217         }
2218
2219       exit:
2220         if (priv->cmdlog) {
2221                 priv->cmdlog[priv->cmdlog_pos++].retcode = rc;
2222                 priv->cmdlog_pos %= priv->cmdlog_len;
2223         }
2224         return rc;
2225 }
2226
2227 static int ipw_send_cmd_simple(struct ipw_priv *priv, u8 command)
2228 {
2229         struct host_cmd cmd = {
2230                 .cmd = command,
2231         };
2232
2233         return __ipw_send_cmd(priv, &cmd);
2234 }
2235
2236 static int ipw_send_cmd_pdu(struct ipw_priv *priv, u8 command, u8 len,
2237                             void *data)
2238 {
2239         struct host_cmd cmd = {
2240                 .cmd = command,
2241                 .len = len,
2242                 .param = data,
2243         };
2244
2245         return __ipw_send_cmd(priv, &cmd);
2246 }
2247
2248 static int ipw_send_host_complete(struct ipw_priv *priv)
2249 {
2250         if (!priv) {
2251                 IPW_ERROR("Invalid args\n");
2252                 return -1;
2253         }
2254
2255         return ipw_send_cmd_simple(priv, IPW_CMD_HOST_COMPLETE);
2256 }
2257
2258 static int ipw_send_system_config(struct ipw_priv *priv)
2259 {
2260         return ipw_send_cmd_pdu(priv, IPW_CMD_SYSTEM_CONFIG,
2261                                 sizeof(priv->sys_config),
2262                                 &priv->sys_config);
2263 }
2264
2265 static int ipw_send_ssid(struct ipw_priv *priv, u8 * ssid, int len)
2266 {
2267         if (!priv || !ssid) {
2268                 IPW_ERROR("Invalid args\n");
2269                 return -1;
2270         }
2271
2272         return ipw_send_cmd_pdu(priv, IPW_CMD_SSID, min(len, IW_ESSID_MAX_SIZE),
2273                                 ssid);
2274 }
2275
2276 static int ipw_send_adapter_address(struct ipw_priv *priv, u8 * mac)
2277 {
2278         if (!priv || !mac) {
2279                 IPW_ERROR("Invalid args\n");
2280                 return -1;
2281         }
2282
2283         IPW_DEBUG_INFO("%s: Setting MAC to %pM\n",
2284                        priv->net_dev->name, mac);
2285
2286         return ipw_send_cmd_pdu(priv, IPW_CMD_ADAPTER_ADDRESS, ETH_ALEN, mac);
2287 }
2288
2289 /*
2290  * NOTE: This must be executed from our workqueue as it results in udelay
2291  * being called which may corrupt the keyboard if executed on default
2292  * workqueue
2293  */
2294 static void ipw_adapter_restart(void *adapter)
2295 {
2296         struct ipw_priv *priv = adapter;
2297
2298         if (priv->status & STATUS_RF_KILL_MASK)
2299                 return;
2300
2301         ipw_down(priv);
2302
2303         if (priv->assoc_network &&
2304             (priv->assoc_network->capability & WLAN_CAPABILITY_IBSS))
2305                 ipw_remove_current_network(priv);
2306
2307         if (ipw_up(priv)) {
2308                 IPW_ERROR("Failed to up device\n");
2309                 return;
2310         }
2311 }
2312
2313 static void ipw_bg_adapter_restart(struct work_struct *work)
2314 {
2315         struct ipw_priv *priv =
2316                 container_of(work, struct ipw_priv, adapter_restart);
2317         mutex_lock(&priv->mutex);
2318         ipw_adapter_restart(priv);
2319         mutex_unlock(&priv->mutex);
2320 }
2321
2322 #define IPW_SCAN_CHECK_WATCHDOG (5 * HZ)
2323
2324 static void ipw_scan_check(void *data)
2325 {
2326         struct ipw_priv *priv = data;
2327         if (priv->status & (STATUS_SCANNING | STATUS_SCAN_ABORTING)) {
2328                 IPW_DEBUG_SCAN("Scan completion watchdog resetting "
2329                                "adapter after (%dms).\n",
2330                                jiffies_to_msecs(IPW_SCAN_CHECK_WATCHDOG));
2331                 queue_work(priv->workqueue, &priv->adapter_restart);
2332         }
2333 }
2334
2335 static void ipw_bg_scan_check(struct work_struct *work)
2336 {
2337         struct ipw_priv *priv =
2338                 container_of(work, struct ipw_priv, scan_check.work);
2339         mutex_lock(&priv->mutex);
2340         ipw_scan_check(priv);
2341         mutex_unlock(&priv->mutex);
2342 }
2343
2344 static int ipw_send_scan_request_ext(struct ipw_priv *priv,
2345                                      struct ipw_scan_request_ext *request)
2346 {
2347         return ipw_send_cmd_pdu(priv, IPW_CMD_SCAN_REQUEST_EXT,
2348                                 sizeof(*request), request);
2349 }
2350
2351 static int ipw_send_scan_abort(struct ipw_priv *priv)
2352 {
2353         if (!priv) {
2354                 IPW_ERROR("Invalid args\n");
2355                 return -1;
2356         }
2357
2358         return ipw_send_cmd_simple(priv, IPW_CMD_SCAN_ABORT);
2359 }
2360
2361 static int ipw_set_sensitivity(struct ipw_priv *priv, u16 sens)
2362 {
2363         struct ipw_sensitivity_calib calib = {
2364                 .beacon_rssi_raw = cpu_to_le16(sens),
2365         };
2366
2367         return ipw_send_cmd_pdu(priv, IPW_CMD_SENSITIVITY_CALIB, sizeof(calib),
2368                                 &calib);
2369 }
2370
2371 static int ipw_send_associate(struct ipw_priv *priv,
2372                               struct ipw_associate *associate)
2373 {
2374         if (!priv || !associate) {
2375                 IPW_ERROR("Invalid args\n");
2376                 return -1;
2377         }
2378
2379         return ipw_send_cmd_pdu(priv, IPW_CMD_ASSOCIATE, sizeof(*associate),
2380                                 associate);
2381 }
2382
2383 static int ipw_send_supported_rates(struct ipw_priv *priv,
2384                                     struct ipw_supported_rates *rates)
2385 {
2386         if (!priv || !rates) {
2387                 IPW_ERROR("Invalid args\n");
2388                 return -1;
2389         }
2390
2391         return ipw_send_cmd_pdu(priv, IPW_CMD_SUPPORTED_RATES, sizeof(*rates),
2392                                 rates);
2393 }
2394
2395 static int ipw_set_random_seed(struct ipw_priv *priv)
2396 {
2397         u32 val;
2398
2399         if (!priv) {
2400                 IPW_ERROR("Invalid args\n");
2401                 return -1;
2402         }
2403
2404         get_random_bytes(&val, sizeof(val));
2405
2406         return ipw_send_cmd_pdu(priv, IPW_CMD_SEED_NUMBER, sizeof(val), &val);
2407 }
2408
2409 static int ipw_send_card_disable(struct ipw_priv *priv, u32 phy_off)
2410 {
2411         __le32 v = cpu_to_le32(phy_off);
2412         if (!priv) {
2413                 IPW_ERROR("Invalid args\n");
2414                 return -1;
2415         }
2416
2417         return ipw_send_cmd_pdu(priv, IPW_CMD_CARD_DISABLE, sizeof(v), &v);
2418 }
2419
2420 static int ipw_send_tx_power(struct ipw_priv *priv, struct ipw_tx_power *power)
2421 {
2422         if (!priv || !power) {
2423                 IPW_ERROR("Invalid args\n");
2424                 return -1;
2425         }
2426
2427         return ipw_send_cmd_pdu(priv, IPW_CMD_TX_POWER, sizeof(*power), power);
2428 }
2429
2430 static int ipw_set_tx_power(struct ipw_priv *priv)
2431 {
2432         const struct libipw_geo *geo = libipw_get_geo(priv->ieee);
2433         struct ipw_tx_power tx_power;
2434         s8 max_power;
2435         int i;
2436
2437         memset(&tx_power, 0, sizeof(tx_power));
2438
2439         /* configure device for 'G' band */
2440         tx_power.ieee_mode = IPW_G_MODE;
2441         tx_power.num_channels = geo->bg_channels;
2442         for (i = 0; i < geo->bg_channels; i++) {
2443                 max_power = geo->bg[i].max_power;
2444                 tx_power.channels_tx_power[i].channel_number =
2445                     geo->bg[i].channel;
2446                 tx_power.channels_tx_power[i].tx_power = max_power ?
2447                     min(max_power, priv->tx_power) : priv->tx_power;
2448         }
2449         if (ipw_send_tx_power(priv, &tx_power))
2450                 return -EIO;
2451
2452         /* configure device to also handle 'B' band */
2453         tx_power.ieee_mode = IPW_B_MODE;
2454         if (ipw_send_tx_power(priv, &tx_power))
2455                 return -EIO;
2456
2457         /* configure device to also handle 'A' band */
2458         if (priv->ieee->abg_true) {
2459                 tx_power.ieee_mode = IPW_A_MODE;
2460                 tx_power.num_channels = geo->a_channels;
2461                 for (i = 0; i < tx_power.num_channels; i++) {
2462                         max_power = geo->a[i].max_power;
2463                         tx_power.channels_tx_power[i].channel_number =
2464                             geo->a[i].channel;
2465                         tx_power.channels_tx_power[i].tx_power = max_power ?
2466                             min(max_power, priv->tx_power) : priv->tx_power;
2467                 }
2468                 if (ipw_send_tx_power(priv, &tx_power))
2469                         return -EIO;
2470         }
2471         return 0;
2472 }
2473
2474 static int ipw_send_rts_threshold(struct ipw_priv *priv, u16 rts)
2475 {
2476         struct ipw_rts_threshold rts_threshold = {
2477                 .rts_threshold = cpu_to_le16(rts),
2478         };
2479
2480         if (!priv) {
2481                 IPW_ERROR("Invalid args\n");
2482                 return -1;
2483         }
2484
2485         return ipw_send_cmd_pdu(priv, IPW_CMD_RTS_THRESHOLD,
2486                                 sizeof(rts_threshold), &rts_threshold);
2487 }
2488
2489 static int ipw_send_frag_threshold(struct ipw_priv *priv, u16 frag)
2490 {
2491         struct ipw_frag_threshold frag_threshold = {
2492                 .frag_threshold = cpu_to_le16(frag),
2493         };
2494
2495         if (!priv) {
2496                 IPW_ERROR("Invalid args\n");
2497                 return -1;
2498         }
2499
2500         return ipw_send_cmd_pdu(priv, IPW_CMD_FRAG_THRESHOLD,
2501                                 sizeof(frag_threshold), &frag_threshold);
2502 }
2503
2504 static int ipw_send_power_mode(struct ipw_priv *priv, u32 mode)
2505 {
2506         __le32 param;
2507
2508         if (!priv) {
2509                 IPW_ERROR("Invalid args\n");
2510                 return -1;
2511         }
2512
2513         /* If on battery, set to 3, if AC set to CAM, else user
2514          * level */
2515         switch (mode) {
2516         case IPW_POWER_BATTERY:
2517                 param = cpu_to_le32(IPW_POWER_INDEX_3);
2518                 break;
2519         case IPW_POWER_AC:
2520                 param = cpu_to_le32(IPW_POWER_MODE_CAM);
2521                 break;
2522         default:
2523                 param = cpu_to_le32(mode);
2524                 break;
2525         }
2526
2527         return ipw_send_cmd_pdu(priv, IPW_CMD_POWER_MODE, sizeof(param),
2528                                 &param);
2529 }
2530
2531 static int ipw_send_retry_limit(struct ipw_priv *priv, u8 slimit, u8 llimit)
2532 {
2533         struct ipw_retry_limit retry_limit = {
2534                 .short_retry_limit = slimit,
2535                 .long_retry_limit = llimit
2536         };
2537
2538         if (!priv) {
2539                 IPW_ERROR("Invalid args\n");
2540                 return -1;
2541         }
2542
2543         return ipw_send_cmd_pdu(priv, IPW_CMD_RETRY_LIMIT, sizeof(retry_limit),
2544                                 &retry_limit);
2545 }
2546
2547 /*
2548  * The IPW device contains a Microwire compatible EEPROM that stores
2549  * various data like the MAC address.  Usually the firmware has exclusive
2550  * access to the eeprom, but during device initialization (before the
2551  * device driver has sent the HostComplete command to the firmware) the
2552  * device driver has read access to the EEPROM by way of indirect addressing
2553  * through a couple of memory mapped registers.
2554  *
2555  * The following is a simplified implementation for pulling data out of the
2556  * the eeprom, along with some helper functions to find information in
2557  * the per device private data's copy of the eeprom.
2558  *
2559  * NOTE: To better understand how these functions work (i.e what is a chip
2560  *       select and why do have to keep driving the eeprom clock?), read
2561  *       just about any data sheet for a Microwire compatible EEPROM.
2562  */
2563
2564 /* write a 32 bit value into the indirect accessor register */
2565 static inline void eeprom_write_reg(struct ipw_priv *p, u32 data)
2566 {
2567         ipw_write_reg32(p, FW_MEM_REG_EEPROM_ACCESS, data);
2568
2569         /* the eeprom requires some time to complete the operation */
2570         udelay(p->eeprom_delay);
2571
2572         return;
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], 6);
2647 }
2648
2649 /*
2650  * Either the device driver (i.e. the host) or the firmware can
2651  * load eeprom data into the designated region in SRAM.  If neither
2652  * happens then the FW will shutdown with a fatal error.
2653  *
2654  * In order to signal the FW to load the EEPROM, the EEPROM_LOAD_DISABLE
2655  * bit needs region of shared SRAM needs to be non-zero.
2656  */
2657 static void ipw_eeprom_init_sram(struct ipw_priv *priv)
2658 {
2659         int i;
2660         __le16 *eeprom = (__le16 *) priv->eeprom;
2661
2662         IPW_DEBUG_TRACE(">>\n");
2663
2664         /* read entire contents of eeprom into private buffer */
2665         for (i = 0; i < 128; i++)
2666                 eeprom[i] = cpu_to_le16(eeprom_read_u16(priv, (u8) i));
2667
2668         /*
2669            If the data looks correct, then copy it to our private
2670            copy.  Otherwise let the firmware know to perform the operation
2671            on its own.
2672          */
2673         if (priv->eeprom[EEPROM_VERSION] != 0) {
2674                 IPW_DEBUG_INFO("Writing EEPROM data into SRAM\n");
2675
2676                 /* write the eeprom data to sram */
2677                 for (i = 0; i < IPW_EEPROM_IMAGE_SIZE; i++)
2678                         ipw_write8(priv, IPW_EEPROM_DATA + i, priv->eeprom[i]);
2679
2680                 /* Do not load eeprom data on fatal error or suspend */
2681                 ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 0);
2682         } else {
2683                 IPW_DEBUG_INFO("Enabling FW initializationg of SRAM\n");
2684
2685                 /* Load eeprom data on fatal error or suspend */
2686                 ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 1);
2687         }
2688
2689         IPW_DEBUG_TRACE("<<\n");
2690 }
2691
2692 static void ipw_zero_memory(struct ipw_priv *priv, u32 start, u32 count)
2693 {
2694         count >>= 2;
2695         if (!count)
2696                 return;
2697         _ipw_write32(priv, IPW_AUTOINC_ADDR, start);
2698         while (count--)
2699                 _ipw_write32(priv, IPW_AUTOINC_DATA, 0);
2700 }
2701
2702 static inline void ipw_fw_dma_reset_command_blocks(struct ipw_priv *priv)
2703 {
2704         ipw_zero_memory(priv, IPW_SHARED_SRAM_DMA_CONTROL,
2705                         CB_NUMBER_OF_ELEMENTS_SMALL *
2706                         sizeof(struct command_block));
2707 }
2708
2709 static int ipw_fw_dma_enable(struct ipw_priv *priv)
2710 {                               /* start dma engine but no transfers yet */
2711
2712         IPW_DEBUG_FW(">> : \n");
2713
2714         /* Start the dma */
2715         ipw_fw_dma_reset_command_blocks(priv);
2716
2717         /* Write CB base address */
2718         ipw_write_reg32(priv, IPW_DMA_I_CB_BASE, IPW_SHARED_SRAM_DMA_CONTROL);
2719
2720         IPW_DEBUG_FW("<< : \n");
2721         return 0;
2722 }
2723
2724 static void ipw_fw_dma_abort(struct ipw_priv *priv)
2725 {
2726         u32 control = 0;
2727
2728         IPW_DEBUG_FW(">> :\n");
2729
2730         /* set the Stop and Abort bit */
2731         control = DMA_CONTROL_SMALL_CB_CONST_VALUE | DMA_CB_STOP_AND_ABORT;
2732         ipw_write_reg32(priv, IPW_DMA_I_DMA_CONTROL, control);
2733         priv->sram_desc.last_cb_index = 0;
2734
2735         IPW_DEBUG_FW("<< \n");
2736 }
2737
2738 static int ipw_fw_dma_write_command_block(struct ipw_priv *priv, int index,
2739                                           struct command_block *cb)
2740 {
2741         u32 address =
2742             IPW_SHARED_SRAM_DMA_CONTROL +
2743             (sizeof(struct command_block) * index);
2744         IPW_DEBUG_FW(">> :\n");
2745
2746         ipw_write_indirect(priv, address, (u8 *) cb,
2747                            (int)sizeof(struct command_block));
2748
2749         IPW_DEBUG_FW("<< :\n");
2750         return 0;
2751
2752 }
2753
2754 static int ipw_fw_dma_kick(struct ipw_priv *priv)
2755 {
2756         u32 control = 0;
2757         u32 index = 0;
2758
2759         IPW_DEBUG_FW(">> :\n");
2760
2761         for (index = 0; index < priv->sram_desc.last_cb_index; index++)
2762                 ipw_fw_dma_write_command_block(priv, index,
2763                                                &priv->sram_desc.cb_list[index]);
2764
2765         /* Enable the DMA in the CSR register */
2766         ipw_clear_bit(priv, IPW_RESET_REG,
2767                       IPW_RESET_REG_MASTER_DISABLED |
2768                       IPW_RESET_REG_STOP_MASTER);
2769
2770         /* Set the Start bit. */
2771         control = DMA_CONTROL_SMALL_CB_CONST_VALUE | DMA_CB_START;
2772         ipw_write_reg32(priv, IPW_DMA_I_DMA_CONTROL, control);
2773
2774         IPW_DEBUG_FW("<< :\n");
2775         return 0;
2776 }
2777
2778 static void ipw_fw_dma_dump_command_block(struct ipw_priv *priv)
2779 {
2780         u32 address;
2781         u32 register_value = 0;
2782         u32 cb_fields_address = 0;
2783
2784         IPW_DEBUG_FW(">> :\n");
2785         address = ipw_read_reg32(priv, IPW_DMA_I_CURRENT_CB);
2786         IPW_DEBUG_FW_INFO("Current CB is 0x%x \n", address);
2787
2788         /* Read the DMA Controlor register */
2789         register_value = ipw_read_reg32(priv, IPW_DMA_I_DMA_CONTROL);
2790         IPW_DEBUG_FW_INFO("IPW_DMA_I_DMA_CONTROL is 0x%x \n", register_value);
2791
2792         /* Print the CB values */
2793         cb_fields_address = address;
2794         register_value = ipw_read_reg32(priv, cb_fields_address);
2795         IPW_DEBUG_FW_INFO("Current CB ControlField is 0x%x \n", register_value);
2796
2797         cb_fields_address += sizeof(u32);
2798         register_value = ipw_read_reg32(priv, cb_fields_address);
2799         IPW_DEBUG_FW_INFO("Current CB Source Field is 0x%x \n", register_value);
2800
2801         cb_fields_address += sizeof(u32);
2802         register_value = ipw_read_reg32(priv, cb_fields_address);
2803         IPW_DEBUG_FW_INFO("Current CB Destination Field is 0x%x \n",
2804                           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 Status Field is 0x%x \n", register_value);
2809
2810         IPW_DEBUG_FW(">> :\n");
2811 }
2812
2813 static int ipw_fw_dma_command_block_index(struct ipw_priv *priv)
2814 {
2815         u32 current_cb_address = 0;
2816         u32 current_cb_index = 0;
2817
2818         IPW_DEBUG_FW("<< :\n");
2819         current_cb_address = ipw_read_reg32(priv, IPW_DMA_I_CURRENT_CB);
2820
2821         current_cb_index = (current_cb_address - IPW_SHARED_SRAM_DMA_CONTROL) /
2822             sizeof(struct command_block);
2823
2824         IPW_DEBUG_FW_INFO("Current CB index 0x%x address = 0x%X \n",
2825                           current_cb_index, current_cb_address);
2826
2827         IPW_DEBUG_FW(">> :\n");
2828         return current_cb_index;
2829
2830 }
2831
2832 static int ipw_fw_dma_add_command_block(struct ipw_priv *priv,
2833                                         u32 src_address,
2834                                         u32 dest_address,
2835                                         u32 length,
2836                                         int interrupt_enabled, int is_last)
2837 {
2838
2839         u32 control = CB_VALID | CB_SRC_LE | CB_DEST_LE | CB_SRC_AUTOINC |
2840             CB_SRC_IO_GATED | CB_DEST_AUTOINC | CB_SRC_SIZE_LONG |
2841             CB_DEST_SIZE_LONG;
2842         struct command_block *cb;
2843         u32 last_cb_element = 0;
2844
2845         IPW_DEBUG_FW_INFO("src_address=0x%x dest_address=0x%x length=0x%x\n",
2846                           src_address, dest_address, length);
2847
2848         if (priv->sram_desc.last_cb_index >= CB_NUMBER_OF_ELEMENTS_SMALL)
2849                 return -1;
2850
2851         last_cb_element = priv->sram_desc.last_cb_index;
2852         cb = &priv->sram_desc.cb_list[last_cb_element];
2853         priv->sram_desc.last_cb_index++;
2854
2855         /* Calculate the new CB control word */
2856         if (interrupt_enabled)
2857                 control |= CB_INT_ENABLED;
2858
2859         if (is_last)
2860                 control |= CB_LAST_VALID;
2861
2862         control |= length;
2863
2864         /* Calculate the CB Element's checksum value */
2865         cb->status = control ^ src_address ^ dest_address;
2866
2867         /* Copy the Source and Destination addresses */
2868         cb->dest_addr = dest_address;
2869         cb->source_addr = src_address;
2870
2871         /* Copy the Control Word last */
2872         cb->control = control;
2873
2874         return 0;
2875 }
2876
2877 static int ipw_fw_dma_add_buffer(struct ipw_priv *priv, dma_addr_t *src_address,
2878                                  int nr, u32 dest_address, u32 len)
2879 {
2880         int ret, i;
2881         u32 size;
2882
2883         IPW_DEBUG_FW(">> \n");
2884         IPW_DEBUG_FW_INFO("nr=%d dest_address=0x%x len=0x%x\n",
2885                           nr, dest_address, len);
2886
2887         for (i = 0; i < nr; i++) {
2888                 size = min_t(u32, len - i * CB_MAX_LENGTH, CB_MAX_LENGTH);
2889                 ret = ipw_fw_dma_add_command_block(priv, src_address[i],
2890                                                    dest_address +
2891                                                    i * CB_MAX_LENGTH, size,
2892                                                    0, 0);
2893                 if (ret) {
2894                         IPW_DEBUG_FW_INFO(": Failed\n");
2895                         return -1;
2896                 } else
2897                         IPW_DEBUG_FW_INFO(": Added new cb\n");
2898         }
2899
2900         IPW_DEBUG_FW("<< \n");
2901         return 0;
2902 }
2903
2904 static int ipw_fw_dma_wait(struct ipw_priv *priv)
2905 {
2906         u32 current_index = 0, previous_index;
2907         u32 watchdog = 0;
2908
2909         IPW_DEBUG_FW(">> : \n");
2910
2911         current_index = ipw_fw_dma_command_block_index(priv);
2912         IPW_DEBUG_FW_INFO("sram_desc.last_cb_index:0x%08X\n",
2913                           (int)priv->sram_desc.last_cb_index);
2914
2915         while (current_index < priv->sram_desc.last_cb_index) {
2916                 udelay(50);
2917                 previous_index = current_index;
2918                 current_index = ipw_fw_dma_command_block_index(priv);
2919
2920                 if (previous_index < current_index) {
2921                         watchdog = 0;
2922                         continue;
2923                 }
2924                 if (++watchdog > 400) {
2925                         IPW_DEBUG_FW_INFO("Timeout\n");
2926                         ipw_fw_dma_dump_command_block(priv);
2927                         ipw_fw_dma_abort(priv);
2928                         return -1;
2929                 }
2930         }
2931
2932         ipw_fw_dma_abort(priv);
2933
2934         /*Disable the DMA in the CSR register */
2935         ipw_set_bit(priv, IPW_RESET_REG,
2936                     IPW_RESET_REG_MASTER_DISABLED | IPW_RESET_REG_STOP_MASTER);
2937
2938         IPW_DEBUG_FW("<< dmaWaitSync \n");
2939         return 0;
2940 }
2941
2942 static void ipw_remove_current_network(struct ipw_priv *priv)
2943 {
2944         struct list_head *element, *safe;
2945         struct libipw_network *network = NULL;
2946         unsigned long flags;
2947
2948         spin_lock_irqsave(&priv->ieee->lock, flags);
2949         list_for_each_safe(element, safe, &priv->ieee->network_list) {
2950                 network = list_entry(element, struct libipw_network, list);
2951                 if (!memcmp(network->bssid, priv->bssid, ETH_ALEN)) {
2952                         list_del(element);
2953                         list_add_tail(&network->list,
2954                                       &priv->ieee->network_free_list);
2955                 }
2956         }
2957         spin_unlock_irqrestore(&priv->ieee->lock, flags);
2958 }
2959
2960 /**
2961  * Check that card is still alive.
2962  * Reads debug register from domain0.
2963  * If card is present, pre-defined value should
2964  * be found there.
2965  *
2966  * @param priv
2967  * @return 1 if card is present, 0 otherwise
2968  */
2969 static inline int ipw_alive(struct ipw_priv *priv)
2970 {
2971         return ipw_read32(priv, 0x90) == 0xd55555d5;
2972 }
2973
2974 /* timeout in msec, attempted in 10-msec quanta */
2975 static int ipw_poll_bit(struct ipw_priv *priv, u32 addr, u32 mask,
2976                                int timeout)
2977 {
2978         int i = 0;
2979
2980         do {
2981                 if ((ipw_read32(priv, addr) & mask) == mask)
2982                         return i;
2983                 mdelay(10);
2984                 i += 10;
2985         } while (i < timeout);
2986
2987         return -ETIME;
2988 }
2989
2990 /* These functions load the firmware and micro code for the operation of
2991  * the ipw hardware.  It assumes the buffer has all the bits for the
2992  * image and the caller is handling the memory allocation and clean up.
2993  */
2994
2995 static int ipw_stop_master(struct ipw_priv *priv)
2996 {
2997         int rc;
2998
2999         IPW_DEBUG_TRACE(">> \n");
3000         /* stop master. typical delay - 0 */
3001         ipw_set_bit(priv, IPW_RESET_REG, IPW_RESET_REG_STOP_MASTER);
3002
3003         /* timeout is in msec, polled in 10-msec quanta */
3004         rc = ipw_poll_bit(priv, IPW_RESET_REG,
3005                           IPW_RESET_REG_MASTER_DISABLED, 100);
3006         if (rc < 0) {
3007                 IPW_ERROR("wait for stop master failed after 100ms\n");
3008                 return -1;
3009         }
3010
3011         IPW_DEBUG_INFO("stop master %dms\n", rc);
3012
3013         return rc;
3014 }
3015
3016 static void ipw_arc_release(struct ipw_priv *priv)
3017 {
3018         IPW_DEBUG_TRACE(">> \n");
3019         mdelay(5);
3020
3021         ipw_clear_bit(priv, IPW_RESET_REG, CBD_RESET_REG_PRINCETON_RESET);
3022
3023         /* no one knows timing, for safety add some delay */
3024         mdelay(5);
3025 }
3026
3027 struct fw_chunk {
3028         __le32 address;
3029         __le32 length;
3030 };
3031
3032 static int ipw_load_ucode(struct ipw_priv *priv, u8 * data, size_t len)
3033 {
3034         int rc = 0, i, addr;
3035         u8 cr = 0;
3036         __le16 *image;
3037
3038         image = (__le16 *) data;
3039
3040         IPW_DEBUG_TRACE(">> \n");
3041
3042         rc = ipw_stop_master(priv);
3043
3044         if (rc < 0)
3045                 return rc;
3046
3047         for (addr = IPW_SHARED_LOWER_BOUND;
3048              addr < IPW_REGISTER_DOMAIN1_END; addr += 4) {
3049                 ipw_write32(priv, addr, 0);
3050         }
3051
3052         /* no ucode (yet) */
3053         memset(&priv->dino_alive, 0, sizeof(priv->dino_alive));
3054         /* destroy DMA queues */
3055         /* reset sequence */
3056
3057         ipw_write_reg32(priv, IPW_MEM_HALT_AND_RESET, IPW_BIT_HALT_RESET_ON);
3058         ipw_arc_release(priv);
3059         ipw_write_reg32(priv, IPW_MEM_HALT_AND_RESET, IPW_BIT_HALT_RESET_OFF);
3060         mdelay(1);
3061
3062         /* reset PHY */
3063         ipw_write_reg32(priv, IPW_INTERNAL_CMD_EVENT, IPW_BASEBAND_POWER_DOWN);
3064         mdelay(1);
3065
3066         ipw_write_reg32(priv, IPW_INTERNAL_CMD_EVENT, 0);
3067         mdelay(1);
3068
3069         /* enable ucode store */
3070         ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, 0x0);
3071         ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, DINO_ENABLE_CS);
3072         mdelay(1);
3073
3074         /* write ucode */
3075         /**
3076          * @bug
3077          * Do NOT set indirect address register once and then
3078          * store data to indirect data register in the loop.
3079          * It seems very reasonable, but in this case DINO do not
3080          * accept ucode. It is essential to set address each time.
3081          */
3082         /* load new ipw uCode */
3083         for (i = 0; i < len / 2; i++)
3084                 ipw_write_reg16(priv, IPW_BASEBAND_CONTROL_STORE,
3085                                 le16_to_cpu(image[i]));
3086
3087         /* enable DINO */
3088         ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, 0);
3089         ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, DINO_ENABLE_SYSTEM);
3090
3091         /* this is where the igx / win driver deveates from the VAP driver. */
3092
3093         /* wait for alive response */
3094         for (i = 0; i < 100; i++) {
3095                 /* poll for incoming data */
3096                 cr = ipw_read_reg8(priv, IPW_BASEBAND_CONTROL_STATUS);
3097                 if (cr & DINO_RXFIFO_DATA)
3098                         break;
3099                 mdelay(1);
3100         }
3101
3102         if (cr & DINO_RXFIFO_DATA) {
3103                 /* alive_command_responce size is NOT multiple of 4 */
3104                 __le32 response_buffer[(sizeof(priv->dino_alive) + 3) / 4];
3105
3106                 for (i = 0; i < ARRAY_SIZE(response_buffer); i++)
3107                         response_buffer[i] =
3108                             cpu_to_le32(ipw_read_reg32(priv,
3109                                                        IPW_BASEBAND_RX_FIFO_READ));
3110                 memcpy(&priv->dino_alive, response_buffer,
3111                        sizeof(priv->dino_alive));
3112                 if (priv->dino_alive.alive_command == 1
3113                     && priv->dino_alive.ucode_valid == 1) {
3114                         rc = 0;
3115                         IPW_DEBUG_INFO
3116                             ("Microcode OK, rev. %d (0x%x) dev. %d (0x%x) "
3117                              "of %02d/%02d/%02d %02d:%02d\n",
3118                              priv->dino_alive.software_revision,
3119                              priv->dino_alive.software_revision,
3120                              priv->dino_alive.device_identifier,
3121                              priv->dino_alive.device_identifier,
3122                              priv->dino_alive.time_stamp[0],
3123                              priv->dino_alive.time_stamp[1],
3124                              priv->dino_alive.time_stamp[2],
3125                              priv->dino_alive.time_stamp[3],
3126                              priv->dino_alive.time_stamp[4]);
3127                 } else {
3128                         IPW_DEBUG_INFO("Microcode is not alive\n");
3129                         rc = -EINVAL;
3130                 }
3131         } else {
3132                 IPW_DEBUG_INFO("No alive response from DINO\n");
3133                 rc = -ETIME;
3134         }
3135
3136         /* disable DINO, otherwise for some reason
3137            firmware have problem getting alive resp. */
3138         ipw_write_reg8(priv, IPW_BASEBAND_CONTROL_STATUS, 0);
3139
3140         return rc;
3141 }
3142
3143 static int ipw_load_firmware(struct ipw_priv *priv, u8 * data, size_t len)
3144 {
3145         int ret = -1;
3146         int offset = 0;
3147         struct fw_chunk *chunk;
3148         int total_nr = 0;
3149         int i;
3150         struct pci_pool *pool;
3151         u32 *virts[CB_NUMBER_OF_ELEMENTS_SMALL];
3152         dma_addr_t phys[CB_NUMBER_OF_ELEMENTS_SMALL];
3153
3154         IPW_DEBUG_TRACE("<< : \n");
3155
3156         pool = pci_pool_create("ipw2200", priv->pci_dev, CB_MAX_LENGTH, 0, 0);
3157         if (!pool) {
3158                 IPW_ERROR("pci_pool_create failed\n");
3159                 return -ENOMEM;
3160         }
3161
3162         /* Start the Dma */
3163         ret = ipw_fw_dma_enable(priv);
3164
3165         /* the DMA is already ready this would be a bug. */
3166         BUG_ON(priv->sram_desc.last_cb_index > 0);
3167
3168         do {
3169                 u32 chunk_len;
3170                 u8 *start;
3171                 int size;
3172                 int nr = 0;
3173
3174                 chunk = (struct fw_chunk *)(data + offset);
3175                 offset += sizeof(struct fw_chunk);
3176                 chunk_len = le32_to_cpu(chunk->length);
3177                 start = data + offset;
3178
3179                 nr = (chunk_len + CB_MAX_LENGTH - 1) / CB_MAX_LENGTH;
3180                 for (i = 0; i < nr; i++) {
3181                         virts[total_nr] = pci_pool_alloc(pool, GFP_KERNEL,
3182                                                          &phys[total_nr]);
3183                         if (!virts[total_nr]) {
3184                                 ret = -ENOMEM;
3185                                 goto out;
3186                         }
3187                         size = min_t(u32, chunk_len - i * CB_MAX_LENGTH,
3188                                      CB_MAX_LENGTH);
3189                         memcpy(virts[total_nr], start, size);
3190                         start += size;
3191                         total_nr++;
3192                         /* We don't support fw chunk larger than 64*8K */
3193                         BUG_ON(total_nr > CB_NUMBER_OF_ELEMENTS_SMALL);
3194                 }
3195
3196                 /* build DMA packet and queue up for sending */
3197                 /* dma to chunk->address, the chunk->length bytes from data +
3198                  * offeset*/
3199                 /* Dma loading */
3200                 ret = ipw_fw_dma_add_buffer(priv, &phys[total_nr - nr],
3201                                             nr, le32_to_cpu(chunk->address),
3202                                             chunk_len);
3203                 if (ret) {
3204                         IPW_DEBUG_INFO("dmaAddBuffer Failed\n");
3205                         goto out;
3206                 }
3207
3208                 offset += chunk_len;
3209         } while (offset < len);
3210
3211         /* Run the DMA and wait for the answer */
3212         ret = ipw_fw_dma_kick(priv);
3213         if (ret) {
3214                 IPW_ERROR("dmaKick Failed\n");
3215                 goto out;
3216         }
3217
3218         ret = ipw_fw_dma_wait(priv);
3219         if (ret) {
3220                 IPW_ERROR("dmaWaitSync Failed\n");
3221                 goto out;
3222         }
3223  out:
3224         for (i = 0; i < total_nr; i++)
3225                 pci_pool_free(pool, virts[i], phys[i]);
3226
3227         pci_pool_destroy(pool);
3228
3229         return ret;
3230 }
3231
3232 /* stop nic */
3233 static int ipw_stop_nic(struct ipw_priv *priv)
3234 {
3235         int rc = 0;
3236
3237         /* stop */
3238         ipw_write32(priv, IPW_RESET_REG, IPW_RESET_REG_STOP_MASTER);
3239
3240         rc = ipw_poll_bit(priv, IPW_RESET_REG,
3241                           IPW_RESET_REG_MASTER_DISABLED, 500);
3242         if (rc < 0) {
3243                 IPW_ERROR("wait for reg master disabled failed after 500ms\n");
3244                 return rc;
3245         }
3246
3247         ipw_set_bit(priv, IPW_RESET_REG, CBD_RESET_REG_PRINCETON_RESET);
3248
3249         return rc;
3250 }
3251
3252 static void ipw_start_nic(struct ipw_priv *priv)
3253 {
3254         IPW_DEBUG_TRACE(">>\n");
3255
3256         /* prvHwStartNic  release ARC */
3257         ipw_clear_bit(priv, IPW_RESET_REG,
3258                       IPW_RESET_REG_MASTER_DISABLED |
3259                       IPW_RESET_REG_STOP_MASTER |
3260                       CBD_RESET_REG_PRINCETON_RESET);
3261
3262         /* enable power management */
3263         ipw_set_bit(priv, IPW_GP_CNTRL_RW,
3264                     IPW_GP_CNTRL_BIT_HOST_ALLOWS_STANDBY);
3265
3266         IPW_DEBUG_TRACE("<<\n");
3267 }
3268
3269 static int ipw_init_nic(struct ipw_priv *priv)
3270 {
3271         int rc;
3272
3273         IPW_DEBUG_TRACE(">>\n");
3274         /* reset */
3275         /*prvHwInitNic */
3276         /* set "initialization complete" bit to move adapter to D0 state */
3277         ipw_set_bit(priv, IPW_GP_CNTRL_RW, IPW_GP_CNTRL_BIT_INIT_DONE);
3278
3279         /* low-level PLL activation */
3280         ipw_write32(priv, IPW_READ_INT_REGISTER,
3281                     IPW_BIT_INT_HOST_SRAM_READ_INT_REGISTER);
3282
3283         /* wait for clock stabilization */
3284         rc = ipw_poll_bit(priv, IPW_GP_CNTRL_RW,
3285                           IPW_GP_CNTRL_BIT_CLOCK_READY, 250);
3286         if (rc < 0)
3287                 IPW_DEBUG_INFO("FAILED wait for clock stablization\n");
3288
3289         /* assert SW reset */
3290         ipw_set_bit(priv, IPW_RESET_REG, IPW_RESET_REG_SW_RESET);
3291
3292         udelay(10);
3293
3294         /* set "initialization complete" bit to move adapter to D0 state */
3295         ipw_set_bit(priv, IPW_GP_CNTRL_RW, IPW_GP_CNTRL_BIT_INIT_DONE);
3296
3297         IPW_DEBUG_TRACE(">>\n");
3298         return 0;
3299 }
3300
3301 /* Call this function from process context, it will sleep in request_firmware.
3302  * Probe is an ok place to call this from.
3303  */
3304 static int ipw_reset_nic(struct ipw_priv *priv)
3305 {
3306         int rc = 0;
3307         unsigned long flags;
3308
3309         IPW_DEBUG_TRACE(">>\n");
3310
3311         rc = ipw_init_nic(priv);
3312
3313         spin_lock_irqsave(&priv->lock, flags);
3314         /* Clear the 'host command active' bit... */
3315         priv->status &= ~STATUS_HCMD_ACTIVE;
3316         wake_up_interruptible(&priv->wait_command_queue);
3317         priv->status &= ~(STATUS_SCANNING | STATUS_SCAN_ABORTING);
3318         wake_up_interruptible(&priv->wait_state);
3319         spin_unlock_irqrestore(&priv->lock, flags);
3320
3321         IPW_DEBUG_TRACE("<<\n");
3322         return rc;
3323 }
3324
3325
3326 struct ipw_fw {
3327         __le32 ver;
3328         __le32 boot_size;
3329         __le32 ucode_size;
3330         __le32 fw_size;
3331         u8 data[0];
3332 };
3333
3334 static int ipw_get_fw(struct ipw_priv *priv,
3335                       const struct firmware **raw, const char *name)
3336 {
3337         struct ipw_fw *fw;
3338         int rc;
3339
3340         /* ask firmware_class module to get the boot firmware off disk */
3341         rc = request_firmware(raw, name, &priv->pci_dev->dev);
3342         if (rc < 0) {
3343                 IPW_ERROR("%s request_firmware failed: Reason %d\n", name, rc);
3344                 return rc;
3345         }
3346
3347         if ((*raw)->size < sizeof(*fw)) {
3348                 IPW_ERROR("%s is too small (%zd)\n", name, (*raw)->size);
3349                 return -EINVAL;
3350         }
3351
3352         fw = (void *)(*raw)->data;
3353
3354         if ((*raw)->size < sizeof(*fw) + le32_to_cpu(fw->boot_size) +
3355             le32_to_cpu(fw->ucode_size) + le32_to_cpu(fw->fw_size)) {
3356                 IPW_ERROR("%s is too small or corrupt (%zd)\n",
3357                           name, (*raw)->size);
3358                 return -EINVAL;
3359         }
3360
3361         IPW_DEBUG_INFO("Read firmware '%s' image v%d.%d (%zd bytes)\n",
3362                        name,
3363                        le32_to_cpu(fw->ver) >> 16,
3364                        le32_to_cpu(fw->ver) & 0xff,
3365                        (*raw)->size - sizeof(*fw));
3366         return 0;
3367 }
3368
3369 #define IPW_RX_BUF_SIZE (3000)
3370
3371 static void ipw_rx_queue_reset(struct ipw_priv *priv,
3372                                       struct ipw_rx_queue *rxq)
3373 {
3374         unsigned long flags;
3375         int i;
3376
3377         spin_lock_irqsave(&rxq->lock, flags);
3378
3379         INIT_LIST_HEAD(&rxq->rx_free);
3380         INIT_LIST_HEAD(&rxq->rx_used);
3381
3382         /* Fill the rx_used queue with _all_ of the Rx buffers */
3383         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
3384                 /* In the reset function, these buffers may have been allocated
3385                  * to an SKB, so we need to unmap and free potential storage */
3386                 if (rxq->pool[i].skb != NULL) {
3387                         pci_unmap_single(priv->pci_dev, rxq->pool[i].dma_addr,
3388                                          IPW_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
3389                         dev_kfree_skb(rxq->pool[i].skb);
3390                         rxq->pool[i].skb = NULL;
3391                 }
3392                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
3393         }
3394
3395         /* Set us so that we have processed and used all buffers, but have
3396          * not restocked the Rx queue with fresh buffers */
3397         rxq->read = rxq->write = 0;
3398         rxq->free_count = 0;
3399         spin_unlock_irqrestore(&rxq->lock, flags);
3400 }
3401
3402 #ifdef CONFIG_PM
3403 static int fw_loaded = 0;
3404 static const struct firmware *raw = NULL;
3405
3406 static void free_firmware(void)
3407 {
3408         if (fw_loaded) {
3409                 release_firmware(raw);
3410                 raw = NULL;
3411                 fw_loaded = 0;
3412         }
3413 }
3414 #else
3415 #define free_firmware() do {} while (0)
3416 #endif
3417
3418 static int ipw_load(struct ipw_priv *priv)
3419 {
3420 #ifndef CONFIG_PM
3421         const struct firmware *raw = NULL;
3422 #endif
3423         struct ipw_fw *fw;
3424         u8 *boot_img, *ucode_img, *fw_img;
3425         u8 *name = NULL;
3426         int rc = 0, retries = 3;
3427
3428         switch (priv->ieee->iw_mode) {
3429         case IW_MODE_ADHOC:
3430                 name = "ipw2200-ibss.fw";
3431                 break;
3432 #ifdef CONFIG_IPW2200_MONITOR
3433         case IW_MODE_MONITOR:
3434                 name = "ipw2200-sniffer.fw";
3435                 break;
3436 #endif
3437         case IW_MODE_INFRA:
3438                 name = "ipw2200-bss.fw";
3439                 break;
3440         }
3441
3442         if (!name) {
3443                 rc = -EINVAL;
3444                 goto error;
3445         }
3446
3447 #ifdef CONFIG_PM
3448         if (!fw_loaded) {
3449 #endif
3450                 rc = ipw_get_fw(priv, &raw, name);
3451                 if (rc < 0)
3452                         goto error;
3453 #ifdef CONFIG_PM
3454         }
3455 #endif
3456
3457         fw = (void *)raw->data;
3458         boot_img = &fw->data[0];
3459         ucode_img = &fw->data[le32_to_cpu(fw->boot_size)];
3460         fw_img = &fw->data[le32_to_cpu(fw->boot_size) +
3461                            le32_to_cpu(fw->ucode_size)];
3462
3463         if (rc < 0)
3464                 goto error;
3465
3466         if (!priv->rxq)
3467                 priv->rxq = ipw_rx_queue_alloc(priv);
3468         else
3469                 ipw_rx_queue_reset(priv, priv->rxq);
3470         if (!priv->rxq) {
3471                 IPW_ERROR("Unable to initialize Rx queue\n");
3472                 goto error;
3473         }
3474
3475       retry:
3476         /* Ensure interrupts are disabled */
3477         ipw_write32(priv, IPW_INTA_MASK_R, ~IPW_INTA_MASK_ALL);
3478         priv->status &= ~STATUS_INT_ENABLED;
3479
3480         /* ack pending interrupts */
3481         ipw_write32(priv, IPW_INTA_RW, IPW_INTA_MASK_ALL);
3482
3483         ipw_stop_nic(priv);
3484
3485         rc = ipw_reset_nic(priv);
3486         if (rc < 0) {
3487                 IPW_ERROR("Unable to reset NIC\n");
3488                 goto error;
3489         }
3490
3491         ipw_zero_memory(priv, IPW_NIC_SRAM_LOWER_BOUND,
3492                         IPW_NIC_SRAM_UPPER_BOUND - IPW_NIC_SRAM_LOWER_BOUND);
3493
3494         /* DMA the initial boot firmware into the device */
3495         rc = ipw_load_firmware(priv, boot_img, le32_to_cpu(fw->boot_size));
3496         if (rc < 0) {
3497                 IPW_ERROR("Unable to load boot firmware: %d\n", rc);
3498                 goto error;
3499         }
3500
3501         /* kick start the device */
3502         ipw_start_nic(priv);
3503
3504         /* wait for the device to finish its initial startup sequence */
3505         rc = ipw_poll_bit(priv, IPW_INTA_RW,
3506                           IPW_INTA_BIT_FW_INITIALIZATION_DONE, 500);
3507         if (rc < 0) {
3508                 IPW_ERROR("device failed to boot initial fw image\n");
3509                 goto error;
3510         }
3511         IPW_DEBUG_INFO("initial device response after %dms\n", rc);
3512
3513         /* ack fw init done interrupt */
3514         ipw_write32(priv, IPW_INTA_RW, IPW_INTA_BIT_FW_INITIALIZATION_DONE);
3515
3516         /* DMA the ucode into the device */
3517         rc = ipw_load_ucode(priv, ucode_img, le32_to_cpu(fw->ucode_size));
3518         if (rc < 0) {
3519                 IPW_ERROR("Unable to load ucode: %d\n", rc);
3520                 goto error;
3521         }
3522
3523         /* stop nic */
3524         ipw_stop_nic(priv);
3525
3526         /* DMA bss firmware into the device */
3527         rc = ipw_load_firmware(priv, fw_img, le32_to_cpu(fw->fw_size));
3528         if (rc < 0) {
3529                 IPW_ERROR("Unable to load firmware: %d\n", rc);
3530                 goto error;
3531         }
3532 #ifdef CONFIG_PM
3533         fw_loaded = 1;
3534 #endif
3535
3536         ipw_write32(priv, IPW_EEPROM_LOAD_DISABLE, 0);
3537
3538         rc = ipw_queue_reset(priv);
3539         if (rc < 0) {
3540                 IPW_ERROR("Unable to initialize queues\n");
3541                 goto error;
3542         }
3543
3544         /* Ensure interrupts are disabled */
3545         ipw_write32(priv, IPW_INTA_MASK_R, ~IPW_INTA_MASK_ALL);
3546         /* ack pending interrupts */
3547         ipw_write32(priv, IPW_INTA_RW, IPW_INTA_MASK_ALL);
3548
3549         /* kick start the device */
3550         ipw_start_nic(priv);
3551
3552         if (ipw_read32(priv, IPW_INTA_RW) & IPW_INTA_BIT_PARITY_ERROR) {
3553                 if (retries > 0) {
3554                         IPW_WARNING("Parity error.  Retrying init.\n");
3555                         retries--;
3556                         goto retry;
3557                 }
3558
3559                 IPW_ERROR("TODO: Handle parity error -- schedule restart?\n");
3560                 rc = -EIO;
3561                 goto error;
3562         }
3563
3564         /* wait for the device */
3565         rc = ipw_poll_bit(priv, IPW_INTA_RW,
3566                           IPW_INTA_BIT_FW_INITIALIZATION_DONE, 500);
3567         if (rc < 0) {
3568                 IPW_ERROR("device failed to start within 500ms\n");
3569                 goto error;
3570         }
3571         IPW_DEBUG_INFO("device response after %dms\n", rc);
3572
3573         /* ack fw init done interrupt */
3574         ipw_write32(priv, IPW_INTA_RW, IPW_INTA_BIT_FW_INITIALIZATION_DONE);
3575
3576         /* read eeprom data and initialize the eeprom region of sram */
3577         priv->eeprom_delay = 1;
3578         ipw_eeprom_init_sram(priv);
3579
3580         /* enable interrupts */
3581         ipw_enable_interrupts(priv);
3582
3583         /* Ensure our queue has valid packets */
3584         ipw_rx_queue_replenish(priv);
3585
3586         ipw_write32(priv, IPW_RX_READ_INDEX, priv->rxq->read);
3587
3588         /* ack pending interrupts */
3589         ipw_write32(priv, IPW_INTA_RW, IPW_INTA_MASK_ALL);
3590
3591 #ifndef CONFIG_PM
3592         release_firmware(raw);
3593 #endif
3594         return 0;
3595
3596       error:
3597         if (priv->rxq) {
3598                 ipw_rx_queue_free(priv, priv->rxq);
3599                 priv->rxq = NULL;
3600         }
3601         ipw_tx_queue_free(priv);
3602         if (raw)
3603                 release_firmware(raw);
3604 #ifdef CONFIG_PM
3605         fw_loaded = 0;
3606         raw = NULL;
3607 #endif
3608
3609         return rc;
3610 }
3611
3612 /**
3613  * DMA services
3614  *
3615  * Theory of operation
3616  *
3617  * A queue is a circular buffers with 'Read' and 'Write' pointers.
3618  * 2 empty entries always kept in the buffer to protect from overflow.
3619  *
3620  * For Tx queue, there are low mark and high mark limits. If, after queuing
3621  * the packet for Tx, free space become < low mark, Tx queue stopped. When
3622  * reclaiming packets (on 'tx done IRQ), if free space become > high mark,
3623  * Tx queue resumed.
3624  *
3625  * The IPW operates with six queues, one receive queue in the device's
3626  * sram, one transmit queue for sending commands to the device firmware,
3627  * and four transmit queues for data.
3628  *
3629  * The four transmit queues allow for performing quality of service (qos)
3630  * transmissions as per the 802.11 protocol.  Currently Linux does not
3631  * provide a mechanism to the user for utilizing prioritized queues, so
3632  * we only utilize the first data transmit queue (queue1).
3633  */
3634
3635 /**
3636  * Driver allocates buffers of this size for Rx
3637  */
3638
3639 /**
3640  * ipw_rx_queue_space - Return number of free slots available in queue.
3641  */
3642 static int ipw_rx_queue_space(const struct ipw_rx_queue *q)
3643 {
3644         int s = q->read - q->write;
3645         if (s <= 0)
3646                 s += RX_QUEUE_SIZE;
3647         /* keep some buffer to not confuse full and empty queue */
3648         s -= 2;
3649         if (s < 0)
3650                 s = 0;
3651         return s;
3652 }
3653
3654 static inline int ipw_tx_queue_space(const struct clx2_queue *q)
3655 {
3656         int s = q->last_used - q->first_empty;
3657         if (s <= 0)
3658                 s += q->n_bd;
3659         s -= 2;                 /* keep some reserve to not confuse empty and full situations */
3660         if (s < 0)
3661                 s = 0;
3662         return s;
3663 }
3664
3665 static inline int ipw_queue_inc_wrap(int index, int n_bd)
3666 {
3667         return (++index == n_bd) ? 0 : index;
3668 }
3669
3670 /**
3671  * Initialize common DMA queue structure
3672  *
3673  * @param q                queue to init
3674  * @param count            Number of BD's to allocate. Should be power of 2
3675  * @param read_register    Address for 'read' register
3676  *                         (not offset within BAR, full address)
3677  * @param write_register   Address for 'write' register
3678  *                         (not offset within BAR, full address)
3679  * @param base_register    Address for 'base' register
3680  *                         (not offset within BAR, full address)
3681  * @param size             Address for 'size' register
3682  *                         (not offset within BAR, full address)
3683  */
3684 static void ipw_queue_init(struct ipw_priv *priv, struct clx2_queue *q,
3685                            int count, u32 read, u32 write, u32 base, u32 size)
3686 {
3687         q->n_bd = count;
3688
3689         q->low_mark = q->n_bd / 4;
3690         if (q->low_mark < 4)
3691                 q->low_mark = 4;
3692
3693         q->high_mark = q->n_bd / 8;
3694         if (q->high_mark < 2)
3695                 q->high_mark = 2;
3696
3697         q->first_empty = q->last_used = 0;
3698         q->reg_r = read;
3699         q->reg_w = write;
3700
3701         ipw_write32(priv, base, q->dma_addr);
3702         ipw_write32(priv, size, count);
3703         ipw_write32(priv, read, 0);
3704         ipw_write32(priv, write, 0);
3705
3706         _ipw_read32(priv, 0x90);
3707 }
3708
3709 static int ipw_queue_tx_init(struct ipw_priv *priv,
3710                              struct clx2_tx_queue *q,
3711                              int count, u32 read, u32 write, u32 base, u32 size)
3712 {
3713         struct pci_dev *dev = priv->pci_dev;
3714
3715         q->txb = kmalloc(sizeof(q->txb[0]) * count, GFP_KERNEL);
3716         if (!q->txb) {
3717                 IPW_ERROR("vmalloc for auxilary BD structures failed\n");
3718                 return -ENOMEM;
3719         }
3720
3721         q->bd =
3722             pci_alloc_consistent(dev, sizeof(q->bd[0]) * count, &q->q.dma_addr);
3723         if (!q->bd) {
3724                 IPW_ERROR("pci_alloc_consistent(%zd) failed\n",
3725                           sizeof(q->bd[0]) * count);
3726                 kfree(q->txb);
3727                 q->txb = NULL;
3728                 return -ENOMEM;
3729         }
3730
3731         ipw_queue_init(priv, &q->q, count, read, write, base, size);
3732         return 0;
3733 }
3734
3735 /**
3736  * Free one TFD, those at index [txq->q.last_used].
3737  * Do NOT advance any indexes
3738  *
3739  * @param dev
3740  * @param txq
3741  */
3742 static void ipw_queue_tx_free_tfd(struct ipw_priv *priv,
3743                                   struct clx2_tx_queue *txq)
3744 {
3745         struct tfd_frame *bd = &txq->bd[txq->q.last_used];
3746         struct pci_dev *dev = priv->pci_dev;
3747         int i;
3748
3749         /* classify bd */
3750         if (bd->control_flags.message_type == TX_HOST_COMMAND_TYPE)
3751                 /* nothing to cleanup after for host commands */
3752                 return;
3753
3754         /* sanity check */
3755         if (le32_to_cpu(bd->u.data.num_chunks) > NUM_TFD_CHUNKS) {
3756                 IPW_ERROR("Too many chunks: %i\n",
3757                           le32_to_cpu(bd->u.data.num_chunks));
3758                 /** @todo issue fatal error, it is quite serious situation */
3759                 return;
3760         }
3761
3762         /* unmap chunks if any */
3763         for (i = 0; i < le32_to_cpu(bd->u.data.num_chunks); i++) {
3764                 pci_unmap_single(dev, le32_to_cpu(bd->u.data.chunk_ptr[i]),
3765                                  le16_to_cpu(bd->u.data.chunk_len[i]),
3766                                  PCI_DMA_TODEVICE);
3767                 if (txq->txb[txq->q.last_used]) {
3768                         libipw_txb_free(txq->txb[txq->q.last_used]);
3769                         txq->txb[txq->q.last_used] = NULL;
3770                 }
3771         }
3772 }
3773
3774 /**
3775  * Deallocate DMA queue.
3776  *
3777  * Empty queue by removing and destroying all BD's.
3778  * Free all buffers.
3779  *
3780  * @param dev
3781  * @param q
3782  */
3783 static void ipw_queue_tx_free(struct ipw_priv *priv, struct clx2_tx_queue *txq)
3784 {
3785         struct clx2_queue *q = &txq->q;
3786         struct pci_dev *dev = priv->pci_dev;
3787
3788         if (q->n_bd == 0)
3789                 return;
3790
3791         /* first, empty all BD's */
3792         for (; q->first_empty != q->last_used;
3793              q->last_used = ipw_queue_inc_wrap(q->last_used, q->n_bd)) {
3794                 ipw_queue_tx_free_tfd(priv, txq);
3795         }
3796
3797         /* free buffers belonging to queue itself */
3798         pci_free_consistent(dev, sizeof(txq->bd[0]) * q->n_bd, txq->bd,
3799                             q->dma_addr);
3800         kfree(txq->txb);
3801
3802         /* 0 fill whole structure */
3803         memset(txq, 0, sizeof(*txq));
3804 }
3805
3806 /**
3807  * Destroy all DMA queues and structures
3808  *
3809  * @param priv
3810  */
3811 static void ipw_tx_queue_free(struct ipw_priv *priv)
3812 {
3813         /* Tx CMD queue */
3814         ipw_queue_tx_free(priv, &priv->txq_cmd);
3815
3816         /* Tx queues */
3817         ipw_queue_tx_free(priv, &priv->txq[0]);
3818         ipw_queue_tx_free(priv, &priv->txq[1]);
3819         ipw_queue_tx_free(priv, &priv->txq[2]);
3820         ipw_queue_tx_free(priv, &priv->txq[3]);
3821 }
3822
3823 static void ipw_create_bssid(struct ipw_priv *priv, u8 * bssid)
3824 {
3825         /* First 3 bytes are manufacturer */
3826         bssid[0] = priv->mac_addr[0];
3827         bssid[1] = priv->mac_addr[1];
3828         bssid[2] = priv->mac_addr[2];
3829
3830         /* Last bytes are random */
3831         get_random_bytes(&bssid[3], ETH_ALEN - 3);
3832
3833         bssid[0] &= 0xfe;       /* clear multicast bit */
3834         bssid[0] |= 0x02;       /* set local assignment bit (IEEE802) */
3835 }
3836
3837 static u8 ipw_add_station(struct ipw_priv *priv, u8 * bssid)
3838 {
3839         struct ipw_station_entry entry;
3840         int i;
3841
3842         for (i = 0; i < priv->num_stations; i++) {
3843                 if (!memcmp(priv->stations[i], bssid, ETH_ALEN)) {
3844                         /* Another node is active in network */
3845                         priv->missed_adhoc_beacons = 0;
3846                         if (!(priv->config & CFG_STATIC_CHANNEL))
3847                                 /* when other nodes drop out, we drop out */
3848                                 priv->config &= ~CFG_ADHOC_PERSIST;
3849
3850                         return i;
3851                 }
3852         }
3853
3854         if (i == MAX_STATIONS)
3855                 return IPW_INVALID_STATION;
3856
3857         IPW_DEBUG_SCAN("Adding AdHoc station: %pM\n", bssid);
3858
3859         entry.reserved = 0;
3860         entry.support_mode = 0;
3861         memcpy(entry.mac_addr, bssid, ETH_ALEN);
3862         memcpy(priv->stations[i], bssid, ETH_ALEN);
3863         ipw_write_direct(priv, IPW_STATION_TABLE_LOWER + i * sizeof(entry),
3864                          &entry, sizeof(entry));
3865         priv->num_stations++;
3866
3867         return i;
3868 }
3869
3870 static u8 ipw_find_station(struct ipw_priv *priv, u8 * bssid)
3871 {
3872         int i;
3873
3874         for (i = 0; i < priv->num_stations; i++)
3875                 if (!memcmp(priv->stations[i], bssid, ETH_ALEN))
3876                         return i;
3877
3878         return IPW_INVALID_STATION;
3879 }
3880
3881 static void ipw_send_disassociate(struct ipw_priv *priv, int quiet)
3882 {
3883         int err;
3884
3885         if (priv->status & STATUS_ASSOCIATING) {
3886                 IPW_DEBUG_ASSOC("Disassociating while associating.\n");
3887                 queue_work(priv->workqueue, &priv->disassociate);
3888                 return;
3889         }
3890
3891         if (!(priv->status & STATUS_ASSOCIATED)) {
3892                 IPW_DEBUG_ASSOC("Disassociating while not associated.\n");
3893                 return;
3894         }
3895
3896         IPW_DEBUG_ASSOC("Disassocation attempt from %pM "
3897                         "on channel %d.\n",
3898                         priv->assoc_request.bssid,
3899                         priv->assoc_request.channel);
3900
3901         priv->status &= ~(STATUS_ASSOCIATING | STATUS_ASSOCIATED);
3902         priv->status |= STATUS_DISASSOCIATING;
3903
3904         if (quiet)
3905                 priv->assoc_request.assoc_type = HC_DISASSOC_QUIET;
3906         else
3907                 priv->assoc_request.assoc_type = HC_DISASSOCIATE;
3908
3909         err = ipw_send_associate(priv, &priv->assoc_request);
3910         if (err) {
3911                 IPW_DEBUG_HC("Attempt to send [dis]associate command "
3912                              "failed.\n");
3913                 return;
3914         }
3915
3916 }
3917
3918 static int ipw_disassociate(void *data)
3919 {
3920         struct ipw_priv *priv = data;
3921         if (!(priv->status & (STATUS_ASSOCIATED | STATUS_ASSOCIATING)))
3922                 return 0;
3923         ipw_send_disassociate(data, 0);
3924         netif_carrier_off(priv->net_dev);
3925         return 1;
3926 }
3927
3928 static void ipw_bg_disassociate(struct work_struct *work)
3929 {
3930         struct ipw_priv *priv =
3931                 container_of(work, struct ipw_priv, disassociate);
3932         mutex_lock(&priv->mutex);
3933         ipw_disassociate(priv);
3934         mutex_unlock(&priv->mutex);
3935 }
3936
3937 static void ipw_system_config(struct work_struct *work)
3938 {
3939         struct ipw_priv *priv =
3940                 container_of(work, struct ipw_priv, system_config);
3941
3942 #ifdef CONFIG_IPW2200_PROMISCUOUS
3943         if (priv->prom_net_dev && netif_running(priv->prom_net_dev)) {
3944                 priv->sys_config.accept_all_data_frames = 1;
3945                 priv->sys_config.accept_non_directed_frames = 1;
3946                 priv->sys_config.accept_all_mgmt_bcpr = 1;
3947                 priv->sys_config.accept_all_mgmt_frames = 1;
3948         }
3949 #endif
3950
3951         ipw_send_system_config(priv);
3952 }
3953
3954 struct ipw_status_code {
3955         u16 status;
3956         const char *reason;
3957 };
3958
3959 static const struct ipw_status_code ipw_status_codes[] = {
3960         {0x00, "Successful"},
3961         {0x01, "Unspecified failure"},
3962         {0x0A, "Cannot support all requested capabilities in the "
3963          "Capability information field"},
3964         {0x0B, "Reassociation denied due to inability to confirm that "
3965          "association exists"},
3966         {0x0C, "Association denied due to reason outside the scope of this "
3967          "standard"},
3968         {0x0D,
3969          "Responding station does not support the specified authentication "
3970          "algorithm"},
3971         {0x0E,
3972          "Received an Authentication frame with authentication sequence "
3973          "transaction sequence number out of expected sequence"},
3974         {0x0F, "Authentication rejected because of challenge failure"},
3975         {0x10, "Authentication rejected due to timeout waiting for next "
3976          "frame in sequence"},
3977         {0x11, "Association denied because AP is unable to handle additional "
3978          "associated stations"},
3979         {0x12,
3980          "Association denied due to requesting station not supporting all "
3981          "of the datarates in the BSSBasicServiceSet Parameter"},
3982         {0x13,
3983          "Association denied due to requesting station not supporting "
3984          "short preamble operation"},
3985         {0x14,
3986          "Association denied due to requesting station not supporting "
3987          "PBCC encoding"},
3988         {0x15,
3989          "Association denied due to requesting station not supporting "
3990          "channel agility"},
3991         {0x19,
3992          "Association denied due to requesting station not supporting "
3993          "short slot operation"},
3994         {0x1A,
3995          "Association denied due to requesting station not supporting "
3996          "DSSS-OFDM operation"},
3997         {0x28, "Invalid Information Element"},
3998         {0x29, "Group Cipher is not valid"},
3999         {0x2A, "Pairwise Cipher is not valid"},
4000         {0x2B, "AKMP is not valid"},
4001         {0x2C, "Unsupported RSN IE version"},
4002         {0x2D, "Invalid RSN IE Capabilities"},
4003         {0x2E, "Cipher suite is rejected per security policy"},
4004 };
4005
4006 static const char *ipw_get_status_code(u16 status)
4007 {
4008         int i;
4009         for (i = 0; i < ARRAY_SIZE(ipw_status_codes); i++)
4010                 if (ipw_status_codes[i].status == (status & 0xff))
4011                         return ipw_status_codes[i].reason;
4012         return "Unknown status value.";
4013 }
4014
4015 static void inline average_init(struct average *avg)
4016 {
4017         memset(avg, 0, sizeof(*avg));
4018 }
4019
4020 #define DEPTH_RSSI 8
4021 #define DEPTH_NOISE 16
4022 static s16 exponential_average(s16 prev_avg, s16 val, u8 depth)
4023 {
4024         return ((depth-1)*prev_avg +  val)/depth;
4025 }
4026
4027 static void average_add(struct average *avg, s16 val)
4028 {
4029         avg->sum -= avg->entries[avg->pos];
4030         avg->sum += val;
4031         avg->entries[avg->pos++] = val;
4032         if (unlikely(avg->pos == AVG_ENTRIES)) {
4033                 avg->init = 1;
4034                 avg->pos = 0;
4035         }
4036 }
4037
4038 static s16 average_value(struct average *avg)
4039 {
4040         if (!unlikely(avg->init)) {
4041                 if (avg->pos)
4042                         return avg->sum / avg->pos;
4043                 return 0;
4044         }
4045
4046         return avg->sum / AVG_ENTRIES;
4047 }
4048
4049 static void ipw_reset_stats(struct ipw_priv *priv)
4050 {
4051         u32 len = sizeof(u32);
4052
4053         priv->quality = 0;
4054
4055         average_init(&priv->average_missed_beacons);
4056         priv->exp_avg_rssi = -60;
4057         priv->exp_avg_noise = -85 + 0x100;
4058
4059         priv->last_rate = 0;
4060         priv->last_missed_beacons = 0;
4061         priv->last_rx_packets = 0;
4062         priv->last_tx_packets = 0;
4063         priv->last_tx_failures = 0;
4064
4065         /* Firmware managed, reset only when NIC is restarted, so we have to
4066          * normalize on the current value */
4067         ipw_get_ordinal(priv, IPW_ORD_STAT_RX_ERR_CRC,
4068                         &priv->last_rx_err, &len);
4069         ipw_get_ordinal(priv, IPW_ORD_STAT_TX_FAILURE,
4070                         &priv->last_tx_failures, &len);
4071
4072         /* Driver managed, reset with each association */
4073         priv->missed_adhoc_beacons = 0;
4074         priv->missed_beacons = 0;
4075         priv->tx_packets = 0;
4076         priv->rx_packets = 0;
4077
4078 }
4079
4080 static u32 ipw_get_max_rate(struct ipw_priv *priv)
4081 {
4082         u32 i = 0x80000000;
4083         u32 mask = priv->rates_mask;
4084         /* If currently associated in B mode, restrict the maximum
4085          * rate match to B rates */
4086         if (priv->assoc_request.ieee_mode == IPW_B_MODE)
4087                 mask &= LIBIPW_CCK_RATES_MASK;
4088
4089         /* TODO: Verify that the rate is supported by the current rates
4090          * list. */
4091
4092         while (i && !(mask & i))
4093                 i >>= 1;
4094         switch (i) {
4095         case LIBIPW_CCK_RATE_1MB_MASK:
4096                 return 1000000;
4097         case LIBIPW_CCK_RATE_2MB_MASK:
4098                 return 2000000;
4099         case LIBIPW_CCK_RATE_5MB_MASK:
4100                 return 5500000;
4101         case LIBIPW_OFDM_RATE_6MB_MASK:
4102                 return 6000000;
4103         case LIBIPW_OFDM_RATE_9MB_MASK:
4104                 return 9000000;
4105         case LIBIPW_CCK_RATE_11MB_MASK:
4106                 return 11000000;
4107         case LIBIPW_OFDM_RATE_12MB_MASK:
4108                 return 12000000;
4109         case LIBIPW_OFDM_RATE_18MB_MASK:
4110                 return 18000000;
4111         case LIBIPW_OFDM_RATE_24MB_MASK:
4112                 return 24000000;
4113         case LIBIPW_OFDM_RATE_36MB_MASK:
4114                 return 36000000;
4115         case LIBIPW_OFDM_RATE_48MB_MASK:
4116                 return 48000000;
4117         case LIBIPW_OFDM_RATE_54MB_MASK:
4118                 return 54000000;
4119         }
4120
4121         if (priv->ieee->mode == IEEE_B)
4122                 return 11000000;
4123         else
4124                 return 54000000;
4125 }
4126
4127 static u32 ipw_get_current_rate(struct ipw_priv *priv)
4128 {
4129         u32 rate, len = sizeof(rate);
4130         int err;
4131
4132         if (!(priv->status & STATUS_ASSOCIATED))
4133                 return 0;
4134
4135         if (priv->tx_packets > IPW_REAL_RATE_RX_PACKET_THRESHOLD) {
4136                 err = ipw_get_ordinal(priv, IPW_ORD_STAT_TX_CURR_RATE, &rate,
4137                                       &len);
4138                 if (err) {
4139                         IPW_DEBUG_INFO("failed querying ordinals.\n");
4140                         return 0;
4141                 }
4142         } else
4143                 return ipw_get_max_rate(priv);
4144
4145         switch (rate) {
4146         case IPW_TX_RATE_1MB:
4147                 return 1000000;
4148         case IPW_TX_RATE_2MB:
4149                 return 2000000;
4150         case IPW_TX_RATE_5MB:
4151                 return 5500000;
4152         case IPW_TX_RATE_6MB:
4153                 return 6000000;
4154         case IPW_TX_RATE_9MB:
4155                 return 9000000;
4156         case IPW_TX_RATE_11MB:
4157                 return 11000000;
4158         case IPW_TX_RATE_12MB:
4159                 return 12000000;
4160         case IPW_TX_RATE_18MB:
4161                 return 18000000;
4162         case IPW_TX_RATE_24MB:
4163                 return 24000000;
4164         case IPW_TX_RATE_36MB:
4165                 return 36000000;
4166         case IPW_TX_RATE_48MB:
4167                 return 48000000;
4168         case IPW_TX_RATE_54MB:
4169                 return 54000000;
4170         }
4171
4172         return 0;
4173 }
4174
4175 #define IPW_STATS_INTERVAL (2 * HZ)
4176 static void ipw_gather_stats(struct ipw_priv *priv)
4177 {
4178         u32 rx_err, rx_err_delta, rx_packets_delta;
4179         u32 tx_failures, tx_failures_delta, tx_packets_delta;
4180         u32 missed_beacons_percent, missed_beacons_delta;
4181         u32 quality = 0;
4182         u32 len = sizeof(u32);
4183         s16 rssi;
4184         u32 beacon_quality, signal_quality, tx_quality, rx_quality,
4185             rate_quality;
4186         u32 max_rate;
4187
4188         if (!(priv->status & STATUS_ASSOCIATED)) {
4189                 priv->quality = 0;
4190                 return;
4191         }
4192
4193         /* Update the statistics */
4194         ipw_get_ordinal(priv, IPW_ORD_STAT_MISSED_BEACONS,
4195                         &priv->missed_beacons, &len);
4196         missed_beacons_delta = priv->missed_beacons - priv->last_missed_beacons;
4197         priv->last_missed_beacons = priv->missed_beacons;
4198         if (priv->assoc_request.beacon_interval) {
4199                 missed_beacons_percent = missed_beacons_delta *
4200                     (HZ * le16_to_cpu(priv->assoc_request.beacon_interval)) /
4201                     (IPW_STATS_INTERVAL * 10);
4202         } else {
4203                 missed_beacons_percent = 0;
4204         }
4205         average_add(&priv->average_missed_beacons, missed_beacons_percent);
4206
4207         ipw_get_ordinal(priv, IPW_ORD_STAT_RX_ERR_CRC, &rx_err, &len);
4208         rx_err_delta = rx_err - priv->last_rx_err;
4209         priv->last_rx_err = rx_err;
4210
4211         ipw_get_ordinal(priv, IPW_ORD_STAT_TX_FAILURE, &tx_failures, &len);
4212         tx_failures_delta = tx_failures - priv->last_tx_failures;
4213         priv->last_tx_failures = tx_failures;
4214
4215         rx_packets_delta = priv->rx_packets - priv->last_rx_packets;
4216         priv->last_rx_packets = priv->rx_packets;
4217
4218         tx_packets_delta = priv->tx_packets - priv->last_tx_packets;
4219         priv->last_tx_packets = priv->tx_packets;
4220
4221         /* Calculate quality based on the following:
4222          *
4223          * Missed beacon: 100% = 0, 0% = 70% missed
4224          * Rate: 60% = 1Mbs, 100% = Max
4225          * Rx and Tx errors represent a straight % of total Rx/Tx
4226          * RSSI: 100% = > -50,  0% = < -80
4227          * Rx errors: 100% = 0, 0% = 50% missed
4228          *
4229          * The lowest computed quality is used.
4230          *
4231          */
4232 #define BEACON_THRESHOLD 5
4233         beacon_quality = 100 - missed_beacons_percent;
4234         if (beacon_quality < BEACON_THRESHOLD)
4235                 beacon_quality = 0;
4236         else
4237                 beacon_quality = (beacon_quality - BEACON_THRESHOLD) * 100 /
4238                     (100 - BEACON_THRESHOLD);
4239         IPW_DEBUG_STATS("Missed beacon: %3d%% (%d%%)\n",
4240                         beacon_quality, missed_beacons_percent);
4241
4242         priv->last_rate = ipw_get_current_rate(priv);
4243         max_rate = ipw_get_max_rate(priv);
4244         rate_quality = priv->last_rate * 40 / max_rate + 60;
4245         IPW_DEBUG_STATS("Rate quality : %3d%% (%dMbs)\n",
4246                         rate_quality, priv->last_rate / 1000000);
4247
4248         if (rx_packets_delta > 100 && rx_packets_delta + rx_err_delta)
4249                 rx_quality = 100 - (rx_err_delta * 100) /
4250                     (rx_packets_delta + rx_err_delta);
4251         else
4252                 rx_quality = 100;
4253         IPW_DEBUG_STATS("Rx quality   : %3d%% (%u errors, %u packets)\n",
4254                         rx_quality, rx_err_delta, rx_packets_delta);
4255
4256         if (tx_packets_delta > 100 && tx_packets_delta + tx_failures_delta)
4257                 tx_quality = 100 - (tx_failures_delta * 100) /
4258                     (tx_packets_delta + tx_failures_delta);
4259         else
4260                 tx_quality = 100;
4261         IPW_DEBUG_STATS("Tx quality   : %3d%% (%u errors, %u packets)\n",
4262                         tx_quality, tx_failures_delta, tx_packets_delta);
4263
4264         rssi = priv->exp_avg_rssi;
4265         signal_quality =
4266             (100 *
4267              (priv->ieee->perfect_rssi - priv->ieee->worst_rssi) *
4268              (priv->ieee->perfect_rssi - priv->ieee->worst_rssi) -
4269              (priv->ieee->perfect_rssi - rssi) *
4270              (15 * (priv->ieee->perfect_rssi - priv->ieee->worst_rssi) +
4271               62 * (priv->ieee->perfect_rssi - rssi))) /
4272             ((priv->ieee->perfect_rssi - priv->ieee->worst_rssi) *
4273              (priv->ieee->perfect_rssi - priv->ieee->worst_rssi));
4274         if (signal_quality > 100)
4275                 signal_quality = 100;
4276         else if (signal_quality < 1)
4277                 signal_quality = 0;
4278
4279         IPW_DEBUG_STATS("Signal level : %3d%% (%d dBm)\n",
4280                         signal_quality, rssi);
4281
4282         quality = min(rx_quality, signal_quality);
4283         quality = min(tx_quality, quality);
4284         quality = min(rate_quality, quality);
4285         quality = min(beacon_quality, quality);
4286         if (quality == beacon_quality)
4287                 IPW_DEBUG_STATS("Quality (%d%%): Clamped to missed beacons.\n",
4288                                 quality);
4289         if (quality == rate_quality)
4290                 IPW_DEBUG_STATS("Quality (%d%%): Clamped to rate quality.\n",
4291                                 quality);
4292         if (quality == tx_quality)
4293                 IPW_DEBUG_STATS("Quality (%d%%): Clamped to Tx quality.\n",
4294                                 quality);
4295         if (quality == rx_quality)
4296                 IPW_DEBUG_STATS("Quality (%d%%): Clamped to Rx quality.\n",
4297                                 quality);
4298         if (quality == signal_quality)
4299                 IPW_DEBUG_STATS("Quality (%d%%): Clamped to signal quality.\n",
4300                                 quality);
4301
4302         priv->quality = quality;
4303
4304         queue_delayed_work(priv->workqueue, &priv->gather_stats,
4305                            IPW_STATS_INTERVAL);
4306 }
4307
4308 static void ipw_bg_gather_stats(struct work_struct *work)
4309 {
4310         struct ipw_priv *priv =
4311                 container_of(work, struct ipw_priv, gather_stats.work);
4312         mutex_lock(&priv->mutex);
4313         ipw_gather_stats(priv);
4314         mutex_unlock(&priv->mutex);
4315 }
4316
4317 /* Missed beacon behavior:
4318  * 1st missed -> roaming_threshold, just wait, don't do any scan/roam.
4319  * roaming_threshold -> disassociate_threshold, scan and roam for better signal.
4320  * Above disassociate threshold, give up and stop scanning.
4321  * Roaming is disabled if disassociate_threshold <= roaming_threshold  */
4322 static void ipw_handle_missed_beacon(struct ipw_priv *priv,
4323                                             int missed_count)
4324 {
4325         priv->notif_missed_beacons = missed_count;
4326
4327         if (missed_count > priv->disassociate_threshold &&
4328             priv->status & STATUS_ASSOCIATED) {
4329                 /* If associated and we've hit the missed
4330                  * beacon threshold, disassociate, turn
4331                  * off roaming, and abort any active scans */
4332                 IPW_DEBUG(IPW_DL_INFO | IPW_DL_NOTIF |
4333                           IPW_DL_STATE | IPW_DL_ASSOC,
4334                           "Missed beacon: %d - disassociate\n", missed_count);
4335                 priv->status &= ~STATUS_ROAMING;
4336                 if (priv->status & STATUS_SCANNING) {
4337                         IPW_DEBUG(IPW_DL_INFO | IPW_DL_NOTIF |
4338                                   IPW_DL_STATE,
4339                                   "Aborting scan with missed beacon.\n");
4340                         queue_work(priv->workqueue, &priv->abort_scan);
4341                 }
4342
4343                 queue_work(priv->workqueue, &priv->disassociate);
4344                 return;
4345         }
4346
4347         if (priv->status & STATUS_ROAMING) {
4348                 /* If we are currently roaming, then just
4349                  * print a debug statement... */
4350                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
4351                           "Missed beacon: %d - roam in progress\n",
4352                           missed_count);
4353                 return;
4354         }
4355
4356         if (roaming &&
4357             (missed_count > priv->roaming_threshold &&
4358              missed_count <= priv->disassociate_threshold)) {
4359                 /* If we are not already roaming, set the ROAM
4360                  * bit in the status and kick off a scan.
4361                  * This can happen several times before we reach
4362                  * disassociate_threshold. */
4363                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
4364                           "Missed beacon: %d - initiate "
4365                           "roaming\n", missed_count);
4366                 if (!(priv->status & STATUS_ROAMING)) {
4367                         priv->status |= STATUS_ROAMING;
4368                         if (!(priv->status & STATUS_SCANNING))
4369                                 queue_delayed_work(priv->workqueue,
4370                                                    &priv->request_scan, 0);
4371                 }
4372                 return;
4373         }
4374
4375         if (priv->status & STATUS_SCANNING &&
4376             missed_count > IPW_MB_SCAN_CANCEL_THRESHOLD) {
4377                 /* Stop scan to keep fw from getting
4378                  * stuck (only if we aren't roaming --
4379                  * otherwise we'll never scan more than 2 or 3
4380                  * channels..) */
4381                 IPW_DEBUG(IPW_DL_INFO | IPW_DL_NOTIF | IPW_DL_STATE,
4382                           "Aborting scan with missed beacon.\n");
4383                 queue_work(priv->workqueue, &priv->abort_scan);
4384         }
4385
4386         IPW_DEBUG_NOTIF("Missed beacon: %d\n", missed_count);
4387 }
4388
4389 static void ipw_scan_event(struct work_struct *work)
4390 {
4391         union iwreq_data wrqu;
4392
4393         struct ipw_priv *priv =
4394                 container_of(work, struct ipw_priv, scan_event.work);
4395
4396         wrqu.data.length = 0;
4397         wrqu.data.flags = 0;
4398         wireless_send_event(priv->net_dev, SIOCGIWSCAN, &wrqu, NULL);
4399 }
4400
4401 static void handle_scan_event(struct ipw_priv *priv)
4402 {
4403         /* Only userspace-requested scan completion events go out immediately */
4404         if (!priv->user_requested_scan) {
4405                 if (!delayed_work_pending(&priv->scan_event))
4406                         queue_delayed_work(priv->workqueue, &priv->scan_event,
4407                                          round_jiffies_relative(msecs_to_jiffies(4000)));
4408         } else {
4409                 union iwreq_data wrqu;
4410
4411                 priv->user_requested_scan = 0;
4412                 cancel_delayed_work(&priv->scan_event);
4413
4414                 wrqu.data.length = 0;
4415                 wrqu.data.flags = 0;
4416                 wireless_send_event(priv->net_dev, SIOCGIWSCAN, &wrqu, NULL);
4417         }
4418 }
4419
4420 /**
4421  * Handle host notification packet.
4422  * Called from interrupt routine
4423  */
4424 static void ipw_rx_notification(struct ipw_priv *priv,
4425                                        struct ipw_rx_notification *notif)
4426 {
4427         DECLARE_SSID_BUF(ssid);
4428         u16 size = le16_to_cpu(notif->size);
4429
4430         IPW_DEBUG_NOTIF("type = %i (%d bytes)\n", notif->subtype, size);
4431
4432         switch (notif->subtype) {
4433         case HOST_NOTIFICATION_STATUS_ASSOCIATED:{
4434                         struct notif_association *assoc = &notif->u.assoc;
4435
4436                         switch (assoc->state) {
4437                         case CMAS_ASSOCIATED:{
4438                                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4439                                                   IPW_DL_ASSOC,
4440                                                   "associated: '%s' %pM \n",
4441                                                   print_ssid(ssid, priv->essid,
4442                                                              priv->essid_len),
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                                                 queue_delayed_work(priv->
4461                                                                    workqueue,
4462                                                                    &priv->
4463                                                                    adhoc_check,
4464                                                                    le16_to_cpu(priv->
4465                                                                    assoc_request.
4466                                                                    beacon_interval));
4467                                                 break;
4468                                         }
4469
4470                                         priv->status &= ~STATUS_ASSOCIATING;
4471                                         priv->status |= STATUS_ASSOCIATED;
4472                                         queue_work(priv->workqueue,
4473                                                    &priv->system_config);
4474
4475 #ifdef CONFIG_IPW2200_QOS
4476 #define IPW_GET_PACKET_STYPE(x) WLAN_FC_GET_STYPE( \
4477                          le16_to_cpu(((struct ieee80211_hdr *)(x))->frame_control))
4478                                         if ((priv->status & STATUS_AUTH) &&
4479                                             (IPW_GET_PACKET_STYPE(&notif->u.raw)
4480                                              == IEEE80211_STYPE_ASSOC_RESP)) {
4481                                                 if ((sizeof
4482                                                      (struct
4483                                                       libipw_assoc_response)
4484                                                      <= size)
4485                                                     && (size <= 2314)) {
4486                                                         struct
4487                                                         libipw_rx_stats
4488                                                             stats = {
4489                                                                 .len = size - 1,
4490                                                         };
4491
4492                                                         IPW_DEBUG_QOS
4493                                                             ("QoS Associate "
4494                                                              "size %d\n", size);
4495                                                         libipw_rx_mgt(priv->
4496                                                                          ieee,
4497                                                                          (struct
4498                                                                           libipw_hdr_4addr
4499                                                                           *)
4500                                                                          &notif->u.raw, &stats);
4501                                                 }
4502                                         }
4503 #endif
4504
4505                                         schedule_work(&priv->link_up);
4506
4507                                         break;
4508                                 }
4509
4510                         case CMAS_AUTHENTICATED:{
4511                                         if (priv->
4512                                             status & (STATUS_ASSOCIATED |
4513                                                       STATUS_AUTH)) {
4514                                                 struct notif_authenticate *auth
4515                                                     = &notif->u.auth;
4516                                                 IPW_DEBUG(IPW_DL_NOTIF |
4517                                                           IPW_DL_STATE |
4518                                                           IPW_DL_ASSOC,
4519                                                           "deauthenticated: '%s' "
4520                                                           "%pM"
4521                                                           ": (0x%04X) - %s \n",
4522                                                           print_ssid(ssid,
4523                                                                      priv->
4524                                                                      essid,
4525                                                                      priv->
4526                                                                      essid_len),
4527                                                           priv->bssid,
4528                                                           le16_to_cpu(auth->status),
4529                                                           ipw_get_status_code
4530                                                           (le16_to_cpu
4531                                                            (auth->status)));
4532
4533                                                 priv->status &=
4534                                                     ~(STATUS_ASSOCIATING |
4535                                                       STATUS_AUTH |
4536                                                       STATUS_ASSOCIATED);
4537
4538                                                 schedule_work(&priv->link_down);
4539                                                 break;
4540                                         }
4541
4542                                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4543                                                   IPW_DL_ASSOC,
4544                                                   "authenticated: '%s' %pM\n",
4545                                                   print_ssid(ssid, priv->essid,
4546                                                              priv->essid_len),
4547                                                   priv->bssid);
4548                                         break;
4549                                 }
4550
4551                         case CMAS_INIT:{
4552                                         if (priv->status & STATUS_AUTH) {
4553                                                 struct
4554                                                     libipw_assoc_response
4555                                                 *resp;
4556                                                 resp =
4557                                                     (struct
4558                                                      libipw_assoc_response
4559                                                      *)&notif->u.raw;
4560                                                 IPW_DEBUG(IPW_DL_NOTIF |
4561                                                           IPW_DL_STATE |
4562                                                           IPW_DL_ASSOC,
4563                                                           "association failed (0x%04X): %s\n",
4564                                                           le16_to_cpu(resp->status),
4565                                                           ipw_get_status_code
4566                                                           (le16_to_cpu
4567                                                            (resp->status)));
4568                                         }
4569
4570                                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4571                                                   IPW_DL_ASSOC,
4572                                                   "disassociated: '%s' %pM \n",
4573                                                   print_ssid(ssid, priv->essid,
4574                                                              priv->essid_len),
4575                                                   priv->bssid);
4576
4577                                         priv->status &=
4578                                             ~(STATUS_DISASSOCIATING |
4579                                               STATUS_ASSOCIATING |
4580                                               STATUS_ASSOCIATED | STATUS_AUTH);
4581                                         if (priv->assoc_network
4582                                             && (priv->assoc_network->
4583                                                 capability &
4584                                                 WLAN_CAPABILITY_IBSS))
4585                                                 ipw_remove_current_network
4586                                                     (priv);
4587
4588                                         schedule_work(&priv->link_down);
4589
4590                                         break;
4591                                 }
4592
4593                         case CMAS_RX_ASSOC_RESP:
4594                                 break;
4595
4596                         default:
4597                                 IPW_ERROR("assoc: unknown (%d)\n",
4598                                           assoc->state);
4599                                 break;
4600                         }
4601
4602                         break;
4603                 }
4604
4605         case HOST_NOTIFICATION_STATUS_AUTHENTICATE:{
4606                         struct notif_authenticate *auth = &notif->u.auth;
4607                         switch (auth->state) {
4608                         case CMAS_AUTHENTICATED:
4609                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
4610                                           "authenticated: '%s' %pM \n",
4611                                           print_ssid(ssid, priv->essid,
4612                                                      priv->essid_len),
4613                                           priv->bssid);
4614                                 priv->status |= STATUS_AUTH;
4615                                 break;
4616
4617                         case CMAS_INIT:
4618                                 if (priv->status & STATUS_AUTH) {
4619                                         IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4620                                                   IPW_DL_ASSOC,
4621                                                   "authentication failed (0x%04X): %s\n",
4622                                                   le16_to_cpu(auth->status),
4623                                                   ipw_get_status_code(le16_to_cpu
4624                                                                       (auth->
4625                                                                        status)));
4626                                 }
4627                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4628                                           IPW_DL_ASSOC,
4629                                           "deauthenticated: '%s' %pM\n",
4630                                           print_ssid(ssid, priv->essid,
4631                                                      priv->essid_len),
4632                                           priv->bssid);
4633
4634                                 priv->status &= ~(STATUS_ASSOCIATING |
4635                                                   STATUS_AUTH |
4636                                                   STATUS_ASSOCIATED);
4637
4638                                 schedule_work(&priv->link_down);
4639                                 break;
4640
4641                         case CMAS_TX_AUTH_SEQ_1:
4642                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4643                                           IPW_DL_ASSOC, "AUTH_SEQ_1\n");
4644                                 break;
4645                         case CMAS_RX_AUTH_SEQ_2:
4646                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4647                                           IPW_DL_ASSOC, "AUTH_SEQ_2\n");
4648                                 break;
4649                         case CMAS_AUTH_SEQ_1_PASS:
4650                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4651                                           IPW_DL_ASSOC, "AUTH_SEQ_1_PASS\n");
4652                                 break;
4653                         case CMAS_AUTH_SEQ_1_FAIL:
4654                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4655                                           IPW_DL_ASSOC, "AUTH_SEQ_1_FAIL\n");
4656                                 break;
4657                         case CMAS_TX_AUTH_SEQ_3:
4658                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4659                                           IPW_DL_ASSOC, "AUTH_SEQ_3\n");
4660                                 break;
4661                         case CMAS_RX_AUTH_SEQ_4:
4662                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4663                                           IPW_DL_ASSOC, "RX_AUTH_SEQ_4\n");
4664                                 break;
4665                         case CMAS_AUTH_SEQ_2_PASS:
4666                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4667                                           IPW_DL_ASSOC, "AUTH_SEQ_2_PASS\n");
4668                                 break;
4669                         case CMAS_AUTH_SEQ_2_FAIL:
4670                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4671                                           IPW_DL_ASSOC, "AUT_SEQ_2_FAIL\n");
4672                                 break;
4673                         case CMAS_TX_ASSOC:
4674                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4675                                           IPW_DL_ASSOC, "TX_ASSOC\n");
4676                                 break;
4677                         case CMAS_RX_ASSOC_RESP:
4678                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4679                                           IPW_DL_ASSOC, "RX_ASSOC_RESP\n");
4680
4681                                 break;
4682                         case CMAS_ASSOCIATED:
4683                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE |
4684                                           IPW_DL_ASSOC, "ASSOCIATED\n");
4685                                 break;
4686                         default:
4687                                 IPW_DEBUG_NOTIF("auth: failure - %d\n",
4688                                                 auth->state);
4689                                 break;
4690                         }
4691                         break;
4692                 }
4693
4694         case HOST_NOTIFICATION_STATUS_SCAN_CHANNEL_RESULT:{
4695                         struct notif_channel_result *x =
4696                             &notif->u.channel_result;
4697
4698                         if (size == sizeof(*x)) {
4699                                 IPW_DEBUG_SCAN("Scan result for channel %d\n",
4700                                                x->channel_num);
4701                         } else {
4702                                 IPW_DEBUG_SCAN("Scan result of wrong size %d "
4703                                                "(should be %zd)\n",
4704                                                size, sizeof(*x));
4705                         }
4706                         break;
4707                 }
4708
4709         case HOST_NOTIFICATION_STATUS_SCAN_COMPLETED:{
4710                         struct notif_scan_complete *x = &notif->u.scan_complete;
4711                         if (size == sizeof(*x)) {
4712                                 IPW_DEBUG_SCAN
4713                                     ("Scan completed: type %d, %d channels, "
4714                                      "%d status\n", x->scan_type,
4715                                      x->num_channels, x->status);
4716                         } else {
4717                                 IPW_ERROR("Scan completed of wrong size %d "
4718                                           "(should be %zd)\n",
4719                                           size, sizeof(*x));
4720                         }
4721
4722                         priv->status &=
4723                             ~(STATUS_SCANNING | STATUS_SCAN_ABORTING);
4724
4725                         wake_up_interruptible(&priv->wait_state);
4726                         cancel_delayed_work(&priv->scan_check);
4727
4728                         if (priv->status & STATUS_EXIT_PENDING)
4729                                 break;
4730
4731                         priv->ieee->scans++;
4732
4733 #ifdef CONFIG_IPW2200_MONITOR
4734                         if (priv->ieee->iw_mode == IW_MODE_MONITOR) {
4735                                 priv->status |= STATUS_SCAN_FORCED;
4736                                 queue_delayed_work(priv->workqueue,
4737                                                    &priv->request_scan, 0);
4738                                 break;
4739                         }
4740                         priv->status &= ~STATUS_SCAN_FORCED;
4741 #endif                          /* CONFIG_IPW2200_MONITOR */
4742
4743                         /* Do queued direct scans first */
4744                         if (priv->status & STATUS_DIRECT_SCAN_PENDING) {
4745                                 queue_delayed_work(priv->workqueue,
4746                                                    &priv->request_direct_scan, 0);
4747                         }
4748
4749                         if (!(priv->status & (STATUS_ASSOCIATED |
4750                                               STATUS_ASSOCIATING |
4751                                               STATUS_ROAMING |
4752                                               STATUS_DISASSOCIATING)))
4753                                 queue_work(priv->workqueue, &priv->associate);
4754                         else if (priv->status & STATUS_ROAMING) {
4755                                 if (x->status == SCAN_COMPLETED_STATUS_COMPLETE)
4756                                         /* If a scan completed and we are in roam mode, then
4757                                          * the scan that completed was the one requested as a
4758                                          * result of entering roam... so, schedule the
4759                                          * roam work */
4760                                         queue_work(priv->workqueue,
4761                                                    &priv->roam);
4762                                 else
4763                                         /* Don't schedule if we aborted the scan */
4764                                         priv->status &= ~STATUS_ROAMING;
4765                         } else if (priv->status & STATUS_SCAN_PENDING)
4766                                 queue_delayed_work(priv->workqueue,
4767                                                    &priv->request_scan, 0);
4768                         else if (priv->config & CFG_BACKGROUND_SCAN
4769                                  && priv->status & STATUS_ASSOCIATED)
4770                                 queue_delayed_work(priv->workqueue,
4771                                                    &priv->request_scan,
4772                                                    round_jiffies_relative(HZ));
4773
4774                         /* Send an empty event to user space.
4775                          * We don't send the received data on the event because
4776                          * it would require us to do complex transcoding, and
4777                          * we want to minimise the work done in the irq handler
4778                          * Use a request to extract the data.
4779                          * Also, we generate this even for any scan, regardless
4780                          * on how the scan was initiated. User space can just
4781                          * sync on periodic scan to get fresh data...
4782                          * Jean II */
4783                         if (x->status == SCAN_COMPLETED_STATUS_COMPLETE)
4784                                 handle_scan_event(priv);
4785                         break;
4786                 }
4787
4788         case HOST_NOTIFICATION_STATUS_FRAG_LENGTH:{
4789                         struct notif_frag_length *x = &notif->u.frag_len;
4790
4791                         if (size == sizeof(*x))
4792                                 IPW_ERROR("Frag length: %d\n",
4793                                           le16_to_cpu(x->frag_length));
4794                         else
4795                                 IPW_ERROR("Frag length of wrong size %d "
4796                                           "(should be %zd)\n",
4797                                           size, sizeof(*x));
4798                         break;
4799                 }
4800
4801         case HOST_NOTIFICATION_STATUS_LINK_DETERIORATION:{
4802                         struct notif_link_deterioration *x =
4803                             &notif->u.link_deterioration;
4804
4805                         if (size == sizeof(*x)) {
4806                                 IPW_DEBUG(IPW_DL_NOTIF | IPW_DL_STATE,
4807                                         "link deterioration: type %d, cnt %d\n",
4808                                         x->silence_notification_type,
4809                                         x->silence_count);
4810                                 memcpy(&priv->last_link_deterioration, x,
4811                                        sizeof(*x));
4812                         } else {
4813                                 IPW_ERROR("Link Deterioration of wrong size %d "
4814                                           "(should be %zd)\n",
4815                                           size, sizeof(*x));
4816                         }
4817                         break;
4818                 }
4819
4820         case HOST_NOTIFICATION_DINO_CONFIG_RESPONSE:{
4821                         IPW_ERROR("Dino config\n");
4822                         if (priv->hcmd
4823                             && priv->hcmd->cmd != HOST_CMD_DINO_CONFIG)
4824                                 IPW_ERROR("Unexpected DINO_CONFIG_RESPONSE\n");
4825
4826                         break;
4827                 }
4828
4829         case HOST_NOTIFICATION_STATUS_BEACON_STATE:{
4830                         struct notif_beacon_state *x = &notif->u.beacon_state;
4831                         if (size != sizeof(*x)) {
4832                                 IPW_ERROR
4833                                     ("Beacon state of wrong size %d (should "
4834                                      "be %zd)\n", size, sizeof(*x));
4835                                 break;
4836                         }
4837
4838                         if (le32_to_cpu(x->state) ==
4839                             HOST_NOTIFICATION_STATUS_BEACON_MISSING)
4840                                 ipw_handle_missed_beacon(priv,
4841                                                          le32_to_cpu(x->
4842                                                                      number));
4843
4844                         break;
4845                 }
4846
4847         case HOST_NOTIFICATION_STATUS_TGI_TX_KEY:{
4848                         struct notif_tgi_tx_key *x = &notif->u.tgi_tx_key;
4849                         if (size == sizeof(*x)) {
4850                                 IPW_ERROR("TGi Tx Key: state 0x%02x sec type "
4851                                           "0x%02x station %d\n",
4852                                           x->key_state, x->security_type,
4853                                           x->station_index);
4854                                 break;
4855                         }
4856
4857                         IPW_ERROR
4858                             ("TGi Tx Key of wrong size %d (should be %zd)\n",
4859                              size, sizeof(*x));
4860                         break;
4861                 }
4862
4863         case HOST_NOTIFICATION_CALIB_KEEP_RESULTS:{
4864                         struct notif_calibration *x = &notif->u.calibration;
4865
4866                         if (size == sizeof(*x)) {
4867                                 memcpy(&priv->calib, x, sizeof(*x));
4868                                 IPW_DEBUG_INFO("TODO: Calibration\n");
4869                                 break;
4870                         }
4871
4872                         IPW_ERROR
4873                             ("Calibration of wrong size %d (should be %zd)\n",
4874                              size, sizeof(*x));
4875                         break;
4876                 }
4877
4878         case HOST_NOTIFICATION_NOISE_STATS:{
4879                         if (size == sizeof(u32)) {
4880                                 priv->exp_avg_noise =
4881                                     exponential_average(priv->exp_avg_noise,
4882                                     (u8) (le32_to_cpu(notif->u.noise.value) & 0xff),
4883                                     DEPTH_NOISE);
4884                                 break;
4885                         }
4886
4887                         IPW_ERROR
4888                             ("Noise stat is wrong size %d (should be %zd)\n",
4889                              size, sizeof(u32));
4890                         break;
4891                 }
4892
4893         default:
4894                 IPW_DEBUG_NOTIF("Unknown notification: "
4895                                 "subtype=%d,flags=0x%2x,size=%d\n",
4896                                 notif->subtype, notif->flags, size);
4897         }
4898 }
4899
4900 /**
4901  * Destroys all DMA structures and initialise them again
4902  *
4903  * @param priv
4904  * @return error code
4905  */
4906 static int ipw_queue_reset(struct ipw_priv *priv)
4907 {
4908         int rc = 0;
4909         /** @todo customize queue sizes */
4910         int nTx = 64, nTxCmd = 8;
4911         ipw_tx_queue_free(priv);
4912         /* Tx CMD queue */
4913         rc = ipw_queue_tx_init(priv, &priv->txq_cmd, nTxCmd,
4914                                IPW_TX_CMD_QUEUE_READ_INDEX,
4915                                IPW_TX_CMD_QUEUE_WRITE_INDEX,
4916                                IPW_TX_CMD_QUEUE_BD_BASE,
4917                                IPW_TX_CMD_QUEUE_BD_SIZE);
4918         if (rc) {
4919                 IPW_ERROR("Tx Cmd queue init failed\n");
4920                 goto error;
4921         }
4922         /* Tx queue(s) */
4923         rc = ipw_queue_tx_init(priv, &priv->txq[0], nTx,
4924                                IPW_TX_QUEUE_0_READ_INDEX,
4925                                IPW_TX_QUEUE_0_WRITE_INDEX,
4926                                IPW_TX_QUEUE_0_BD_BASE, IPW_TX_QUEUE_0_BD_SIZE);
4927         if (rc) {
4928                 IPW_ERROR("Tx 0 queue init failed\n");
4929                 goto error;
4930         }
4931         rc = ipw_queue_tx_init(priv, &priv->txq[1], nTx,
4932                                IPW_TX_QUEUE_1_READ_INDEX,
4933                                IPW_TX_QUEUE_1_WRITE_INDEX,
4934                                IPW_TX_QUEUE_1_BD_BASE, IPW_TX_QUEUE_1_BD_SIZE);
4935         if (rc) {
4936                 IPW_ERROR("Tx 1 queue init failed\n");
4937                 goto error;
4938         }
4939         rc = ipw_queue_tx_init(priv, &priv->txq[2], nTx,
4940                                IPW_TX_QUEUE_2_READ_INDEX,
4941                                IPW_TX_QUEUE_2_WRITE_INDEX,
4942                                IPW_TX_QUEUE_2_BD_BASE, IPW_TX_QUEUE_2_BD_SIZE);
4943         if (rc) {
4944                 IPW_ERROR("Tx 2 queue init failed\n");
4945                 goto error;
4946         }
4947         rc = ipw_queue_tx_init(priv, &priv->txq[3], nTx,
4948                                IPW_TX_QUEUE_3_READ_INDEX,
4949                                IPW_TX_QUEUE_3_WRITE_INDEX,
4950                                IPW_TX_QUEUE_3_BD_BASE, IPW_TX_QUEUE_3_BD_SIZE);
4951         if (rc) {
4952                 IPW_ERROR("Tx 3 queue init failed\n");
4953                 goto error;
4954         }
4955         /* statistics */
4956         priv->rx_bufs_min = 0;
4957         priv->rx_pend_max = 0;
4958         return rc;
4959
4960       error:
4961         ipw_tx_queue_free(priv);
4962         return rc;
4963 }
4964
4965 /**
4966  * Reclaim Tx queue entries no more used by NIC.
4967  *
4968  * When FW advances 'R' index, all entries between old and
4969  * new 'R' index need to be reclaimed. As result, some free space
4970  * forms. If there is enough free space (> low mark), wake Tx queue.
4971  *
4972  * @note Need to protect against garbage in 'R' index
4973  * @param priv
4974  * @param txq
4975  * @param qindex
4976  * @return Number of used entries remains in the queue
4977  */
4978 static int ipw_queue_tx_reclaim(struct ipw_priv *priv,
4979                                 struct clx2_tx_queue *txq, int qindex)
4980 {
4981         u32 hw_tail;
4982         int used;
4983         struct clx2_queue *q = &txq->q;
4984
4985         hw_tail = ipw_read32(priv, q->reg_r);
4986         if (hw_tail >= q->n_bd) {
4987                 IPW_ERROR
4988                     ("Read index for DMA queue (%d) is out of range [0-%d)\n",
4989                      hw_tail, q->n_bd);
4990                 goto done;
4991         }
4992         for (; q->last_used != hw_tail;
4993              q->last_used = ipw_queue_inc_wrap(q->last_used, q->n_bd)) {
4994                 ipw_queue_tx_free_tfd(priv, txq);
4995                 priv->tx_packets++;
4996         }
4997       done:
4998         if ((ipw_tx_queue_space(q) > q->low_mark) &&
4999             (qindex >= 0))
5000                 netif_wake_queue(priv->net_dev);
5001         used = q->first_empty - q->last_used;
5002         if (used < 0)
5003                 used += q->n_bd;
5004
5005         return used;
5006 }
5007
5008 static int ipw_queue_tx_hcmd(struct ipw_priv *priv, int hcmd, void *buf,
5009                              int len, int sync)
5010 {
5011         struct clx2_tx_queue *txq = &priv->txq_cmd;
5012         struct clx2_queue *q = &txq->q;
5013         struct tfd_frame *tfd;
5014
5015         if (ipw_tx_queue_space(q) < (sync ? 1 : 2)) {
5016                 IPW_ERROR("No space for Tx\n");
5017                 return -EBUSY;
5018         }
5019
5020         tfd = &txq->bd[q->first_empty];
5021         txq->txb[q->first_empty] = NULL;
5022
5023         memset(tfd, 0, sizeof(*tfd));
5024         tfd->control_flags.message_type = TX_HOST_COMMAND_TYPE;
5025         tfd->control_flags.control_bits = TFD_NEED_IRQ_MASK;
5026         priv->hcmd_seq++;
5027         tfd->u.cmd.index = hcmd;
5028         tfd->u.cmd.length = len;
5029         memcpy(tfd->u.cmd.payload, buf, len);
5030         q->first_empty = ipw_queue_inc_wrap(q->first_empty, q->n_bd);
5031         ipw_write32(priv, q->reg_w, q->first_empty);
5032         _ipw_read32(priv, 0x90);
5033
5034         return 0;
5035 }
5036
5037 /*
5038  * Rx theory of operation
5039  *
5040  * The host allocates 32 DMA target addresses and passes the host address
5041  * to the firmware at register IPW_RFDS_TABLE_LOWER + N * RFD_SIZE where N is
5042  * 0 to 31
5043  *
5044  * Rx Queue Indexes
5045  * The host/firmware share two index registers for managing the Rx buffers.
5046  *
5047  * The READ index maps to the first position that the firmware may be writing
5048  * to -- the driver can read up to (but not including) this position and get
5049  * good data.
5050  * The READ index is managed by the firmware once the card is enabled.
5051  *
5052  * The WRITE index maps to the last position the driver has read from -- the
5053  * position preceding WRITE is the last slot the firmware can place a packet.
5054  *
5055  * The queue is empty (no good data) if WRITE = READ - 1, and is full if
5056  * WRITE = READ.
5057  *
5058  * During initialization the host sets up the READ queue position to the first
5059  * INDEX position, and WRITE to the last (READ - 1 wrapped)
5060  *
5061  * When the firmware places a packet in a buffer it will advance the READ index
5062  * and fire the RX interrupt.  The driver can then query the READ index and
5063  * process as many packets as possible, moving the WRITE index forward as it
5064  * resets the Rx queue buffers with new memory.
5065  *
5066  * The management in the driver is as follows:
5067  * + A list of pre-allocated SKBs is stored in ipw->rxq->rx_free.  When
5068  *   ipw->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled
5069  *   to replensish the ipw->rxq->rx_free.
5070  * + In ipw_rx_queue_replenish (scheduled) if 'processed' != 'read' then the
5071  *   ipw->rxq is replenished and the READ INDEX is updated (updating the
5072  *   'processed' and 'read' driver indexes as well)
5073  * + A received packet is processed and handed to the kernel network stack,
5074  *   detached from the ipw->rxq.  The driver 'processed' index is updated.
5075  * + The Host/Firmware ipw->rxq is replenished at tasklet time from the rx_free
5076  *   list. If there are no allocated buffers in ipw->rxq->rx_free, the READ
5077  *   INDEX is not incremented and ipw->status(RX_STALLED) is set.  If there
5078  *   were enough free buffers and RX_STALLED is set it is cleared.
5079  *
5080  *
5081  * Driver sequence:
5082  *
5083  * ipw_rx_queue_alloc()       Allocates rx_free
5084  * ipw_rx_queue_replenish()   Replenishes rx_free list from rx_used, and calls
5085  *                            ipw_rx_queue_restock
5086  * ipw_rx_queue_restock()     Moves available buffers from rx_free into Rx
5087  *                            queue, updates firmware pointers, and updates
5088  *                            the WRITE index.  If insufficient rx_free buffers
5089  *                            are available, schedules ipw_rx_queue_replenish
5090  *
5091  * -- enable interrupts --
5092  * ISR - ipw_rx()             Detach ipw_rx_mem_buffers from pool up to the
5093  *                            READ INDEX, detaching the SKB from the pool.
5094  *                            Moves the packet buffer from queue to rx_used.
5095  *                            Calls ipw_rx_queue_restock to refill any empty
5096  *                            slots.
5097  * ...
5098  *
5099  */
5100
5101 /*
5102  * If there are slots in the RX queue that  need to be restocked,
5103  * and we have free pre-allocated buffers, fill the ranks as much
5104  * as we can pulling from rx_free.
5105  *
5106  * This moves the 'write' index forward to catch up with 'processed', and
5107  * also updates the memory address in the firmware to reference the new
5108  * target buffer.
5109  */
5110 static void ipw_rx_queue_restock(struct ipw_priv *priv)
5111 {
5112         struct ipw_rx_queue *rxq = priv->rxq;
5113         struct list_head *element;
5114         struct ipw_rx_mem_buffer *rxb;
5115         unsigned long flags;
5116         int write;
5117
5118         spin_lock_irqsave(&rxq->lock, flags);
5119         write = rxq->write;
5120         while ((ipw_rx_queue_space(rxq) > 0) && (rxq->free_count)) {
5121                 element = rxq->rx_free.next;
5122                 rxb = list_entry(element, struct ipw_rx_mem_buffer, list);
5123                 list_del(element);
5124
5125                 ipw_write32(priv, IPW_RFDS_TABLE_LOWER + rxq->write * RFD_SIZE,
5126                             rxb->dma_addr);
5127                 rxq->queue[rxq->write] = rxb;
5128                 rxq->write = (rxq->write + 1) % RX_QUEUE_SIZE;
5129                 rxq->free_count--;
5130         }
5131         spin_unlock_irqrestore(&rxq->lock, flags);
5132
5133         /* If the pre-allocated buffer pool is dropping low, schedule to
5134          * refill it */
5135         if (rxq->free_count <= RX_LOW_WATERMARK)
5136                 queue_work(priv->workqueue, &priv->rx_replenish);
5137
5138         /* If we've added more space for the firmware to place data, tell it */
5139         if (write != rxq->write)
5140                 ipw_write32(priv, IPW_RX_WRITE_INDEX, rxq->write);
5141 }
5142
5143 /*
5144  * Move all used packet from rx_used to rx_free, allocating a new SKB for each.
5145  * Also restock the Rx queue via ipw_rx_queue_restock.
5146  *
5147  * This is called as a scheduled work item (except for during intialization)
5148  */
5149 static void ipw_rx_queue_replenish(void *data)
5150 {
5151         struct ipw_priv *priv = data;
5152         struct ipw_rx_queue *rxq = priv->rxq;
5153         struct list_head *element;
5154         struct ipw_rx_mem_buffer *rxb;
5155         unsigned long flags;
5156
5157         spin_lock_irqsave(&rxq->lock, flags);
5158         while (!list_empty(&rxq->rx_used)) {
5159                 element = rxq->rx_used.next;
5160                 rxb = list_entry(element, struct ipw_rx_mem_buffer, list);
5161                 rxb->skb = alloc_skb(IPW_RX_BUF_SIZE, GFP_ATOMIC);
5162                 if (!rxb->skb) {
5163                         printk(KERN_CRIT "%s: Can not allocate SKB buffers.\n",
5164                                priv->net_dev->name);
5165                         /* We don't reschedule replenish work here -- we will
5166                          * call the restock method and if it still needs
5167                          * more buffers it will schedule replenish */
5168                         break;
5169                 }
5170                 list_del(element);
5171
5172                 rxb->dma_addr =
5173                     pci_map_single(priv->pci_dev, rxb->skb->data,
5174                                    IPW_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
5175
5176                 list_add_tail(&rxb->list, &rxq->rx_free);
5177                 rxq->free_count++;
5178         }
5179         spin_unlock_irqrestore(&rxq->lock, flags);
5180
5181         ipw_rx_queue_restock(priv);
5182 }
5183
5184 static void ipw_bg_rx_queue_replenish(struct work_struct *work)
5185 {
5186         struct ipw_priv *priv =
5187                 container_of(work, struct ipw_priv, rx_replenish);
5188         mutex_lock(&priv->mutex);
5189         ipw_rx_queue_replenish(priv);
5190         mutex_unlock(&priv->mutex);
5191 }
5192
5193 /* Assumes that the skb field of the buffers in 'pool' is kept accurate.
5194  * If an SKB has been detached, the POOL needs to have its SKB set to NULL
5195  * This free routine walks the list of POOL entries and if SKB is set to
5196  * non NULL it is unmapped and freed
5197  */
5198 static void ipw_rx_queue_free(struct ipw_priv *priv, struct ipw_rx_queue *rxq)
5199 {
5200         int i;
5201
5202         if (!rxq)
5203                 return;
5204
5205         for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
5206                 if (rxq->pool[i].skb != NULL) {
5207                         pci_unmap_single(priv->pci_dev, rxq->pool[i].dma_addr,
5208                                          IPW_RX_BUF_SIZE, PCI_DMA_FROMDEVICE);
5209                         dev_kfree_skb(rxq->pool[i].skb);
5210                 }
5211         }
5212
5213         kfree(rxq);
5214 }
5215
5216 static struct ipw_rx_queue *ipw_rx_queue_alloc(struct ipw_priv *priv)
5217 {
5218         struct ipw_rx_queue *rxq;
5219         int i;
5220
5221         rxq = kzalloc(sizeof(*rxq), GFP_KERNEL);
5222         if (unlikely(!rxq)) {
5223                 IPW_ERROR("memory allocation failed\n");
5224                 return NULL;
5225         }
5226         spin_lock_init(&rxq->lock);
5227         INIT_LIST_HEAD(&rxq->rx_free);
5228         INIT_LIST_HEAD(&rxq->rx_used);
5229
5230         /* Fill the rx_used queue with _all_ of the Rx buffers */
5231         for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++)
5232                 list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
5233
5234         /* Set us so that we have processed and used all buffers, but have
5235          * not restocked the Rx queue with fresh buffers */
5236         rxq->read = rxq->write = 0;
5237         rxq->free_count = 0;
5238
5239         return rxq;
5240 }
5241
5242 static int ipw_is_rate_in_mask(struct ipw_priv *priv, int ieee_mode, u8 rate)
5243 {
5244         rate &= ~LIBIPW_BASIC_RATE_MASK;
5245         if (ieee_mode == IEEE_A) {
5246                 switch (rate) {
5247                 case LIBIPW_OFDM_RATE_6MB:
5248                         return priv->rates_mask & LIBIPW_OFDM_RATE_6MB_MASK ?
5249                             1 : 0;
5250                 case LIBIPW_OFDM_RATE_9MB:
5251                         return priv->rates_mask & LIBIPW_OFDM_RATE_9MB_MASK ?
5252                             1 : 0;
5253                 case LIBIPW_OFDM_RATE_12MB:
5254                         return priv->
5255                             rates_mask & LIBIPW_OFDM_RATE_12MB_MASK ? 1 : 0;
5256                 case LIBIPW_OFDM_RATE_18MB:
5257                         return priv->
5258                             rates_mask & LIBIPW_OFDM_RATE_18MB_MASK ? 1 : 0;
5259                 case LIBIPW_OFDM_RATE_24MB:
5260                         return priv->
5261                             rates_mask & LIBIPW_OFDM_RATE_24MB_MASK ? 1 : 0;
5262                 case LIBIPW_OFDM_RATE_36MB:
5263                         return priv->
5264                             rates_mask & LIBIPW_OFDM_RATE_36MB_MASK ? 1 : 0;
5265                 case LIBIPW_OFDM_RATE_48MB:
5266                         return priv->
5267                             rates_mask & LIBIPW_OFDM_RATE_48MB_MASK ? 1 : 0;
5268                 case LIBIPW_OFDM_RATE_54MB:
5269                         return priv->
5270                             rates_mask & LIBIPW_OFDM_RATE_54MB_MASK ? 1 : 0;
5271                 default:
5272                         return 0;
5273                 }
5274         }
5275
5276         /* B and G mixed */
5277         switch (rate) {
5278         case LIBIPW_CCK_RATE_1MB:
5279                 return priv->rates_mask & LIBIPW_CCK_RATE_1MB_MASK ? 1 : 0;
5280         case LIBIPW_CCK_RATE_2MB:
5281                 return priv->rates_mask & LIBIPW_CCK_RATE_2MB_MASK ? 1 : 0;
5282         case LIBIPW_CCK_RATE_5MB:
5283                 return priv->rates_mask & LIBIPW_CCK_RATE_5MB_MASK ? 1 : 0;
5284         case LIBIPW_CCK_RATE_11MB:
5285                 return priv->rates_mask & LIBIPW_CCK_RATE_11MB_MASK ? 1 : 0;
5286         }
5287
5288         /* If we are limited to B modulations, bail at this point */
5289         if (ieee_mode == IEEE_B)
5290                 return 0;
5291
5292         /* G */
5293         switch (rate) {
5294         case LIBIPW_OFDM_RATE_6MB:
5295                 return priv->rates_mask & LIBIPW_OFDM_RATE_6MB_MASK ? 1 : 0;
5296         case LIBIPW_OFDM_RATE_9MB:
5297                 return priv->rates_mask & LIBIPW_OFDM_RATE_9MB_MASK ? 1 : 0;
5298         case LIBIPW_OFDM_RATE_12MB:
5299                 return priv->rates_mask & LIBIPW_OFDM_RATE_12MB_MASK ? 1 : 0;
5300         case LIBIPW_OFDM_RATE_18MB:
5301                 return priv->rates_mask & LIBIPW_OFDM_RATE_18MB_MASK ? 1 : 0;
5302         case LIBIPW_OFDM_RATE_24MB:
5303                 return priv->rates_mask & LIBIPW_OFDM_RATE_24MB_MASK ? 1 : 0;
5304         case LIBIPW_OFDM_RATE_36MB:
5305                 return priv->rates_mask & LIBIPW_OFDM_RATE_36MB_MASK ? 1 : 0;
5306         case LIBIPW_OFDM_RATE_48MB:
5307                 return priv->rates_mask & LIBIPW_OFDM_RATE_48MB_MASK ? 1 : 0;
5308         case LIBIPW_OFDM_RATE_54MB:
5309                 return priv->rates_mask & LIBIPW_OFDM_RATE_54MB_MASK ? 1 : 0;
5310         }
5311
5312         return 0;
5313 }
5314
5315 static int ipw_compatible_rates(struct ipw_priv *priv,
5316                                 const struct libipw_network *network,
5317                                 struct ipw_supported_rates *rates)
5318 {
5319         int num_rates, i;
5320
5321         memset(rates, 0, sizeof(*rates));
5322         num_rates = min(network->rates_len, (u8) IPW_MAX_RATES);
5323         rates->num_rates = 0;
5324         for (i = 0; i < num_rates; i++) {
5325                 if (!ipw_is_rate_in_mask(priv, network->mode,
5326                                          network->rates[i])) {
5327
5328                         if (network->rates[i] & LIBIPW_BASIC_RATE_MASK) {
5329                                 IPW_DEBUG_SCAN("Adding masked mandatory "
5330                                                "rate %02X\n",
5331                                                network->rates[i]);
5332                                 rates->supported_rates[rates->num_rates++] =
5333                                     network->rates[i];
5334                                 continue;
5335                         }
5336
5337                         IPW_DEBUG_SCAN("Rate %02X masked : 0x%08X\n",
5338                                        network->rates[i], priv->rates_mask);
5339                         continue;
5340                 }
5341
5342                 rates->supported_rates[rates->num_rates++] = network->rates[i];
5343         }
5344
5345         num_rates = min(network->rates_ex_len,
5346                         (u8) (IPW_MAX_RATES - num_rates));
5347         for (i = 0; i < num_rates; i++) {
5348                 if (!ipw_is_rate_in_mask(priv, network->mode,
5349                                          network->rates_ex[i])) {
5350                         if (network->rates_ex[i] & LIBIPW_BASIC_RATE_MASK) {
5351                                 IPW_DEBUG_SCAN("Adding masked mandatory "
5352                                                "rate %02X\n",
5353                                                network->rates_ex[i]);
5354                                 rates->supported_rates[rates->num_rates++] =
5355                                     network->rates[i];
5356                                 continue;
5357                         }
5358
5359                         IPW_DEBUG_SCAN("Rate %02X masked : 0x%08X\n",
5360                                        network->rates_ex[i], priv->rates_mask);
5361                         continue;
5362                 }
5363
5364                 rates->supported_rates[rates->num_rates++] =
5365                     network->rates_ex[i];
5366         }
5367
5368         return 1;
5369 }
5370
5371 static void ipw_copy_rates(struct ipw_supported_rates *dest,
5372                                   const struct ipw_supported_rates *src)
5373 {
5374         u8 i;
5375         for (i = 0; i < src->num_rates; i++)
5376                 dest->supported_rates[i] = src->supported_rates[i];
5377         dest->num_rates = src->num_rates;
5378 }
5379
5380 /* TODO: Look at sniffed packets in the air to determine if the basic rate
5381  * mask should ever be used -- right now all callers to add the scan rates are
5382  * set with the modulation = CCK, so BASIC_RATE_MASK is never set... */
5383 static void ipw_add_cck_scan_rates(struct ipw_supported_rates *rates,
5384                                    u8 modulation, u32 rate_mask)
5385 {
5386         u8 basic_mask = (LIBIPW_OFDM_MODULATION == modulation) ?
5387             LIBIPW_BASIC_RATE_MASK : 0;
5388
5389         if (rate_mask & LIBIPW_CCK_RATE_1MB_MASK)
5390                 rates->supported_rates[rates->num_rates++] =
5391                     LIBIPW_BASIC_RATE_MASK | LIBIPW_CCK_RATE_1MB;
5392
5393         if (rate_mask & LIBIPW_CCK_RATE_2MB_MASK)
5394                 rates->supported_rates[rates->num_rates++] =
5395                     LIBIPW_BASIC_RATE_MASK | LIBIPW_CCK_RATE_2MB;
5396
5397         if (rate_mask & LIBIPW_CCK_RATE_5MB_MASK)
5398                 rates->supported_rates[rates->num_rates++] = basic_mask |
5399                     LIBIPW_CCK_RATE_5MB;
5400
5401         if (rate_mask & LIBIPW_CCK_RATE_11MB_MASK)
5402                 rates->supported_rates[rates->num_rates++] = basic_mask |
5403                     LIBIPW_CCK_RATE_11MB;
5404 }
5405
5406 static void ipw_add_ofdm_scan_rates(struct ipw_supported_rates *rates,
5407                                     u8 modulation, u32 rate_mask)
5408 {
5409         u8 basic_mask = (LIBIPW_OFDM_MODULATION == modulation) ?
5410             LIBIPW_BASIC_RATE_MASK : 0;
5411
5412         if (rate_mask & LIBIPW_OFDM_RATE_6MB_MASK)
5413                 rates->supported_rates[rates->num_rates++] = basic_mask |
5414                     LIBIPW_OFDM_RATE_6MB;
5415
5416         if (rate_mask & LIBIPW_OFDM_RATE_9MB_MASK)
5417                 rates->supported_rates[rates->num_rates++] =
5418                     LIBIPW_OFDM_RATE_9MB;
5419
5420         if (rate_mask & LIBIPW_OFDM_RATE_12MB_MASK)
5421                 rates->supported_rates[rates->num_rates++] = basic_mask |
5422                     LIBIPW_OFDM_RATE_12MB;
5423
5424         if (rate_mask & LIBIPW_OFDM_RATE_18MB_MASK)
5425                 rates->supported_rates[rates->num_rates++] =
5426                     LIBIPW_OFDM_RATE_18MB;
5427
5428         if (rate_mask & LIBIPW_OFDM_RATE_24MB_MASK)
5429                 rates->supported_rates[rates->num_rates++] = basic_mask |
5430                     LIBIPW_OFDM_RATE_24MB;
5431
5432         if (rate_mask & LIBIPW_OFDM_RATE_36MB_MASK)
5433                 rates->supported_rates[rates->num_rates++] =
5434                     LIBIPW_OFDM_RATE_36MB;
5435
5436         if (rate_mask & LIBIPW_OFDM_RATE_48MB_MASK)
5437                 rates->supported_rates[rates->num_rates++] =
5438                     LIBIPW_OFDM_RATE_48MB;
5439
5440         if (rate_mask & LIBIPW_OFDM_RATE_54MB_MASK)
5441                 rates->supported_rates[rates->num_rates++] =
5442                     LIBIPW_OFDM_RATE_54MB;
5443 }
5444
5445 struct ipw_network_match {
5446         struct libipw_network *network;
5447         struct ipw_supported_rates rates;
5448 };
5449
5450 static int ipw_find_adhoc_network(struct ipw_priv *priv,
5451                                   struct ipw_network_match *match,
5452                                   struct libipw_network *network,
5453                                   int roaming)
5454 {
5455         struct ipw_supported_rates rates;
5456         DECLARE_SSID_BUF(ssid);
5457
5458         /* Verify that this network's capability is compatible with the
5459          * current mode (AdHoc or Infrastructure) */
5460         if ((priv->ieee->iw_mode == IW_MODE_ADHOC &&
5461              !(network->capability & WLAN_CAPABILITY_IBSS))) {
5462                 IPW_DEBUG_MERGE("Network '%s (%pM)' excluded due to "
5463                                 "capability mismatch.\n",
5464                                 print_ssid(ssid, network->ssid,
5465                                            network->ssid_len),
5466                                 network->bssid);
5467                 return 0;
5468         }
5469
5470         if (unlikely(roaming)) {
5471                 /* If we are roaming, then ensure check if this is a valid
5472                  * network to try and roam to */
5473                 if ((network->ssid_len != match->network->ssid_len) ||
5474                     memcmp(network->ssid, match->network->ssid,
5475                            network->ssid_len)) {
5476                         IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5477                                         "because of non-network ESSID.\n",
5478                                         print_ssid(ssid, network->ssid,
5479                                                    network->ssid_len),
5480                                         network->bssid);
5481                         return 0;
5482                 }
5483         } else {
5484                 /* If an ESSID has been configured then compare the broadcast
5485                  * ESSID to ours */
5486                 if ((priv->config & CFG_STATIC_ESSID) &&
5487                     ((network->ssid_len != priv->essid_len) ||
5488                      memcmp(network->ssid, priv->essid,
5489                             min(network->ssid_len, priv->essid_len)))) {
5490                         char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
5491
5492                         strncpy(escaped,
5493                                 print_ssid(ssid, network->ssid,
5494                                            network->ssid_len),
5495                                 sizeof(escaped));
5496                         IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5497                                         "because of ESSID mismatch: '%s'.\n",
5498                                         escaped, network->bssid,
5499                                         print_ssid(ssid, priv->essid,
5500                                                    priv->essid_len));
5501                         return 0;
5502                 }
5503         }
5504
5505         /* If the old network rate is better than this one, don't bother
5506          * testing everything else. */
5507
5508         if (network->time_stamp[0] < match->network->time_stamp[0]) {
5509                 IPW_DEBUG_MERGE("Network '%s excluded because newer than "
5510                                 "current network.\n",
5511                                 print_ssid(ssid, match->network->ssid,
5512                                            match->network->ssid_len));
5513                 return 0;
5514         } else if (network->time_stamp[1] < match->network->time_stamp[1]) {
5515                 IPW_DEBUG_MERGE("Network '%s excluded because newer than "
5516                                 "current network.\n",
5517                                 print_ssid(ssid, match->network->ssid,
5518                                            match->network->ssid_len));
5519                 return 0;
5520         }
5521
5522         /* Now go through and see if the requested network is valid... */
5523         if (priv->ieee->scan_age != 0 &&
5524             time_after(jiffies, network->last_scanned + priv->ieee->scan_age)) {
5525                 IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5526                                 "because of age: %ums.\n",
5527                                 print_ssid(ssid, network->ssid,
5528                                            network->ssid_len),
5529                                 network->bssid,
5530                                 jiffies_to_msecs(jiffies -
5531                                                  network->last_scanned));
5532                 return 0;
5533         }
5534
5535         if ((priv->config & CFG_STATIC_CHANNEL) &&
5536             (network->channel != priv->channel)) {
5537                 IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5538                                 "because of channel mismatch: %d != %d.\n",
5539                                 print_ssid(ssid, network->ssid,
5540                                            network->ssid_len),
5541                                 network->bssid,
5542                                 network->channel, priv->channel);
5543                 return 0;
5544         }
5545
5546         /* Verify privacy compatability */
5547         if (((priv->capability & CAP_PRIVACY_ON) ? 1 : 0) !=
5548             ((network->capability & WLAN_CAPABILITY_PRIVACY) ? 1 : 0)) {
5549                 IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5550                                 "because of privacy mismatch: %s != %s.\n",
5551                                 print_ssid(ssid, network->ssid,
5552                                            network->ssid_len),
5553                                 network->bssid,
5554                                 priv->
5555                                 capability & CAP_PRIVACY_ON ? "on" : "off",
5556                                 network->
5557                                 capability & WLAN_CAPABILITY_PRIVACY ? "on" :
5558                                 "off");
5559                 return 0;
5560         }
5561
5562         if (!memcmp(network->bssid, priv->bssid, ETH_ALEN)) {
5563                 IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5564                                 "because of the same BSSID match: %pM"
5565                                 ".\n", print_ssid(ssid, network->ssid,
5566                                                   network->ssid_len),
5567                                 network->bssid,
5568                                 priv->bssid);
5569                 return 0;
5570         }
5571
5572         /* Filter out any incompatible freq / mode combinations */
5573         if (!libipw_is_valid_mode(priv->ieee, network->mode)) {
5574                 IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5575                                 "because of invalid frequency/mode "
5576                                 "combination.\n",
5577                                 print_ssid(ssid, network->ssid,
5578                                            network->ssid_len),
5579                                 network->bssid);
5580                 return 0;
5581         }
5582
5583         /* Ensure that the rates supported by the driver are compatible with
5584          * this AP, including verification of basic rates (mandatory) */
5585         if (!ipw_compatible_rates(priv, network, &rates)) {
5586                 IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5587                                 "because configured rate mask excludes "
5588                                 "AP mandatory rate.\n",
5589                                 print_ssid(ssid, network->ssid,
5590                                            network->ssid_len),
5591                                 network->bssid);
5592                 return 0;
5593         }
5594
5595         if (rates.num_rates == 0) {
5596                 IPW_DEBUG_MERGE("Network '%s (%pM)' excluded "
5597                                 "because of no compatible rates.\n",
5598                                 print_ssid(ssid, network->ssid,
5599                                            network->ssid_len),
5600                                 network->bssid);
5601                 return 0;
5602         }
5603
5604         /* TODO: Perform any further minimal comparititive tests.  We do not
5605          * want to put too much policy logic here; intelligent scan selection
5606          * should occur within a generic IEEE 802.11 user space tool.  */
5607
5608         /* Set up 'new' AP to this network */
5609         ipw_copy_rates(&match->rates, &rates);
5610         match->network = network;
5611         IPW_DEBUG_MERGE("Network '%s (%pM)' is a viable match.\n",
5612                         print_ssid(ssid, network->ssid, network->ssid_len),
5613                         network->bssid);
5614
5615         return 1;
5616 }
5617
5618 static void ipw_merge_adhoc_network(struct work_struct *work)
5619 {
5620         DECLARE_SSID_BUF(ssid);
5621         struct ipw_priv *priv =
5622                 container_of(work, struct ipw_priv, merge_networks);
5623         struct libipw_network *network = NULL;
5624         struct ipw_network_match match = {
5625                 .network = priv->assoc_network
5626         };
5627
5628         if ((priv->status & STATUS_ASSOCIATED) &&
5629             (priv->ieee->iw_mode == IW_MODE_ADHOC)) {
5630                 /* First pass through ROAM process -- look for a better
5631                  * network */
5632                 unsigned long flags;
5633
5634                 spin_lock_irqsave(&priv->ieee->lock, flags);
5635                 list_for_each_entry(network, &priv->ieee->network_list, list) {
5636                         if (network != priv->assoc_network)
5637                                 ipw_find_adhoc_network(priv, &match, network,
5638                                                        1);
5639                 }
5640                 spin_unlock_irqrestore(&priv->ieee->lock, flags);
5641
5642                 if (match.network == priv->assoc_network) {
5643                         IPW_DEBUG_MERGE("No better ADHOC in this network to "
5644                                         "merge to.\n");
5645                         return;
5646                 }
5647
5648                 mutex_lock(&priv->mutex);
5649                 if ((priv->ieee->iw_mode == IW_MODE_ADHOC)) {
5650                         IPW_DEBUG_MERGE("remove network %s\n",
5651                                         print_ssid(ssid, priv->essid,
5652                                                    priv->essid_len));
5653                         ipw_remove_current_network(priv);
5654                 }
5655
5656                 ipw_disassociate(priv);
5657                 priv->assoc_network = match.network;
5658                 mutex_unlock(&priv->mutex);
5659                 return;
5660         }
5661 }
5662
5663 static int ipw_best_network(struct ipw_priv *priv,
5664                             struct ipw_network_match *match,
5665                             struct libipw_network *network, int roaming)
5666 {
5667         struct ipw_supported_rates rates;
5668         DECLARE_SSID_BUF(ssid);
5669
5670         /* Verify that this network's capability is compatible with the
5671          * current mode (AdHoc or Infrastructure) */
5672         if ((priv->ieee->iw_mode == IW_MODE_INFRA &&
5673              !(network->capability & WLAN_CAPABILITY_ESS)) ||
5674             (priv->ieee->iw_mode == IW_MODE_ADHOC &&
5675              !(network->capability & WLAN_CAPABILITY_IBSS))) {
5676                 IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded due to "
5677                                 "capability mismatch.\n",
5678                                 print_ssid(ssid, network->ssid,
5679                                            network->ssid_len),
5680                                 network->bssid);
5681                 return 0;
5682         }
5683
5684         if (unlikely(roaming)) {
5685                 /* If we are roaming, then ensure check if this is a valid
5686                  * network to try and roam to */
5687                 if ((network->ssid_len != match->network->ssid_len) ||
5688                     memcmp(network->ssid, match->network->ssid,
5689                            network->ssid_len)) {
5690                         IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5691                                         "because of non-network ESSID.\n",
5692                                         print_ssid(ssid, network->ssid,
5693                                                    network->ssid_len),
5694                                         network->bssid);
5695                         return 0;
5696                 }
5697         } else {
5698                 /* If an ESSID has been configured then compare the broadcast
5699                  * ESSID to ours */
5700                 if ((priv->config & CFG_STATIC_ESSID) &&
5701                     ((network->ssid_len != priv->essid_len) ||
5702                      memcmp(network->ssid, priv->essid,
5703                             min(network->ssid_len, priv->essid_len)))) {
5704                         char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
5705                         strncpy(escaped,
5706                                 print_ssid(ssid, network->ssid,
5707                                            network->ssid_len),
5708                                 sizeof(escaped));
5709                         IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5710                                         "because of ESSID mismatch: '%s'.\n",
5711                                         escaped, network->bssid,
5712                                         print_ssid(ssid, priv->essid,
5713                                                    priv->essid_len));
5714                         return 0;
5715                 }
5716         }
5717
5718         /* If the old network rate is better than this one, don't bother
5719          * testing everything else. */
5720         if (match->network && match->network->stats.rssi > network->stats.rssi) {
5721                 char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
5722                 strncpy(escaped,
5723                         print_ssid(ssid, network->ssid, network->ssid_len),
5724                         sizeof(escaped));
5725                 IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded because "
5726                                 "'%s (%pM)' has a stronger signal.\n",
5727                                 escaped, network->bssid,
5728                                 print_ssid(ssid, match->network->ssid,
5729                                            match->network->ssid_len),
5730                                 match->network->bssid);
5731                 return 0;
5732         }
5733
5734         /* If this network has already had an association attempt within the
5735          * last 3 seconds, do not try and associate again... */
5736         if (network->last_associate &&
5737             time_after(network->last_associate + (HZ * 3UL), jiffies)) {
5738                 IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5739                                 "because of storming (%ums since last "
5740                                 "assoc attempt).\n",
5741                                 print_ssid(ssid, network->ssid,
5742                                            network->ssid_len),
5743                                 network->bssid,
5744                                 jiffies_to_msecs(jiffies -
5745                                                  network->last_associate));
5746                 return 0;
5747         }
5748
5749         /* Now go through and see if the requested network is valid... */
5750         if (priv->ieee->scan_age != 0 &&
5751             time_after(jiffies, network->last_scanned + priv->ieee->scan_age)) {
5752                 IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5753                                 "because of age: %ums.\n",
5754                                 print_ssid(ssid, network->ssid,
5755                                            network->ssid_len),
5756                                 network->bssid,
5757                                 jiffies_to_msecs(jiffies -
5758                                                  network->last_scanned));
5759                 return 0;
5760         }
5761
5762         if ((priv->config & CFG_STATIC_CHANNEL) &&
5763             (network->channel != priv->channel)) {
5764                 IPW_DEBUG_ASSOC("Network '%s (%pM)' excluded "
5765                                 "because of channel mismatch: %d != %d.\n",
5766                                 print_ssid(ssid, network->ssid,
5767                                            network->ssid_len),
5768                                 network->bssid,
5769                                 network->channel, priv->channel);
5770                 return 0;
5771         }
5772
5773         /* Verify privacy compatability */
5774         if (((priv->capability & CAP_PRIVACY_ON) ? 1 : 0) !=
5775     &n