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