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