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