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